#!/usr/bin/env python3 """Play the physical G1 + table + object env and write an MP4. This does **not** load DexYCB, HaWoR, or ``isaaclab_replay.npz``. The scene is procedural Isaac Lab: Nucleus G1 (minimal USD), a cuboid table, a cuboid object. Actions are zeros (or ``--random``) unless you pass a later checkpoint. ./play.sh --headless --steps 300 # MP4: simulation/runs/rl/play/g1_table_object.mp4 """ from __future__ import annotations import argparse import os import sys from pathlib import Path from isaaclab.app import AppLauncher parser = argparse.ArgumentParser(description="Play V2D-G1-TableObject and record MP4.") parser.add_argument("--task", type=str, default="V2D-G1-TableObject-Play-v0") parser.add_argument("--num_envs", type=int, default=1) parser.add_argument("--steps", type=int, default=300) parser.add_argument("--random", action="store_true") parser.add_argument( "--output", type=Path, default=None, help="MP4 path (default: $RUNS_DIR/rl/play/g1_table_object.mp4)", ) parser.add_argument("--fps", type=float, default=30.0) 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 gymnasium as gym # noqa: E402 import numpy as np # noqa: E402 import torch # noqa: E402 from isaaclab_tasks.utils import parse_env_cfg # noqa: E402 import v2d_sim # noqa: E402, F401 def _as_uint8_rgb(img) -> np.ndarray | None: if img is None: return None if hasattr(img, "cpu"): img = img.detach().cpu().numpy() img = np.asarray(img) 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") 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-rl] 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: runs = Path(os.environ.get("RUNS_DIR", Path.cwd() / "runs")) out_mp4 = (args_cli.output or (runs / "rl" / "play" / "g1_table_object.mp4")).resolve() env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=args_cli.num_envs) env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array") env.reset() print("[v2d-rl] play uses procedural Isaac assets (not DexYCB / isaaclab_replay.npz)", flush=True) print(" robot: Unitree G1 (G1_MINIMAL_CFG), gravity on, floating base", flush=True) print(" table: kinematic cuboid object: dynamic cuboid", flush=True) print(f" actions: {'random' if args_cli.random else 'zeros'} steps={args_cli.steps}", flush=True) print(f" mp4 {out_mp4}", flush=True) frames: list[np.ndarray] = [] for i in range(args_cli.steps): if not simulation_app.is_running(): break if args_cli.random: action = torch.as_tensor(env.action_space.sample(), device=env.unwrapped.device) else: action = torch.zeros(env.unwrapped.action_space.shape, device=env.unwrapped.device) _obs, rew, _term, _trunc, _info = env.step(action) rgb = _as_uint8_rgb(env.unwrapped.render()) if rgb is not None: frames.append(rgb) if i % 50 == 0: r = rew.mean().item() if hasattr(rew, "mean") else float(rew) print(f" step {i} reward_mean={r:.3f} frames={len(frames)}", flush=True) _write_mp4(out_mp4, frames, args_cli.fps) print(f"[v2d-rl] wrote {out_mp4} ({len(frames)} frames)", flush=True) env.close() if __name__ == "__main__": try: main() finally: simulation_app.close() sys.exit(0)