"""Gymnasium environment: drive a MuJoCo ATV over terrain reconstructed from a single TartanDrive 2.0 sequence. Observation/action layout is chosen to match the real dataset's own column conventions (metadata_utils.lidar_terrain's ENU frame, gps_odom's 13-column layout, IMU's angular-velocity+linear-acceleration 6-column layout) so this env's rollouts stay directly comparable to real logs, and so a policy trained here can later be evaluated/fine-tuned against the real `kitti_format` data. """ import os os.environ.setdefault("MUJOCO_GL", "egl") from pathlib import Path import gymnasium as gym import mujoco import numpy as np from gymnasium import spaces from metadata_utils.calibration import load_cam_P, load_extrinsics from metadata_utils.lidar_terrain import build_terrain_for_sequence, load_sequence_poses from sim.mjcf_builder import CAM_NAME, build_mjcf from sim.vehicle_config import get_vehicle_config REPO_ROOT = Path(__file__).resolve().parent.parent DEFAULT_CALIBRATION_DIR = REPO_ROOT / "calibration" class TartanDriveEnv(gym.Env): """One episode = one drive over the reconstructed terrain patch for `scene_dir`.""" metadata = {"render_modes": ["rgb_array"]} def __init__(self, scene_dir, calibration_dir=None, cache_path=None, frame_stride=5, cell_size=0.3, frame_range=None, control_substeps=4, max_episode_steps=1000, max_tilt_rad=1.0, image_width=1024, image_height=544): super().__init__() self.scene_dir = Path(scene_dir) calibration_dir = Path(calibration_dir or DEFAULT_CALIBRATION_DIR) self.extrinsics = load_extrinsics(calibration_dir / "extrinsics.yaml") self.cam_P = load_cam_P(calibration_dir / "multisense_intrinsics.txt") self.vehicle_cfg = get_vehicle_config() self.terrain = build_terrain_for_sequence( self.scene_dir, self.extrinsics, cache_path=cache_path, frame_stride=frame_stride, cell_size=cell_size, frame_range=frame_range) self.poses = load_sequence_poses(self.scene_dir) scene = build_mjcf( self.terrain, self.vehicle_cfg, self.extrinsics, self.cam_P, image_height=image_height, image_width=image_width, spawn_xy=(self.poses.positions[0, 0], self.poses.positions[0, 1]), spawn_quat_xyzw=self.poses.quats_xyzw[0]) self.model = mujoco.MjModel.from_xml_string(scene.xml) self.model.hfield_data[:] = scene.hfield_data_flat self.data = mujoco.MjData(self.model) self.renderer = mujoco.Renderer(self.model, height=image_height, width=image_width) self._chassis_id = self.model.body("chassis").id self._free_qpos_adr = self.model.jnt_qposadr[self.model.joint("chassis_free").id] self._free_dof_adr = self.model.jnt_dofadr[self.model.joint("chassis_free").id] self.control_substeps = control_substeps self.max_episode_steps = max_episode_steps self.max_tilt_rad = max_tilt_rad self._step_count = 0 self.observation_space = spaces.Dict({ "image": spaces.Box(0, 255, (image_height, image_width, 3), dtype=np.uint8), "imu": spaces.Box(-np.inf, np.inf, (6,), dtype=np.float32), "odom": spaces.Box(-np.inf, np.inf, (13,), dtype=np.float32), }) self.action_space = spaces.Box( low=np.array([-1.0, -1.0], dtype=np.float32), high=np.array([1.0, 1.0], dtype=np.float32)) def reset(self, seed=None, options=None): super().reset(seed=seed) mujoco.mj_resetData(self.model, self.data) mujoco.mj_forward(self.model, self.data) self.data.ctrl[:] = 0.0 # settle onto the terrain under gravity before the episode starts, so the # initial spawn-height estimate's contact penetration doesn't resolve into # a violent first-step impulse on real (bumpy) reconstructed terrain for _ in range(150): mujoco.mj_step(self.model, self.data) self._step_count = 0 return self._get_obs(), {} def step(self, action): action = np.clip(np.asarray(action, dtype=np.float64), -1.0, 1.0) throttle, steer = action self.data.ctrl[0:4] = throttle self.data.ctrl[4:6] = steer * self.vehicle_cfg.max_steer_rad for _ in range(self.control_substeps): mujoco.mj_step(self.model, self.data) self._step_count += 1 obs = self._get_obs() terminated = self._check_terminated() truncated = self._step_count >= self.max_episode_steps reward = 0.0 # stubbed; traversability-based reward is Phase 2 scope return obs, reward, terminated, truncated, {} def render(self): self.renderer.update_scene(self.data, camera=CAM_NAME) return self.renderer.render() def close(self): self.renderer.close() # -- internals ------------------------------------------------------------ def _get_obs(self): image = self.render() gyro = self.data.sensor("imu_gyro").data accel = self.data.sensor("imu_accel").data imu = np.concatenate([gyro, accel]).astype(np.float32) pos = self.data.qpos[self._free_qpos_adr:self._free_qpos_adr + 3] quat_wxyz = self.data.qpos[self._free_qpos_adr + 3:self._free_qpos_adr + 7] quat_xyzw = quat_wxyz[[1, 2, 3, 0]] linvel_world = self.data.qvel[self._free_dof_adr:self._free_dof_adr + 3] angvel_body = self.data.qvel[self._free_dof_adr + 3:self._free_dof_adr + 6] # gps_odom convention: col0=northing(+y), col1=-easting(-x), col2=altitude(z) odom = np.concatenate([ [pos[1], -pos[0], pos[2]], quat_xyzw, linvel_world, angvel_body, ]).astype(np.float32) return {"image": image, "imu": imu, "odom": odom} def _check_terminated(self): R = self.data.xmat[self._chassis_id].reshape(3, 3) up_z = R[2, 2] # world-z component of the chassis' local up axis tilt = np.arccos(np.clip(up_z, -1.0, 1.0)) return bool(tilt > self.max_tilt_rad)