File size: 18,483 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
289
290
291
"""Skeletons for the condition proxy: a joint tree, per-joint part ids, a rest pose, and capsule sizing.

Part ids (1..30) reuse the BOSSV2V humanoid vocabulary where the anatomy matches so a quadruped's front legs look like
arms and its hind legs like legs to the model; new structures get new ids:
    1 pelvis/root  2 spine_01  3 spine_02/chest  4 neck  5 head
    6/7/8 upperarm/lowerarm/hand L   9/10/11 R    12/13/14 thigh/calf/foot L   15/16/17 R    18 weapon
    19-22 tail segments   23-25 wing L   26-28 wing R   29-30 extra limbs
Rest poses are in a local frame: root above the origin, facing +X, UE axes (Y = right, so the LEFT side is -Y), cm.
Links are drawn with the CHILD joint's part id (dataset rule).
"""
from dataclasses import dataclass, field
import numpy as np

HUMANOID_JOINTS = ["pelvis", "spine_01", "spine_02", "neck_01", "head", "upperarm_l", "lowerarm_l", "hand_l",
                   "upperarm_r", "lowerarm_r", "hand_r", "thigh_l", "calf_l", "foot_l", "thigh_r", "calf_r", "foot_r"]
HUMANOID_PARENTS = ["", "pelvis", "spine_01", "spine_02", "neck_01", "neck_01", "upperarm_l", "lowerarm_l",
                    "neck_01", "upperarm_r", "lowerarm_r", "pelvis", "thigh_l", "calf_l", "pelvis", "thigh_r", "calf_r"]
LINE_RATIO, JOINT_RATIO, HEAD_RATIO = 0.006, 0.012, 0.018       # of body height, as in condition_profile.json
WEAPON_PART = 18


@dataclass
class Weapon:
    hand: str                      # joint the grip follows
    length: float                  # cm
    radius: float                  # cm (dataset: player 1.75, boss 5.5)
    grip_offset: float = 0.0       # cm from the grip end to the hand along the shaft (butt sticks out behind the hand)


@dataclass
class Skeleton:
    name: str
    joints: list
    parents: list                  # parent joint name per joint ("" for the root)
    parts: list                    # part id per joint
    rest: np.ndarray               # (J, 3) local rest positions, facing +X, root at index 0
    height: float                  # body size used for capsule radii (cm)
    weapon: Weapon = None
    family: str = "custom"
    meta: dict = field(default_factory=dict)

    def __post_init__(self):
        self.rest = np.asarray(self.rest, float)
        assert len(self.joints) == len(self.parents) == len(self.parts) == len(self.rest)
        assert self.parents[0] == "" and all(p in self.joints for p in self.parents[1:])
        assert all(1 <= p <= 30 for p in self.parts)
        self.index = {n: i for i, n in enumerate(self.joints)}
        self.parent_idx = [-1] + [self.index[p] for p in self.parents[1:]]
        assert all(self.parent_idx[i] < i for i in range(1, len(self.joints))), "joints must be topologically ordered"

    @property
    def bone_lengths(self):
        return np.array([0.0] + [np.linalg.norm(self.rest[i] - self.rest[self.parent_idx[i]]) for i in range(1, len(self.joints))])

    def descendants(self, joint):
        """Indices of `joint` and every joint below it."""
        root = self.index[joint]; out = [root]
        for i in range(root + 1, len(self.joints)):
            if self.parent_idx[i] in out:
                out.append(i)
        return out

    def place(self, root_pos, yaw=0.0):
        """Rest pose moved so the root sits at root_pos and the body faces yaw (rad about +Z; 0 = +X)."""
        from .geometry import rot_z
        return np.asarray(root_pos, float) + (self.rest - self.rest[0]) @ rot_z(yaw).T

    def capsules(self, pose, slot, weapon_ends=None):
        """Capsules for one frame: links (child part), joint spheres, weapon stick."""
        caps = []
        size = self.height
        for i in range(1, len(self.joints)):
            caps.append((pose[self.parent_idx[i]], pose[i], size * LINE_RATIO, slot * 32 + self.parts[i]))
        for i, n in enumerate(self.joints):
            r = HEAD_RATIO if self.parts[i] == 5 else JOINT_RATIO
            caps.append((pose[i], pose[i], size * r, slot * 32 + self.parts[i]))
        if weapon_ends is not None and self.weapon is not None:
            caps.append((weapon_ends[0], weapon_ends[1], self.weapon.radius, slot * 32 + WEAPON_PART))
        return caps


