"""Joint-local axes transformed from recorded mocap orientations into world space.""" import json import h5py import numpy as np AXIS_LENGTH_M = 0.018 AXIS_COLORS = np.array([[245, 75, 75], [65, 210, 95], [70, 135, 255]], dtype=np.uint8) def axis_segments(positions, quaternions_wxyz, world_from_mocap): """Return three positive-axis segments per valid joint, ordered X, Y, Z.""" positions = np.asarray(positions, dtype=float) q = np.asarray(quaternions_wxyz, dtype=float) norms = np.linalg.norm(q, axis=-1) valid = np.isfinite(positions).all(axis=-1) & np.isfinite(q).all(axis=-1) & (norms > 1e-8) q = q[valid] / norms[valid, None] w, x, y, z = q.T rotation = np.empty((len(q), 3, 3)) rotation[:, 0, :] = np.column_stack((1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w))) rotation[:, 1, :] = np.column_stack((2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w))) rotation[:, 2, :] = np.column_stack((2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y))) # Matrix columns are the joint axes expressed in the destination frame. directions = (world_from_mocap @ rotation).transpose(0, 2, 1) origins = np.broadcast_to(positions[valid, None, :], directions.shape) lines = np.stack((origins, origins + AXIS_LENGTH_M * directions), axis=2).reshape(-1, 2, 3) return lines, np.tile(AXIS_COLORS, (len(q), 1)) class JointAxes: def __init__(self, episode): meta = json.loads((episode / 'meta/world_motion.json').read_text(encoding='utf-8')) self.rotations = {} self.orientations = {} for side in ['left', 'right']: rotation = np.asarray(meta[f'{side}_initial_world_from_mocap'], dtype=float) if rotation.shape != (3, 3) or not np.isfinite(rotation).all(): raise ValueError(f'Invalid world-from-mocap rotation: {side}') self.rotations[side] = rotation with h5py.File(episode / f'mocap/{side}.h5', 'r') as handle: # Acquisition already applied P-pose calibration. Do not apply it twice. self.orientations[side] = handle['skeleton'][:, :, 3:7] def frame(self, side, frame, positions): return axis_segments(positions, self.orientations[side][frame], self.rotations[side])