File size: 16,938 Bytes
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""Motion primitives on world-space pose tracks. Every edit is a rigid rotation of a joint subtree or an IK solve with
fixed bone lengths, so bone lengths never drift.

A Track holds one entity over the whole shot:
    poses  (T, J, 3) world cm
    weapon (T, 2, 3) grip end, tip end (or None)
Primitives take frame ranges [t0, t1) and edit the track in place; they compose left to right.
"""
import numpy as np
from .geometry import rot_axis, rot_z, UP

ease = lambda u: u * u * (3 - 2 * u)


class Track:
    def __init__(self, skeleton, frames, root=(0, 0, None), yaw=0.0):
        self.sk = skeleton; self.T = frames
        r = np.array(root, dtype=object)
        z = skeleton.rest[0, 2] if root[2] is None else root[2]
        base = skeleton.place([float(root[0]), float(root[1]), float(z)], yaw)
        self.poses = np.repeat(base[None], frames, axis=0)
        self.yaw = np.full(frames, float(yaw))
        self.weapon = None
        if skeleton.weapon is not None:
            self.attach_weapon(0, frames)

    # ------------------------------------------------------------------ helpers
    def j(self, name):
        return self.sk.index[name]

    def forward(self, t):
        return np.array([np.cos(self.yaw[t]), np.sin(self.yaw[t]), 0.0])

    def right(self, t):
        return np.array([-np.sin(self.yaw[t]), np.cos(self.yaw[t]), 0.0])      # UE: +Y is right of +X

    def rotate_subtree(self, t, joint, R, pivot=None):
        """Rotate `joint`'s subtree about pivot (default the joint); a weapon held by a hand in the subtree rotates too."""
        idx = self.sk.descendants(joint)
        p = self.poses[t, self.j(joint)] if pivot is None else np.asarray(pivot, float)
        self.poses[t, idx] = (self.poses[t, idx] - p) @ R.T + p
        if self._holds_weapon(idx):
            self.weapon[t] = (self.weapon[t] - p) @ R.T + p

    def _holds_weapon(self, idx):
        return self.weapon is not None and self.sk.weapon is not None and self.j(self.sk.weapon.hand) in idx

    def attach_weapon(self, t0, t1, direction=None, pitch_deg=35.0):
        """Weapon rigid in the hand: grip end behind the hand by grip_offset, pointing `direction` (world, per-frame
        callable or vector) or, by default, forward-up from the forearm (pitch_deg above the facing direction)."""
        w = self.sk.weapon; assert w is not None
        if self.weapon is None:
            self.weapon = np.zeros((self.T, 2, 3))
        hand = self.j(w.hand)
        for t in range(t0, t1):
            if direction is None:
                d = self.forward(t) * np.cos(np.radians(pitch_deg)) + UP * np.sin(np.radians(pitch_deg))
            else:
                d = np.asarray(direction(t) if callable(direction) else direction, float)
            d = d / np.linalg.norm(d)
            butt = self.poses[t, hand] - d * w.grip_offset
            self.weapon[t] = [butt, butt + d * w.length]

    def carry_weapon_rigidly(self, t0, t1, joint=None):
        """Keep the weapon's pose relative to `joint` (default the hand) as it was at t0 - 1, translating with the joint
        and rotating with the subtree yaw -- use after primitives that move the hand."""
        joint = joint or self.sk.weapon.hand
        ref = max(t0 - 1, 0); h = self.j(joint)
        rel = self.weapon[ref] - self.poses[ref, h]; yaw0 = self.yaw[ref]
        for t in range(t0, t1):
            self.weapon[t] = self.poses[t, h] + rel @ rot_z(self.yaw[t] - yaw0).T

    # ---------------------------------------------------------------- whole body
    def translate(self, t0, t1, offset):
        off = np.asarray(offset, float)
        self.poses[t0:t1] += off
        if self.weapon is not None:
            self.weapon[t0:t1] += off

    def freeze(self, t0, t1=None, at=None):
        """Hold the pose (and weapon) of frame `at` (default t0) for [t0, t1)."""
        t1 = self.T if t1 is None else t1; at = t0 if at is None else at
        self.poses[t0:t1] = self.poses[at]; self.yaw[t0:t1] = self.yaw[at]
        if self.weapon is not None:
            self.weapon[t0:t1] = self.weapon[at]

    def turn(self, t0, t1, dyaw, hold=True):
        """Rotate about the root's vertical axis by dyaw (rad), eased over [t0, t1); frames after t1 keep the new
        facing if hold."""
        end = self.T if hold else t1
        for t in range(t0, end):
            a = dyaw * (ease((t - t0) / max(1, t1 - t0)) if t < t1 else 1.0)
            R = rot_z(a); p = self.poses[t, 0].copy()
            self.poses[t] = (self.poses[t] - p) @ R.T + p
            if self.weapon is not None:
                self.weapon[t] = (self.weapon[t] - p) @ R.T + p
            self.yaw[t] += a

    def move_root_path(self, t0, t1, waypoints, face_motion=True, hold=True):
        """Carry the whole body along a polyline of world xy waypoints (first = current root xy), eased by arc length.
        Faces the direction of travel when face_motion. Legs are not animated here -- use gait() afterwards."""
        wp = np.asarray(waypoints, float)
        seglen = np.linalg.norm(np.diff(wp, axis=0), axis=1); cum = np.r_[0, np.cumsum(seglen)]; total = cum[-1]
        start_xy = self.poses[t0, 0, :2].copy()
        def at(s):
            k = min(np.searchsorted(cum, s, side="right") - 1, len(seglen) - 1)
            return wp[k] + (wp[k + 1] - wp[k]) * ((s - cum[k]) / max(seglen[k], 1e-6))
        end = self.T if hold else t1
        for t in range(t0, end):
            u = ease((t - t0) / max(1, t1 - t0)) if t < t1 else 1.0
            xy = at(u * total)
            self.translate(t, t + 1, [xy[0] - self.poses[t, 0, 0], xy[1] - self.poses[t, 0, 1], 0.0])
            if face_motion and t < t1:
                ahead = at(min(total, u * total + 5.0)) - xy
                if np.linalg.norm(ahead) > 1e-3:
                    target = np.arctan2(ahead[1], ahead[0])
                    d = (target - self.yaw[t] + np.pi) % (2 * np.pi) - np.pi
                    self.turn(t, t + 1, d, hold=False)
                    if t + 1 < self.T:
                        self.yaw[t + 1:] = self.yaw[t]
        _ = start_xy

    def jump(self, t0, t1, height, offset=(0, 0), tuck=0.35):
        """Parabolic hop over [t0, t1): apex `height` cm, horizontal `offset` (world xy cm, persists after landing).
        Knees tuck toward the body at the apex by `tuck` of leg length when IK legs are known."""
        off = np.asarray(offset, float)
        for t in range(t0, self.T):
            u = min(1.0, (t - t0) / max(1, t1 - t0))
            lift = 4 * height * u * (1 - u) if t < t1 else 0.0
            self.translate(t, t + 1, [off[0] * ease(u), off[1] * ease(u), lift])

    # -------------------------------------------------------------------- limbs
    def two_bone_ik(self, t, upper, lower, end, target, pole):
        """Place `lower` and `end` so `end` reaches `target` (clamped), bending toward `pole` (world direction)."""
        a = self.poses[t, self.j(upper)]; L1 = np.linalg.norm(self.sk.rest[self.j(lower)] - self.sk.rest[self.j(upper)])
        L2 = np.linalg.norm(self.sk.rest[self.j(end)] - self.sk.rest[self.j(lower)])
        d = np.asarray(target, float) - a; dist = np.clip(np.linalg.norm(d), 1e-3, (L1 + L2) * 0.999)
        dn = d / np.linalg.norm(d)
        cos_a = np.clip((L1 * L1 + dist * dist - L2 * L2) / (2 * L1 * dist), -1, 1)
        pole = np.asarray(pole, float); pole = pole - dn * (pole @ dn)
        pole = pole / np.linalg.norm(pole) if np.linalg.norm(pole) > 1e-6 else np.cross(dn, UP)
        knee = a + dn * L1 * cos_a + pole * L1 * np.sqrt(1 - cos_a ** 2)
        tail = self.sk.descendants(end)
        old_end = self.poses[t, self.j(end)].copy()
        shift = a + dn * dist - self.poses[t, self.j(end)]
        self.poses[t, self.j(lower)] = knee
        self.poses[t, tail] += shift
        # re-normalise the lower bone exactly
        e = self.poses[t, self.j(end)]; v = e - knee
        self.poses[t, tail] += knee + v / np.linalg.norm(v) * L2 - e
        if self._holds_weapon(tail):                                     # a held weapon follows the hand
            self.weapon[t] += self.poses[t, self.j(end)] - old_end

    def legs(self):
        """(upper, lower, foot) chains of the skeleton, detected by naming."""
        sk = self.sk; out = []
        for n in sk.joints:
            if n.startswith("thigh_"):
                s = n[len("thigh_"):]; out.append((n, f"calf_{s}", f"foot_{s}"))
            elif n.endswith("_upper") and (n.startswith("front") or n.startswith("hind")):
                p = n[:-len("_upper")]; out.append((n, f"{p}_lower", f"{p}_foot"))
            elif n.endswith("_hip") and n.startswith("leg"):
                p = n[:-len("_hip")]; out.append((n, f"{p}_knee", f"{p}_foot"))
        return out

    def gait(self, t0, t1, period=None, duty=0.6, lift=None, phases=None, max_stride=0.7, foot_offsets=None, blend_in=4):
        """Plant-and-swing feet under the moving root over [t0, t1) with two-bone IK. Rest foot offsets are carried in
        the body frame; each foot stays fixed on the ground during stance. phases: per-leg cycle offsets (default:
        alternate left/right, diagonal pairs for four legs, tripod-like for six+). period=None picks the cycle length
        from the root speed so one stance covers at most max_stride of the leg length (otherwise IK cannot keep the
        planted foot and it slides)."""
        chains = self.legs(); assert chains, "skeleton has no recognised legs"
        if period is None:
            leg_len = np.mean([self.sk.bone_lengths[self.j(c[1])] + self.sk.bone_lengths[self.j(c[2])] for c in chains])
            speed = np.linalg.norm(self.poses[t1 - 1, 0, :2] - self.poses[t0, 0, :2]) / max(1, t1 - t0)
            peak = 1.5 * speed                                   # eased paths peak at 1.5x the mean speed
            period = int(np.clip(max_stride * leg_len / max(peak * duty, 1e-3), 8, 48))
        self.gait_period = period
        n = len(chains)
        if phases is None:
            phases = [((k % 2) * 0.5 + (k // 2) * 0.25) % 1.0 for k in range(n)] if n > 2 else [0.0, 0.5]
        lift = lift if lift is not None else 0.12 * self.sk.height
        # body-frame foot offsets (x forward, y right): the skeleton's rest stance unless given (e.g. a wide lunge)
        rest_rel = foot_offsets or {c: self.sk.rest[self.j(c[2])] - self.sk.rest[0] for c in chains}
        def plant(c, cyc, ph):
            tc = int(round(t0 + (cyc + duty / 2 - ph) * period)); tc = min(max(tc, 0), self.T - 1)
            off = rest_rel[c] @ rot_z(self.yaw[tc]).T
            p = self.poses[tc, 0] + off; p[2] = 0.0
            return p
        prev_feet = {c: self.poses[max(t0 - 1, 0), self.j(c[2])].copy() for c in chains}
        for t in range(t0, t1):
            for c, ph in zip(chains, phases):
                x = (t - t0) / period + ph; cyc = int(np.floor(x)); s = x - cyc
                if s < duty:
                    target = plant(c, cyc, ph)
                else:
                    u = (s - duty) / (1 - duty)
                    target = plant(c, cyc, ph) * (1 - ease(u)) + plant(c, cyc + 1, ph) * ease(u)
                    target[2] += lift * np.sin(np.pi * u)
                if blend_in and t0 > 0 and t - t0 < blend_in:             # ease in from the feet before the gait
                    k = ease((t - t0 + 1) / (blend_in + 1))
                    target = prev_feet[c] * (1 - k) + target * k
                self.two_bone_ik(t, *c, target=target, pole=self.forward(t) + 0.3 * UP)

    def swing_limb(self, t0, t1, joint, axis, angle, back_by=None):
        """Rotate `joint`'s subtree about `axis` (world vector or 'right'/'forward'/'up', body-relative) by `angle` rad
        with ease-in-out, returning to rest over the following `back_by` frames if given."""
        for t in range(t0, min(self.T, t1 + (back_by or 0))):
            if t < t1:
                a = angle * ease((t - t0) / max(1, t1 - t0))
            else:
                a = angle * (1 - ease((t - t1) / back_by))
            ax = {"right": self.right(t), "forward": self.forward(t), "up": UP}.get(axis, axis) if isinstance(axis, str) else axis
            self.rotate_subtree(t, joint, rot_axis(ax, a))

    def reach(self, t0, t1, joint_chain, target, hold=0, pole=None):
        """Two-bone reach of an (upper, lower, end) chain toward a world target and back."""
        pole = pole if pole is not None else UP
        for t in range(t0, min(self.T, t1 + hold + (t1 - t0))):
            if t < t1:
                u = ease((t - t0) / max(1, t1 - t0))
            elif t < t1 + hold:
                u = 1.0
            else:
                u = 1 - ease((t - t1 - hold) / max(1, t1 - t0))
            cur = self.poses[t, self.j(joint_chain[2])]
            self.two_bone_ik(t, *joint_chain, target=cur * (1 - u) + np.asarray(target, float) * u, pole=pole)

    def lunge(self, t0, t1, distance, head_drop=0.0, recover=None, plant_feet=True):
        """Body thrust forward `distance` cm (bite / charge) with optional head dip, then back over `recover` frames
        (or stay if None). plant_feet keeps the feet on their t0 positions via IK while the body moves."""
        planted = {c: self.poses[t0, self.j(c[2])].copy() for c in self.legs()}
        for t in range(t0, self.T):
            if t < t1:
                u = ease((t - t0) / max(1, t1 - t0))
            elif recover:
                u = 1 - ease(min(1.0, (t - t1) / recover))
            else:
                u = 1.0
            self.translate(t, t + 1, self.forward(t) * distance * u)
            if head_drop and "neck_01" in self.sk.index:
                self.rotate_subtree(t, "neck_01", rot_axis(self.right(t), head_drop * u))
            if plant_feet and u > 0:
                for c in self.legs():                                    # feet stay where they stood at t0
                    self.two_bone_ik(t, *c, target=planted[c], pole=self.forward(t) + 0.3 * UP)

    def chain_wave(self, t0, t1, joints, axis, amplitude, cycles=1.0, delay=0.15):
        """Travelling rotation along a joint chain (tail swipe, serpent slither, wing flap): joint k rotates about
        `axis` by amplitude * sin(2 pi (cycles * u - k * delay)), applied root-to-tip."""
        for t in range(t0, t1):
            u = (t - t0) / max(1, t1 - t0); env = np.sin(np.pi * u)
            for k, jn in enumerate(joints):
                ax = {"right": self.right(t), "forward": self.forward(t), "up": UP}.get(axis, axis) if isinstance(axis, str) else axis
                a = amplitude * env * np.sin(2 * np.pi * (cycles * u - k * delay))
                self.rotate_subtree(t, jn, rot_axis(ax, a / max(1, len(joints)) * 1.5))

    def hit_react(self, t0, t1, direction, push=40.0, lean=0.35):
        """Stagger: pushed `push` cm along world `direction` with the upper body leaning away, recovering by t1."""
        d = np.asarray(direction, float); d[2] = 0; d = d / np.linalg.norm(d)
        spine = "spine_01" if "spine_01" in self.sk.index else self.sk.joints[1]
        for t in range(t0, self.T):
            u = (t - t0) / max(1, t1 - t0)
            k = np.sin(np.pi * min(u, 1.0)) if t < t1 else 0.0
            self.translate(t, t + 1, d * push * ease(min(u, 1.0)))
            if k:
                self.rotate_subtree(t, spine, rot_axis(np.cross(UP, d), lean * k))

    # -------------------------------------------------------------------- weapon
    def throw_weapon(self, t_release, t_catch, hold_frame, loop_side=250.0, loop_out=0.0, lift=40.0, spins=3,
                     spin_axis=None, camera_forward=None):
        """Detach the weapon at t_release, fly a boomerang loop and land exactly on the weapon pose of `hold_frame`
        at t_catch (pose there must already hold the weapon). spin_axis default: toward the camera (pinwheel)."""
        w0 = self.weapon[t_release].copy(); w1 = self.weapon[hold_frame].copy()
        L = np.linalg.norm(w0[1] - w0[0]); c0, c1 = w0.mean(0), w1.mean(0)
        a0, a1 = (w0[1] - w0[0]) / L, (w1[1] - w1[0]) / L
        fwd = np.asarray(camera_forward, float) if camera_forward is not None else self.forward(t_release)
        tocam = -fwd.copy(); tocam[2] = 0; tocam /= np.linalg.norm(tocam)
        side = np.cross(UP, tocam); side /= np.linalg.norm(side)
        axis = tocam if spin_axis is None else np.asarray(spin_axis, float)
        def slerp(p, q, u):
            om = np.arccos(np.clip(p @ q, -1, 1))
            return p if om < 1e-6 else (np.sin((1 - u) * om) * p + np.sin(u * om) * q) / np.sin(om)
        for t in range(t_release + 1, t_catch):
            u = (t - t_release) / (t_catch - t_release)
            c = c0 + (c1 - c0) * ease(u) + loop_out * np.sin(np.pi * u) * tocam + loop_side * np.sin(2 * np.pi * u) * side + lift * np.sin(np.pi * u) * UP
            d = rot_axis(axis, 2 * np.pi * spins * ease(u)) @ slerp(a0, a1, ease(u))
            self.weapon[t] = [c - d * L / 2, c + d * L / 2]