# ----------------------------------------------------------------------------------------------------------- families
def humanoid(height=180.0, shoulder=0.13, hip=0.055, weapon=None, name="humanoid", lengths=None):
    """Proportional humanoid in the BOSSV2V 17-joint layout, standing, arms slightly out. `lengths` (joint -> bone cm)
    overrides the proportional defaults (use humanoid_from_states for a measured character)."""
    H = height
    z_pelvis = 0.53 * H
    rest = {
        "pelvis": [0, 0, z_pelvis], "spine_01": [0, 0, z_pelvis + 0.07 * H], "spine_02": [0, 0, z_pelvis + 0.17 * H],
        "neck_01": [0, 0, z_pelvis + 0.30 * H], "head": [0, 0, z_pelvis + 0.40 * H],
        "upperarm_l": [0, -shoulder * H, z_pelvis + 0.29 * H], "lowerarm_l": [0, -shoulder * H - 0.05 * H, z_pelvis + 0.13 * H],
        "hand_l": [0.03 * H, -shoulder * H - 0.07 * H, z_pelvis - 0.02 * H],
        "upperarm_r": [0, shoulder * H, z_pelvis + 0.29 * H], "lowerarm_r": [0, shoulder * H + 0.05 * H, z_pelvis + 0.13 * H],
        "hand_r": [0.03 * H, shoulder * H + 0.07 * H, z_pelvis - 0.02 * H],
        "thigh_l": [0, -hip * H, z_pelvis - 0.02 * H], "calf_l": [0.01 * H, -hip * H, 0.28 * H], "foot_l": [0, -hip * H, 0.0],
        "thigh_r": [0, hip * H, z_pelvis - 0.02 * H], "calf_r": [0.01 * H, hip * H, 0.28 * H], "foot_r": [0, hip * H, 0.0],
    }
    pts = np.array([rest[j] for j in HUMANOID_JOINTS], float)
    sk = Skeleton(name, HUMANOID_JOINTS, HUMANOID_PARENTS, list(range(1, 18)), pts, H, weapon, "humanoid")
    if lengths:
        sk = with_bone_lengths(sk, lengths)
    return sk


def with_bone_lengths(sk, lengths):
    """Rescale individual bones (joint -> new length from its parent) keeping rest directions."""
    rest = sk.rest.copy(); rel = sk.rest - np.r_[[sk.rest[0]], sk.rest[sk.parent_idx[1:]]]
    for i in range(1, len(sk.joints)):
        d = rel[i]; L = np.linalg.norm(d)
        new_L = lengths.get(sk.joints[i], L)
        rest[i] = rest[sk.parent_idx[i]] + (d / L * new_L if L > 1e-6 else d)
    return Skeleton(sk.name, sk.joints, sk.parents, sk.parts, rest, sk.height, sk.weapon, sk.family, dict(sk.meta))


def _chain(prefix, start, direction, n, seg_len, parent, parts):
    names, parents, pts, pids = [], [], [], []
    d = np.asarray(direction, float); d = d / np.linalg.norm(d)
    prev, p = parent, np.asarray(start, float)
    for k in range(n):
        p = p + d * seg_len
        nm = f"{prefix}_{k + 1}"
        names.append(nm); parents.append(prev); pts.append(p.copy()); pids.append(parts[min(k, len(parts) - 1)])
        prev = nm
    return names, parents, pts, pids


