from pathlib import Path import os import sys import threading import gymnasium as gym from gymnasium import spaces import numpy as np from huggingface_hub import snapshot_download import yaml # LeRobot initially fetches only env.py. Hydrate its matching Hub snapshot; # a complete local checkout can also be used without another network request. _repo_dir = Path(__file__).parent _UPSTREAM_REPO_ID = "lerobot/unitree-g1-mujoco" _SNAPSHOT_SENTINELS = ("sim/simulator_factory.py", "assets/meshes/pelvis.STL") def _hub_repo_id_from_cache(repo_dir: Path) -> tuple[str, str | None]: """Recover (repo_id, revision) from a Hub cache path `.../models--owner--name/snapshots//`. Falls back to the upstream repo id (and no revision) when `repo_dir` is not a Hub snapshot, so forks under another namespace hydrate their own files instead of upstream's. """ if repo_dir.parent.name != "snapshots": return _UPSTREAM_REPO_ID, None cache_name = repo_dir.parent.parent.name if cache_name.startswith("models--"): return cache_name.removeprefix("models--").replace("--", "/"), repo_dir.name return _UPSTREAM_REPO_ID, repo_dir.name def _needs_hydration(repo_dir: Path) -> bool: """True unless the full snapshot is present. The sentinels match none of the XR teleop's partial-download patterns (`sim/mjcf/*.py`, `assets/*.xml`), so that partial snapshot, which already has `assets/scene.xml`, is hydrated too. """ return not all((repo_dir / name).is_file() for name in _SNAPSHOT_SENTINELS) def _parse_env_option(value: str): """Turn an environment-variable string into bool/int/list/str for `option()`.""" lowered = value.strip().lower() if lowered in ("1", "true", "yes", "on"): return True if lowered in ("0", "false", "no", "off"): return False if lowered.isdigit(): return int(lowered) if "," in value: return [item.strip() for item in value.split(",") if item.strip()] return value.strip() if _needs_hydration(_repo_dir): _repo_id, _revision = _hub_repo_id_from_cache(_repo_dir) snapshot_download(_repo_id, revision=_revision) # Ensure sim module is importable sys.path.insert(0, str(Path(__file__).parent)) from sim.simulator_factory import SimulatorFactory, init_channel from sim.model_config import select_end_effector from sim.head_hand_sim import SimHeadHandDevice def make_env(n_envs=1, use_async_envs=False, **kwargs): """Create a UnitreeG1 simulation environment. Args: n_envs: Number of environments (currently only 1 supported) use_async_envs: Whether to use async envs (not implemented) cfg: LeRobot's UnitreeG1MujocoEnv config, when called through lerobot.envs.make_env. Any of the options below that it carries are read off it; keywords win. **kwargs: Additional arguments passed to simulator - publish_images: bool, whether to publish camera images via ZMQ - camera_port: int, ZMQ port for camera images - cameras: list of camera names - body: "29dof" or "23dof" (rev_1_0 hardware) - end_effector: "rubber_hand" (stock passive hand), "none" (bare wrist), "dex1" grippers, "dex3" hands or "amazing_hand"; any fits either body - head_mount: "fixed" (stock head) or "pan_tilt" - head_sensor: "d435i" (stock camera) or "d455" - world: "" (plain floor), a world name from the worlds repo (e.g. "pick_cylinder"), a folder or world.xml path, or "owner/repo[@rev]:name" - world_grasp: "physics" (default; finger contacts only) or "attach" (an AmazingHand that closes on the world's object welds it kinematically); only meaningful with a world - world_randomize: metres of uniform xy jitter (and +-world_randomize_yaw) of the world's free objects at start and on every reset; 0 keeps them at their spawn pose; unset uses config.yaml's WORLD_RANDOMIZE, else the world's world.yaml `randomize`, else 0 - world_randomize_yaw: deg of uniform yaw jitter about the world z axis while world_randomize > 0 (default config.yaml's WORLD_RANDOMIZE_YAW, 15); 180 gives any heading - onscreen: bool, override the interactive viewer setting """ repo_dir = Path(__file__).parent cfg = kwargs.get("cfg") def option(name, default=None): """An option as given by keyword, else by cfg, else by environment, else the default. None means "not set", so a cfg field can leave the choice to config.yaml. The environment variable is ``UNITREE_G1_MUJOCO_`` (e.g. ``UNITREE_G1_MUJOCO_ONSCREEN=0``), which is the only override reachable when LeRobot loads this env through ``make_env(repo_id)``. """ for value in (kwargs.get(name), getattr(cfg, name, None)): if value is not None: return value env_value = os.environ.get(f"UNITREE_G1_MUJOCO_{name.upper()}") if env_value is not None: return _parse_env_option(env_value) return default # Load config config_path = repo_dir / "config.yaml" with open(config_path) as f: config = yaml.safe_load(f) for key in ("JOYSTICK_TYPE", "JOYSTICK_DEVICE", "HEADHAND_STATE_PORT", "HEADHAND_CMD_PORT"): env_value = os.environ.get(f"UNITREE_G1_MUJOCO_{key}") if env_value is not None: config[key] = _parse_env_option(env_value) config = select_end_effector( config, option("end_effector"), option("body"), option("head_mount"), option("head_sensor"), option("world"), option("world_grasp"), ) config["WORLD_RANDOMIZE"] = float(option("world_randomize", config["WORLD_RANDOMIZE"]) or 0.0) config["WORLD_RANDOMIZE_YAW"] = float(option("world_randomize_yaw", config.get("WORLD_RANDOMIZE_YAW", 15.0))) # Configure cameras if requested publish_images = option("publish_images", True) camera_port = option("camera_port", 5555) cameras = option("cameras") if cameras is None: cameras = config["CAMERAS"] enable_offscreen = publish_images or config.get("ENABLE_OFFSCREEN", False) camera_configs = {} if enable_offscreen: for cam_name in cameras: camera_configs[cam_name] = {"height": 480, "width": 640} # Initialize DDS channel init_channel(config=config) # Create simulator (runs in same process) simulator = SimulatorFactory.create_simulator( config=config, env_name="default", onscreen=option("onscreen", config.get("ENABLE_ONSCREEN", True)), offscreen=enable_offscreen, camera_configs=camera_configs, ) headhand_server = None headhand_shutdown = None headhand_thread = None if config["HEAD_MOUNT"] != "fixed" or config["END_EFFECTOR"] == "amazing_hand": from lerobot.robots.unitree_g1.headhand_zmq import HeadHandServer device = SimHeadHandDevice(simulator.sim_env.mj_model, simulator.sim_env.mj_data) device.connect() headhand_server = HeadHandServer( device, state_port=option("headhand_state_port", config.get("HEADHAND_STATE_PORT", 6003)), cmd_port=option("headhand_cmd_port", config.get("HEADHAND_CMD_PORT", 6002)), bind_address="127.0.0.1", ) headhand_shutdown = threading.Event() headhand_thread = threading.Thread( target=headhand_server.run, args=(headhand_shutdown,), daemon=True ) headhand_thread.start() class UnitreeG1Env(gym.Env): """Gymnasium environment wrapper for Unitree G1 MuJoCo simulation.""" metadata = {"render_modes": ["human"]} def __init__(self, sim, cam_configs, pub_images, cam_port): super().__init__() self.simulator = sim self.sim_env = sim.sim_env self.step_count = 0 self.camera_configs = cam_configs self.camera_names = tuple(cam_configs) self.camera_port = cam_port self.end_effector = config["END_EFFECTOR"] self.metadata = {"render_modes": ["human"], "cameras": self.camera_names} self.headhand_server = headhand_server self.headhand_shutdown = headhand_shutdown self.headhand_thread = headhand_thread # Get timing from config self.sim_dt = config["SIMULATE_DT"] self.viewer_dt = config.get("VIEWER_DT", 0.02) self.image_dt = config.get("IMAGE_DT", 0.033333) # Start image publishing subprocess if requested if pub_images and len(cam_configs) > 0: sim.start_image_publish_subprocess( start_method=config.get("MP_START_METHOD", "spawn"), camera_port=cam_port ) print(f"Camera images publishing on tcp://localhost:{cam_port}: {', '.join(self.camera_names)}") # Define spaces num_joints = config.get("NUM_MOTORS", 29) self.action_space = spaces.Box(-np.pi, np.pi, shape=(num_joints,), dtype=np.float32) self.observation_space = spaces.Box(-np.inf, np.inf, shape=(num_joints * 3 + 10,), dtype=np.float32) def reset(self, seed=None, options=None): """Reset the simulation.""" super().reset(seed=seed, options=options) self.simulator.reset() self.step_count = 0 obs = self._get_obs() return obs, {} def step(self, action=None): """Execute one simulation step. Caller handles timing.""" # Run physics step self.sim_env.sim_step() # Update viewer at viewer rate if self.step_count % int(self.viewer_dt / self.sim_dt) == 0: self.sim_env.update_viewer() # Update render caches at image rate (for ZMQ publishing) if self.step_count % int(self.image_dt / self.sim_dt) == 0: self.sim_env.update_render_caches() self.step_count += 1 obs = self._get_obs() reward = 0.0 terminated = False truncated = False info = {} return obs, reward, terminated, truncated, info def _get_obs(self): """Get current observation from simulation.""" obs_dict = self.sim_env.prepare_obs() obs = np.concatenate([ obs_dict.get("body_q", np.zeros(29)), obs_dict.get("body_dq", np.zeros(29)), obs_dict.get("body_tau_est", np.zeros(29)), obs_dict.get("floating_base_pose", np.zeros(7))[:4], obs_dict.get("floating_base_vel", np.zeros(6))[:3], obs_dict.get("floating_base_acc", np.zeros(3))[:3], ]).astype(np.float32) return obs def close(self): """Close the simulation.""" print("++++closing simulator ++++") if self.headhand_shutdown is not None: self.headhand_shutdown.set() if self.headhand_server is not None: self.headhand_server.stop() if self.headhand_thread is not None: self.headhand_thread.join(timeout=2.0) self.simulator.close() return UnitreeG1Env(simulator, camera_configs, publish_images, camera_port)