File size: 19,559 Bytes
3f4bb1d | 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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 | #!/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/<seq>/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: <npz-dir>/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()
|