def quadruped(body_length=300.0, shoulder_height=150.0, neck=80.0, head=50.0, tail_segments=4, tail_length=200.0,
              name="quadruped", wings=0.0, belly=None, leg_spread=0.18):
    """Four-legged beast facing +X. Front legs use the arm part ids, hind legs the leg part ids. wings > 0 adds two
    3-segment wings of that span (cm) at the shoulders (dragon)."""
    Hs = shoulder_height; half = body_length / 2; lat = leg_spread * body_length
    belly = Hs * 0.62 if belly is None else float(belly)   # chest/elbow line: the legs hang from here, not from the back     # trunk height above ground: short-legged beasts sit low
    names = ["pelvis", "spine_01", "spine_02", "neck_01", "head"]
    parents = ["", "pelvis", "spine_01", "spine_02", "neck_01"]
    withers = Hs                                             # the back rides at the nominal shoulder height; the drop
    pts = [[-half, 0, Hs * 0.94], [0, 0, Hs * 0.97], [half, 0, withers],   # from here down to `belly` is the chest depth
           [half + neck * 0.55, 0, withers + neck * 0.35], [half + neck * 0.55 + head * 0.9, 0, withers + neck * 0.18]]
    parts = [1, 2, 3, 4, 5]

    def leg(prefix, hip_joint, x, y, ids, bend):
        """bend -1: elbow folds back (front legs); +1: stifle points forward (hind legs) -> animal, not table."""
        nonlocal names, parents, pts, parts
        upper = [x, y, belly]
        knee = [x + bend * 0.28 * belly, y, belly * 0.48]
        foot = [x - bend * 0.08 * belly, y, 0.0]
        names += [f"{prefix}_upper", f"{prefix}_lower", f"{prefix}_foot"]
        parents += [hip_joint, f"{prefix}_upper", f"{prefix}_lower"]
        pts += [upper, knee, foot]; parts += list(ids)

    leg("front_l", "spine_02", half, -lat, (6, 7, 8), -1); leg("front_r", "spine_02", half, lat, (9, 10, 11), -1)
    leg("hind_l", "pelvis", -half, -lat, (12, 13, 14), 1); leg("hind_r", "pelvis", -half, lat, (15, 16, 17), 1)
    if tail_segments:
        n, pa, pp, pi = _chain("tail", pts[0], [-1, 0, -0.15], tail_segments, tail_length / tail_segments, "pelvis", [19, 20, 21, 22])
        names += n; parents += pa; pts += [list(x) for x in pp]; parts += pi
    if wings > 0:
        arm = wings / 2 * 0.42                                # shoulder -> raised wrist
        finger = wings / 2 * 0.58                             # wrist -> tip, fingers sweep down and back into an arc
        for side, sgn, ids in (("wing_l", -1, [23, 24, 25]), ("wing_r", 1, [26, 27, 28])):
            root_pt = [half * 0.75, sgn * lat * 0.45, belly * 1.05]
            nm, pa, pp, pi = _chain(side, root_pt, [0.05, sgn * 0.8, 0.62], 2, arm / 2, "spine_02", ids[:2])
            names += nm; parents += pa; pts += [list(x) for x in pp]; parts += pi
            wrist = np.asarray(pp[-1], float); wrist_name = nm[-1]
            # graded finger lengths with the outer half curling down: a swept membrane edge, not three straight spokes
            for k, (d, frac) in enumerate((([0.45, sgn * 0.85, -0.25], 1.00),
                                           ([-0.15, sgn * 0.92, -0.32], 0.86),
                                           ([-0.70, sgn * 0.62, -0.30], 0.64))):
                d = np.asarray(d, float); d /= np.linalg.norm(d)
                d2 = d + np.array([0.0, 0.0, -0.55]); d2 /= np.linalg.norm(d2)
                a = wrist + d * finger * frac * 0.55
                b = a + d2 * finger * frac * 0.45
                names += [f"{side}f{k + 1}_1", f"{side}f{k + 1}_2"]
                parents += [wrist_name, f"{side}f{k + 1}_1"]
                pts += [list(a), list(b)]; parts += [ids[2], ids[2]]
    size = max(body_length, Hs)
    return Skeleton(name, names, parents, parts, np.array(pts, float), size, None, "dragon" if wings > 0 else "quadruped",
                    dict(body_length=body_length, shoulder_height=Hs))


def dragon(body_length=500.0, shoulder_height=260.0, wingspan=1200.0, **kw):
    return quadruped(body_length, shoulder_height, neck=kw.pop("neck", 220.0), head=kw.pop("head", 110.0),
                     tail_segments=kw.pop("tail_segments", 4), tail_length=kw.pop("tail_length", 450.0), wings=wingspan,
                     name=kw.pop("name", "dragon"), **kw)


