#!/usr/bin/env python3 """Isaac Lab replay of v2d G1 Inspire + object + MANO. Scene: a table, the tracked object as a dynamic box, and the floating Inspire hand. Predicted object motion is not assumed to already sit on the table, so replay has two phases: 1. **Settle (physics)** — XY of the object is locked to the video start; gravity may change Z and rotation until the object rests on the table. The hand (and MANO) keep the same relative pose to the object as in the video at t=0. 2. **Motion** — remaining clip is applied as a rigid delta from that settled start, so hand–object relative motion matches the video. Plays once, writes an MP4, then exits. Usage (from simulation/): ./replay_v2d.sh --npz ../reconstruction/runs//obj_tracking_out/isaaclab_replay.npz --headless """ from __future__ import annotations import argparse import sys from pathlib import Path from isaaclab.app import AppLauncher if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(line_buffering=True) parser = argparse.ArgumentParser(description="Replay v2d G1 Inspire + object + MANO in Isaac Lab.") parser.add_argument("--npz", type=Path, required=True, help="isaaclab_replay.npz from retarget/export_isaaclab.py") parser.add_argument( "--output", type=Path, default=None, help="MP4 path (default: /isaaclab_replay.mp4)", ) parser.add_argument("--no-mano", action="store_true") parser.add_argument("--no-object", action="store_true") parser.add_argument("--table-z", type=float, default=0.75, help="Table-top height (m).") parser.add_argument("--drop-height", type=float, default=0.08, help="Object origin above table at settle start (m).") parser.add_argument("--settle-sec", type=float, default=2.0, help="Physics settle duration (s).") parser.add_argument("--no-settle", action="store_true", help="Skip physics settle; play video poses on the table.") AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() args_cli.enable_cameras = True app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app import numpy as np # noqa: E402 import torch # noqa: E402 import isaaclab.sim as sim_utils # noqa: E402 from isaaclab.actuators import ImplicitActuatorCfg # noqa: E402 from isaaclab.assets import Articulation, ArticulationCfg, RigidObject, RigidObjectCfg # noqa: E402 from isaaclab.markers import VisualizationMarkers, VisualizationMarkersCfg # noqa: E402 from isaaclab.sensors.camera import Camera, CameraCfg # noqa: E402 from isaaclab.sim import SimulationContext # noqa: E402 _NONE_DRIVE = sim_utils.UrdfConverterCfg.JointDriveCfg( gains=sim_utils.UrdfConverterCfg.JointDriveCfg.PDGainsCfg(stiffness=0.0, damping=0.0) ) _TABLE_SIZE = (1.6, 1.0, 0.05) def _wxyz_to_xyzw(wxyz: np.ndarray) -> np.ndarray: wxyz = np.asarray(wxyz, dtype=np.float64) return np.stack([wxyz[..., 1], wxyz[..., 2], wxyz[..., 3], wxyz[..., 0]], axis=-1) def _pose7_xyzw(pos: np.ndarray, wxyz: np.ndarray) -> np.ndarray: return np.concatenate([np.asarray(pos, dtype=np.float64), _wxyz_to_xyzw(wxyz)], axis=-1) def _quat_mul(q1: np.ndarray, q2: np.ndarray) -> np.ndarray: x1, y1, z1, w1 = np.asarray(q1, dtype=np.float64) x2, y2, z2, w2 = np.asarray(q2, dtype=np.float64) return np.array( [ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, ] ) def _quat_conj(q: np.ndarray) -> np.ndarray: return np.array([-q[0], -q[1], -q[2], q[3]], dtype=np.float64) def _quat_apply(q: np.ndarray, v: np.ndarray) -> np.ndarray: v = np.asarray(v, dtype=np.float64) qv = np.array([v[0], v[1], v[2], 0.0]) return _quat_mul(_quat_mul(q, qv), _quat_conj(q))[:3] def _compose(a: np.ndarray, b: np.ndarray) -> np.ndarray: """SE3 multiply pose7 xyz+xyzw: a * b.""" pa, qa = a[:3], a[3:] pb, qb = b[:3], b[3:] out = np.empty(7, dtype=np.float64) out[:3] = pa + _quat_apply(qa, pb) out[3:] = _quat_mul(qa, qb) return out def _inverse(a: np.ndarray) -> np.ndarray: q = _quat_conj(a[3:]) out = np.empty(7, dtype=np.float64) out[:3] = -_quat_apply(q, a[:3]) out[3:] = q return out def _apply_pose_pts(pose: np.ndarray, pts: np.ndarray) -> np.ndarray: p, q = pose[:3], pose[3:] pts = np.asarray(pts, dtype=np.float64) flat = pts.reshape(-1, 3) out = np.empty_like(flat) for i, v in enumerate(flat): out[i] = p + _quat_apply(q, v) return out.reshape(pts.shape) def _hand_cfg(urdf: str, prim: str) -> ArticulationCfg: return ArticulationCfg( prim_path=prim, spawn=sim_utils.UrdfFileCfg( asset_path=urdf, fix_base=False, activate_contact_sensors=False, merge_fixed_joints=True, rigid_props=sim_utils.RigidBodyPropertiesCfg( disable_gravity=True, linear_damping=0.0, angular_damping=0.0, max_linear_velocity=1000.0, max_angular_velocity=1000.0, ), collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=False), articulation_props=sim_utils.ArticulationRootPropertiesCfg( enabled_self_collisions=False, solver_position_iteration_count=8, solver_velocity_iteration_count=0, ), joint_drive=_NONE_DRIVE, ), init_state=ArticulationCfg.InitialStateCfg( pos=(0.0, 0.0, 0.5), joint_pos={".*": 0.0}, joint_vel={".*": 0.0}, ), actuators={ "fingers": ImplicitActuatorCfg( joint_names_expr=[".*"], stiffness=0.0, damping=0.0, effort_limit_sim=10.0, velocity_limit_sim=10.0, ), }, ) def _object_cfg(urdf: str, prim: str, *, physics: bool) -> RigidObjectCfg: return RigidObjectCfg( prim_path=prim, spawn=sim_utils.UrdfFileCfg( asset_path=urdf, fix_base=False, joint_drive=None, mass_props=sim_utils.MassPropertiesCfg(mass=0.35), rigid_props=sim_utils.RigidBodyPropertiesCfg( disable_gravity=not physics, kinematic_enabled=not physics, linear_damping=0.15 if physics else 0.0, angular_damping=0.35 if physics else 0.0, max_linear_velocity=5.0, max_angular_velocity=20.0, ), collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=physics), physics_material=sim_utils.RigidBodyMaterialCfg( static_friction=0.8, dynamic_friction=0.6, restitution=0.0 ), ), init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 0.5)), ) def _spawn_table(xy: np.ndarray, table_top: float) -> None: thick = _TABLE_SIZE[2] cfg = sim_utils.CuboidCfg( size=_TABLE_SIZE, rigid_props=sim_utils.RigidBodyPropertiesCfg( kinematic_enabled=True, disable_gravity=True, ), mass_props=sim_utils.MassPropertiesCfg(mass=50.0), collision_props=sim_utils.CollisionPropertiesCfg(), visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.48, 0.34, 0.22)), physics_material=sim_utils.RigidBodyMaterialCfg( static_friction=0.9, dynamic_friction=0.7, restitution=0.0 ), ) cfg.func( "/World/Table", cfg, translation=(float(xy[0]), float(xy[1]), float(table_top - 0.5 * thick)), ) def _joint_order(sim_names: list[str], src_names: list[str]) -> list[int | None]: src = {n: i for i, n in enumerate(src_names)} order: list[int | None] = [src.get(name) for name in sim_names] matched = sum(i is not None for i in order) missing = [n for n, i in zip(sim_names, order) if i is None] extra = [n for n in src_names if n not in set(sim_names)] print(f"[v2d] joint map: {matched}/{len(sim_names)} sim joints in retarget q", flush=True) if missing: print(f"[v2d] sim joints not in npz (held at 0, often mimics): {missing}", flush=True) if extra: print(f"[v2d] retarget joints unused by sim (often mimics): {extra}", flush=True) if matched == 0: raise RuntimeError(f"no joint-name overlap: sim={sim_names} retarget={src_names}") return order def _finger_row(finger_q: np.ndarray, t: int, order: list[int | None]) -> np.ndarray: row = np.zeros(len(order), dtype=np.float64) src = finger_q[t] for j, idx in enumerate(order): if idx is not None and idx < src.shape[0] and np.isfinite(src[idx]): row[j] = src[idx] return row def _as_numpy(x) -> np.ndarray: if hasattr(x, "torch"): x = x.torch if isinstance(x, torch.Tensor): return x.detach().cpu().numpy() return np.asarray(x) def _rgb_frame(camera: Camera) -> np.ndarray: out = camera.data.output rgb = out["rgb"] if isinstance(out, dict) or hasattr(out, "__getitem__") else out img = _as_numpy(rgb) if img.ndim == 4: img = img[0] img = img[..., :3] if img.dtype != np.uint8: scale = 255.0 if float(np.nanmax(img)) <= 1.5 else 1.0 img = np.clip(img * scale, 0, 255).astype(np.uint8) h, w = img.shape[:2] return img[: h - (h % 2), : w - (w % 2)] def _write_mp4(path: Path, frames: list[np.ndarray], fps: float) -> None: if not frames: raise RuntimeError("no frames captured for MP4") path.parent.mkdir(parents=True, exist_ok=True) try: import imageio.v2 as imageio imageio.mimsave(str(path), frames, fps=float(fps), codec="libx264", pixelformat="yuv420p") return except Exception as exc: print(f"[v2d] imageio h264 failed ({exc}); trying OpenCV", flush=True) import cv2 h, w = frames[0].shape[:2] writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h)) if not writer.isOpened(): raise RuntimeError(f"could not open VideoWriter for {path}") for fr in frames: writer.write(cv2.cvtColor(fr, cv2.COLOR_RGB2BGR)) writer.release() def main() -> None: npz_path = args_cli.npz.resolve() if not npz_path.is_file(): raise SystemExit(f"missing {npz_path} — run retarget/export_isaaclab.sh first") out_mp4 = (args_cli.output or (npz_path.parent / "isaaclab_replay.mp4")).resolve() data = np.load(npz_path, allow_pickle=True) fps = float(data["fps"]) n = int(data["root_pos"].shape[0]) side = str(data["side"]) hand_urdf = str(data["hand_urdf"]) obj_urdf = str(data["object_urdf"]) if "object_urdf" in data else "" finger_names = [str(x) for x in np.atleast_1d(data["finger_joint_names"]).tolist()] root_pose = _pose7_xyzw(data["root_pos"], data["root_wxyz"]) finger_q = np.asarray(data["finger_q"], dtype=np.float64) obj_pose = None if ( not args_cli.no_object and obj_urdf and Path(obj_urdf).is_file() and np.isfinite(data["object_pos"]).any() ): obj_pose = _pose7_xyzw(data["object_pos"], data["object_wxyz"]) mano = None if args_cli.no_mano else np.asarray(data["mano_joints"], dtype=np.float64) table_top = float(args_cli.table_z) drop = float(args_cli.drop_height) if obj_pose is not None: z_shift = table_top + drop - float(obj_pose[0, 2]) obj_pose = obj_pose.copy() obj_pose[:, 2] += z_shift root_pose = root_pose.copy() root_pose[:, 2] += z_shift if mano is not None: mano = mano.copy() mano[:, :, 2] += z_shift xy0 = obj_pose[0, :2].copy() else: z_shift = 0.0 xy0 = root_pose[0, :2].copy() print(f"[v2d] {n} frames @ {fps} fps side={side}", flush=True) print(f"[v2d] table top z={table_top:.3f} m z_shift={z_shift:.3f} m xy=({xy0[0]:.3f}, {xy0[1]:.3f})", flush=True) print(f"[v2d] hand {hand_urdf}", flush=True) if obj_pose is not None: print(f"[v2d] object {obj_urdf}", flush=True) print(f"[v2d] mp4 {out_mp4}", flush=True) sim_dt = 1.0 / 60.0 sim_cfg = sim_utils.SimulationCfg(dt=sim_dt, device=args_cli.device) sim = SimulationContext(sim_cfg) look = np.array([xy0[0], xy0[1], table_top + 0.15], dtype=np.float32) eye = np.array([look[0] + 1.15, look[1] - 1.15, look[2] + 0.75], dtype=np.float32) sim.set_camera_view(eye=eye.tolist(), target=look.tolist()) ground_cfg = sim_utils.GroundPlaneCfg() ground_cfg.func("/World/defaultGroundPlane", ground_cfg) light_cfg = sim_utils.DomeLightCfg(intensity=2500.0, color=(0.8, 0.8, 0.8)) light_cfg.func("/World/Light", light_cfg) _spawn_table(xy0, table_top) do_physics = obj_pose is not None and not args_cli.no_settle hand = Articulation(_hand_cfg(hand_urdf, "/World/G1Inspire")) obj = None if obj_pose is not None: obj = RigidObject(_object_cfg(obj_urdf, "/World/Object", physics=do_physics)) mano_markers = None if mano is not None: mano_markers = VisualizationMarkers( VisualizationMarkersCfg( prim_path="/World/Visuals/mano", markers={ "joint": sim_utils.SphereCfg( radius=0.008, visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.15, 0.85, 0.35)), ), }, ) ) camera = Camera( CameraCfg( prim_path="/World/RecordCamera", update_period=0.0, height=480, width=640, data_types=["rgb"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5), ), ) ) sim.reset() camera.set_world_poses_from_view( torch.tensor(eye, device=sim.device).unsqueeze(0), torch.tensor(look, device=sim.device).unsqueeze(0), ) sim_names = list(hand.joint_names) print(f"[v2d] sim joints ({len(sim_names)}): {sim_names}", flush=True) order = _joint_order(sim_names, finger_names) device = sim.device zeros6 = torch.zeros(1, 6, device=device) def _write_hand(pose7: np.ndarray, t_fingers: int) -> None: rp = torch.tensor(pose7, dtype=torch.float32, device=device).unsqueeze(0) if torch.isfinite(rp).all(): hand.write_root_pose_to_sim_index(root_pose=rp) hand.write_root_velocity_to_sim_index(root_velocity=zeros6) jq = torch.tensor(_finger_row(finger_q, t_fingers, order), dtype=torch.float32, device=device).unsqueeze(0) hand.write_joint_state_to_sim_index(position=jq, velocity=torch.zeros_like(jq)) hand.write_data_to_sim() def _write_obj(pose7: np.ndarray) -> None: if obj is None: return op = torch.tensor(pose7, dtype=torch.float32, device=device).unsqueeze(0) obj.write_root_pose_to_sim_index(root_pose=op) obj.write_root_velocity_to_sim_index(root_velocity=zeros6) obj.write_data_to_sim() def _write_mano_from_world(pts: np.ndarray) -> None: if mano_markers is None: return if np.isfinite(pts).all(): mano_markers.visualize(translations=pts) def _lock_object_xy(pose7: np.ndarray) -> np.ndarray: out = pose7.copy() out[0] = xy0[0] out[1] = xy0[1] return out def _read_obj_pose() -> np.ndarray: return _as_numpy(obj.data.root_link_pose_w).reshape(-1)[:7].astype(np.float64) def _read_obj_vel() -> np.ndarray: return _as_numpy(obj.data.root_link_vel_w).reshape(-1)[:6].astype(np.float64) def _step_sim() -> None: sim.step() hand.update(sim_dt) if obj is not None: obj.update(sim_dt) camera.update(sim_dt) t0_obj = obj_pose[0].copy() if obj_pose is not None else None t0_hand = root_pose[0].copy() t0_mano = mano[0].copy() if mano is not None else None rel_hand = _compose(_inverse(t0_obj), t0_hand) if t0_obj is not None else None frames: list[np.ndarray] = [] capture_every = max(1, int(round((1.0 / max(fps, 1e-3)) / sim_dt))) def _maybe_capture(step_i: int, force: bool = False) -> None: if force or step_i % capture_every == 0: frames.append(_rgb_frame(camera)) # Camera warmup. if obj_pose is not None: _write_obj(obj_pose[0]) _write_hand(root_pose[0], 0) if mano is not None: _write_mano_from_world(mano[0]) for _ in range(4): _step_sim() settled = t0_obj.copy() if t0_obj is not None else None if do_physics: n_settle = max(1, int(round(float(args_cli.settle_sec) / sim_dt))) print(f"[v2d] settle {n_settle} steps ({args_cli.settle_sec:.2f}s), XY locked, Z/rot free", flush=True) _write_obj(_lock_object_xy(obj_pose[0])) for s in range(n_settle): if not simulation_app.is_running(): break _step_sim() pose = _lock_object_xy(_read_obj_pose()) vel = _read_obj_vel() vel[0] = 0.0 vel[1] = 0.0 op = torch.tensor(pose, dtype=torch.float32, device=device).unsqueeze(0) ov = torch.tensor(vel, dtype=torch.float32, device=device).unsqueeze(0) obj.write_root_pose_to_sim_index(root_pose=op) obj.write_root_velocity_to_sim_index(root_velocity=ov) obj.write_data_to_sim() obj.update(0.0) pose = _lock_object_xy(_read_obj_pose()) _write_hand(_compose(pose, rel_hand), 0) if t0_mano is not None: delta = _compose(pose, _inverse(t0_obj)) _write_mano_from_world(_apply_pose_pts(delta, t0_mano)) _maybe_capture(s) if s % 30 == 0: print( f" settle {s}/{n_settle} z={pose[2]:.3f} |v|={np.linalg.norm(vel[:3]):.3f}", flush=True, ) settled = _lock_object_xy(_read_obj_pose()) print( f"[v2d] settled z={settled[2]:.3f} m (video start z={t0_obj[2]:.3f} m)", flush=True, ) delta = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], dtype=np.float64) if settled is not None and t0_obj is not None: delta = _compose(settled, _inverse(t0_obj)) # After settle, drive both bodies kinematically so the clip cannot fight gravity. _write_obj(settled) print(f"[v2d] motion {n} frames", flush=True) for t in range(n): if not simulation_app.is_running(): break if obj_pose is not None: _write_obj(_compose(delta, obj_pose[t])) _write_hand(_compose(delta, root_pose[t]), t) if mano is not None: _write_mano_from_world(_apply_pose_pts(delta, mano[t])) _step_sim() _maybe_capture(t, force=(t == n - 1)) if t % 10 == 0 or t == n - 1: print(f" motion {t + 1}/{n}", flush=True) _write_mp4(out_mp4, frames, fps) print(f"[v2d] wrote {out_mp4} ({len(frames)} frames)", flush=True) if __name__ == "__main__": main() simulation_app.close()