yuzhewu207's picture
ww_index: window list, captions, lags and scripts to rebuild the WildWorld windows from upstream
a54e6a7 verified
Raw History Blame Contribute Delete
5.6 kB
"""Recorded humanoid motion clips from BOSSV2V, stored body-relative and retargeted to any humanoid skeleton.
Clip frame: root (pelvis) ground point at the clip's first frame at the origin, facing +X (UE: +Y right). Facing is
taken from the hips: right = thigh_r - thigh_l (horizontal), forward = (right_y, -right_x).
Retargeting walks the joint tree parent-first and re-lays every bone along the clip's bone direction with the target
skeleton's length; the root path is scaled by the leg-length ratio; the weapon keeps its clip direction, re-anchored
to the target hand.
"""
import glob, json
from pathlib import Path
import numpy as np
from .geometry import rot_z
from .skeleton import HUMANOID_JOINTS
DATA = Path(__file__).resolve().parent / "data"
BOSSV2V = "/data/yuzhewu/datasets/BOSSV2V"
_J = {n: i for i, n in enumerate(HUMANOID_JOINTS)}
def facing_yaw(joints):
r = joints[_J["thigh_r"]] - joints[_J["thigh_l"]]
return float(np.arctan2(-r[0], r[1])) # forward = (r_y, -r_x)
def to_clip_frame(J, W):
"""World (T,17,3) joints and (T,2,3) weapon -> clip frame of their first frame."""
yaw0 = facing_yaw(J[0]); origin = J[0, 0].copy(); origin[2] = 0.0
R = rot_z(-yaw0)
return (J - origin) @ R.T, (W - origin) @ R.T
def extract(out=DATA / "humanoid_clips.npz", min_frames=12):
"""Cut every labelled boss move (and player hit reactions) out of the local BOSSV2V clips."""
clips = {}
for d in sorted(glob.glob(f"{BOSSV2V}/session_*")):
if not (Path(d, "pairs.jsonl").exists() and Path(d, "states.npz").exists()):
continue
rows = [json.loads(l) for l in open(Path(d, "pairs.jsonl"))]
z = np.load(Path(d, "states.npz")); J = z["joints_world_cm"]; W = z["weapon_endpoints_world_cm"]
for key, ent in (("boss_move", 1), ("player_reaction", 0)):
labels = [r[key] for r in rows]
s = 0
for i in range(1, len(labels) + 1):
if i == len(labels) or labels[i] != labels[s]:
name = labels[s]
if name not in (None, "None") and i - s >= min_frames:
role = "boss" if ent == 1 else "player"
j, w = to_clip_frame(J[s:i, ent], W[s:i, ent])
k = f"{role}/{name}/{Path(d).name[-8:]}_{s:04d}"
clips[k + "/joints"] = j.astype(np.float32); clips[k + "/weapon"] = w.astype(np.float32)
s = i
DATA.mkdir(parents=True, exist_ok=True)
np.savez_compressed(out, **clips)
return sorted({k.rsplit("/", 1)[0] for k in clips})
def load(path=DATA / "humanoid_clips.npz"):
z = np.load(path)
clips = {}
for k in z.files:
base, what = k.rsplit("/", 1)
clips.setdefault(base, {})[what] = z[k]
return clips
def names(clips, role=None, move=None):
return sorted(k for k in clips if (role is None or k.split("/")[0] == role) and (move is None or k.split("/")[1] == move))
def retarget(clip, skeleton, speed=1.0, mirror=False):
"""Clip (clip frame) -> (joints (T',17,3), weapon (T',2,3)) in the clip frame for `skeleton`'s bone lengths."""
J, W = clip["joints"].astype(float), clip["weapon"].astype(float)
if mirror:
J = J.copy(); W = W.copy(); J[..., 1] *= -1; W[..., 1] *= -1
swap = [_J[n.replace("_l", "_TMP").replace("_r", "_l").replace("_TMP", "_r")] for n in HUMANOID_JOINTS]
J = J[:, swap]
T = J.shape[0]
src_t = np.arange(0, T - 1 + 1e-6, speed)
idx = np.floor(src_t).astype(int); frac = (src_t - idx)[:, None, None]
nxt = np.minimum(idx + 1, T - 1)
J = J[idx] * (1 - frac) + J[nxt] * frac; W = W[idx] * (1 - frac) + W[nxt] * frac
sk = skeleton; lengths = sk.bone_lengths
src_leg = np.median(np.linalg.norm(J[:, _J["thigh_l"]] - J[:, _J["calf_l"]], axis=1) + np.linalg.norm(J[:, _J["calf_l"]] - J[:, _J["foot_l"]], axis=1))
tgt_leg = lengths[_J["calf_l"]] + lengths[_J["foot_l"]]
scale = tgt_leg / src_leg
out = np.zeros_like(J)
out[:, 0] = J[:, 0] * scale
for i in range(1, 17):
p = sk.parent_idx[i]
d = J[:, i] - J[:, p]; d = d / np.maximum(np.linalg.norm(d, axis=1, keepdims=True), 1e-6)
out[:, i] = out[:, p] + d * lengths[i]
weapon = None
if sk.weapon is not None:
h = _J[sk.weapon.hand]
d = W[:, 1] - W[:, 0]; d = d / np.maximum(np.linalg.norm(d, axis=1, keepdims=True), 1e-6)
butt = out[:, h] + (W[:, 0] - J[:, h]) / np.maximum(np.linalg.norm(W[:, 0] - J[:, h], axis=1, keepdims=True), 1e-6) * sk.weapon.grip_offset
weapon = np.stack([butt, butt + d * sk.weapon.length], axis=1)
return out, weapon
def play(track, clip, t0, root_xy=None, yaw=None, speed=1.0, mirror=False, hold=True):
"""Write a retargeted clip into a Track starting at frame t0, placed at root_xy / yaw (default: where the track's
root and facing are at t0). Frames after the clip hold its last pose if hold."""
J, W = retarget(clip, track.sk, speed, mirror)
root_xy = track.poses[t0, 0, :2] if root_xy is None else np.asarray(root_xy, float)
yaw = track.yaw[t0] if yaw is None else yaw
R = rot_z(yaw); off = np.array([root_xy[0], root_xy[1], 0.0])
n = min(len(J), track.T - t0)
track.poses[t0:t0 + n] = J[:n] @ R.T + off
track.yaw[t0:t0 + n] = yaw
if W is not None:
if track.weapon is None:
track.weapon = np.zeros((track.T, 2, 3))
track.weapon[t0:t0 + n] = W[:n] @ R.T + off
if hold and t0 + n < track.T:
track.freeze(t0 + n, track.T, at=t0 + n - 1)
return n