def wyvern(body_length=380.0, hip_height=185.0, shoulder_height=375.0, neck=150.0, head=90.0,
           wingspan=1230.0, wing_rise=210.0, stance_width=315.0, tail_segments=5, tail_length=280.0,
           name="wyvern"):
    """Two-legged winged dragon facing +X: the wings ARE the forelimbs, so there are NO front legs.

    This is WildWorld's most common monster body plan (2 legs + 2 wings = 4874 of 15226 windows;
    4 legs + 2 wings is only 520), and it is what concept art calls a dragon. quadruped(wings=...)
    draws four legs plus wings and produces a ten-limbed creature. Every size here is meant to be
    MEASURED off the first frame (hip and shoulder height, body length, wingspan), never guessed."""
    half = body_length / 2; hs = shoulder_height; half_span = wingspan / 2; lat = stance_width / 2
    names = ["pelvis", "spine_01", "spine_02", "neck_01", "head"]
    parents = ["", "pelvis", "spine_01", "spine_02", "neck_01"]
    pts = [[-half, 0, hip_height],                           # reared trunk: hips low, shoulders high
           [0, 0, (hip_height + hs) / 2],
           [half, 0, hs],
           [half + neck * 0.55, 0, hs * 0.97],
           [half + neck * 0.55 + head, 0, hs * 0.88]]        # head carried forward and a little below the back
    parts = [1, 2, 3, 4, 5]
    for side, sgn, ids in (("hind_l", -1, (12, 13, 14)), ("hind_r", 1, (15, 16, 17))):
        names += [f"{side}_upper", f"{side}_lower", f"{side}_foot"]
        parents += ["pelvis", f"{side}_upper", f"{side}_lower"]
        pts += [[-half, sgn * lat, hip_height * 0.98],
                [-half + 0.30 * hip_height, sgn * lat, hip_height * 0.46],   # stifle forward, bird-like
                [-half - 0.06 * hip_height, sgn * lat, 0.0]]
        parts += list(ids)
    if tail_segments:
        n, pa, pp, pi = _chain("tail", pts[0], [-1, 0, -0.25], tail_segments, tail_length / tail_segments,
                               "pelvis", [19, 20, 21, 22])
        names += n; parents += pa; pts += [list(x) for x in pp]; parts += pi
    for side, sgn, ids in (("wing_l", -1, [23, 24, 25]), ("wing_r", 1, [26, 27, 28])):
        root = np.array([half * 0.75, sgn * lat * 0.35, hs * 0.98])
        wrist = np.array([root[0] + 0.06 * half_span, sgn * 0.40 * half_span, root[2] + 0.62 * wing_rise])
        elbow = root + 0.5 * (wrist - root) + np.array([0.0, 0.0, 0.12 * wing_rise])
        names += [f"{side}_1", f"{side}_2"]; parents += ["spine_02", f"{side}_1"]
        pts += [list(elbow), list(wrist)]; parts += ids[:2]
        # leading finger carries the claw high, middle finger sets the span, trailing finger drops behind
        for k, (fx, fy, fz) in enumerate(((0.28, 0.48, 0.87), (-0.02, 1.00, 0.00), (-0.42, 0.66, -0.30))):
            tip = np.array([root[0] + fx * half_span, sgn * fy * half_span, root[2] + fz * wing_rise])
            mid = wrist + 0.5 * (tip - wrist) + np.array([0.0, 0.0, 0.03 * wing_rise])
            names += [f"{side}f{k + 1}_1", f"{side}f{k + 1}_2"]
            parents += [f"{side}_2", f"{side}f{k + 1}_1"]
            pts += [list(mid), list(tip)]; parts += [ids[2], ids[2]]
    return Skeleton(name, names, parents, parts, np.array(pts, float), max(body_length, hs), None, "dragon",
                    dict(body_length=body_length, shoulder_height=hs, wingspan=wingspan))


def serpent(length=1200.0, segments=10, girth_height=60.0, head_raise=120.0, name="serpent", s_curve=0.55):
    """Snake/worm facing +X: root at the front of the body, neck and head rearing forward, body segments trailing -X."""
    seg = length / segments
    # Reared front: the neck rises and leans back, then the head comes forward again -> the S the reference art shows.
    names = ["pelvis", "neck_01", "neck_02", "neck_03", "neck_04", "head"]
    parents = ["", "pelvis", "neck_01", "neck_02", "neck_03", "neck_04"]
    # five joints trace a smooth S (scaled by the rear-up, not by one body segment): rise forward, ease back
    # over the coil, then the head thrusts out again. Three joints made it read as a hard Z.
    k = s_curve / 0.55
    prof = ((0.22 * k, 0.25), (0.31 * k, 0.52), (0.19 * k, 0.74), (0.17 * k, 0.96), (0.56, 0.90))
    pts = [[0.0, 0.0, girth_height]] + [[head_raise * fx, 0.0, girth_height + head_raise * fz] for fx, fz in prof]
    parts = [1, 3, 3, 4, 4, 5]
    prev = "pelvis"
    for k in range(1, segments):
        names.append(f"body_{k}"); parents.append(prev); prev = f"body_{k}"
        pts.append([-k * seg, 0.0, girth_height]); parts.append(2 if k < segments / 3 else (3 if k < 2 * segments / 3 else 19 + min(3, k % 4)))
    return Skeleton(name, names, parents, parts, np.array(pts, float), max(length / 4, girth_height + head_raise), None, "serpent",
                    dict(length=length, segments=segments))


def spider(leg_count=8, body_length=200.0, body_height=90.0, leg_span=350.0, name="spider"):
    """Arachnid/insect: thorax + abdomen + head, leg_count legs (even) spread along the body, 3 segments each."""
    names = ["pelvis", "spine_01", "spine_02", "neck_01", "head"]
    parents = ["", "pelvis", "spine_01", "spine_02", "neck_01"]
    L = body_length
    pts = [[-0.4 * L, 0, body_height], [-0.1 * L, 0, body_height], [0.15 * L, 0, body_height], [0.3 * L, 0, body_height * 1.02], [0.45 * L, 0, body_height * 0.95]]
    parts = [1, 2, 3, 4, 5]
    pairs = leg_count // 2
    id_sets = [((6, 7, 8), (9, 10, 11)), ((12, 13, 14), (15, 16, 17)), ((29, 7, 8), (30, 10, 11)), ((29, 13, 14), (30, 16, 17))]
    for k in range(pairs):
        x = 0.2 * L - k * (0.35 * L / max(1, pairs - 1))
        for side, sgn, ids in (("l", -1, id_sets[k % 4][0]), ("r", 1, id_sets[k % 4][1])):
            pre = f"leg{k + 1}_{side}"
            hip = [x, sgn * 0.12 * L, body_height]
            knee = [x + 0.05 * L * (1.5 - k), sgn * leg_span * 0.3, body_height * 1.6]
            foot = [x + 0.12 * L * (1.5 - k), sgn * leg_span * 0.5, 0.0]
            names += [f"{pre}_hip", f"{pre}_knee", f"{pre}_foot"]
            parents += ["spine_01", f"{pre}_hip", f"{pre}_knee"]
            pts += [hip, knee, foot]; parts += list(ids)
    return Skeleton(name, names, parents, parts, np.array(pts, float), max(body_length, leg_span) * 0.8, None, "spider",
                    dict(leg_count=leg_count))


def humanoid_from_states(states_path, entity, weapon_radius=None, name=None):
    """Measured humanoid (BOSSV2V entity 0 = player, 1 = boss): median bone lengths over the clip on the proportional
    rest directions, plus the measured weapon length and grip offset from the right hand."""
    z = np.load(states_path)
    Jw = z["joints_world_cm"][:, entity]; Ww = z["weapon_endpoints_world_cm"][:, entity]
    base = humanoid(height=float(np.median(Jw[:, 4, 2] - np.minimum(Jw[:, 13, 2], Jw[:, 16, 2]))) * 1.08)
    lengths = {}
    for i in range(1, 17):
        lengths[HUMANOID_JOINTS[i]] = float(np.median(np.linalg.norm(Jw[:, i] - Jw[:, base.parent_idx[i]], axis=1)))
    wlen = float(np.median(np.linalg.norm(Ww[:, 1] - Ww[:, 0], axis=1)))
    grip = float(np.median(np.linalg.norm(Ww[:, 0] - Jw[:, 10], axis=1)))
    radius = weapon_radius if weapon_radius is not None else (1.75 if entity == 0 else 5.5)
    height = 180.0 if entity == 0 else 460.0                       # the dataset's fixed sizing constants
    sk = with_bone_lengths(humanoid(height=height), lengths)
    sk.weapon = Weapon("hand_r", wlen, radius, grip)
    sk.name = name or ("player" if entity == 0 else "boss"); sk.height = height
    return sk