diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a0e750458bfab5ad0d18bbfc0ff1182569835c0a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/__init__.py @@ -0,0 +1 @@ +from .g1_robot import * diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/g1_robot.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/g1_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..a4b59e07022face62c792f78571178134ce127aa --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/robots/manipulators/g1_robot.py @@ -0,0 +1,391 @@ +import numpy as np +from robosuite.models.robots.manipulators.legged_manipulator_model import ( + LeggedManipulatorModel, +) +from robosuite.robots import register_robot_class +from robosuite.utils.mjcf_utils import find_elements, xml_path_completion + +import robocasa.models + + +@register_robot_class("LeggedRobot") +class G1(LeggedManipulatorModel): + """ + G1 is a mobile manipulator robot created by Unitree. + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right", "left"] + + def __init__(self, idn: int = 0): + super().__init__( + xml_path_completion( + "robots/unitree_g1/g1_29dof_rev_1_0.xml", + root=robocasa.models.assets_root, + ), + idn=idn, + ) + + def _print_joint_info(self): + """Print formatted information about joints""" + # ANSI color codes + BLUE = "\033[94m" + GREEN = "\033[92m" + RED = "\033[91m" + ENDC = "\033[0m" + BOLD = "\033[1m" + + print(f"\n{BOLD}{BLUE}================ joints info ================{ENDC}") + + # Print joints by category + categories = { + "Arms": self._arms_joints, + "Base": self._base_joints, + "Torso": self._torso_joints, + "Head": self._head_joints, + "Legs": self._legs_joints, + } + + for category, joints in categories.items(): + if joints: + print(f"{GREEN}{category} ({len(joints)}){ENDC}: {', '.join(joints)}") + else: + print(f"{RED}{category} (disabled){ENDC}") + print() + + def _print_actuator_info(self): + """Print formatted information about actuators""" + # ANSI color codes + BLUE = "\033[94m" + GREEN = "\033[92m" + RED = "\033[91m" + ENDC = "\033[0m" + BOLD = "\033[1m" + + print(f"\n{BOLD}{BLUE}================ actuators info ================{ENDC}") + + # Print actuators by category + categories = { + "Arms": self._arms_actuators, + "Base": self._base_actuators, + "Torso": self._torso_actuators, + "Head": self._head_actuators, + "Legs": self._legs_actuators, + } + + for category, actuators in categories.items(): + if actuators: + print(f"{GREEN}{category} ({len(actuators)}){ENDC}: {', '.join(actuators)}") + else: + print(f"{RED}{category} (disabled){ENDC}") + print() + + def update_joints(self): + """internal function to update joint lists""" + for joint in self.all_joints: + if "waist" in joint: + self.torso_joints.append(joint) + elif "base" in joint: + self.base_joints.append(joint) + elif "knee" in joint or "hip" in joint or "ankle" in joint: + self.legs_joints.append(joint) + + for joint in self.all_joints: + if ( + joint not in self._base_joints + and joint not in self._torso_joints + and joint not in self._head_joints + and joint not in self._legs_joints + ): + self._arms_joints.append(joint) + + # adjust the order of the joints, make sure the right arm joints are before the left arm joints + self._arms_joints = [joint for joint in self._arms_joints if "right" in joint] + [ + joint for joint in self._arms_joints if "left" in joint + ] + + # self._print_joint_info() + + def update_actuators(self): + """internal function to update actuator lists""" + for actuator in self.all_actuators: + if "waist" in actuator: + self.torso_actuators.append(actuator) + elif "base" in actuator: + self.base_actuators.append(actuator) + elif "knee" in actuator or "hip" in actuator or "ankle" in actuator: + self.legs_actuators.append(actuator) + + for actuator in self.all_actuators: + if ( + actuator not in self._base_actuators + and actuator not in self._torso_actuators + and actuator not in self._head_actuators + and actuator not in self._legs_actuators + ): + self._arms_actuators.append(actuator) + + # adjust the order of the actuators, make sure the right arm actuators are before the left arm actuators + self._arms_actuators = [ + actuator for actuator in self._arms_actuators if "right" in actuator + ] + [actuator for actuator in self._arms_actuators if "left" in actuator] + # self._print_actuator_info() + + @property + def default_base(self): + return "NullBase" + # return "NoActuationBase" + + @property + def default_gripper(self): + # return {"right": None, "left": None} + return {"right": "G1ThreeFingerRightHand", "left": "G1ThreeFingerLeftHand"} + + @property + def init_qpos(self): + DEFAULT_DOF_ANGLES = { + "left_hip_pitch_joint": -0.1, + "left_hip_roll_joint": 0.0, + "left_hip_yaw_joint": 0.0, + "left_knee_joint": 0.3, + "left_ankle_pitch_joint": -0.2, + "left_ankle_roll_joint": 0.0, + "right_hip_pitch_joint": -0.1, + "right_hip_roll_joint": 0.0, + "right_hip_yaw_joint": 0.0, + "right_knee_joint": 0.3, + "right_ankle_pitch_joint": -0.2, + "right_ankle_roll_joint": 0.0, + "waist_yaw_joint": 0.0, + "waist_roll_joint": 0.0, + "waist_pitch_joint": 0.0, + "left_shoulder_pitch_joint": 0.0, + "left_shoulder_roll_joint": 0.0, # 0.3, + "left_shoulder_yaw_joint": 0.0, + "left_elbow_joint": 0.0, # 1.0, + "left_wrist_roll_joint": 0.0, + "left_wrist_pitch_joint": 0.0, + "left_wrist_yaw_joint": 0.0, + "right_shoulder_pitch_joint": 0.0, + "right_shoulder_roll_joint": 0.0, # -0.3, + "right_shoulder_yaw_joint": 0.0, + "right_elbow_joint": 0.0, # 1.0, + "right_wrist_roll_joint": 0.0, + "right_wrist_pitch_joint": 0.0, + "right_wrist_yaw_joint": 0.0, + } + + joints = self.worldbody.findall(".//joint") + joints = [joint for joint in joints if joint.get("name").startswith("robot")] + init_qpos = np.array([0.0] * len(joints)) + for joint_id, joint in enumerate(joints): + init_qpos[joint_id] = DEFAULT_DOF_ANGLES[ + joint.get("name")[joint.get("name").find("_") + 1 :] + ] + return init_qpos + + @property + def base_xpos_offset(self): + return { + "bins": (-0.30, -0.1, 0.95), + "empty": (-0.29, 0, 0.95), + "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.95), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "bimanual" + + @property + def _eef_name(self): + return {"right": "right_eef", "left": "left_eef"} + + @property + def torso_body(self): + return ["torso_link"] + + def get_camera_configs(self): + _cam_config = {} + + # egoview camera + egoview_mount_body = find_elements( + root=self.root, + tags="body", + attribs={"name": f"{self.naming_prefix}torso_link"}, + ) + if egoview_mount_body is not None: + # realsense D435i, 1920 * 1080, 69° × 42° + _cam_config[f"{self.naming_prefix}rs_egoview"] = dict( + pos=[0.07555294, 0.02579919, 0.49719054], + # quat=[0.69263989, 0.16169103, -0.19008497, -0.67673754], + quat=[0.67876761, 0.20864099, -0.20567003, -0.67338199], + camera_attribs=dict(fovy="40"), + parent_body=f"{self.naming_prefix}torso_link", + ) + + # OAK-D W, OV9782, 640*480 + _cam_config[f"{self.naming_prefix}oak_egoview"] = dict( + pos=[0.10209156, -0.00937542, 0.42446595], + quat=[0.64367383, 0.26523914, -0.27106013, -0.66472446], + camera_attribs=dict(fovy="79.5"), + parent_body=f"{self.naming_prefix}torso_link", + ) + + _cam_config[f"{self.naming_prefix}oak_left_monoview"] = dict( + pos=[0.10209156, 0.02857542, 0.42446595], + quat=[0.64367383, 0.26523914, -0.27106013, -0.66472446], + camera_attribs=dict(fovy="79.5"), + parent_body=f"{self.naming_prefix}torso_link", + ) + + _cam_config[f"{self.naming_prefix}oak_right_monoview"] = dict( + pos=[0.10209156, -0.04657542, 0.42446595], + quat=[0.64367383, 0.26523914, -0.27106013, -0.66472446], + camera_attribs=dict(fovy="79.5"), + parent_body=f"{self.naming_prefix}torso_link", + ) + + # tppview camera + tpp_mount_body = find_elements( + root=self.root, + tags="body", + attribs={"name": f"{self.naming_prefix}pelvis"}, + ) + if tpp_mount_body is not None: + _cam_config[f"{self.naming_prefix}rs_tppview"] = dict( + pos=[-1.131, -0.626, 1.247 - 0.793], + quat=[0.67953146, 0.46872971, -0.3204774, -0.46456828], + camera_attribs=dict(fovy="60"), + parent_body=f"{self.naming_prefix}pelvis", + ) + + return _cam_config + + def _disable_collisions(self, body_parts): + """ + Disable collision detection for specified body parts by setting + contype="0" and conaffinity="0" for all collision geometries in those parts. + + Args: + body_parts (list): List of strings identifying body parts to disable collisions for. + Examples: ["hip", "knee", "ankle"], ["waist"], ["shoulder"], etc. + """ + # Find all body elements in the worldbody + for body in self.worldbody.findall(".//body"): + body_name = body.get("name", "") + # Check if this body belongs to specified body parts + if any(part in body_name for part in body_parts): + # Find all geom elements in this body + for geom in body.findall(".//geom"): + # Check if this is a collision geom (doesn't have contype="0" and conaffinity="0") + contype = geom.get("contype") + conaffinity = geom.get("conaffinity") + + # If contype and conaffinity are not already "0", set them to disable collision + if contype != "0" or conaffinity != "0": + geom.set("contype", "0") + geom.set("conaffinity", "0") + + +@register_robot_class("LeggedRobot") +class G1FixedBase(G1): + def __init__(self, idn: int = 0): + super().__init__(idn=idn) + + # Remove base actuation + self._remove_free_joint() + + +@register_robot_class("LeggedRobot") +class G1FixedLowerBody(G1): + def __init__(self, idn: int = 0): + super().__init__(idn=idn) + + # Remove lower body actuation + self._remove_joint_actuation("knee") + self._remove_joint_actuation("hip") + self._remove_joint_actuation("ankle") + + self._remove_free_joint() + + +@register_robot_class("LeggedRobot") +class G1ArmsOnly(G1): + def __init__(self, idn: int = 0): + super().__init__(idn=idn) + + # Remove lower body actuation + self._remove_joint_actuation("knee") + self._remove_joint_actuation("hip") + self._remove_joint_actuation("ankle") + + # Remove spine & head actuation + self._remove_joint_actuation("waist") + + self._remove_free_joint() + + +@register_robot_class("LeggedRobot") +class G1ArmsOnlyFloating(G1): + def __init__(self, idn: int = 0): + super().__init__(idn=idn) + + # Remove lower body actuation + self._remove_joint_actuation("knee") + self._remove_joint_actuation("hip") + self._remove_joint_actuation("ankle") + + # Remove spine & head actuation + self._remove_joint_actuation("waist") + + self._remove_free_joint() + + @property + def default_base(self): + return "FloatingLeggedBase" + + @property + def base_xpos_offset(self): + return { + "bins": (-0.30, -0.1, 0.97), + "empty": (-0.29, 0, 0.97), + "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.97), + } + + +@register_robot_class("LeggedRobot") +class G1FloatingBody(G1): + def __init__(self, idn: int = 0): + super().__init__(idn=idn) + + # Remove lower body actuation + self._remove_joint_actuation("knee") + self._remove_joint_actuation("hip") + self._remove_joint_actuation("ankle") + + # Disable collision detection for lower body parts + self._disable_collisions(["hip", "knee", "ankle"]) + + self._remove_free_joint() + + @property + def default_base(self): + return "FloatingLeggedBase" + + @property + def base_xpos_offset(self): + return { + "bins": (-0.30, -0.1, 0.97), + "empty": (-0.29, 0, 0.97), + "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.97), + } diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2a22ff2bd9e5472155f3253cc17449c8e02f09d6 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/__init__.py @@ -0,0 +1,3 @@ +from .ground_arena import GroundArena +from .lab_arena import LabArena +from .factory_arena import FactoryArena diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/factory_arena.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/factory_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..056ab42a13eb9bb5605d12b4ea8547989fd7740e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/factory_arena.py @@ -0,0 +1,14 @@ +from robosuite.models.arenas import Arena +from robosuite.utils.mjcf_utils import xml_path_completion +import robocasa + + +class FactoryArena(Arena): + """Factory workspace.""" + + def __init__(self): + super().__init__( + xml_path_completion( + "arenas/gear_factory/gear_factory.xml", root=robocasa.models.assets_root + ) + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/ground_arena.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/ground_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..cf94b8a331909422a4fd45af8978720509e9e688 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/ground_arena.py @@ -0,0 +1,13 @@ +from robosuite.models.arenas import Arena +from robosuite.utils.mjcf_utils import xml_path_completion + +import robocasa + + +class GroundArena(Arena): + """Empty workspace.""" + + def __init__(self): + super().__init__( + xml_path_completion("arenas/ground_arena.xml", root=robocasa.models.assets_root) + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/lab_arena.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/lab_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..84ca87e34e3732e1f9050f3552ba38900ff44eb0 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/models/scenes/lab_arena.py @@ -0,0 +1,12 @@ +from robosuite.models.arenas import Arena +from robosuite.utils.mjcf_utils import xml_path_completion +import robocasa + + +class LabArena(Arena): + """Lab workspace.""" + + def __init__(self): + super().__init__( + xml_path_completion("arenas/gear_lab/gear_lab.xml", root=robocasa.models.assets_root) + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd4d6a4f9e82ded5ad6bbec5664058b450a5f55a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/__init__.py @@ -0,0 +1 @@ +from robosuite.utils import * diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/camera_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/camera_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..537e7c65de63ebf149ca5337d4b3fc4f58376184 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/camera_utils.py @@ -0,0 +1,246 @@ +""" +Collection of constants for cameras / robots / etc +in kitchen environments +""" + +import numpy as np +import matplotlib.pyplot as plt + + +# https://github.com/yusukeurakami/mujoco_2d_projection +def global2label(obj_pos, cam_pos, cam_ori, output_size=[64, 64], fov=90, s=1): + """ + :param obj_pos: 3D coordinates of the joint from MuJoCo in nparray [m] + :param cam_pos: 3D coordinates of the camera from MuJoCo in nparray [m] + :param cam_ori: camera 3D rotation (Rotation order of x->y->z) from MuJoCo in nparray [rad] + :param fov: field of view in integer [degree] + :return: Heatmap of the object in the 2D pixel space. + """ + + e = np.array([output_size[0] / 2, output_size[1] / 2, 1]) + fov = np.array([fov]) + + # Converting the MuJoCo coordinate into typical computer vision coordinate. + cam_ori_cv = np.array([cam_ori[1], cam_ori[0], -cam_ori[2]]) + obj_pos_cv = np.array([obj_pos[1], obj_pos[0], -obj_pos[2]]) + cam_pos_cv = np.array([cam_pos[1], cam_pos[0], -cam_pos[2]]) + + obj_pos_in_2D, obj_pos_from_cam = get_2D_from_3D(obj_pos_cv, cam_pos_cv, cam_ori_cv, fov, e) + label = gkern( + output_size[0], + output_size[1], + (obj_pos_in_2D[1], output_size[0] - obj_pos_in_2D[0]), + sigma=s, + ) + return label + + +def get_2D_from_3D(a, c, theta, fov, e): + """ + :param a: 3D coordinates of the joint in nparray [m] + :param c: 3D coordinates of the camera in nparray [m] + :param theta: camera 3D rotation (Rotation order of x->y->z) in nparray [rad] + :param fov: field of view in integer [degree] + :param e: + :return: + - (bx, by) ==> 2D coordinates of the obj [pixel] + - d ==> 3D coordinates of the joint (relative to the camera) [m] + """ + + # Get the vector from camera to object in global coordinate. + ac_diff = a - c + + # Rotate the vector in to camera coordinate + x_rot = np.array( + [ + [1, 0, 0], + [0, np.cos(theta[0]), np.sin(theta[0])], + [0, -np.sin(theta[0]), np.cos(theta[0])], + ] + ) + + y_rot = np.array( + [ + [np.cos(theta[1]), 0, -np.sin(theta[1])], + [0, 1, 0], + [np.sin(theta[1]), 0, np.cos(theta[1])], + ] + ) + + z_rot = np.array( + [ + [np.cos(theta[2]), np.sin(theta[2]), 0], + [-np.sin(theta[2]), np.cos(theta[2]), 0], + [0, 0, 1], + ] + ) + + transform = z_rot.dot(y_rot.dot(x_rot)) + d = transform.dot(ac_diff) + + # scaling of projection plane using fov + fov_rad = np.deg2rad(fov) + e[2] *= e[0] * 1 / np.tan(fov_rad / 2.0) + + # Projection from d to 2D + bx = e[2] * d[0] / (d[2]) + e[0] + by = e[2] * d[1] / (d[2]) + e[1] + + return (bx, by), d + + +def gkern(h, w, center, sigma=1): + x = np.arange(0, w, 1, float) + y = np.arange(0, h, 1, float) + y = y[:, np.newaxis] + x0 = center[0] + y0 = center[1] + return np.exp(-1 * ((x - x0) ** 2 + (y - y0) ** 2) / sigma**2) + + +def compute_2d_projection( + obj_pos=np.array([0.2, 0.25, 1.0]), + cam_pos=np.array([0.7, 0, 1.5]), + cam_ori=np.array([0.2, 1.2, 1.57]), + fov=90, + output_size=[64, 64], +): + e = np.array([output_size[0] / 2, output_size[1] / 2, 1]) + fov = np.array([fov]) + + # Converting the MuJoCo coordinate into typical computer vision coordinate. + cam_ori_cv = np.array([cam_ori[1], cam_ori[0], -cam_ori[2]]) + obj_pos_cv = np.array([obj_pos[1], obj_pos[0], -obj_pos[2]]) + cam_pos_cv = np.array([cam_pos[1], cam_pos[0], -cam_pos[2]]) + + obj_pos_in_2D, obj_pos_from_cam = get_2D_from_3D(obj_pos_cv, cam_pos_cv, cam_ori_cv, fov, e) + + return obj_pos_in_2D[1], output_size[0] - obj_pos_in_2D[0] + + +def global2label(obj_pos, cam_pos, cam_ori, output_size=[64, 64], fov=90, s=1): + """ + :param obj_pos: 3D coordinates of the joint from MuJoCo in nparray [m] + :param cam_pos: 3D coordinates of the camera from MuJoCo in nparray [m] + :param cam_ori: camera 3D rotation (Rotation order of x->y->z) from MuJoCo in nparray [rad] + :param fov: field of view in integer [degree] + :return: Heatmap of the object in the 2D pixel space. + """ + + e = np.array([output_size[0] / 2, output_size[1] / 2, 1]) + fov = np.array([fov]) + + # Converting the MuJoCo coordinate into typical computer vision coordinate. + cam_ori_cv = np.array([cam_ori[1], cam_ori[0], -cam_ori[2]]) + obj_pos_cv = np.array([obj_pos[1], obj_pos[0], -obj_pos[2]]) + cam_pos_cv = np.array([cam_pos[1], cam_pos[0], -cam_pos[2]]) + + obj_pos_in_2D, obj_pos_from_cam = get_2D_from_3D(obj_pos_cv, cam_pos_cv, cam_ori_cv, fov, e) + label = gkern( + output_size[0], + output_size[1], + (obj_pos_in_2D[1], output_size[0] - obj_pos_in_2D[0]), + sigma=s, + ) + return label + + +def visualize_2d_projection( + obj_pos=np.array([0.2, 0.25, 1.0]), + cam_pos=np.array([0.7, 0, 1.5]), + cam_ori=np.array([0.2, 1.2, 1.57]), + fov=90, + output_size=[64, 64], +): + s = 1 # std for heapmap signal + label = global2label(obj_pos, cam_pos, cam_ori, output_size, fov=fov, s=s) + plt.imshow(label) + plt.show() + + +# default free cameras for different kitchen layouts +LAYOUT_CAMS = { + 0: dict( + lookat=[2.26593463, -1.00037131, 1.38769295], + distance=3.0505089839567323, + azimuth=90.71563812375285, + elevation=-12.63948837207208, + ), + 1: dict( + lookat=[2.66147999, -1.00162429, 1.2425155], + distance=3.7958766287746255, + azimuth=89.75784013699234, + elevation=-15.177406642875091, + ), + 2: dict( + lookat=[3.02344359, -1.48874618, 1.2412914], + distance=3.6684844368165512, + azimuth=51.67880851867874, + elevation=-13.302619131542388, + ), + # 3: dict( + # lookat=[11.44842548, -11.47664723, 11.24115989], + # distance=43.923271794728187, + # azimuth=227.12928449329333, + # elevation=-16.495686334624907, + # ), + 4: dict( + lookat=[1.6, -1.0, 1.0], + distance=5, + azimuth=89.70301806083651, + elevation=-18.02177994296577, + ), +} + +DEFAULT_LAYOUT_CAM = { + "lookat": [2.25, -1, 1.05312667], + "distance": 5, + "azimuth": 89.70301806083651, + "elevation": -18.02177994296577, +} + +CAM_CONFIGS = dict( + robot0_agentview_center=dict( + pos=[-0.6, 0.0, 1.15], + quat=[ + 0.636945903301239, + 0.3325185477733612, + -0.3199238181114197, + -0.6175596117973328, + ], + parent_body="mobilebase0_support", + ), + robot0_agentview_left=dict( + pos=[-0.5, 0.35, 1.05], + quat=[0.55623853, 0.29935253, -0.37678665, -0.6775092], + camera_attribs=dict(fovy="60"), + parent_body="mobilebase0_support", + ), + robot0_agentview_right=dict( + pos=[-0.5, -0.35, 1.05], + quat=[ + 0.6775091886520386, + 0.3767866790294647, + -0.2993525564670563, + -0.55623859167099, + ], + camera_attribs=dict(fovy="60"), + parent_body="mobilebase0_support", + ), + robot0_frontview=dict( + pos=[-0.50, 0, 0.95], + quat=[ + 0.6088936924934387, + 0.3814677894115448, + -0.3673907518386841, + -0.5905545353889465, + ], + camera_attribs=dict(fovy="60"), + parent_body="mobilebase0_support", + ), + robot0_eye_in_hand=dict( + pos=[0.05, 0, 0], + quat=[0, 0.707107, 0.707107, 0], + parent_body="robot0_right_hand", + ), +) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/config_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb5faf04fbc0f37967b7c99b124f5c80307cb1b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/config_utils.py @@ -0,0 +1,63 @@ +import copy +import os +import pathlib +import robosuite +from robosuite.controllers import load_composite_controller_config + + +def is_stale_controller_config(config: dict): + """ + Checks if a controller config is in the format from robosuite versions <= 1.4.1. + Does not check for config validity, only the format type. + Args: + config (dict): Controller configuration + Returns: + bool: True if the config is in the old format, False otherwise + """ + + OLD_CONTROLLER_TYPES = [ + "JOINT_VELOCITY", + "JOINT_TORQUE", + "JOINT_POSITION", + "OSC_POSITION", + "OSC_POSE", + "IK_POSE", + ] + if ( + "body_parts" not in config or "body_parts_controller_configs" not in config + ) and "type" in config: + return config["type"] in OLD_CONTROLLER_TYPES + return False + + +def refactor_composite_controller_config(controller_config, robot_type, arms): + """ + Checks if a controller config is in the format from robosuite versions <= 1.4.1. + If this is the case, converts the controller config to the new composite controller + config format in robosuite versions >= 1.5. If the robot has a default + controller config use that and override the arms with the old controller config. + If not just use the old controller config for arms. + Args: + old_controller_config (dict): Old controller config + Returns: + dict: New controller config + """ + if not is_stale_controller_config(controller_config): + return controller_config + + config_dir = pathlib.Path(robosuite.__file__).parent / "controllers/config/robots/" + name = robot_type.lower() + configs = os.listdir(config_dir) + if f"default_{name}.json" in configs: + new_controller_config = load_composite_controller_config(robot=name) + else: + new_controller_config = {} + new_controller_config["type"] = "BASIC" + new_controller_config["body_parts"] = {} + + for arm in arms: + new_arm_config = copy.deepcopy(controller_config) + if "gripper" not in new_arm_config: + new_arm_config["gripper"] = {"type": "GRIP"} + new_controller_config["body_parts"][arm] = new_arm_config + return new_controller_config diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/cotrain_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/cotrain_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bd07dfa3a128803cb131b0cea35f59e45b78f391 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/cotrain_utils.py @@ -0,0 +1,25 @@ +""" +Utility functions and constants for co-training with real robot. +""" + +from robosuite.models.robots.manipulators.gr1_robot import GR1 + +# Initial pose configuration for co-training with real robot +COTRAIN_REAL_MATCHED_ROBOT_INITIAL_POSE = { + GR1: { + "robot0_r_shoulder_pitch": -0.22963779, + "robot0_r_shoulder_roll": -0.38363408, + "robot0_r_shoulder_yaw": 0.14360377, + "robot0_r_elbow_pitch": -1.5289252, + "robot0_r_wrist_yaw": -0.2897802, + "robot0_r_wrist_roll": -0.07134621, + "robot0_r_wrist_pitch": -0.04550289, + "robot0_l_shoulder_pitch": -0.10933163, + "robot0_l_shoulder_roll": 0.43292055, + "robot0_l_shoulder_yaw": -0.15983289, + "robot0_l_elbow_pitch": -1.48233023, + "robot0_l_wrist_yaw": 0.2359135, + "robot0_l_wrist_roll": 0.26184522, + "robot0_l_wrist_pitch": 0.00830735, + } +} diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dataset_registry.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dataset_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..fededf1d4c937f4fa54fc746ba38f6365b5219d1 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dataset_registry.py @@ -0,0 +1,352 @@ +import os +from collections import OrderedDict +from copy import deepcopy +from pathlib import Path + +import robocasa +import robocasa.macros as macros + +SINGLE_STAGE_TASK_DATASETS = OrderedDict( + PnPCounterToCab=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_pnp/PnPCounterToCab/2024-04-24", + mg_path="v0.1/single_stage/kitchen_pnp/PnPCounterToCab/mg/2024-05-04-22-12-27_and_2024-05-07-07-39-33", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/c0a0vdyqeqh6o9z4c57sk61aypladizj.hdf5", + human_im="https://utexas.box.com/shared/static/gznii250ip99731ii2r0ml6be7gzt2cp.hdf5", + mg_im="https://utexas.box.com/shared/static/7y9csrcx6uhhq4p3yctmm2df3rjqpw6g.hdf5", + ), + ), + PnPCabToCounter=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_pnp/PnPCabToCounter/2024-04-24", + mg_path="v0.1/single_stage/kitchen_pnp/PnPCabToCounter/mg/2024-07-12-04-33-29", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/fgd165p91ts9qurfb496ubi1xdqgrz97.hdf5", + human_im="https://utexas.box.com/shared/static/pdfh88slq4bazfglixaw80whvbtlbw6r.hdf5", + mg_im="https://utexas.box.com/shared/static/mfltre5w8qi8ps1fqicblx40p008425z.hdf5", + ), + ), + PnPCounterToSink=dict( + horizon=700, + human_path="v0.1/single_stage/kitchen_pnp/PnPCounterToSink/2024-04-25", + mg_path="v0.1/single_stage/kitchen_pnp/PnPCounterToSink/mg/2024-05-04-22-14-06_and_2024-05-07-07-40-17", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/nc0x55xwlgs4acj97ngdj1q6pv450ooo.hdf5", + human_im="https://utexas.box.com/shared/static/0z1wr8iwfusfqqpp56j3vfxvvse1x0vc.hdf5", + mg_im="https://utexas.box.com/shared/static/5vkb2fpthnw554q888fynk3zqwsgk2e5.hdf5", + ), + ), + PnPSinkToCounter=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_pnp/PnPSinkToCounter/2024-04-26_2", + mg_path="v0.1/single_stage/kitchen_pnp/PnPSinkToCounter/mg/2024-05-04-22-14-34_and_2024-05-07-07-40-21", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/uyhepwjyr0880a5q03fc61qmhbrhwy7k.hdf5", + human_im="https://utexas.box.com/shared/static/pe03k5qvcuq1nzbpfag5pfo2t8fzvl9i.hdf5", + mg_im="https://utexas.box.com/shared/static/ppj3j8jnxkpusi7ft44f5ut7szkmu8yr.hdf5", + ), + ), + PnPCounterToMicrowave=dict( + horizon=600, + human_path="v0.1/single_stage/kitchen_pnp/PnPCounterToMicrowave/2024-04-27", + mg_path="v0.1/single_stage/kitchen_pnp/PnPCounterToMicrowave/mg/2024-05-04-22-13-21_and_2024-05-07-07-41-17", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/z1qwxsuczjmv68p7267nylbv9ebc6g4p.hdf5", + human_im="https://utexas.box.com/shared/static/2kun70ehqzanl5h0hbgpdezrfrvuimq8.hdf5", + mg_im="https://utexas.box.com/shared/static/vdm6pzl68xqqxvk9iy7i3l62j37t3sbp.hdf5", + ), + ), + PnPMicrowaveToCounter=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_pnp/PnPMicrowaveToCounter/2024-04-26", + mg_path="v0.1/single_stage/kitchen_pnp/PnPMicrowaveToCounter/mg/2024-05-04-22-14-26_and_2024-05-07-07-41-42", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/emnl5i3s621sf5smgek5lu4twbc326jt.hdf5", + human_im="https://utexas.box.com/shared/static/z2t1kyto32thprw7xvq3r4tjvkdz0dl2.hdf5", + mg_im="https://utexas.box.com/shared/static/3gs5cvp5qyzvk7gplmp0lkwfs1x1mkrj.hdf5", + ), + ), + PnPCounterToStove=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_pnp/PnPCounterToStove/2024-04-26", + mg_path="v0.1/single_stage/kitchen_pnp/PnPCounterToStove/mg/2024-05-04-22-14-20", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/9z2k5iqspwdo2153yuutcvqb9zzzvtdu.hdf5", + human_im="https://utexas.box.com/shared/static/penrv5sysn192gxwj7n7f6k0gjceovfn.hdf5", + mg_im="https://utexas.box.com/shared/static/1ytpoks6mp9f56wh36ni8k02fz0kbvmb.hdf5", + ), + ), + PnPStoveToCounter=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_pnp/PnPStoveToCounter/2024-05-01", + mg_path="v0.1/single_stage/kitchen_pnp/PnPStoveToCounter/mg/2024-05-04-22-14-40", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/1m3v1rkh7gna5ujt0vcwzej7stv5rdio.hdf5", + human_im="https://utexas.box.com/shared/static/rht9bfh38gaue5ig17ubpsibb4jrgtyv.hdf5", + mg_im="https://utexas.box.com/shared/static/uvrx2d7zxungplafbn9kg6rbe23ysund.hdf5", + ), + ), + OpenSingleDoor=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_doors/OpenSingleDoor/2024-04-24", + mg_path="v0.1/single_stage/kitchen_doors/OpenSingleDoor/mg/2024-05-04-22-37-39", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/hjukxdpqvnrghtbjbhin28idzkysq7oa.hdf5", + human_im="https://utexas.box.com/shared/static/vhvlbuza3g1lpqa9m6zvmbzh8xquvqy8.hdf5", + mg_im="https://utexas.box.com/shared/static/ekf6qwp9s07jnkpazbohlv03d6b73vth.hdf5", + ), + ), + CloseSingleDoor=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_doors/CloseSingleDoor/2024-04-24", + mg_path="v0.1/single_stage/kitchen_doors/CloseSingleDoor/mg/2024-05-04-22-34-56", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/gea28p5mrvj9lnw1s6c8fqvzxk5f779i.hdf5", + human_im="https://utexas.box.com/shared/static/2wnm0u1x9fp9ni02pmzqzhpjsb1kgfrr.hdf5", + mg_im="https://utexas.box.com/shared/static/5mg9vkhilkaxza83l48aht3sk76086tm.hdf5", + ), + ), + OpenDoubleDoor=dict( + horizon=1000, + human_path="v0.1/single_stage/kitchen_doors/OpenDoubleDoor/2024-04-26", + mg_path="v0.1/single_stage/kitchen_doors/OpenDoubleDoor/mg/2024-05-04-22-35-53", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/xl23utiszzdbjdqlveq1mxxca9m3kbvw.hdf5", + human_im="https://utexas.box.com/shared/static/8swihowjd5fdk1vpf0k94gl72f8nbjeb.hdf5", + mg_im="https://utexas.box.com/shared/static/5djutjyyksic6qpl2uuq9cvzj3r78jvf.hdf5", + ), + ), + CloseDoubleDoor=dict( + horizon=700, + human_path="v0.1/single_stage/kitchen_doors/CloseDoubleDoor/2024-04-29", + mg_path="v0.1/single_stage/kitchen_doors/CloseDoubleDoor/mg/2024-05-04-22-22-42_and_2024-05-08-06-02-36", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/zozyctzejc2nrlpjwqjq4w761830kq45.hdf5", + human_im="https://utexas.box.com/shared/static/14f2ssfhwfhyo9cvj0s3kq303bv38g6t.hdf5", + mg_im="https://utexas.box.com/shared/static/7t269kmcrsycc4wz5wonw62ijopjhyv7.hdf5", + ), + ), + OpenDrawer=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_drawer/OpenDrawer/2024-05-03", + mg_path="v0.1/single_stage/kitchen_drawer/OpenDrawer/mg/2024-05-04-22-38-42", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/990d2f339zvalvlw50s4s1l6sfvt018m.hdf5", + human_im="https://utexas.box.com/shared/static/d8a0g5827kbm4ufk3p1tbuz3idstgum8.hdf5", + mg_im="https://utexas.box.com/shared/static/t0sio5vrdax5bdfqkumfh63inq6o9b88.hdf5", + ), + ), + CloseDrawer=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_drawer/CloseDrawer/2024-04-30", + mg_path="v0.1/single_stage/kitchen_drawer/CloseDrawer/mg/2024-05-09-09-32-19", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/ooekd1zdy02hfu234xm5h63f7mzbez4b.hdf5", + human_im="https://utexas.box.com/shared/static/4r5w0a6i4jtgv5qmqx09fnqh5d7c45oi.hdf5", + mg_im="https://utexas.box.com/shared/static/aohabqltp8c6ze61u4h2uhtc9p9w35zb.hdf5", + ), + ), + TurnOnSinkFaucet=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_sink/TurnOnSinkFaucet/2024-04-25", + mg_path="v0.1/single_stage/kitchen_sink/TurnOnSinkFaucet/mg/2024-05-04-22-17-46", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/7vogk85ed3sm1o1vo8fzast9rs8zshgk.hdf5", + human_im="https://utexas.box.com/shared/static/f0brygtzwgmmwccg58b6m82yapa4jnji.hdf5", + mg_im="https://utexas.box.com/shared/static/p8x9njpsf5j9fkmnu7lwajupzm1t7aap.hdf5", + ), + ), + TurnOffSinkFaucet=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_sink/TurnOffSinkFaucet/2024-04-25", + mg_path="v0.1/single_stage/kitchen_sink/TurnOffSinkFaucet/mg/2024-05-04-22-17-26", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/ukkycoa2c6k5d6bpt1cdplzk2nrg879t.hdf5", + human_im="https://utexas.box.com/shared/static/ceewfn4ydhprupdcdppfe8wu4x61oxdg.hdf5", + mg_im="https://utexas.box.com/shared/static/r392ma0dje2t5ov4dug4vbqhn0z6hblk.hdf5", + ), + ), + TurnSinkSpout=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_sink/TurnSinkSpout/2024-04-29", + mg_path="v0.1/single_stage/kitchen_sink/TurnSinkSpout/mg/2024-05-09-09-31-12", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/zxop70u9s6rl4udz7fhp4besrvu508pj.hdf5", + human_im="https://utexas.box.com/shared/static/nnojt3760k143fxwhf2u0kzh1i56n7x1.hdf5", + mg_im="https://utexas.box.com/shared/static/34l1y45xquau66nk8j7hrpfvlad4b9fg.hdf5", + ), + ), + TurnOnStove=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_stove/TurnOnStove/2024-05-02", + mg_path="v0.1/single_stage/kitchen_stove/TurnOnStove/mg/2024-05-08-09-20-31", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/ow4npc933yty4blxg8rc2pgjp6f1yc36.hdf5", + human_im="https://utexas.box.com/shared/static/dewbngq5wk6dipb29x6984x6dygu2gck.hdf5", + mg_im="https://utexas.box.com/shared/static/7gzolvj3fyzhhfjoxswmmpjpxu5q4too.hdf5", + ), + ), + TurnOffStove=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_stove/TurnOffStove/2024-05-02", + mg_path="v0.1/single_stage/kitchen_stove/TurnOffStove/mg/2024-05-08-09-20-45", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/vp6u3huv9c2vg5r09105gkbmwguycnn0.hdf5", + human_im="https://utexas.box.com/shared/static/8tukea09szcjb2ncbe43zt65n7dzg4eh.hdf5", + mg_im="https://utexas.box.com/shared/static/6rv14y77hfknrwfbwn5qtlfdydkr8tog.hdf5", + ), + ), + CoffeeSetupMug=dict( + horizon=600, + human_path="v0.1/single_stage/kitchen_coffee/CoffeeSetupMug/2024-04-25", + mg_path="v0.1/single_stage/kitchen_coffee/CoffeeSetupMug/mg/2024-05-04-22-22-13_and_2024-05-08-05-52-13", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/zxytzos86xes7jo8z0gp7lklawbiyo8g.hdf5", + human_im="https://utexas.box.com/shared/static/pv2i49t4p7238gp34txhm7jcl7domw58.hdf5", + mg_im="https://utexas.box.com/shared/static/uagjbu3y2ds0hzm7789nuj0ppxp9dxxl.hdf5", + ), + ), + CoffeeServeMug=dict( + horizon=600, + human_path="v0.1/single_stage/kitchen_coffee/CoffeeServeMug/2024-05-01", + mg_path="v0.1/single_stage/kitchen_coffee/CoffeeServeMug/mg/2024-05-04-22-21-50", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/tse3mkxx913pf4d4ij7fplchtv1rchkq.hdf5", + human_im="https://utexas.box.com/shared/static/ts3537f93dzjpkux19syy0pndw5re231.hdf5", + mg_im="https://utexas.box.com/shared/static/ikkr7qu89v9e0o1kwiqttkxllaxvv2n4.hdf5", + ), + ), + CoffeePressButton=dict( + horizon=300, + human_path="v0.1/single_stage/kitchen_coffee/CoffeePressButton/2024-04-25", + mg_path="v0.1/single_stage/kitchen_coffee/CoffeePressButton/mg/2024-05-04-22-21-32", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/t6oblmeilexe9ndca4ccaxdclw1tzps5.hdf5", + human_im="https://utexas.box.com/shared/static/l5dnmcfd0r36vhdqgjchxo20vajt7ohl.hdf5", + mg_im="https://utexas.box.com/shared/static/y5zm9mlslfg8p4jkpwnxlizcsvsca1mb.hdf5", + ), + ), + TurnOnMicrowave=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_microwave/TurnOnMicrowave/2024-04-25", + mg_path="v0.1/single_stage/kitchen_microwave/TurnOnMicrowave/mg/2024-05-04-22-40-00", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/o1sp7qrcd97b6jo68olx58l35wffpbna.hdf5", + human_im="https://utexas.box.com/shared/static/t6eromogy5is2no3s1e5bk1nb2hgab2k.hdf5", + mg_im="https://utexas.box.com/shared/static/t1n5oijudf8yn85bj8v64b1codde7kye.hdf5", + ), + ), + TurnOffMicrowave=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_microwave/TurnOffMicrowave/2024-04-25", + mg_path="v0.1/single_stage/kitchen_microwave/TurnOffMicrowave/mg/2024-05-04-22-39-23", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/m2exfytqjd0496y70b3ou2i8993ryb50.hdf5", + human_im="https://utexas.box.com/shared/static/0drm2h7fgd5857x8xgcj1lph23srpbj1.hdf5", + mg_im="https://utexas.box.com/shared/static/7c8bku46us9a8sddwg3zk6z3p4ce6ya0.hdf5", + ), + ), + NavigateKitchen=dict( + horizon=500, + human_path="v0.1/single_stage/kitchen_navigate/NavigateKitchen/2024-05-09", + mg_path=None, + download_links=dict( + human_raw="https://utexas.box.com/shared/static/pzvzuvmkla74kro84yw13uwjr2g89z8m.hdf5", + human_im="https://utexas.box.com/shared/static/mbi6011svy2zb436wsf2hhc337aduwmw.hdf5", + ), + ), +) + + +MULTI_STAGE_TASK_DATASETS = OrderedDict( + ArrangeVegetables=dict( + human_path="v0.1/multi_stage/chopping_food/ArrangeVegetables/2024-05-11", + horizon=1200, + activity="chopping_food", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/hiwbv68h3vty9ksqsdhcw2xhuvkwcf3o.hdf5", + human_im="https://utexas.box.com/shared/static/ovzt0bod4nrrack6dak12jn1fx2cnwbw.hdf5", + ), + ), + MicrowaveThawing=dict( + human_path="v0.1/multi_stage/defrosting_food/MicrowaveThawing/2024-05-11", + horizon=1000, + activity="defrosting_food", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/wreambog4jak8og9nbhm0nr2t6w5ygdt.hdf5", + human_im="https://utexas.box.com/shared/static/ehwo6728r3qyi8g0h70zhawijojqotnm.hdf5", + ), + ), + RestockPantry=dict( + human_path="v0.1/multi_stage/restocking_supplies/RestockPantry/2024-05-10", + horizon=1000, + activity="restocking_supplies", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/t2g6rdyh006bw09cxxxamd7thton5grl.hdf5", + human_im="https://utexas.box.com/shared/static/35yr2xmsmwq0xkknvlmlivh9ifste71q.hdf5", + ), + ), + PreSoakPan=dict( + human_path="v0.1/multi_stage/washing_dishes/PreSoakPan/2024-05-10", + horizon=1500, + activity="washing_dishes", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/d4vg2pag7465xp99vej1skk3frmohzk1.hdf5", + human_im="https://utexas.box.com/shared/static/etotr8tn0z57ttb311bibh0mdmc65j96.hdf5", + ), + ), + PrepareCoffee=dict( + human_path="v0.1/multi_stage/brewing/PrepareCoffee/2024-05-07", + horizon=1000, + activity="brewing", + download_links=dict( + human_raw="https://utexas.box.com/shared/static/qhtle2ccvm17g65ecg2vrudpkl9v5wkk.hdf5", + human_im="https://utexas.box.com/shared/static/qq3p4ctlmiv751jx5av92aaz9dxylw76.hdf5", + ), + ), +) + + +def get_ds_path(task, ds_type, return_info=False): + if task in SINGLE_STAGE_TASK_DATASETS: + ds_config = SINGLE_STAGE_TASK_DATASETS[task] + elif task in MULTI_STAGE_TASK_DATASETS: + ds_config = MULTI_STAGE_TASK_DATASETS[task] + else: + raise ValueError + + if ds_type == "human_raw": + folder = ds_config["human_path"] + fname = "demo.hdf5" + elif ds_type == "human_im": + folder = ds_config["human_path"] + if task in SINGLE_STAGE_TASK_DATASETS: + fname = "demo_gentex_im128_randcams.hdf5" + elif task in MULTI_STAGE_TASK_DATASETS: + fname = "demo_im128.hdf5" + elif ds_type == "mg_im": + # mg dataset is not available for all tasks + folder = ds_config.get("mg_path", None) + fname = "demo_gentex_im128_randcams.hdf5" + else: + raise ValueError + + # if dataset type is not registered, return None + if folder is None: + ret = (None, None) if return_info is True else None + return ret + + if macros.DATASET_BASE_PATH is None: + ds_base_path = os.path.join(Path(robocasa.__path__[0]).parent.absolute(), "datasets") + else: + ds_base_path = macros.DATASET_BASE_PATH + ds_path = os.path.join(ds_base_path, folder, fname) + + if return_info is False: + return ds_path + + ds_info = {} + ds_info["url"] = ds_config["download_links"][ds_type] + ds_info["horizon"] = ds_config["horizon"] + return ds_path, ds_info diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dexmg_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dexmg_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4a7edbde7483216062e3a508d108537468556953 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/dexmg_utils.py @@ -0,0 +1,99 @@ +class DexMGConfigHelper: + """ + Helper class for multi-inheritance scenarios, specifically designed to support task configuration + and environment interaction in robotic manipulation tasks. + + Example Usage: + This class is intended to be used in multi-inheritance cases such as: + class PnPCounterToSink(Kitchen, DexMGConfigHelper) + which will automatically generate a new configuration class: + class PnPCounterToSink_Config(MG_Config) + + Behavior: + 1. In the implementation of the MG_RoboSuiteHumanoidGeneric class: + - `self.env` will be an instance of PnPCounterToSink, enabling access to: + - `self.env.get_object()` to retrieve key objects. + - `self.env.get_subtask_term_signals()` to obtain signal information. + 2. In the implementation of PnPCounterToSink_Config: + - `self.task_config()` delegates to `PnPCounterToSink.task_config`, which defines + subtask divisions based on objects and signals. + + Attributes: + subclasses (list): A list storing tuples of subclass names and their respective classes. + """ + + class AttrDict(dict): + def __getattr__(self, key): + if key not in self: + self[key] = ( + DexMGConfigHelper.AttrDict() + ) # Create a new AttrDict if key doesn't exist + return self[key] + + def __setattr__(self, key, value): + self[key] = value + + def to_dict(self): + """Recursively converts AttrDict to a normal dictionary""" + return { + key: (value.to_dict() if isinstance(value, DexMGConfigHelper.AttrDict) else value) + for key, value in self.items() + } + + subclasses = [] + + def __init_subclass__(cls, **kwargs): + """ + Automatically registers each subclass of DexMGConfigHelper. + + Args: + cls: The subclass being registered. + kwargs: Additional keyword arguments. + """ + super().__init_subclass__(**kwargs) + DexMGConfigHelper.subclasses.append((cls.__name__, cls)) + + def __init__(self): + """ + Initialize a DexMGConfigHelper instance. + Note: This is an abstract class and should not be instantiated directly. + """ + pass + + # Misc functions copied from dexmimicgen.mimicgen.env_interfaces.robosuite_humanoid + def get_grippers(self): + """ + Get grippers for the environment. + """ + return self.robots[0].gripper["right"], self.robots[0].gripper["left"] + + def get_object(self): + """ + Retrieve a key object required for the task. + This method must be implemented in subclasses. + + Raises: + NotImplementedError: If the method is not overridden in a subclass. + """ + raise NotImplementedError + + def get_subtask_term_signals(self): + """ + Retrieve signals used to define subtask termination conditions. + This method must be implemented in subclasses. + + Raises: + NotImplementedError: If the method is not overridden in a subclass. + """ + raise NotImplementedError + + @staticmethod + def task_config(): + """ + Define the configuration for dividing a task into subtasks. + This method must be implemented in subclasses. + + Raises: + NotImplementedError: If the method is not overridden in a subclass. + """ + raise NotImplementedError diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/env_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/env_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d075ca7fc6e81141bad2111504ec1a0a485aae32 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/env_utils.py @@ -0,0 +1,105 @@ +from robocasa.utils.dataset_registry import ( + get_ds_path, + SINGLE_STAGE_TASK_DATASETS, + MULTI_STAGE_TASK_DATASETS, +) +from robocasa.scripts.playback_dataset import get_env_metadata_from_dataset +from robosuite.controllers import load_composite_controller_config +import os +import robosuite +import imageio +import numpy as np +from tqdm import tqdm +from termcolor import colored + + +def create_env( + env_name, + # robosuite-related configs + robots="PandaOmron", + camera_names=[ + "robot0_agentview_left", + "robot0_agentview_right", + "robot0_eye_in_hand", + ], + camera_widths=128, + camera_heights=128, + seed=None, + # robocasa-related configs + obj_instance_split=None, + generative_textures=None, + randomize_cameras=False, + layout_and_style_ids=None, + layout_ids=None, + style_ids=None, +): + controller_config = load_composite_controller_config( + controller=None, + robot=robots if isinstance(robots, str) else robots[0], + ) + + env_kwargs = dict( + env_name=env_name, + robots=robots, + controller_configs=controller_config, + camera_names=camera_names, + camera_widths=camera_widths, + camera_heights=camera_heights, + has_renderer=False, + has_offscreen_renderer=True, + ignore_done=True, + use_object_obs=True, + use_camera_obs=True, + camera_depths=False, + seed=seed, + obj_instance_split=obj_instance_split, + generative_textures=generative_textures, + randomize_cameras=randomize_cameras, + layout_and_style_ids=layout_and_style_ids, + layout_ids=layout_ids, + style_ids=style_ids, + translucent_robot=False, + ) + + env = robosuite.make(**env_kwargs) + return env + + +def run_random_rollouts(env, num_rollouts, num_steps, video_path=None): + video_writer = None + if video_path is not None: + video_writer = imageio.get_writer(video_path, fps=20) + + info = {} + num_success_rollouts = 0 + for rollout_i in tqdm(range(num_rollouts)): + obs = env.reset() + for step_i in range(num_steps): + # sample and execute random action + action = np.random.uniform(low=env.action_spec[0], high=env.action_spec[1]) + obs, _, _, _ = env.step(action) + + if video_writer is not None: + video_img = env.sim.render( + height=512, width=512, camera_name="robot0_agentview_center" + )[::-1] + video_writer.append_data(video_img) + + if env._check_success(): + num_success_rollouts += 1 + break + + if video_writer is not None: + video_writer.close() + print(colored(f"Saved video of rollouts to {video_path}", color="yellow")) + + info["num_success_rollouts"] = num_success_rollouts + + return info + + +if __name__ == "__main__": + # select random task to run rollouts for + env_name = np.random.choice(list(SINGLE_STAGE_TASK_DATASETS) + list(MULTI_STAGE_TASK_DATASETS)) + env = create_eval_env(env_name=env_name) + info = run_random_rollouts(env, num_rollouts=3, num_steps=100, video_path="/tmp/test.mp4") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af2ec96cbfc7eb7cb6a890e2cc96056ac5ebdcbd --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/__init__.py @@ -0,0 +1,4 @@ +from .gymnasium_basic import RoboCasaEnv # noqa: F401 + + +# from .gymnasium_gearbc import GearBCRoboCasaEnv # noqa: F401 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/gymnasium_basic.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/gymnasium_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..e652c6f8092ea9cfe154392dc1d3f581fd981560 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/gym_utils/gymnasium_basic.py @@ -0,0 +1,417 @@ +import datetime, uuid +from copy import deepcopy +import gymnasium as gym +import h5py +import numpy as np +import os +import robocasa.utils.transform_utils as T +import robosuite +from gymnasium import spaces +from robocasa.models.robots import ( + GR00T_ROBOCASA_ENVS_GR1_ARMS_ONLY, + GR00T_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST, + GR00T_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY, + gather_robot_observations, + make_key_converter, +) +from robosuite.controllers import load_composite_controller_config +from robosuite.controllers.composite.composite_controller import HybridMobileBase +from robocasa.wrappers.ik_wrapper import IKWrapper + + +ALLOWED_LANGUAGE_CHARSET = ( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.\n\t[]{}()!?'_:" +) + + +def create_env_robosuite( + env_name, + # robosuite-related configs + robots="PandaOmron", + controller_configs=None, + camera_names=[ + "egoview", + "robot0_eye_in_left_hand", + "robot0_eye_in_right_hand", + ], + camera_widths=128, + camera_heights=128, + render_camera=None, + enable_render=True, + seed=None, + # robocasa-related configs + obj_instance_split=None, + generative_textures=None, + randomize_cameras=False, + layout_and_style_ids=None, + layout_ids=None, + style_ids=None, + onscreen=False, + renderer="mujoco", + translucent_robot=False, + control_freq=20, +): + if controller_configs is None: + controller_configs = load_composite_controller_config( + controller=None, + robot=robots if isinstance(robots, str) else robots[0], + ) + env_kwargs = dict( + env_name=env_name, + robots=robots, + controller_configs=controller_configs, + camera_names=camera_names, + camera_widths=camera_widths, + camera_heights=camera_heights, + has_renderer=onscreen, + has_offscreen_renderer=enable_render, + renderer=renderer, + ignore_done=True, + use_object_obs=True, + use_camera_obs=enable_render, + camera_depths=False, + seed=seed, + translucent_robot=translucent_robot, + control_freq=control_freq, + render_camera=render_camera, + randomize_cameras=randomize_cameras, + ) + + env = robosuite.make(**env_kwargs) + return env, env_kwargs + + +class RoboCasaEnv(gym.Env): + def __init__( + self, + env_name=None, + robots_name=None, + camera_names=None, + camera_widths=None, + camera_heights=None, + enable_render=True, + render_camera=None, + onscreen=False, + dump_rollout_dataset_dir=None, + rollout_hdf5=None, + rollout_trainset=None, + controller_configs=None, + ik_indicator=False, + **kwargs, # Accept additional kwargs + ): + self.key_converter = make_key_converter(robots_name) + ( + _, + camera_names, + default_camera_widths, + default_camera_heights, + ) = self.key_converter.get_camera_config() + + if camera_widths is None: + camera_widths = default_camera_widths + if camera_heights is None: + camera_heights = default_camera_heights + + if controller_configs is not None: + controller_configs = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "../../../", + controller_configs, + ) + controller_configs = load_composite_controller_config( + controller=controller_configs, + robot=robots_name.split("_")[0], + ) + if ( + robots_name in GR00T_ROBOCASA_ENVS_GR1_ARMS_ONLY + or robots_name in GR00T_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST + or robots_name in GR00T_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY + ): + controller_configs["type"] = "BASIC" + controller_configs["composite_controller_specific_configs"] = {} + controller_configs["control_delta"] = False + + self.env, self.env_kwargs = create_env_robosuite( + env_name=env_name, + robots=robots_name.split("_"), + controller_configs=controller_configs, + camera_names=camera_names, + camera_widths=camera_widths, + camera_heights=camera_heights, + render_camera=render_camera, + enable_render=enable_render, + onscreen=onscreen, + **kwargs, # Forward kwargs to create_env_robosuite + ) + + if ik_indicator: + self.env = IKWrapper(self.env, ik_indicator=True) + + # TODO: the following info should be output by gr00trobocasa + self.camera_names = camera_names + self.camera_widths = camera_widths + self.camera_heights = camera_heights + self.enable_render = enable_render and not onscreen + self.render_obs_key = f"{camera_names[0]}_image" + self.render_cache = None + + # setup spaces + action_space = spaces.Dict() + for robot in self.env.robots: + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + for part_name, controller in cc.part_controllers.items(): + min_value, max_value = -1, 1 + start_idx, end_idx = cc._action_split_indexes[part_name] + shape = [end_idx - start_idx] + this_space = spaces.Box( + low=min_value, high=max_value, shape=shape, dtype=np.float32 + ) + action_space[f"{pf}{part_name}"] = this_space + if isinstance(cc, HybridMobileBase): + this_space = spaces.Discrete(2) + action_space[f"{pf}base_mode"] = this_space + + action_space = spaces.Dict(action_space) + self.action_space = action_space + + # Calling env._get_observations(force_update=True) will pollute the observables. + # This is safe because it is only called from the constructor and will be overwritten later in reset(). + obs = ( + self.env.viewer._get_observations(force_update=True) + if self.env.viewer_get_obs + else self.env._get_observations(force_update=True) + ) + obs.update(gather_robot_observations(self.env)) + observation_space = spaces.Dict() + for obs_name, obs_value in obs.items(): + shape = list(obs_value.shape) + if obs_name.endswith("_image"): + continue + min_value, max_value = -1, 1 + this_space = spaces.Box(low=min_value, high=max_value, shape=shape, dtype=np.float32) + observation_space[obs_name] = this_space + + for camera_name in camera_names: + shape = [camera_heights, camera_widths, 3] + this_space = spaces.Box(low=0, high=255, shape=shape, dtype=np.uint8) + observation_space[f"{camera_name}_image"] = this_space + + observation_space["language"] = spaces.Text( + max_length=256, charset=ALLOWED_LANGUAGE_CHARSET + ) + + self.observation_space = observation_space + + self.dump_rollout_dataset_dir = dump_rollout_dataset_dir + self.gr00t_exporter = None + self.np_exporter = None + + self.rollout_hdf5 = rollout_hdf5 + self.rollout_trainset = rollout_trainset + self.rollout_initial_state = {} + + def begin_rollout_dataset_dump(self): + if self.dump_rollout_dataset_dir is not None: + gr00t_env_meta = dict( + env_name=self.env_kwargs["env_name"], + env_version=robosuite.__version__, + type=1, + env_kwargs=deepcopy(self.env_kwargs), + ) + gr00t_dir = os.path.join( + self.dump_rollout_dataset_dir, + self.env_kwargs["env_name"] + + "_" + + "_".join(robot.name for robot in self.env.robots) + + "_Env", + f"{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}-{str(uuid.uuid4())[:8]}", + ) + if not os.path.exists(gr00t_dir): + os.makedirs(gr00t_dir, exist_ok=True) + self.gr00t_exporter = Gr00tExporter( + gr00t_dir, + self.env, + gr00t_env_meta, + ) + self.np_exporter = {} + self.np_exporter["success"] = [] + for signal in self.env.get_subtask_term_signals(): + self.np_exporter[signal] = [] + + def process_rollout_dataset_dump_before_step(self, env_action): + if self.gr00t_exporter is not None: + self.gr00t_exporter.add_record_before_step(self.env, env_action) + self.np_exporter["success"].append(self.env.reward()) + for signal, value in self.env.get_subtask_term_signals().items(): + self.np_exporter[signal].append(value) + + def process_rollout_dataset_dump_after_step(self, env_action): + if self.gr00t_exporter is not None: + self.gr00t_exporter.add_record_after_step(self.env, env_action) + + def complete_rollout_dataset_dump(self): + if self.gr00t_exporter is not None and self.np_exporter is not None: + data = {k: np.array(v, dtype=np.float32) for k, v in self.np_exporter.items()} + np.savez(os.path.join(self.gr00t_exporter.gr00t_dir, "rewards.npz"), **data) + self.gr00t_exporter.finish() + self.np_exporter = None + self.gr00t_exporter = None + + def get_basic_observation(self, raw_obs): + raw_obs.update(gather_robot_observations(self.env)) + + # Image are in (H, W, C), flip it upside down + def process_img(img): + return np.copy(img[::-1, :, :]) + + for obs_name, obs_value in raw_obs.items(): + if obs_name.endswith("_image"): + # image observations + raw_obs[obs_name] = process_img(obs_value) + else: + # non-image observations + raw_obs[obs_name] = obs_value.astype(np.float32) + + # Return black image if rendering is disabled + if not self.enable_render: + for name in self.camera_names: + raw_obs[f"{name}_image"] = np.zeros( + (self.camera_heights, self.camera_widths, 3), dtype=np.uint8 + ) + + self.render_cache = raw_obs[self.render_obs_key] + raw_obs["language"] = self.env.get_ep_meta().get("lang", "") + + return raw_obs + + def reset(self, seed=None, options=None): + if seed is not None and self.rollout_trainset is not None and seed < self.rollout_trainset: + if seed not in self.rollout_initial_state: + f = h5py.File(self.rollout_hdf5, "r") + demos = list(f["data"].keys()) + inds = np.argsort([int(elem[5:]) for elem in demos]) + demos = [demos[i] for i in inds] + ep = demos[seed] + self.rollout_initial_state[seed] = { + "states": f["data/{}/states".format(ep)][0], + "ep_meta": f["data/{}".format(ep)].attrs.get("ep_meta", None), + "model": f["data/{}".format(ep)].attrs["model_file"], + } + reset_to(self.env, self.rollout_initial_state[seed]) + obs = None + else: + # NOTE: self.env can be either a robosuite environment or ik wrapper + if isinstance(self.env, IKWrapper): + self.env.unwrapped.seed = seed + self.env.unwrapped.rng = np.random.default_rng(seed=seed) + else: + self.env.seed = seed + self.env.rng = np.random.default_rng(seed=seed) + raw_obs = self.env.reset() + obs = self.get_basic_observation(raw_obs) + + info = {} + info["success"] = False + info["intermediate_signals"] = {} + + self.complete_rollout_dataset_dump() + self.begin_rollout_dataset_dump() + + return obs, info + + def step(self, action_dict): + env_action = [] + for robot in self.env.robots: + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + action = np.zeros(cc.action_limits[0].shape) + for part_name, controller in cc.part_controllers.items(): + start_idx, end_idx = cc._action_split_indexes[part_name] + act = action_dict.pop(f"{pf}{part_name}") + action[start_idx:end_idx] = act + + # set external torque compensation if available + if "gripper" not in part_name and controller.use_external_torque_compensation: + controller.external_torque_compensation = action_dict.pop( + f"{pf}{part_name}_tau" + ) + if isinstance(cc, HybridMobileBase): + action[-1] = action_dict.pop(f"{pf}base_mode") + env_action.append(action) + + env_action = np.concatenate(env_action) + + self.process_rollout_dataset_dump_before_step(env_action) + raw_obs, reward, done, info = self.env.step(env_action) + self.process_rollout_dataset_dump_after_step(env_action) + + obs = self.get_basic_observation(raw_obs) + + truncated = False + + info["success"] = reward > 0 + info["intermediate_signals"] = {} + if hasattr(self.env, "_get_intermediate_signals"): + info["intermediate_signals"] = self.env._get_intermediate_signals() + + if hasattr(self.env, "_get_auxiliary_states"): + info["auxiliary_states"] = self.env._get_auxiliary_states() + + if hasattr(self.env, "obj_body_id"): + for obj_name in self.env.obj_body_id.keys(): + info[f"{obj_name}_pos"] = list( + self.env.sim.data.body_xpos[self.env.obj_body_id[obj_name]] + ) + info[f"{obj_name}_quat_xyzw"] = list( + T.convert_quat( + np.array(self.env.sim.data.body_xquat[self.env.obj_body_id[obj_name]]), + to="xyzw", + ) + ) + + return obs, reward, done, truncated, info + + def render(self): + if self.render_cache is None: + raise RuntimeError("Must run reset or step before render.") + return self.render_cache + + def close(self): + self.complete_rollout_dataset_dump() + self.env.close() + + def get_actuator_names(self): + joint_names = self.get_joint_names() + + model = self.env.sim.model + + actuated_joint_names = [] + for ii in range(model.nu): + joint_id = model.actuator_trnid[ii, 0] + actuated_joint_names.append(model.joint(joint_id).name) + + actuator_names = {} + actuator_indices = {} + for part_name, _joint_names in joint_names.items(): + actuator_names[part_name] = [] + actuator_indices[part_name] = [] + for _jn in _joint_names: + if _jn in actuated_joint_names: + actuator_names[part_name].append(_jn) + actuator_indices[part_name].append(actuated_joint_names.index(_jn)) + actuator_names[part_name] = ( + np.array(actuator_names[part_name])[np.argsort(actuator_indices[part_name])] + ).tolist() + return actuator_names + + def get_joint_names(self): + joint_names = {} + for _robot in self.env.robots: + cc = _robot.composite_controller + for part_name, part_controller in cc.part_controllers.items(): + if "gripper" in part_name: + joint_names[part_name] = part_controller.joint_index + else: + joint_names[part_name] = part_controller.joint_names + return joint_names diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb69cbf75946578508a38c3d3e60381e68c4091 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/__init__.py @@ -0,0 +1,3 @@ +import os + +assets_root = os.path.join(os.path.dirname(__file__), "assets") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/file_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/file_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c246eb915655646febc9ee39d9611d1ef51f0d31 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/file_utils.py @@ -0,0 +1,35 @@ +from pathlib import Path + +# import robosuite_model_zoo +import os +import shutil + + +def get_ext(path): + return Path(path).suffix + + +def get_stem(path): + return Path(path).stem + + +def get_name(path): + return Path(path).name + + +def make_asset_path(base_asset_path, model_prefix, model_name): + if base_asset_path is None: + base_asset_path = os.path.join( + os.path.dirname(robosuite_model_zoo.__file__), + "assets_private", + ) + if model_prefix is not None: + base_asset_path = os.path.join(base_asset_path, model_prefix) + asset_path = os.path.join(base_asset_path, model_name) + + if os.path.exists(asset_path): + shutil.rmtree(asset_path) + + os.makedirs(asset_path) + + return asset_path diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/fixture_template.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/fixture_template.xml new file mode 100644 index 0000000000000000000000000000000000000000..6fece8297569124359e7a06a52348eb425c018bc --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/fixture_template.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/install_vhacd.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/install_vhacd.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4bc7c6684b15f865b1bccc30edfca5f552d0a9c --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/install_vhacd.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# +# Install V-HACD 4.0. +# Adapted from https://github.com/kevinzakka/obj2mjcf/blob/main/install_vhacd.sh + +# Check that cmake is installed. +t=`which cmake` +if [ -z "$t" ]; then + echo "You need cmake to install V-HACD." 1>&2 + exit 1 +fi + +# Clone and build executable. +# TODO(kevin): Peg to a 4.0 release when available, see #113. +git clone https://github.com/kmammou/v-hacd.git +cd v-hacd/app +cmake CMakeLists.txt +cmake --build . + +# Add executable to /usr/local/bin. +sudo ln -s "$PWD/TestVHACD" /usr/local/bin/TestVHACD diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/log_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/log_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..31e05dd43ffa5931351888412b949eb2636e95ef --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/log_utils.py @@ -0,0 +1,46 @@ +import json +import numpy as np +from termcolor import colored +from copy import deepcopy +import os +import sys +import textwrap + + +class NumpyEncoder(json.JSONEncoder): + """ + Special json encoder for numpy types + From https://stackoverflow.com/a/49677241 + """ + + def default(self, obj): + if isinstance(obj, np.integer): + return int(obj) + elif isinstance(obj, np.floating): + return float(obj) + elif isinstance(obj, np.ndarray): + return obj.tolist() + return json.JSONEncoder.default(self, obj) + + +def maybe_log_info(message, log=False, color="yellow", indent=False): + if log: + if indent: + message = textwrap.indent(message, " " * 5) + print(colored(message, color)) + + +def save_meta(args, asset_path): + # get args + meta = vars(args) + + # get relative path of running script + script_path = os.path.abspath(sys.argv[0]) + path_list = script_path.split("/") + # idx = len(path_list) - 1 - path_list[::-1].index("robosuite_model_zoo") + # meta["script"] = "/".join(path_list[idx:]) + meta["cmd"] = "python " + " ".join(sys.argv) + + # save meta data + with open(os.path.join(asset_path, "meta.json"), "w") as outfile: + json.dump(meta, outfile, indent=4) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_gen_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_gen_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f802c05215289bd643b8f855c4df2b032c5dc6ec --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_gen_utils.py @@ -0,0 +1,800 @@ +import numpy as np +import trimesh +import os +import robosuite +import xml.etree.ElementTree as ET +import shutil +import json +from termcolor import colored +from copy import deepcopy +from pathlib import Path + +# import robosuite_model_zoo +from robosuite.utils.transform_utils import mat2quat +import robocasa.utils.model_zoo.log_utils as LogUtils +import robocasa.utils.model_zoo.mtl_utils as MtlUtils + +from robosuite.utils.mjcf_utils import array_to_string, string_to_array + + +def parse_model_info( + model_path, + model_name, + coll_model_path, + asset_path, + obj_path=None, + verbose=False, + center=False, + prescale=False, + rot=None, + transform=None, +): + """ + Extract visual and collision geoms from + main model file and collision model file + """ + + LogUtils.maybe_log_info("Parsing input models...", log=verbose) + + geoms, textures, materials, transform = parse_model( + model_path, + model_name, + asset_path, + obj_path=obj_path, + center=center, + prescale=prescale, + rot=rot, + transform=transform, + # visual_only=(coll_model_path is None), + visual_only=True, + verbose=verbose, + ) + + coll_geoms, bb_info = parse_coll_model( + coll_model_path, + asset_path, + verbose=verbose, + transform=transform, + ) + + if coll_geoms is not None: + geoms = geoms + coll_geoms + + geoms_to_print = deepcopy(geoms) + for g in geoms_to_print: + if "rot_orig" in g: + del g["rot_orig"] + LogUtils.maybe_log_info( + "parsed geoms:\n" + json.dumps(geoms_to_print, indent=4, cls=LogUtils.NumpyEncoder), + log=verbose, + indent=True, + ) + + model_info = dict( + geoms=geoms, + textures=textures, + materials=materials, + bb=bb_info, + ) + + return model_info + + +def parse_model( + model_path, + model_name, + asset_path, + obj_path=None, + visual_only=False, + center=False, + prescale=False, + rot=None, + transform=None, + verbose=False, +): + """ + Extract meshes from main model file + """ + + LogUtils.maybe_log_info( + "parsing (main) model: {}".format(model_path), + log=verbose, + indent=True, + ) + + # load the model + if obj_path is None: + obj_files = [ + os.path.join(model_path, name) + for name in os.listdir(model_path) + if name.endswith(".obj") + ] + obj_file = obj_files[0] + else: + obj_file = obj_path + + geoms, textures, materials = [], [], [] + vis_path = os.path.join(asset_path, "visual") + coll_path = os.path.join(asset_path, "collision") + + if not os.path.isdir(vis_path): + os.makedirs(vis_path) + if not os.path.isdir(coll_path): + os.makedirs(coll_path) + + resolver = trimesh.resolvers.FilePathResolver(os.path.dirname(obj_file)) + model = trimesh.load( + obj_file, + resolver=resolver, + split_object=True, + # group_material=True, + process=False, + maintain_order=False, + ) + + # If transform is passed as an argument, center and prescale must be False. Rotation is applied afterward regardless. + if transform is not None: + assert center is False and prescale is False + + if center: + mat_t = np.eye((4)) + center = (model.bounds[0] + model.bounds[1]) / 2 + mat_t[:3, 3] = -center + transform = mat_t + + if prescale: + mat_s = np.eye((4)) + scale_factor = 1 / np.max(model.bounds[1] - model.bounds[0]) + mat_s *= scale_factor + + if transform is None: + transform = mat_s + else: + transform = np.matmul(mat_s, transform) + + rot = rot or [] + for r in rot: + mat_R = np.eye(4) + + if r in ["x", "x90"]: + mat_R[:3, :3] = [[1, 0, 0], [0, 0, -1], [0, 1, 0]] + elif r in ["x180"]: + mat_R[:3, :3] = [[1, 0, 0], [0, -1, 0], [0, 0, -1]] + elif r in ["x270"]: + mat_R[:3, :3] = [[1, 0, 0], [0, 0, 1], [0, -1, 0]] + + elif r in ["y", "y90"]: + mat_R[:3, :3] = [[0, 0, 1], [0, 1, 0], [-1, 0, 0]] + elif r in ["y180"]: + mat_R[:3, :3] = [[-1, 0, 0], [0, 1, 0], [0, 0, -1]] + elif r in ["y270"]: + mat_R[:3, :3] = [[0, 0, -1], [0, 1, 0], [1, 0, 0]] + + elif r in ["z", "z90"]: + mat_R[:3, :3] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]] + elif r in ["z180"]: + mat_R[:3, :3] = [[-1, 0, 0], [0, -1, 0], [0, 0, 1]] + elif r in ["z270"]: + mat_R[:3, :3] = [[0, 1, 0], [-1, 0, 0], [0, 0, 1]] + elif r in ["z60"]: + mat_R[:3, :3] = [ + [0.5000000, -0.8660254, 0.0000000], + [0.8660254, 0.5000000, 0.0000000], + [0, 0, 1], + ] + + else: + raise ValueError("Invalid choice of rotation {}".format(r)) + + if transform is None: + transform = mat_R + else: + transform = np.matmul(mat_R, transform) + + if transform is not None: + if isinstance(model, trimesh.base.Trimesh): + model.apply_transform(transform) + else: + for k in model.geometry: + model.geometry[k].apply_transform(transform) + + # debugging + # model.show() + # exit() + + mtls = MtlUtils.get_mtls(obj_file, work_dir=vis_path) + + """ + save mtl info. this section adapted from obj2mjf (credit: Kevin Zakka) + """ + for mtl in mtls: + if mtl.map_Kd is not None: + # Create the texture asset. + texture_path = Path(mtl.map_Kd) + texture = dict( + type="2d", + name=texture_path.stem, + file=os.path.join("visual", texture_path.name), + ) + # Reference the texture asset in a material asset. + material = dict( + name=mtl.name, + texture=texture_path.stem, + specular=mtl.mjcf_specular(), + shininess=mtl.mjcf_shininess(), + ) + + textures.append(texture) + materials.append(material) + else: + material = dict( + name=mtl.name, + specular=mtl.mjcf_specular(), + shininess=mtl.mjcf_shininess(), + rgba=mtl.mjcf_rgba(), + ) + materials.append(material) + + submodels = [] + + if isinstance(model, trimesh.base.Trimesh): + submodels = [(materials[-1]["name"], model)] + else: + submodels = list(model.geometry.items()) + + for sm_i, (sm_name, sm) in enumerate(submodels): + # ch_mesh = sm.convex_hull + # bb_mesh = sm.bounding_box_oriented + + # set visual geom path, copy to visual folder + # model_file = os.path.basename(model_path) + obj_name = os.path.basename(obj_file)[:-4] + vis_geom_path = os.path.join(vis_path, "{}_{}.obj".format(obj_name, sm_i)) + # shutil.copyfile( + # obj_file, + # vis_geom_path, + # ) + sm.export(vis_geom_path) + + vis_geom = dict( + obj_type="visual", + geom_type="mesh", + path=vis_geom_path, + name="{}_{}_vis".format(obj_name, sm_i), + material=sm_name, + # **get_bb_info(sm.bounding_box_oriented) + ) + geoms.append(vis_geom) + + if visual_only: + continue + + ch_mesh = sm.convex_hull + # bb_mesh = ch_mesh.bounding_box_oriented + + # obj_name = os.path.basename(obj_file)[:-3] + coll_geom_path = os.path.join(coll_path, "{}_{}.obj".format(obj_name, sm_i)) + coll_geom = dict( + obj_type="collision", + geom_type="mesh", + # path=os.path.join(coll_path, "{}_ch.stl".format(model_name)), + path=coll_geom_path, + name="{}_{}_coll".format(obj_name, sm_i), + **get_bb_info(ch_mesh.bounding_box_oriented), + ) + geoms.append(coll_geom) + ch_mesh.export(coll_geom["path"]) + + return geoms, textures, materials, transform + + +def parse_coll_model( + coll_model_path, + asset_path, + verbose=False, + transform=None, +): + """ + Extract list of primitive geoms from collision model file + """ + + if coll_model_path is None: + return None, None + + LogUtils.maybe_log_info( + "parsing collision model: {}".format(coll_model_path), + log=verbose, + indent=True, + ) + + # load the model + obj_files = [ + os.path.join(coll_model_path, name) + for name in os.listdir(coll_model_path) + if name.endswith(".obj") + ] + + geoms = [] + coll_path = os.path.join(asset_path, "collision") + + scene = trimesh.scene.scene.Scene() + + for obj_file in obj_files: + resolver = trimesh.resolvers.FilePathResolver(os.path.dirname(obj_file)) + model = trimesh.load(obj_file, resolver=resolver) + + if transform is not None: + model.apply_transform(transform) + model.export(obj_file) + + # ch_mesh = model.convex_hull + # bb_mesh = ch_mesh.bounding_box_oriented + + scene.add_geometry(model) + + if not os.path.isdir(coll_path): + os.makedirs(coll_path) + + # set visual geom path, copy to visual folder + # model_file = os.path.basename(model_path) + obj_name = os.path.basename(obj_file)[:-3] + coll_geom_path = os.path.join(coll_path, os.path.basename(obj_file)) + # shutil.copyfile( + # obj_file, + # coll_geom_path, + # ) + + # obj_name = os.path.basename(obj_file)[:-3] + coll_geom = dict( + obj_type="collision", + geom_type="mesh", + # path=os.path.join(coll_path, "{}_ch.stl".format(model_name)), + path=coll_geom_path, + name="{}_coll".format(obj_name), + # **get_bb_info(bb_mesh) + ) + geoms.append(coll_geom) + + bb_info = get_bb_info(scene.bounding_box) + + # f = open(coll_model_path, "r") + # lines = f.readlines() + # f.close() + + # geoms = [] + + # start_inds = [i for (i, line) in enumerate(lines) if line.startswith("o ")] + + # num_coll_meshes = 0 + # for start, end in zip(start_inds, start_inds[1:] + [len(lines)]): + # obj_lines = lines[start:end] + + # # filter out lines corresponding to faces + # obj_lines_filtered = [line for line in obj_lines if not line.startswith("f ")] + + # geom = dict() + + # tmp = tempfile.NamedTemporaryFile(suffix=".obj") + # with open(tmp.name, "w") as f: + # [f.write(line) for line in obj_lines_filtered] + + # mesh = trimesh.load(tmp.name) + + # bb_mesh = mesh.bounding_box_oriented + + # geom.update( + # obj_name=obj_lines[0], + # obj_type="collision", + # **get_bb_info(bb_mesh) + # ) + + # obj_type_substr = obj_lines_filtered[0][2:] + # if obj_type_substr.startswith("Cube"): + # geom_type = "box" + # elif obj_type_substr.startswith("Cylinder"): + # geom_type = "cylinder" + + # """ + # post-process size and orientation of cylinder + # """ + + # pos = geom["pos"] + # quat = geom["quat"] + # size = geom["size"] + + # T = bb_mesh.primitive.transform + + # trans_mesh = mesh.copy() + # trans_mesh.apply_transform(np.linalg.inv(T)) + + # V = np.array(trans_mesh.vertices) + # n = len(V) # number of vertices + # th = 1e-5 # threshold for checking vertices + + # upright_axis = None + # for idx in [0, 1, 2]: + # V = np.take(V, indices=np.argsort(V, axis=0)[:,idx], axis=0) + + # if np.std(V[:n//2,idx]) < th and np.std(V[-n//2:,idx]) < th: + # upright_axis = idx + + # assert upright_axis is not None + # circle_axes = np.delete(np.arange(3), upright_axis) + # assert np.abs(size[circle_axes][1] - size[circle_axes][0]) < 0.01, ( + # "Detected elliptic cylinder! " + # "Mujoco only accepts circular cylinders." + # ) + + # if upright_axis == 0: + # geom["quat"] = mat2quat( + # np.linalg.inv( + # np.matmul( + # np.array([ + # [0, 0, 1], + # [0, 1, 0], + # [-1, 0, 0], + # ]), + # np.linalg.inv(geom["rot_orig"]) + # ) + # ) + # )[[3,0,1,2]] + # elif upright_axis == 1: + # raise NotImplementedError + + # geom["size"] = [np.mean(size[circle_axes]), size[upright_axis]] + + # elif obj_type_substr.startswith("Sphere"): + # geom_type = "ellipsoid" + # else: + # raise ValueError( + # "Detected non-primitive object in collision model:", + # obj_lines_filtered[0] + # ) + + # geom["geom_type"] = geom_type + + # geoms.append(geom) + + return geoms, bb_info + + +def get_geom_element(model_name, geom_info, sc=1.0, show_if_coll_geom=False): + """ + Generate xml element for mjcf geom + """ + + if geom_info.get("hide", False): + return None + + elem = ET.Element("geom") + + elem.attrib["solimp"] = "0.998 0.998 0.001" + elem.attrib["solref"] = "0.001 1" + elem.attrib["density"] = "100" + elem.attrib["friction"] = "0.95 0.3 0.1" + + if geom_info["geom_type"] == "mesh": + elem.attrib["type"] = "mesh" + elem.attrib["mesh"] = geom_info["name"] + else: + raise NotImplementedError + elem.attrib["type"] = geom_info["geom_type"] + elem.attrib["pos"] = " ".join(["{:.5f}".format(v * sc) for v in geom_info["pos"]]) + elem.attrib["quat"] = " ".join(["{:.5f}".format(v) for v in geom_info["quat"]]) + size = geom_info["size"] + elem.attrib["size"] = " ".join(["{:.5f}".format(v * sc / 2) for v in size]) + + if geom_info["obj_type"] == "visual": + elem.attrib["conaffinity"] = "0" + elem.attrib["contype"] = "0" + elem.attrib["group"] = "1" + elem.attrib["material"] = geom_info.get("material", model_name) + elif geom_info["obj_type"] == "collision": + elem.attrib["group"] = "0" + # elem.attrib["condim"] = "4" + + if show_if_coll_geom: + elem.attrib["rgba"] = "0.8 0.8 0.8 0.3" + else: + elem.attrib["rgba"] = "0.8 0.8 0.8 0.0" + + return elem + + +def get_texture_element(texture_info): + elem = ET.Element("texture") + + for k, v in texture_info.items(): + elem.attrib[k] = str(v) + + return elem + + +def get_material_element(material_info): + elem = ET.Element("material") + + for k, v in material_info.items(): + elem.attrib[k] = str(v) + + return elem + + +def get_mesh_element(geom_info, sc=1.0): + """ + Generate xml element for mjcf mesh asset + """ + assert geom_info["geom_type"] == "mesh" + + if geom_info.get("hide", False): + return None + + elem = ET.Element("mesh") + + elem.attrib["file"] = "/".join(geom_info["path"].split("/")[-2:]) + elem.attrib["name"] = geom_info["name"] + elem.attrib["scale"] = "{sc} {sc} {sc}".format(sc=sc) + + return elem + + +def generate_mjcf( + asset_path, + model_name, + model_info, + sc=1.0, + texture_path=None, + hide_vis_geoms=False, + show_coll_geoms=False, + show_sites=False, + verbose=False, +): + """ + Generate mjcf model for object + """ + + LogUtils.maybe_log_info("Generating MJCF...", log=verbose) + + geoms = model_info["geoms"] + textures = model_info["textures"] + materials = model_info["materials"] + bb_info = model_info["bb"] + + ### for now, assume mtl doesn't contain texture #### + # texture_from_mtl = False + # if texture_path is None: + # # get the texture used in the mtl file + # mtl_path = model_path[:-3] + 'mtl' + # texture_dict = {} + # with open(mtl_path, "r") as f: + # for i, line in enumerate(f.readlines()): + # if len(line) > 1: + # key, value = line.split(" ", 1) + # texture_dict[key] = value.strip() + # + # if "map_Kd" in texture_dict: + # texture_path = texture_dict["map_Kd"] + # texture_from_mtl = True + + # load template xml + tree = ET.parse( + os.path.join(os.path.dirname(os.path.realpath(__file__)), "object_template.xml") + ) + root = tree.getroot() + + # set model name + root.attrib["model"] = model_name + + # add mesh assets + asset = root.find("asset") + for geom in geoms: + if geom["geom_type"] == "mesh": + mesh_elem = get_mesh_element(geom, sc=sc) + if mesh_elem is not None: + asset.append(mesh_elem) + + # update default texture and material assets + texture = asset.find("texture") + texture.attrib["name"] = texture.attrib["name"].replace("template", model_name) + if texture_path is not None: + texture.attrib["file"] = "/".join(texture_path.split("/")[-1:]) + else: + texture.attrib["file"] = os.path.join( + os.path.dirname(robosuite.__file__), "models/assets/textures/ceramic.png" + ) + material = asset.find("material") + for k in ["name", "texture"]: + material.attrib[k] = material.attrib[k].replace("template", model_name) + + # add textures + for texture in textures: + texture_elem = get_texture_element(texture) + if texture_elem is not None: + asset.append(texture_elem) + + # add materials + for material in materials: + material_elem = get_material_element(material) + if material_elem is not None: + asset.append(material_elem) + + # add geoms + worldbody = root.find("worldbody") + body = worldbody.find("body").find("body") + for geom in geoms: + if geom["obj_type"] == "visual" and hide_vis_geoms: + continue + + geom_elem = get_geom_element( + model_name, + geom, + sc=sc, + show_if_coll_geom=show_coll_geoms, + ) + if geom_elem is not None: + body.append(geom_elem) + + sites = worldbody.find("body").findall("site") + + if show_sites: + object_body = worldbody.find("body").find("body") + vis_site_strings = [ + """""", + """""", + """""", + ] + for s in vis_site_strings: + object_body.append(ET.fromstring(s)) + + # for debugging + vis_sites = object_body.findall("site") + sites = sites + vis_sites + + if bb_info is not None: + for site in sites: + if site.get("name") == "horizontal_radius_site": + pos = bb_info["pos"].copy() + pos[0] += bb_info["size"][0] / 2 + pos[1] += bb_info["size"][1] / 2 + pos = np.array([pos[0], pos[1], pos[2]]) + site.set("pos", array_to_string(pos * sc)) + elif site.get("name") == "bottom_site": + pos = bb_info["pos"].copy() + pos[2] -= bb_info["size"][2] / 2 + pos = np.array([pos[0], pos[1], pos[2]]) + site.set("pos", array_to_string(pos * sc)) + elif site.get("name") == "top_site": + pos = bb_info["pos"].copy() + pos[2] += bb_info["size"][2] / 2 + pos = np.array([pos[0], pos[1], pos[2]]) + site.set("pos", array_to_string(pos * sc)) + + # save xml for new model + mjcf_path = os.path.join(asset_path, "model.xml") + tree.write(mjcf_path, encoding="utf-8") + LogUtils.maybe_log_info("Wrote MJCF to: {}".format(mjcf_path), log=verbose, indent=True) + + # LogUtils.maybe_log_info( + # "\nTest generated MJCF with robosuite:\npython {base_path}/scripts/object_play.py --device spacemouse --mjcf_path {mjcf_path}".format( + # base_path=os.path.dirname(robosuite_model_zoo.__file__), + # mjcf_path=mjcf_path, + # ), + # log=True, + # color="green" + # ) + + return mjcf_path + + +def get_file_name_and_type(path): + """ + Extract name of object model file and file format + """ + split_name = os.path.basename(path).split(".") + assert len(split_name) == 2 + return split_name[0], split_name[1] + + +def get_bb_info(bb_mesh): + """ + Extract size, position, and orientation (quat) from bounding box mesh + """ + ext = np.array(bb_mesh.primitive.extents) + transform = np.array(bb_mesh.primitive.transform) + + center = transform[:-1, 3] + rot = transform[:3, :3] + quat = mat2quat(rot)[[3, 0, 1, 2]] + + return dict( + pos=center, + quat=quat, + size=ext, + rot_orig=rot, + ) + + +def decompose_convex( + filename, + work_dir, + # V-HACD params + max_output_convex_hulls=32, + voxel_resolution=100000, + volume_error_percent=1.0, + max_hull_vert_count=64, +): + """ + Adapted from https://github.com/kevinzakka/obj2mjcf/blob/main/obj2mjcf/_cli.py + """ + + _VHACD_EXECUTABLE = shutil.which("TestVHACD") + _VHACD_OUTPUTS = ["decomp.obj", "decomp.stl"] + + obj_file = filename.resolve() + + import tempfile + import subprocess + from pathlib import Path + import enum + + with tempfile.TemporaryDirectory() as tmpdirname: + prev_dir = os.getcwd() + os.chdir(tmpdirname) + + # Copy the obj file to the temporary directory. + shutil.copy(obj_file, tmpdirname) + + # Call V-HACD, suppressing output. + ret = subprocess.run( + [ + f"{_VHACD_EXECUTABLE}", + obj_file.name, + "-o", + "obj", + "-h", + f"{max_output_convex_hulls}", # max_output_convex_hulls + "-r", + f"{voxel_resolution}", # voxel_resolution + "-e", + f"{volume_error_percent}", # volume_error_percent + "-d", + f"{14}", # max_recursion_depth + "-s", + f"{int(not False)}", # disable_shrink_wrap + # "-f", + # f"{enum.auto().name.lower()}", # fill_mode.name.lower() + "-v", + f"{max_hull_vert_count}", # max_hull_vert_count + "-a", + f"{int(not False)}", # disable_async + "-l", + f"{2}", # min_edge_length + "-p", + f"{int(False)}", # split_hull + ], + # stdout=subprocess.DEVNULL, + # stderr=subprocess.STDOUT, + check=True, + ) + # if ret.returncode != 0: + # logging.error(f"V-HACD failed on {filename}") + # return False + + # Remove the original obj file and the V-HACD output files. + for name in _VHACD_OUTPUTS + [obj_file.name]: + file_to_delete = Path(tmpdirname) / name + if file_to_delete.exists(): + file_to_delete.unlink() + + os.chdir(prev_dir) + + # Get list of sorted collisions. + collisions = list(Path(tmpdirname).glob("*.obj")) + collisions.sort(key=lambda x: x.stem) + + os.makedirs(work_dir.resolve(), exist_ok=True) + + for i, filename in enumerate(collisions): + savename = str(work_dir / f"{obj_file.stem}_collision_{i}.obj") + shutil.move(str(filename), savename) + + return True diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_obj.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_obj.py new file mode 100644 index 0000000000000000000000000000000000000000..12faf382ab3aa79bf72104718509f9efb6f62fce --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mjcf_obj.py @@ -0,0 +1,251 @@ +import os +import time +import numpy as np +import tempfile +import random +import string +import xml.etree.ElementTree as ET + +import robosuite + +from robosuite.models.objects import MujocoXMLObject +from robosuite.utils.mjcf_utils import array_to_string, string_to_array + +import robosuite.utils.transform_utils as T + +import robosuite_model_zoo + + +def postprocess_model_xml(xml_str): + """ + New version of postprocess model xml that only replaces robosuite file paths if necessary (otherwise + there is an error with the "max" operation), and also replaces robosuite-model-zoo file paths + if necessary. + """ + + path = os.path.split(robosuite.__file__)[0] + path_split = path.split("/") + + # replace mesh and texture file paths + tree = ET.fromstring(xml_str) + root = tree + asset = root.find("asset") + meshes = asset.findall("mesh") + textures = asset.findall("texture") + all_elements = meshes + textures + + for elem in all_elements: + old_path = elem.get("file") + if old_path is None: + continue + + old_path_split = old_path.split("/") + # maybe replace all paths to robosuite assets + check_lst = [loc for loc, val in enumerate(old_path_split) if val == "robosuite"] + if len(check_lst) > 0: + ind = max(check_lst) # last occurrence index + new_path_split = path_split + old_path_split[ind + 1 :] + new_path = "/".join(new_path_split) + elem.set("file", new_path) + + # maybe replace all paths to robosuite model zoo assets + check_lst = [ + loc for loc, val in enumerate(old_path_split) if val == "robosuite-model-zoo-dev" + ] + if len(check_lst) > 0: + ind = max(check_lst) # last occurrence index + new_path_split = ( + os.path.split(robosuite_model_zoo.__file__)[0].split("/")[:-1] + + old_path_split[ind + 1 :] + ) + new_path = "/".join(new_path_split) + elem.set("file", new_path) + + return ET.tostring(root, encoding="utf8").decode("utf8") + + +class MJCFObject(MujocoXMLObject): + """ + Blender object with support for changing the scaling + """ + + def __init__( + self, + name, + mjcf_path, + scale=1.0, + solimp=(0.998, 0.998, 0.001), + solref=(0.001, 1), + density=100, + friction=(0.95, 0.3, 0.1), + margin=None, + rgba=None, + priority=None, + ): + # get scale in x, y, z + if isinstance(scale, float): + scale = [scale, scale, scale] + elif isinstance(scale, tuple) or isinstance(scale, list): + assert len(scale) == 3 + scale = tuple(scale) + else: + raise Exception("got invalid scale: {}".format(scale)) + scale = np.array(scale) + + self.solimp = solimp + self.solref = solref + self.density = density + self.friction = friction + self.margin = margin + + self.priority = priority + + self.rgba = rgba + + # read default xml + xml_path = mjcf_path + folder = os.path.dirname(xml_path) + tree = ET.parse(xml_path) + root = tree.getroot() + + # modify mesh scales + asset = root.find("asset") + meshes = asset.findall("mesh") + for mesh in meshes: + # if a scale already exists, multiply the scales + scale_to_set = scale + existing_scale = mesh.get("scale") + if existing_scale is not None: + scale_to_set = string_to_array(existing_scale) * scale + mesh.set("scale", array_to_string(scale_to_set)) + + # modify sites for collision (assumes we can just scale up the locations - may or may not work) + for n in ["bottom_site", "top_site", "horizontal_radius_site"]: + site = root.find("worldbody/body/site[@name='{}']".format(n)) + pos = string_to_array(site.get("pos")) + pos = scale * pos + site.set("pos", array_to_string(pos)) + + """ + # disable collision geoms + worldbody = root.find("worldbody") + from robosuite.utils.mjcf_utils import find_elements + geoms = find_elements( + root=worldbody, + tags="geom", + attribs={"group": "0"}, + return_first=False + ) + for g in geoms: + # g.set("group", "1") + g.set("mass", "0.0001") + g.set("conaffinity", "2") + g.set("contype", "2") + """ + + # write modified xml (and make sure to postprocess any paths just in case) + xml_str = ET.tostring(root, encoding="utf8").decode("utf8") + xml_str = postprocess_model_xml(xml_str) + time_str = str(time.time()).replace(".", "_") + new_xml_path = os.path.join(folder, "{}_{}.xml".format(time_str, os.getpid())) + f = open(new_xml_path, "w") + f.write(xml_str) + f.close() + # print(f"Write to {new_xml_path}") + + # initialize object with new xml we wrote + super().__init__( + # xml_path_completion("objects/{}.xml".format(obj_name)), + fname=new_xml_path, + name=name, + joints=[dict(type="free", damping="0.0005")], + # joints=None, + obj_type="all", + duplicate_collision_geoms=False, + ) + + # clean up xml - we don't need it anymore + if os.path.exists(new_xml_path): + os.remove(new_xml_path) + + def _get_geoms(self, root, _parent=None): + """ + Helper function to recursively search through element tree starting at @root and returns + a list of (parent, child) tuples where the child is a geom element + + Args: + root (ET.Element): Root of xml element tree to start recursively searching through + _parent (ET.Element): Parent of the root element tree. Should not be used externally; only set + during the recursive call + + Returns: + list: array of (parent, child) tuples where the child element is a geom type + """ + geom_pairs = super(MJCFObject, self)._get_geoms(root=root, _parent=_parent) + + # modify geoms according to the attributes + for i, (parent, element) in enumerate(geom_pairs): + element.set("solref", array_to_string(self.solref)) + element.set("solimp", array_to_string(self.solimp)) + element.set("density", str(self.density)) + element.set("friction", array_to_string(self.friction)) + if self.margin is not None: + element.set("margin", str(self.margin)) + + if (self.rgba is not None) and (element.get("group") == "1"): + element.set("rgba", array_to_string(self.rgba)) + + if self.priority is not None: + # set high priorit + element.set("priority", str(self.priority)) + + return geom_pairs + + @property + def horizontal_radius(self): + horizontal_radius_site = self.worldbody.find( + "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) + ) + site_values = string_to_array(horizontal_radius_site.get("pos")) + return np.linalg.norm(site_values[0:2]) + + def get_bbox_points(self, trans=None, rot=None): + """ + Get the full 8 bounding box points of the object + rot: a rotation matrix + """ + bbox_offsets = [] + + bottom_offset = self.bottom_offset + top_offset = self.top_offset + horizontal_radius_site = self.worldbody.find( + "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) + ) + horiz_radius = string_to_array(horizontal_radius_site.get("pos"))[:2] + + center = np.mean([bottom_offset, top_offset], axis=0) + half_size = [horiz_radius[0], horiz_radius[1], top_offset[2] - center[2]] + + # center = np.array([0, 0, 0]) + # half_size = np.array([0.01, 0.01, 0.01]) + + bbox_offsets = [ + center + half_size * np.array([-1, -1, -1]), # p0 + center + half_size * np.array([1, -1, -1]), # px + center + half_size * np.array([-1, 1, -1]), # py + center + half_size * np.array([-1, -1, 1]), # pz + center + half_size * np.array([1, 1, 1]), + center + half_size * np.array([-1, 1, 1]), + center + half_size * np.array([1, -1, 1]), + center + half_size * np.array([1, 1, -1]), + ] + + if trans is None: + trans = np.array([0, 0, 0]) + if rot is not None: + rot = T.quat2mat(rot) + else: + rot = np.eye(3) + + points = [(np.matmul(rot, p) + trans) for p in bbox_offsets] + return points diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mtl_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mtl_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d5176049778be9fbfe2ace60d374a93128740146 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/mtl_utils.py @@ -0,0 +1,198 @@ +""" +Much of this code is directly copied from obj2mjcf: +https://github.com/kevinzakka/obj2mjcf/blob/main/obj2mjcf/_cli.py + +Credit: Kevin Zakka +""" + +from dataclasses import dataclass +from typing import Optional, Sequence +from PIL import Image +from pathlib import Path + +import os +import shutil + +# MTL fields relevant to MuJoCo. +_MTL_FIELDS = ( + # Ambient, diffuse and specular colors. + "Ka", + "Kd", + "Ks", + # d or Tr are used for the rgba transparency. + "d", + "Tr", + # Shininess. + "Ns", + # References a texture file. + "map_Kd", +) + +# Character used to denote a comment in an MTL file. +_MTL_COMMENT_CHAR = "#" + + +@dataclass +class Material: + name: str + Ka: Optional[str] = None + Kd: Optional[str] = None + Ks: Optional[str] = None + d: Optional[str] = None + Tr: Optional[str] = None + Ns: Optional[str] = None + map_Kd: Optional[str] = None + + @staticmethod + def from_string(lines: Sequence[str]) -> "Material": + """Construct a Material object from a string.""" + attrs = {"name": lines[0].split(" ")[1].strip()} + for line in lines[1:]: + for attr in _MTL_FIELDS: + if line.startswith(attr): + elems = line.split(" ")[1:] + elems = [elem for elem in elems if elem != ""] + attrs[attr] = " ".join(elems) + break + return Material(**attrs) + + def mjcf_rgba(self) -> str: + Kd = self.Kd or "1.0 1.0 1.0" + if self.d is not None: # alpha + alpha = self.d + elif self.Tr is not None: # 1 - alpha + alpha = str(1.0 - float(self.Tr)) + else: + alpha = "1.0" + # alpha = "1.0" + # TODO(kevin): Figure out how to use Ka for computing rgba. + return f"{Kd} {alpha}" + + def mjcf_shininess(self) -> str: + if self.Ns is not None: + # Normalize Ns value to [0, 1]. Ns values normally range from 0 to 1000. + Ns = float(self.Ns) / 1_000 + else: + Ns = 0.5 + return f"{Ns}" + + def mjcf_specular(self) -> str: + if self.Ks is not None: + # Take the average of the specular RGB values. + Ks = sum(list(map(float, self.Ks.split(" ")))) / 3 + else: + Ks = 0.5 + return f"{Ks}" + + +def get_mtls(filename, work_dir): + filename = Path(filename) + work_dir = Path(work_dir) + + process_mtl = False + with open(filename, "r") as f: + for line in f.readlines(): + if line.startswith("mtllib"): # Deals with commented out lines. + process_mtl = True + name = line.split()[1] + break + + sub_mtls: List[List[str]] = [] + mtls: List[Material] = [] + if process_mtl: + # Make sure the MTL file exists. The MTL filepath is relative to the OBJ's. + mtl_filename = filename.parent / name + if not mtl_filename.exists(): + raise RuntimeError( + f"The MTL file {mtl_filename.resolve()} referenced in the OBJ file " + f"{filename} does not exist" + ) + # logging.info(f"Found MTL file: {mtl_filename}") + + # Parse the MTL file into separate materials. + with open(mtl_filename, "r") as f: + lines = f.readlines() + # Remove comments. + lines = [line for line in lines if not line.startswith(_MTL_COMMENT_CHAR)] + # Remove empty lines. + lines = [line for line in lines if line.strip()] + # Remove trailing whitespace. + lines = [line.strip() for line in lines] + # Split at each new material definition. + for line in lines: + if line.startswith("newmtl"): + sub_mtls.append([]) + sub_mtls[-1].append(line) + for sub_mtl in sub_mtls: + mtls.append(Material.from_string(sub_mtl)) + + # Process each material. + for mtl in mtls: + # logging.info(f"Found material: {mtl.name}") + if mtl.map_Kd is not None: + texture_path = Path(mtl.map_Kd) + texture_name = texture_path.name + src_filename = filename.parent / texture_path + if not src_filename.exists(): + raise RuntimeError( + f"The texture file {src_filename} referenced in the MTL file " + f"{mtl.name} does not exist" + ) + # We want a flat directory structure in work_dir. + dst_filename = work_dir / texture_name + shutil.copy(src_filename, dst_filename) + # MuJoCo only supports PNG textures ¯\_(ツ)_/¯. + if texture_path.suffix.lower() in [".jpg", ".jpeg"]: + image = Image.open(dst_filename) + os.remove(dst_filename) + dst_filename = (work_dir / texture_path.stem).with_suffix(".png") + image.save(dst_filename) + texture_name = dst_filename.name + mtl.map_Kd = texture_name + resize_texture(dst_filename, 1.0) + # logging.info("Done processing MTL file") + + return mtls + + +def resize_texture(filename: Path, resize_percent) -> None: + """Resize a texture to a percentage of its original size.""" + if resize_percent == 1.0: + return + image = Image.open(filename) + new_width = int(image.size[0] * resize_percent) + new_height = int(image.size[1] * resize_percent) + logging.info(f"Resizing {filename} to {new_width}x{new_height}") + image = image.resize((new_width, new_height), Image.LANCZOS) + image.save(filename) + + +def get_image_paths(mtl_path): + image_paths = [] + + # Parse the MTL file into separate materials. + with open(mtl_path, "r") as f: + lines = f.readlines() + # Remove comments. + lines = [line for line in lines if not line.startswith(_MTL_COMMENT_CHAR)] + # Remove empty lines. + lines = [line for line in lines if line.strip()] + # Remove trailing whitespace. + lines = [line.strip() for line in lines] + # Split at each new material definition. + + sub_mtls = [] + + for line in lines: + if line.startswith("newmtl"): + sub_mtls.append([]) + sub_mtls[-1].append(line) + for sub_mtl in sub_mtls: + # print(sub_mtl) + + path = Material.from_string(sub_mtl).map_Kd + + if path is not None: + image_paths.append(path) + + return image_paths diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_play_env.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_play_env.py new file mode 100644 index 0000000000000000000000000000000000000000..22ed17c713fbbb15de74df77796d9d7e65cc22f5 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_play_env.py @@ -0,0 +1,250 @@ +import numpy as np + +from robosuite.environments.manipulation.single_arm_env import SingleArmEnv +from robosuite.models.arenas import TableArena +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.placement_samplers import UniformRandomSampler + +from robocasa.utils.model_zoo.mjcf_obj import MJCFObject +from robosuite.models.objects import BoxObject + +import robosuite.utils.transform_utils as T + + +class ObjectPlayEnv(SingleArmEnv): + def __init__( + self, + robots, + obj_mjcf_path, + obj_scale=1.0, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + table_full_size=(0.8, 0.8, 0.05), + table_friction=(1.0, 5e-3, 1e-4), + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + placement_initializer=None, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + x_range=(-0.03, 0.03), + y_range=(-0.03, 0.03), + rotation=None, + num_objects=1, + ): + # settings for table top + self.table_full_size = table_full_size + self.table_friction = table_friction + self.table_offset = np.array((0, 0, 0.8)) + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + # object placement initializer + self.placement_initializer = placement_initializer + + self._obj_mjcf_path = obj_mjcf_path + self._obj_scale = obj_scale + self._x_range = x_range + self._y_range = y_range + self._rotation = rotation + self._num_objects = num_objects + + self._cam_configs = dict( + agentview=dict( + pos=[0, -0.5, 1.35], + quat=T.convert_quat( + np.array([0.3826834, 0, 0, 0.9238795]), + to="wxyz", + ), + ), + ) + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + mount_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + ) + + def reward(self, action=None): + reward = 0.0 + + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose accordingly + # xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + # self.robots[0].robot_model.set_base_xpos(xpos) + ### logic copied from kitchen.py to rotate robot around ### + for robot, rotation, offset in zip(self.robots, (-np.pi / 2,), (0,)): + xpos = robot.robot_model.base_xpos_offset["table"](self.table_full_size[0]) + rot = np.array((0, 0, rotation)) + xpos = T.euler2mat(rot) @ np.array(xpos) + xpos += np.array((0, offset, 0)) + robot.robot_model.set_base_xpos(xpos) + robot.robot_model.set_base_ori(rot) + + # load model for table top workspace + self.mujoco_arena = TableArena( + table_full_size=self.table_full_size, + table_friction=self.table_friction, + table_offset=self.table_offset, + ) + + # Arena always gets set to zero origin + self.mujoco_arena.set_origin([0, 0, 0]) + + self.set_cameras() + + objects = [] + for obj_num in range(self._num_objects): + if self._obj_mjcf_path == "cube": + # debugging case using primitive geom + obj = BoxObject( + name="cube_{}".format(obj_num), + size_min=[0.020, 0.020, 0.020], # [0.015, 0.015, 0.015], + size_max=[0.022, 0.022, 0.022], # [0.018, 0.018, 0.018]) + rgba=[1, 0, 0, 1], + ) + else: + obj = MJCFObject( + name="MCJFObj_{}".format(obj_num), + mjcf_path=self._obj_mjcf_path, + scale=self._obj_scale, + ) + + objects.append(obj) + + # Create placement initializer + if self.placement_initializer is not None: + self.placement_initializer.reset() + self.placement_initializer.add_objects(objects) + else: + self.placement_initializer = UniformRandomSampler( + name="ObjectSampler", + mujoco_objects=objects, + x_range=self._x_range, + y_range=self._y_range, + rotation=self._rotation, + ensure_object_boundary_in_range=False, + ensure_valid_placement=True, + reference_pos=self.table_offset, + z_offset=0.01, + # # for debugging + # x_range=(0, 0), + # y_range=(0, 0), + # rotation=(0, 0), + ) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=self.mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=objects, + ) + + # def _setup_references(self): + # """ + # Sets up references to important components. A reference is typically an + # index or a list of indices that point to the corresponding elements + # in a flatten array, which is how MuJoCo stores physical simulation data. + # """ + # super()._setup_references() + + # # Additional object references from this env + # self.obj_body_id = self.sim.model.body_name2id(self.mjcf_obj.root_body) + + def set_cameras(self): + """ + copied from environments/manipulation/kitchen.py + """ + for cam_name, cam_cfg in self._cam_configs.items(): + if cam_cfg.get("parent_body", None) is not None: + continue + + self.mujoco_arena.set_camera( + camera_name=cam_name, pos=cam_cfg["pos"], quat=cam_cfg["quat"] + ) + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + # self.sim.model.body_pos[self.sim.model.body_name2id(obj.root_body)] = obj_pos + # self.sim.model.body_quat[self.sim.model.body_name2id(obj.root_body)] = obj_quat + + self.sim.data.set_joint_qpos( + obj.joints[0], + np.concatenate([np.array(obj_pos), np.array(obj_quat)]), + ) + + # def visualize(self, vis_settings): + # """ + # In addition to super call, visualize gripper site proportional to the distance to the cube. + # + # Args: + # vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + # component should be visualized. Should have "grippers" keyword as well as any other relevant + # options specified. + # """ + # # Run superclass method first + # super().visualize(vis_settings=vis_settings) + # + # # Color the gripper visualization site according to its distance to the cube + # if vis_settings["grippers"]: + # self._visualize_gripper_to_target(gripper=self.robots[0].gripper, target=self.cube) + + def _check_success(self): + return False diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_template.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_template.xml new file mode 100644 index 0000000000000000000000000000000000000000..986e66ffb6df37968b604ab9b39926be136c95ca --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/object_template.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/parser_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/parser_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..83ca6b4114f6451fd16d1f08baa13e892346d403 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/model_zoo/parser_utils.py @@ -0,0 +1,61 @@ +import argparse + + +def get_base_parser(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--base_asset_path", + type=str, + help="(optional) base asset path where model files are stored. " + "Defaults to robosuite_model_zoo/assets_private folder.", + ) + parser.add_argument( + "--model_folder", + type=str, + help="(optional) folder to store model (relative to base asset path). " "Defaults to None.", + ) + parser.add_argument( + "--model_name", + type=str, + help="(optional) name of saved mjcf model. " "Defaults to name from --model_path.", + ) + parser.add_argument( + "--scale", + type=float, + default=1.0, + help="1d scaling of input model", + ) + parser.add_argument( + "--show_sites", + action="store_true", + help="show model bounds sites", + ) + parser.add_argument( + "--verbose", + action="store_true", + help="print detailed information for debugging", + ) + + ### V-HACD settings ### + parser.add_argument( + "--vhacd_max_output_convex_hulls", + type=float, + default=32, + ) + parser.add_argument( + "--vhacd_voxel_resolution", + type=float, + default=100000, + ) + parser.add_argument( + "--vhacd_volume_error_percent", + type=float, + default=1.0, + ) + parser.add_argument( + "--vhacd_max_hull_vert_count", + type=float, + default=64, + ) + + return parser diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/object_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/object_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0ef5bef716a805f90634c2714d3b71a596f5d963 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/object_utils.py @@ -0,0 +1,621 @@ +import numpy as np +import mujoco as mj +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string + +from robocasa.models.objects.objects import MJCFObject + + +def obj_inside_of(env, obj_name, fixture_id, partial_check=False): + """ + whether an object (another mujoco object) is inside of fixture. applies for most fixtures + """ + from robocasa.models.fixtures import Fixture + + obj = env.objects[obj_name] + fixture = env.get_fixture(fixture_id) + assert isinstance(obj, MJCFObject) + assert isinstance(fixture, Fixture) + + # step 1: calculate fxiture points + fixtr_p0, fixtr_px, fixtr_py, fixtr_pz = fixture.get_int_sites(relative=False) + u = fixtr_px - fixtr_p0 + v = fixtr_py - fixtr_p0 + w = fixtr_pz - fixtr_p0 + + # get the position and quaternion of object + obj_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[obj.name]]) + obj_quat = T.convert_quat(env.sim.data.body_xquat[env.obj_body_id[obj.name]], to="xyzw") + + if partial_check: + obj_points_to_check = [obj_pos] + th = 0.0 + else: + # calculate 8 boundary points of object + obj_points_to_check = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) + # threshold to mitigate false negatives: even if the bounding box point is out of bounds, + th = 0.05 + + inside_of = True + for obj_p in obj_points_to_check: + check1 = np.dot(u, fixtr_p0) - th <= np.dot(u, obj_p) <= np.dot(u, fixtr_px) + th + check2 = np.dot(v, fixtr_p0) - th <= np.dot(v, obj_p) <= np.dot(v, fixtr_py) + th + check3 = np.dot(w, fixtr_p0) - th <= np.dot(w, obj_p) <= np.dot(w, fixtr_pz) + th + + if not (check1 and check2 and check3): + inside_of = False + break + + return inside_of + + +# used for cabinets, cabinet panels, counters, etc. +def set_geom_dimensions(sizes, positions, geoms, rotated=False): + """ + set the dimensions of geoms in a fixture + + Args: + sizes (dict): dictionary of sizes for each side + + positions (dict): dictionary of positions for each side + + geoms (dict): dictionary of geoms for each side + + rotated (bool): whether the fixture is rotated. Fixture may be rotated to make texture appear uniform + due to mujoco texture conventions + """ + if rotated: + # rotation trick to make texture appear uniform + # see .xml file + for side in sizes.keys(): + # not the best detection method, TODO: check euler + if "door" in side or "trim" in side: + sizes[side] = [sizes[side][i] for i in [0, 2, 1]] + + # set sizes and positions of all geoms + for side in positions.keys(): + for geom in geoms[side]: + if geom is None: + raise ValueError("Did not find geom:", side) + geom.set("pos", array_to_string(positions[side])) + geom.set("size", array_to_string(sizes[side])) + + +def get_rel_transform(fixture_A, fixture_B): + """ + Gets fixture_B's position and rotation relative to fixture_A's frame + """ + A_trans = np.array(fixture_A.pos) + B_trans = np.array(fixture_B.pos) + + A_rot = np.array([0, 0, fixture_A.rot]) + B_rot = np.array([0, 0, fixture_B.rot]) + + A_mat = T.euler2mat(A_rot) + B_mat = T.euler2mat(B_rot) + + T_WA = np.vstack((np.hstack((A_mat, A_trans[:, None])), [0, 0, 0, 1])) + T_WB = np.vstack((np.hstack((B_mat, B_trans[:, None])), [0, 0, 0, 1])) + + T_AB = np.matmul(np.linalg.inv(T_WA), T_WB) + + return T_AB[:3, 3], T_AB[:3, :3] + + +def compute_rel_transform(A_pos, A_mat, B_pos, B_mat): + """ + Gets B's position and rotation relative to A's frame + """ + T_WA = np.vstack((np.hstack((A_mat, A_pos[:, None])), [0, 0, 0, 1])) + T_WB = np.vstack((np.hstack((B_mat, B_pos[:, None])), [0, 0, 0, 1])) + + T_AB = np.matmul(np.linalg.inv(T_WA), T_WB) + + return T_AB[:3, 3], T_AB[:3, :3] + + +def get_fixture_to_point_rel_offset(fixture, point): + """ + get offset relative to fixture's frame, given a global point + """ + global_offset = point - fixture.pos + T_WF = T.euler2mat([0, 0, fixture.rot]) + rel_offset = np.matmul(np.linalg.inv(T_WF), global_offset) + return rel_offset + + +def get_pos_after_rel_offset(fixture, offset): + """ + get global position of a fixture, after applying offset relative to center of fixture + """ + fixture_rot = np.array([0, 0, fixture.rot]) + fixture_mat = T.euler2mat(fixture_rot) + + return fixture.pos + np.dot(fixture_mat, offset) + + +def project_point_to_line(P, A, B): + """ + logic copied from here: https://stackoverflow.com/a/61342198 + """ + AP = P - A + AB = B - A + result = A + np.dot(AP, AB) / np.dot(AB, AB) * AB + + return result + + +def point_in_fixture(point, fixture, only_2d=False): + """ + check if point is inside of the exterior bounding boxes of the fixture + + Args: + point (np.array): point to check + + fixture (Fixture): fixture object + + only_2d (bool): whether to check only in 2D + """ + p0, px, py, pz = fixture.get_ext_sites(relative=False) + th = 0.00 + u = px - p0 + v = py - p0 + w = pz - p0 + check1 = np.dot(u, p0) - th <= np.dot(u, point) <= np.dot(u, px) + th + check2 = np.dot(v, p0) - th <= np.dot(v, point) <= np.dot(v, py) + th + check3 = np.dot(w, p0) - th <= np.dot(w, point) <= np.dot(w, pz) + th + + if only_2d: + return check1 and check2 + else: + return check1 and check2 and check3 + + +def obj_in_region( + obj, + obj_pos, + obj_quat, + p0, + px, + py, + pz=None, +): + """ + check if object is in the region defined by the points. + Uses either the objects bounding box or the object's horizontal radius + """ + from robocasa.models.fixtures import Fixture + + if isinstance(obj, MJCFObject) or isinstance(obj, Fixture): + obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) + else: + radius = obj.horizontal_radius + obj_points = obj_pos + np.array( + [ + [radius, 0, 0], + [-radius, 0, 0], + [0, radius, 0], + [0, -radius, 0], + ] + ) + + u = px - p0 + v = py - p0 + w = pz - p0 if pz is not None else None + + for point in obj_points: + check1 = np.dot(u, p0) <= np.dot(u, point) <= np.dot(u, px) + check2 = np.dot(v, p0) <= np.dot(v, point) <= np.dot(v, py) + + if not check1 or not check2: + return False + + if w is not None: + check3 = np.dot(w, p0) <= np.dot(w, point) <= np.dot(w, pz) + if not check3: + return False + + return True + + +def obj_in_region_with_keypoints( + obj, obj_pos, obj_quat, region_points, min_num_points=3, region_type="box" +): + """ + check if object is in the region defined by the keypoints. Only min_num_points points need to be in the region to return True. + Keypoints include the points of the object's bounding box and the center of the object. + region can be a box or a cylinder or a sphere + TODO: support plane region + """ + from robocasa.models.fixtures import Fixture + + if isinstance(obj, MJCFObject) or isinstance(obj, Fixture): + obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) + else: + radius = obj.horizontal_radius + obj_points = obj_pos + np.array( + [ + [radius, 0, 0], + [-radius, 0, 0], + [0, radius, 0], + [0, -radius, 0], + ] + ) + + # center points of object for each plane + obj_u = obj_points[1] - obj_points[0] + obj_v = obj_points[2] - obj_points[0] + obj_w = obj_points[3] - obj_points[0] + centers = [] + + # Front and back XY planes + center_xy_front = obj_points[0] + 0.5 * obj_u + 0.5 * obj_v + center_xy_back = center_xy_front + obj_w + centers.extend([center_xy_front, center_xy_back]) + + if obj_w is not None: + # Left and right XZ planes + center_xz_left = obj_points[0] + 0.5 * obj_u + 0.5 * obj_w + center_xz_right = center_xz_left + obj_v + centers.extend([center_xz_left, center_xz_right]) + + # Top and bottom YZ planes + center_yz_top = obj_points[0] + 0.5 * obj_v + 0.5 * obj_w + center_yz_bottom = center_yz_top + obj_u + centers.extend([center_yz_top, center_yz_bottom]) + + center_point = np.mean(obj_points, axis=0) + centers.append(center_point) + obj_points = np.concatenate([obj_points, centers]) + + # Erode the bounding box by pulling points 10% closer to the center + # Avoids false negatives when object is near the edge of the region + obj_points = obj_points * 0.8 + center_point * 0.2 + + if region_type == "box": + if len(region_points) == 4: + p0, px, py, pz = region_points + elif len(region_points) == 3: + p0, px, py = region_points + pz = None + else: + raise ValueError(f"Invalid number of region points: {len(region_points)}") + return obj_in_box_region(obj_points, p0, px, py, pz, min_num_points) + elif region_type == "cylinder": + p0, axis_vector, radius = region_points + return obj_in_cylinder_region(obj_points, p0, axis_vector, radius, min_num_points) + elif region_type == "sphere": + p0, radius = region_points + return obj_in_sphere_region(obj_points, p0, radius, min_num_points) + + +def fixture_pairwise_dist(f1, f2): + """ + Gets the distance between two fixtures by finding the minimum distance between their exterior bounding box points + """ + f1_points = f1.get_ext_sites(all_points=True, relative=False) + f2_points = f2.get_ext_sites(all_points=True, relative=False) + + all_dists = [np.linalg.norm(p1 - p2) for p1 in f1_points for p2 in f2_points] + return np.min(all_dists) + + +def objs_intersect( + obj, + obj_pos, + obj_quat, + other_obj, + other_obj_pos, + other_obj_quat, +): + """ + check if two objects intersect + """ + from robocasa.models.fixtures import Fixture + + bbox_check = (isinstance(obj, MJCFObject) or isinstance(obj, Fixture)) and ( + isinstance(other_obj, MJCFObject) or isinstance(other_obj, Fixture) + ) + if bbox_check: + obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) + other_obj_points = other_obj.get_bbox_points(trans=other_obj_pos, rot=other_obj_quat) + + face_normals = [ + obj_points[1] - obj_points[0], + obj_points[2] - obj_points[0], + obj_points[3] - obj_points[0], + other_obj_points[1] - other_obj_points[0], + other_obj_points[2] - other_obj_points[0], + other_obj_points[3] - other_obj_points[0], + ] + + intersect = True + + # noramlize length of normals + for normal in face_normals: + normal = np.array(normal) / np.linalg.norm(normal) + + obj_projs = [np.dot(p, normal) for p in obj_points] + other_obj_projs = [np.dot(p, normal) for p in other_obj_points] + + # see if gap detected + if np.min(other_obj_projs) > np.max(obj_projs) or np.min(obj_projs) > np.max( + other_obj_projs + ): + intersect = False + break + else: + """ + old code from placement_samplers.py + """ + obj_x, obj_y, obj_z = obj_pos + other_obj_x, other_obj_y, other_obj_z = other_obj_pos + xy_collision = ( + np.linalg.norm((obj_x - other_obj_x, obj_y - other_obj_y)) + <= other_obj.horizontal_radius + obj.horizontal_radius + ) + if obj_z > other_obj_z: + z_collision = obj_z - other_obj_z <= other_obj.top_offset[-1] - obj.bottom_offset[-1] + else: + z_collision = other_obj_z - obj_z <= obj.top_offset[-1] - other_obj.bottom_offset[-1] + + if xy_collision and z_collision: + intersect = True + else: + intersect = False + + return intersect + + +def normalize_joint_value(raw, joint_min, joint_max): + """ + normalize raw value to be between 0 and 1 + """ + return (raw - joint_min) / (joint_max - joint_min) + + +def get_highest_spawn_region(env, receptacle): + """ + Get the highest spawn region of a receptacle. + """ + return max( + receptacle.spawns, + key=lambda x: env.sim.data.geom_xpos[env.sim.model.geom_name2id(x.get("name"))][2], + ) + + +def calculate_spawn_region(env, spawn): + """ + Calculates the corner points of the spawn region. + + Parameters: + env: The simulation/environment object. + spawn: The spawn geom. + + Returns: + For box: (p0, px, py, pz) + For cylinder: (p0, axis_vector, radius) + For sphere: (center, radius) + """ + # Get spawn parameters from the simulation. + spawn_name = spawn.get("name") + spawn_id = env.sim.model.geom_name2id(spawn_name) + + spawn_pos = env.sim.data.get_geom_xpos(spawn_name) + spawn_xmat = env.sim.data.get_geom_xmat(spawn_name) + spawn_size = env.sim.model.geom_size[spawn_id] + spawn_type = env.sim.model.geom_type[spawn_id] + assert spawn_type in [ + mj.mjtGeom.mjGEOM_BOX, + mj.mjtGeom.mjGEOM_CYLINDER, + mj.mjtGeom.mjGEOM_SPHERE, + ], "Spawn region only supports box, cylinder and sphere geometries." + + if spawn_type == mj.mjtGeom.mjGEOM_BOX: + # Box geometry - return corners as before + p0 = ( + spawn_pos + - spawn_size[0] * spawn_xmat[:, 0] + - spawn_size[1] * spawn_xmat[:, 1] + - spawn_size[2] * spawn_xmat[:, 2] + ) + px = p0 + 2 * spawn_size[0] * spawn_xmat[:, 0] + py = p0 + 2 * spawn_size[1] * spawn_xmat[:, 1] + pz = p0 + 2 * spawn_size[2] * spawn_xmat[:, 2] + return p0, px, py, pz + elif spawn_type == mj.mjtGeom.mjGEOM_CYLINDER: + # Cylinder geometry - return (base_center, axis_vector, radius) + height = spawn_size[1] * 2 + radius = spawn_size[0] + axis_vector = height * spawn_xmat[:, 2] + return spawn_pos, axis_vector, radius + elif spawn_type == mj.mjtGeom.mjGEOM_SPHERE: + # Sphere geometry - return (center, radius) + radius = spawn_size[0] + return spawn_pos, radius + else: + raise ValueError(f"Invalid spawn type: {spawn_type}") + + +def check_obj_in_receptacle( + env, obj_name, receptacle_name, th=None, spawn_check=True, spawn_regions=None +): + """ + check if object is in receptacle object based on spawn regions or threshold + """ + obj = env.objects[obj_name] + recep = env.objects[receptacle_name] + obj_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[obj_name]]) + obj_quat = T.convert_quat( + np.array(env.sim.data.body_xquat[env.obj_body_id[obj_name]]), to="xyzw" + ) + recep_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[receptacle_name]]) + + if len(recep.spawns) > 0 and spawn_check: + if spawn_regions is None: + spawn_regions = recep.spawns + + for spawn in spawn_regions: + region_points = calculate_spawn_region(env, spawn) + + if obj_in_region_with_keypoints( + obj, + obj_pos, + obj_quat, + region_points, + min_num_points=2, + region_type=spawn.get("type"), + ): + return True + return False + else: + if th is None: + th = recep.horizontal_radius * 0.7 + obj_in_recep = ( + env.check_contact(obj, recep) and np.linalg.norm(obj_pos[:2] - recep_pos[:2]) < th + ) + return obj_in_recep + + +def check_obj_fixture_contact(env, obj_name, fixture_name): + """ + check if object is in contact with fixture + """ + obj = env.objects[obj_name] + fixture = env.get_fixture(fixture_name) + return env.check_contact(obj, fixture) + + +def gripper_obj_far(env, obj_name="obj", th=0.25): + """ + check if gripper is far from object based on distance defined by threshold + """ + return gripper_obj_far_by_side(env=env, obj_name=obj_name, gripper_side="right", th=th)[1] + + +def any_gripper_obj_far(env, obj_name="obj", th=0.25): + """ + check if all grippers are far from object based on distance defined by threshold + """ + left_is_far = gripper_obj_far_by_side(env=env, obj_name=obj_name, gripper_side="left", th=th)[1] + right_is_far = gripper_obj_far_by_side(env=env, obj_name=obj_name, gripper_side="right", th=th)[ + 1 + ] + return left_is_far and right_is_far + + +def gripper_obj_far_by_side(env, obj_name: str, gripper_side: str, th: float = 0.25): + """ + check if gripper is far from object based on distance defined by threshold + """ + obj_pos = env.sim.data.body_xpos[env.obj_body_id[obj_name]] + gripper_site_pos = env.sim.data.site_xpos[env.robots[0].eef_site_id[gripper_side]] + dist = np.linalg.norm(gripper_site_pos - obj_pos) + return dist, dist > th + + +def obj_cos(env, obj_name="obj", ref=(0, 0, 1)): + def cos(u, v): + return np.dot(u, v) / max(np.linalg.norm(u) * np.linalg.norm(v), 1e-10) + + obj_id = env.obj_body_id[obj_name] + obj_quat = T.convert_quat(np.array(env.sim.data.body_xquat[obj_id]), to="xyzw") + obj_mat = T.quat2mat(obj_quat) + + return cos(obj_mat[:, 2], np.array(ref)) + + +def check_obj_upright(env, obj_name, threshold=0.8, symmetric: bool = False): + """ + Check if an object is upright based on its z-axis orientation + """ + obj_id = env.obj_body_id[obj_name] + obj_quat = T.convert_quat(np.array(env.sim.data.body_xquat[obj_id]), to="xyzw") + obj_mat = T.quat2mat(obj_quat) + z_alignment = obj_mat[:, 2][2] + z_alignment = abs(z_alignment) if symmetric else z_alignment + return z_alignment > threshold + + +def obj_in_box_region(obj_points, p0, px, py, pz, min_num_points): + """ + Check if enough object points are inside a box region defined by corner points. + + Args: + obj_points (np.array): Points to check + p0 (np.array): Origin corner point + px (np.array): X-axis corner point + py (np.array): Y-axis corner point + pz (np.array): Z-axis corner point (optional) + min_num_points (int): Minimum number of points that need to be in region + + Returns: + bool: True if enough points are inside the region + """ + u = px - p0 + v = py - p0 + w = pz - p0 if pz is not None else None + + num_points_in_region = 0 + for point in obj_points: + check1 = np.dot(u, p0) <= np.dot(u, point) <= np.dot(u, px) + check2 = np.dot(v, p0) <= np.dot(v, point) <= np.dot(v, py) + + if w is not None: + check3 = np.dot(w, p0) <= np.dot(w, point) <= np.dot(w, pz) + if check1 and check2 and check3: + num_points_in_region += 1 + else: + if check1 and check2: + num_points_in_region += 1 + + return num_points_in_region >= min_num_points + + +def obj_in_cylinder_region(obj_points, p0, axis_vector, radius, min_num_points): + """ + Check if enough object points are inside a cylinder region defined by base point, height vector and radius + + Args: + obj_points (np.array): Points to check + p0 (np.array): Base center point of cylinder + axis_vector (np.array): Vector from base center to top center, defines cylinder axis and height + radius (float): Radius of cylinder + min_num_points (int): Minimum number of points that need to be in region + """ + num_points_in_region = 0 + # Normalize height vector to get axis direction + axis = axis_vector / np.linalg.norm(axis_vector) + height_magnitude = np.linalg.norm(axis_vector) + + for point in obj_points: + # Project point onto cylinder axis + point_rel = point - p0 + height_proj = np.dot(point_rel, axis) + + # Check height bounds + if 0 <= height_proj <= height_magnitude: + # Check radius by removing height component + radius_vec = point_rel - height_proj * axis + if np.linalg.norm(radius_vec) <= radius: + num_points_in_region += 1 + + return num_points_in_region >= min_num_points + + +def obj_in_sphere_region(obj_points, p0, radius, min_num_points): + """ + Check if enough object points are inside a sphere region defined by center and radius + + Args: + obj_points (np.array): Points to check + p0 (np.array): Center point of sphere + radius (float): Radius of sphere + min_num_points (int): Minimum number of points that need to be in region + """ + num_points_in_region = 0 + for point in obj_points: + if np.linalg.norm(point - p0) <= radius: + num_points_in_region += 1 + + return num_points_in_region >= min_num_points diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/placement_samplers.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/placement_samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..df9651ca8143b1ade25824c9a450a7029a4b665c --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/placement_samplers.py @@ -0,0 +1,711 @@ +import collections +from copy import copy + +import numpy as np + +from robocasa.models.objects.objects import MJCFObject +from robosuite.models.objects import MujocoObject +from robosuite.utils import RandomizationError +from robosuite.utils.transform_utils import ( + convert_quat, + euler2mat, + mat2quat, + quat_multiply, + rotate_2d_point, +) + +from robocasa.utils.object_utils import ( + obj_in_region, + objs_intersect, + obj_in_region_with_keypoints, +) + + +class ObjectPositionSampler: + """ + Base class of object placement sampler. + + Args: + name (str): Name of this sampler. + + mujoco_objects (None or MujocoObject or list of MujocoObject): single model or list of MJCF object models + + ensure_object_boundary_in_range (bool): If True, will ensure that the object is enclosed within a given boundary + (should be implemented by subclass) + + ensure_valid_placement (bool): If True, will check for correct (valid) object placements + + reference_pos (3-array): global (x,y,z) position relative to which sampling will occur + + z_offset (float): Add a small z-offset to placements. This is useful for fixed objects + that do not move (i.e. no free joint) to place them above the table. + """ + + def __init__( + self, + name, + mujoco_objects=None, + ensure_object_boundary_in_range=True, + ensure_valid_placement=True, + reference_pos=(0, 0, 0), + reference_rot=0, + z_offset=0.0, + rng=None, + ): + if rng is None: + rng = np.random.default_rng() + self.rng = rng + + # Setup attributes + self.name = name + if mujoco_objects is None: + self.mujoco_objects = [] + else: + # Shallow copy the list so we don't modify the inputted list but still keep the object references + self.mujoco_objects = ( + [mujoco_objects] + if isinstance(mujoco_objects, MujocoObject) + else copy(mujoco_objects) + ) + self.ensure_object_boundary_in_range = ensure_object_boundary_in_range + self.ensure_valid_placement = ensure_valid_placement + self.reference_pos = reference_pos + self.reference_rot = reference_rot + self.z_offset = z_offset + + def add_objects(self, mujoco_objects): + """ + Add additional objects to this sampler. Checks to make sure there's no identical objects already stored. + + Args: + mujoco_objects (MujocoObject or list of MujocoObject): single model or list of MJCF object models + """ + mujoco_objects = ( + [mujoco_objects] if isinstance(mujoco_objects, MujocoObject) else mujoco_objects + ) + for obj in mujoco_objects: + assert obj not in self.mujoco_objects, "Object '{}' already in sampler!".format( + obj.name + ) + self.mujoco_objects.append(obj) + + def reset(self): + """ + Resets this sampler. Removes all mujoco objects from this sampler. + """ + self.mujoco_objects = [] + + def sample(self, fixtures=None, reference=None, on_top=True): + """ + Uniformly sample on a surface (not necessarily table surface). + + Args: + fixtures (dict): dictionary of current object placements in the scene as well as any other relevant + obstacles that should not be in contact with newly sampled objects. Used to make sure newly + generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject) + + reference (str or 3-tuple or None): if provided, sample relative placement. Can either be a string, which + corresponds to an existing object found in @fixtures, or a direct (x,y,z) value. If None, will sample + relative to this sampler's `'reference_pos'` value. + + on_top (bool): if True, sample placement on top of the reference object. + + Return: + dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the + placements specified in @fixtures. Note quat is in (w,x,y,z) form + """ + raise NotImplementedError + + @property + def sides_combinations(self): + return { + "left": ["front_left", "back_left"], + "right": ["front_right", "back_right"], + "front": ["front_left", "front_right"], + "back": ["back_left", "back_right"], + "all": ["front_left", "front_right", "back_left", "back_right"], + } + + @property + def valid_sides(self): + return set( + [ + "left", + "right", + "front", + "back", + "all", + "front_left", + "front_right", + "back_left", + "back_right", + ] + ) + + +class UniformRandomSampler(ObjectPositionSampler): + """ + Places all objects within the table uniformly random. + + Args: + name (str): Name of this sampler. + + mujoco_objects (None or MujocoObject or list of MujocoObject): single model or list of MJCF object models + + x_range (2-array of float): Specify the (min, max) relative x_range used to uniformly place objects + + y_range (2-array of float): Specify the (min, max) relative y_range used to uniformly place objects + + rotation (None or float or Iterable): + :`None`: Add uniform random random rotation + :`Iterable (a,b)`: Uniformly randomize rotation angle between a and b (in radians) + :`value`: Add fixed angle rotation + + rotation_axis (str): Can be 'x', 'y', or 'z'. Axis about which to apply the requested rotation + + ensure_object_boundary_in_range (bool): + :`True`: The center of object is at position: + [uniform(min x_range + radius, max x_range - radius)], [uniform(min x_range + radius, max x_range - radius)] + :`False`: + [uniform(min x_range, max x_range)], [uniform(min x_range, max x_range)] + + ensure_valid_placement (bool): If True, will check for correct (valid) object placements + + reference_pos (3-array): global (x,y,z) position relative to which sampling will occur + + z_offset (float): Add a small z-offset to placements. This is useful for fixed objects + that do not move (i.e. no free joint) to place them above the table. + + num_attempts (int): Number of attempts to sample an object before giving up. + """ + + def __init__( + self, + name, + mujoco_objects=None, + x_range=(0, 0), + y_range=(0, 0), + rotation=None, + rotation_axis="z", + ensure_object_boundary_in_range=True, + ensure_valid_placement=True, + ensure_object_in_ref_region=False, + ensure_object_out_of_ref_region=False, + reference_pos=(0, 0, 0), + reference_rot=0, + z_offset=0.0, + rng=None, + side="all", + num_attempts=5000, + ): + """Uniformly sample the position of the object. + + Args: + ensure_object_in_ref_region (bool, optional): + If True, we need to ensure the object be placed within the reference region. Not need to be fully in the region, but at least the center of the object. + ensure_object_out_of_ref_region (bool, optional): + If True, we need to ensure the object be placed outside the reference region. Need to be fully outside the region. + """ + self.x_range = x_range + self.y_range = y_range + self.rotation = rotation + self.rotation_axis = rotation_axis + self.num_attempts = num_attempts + if side not in self.valid_sides: + raise ValueError("Invalid value for side, must be one of:", self.valid_sides) + + super().__init__( + name=name, + mujoco_objects=mujoco_objects, + ensure_object_boundary_in_range=ensure_object_boundary_in_range, + ensure_valid_placement=ensure_valid_placement, + reference_pos=reference_pos, + reference_rot=reference_rot, + z_offset=z_offset, + rng=rng, + ) + self.ensure_object_in_ref_region = ensure_object_in_ref_region + self.ensure_object_out_of_ref_region = ensure_object_out_of_ref_region + + def _sample_x(self): + """ + Samples the x location for a given object + + Returns: + float: sampled x position + """ + minimum, maximum = self.x_range + return self.rng.uniform(high=maximum, low=minimum) + + def _sample_y(self): + """ + Samples the y location for a given object + + Returns: + float: sampled y position + """ + minimum, maximum = self.y_range + return self.rng.uniform(high=maximum, low=minimum) + + def _sample_quat(self): + """ + Samples the orientation for a given object + + Returns: + np.array: sampled object quaternion in (w,x,y,z) form + + Raises: + ValueError: [Invalid rotation axis] + """ + if self.rotation is None: + rot_angle = self.rng.uniform(high=2 * np.pi, low=0) + elif isinstance(self.rotation, collections.abc.Iterable): + if isinstance(self.rotation[0], collections.abc.Iterable): + rotation = self.rng.choice(self.rotation) + else: + rotation = self.rotation + rot_angle = self.rng.uniform(high=max(rotation), low=min(rotation)) + else: + rot_angle = self.rotation + + # Return angle based on axis requested + if self.rotation_axis == "x": + return np.array([np.cos(rot_angle / 2), np.sin(rot_angle / 2), 0, 0]) + elif self.rotation_axis == "y": + return np.array([np.cos(rot_angle / 2), 0, np.sin(rot_angle / 2), 0]) + elif self.rotation_axis == "z": + return np.array([np.cos(rot_angle / 2), 0, 0, np.sin(rot_angle / 2)]) + else: + # Invalid axis specified, raise error + raise ValueError( + "Invalid rotation axis specified. Must be 'x', 'y', or 'z'. Got: {}".format( + self.rotation_axis + ) + ) + + def sample(self, placed_objects=None, reference=None, neg_reference=None, on_top=True): + """ + Uniformly sample relative to this sampler's reference_pos or @reference (if specified). + + Args: + placed_objects (dict): dictionary of current object placements in the scene as well as any other relevant + obstacles that should not be in contact with newly sampled objects. Used to make sure newly + generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject) + + reference (str, tuple, or None, optional): Defines the reference for relative placement. It can be an object + name found in `fixtures`, a tuple specifying an object and its site ID, or a direct (x, y, z) coordinate. + If not provided, placement is sampled relative to this sampler's `reference_pos`. + + on_top (bool): if True, sample placement on top of the reference object. This corresponds to a sampled + z-offset of the current sampled object's bottom_offset + the reference object's top_offset + (if specified) + + Return: + dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the + placements specified in @fixtures. Note quat is in (w,x,y,z) form + + Raises: + RandomizationError: [Cannot place all objects] + AssertionError: [Reference object name does not exist, invalid inputs] + """ + # Standardize inputs + placed_objects = {} if placed_objects is None else copy(placed_objects) + spawn_ref_obj = None + + if reference is None: + base_offset = self.reference_pos + elif type(reference) is str: + assert ( + reference in placed_objects + ), "Invalid reference received. Current options are: {}, requested: {}".format( + placed_objects.keys(), reference + ) + ref_pos, _, ref_obj = placed_objects[reference] + base_offset = np.array(ref_pos) + if on_top: + base_offset += np.array((0, 0, ref_obj.top_offset[-1])) + # Handle shelf object references + # If the reference is provided as a tuple (object_key: str, spawn_id: int), + # then we treat it as a reference to a specific shelf level + elif type(reference) is tuple and len(reference) == 2: + (reference, spawn_id) = reference + assert ( + reference in placed_objects + ), "Invalid reference received. Current options are: {}, requested: {}".format( + placed_objects.keys(), reference + ) + ref_pos, _, ref_obj = placed_objects[reference] + assert isinstance( + ref_obj, MJCFObject + ), "Invalid reference received. Should be of type MJCFObject" + if spawn_id == -1: + spawn_id, site = ref_obj.get_random_spawn(self.rng, exclude_disabled=True) + else: + site = ref_obj.spawns[spawn_id] + ref_obj.set_spawn_active(spawn_id, False) + + base_offset = np.array(ref_pos) + base_offset += ref_obj.get_spawn_bottom_offset(site) + spawn_ref_obj = ref_obj + else: + base_offset = np.array(reference) + assert ( + base_offset.shape[0] == 3 + ), "Invalid reference received. Should be (x,y,z) 3-tuple, but got: {}".format( + base_offset + ) + + # Sample pos and quat for all objects assigned to this sampler + for obj in self.mujoco_objects: + # First make sure the currently sampled object hasn't already been sampled + assert obj.name not in placed_objects, "Object '{}' has already been sampled!".format( + obj.name + ) + + success = False + + # get reference rotation + ref_quat = convert_quat(mat2quat(euler2mat([0, 0, self.reference_rot])), to="wxyz") + + ### get boundary points ### + region_points = np.array( + [ + [self.x_range[0], self.y_range[0], 0], + [self.x_range[1], self.y_range[0], 0], + [self.x_range[0], self.y_range[1], 0], + ] + ) + for i in range(len(region_points)): + region_points[i][0:2] = rotate_2d_point( + region_points[i][0:2], rot=self.reference_rot + ) + region_points += base_offset + + for i in range(self.num_attempts): + # sample object coordinates + relative_x = self._sample_x() + relative_y = self._sample_y() + + # apply rotation + object_x, object_y = rotate_2d_point( + [relative_x, relative_y], rot=self.reference_rot + ) + + object_x = object_x + base_offset[0] + object_y = object_y + base_offset[1] + object_z = self.z_offset + base_offset[2] + if on_top: + object_z -= obj.bottom_offset[-1] + + # random rotation + quat = self._sample_quat() + # multiply this quat by the object's initial rotation if it has the attribute specified + if hasattr(obj, "init_quat"): + quat = quat_multiply(quat, obj.init_quat) + quat = convert_quat( + quat_multiply( + convert_quat(ref_quat, to="xyzw"), + convert_quat(quat, to="xyzw"), + ), + to="wxyz", + ) + + location_valid = True + + # ensure object placed fully in region + if self.ensure_object_boundary_in_range and not obj_in_region( + obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + p0=region_points[0], + px=region_points[1], + py=region_points[2], + ): + location_valid = False + continue + + # objects cannot overlap + if self.ensure_valid_placement: + for (x, y, z), other_quat, other_obj in placed_objects.values(): + if spawn_ref_obj and other_obj == spawn_ref_obj: + if not objs_intersect( + obj=obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + other_obj=other_obj, + other_obj_pos=[x, y, z], + other_obj_quat=convert_quat(other_quat, to="xyzw"), + ): + location_valid = False + break + else: + if objs_intersect( + obj=obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + other_obj=other_obj, + other_obj_pos=[x, y, z], + other_obj_quat=convert_quat(other_quat, to="xyzw"), + ): + location_valid = False + break + + # ensure at least one point of the object should be in the region + if self.ensure_object_in_ref_region and reference is not None: + _ref_pos, _ref_quat, _ref_obj = placed_objects[reference] + if not obj_in_region_with_keypoints( + obj=obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + region_points=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[:3], + min_num_points=3, + ): + location_valid = False + break + + if self.ensure_object_out_of_ref_region and neg_reference is not None: + for nf in neg_reference: + assert ( + nf in placed_objects + ), "Invalid negative reference received. Current options are: {}, requested: {}".format( + placed_objects.keys(), nf + ) + _ref_pos, _ref_quat, _ref_obj = placed_objects[nf] + if obj_in_region( + obj=obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + p0=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[0], + px=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[1], + py=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[2], + ): + location_valid = False + break + + if location_valid: + # location is valid, put the object down + pos = (object_x, object_y, object_z) + placed_objects[obj.name] = (pos, quat, obj) + success = True + break + + if not success: + raise RandomizationError(f"Cannot place object: {obj.name}") + + return placed_objects + + +class SequentialCompositeSampler(ObjectPositionSampler): + """ + Samples position for each object sequentially. Allows chaining + multiple placement initializers together - so that object locations can + be sampled on top of other objects or relative to other object placements. + + Args: + name (str): Name of this sampler. + """ + + def __init__(self, name, rng=None): + # Samplers / args will be filled in later + self.samplers = collections.OrderedDict() + self.sample_args = collections.OrderedDict() + self.sampler_optional = collections.OrderedDict() + + super().__init__(name=name, rng=rng) + + def append_sampler(self, sampler, sample_args=None, optional=False): + """ + Adds a new placement initializer with corresponding @sampler and arguments + + Args: + sampler (ObjectPositionSampler): sampler to add + sample_args (None or dict): If specified, should be additional arguments to pass to @sampler's sample() + call. Should map corresponding sampler's arguments to values (excluding @fixtures argument) + optional (bool): If True, do not raise an error if the sampler fails to place all objects. This parameter + is for handling optional clutter generation. When True, clutter objects that can't be placed due to + space constraints are silently skipped. + + Raises: + AssertionError: [Object name in samplers] + """ + # Verify that all added mujoco objects haven't already been added, and add to this sampler's objects dict + for obj in sampler.mujoco_objects: + assert ( + obj not in self.mujoco_objects + ), f"Object '{obj.name}' already has sampler associated with it!" + self.mujoco_objects.append(obj) + self.samplers[sampler.name] = sampler + self.sample_args[sampler.name] = sample_args + self.sampler_optional[sampler.name] = optional + + def hide(self, mujoco_objects): + """ + Helper method to remove an object from the workspace. + + Args: + mujoco_objects (MujocoObject or list of MujocoObject): Object(s) to hide + """ + sampler = UniformRandomSampler( + name="HideSampler", + mujoco_objects=mujoco_objects, + x_range=[-10, -20], + y_range=[-10, -20], + rotation=[0, 0], + rotation_axis="z", + z_offset=10, + ensure_object_boundary_in_range=False, + ensure_valid_placement=False, + rng=self.rng, + ) + self.append_sampler(sampler=sampler) + + def add_objects(self, mujoco_objects): + """ + Override super method to make sure user doesn't call this (all objects should implicitly belong to sub-samplers) + """ + raise AttributeError("add_objects() should not be called for SequentialCompsiteSamplers!") + + def add_objects_to_sampler(self, sampler_name, mujoco_objects): + """ + Adds specified @mujoco_objects to sub-sampler with specified @sampler_name. + + Args: + sampler_name (str): Existing sub-sampler name + mujoco_objects (MujocoObject or list of MujocoObject): Object(s) to add + """ + # First verify that all mujoco objects haven't already been added, and add to this sampler's objects dict + mujoco_objects = ( + [mujoco_objects] if isinstance(mujoco_objects, MujocoObject) else mujoco_objects + ) + for obj in mujoco_objects: + assert ( + obj not in self.mujoco_objects + ), f"Object '{obj.name}' already has sampler associated with it!" + self.mujoco_objects.append(obj) + # Make sure sampler_name exists + assert ( + sampler_name in self.samplers.keys() + ), "Invalid sub-sampler specified, valid options are: {}, " "requested: {}".format( + self.samplers.keys(), sampler_name + ) + # Add the mujoco objects to the requested sub-sampler + self.samplers[sampler_name].add_objects(mujoco_objects) + + def reset(self): + """ + Resets this sampler. In addition to base method, iterates over all sub-samplers and resets them + """ + super().reset() + for sampler in self.samplers.values(): + sampler.reset() + + def sample(self, placed_objects=None, reference=None, on_top=True): + """ + Sample from each placement initializer sequentially, in the order + that they were appended. + + Args: + placed_objects (dict): dictionary of current object placements in the scene as well as any other relevant + obstacles that should not be in contact with newly sampled objects. Used to make sure newly + generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject) + + reference (str or 3-tuple or None): if provided, sample relative placement. This will override each + sampler's @reference argument if not already specified. Can either be a string, which + corresponds to an existing object found in @fixtures, or a direct (x,y,z) value. If None, will sample + relative to this sampler's `'reference_pos'` value. + + on_top (bool): if True, sample placement on top of the reference object. This will override each + sampler's @on_top argument if not already specified. This corresponds to a sampled + z-offset of the current sampled object's bottom_offset + the reference object's top_offset + (if specified) + + Return: + dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the + placements specified in @fixtures. Note quat is in (w,x,y,z) form + + Raises: + RandomizationError: [Cannot place all objects] + """ + # Standardize inputs + placed_objects = {} if placed_objects is None else copy(placed_objects) + + # Iterate through all samplers to sample + for sampler, s_args in zip(self.samplers.values(), self.sample_args.values()): + # Pre-process sampler args + if s_args is None: + s_args = {} + for arg_name, arg in zip(("reference", "on_top"), (reference, on_top)): + if arg_name not in s_args: + s_args[arg_name] = arg + # Run sampler + try: + new_placements = sampler.sample( + placed_objects=placed_objects or s_args.pop("placed_objects", {}), + **s_args, + ) + except RandomizationError: + if self.sampler_optional[sampler.name]: + continue + else: + raise + # Update placements + placed_objects.update(new_placements) + + # only return placements for newly placed objects + sampled_obj_names = [ + obj.name for sampler in self.samplers.values() for obj in sampler.mujoco_objects + ] + return {k: v for (k, v) in placed_objects.items() if k in sampled_obj_names} + + +class MultiRegionSampler(ObjectPositionSampler): + def __init__( + self, + name, + regions, + side="all", + mujoco_objects=None, + rotation=None, + rotation_axis="z", + ensure_object_boundary_in_range=True, + ensure_valid_placement=True, + ensure_object_in_ref_region=False, + rng=None, + z_offset=0.0, + ): + if len(regions) != 4: + raise ValueError("Exactly four sites (one for each quadrant) must be provided.") + if side not in self.valid_sides: + raise ValueError("Invalid value for side, must be one of:", self.valid_sides) + + # initialize sides and regions + if side in self.sides_combinations: + self.sides = self.sides_combinations[side] + else: + self.sides = [side] + self.regions = regions + + # create a list of uniform samplers (one for each site) + self.samplers = list() + for s in self.sides: + site = self.regions[s] + sampler = UniformRandomSampler( + name=name, + mujoco_objects=mujoco_objects, + reference_pos=site["pos"], + x_range=site["x_range"], + y_range=site["y_range"], + rotation=rotation, + rotation_axis=rotation_axis, + ensure_object_boundary_in_range=ensure_object_boundary_in_range, + ensure_valid_placement=ensure_valid_placement, + ensure_object_in_ref_region=ensure_object_in_ref_region, + z_offset=z_offset, + rng=rng, + ) + self.samplers.append(sampler) + + def sample(self, fixtures=None, reference=None, on_top=True): + # randomly picks a sampler and calls its sample function + sampler = self.rng.choice(self.samplers) + return sampler.sample(fixtures=fixtures, reference=reference, on_top=on_top) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/postprocess_xml_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/postprocess_xml_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ce535f75e67bdf1bb62ba160399361772b3a3785 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/postprocess_xml_utils.py @@ -0,0 +1,78 @@ +import h5py +import json +import argparse +import os +from shutil import copyfile +import robosuite +import xml.etree.ElementTree as ET +from tqdm import tqdm +import numpy as np + + +def get_eef_panda_site(prefix): + """ + Helper function for new element added in robosuite v1.5 + """ + + eef_panda_site = ( + """ """ + ) + + tree = ET.ElementTree(ET.fromstring(eef_panda_site)) + root = tree.getroot() + for elem in root.iter(): + elem.attrib["name"] = "{}_{}".format(prefix, elem.get("name")) + + return tree + + +def update_gripper_name(gripper_name: str): + tokens = gripper_name.split("_") + tokens.insert(1, "right") + return "_".join(tokens) + + +def convert_xml(xml_str): + """ + Postprocess xml string generated by robosuite to be compatible with robosuite v1.5 + This script should not the xml string if it was already generated using robosuite v1.5 + Args: + xml_str (str): xml string to process (from robosuite v1.4.1) + """ + + root = ET.fromstring(xml_str) + worldbody = root.find("worldbody") + bodies_to_process = [] + + for body in worldbody.iter("body"): + body_name = body.get("name") + if "link0" in body_name: + if body not in bodies_to_process: + bodies_to_process.append(body) + + # add elements introduced in v1.5 + for body in bodies_to_process: + prefix = body.get("name").split("_")[0] + eef_tree = get_eef_panda_site(prefix) + body.append(eef_tree.getroot()) + + assets = root.find("asset") + + # change path from mounts to bases + for asset in assets.iter("mesh"): + path = asset.get("file") + assert "robosuite/models/assets" in path or "robocasa/models/assets" in path, print(path) + if "mounts" in path: + assert not "robot" in path + new_path = path.replace( + "robosuite/models/assets/mounts", "robosuite/models/assets/bases" + ) + asset.set("file", new_path) + + # update naming prefixes + for elem in root.iter(): + for attr, value in elem.attrib.items(): + if value.startswith("mount"): + elem.set(attr, value.replace("mount", "fixed_base", 1)) + elif value.startswith("gripper"): + elem.set(attr, update_gripper_name(value)) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/configs.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/configs.py new file mode 100644 index 0000000000000000000000000000000000000000..fe17da505106fc28b9fb93a888b563a106cfcf79 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/configs.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from typing import TYPE_CHECKING, Any, Optional, Union + +import numpy as np + +from robocasa.utils.scene.success_criteria import SuccessCriteria + +if TYPE_CHECKING: + from robocasa.utils.scene.scene import SceneObject + + +@dataclass(frozen=True) +class ReferenceConfig: + obj: Optional[SceneObject] + spawn_id: Optional[int] = None + on_top: bool = True + + def to_dict(self) -> Optional[dict[str, Any]]: + if self.obj is None: + return None + if self.spawn_id is None: + return {"reference": self.obj.cfg.name, "on_top": self.on_top} + else: + return {"reference": (self.obj.cfg.name, self.spawn_id)} + + +@dataclass(frozen=True) +class SamplingConfig: + x_range: np.ndarray = np.zeros(2) + y_range: np.ndarray = np.zeros(2) + rotation: np.ndarray = np.zeros(2) + reference_pos: np.ndarray = np.zeros(3) + z_offset: float = 0 + reference: Optional[ReferenceConfig] = None + + @property + def sampling_args(self) -> Optional[dict]: + if self.reference is None: + return None + return self.reference.to_dict() + + +@dataclass(frozen=True) +class ObjectConfig: + mjcf_path: str + name: str + static: bool = False + scale: float = 1.0 + density: int = 100 + friction: tuple[float, float, float] = (1, 1, 1) + margin: Optional[float] = None + rgba: Optional[tuple[float, float, float, float]] = None + sampler_config: SamplingConfig = SamplingConfig() + + +@dataclass(frozen=True) +class SceneConfig: + objects: list[SceneObject] + success: SuccessCriteria + instruction: str + + +class SceneHandedness(Enum): + UNIVERSAL = "UNIVERSAL" + LEFT = "LEFT" + RIGHT = "RIGHT" + + +@dataclass(frozen=True) +class SceneScaleConfig: + planar_scale: Union[float, tuple[float, float]] = 1.0 + vertical_scale: float = 1.0 + handedness: SceneHandedness = SceneHandedness.UNIVERSAL + handedness_axis: int = 1 + + def get_ref_pos(self, pos: np.ndarray) -> np.ndarray: + pos = pos.astype(float, copy=True) # ensure float + pos[self.handedness_axis] *= float(self._handedness_factor) + pos[:2] = pos[:2] * np.array(self._scale, dtype=float) + pos[2] *= float(self.vertical_scale) + return pos + + def get_rotation(self, rot: Optional[np.ndarray]) -> Optional[np.ndarray]: + if rot is None: + return None + rot = rot.astype(float, copy=True) + rot *= float(self._handedness_factor) + return rot + + def get_ranges(self, x_range: np.ndarray, y_range: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + x_range = x_range.astype(float, copy=True) + y_range = y_range.astype(float, copy=True) + + if self.handedness_axis == 0: + x_range *= float(self._handedness_factor) + x_range.sort() + elif self.handedness_axis == 1: + y_range *= float(self._handedness_factor) + y_range.sort() + return x_range, y_range + + def get_z_offset(self, z_offset: float) -> float: + return float(z_offset) * float(self.vertical_scale) + + @property + def _handedness_factor(self) -> float: + if self.handedness == "LEFT": # replace with enum comparison + return -1.0 + else: + return 1.0 + + @property + def _scale(self) -> tuple[float, float]: + if isinstance(self.planar_scale, tuple) and len(self.planar_scale) == 2: + return float(self.planar_scale[0]), float(self.planar_scale[1]) + elif isinstance(self.planar_scale, (float, int)): + scale = float(self.planar_scale) + return scale, scale + else: + raise ValueError( + f"Invalid type for 'planar_scale': expected float or tuple[float, float], " + f"but got {type(self.planar_scale).__name__}" + ) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/scene.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/scene.py new file mode 100644 index 0000000000000000000000000000000000000000..f59e05afd4683830ca08cc3bcf82a346a98260ee --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/scene.py @@ -0,0 +1,146 @@ +from graphlib import CycleError, TopologicalSorter +from pathlib import Path + +import numpy as np +from robosuite.environments import MujocoEnv +from robosuite.utils import transform_utils as T +from robosuite.utils.mjcf_utils import xml_path_completion + +import robocasa +from robocasa.models.objects.objects import MJCFObject +from robocasa.utils.placement_samplers import ( + ObjectPositionSampler, + SequentialCompositeSampler, + UniformRandomSampler, +) +from robocasa.utils.scene.configs import ( + ObjectConfig, + SceneConfig, + SceneScaleConfig, +) + + +class SceneObject: + def __init__(self, cfg: ObjectConfig): + self.cfg = cfg + self._mujoco_object = self._get_object() + + @property + def mj_obj(self) -> MJCFObject: + return self._mujoco_object + + def get_sampler_with_args( + self, env: MujocoEnv, scene_scale: SceneScaleConfig + ) -> tuple[ObjectPositionSampler, dict]: + return ( + self._get_sampler(self._mujoco_object, env, scene_scale), + self.cfg.sampler_config.sampling_args, + ) + + def _get_object(self) -> MJCFObject: + abs_mjcf_path = ( + self.cfg.mjcf_path + if Path(self.cfg.mjcf_path).is_absolute() + else xml_path_completion(self.cfg.mjcf_path, root=robocasa.models.assets_root) + ) + return MJCFObject( + name=self.cfg.name, + mjcf_path=abs_mjcf_path, + scale=self.cfg.scale, + solimp=(0.998, 0.998, 0.001), + solref=(0.001, 1), + density=self.cfg.density, + friction=self.cfg.friction, + margin=self.cfg.margin, + static=self.cfg.static, + rgba=self.cfg.rgba, + ) + + def _get_sampler( + self, obj: MJCFObject, env: MujocoEnv, scene_scale: SceneScaleConfig + ) -> ObjectPositionSampler: + x_range, y_range = scene_scale.get_ranges( + self.cfg.sampler_config.x_range, self.cfg.sampler_config.y_range + ) + z_offset = scene_scale.get_z_offset(self.cfg.sampler_config.z_offset) + rotation = scene_scale.get_rotation(self.cfg.sampler_config.rotation) + reference_pos = scene_scale.get_ref_pos(self.cfg.sampler_config.reference_pos) + return UniformRandomSampler( + name=f"{self.cfg.name}_sampler", + mujoco_objects=obj, + x_range=x_range, + y_range=y_range, + rotation=rotation, + rng=env.rng, + rotation_axis="z", + ensure_object_boundary_in_range=False, + ensure_valid_placement=False, + reference_pos=reference_pos, + z_offset=z_offset, + ) + + +class Scene: + def __init__(self, env: MujocoEnv, config: SceneConfig, scene_scale: SceneScaleConfig): + self._env = env + self._config = config + self._scene_scale = scene_scale + self._scene_objects: dict[MJCFObject, SceneObject] = {} + for scene_obj in self._config.objects: + self._scene_objects[scene_obj.mj_obj] = scene_obj + self._scene_sampler = self._get_sampler() + + @property + def mujoco_objects(self) -> list[MJCFObject]: + return list(self._scene_objects.keys()) + + @property + def instruction(self) -> str: + return self._config.instruction + + def reset(self) -> None: + sim = self._env.sim + object_placements = self._scene_sampler.sample() + for obj_pos, obj_quat, obj in object_placements.values(): + scene_obj = self._scene_objects[obj] + if scene_obj.cfg.static: + body_id = sim.model.body_name2id(obj.root_body) + sim.model.body_pos[body_id] = obj_pos + sim.model.body_quat[body_id] = obj_quat + obj.set_pos(obj_pos) + obj.set_euler(T.mat2euler(T.quat2mat(T.convert_quat(obj_quat, "xyzw")))) + else: + joint_name = next(j for j in obj.joints if np.size(sim.data.get_joint_qpos(j)) == 7) + qpos = np.concatenate([np.array(obj_pos), np.array(obj_quat)]) + # Set qpos0 to support robust mujoco environment reset + start_i, end_i = sim.model.get_joint_qpos_addr(joint_name) + sim.data.model.qpos0[start_i:end_i] = qpos + # Set qpos + sim.data.set_joint_qpos( + joint_name, + qpos, + ) + + def success(self) -> bool: + return self._config.success.is_true(self._env) + + def _get_sampler(self) -> SequentialCompositeSampler: + sorted_objects = self._sort_scene_objects(list(self._scene_objects.values())) + + scene_sampler = SequentialCompositeSampler(name="SceneSampler", rng=self._env.rng) + for obj in sorted_objects: + sampler, args = obj.get_sampler_with_args(self._env, self._scene_scale) + scene_sampler.append_sampler(sampler=sampler, sample_args=args) + + return scene_sampler + + @staticmethod + def _sort_scene_objects(scene_objects: list[SceneObject]) -> list[SceneObject]: + ts = TopologicalSorter() + for obj in scene_objects: + ref = obj.cfg.sampler_config.reference.obj if obj.cfg.sampler_config.reference else None + ts.add(obj, *([ref] if ref else [])) + try: + return list(ts.static_order()) + except CycleError: + raise ValueError("Circular reference detected") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/success_criteria.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/success_criteria.py new file mode 100644 index 0000000000000000000000000000000000000000..55c48ba2f83b42dfaf9434f8ea5860e7c21c12ab --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/scene/success_criteria.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Optional + +import numpy as np +from robosuite.environments import MujocoEnv +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv + +from robocasa.utils import object_utils as OU + +if TYPE_CHECKING: + from robocasa.utils.scene.scene import SceneObject + + +class SuccessCriteria(ABC): + @abstractmethod + def is_true(self, env: MujocoEnv) -> bool: + raise NotImplementedError + + +class IsUpright(SuccessCriteria): + def __init__(self, obj: SceneObject, threshold=0.8, symmetric: bool = False): + self._obj = obj + self._threshold = threshold + self._symmetric = symmetric + + def is_true(self, env: MujocoEnv) -> bool: + return OU.check_obj_upright( + env, + obj_name=self._obj.mj_obj.name, + threshold=self._threshold, + symmetric=self._symmetric, + ) + + +class IsClose(SuccessCriteria): + def __init__( + self, + obj_a: SceneObject, + obj_b: SceneObject, + max_distance: float, + use_xy_only: bool = False, + ): + self._obj_a = obj_a + self._obj_b = obj_b + self._max_distance = max_distance + self._use_xy_only = use_xy_only + + def is_true(self, env: MujocoEnv) -> bool: + pos_a = env.sim.data.body_xpos[env.obj_body_id[self._obj_a.mj_obj.name]] + pos_b = env.sim.data.body_xpos[env.obj_body_id[self._obj_b.mj_obj.name]] + if self._use_xy_only: + pos_a = pos_a[:2] + pos_b = pos_b[:2] + return np.linalg.norm(pos_a - pos_b) <= self._max_distance + + +class IsInContact(SuccessCriteria): + def __init__(self, obj_a: SceneObject, obj_b: SceneObject): + self._obj_a = obj_a + self._obj_b = obj_b + + def is_true(self, env: MujocoEnv) -> bool: + return env.check_contact(self._obj_a.mj_obj, self._obj_b.mj_obj) + + +class IsGripperFar(SuccessCriteria): + def __init__(self, obj: SceneObject, threshold: float = 0.4): + self._threshold = threshold + self._obj = obj + + def is_true(self, env: MujocoEnv) -> bool: + return OU.any_gripper_obj_far(env, obj_name=self._obj.mj_obj.name, th=self._threshold) + + +class IsGrasped(SuccessCriteria): + _GRIPPERS = {"left", "right"} + + def __init__(self, obj: SceneObject, gripper: Optional[str] = None): + self._obj = obj + self._grippers = {gripper} if gripper in self._GRIPPERS else self._GRIPPERS + + def is_true(self, env: MujocoEnv) -> bool: + assert isinstance(env, ManipulationEnv), "Expected a ManipulationEnv instance." + robot = env.robots[0] + return any(env._check_grasp(robot.gripper[g], self._obj.mj_obj) for g in self._grippers) + + +class IsRobotInRange(SuccessCriteria): + def __init__(self, target: SceneObject, threshold: float, planar: bool): + self._target = target + self._threshold = threshold + self._planar = planar + + def is_true(self, env: MujocoEnv) -> bool: + robot = env.robots[0] + robot_pos = env.sim.data.get_body_xpos(robot.robot_model.root_body) + obj_pos = env.sim.data.body_xpos[env.obj_body_id[self._target.mj_obj.name]] + if self._planar: + robot_pos = robot_pos[:2] + obj_pos = obj_pos[:2] + return np.linalg.norm(robot_pos - obj_pos) <= self._threshold + + +class IsPositionInRange(SuccessCriteria): + def __init__( + self, + target: SceneObject, + axis_index: int, + min_val: Optional[float] = None, + max_val: Optional[float] = None, + ): + self._target = target + self._axis = axis_index + self._min = min_val or float("-inf") + self._max = max_val or float("inf") + + def is_true(self, env: MujocoEnv) -> bool: + pos = env.sim.data.body_xpos[env.obj_body_id[self._target.mj_obj.name]] + return self._min <= pos[self._axis] <= self._max + + +class IsJointQposInRange(SuccessCriteria): + def __init__(self, obj: SceneObject, joint_id: int, min_val: float, max_val: float): + self._obj = obj + self._joint_id = joint_id + self._min = min_val + self._max = max_val + + def is_true(self, env: MujocoEnv) -> bool: + qpos = env.sim.data.get_joint_qpos(self._obj.mj_obj.joints[self._joint_id]) + return self._min <= qpos <= self._max + + +class NotCriteria(SuccessCriteria): + def __init__(self, criteria: SuccessCriteria): + self.criteria = criteria + + def is_true(self, env: MujocoEnv) -> bool: + return not self.criteria.is_true(env) + + +class AllCriteria(SuccessCriteria): + def __init__(self, *criteria: SuccessCriteria): + self.criteria = criteria + + def is_true(self, env: MujocoEnv) -> bool: + return all(c.is_true(env) for c in self.criteria) + + +class AnyCriteria(SuccessCriteria): + def __init__(self, *criteria: SuccessCriteria): + self.criteria = criteria + + def is_true(self, env: MujocoEnv) -> bool: + return any(c.is_true(env) for c in self.criteria) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/texture_swap.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/texture_swap.py new file mode 100644 index 0000000000000000000000000000000000000000..4d9044a89916b3459bb236a7f11a655b2f831811 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/texture_swap.py @@ -0,0 +1,670 @@ +import inspect +import os +import random +from copy import deepcopy +from pathlib import Path + +import numpy as np +from lxml import etree as ET +from robosuite.utils.mjcf_utils import find_elements + +import robocasa + +TEXTURES_DIR = Path(inspect.getfile(robocasa)).parent / "models" / "assets" / "generative_textures" + +CABINET_TEX_NAMES = [ + "flat copy 26.png", + "196415a6-3c0f-4a1f-a644-fc54a6801223.png", + "2a310e7f-8005-4dba-8dea-edb1484e1e28.png", + "flat copy 37.png", + "1fb8c016-b655-48ab-ad53-d6238a745065.png", + "f80067c5-9967-4607-880f-1c4002d400cb.png", + "00846c84-f900-4bdd-897f-3928e7d87dce.png", + "flat copy 38.png", + "54c4d59e-c0b1-4608-a953-568e9ae13409.png", + "flat copy 2.png", + "flat copy 23.png", + "flat copy 16.png", + "251695ed-d413-48fe-817e-c3e02b3ee117.png", + "18338c06-57fc-4882-ad44-b5f3b3846806.png", + "flat copy 40.png", + "36a1e6cb-98a1-4ada-a14e-8c04f135c5ee.png", + "f06bca10-a7ce-4a4a-92f6-973d7400fe8a.png", + "flat copy 41.png", + "397c17e0-e91b-4fa6-98d9-97e6d2f009ed.png", + "532a9660-8c7a-488b-8930-9134a9479afa.png", + "flat copy 33.png", + "d0299fe2-026b-4727-85e1-cb5de303e315.png", + "68a933bc-df0c-4891-bd41-2c05e4fde504.png", + "6698bb80-52f7-4e5b-ad6a-4a8122504f9a.png", + "99f0113d-8cb4-40b6-9670-b4be4c1fc475.png", + "flat copy 32.png", + "flat copy 34.png", + "c1ad279c-9093-469e-aa20-b73af0fc8db4.png", + "518ddc39-55c2-4b18-8bf6-e9c4f0806760.png", + "flat copy 8.png", + "860cab10-089c-4d99-ae89-3e4f87df5d9c.png", + "f29d41e9-d285-47e4-ad29-f04423533802.png", + "flat copy 13.png", + "flat copy 12.png", + "e6420ee4-14f0-404f-9cd7-abc9a69da621.png", + "flat copy 4.png", + "de7f86d5-56c9-4331-a9aa-655687dc354b.png", + "flat copy 35.png", + "flat.png", + "b6abcb20-8b90-42d3-9175-ba6b4d53a7a9.png", + "d29a6530-28d6-4dbe-bce5-9014d613ae5e.png", + "992f49b2-3f7c-4c54-a4d6-75af4693353b.png", + "flat copy 27.png", + "fd195b15-b98c-47c9-b608-de4157f6ceba.png", + "flat copy 10.png", + "flat copy 15.png", + "af993127-4ec6-4fa3-9a27-018af985a4a0.png", + "8de5fd51-b7b5-4014-a892-f0498c35fec2.png", + "flat copy 3.png", + "flat copy 11.png", + "flat copy 30.png", + "edc5b189-60a3-4aa0-a68d-cc35009f3648.png", + "flat copy 20.png", + "flat copy 19.png", + "9fe8882d-3aa9-4d2b-8de3-d9d220ea526c.png", + "flat copy 7.png", + "flat copy 46.png", + "flat copy 9.png", + "230e3f37-02d7-4be9-b6a8-1e4fb3acd368.png", + "flat copy 45.png", + "7f426b18-12ee-492b-9c69-dfa8ccbc42cc.png", + "flat copy 49.png", + "flat copy 22.png", + "7fe6e2dc-615f-432e-92d4-0a4f17a9ac49.png", + "flat copy 47.png", + "flat copy 42.png", + "34c9cf7b-5b5d-4c81-bb95-6d5743d25a18.png", + "aae9ec57-7df1-4af7-8e40-62962b90cce4.png", + "flat copy 36.png", + "flat copy 25.png", + "5a34b72d-3b7e-4a9a-9a0f-f73f2230fe28.png", + "e2e0160d-9809-48d2-b018-416ee0254fc0.png", + "a6bb714e-0f35-46d6-b7e8-3c18232a4801.png", + "a86a130e-04a3-44b0-99b7-44ce0a63cc2b.png", + "01f783e0-38de-497d-8ebe-c8d8a47e520a.png", + "flat copy 44.png", + "e0e2d63e-900b-4ecb-8df9-28115a58c3a2.png", + "flat copy 50.png", + "flat copy 5.png", + "flat copy 18.png", + "1aac54cf-8bf3-428c-93cd-1d3c258ff6b4.png", + "flat copy 14.png", + "11717454-440d-4b32-85c3-bf0013c66c61.png", + "67d50012-cba6-4525-8e00-b71124861f7e.png", + "25436e21-3140-4875-89a9-d14c5ce20f31.png", + "e4a28073-2252-4603-8c4b-75527a8c5ae9.png", + "flat copy 17.png", + "flat copy 48.png", + "flat copy 6.png", + "28d31de4-53f8-434a-ac57-4d5d27f5ab2f.png", + "flat copy.png", + "flat copy 39.png", + "flat copy 43.png", + "flat copy 24.png", + "6a13b80d-83c7-4fe1-8412-4fc07eefaa35.png", + "43a60b06-97b9-4119-b416-c7fc6783aa81.png", + "flat copy 21.png", + "flat copy 28.png", + "flat copy 31.png", + "flat copy 29.png", +] + +COUNTER_TOP_TEX_NAMES = [ + "5065776e-1fbc-4a70-a786-9a2ec6ee5aa0.png", + "e7f151aa-2354-48d0-94e8-071462f16ca7.png", + "b6618923-8455-44c3-8ae6-b766f34267cc.png", + "71d72043-3d97-4ea6-82f0-3ccbb53e0534.png", + "deb1e565-5c29-4285-aef8-f904c2b41dfb.png", + "ecf23b20-3db2-476a-bc06-442754ba5e76.png", + "39be4639-f28b-4bfa-8c1e-4b37e40395be.png", + "8bafdd4c-a44c-4bc0-8978-e7bc0abcedb4.png", + "3b958a28-0807-484a-92e7-f17b4c6dcbeb.png", + "ecd3c3fb-c4f2-4021-86d8-665e92b2735e.png", + "014ac251-0435-41c2-9dee-c664ee268327.png", + "0171bbba-6293-4117-b0ad-bc4b98d1c20e.png", + "0bd64a61-e098-4d06-ba3f-0a12269d3584.png", + "d5db5c5c-779b-4de0-ac66-31856239d488.png", + "9c47a3ac-2e56-47c1-86d4-006f98e21987.png", + "133b4eaf-bb93-4655-844c-a02278dfc032.png", + "58bcfa8c-6e11-494f-8fc5-d5a32ac7b3de.png", + "276de88a-374b-4dde-ac45-c52d651044b3.png", + "f52f1aaa-c061-42c0-8bdd-d2edb4af8736.png", + "1ccd1303-2e23-44c4-bb21-0dd474b0d899.png", + "761d55a2-5858-4d02-ab13-0bb272a67eed.png", + "c9d714cd-b00b-4d96-b6a6-cdc9e01c1b71.png", + "06da7e0e-c12c-4da7-a56b-9a3c82d87809.png", + "e5d1c208-34ad-49a7-8151-c0d55ecff952.png", + "9ccbd07a-887c-48c8-a806-0fac93606bb0.png", + "3d48ef42-02d9-41ed-bef6-f5c0dd47cdfa.png", + "9e1fd142-1d1c-4a82-a961-681db31b343f.png", + "5259cbe7-d956-4a0a-99d1-d7c7d391488f.png", + "94bdb3c5-faa2-4274-9337-ca5b9fabce88.png", + "e572f3d8-9ef2-4cd2-83c1-8acb766dbc4b.png", + "956782b3-ca4b-49e8-8939-6c50e87b9609.png", + "258270ae-3af4-4644-a031-176efac2c3f9.png", + "1fa52c2f-7474-4aa9-9ff9-0e411a78daac.png", + "f1299a54-59e5-42ea-9f53-e9f11fd6ca3c.png", + "6a6a86a2-bbba-422a-9620-5b90adaaf7a3.png", + "771c03d6-f0c8-4e3e-b734-0a07fff03c22.png", + "8c6ed656-6d1c-4707-82a2-cbff87a589f7.png", + "6a4f994f-293f-4a8a-8f8d-ac99f8e58adf.png", + "da90fb4d-3dfb-4a17-8ecc-95e82ab69b32.png", + "1563c9ee-30ab-44cc-b21f-fab5ad8df99d.png", + "932f5612-9058-4923-820d-894d630190cb.png", + "5e2958ab-c27d-41c8-8167-de9053f79038.png", + "2408cfed-ad91-43e2-9295-fdafafb76c8d.png", + "8549466d-50fe-4cb9-9001-e93532e7938c.png", + "00e4b598-2dd0-4ff9-b0a4-46e223a9296e.png", + "0666bf9a-4625-4132-bd7f-0079dace8c8c.png", + "ceb18b7d-1dcf-4aa2-adae-0e0aae1c5eeb.png", + "a4903060-7bfd-4bd5-b8d6-b916d172a82b.png", + "f5f4cf81-db71-42c7-b889-c25c145132c6.png", + "bf277536-38a6-41cd-a278-bd68e25816fd.png", + "a1cfe2ab-12cd-4d43-9ffc-77d48d0493f3.png", + "1c72f7db-374f-47db-8424-9526d4e7fa7a.png", + "3dc423ca-b351-429f-9842-1bd17e3ce360.png", + "2a8aea9d-218c-4601-8e8d-b98eb93fa461.png", + "451b6b8b-5d86-44ad-853b-e99153ba48e1.png", + "25d4c91a-c831-4249-b78e-a4b25d0b1ea1.png", + "b4f0036f-f2e7-4167-bbc4-708ee783052f.png", + "db04923e-96ac-41db-a16c-901f10a41bf0.png", + "65e832aa-974a-4ca8-9dd8-e90a96d75b6c.png", + "f66bf802-8273-4df7-a58a-faa8ba6ed46f.png", + "827976d2-dbab-47a3-905f-602e945a6b30.png", + "124bd263-2b8a-4057-9211-b36869047fd2.png", + "f69e2027-7163-4a53-8361-6050e5679242.png", + "d366b33d-335e-4a76-91f5-a5ce14266c89.png", + "adcb6ab3-7ecf-47f9-a11e-6a505ad23d98.png", + "2cea6a36-7053-4808-be22-fc5cc76b5531.png", + "ac3491a2-e817-4f5e-8453-ce34cb78a8a9.png", + "a875270b-fd82-409d-9bed-1d567657ff8e.png", + "f29cfb8b-d640-48a4-ae5e-02395ed7c6db.png", + "8c165058-abec-4ea9-9990-19b7eff4df4f.png", + "1c6ea15c-1cad-4a0c-838a-5eee8f99cfc9.png", + "897d7c04-f1bd-4bb1-bffb-bfada23a5b58.png", + "1b23c19f-7e79-4b96-a744-42615a72d722.png", + "f921b606-5363-41c2-aa93-dc8ec1475fda.png", + "efca4079-dd9f-4d54-8943-216d6c02e70a.png", + "040ff758-026f-4313-b390-ec86d3690f9d.png", + "0104c474-6473-4e05-b789-6bdb59f55da7.png", + "f73ed4a7-c1b1-4660-9eba-00f2ba25977b.png", + "0b184f66-ba4f-4fcd-9556-bea9f58dc9c6.png", + "7f638e9b-10e8-448c-a2f9-a75ae414dcfa.png", + "e563fd4b-656f-45f1-b803-df0d6dcb8bd3.png", + "0ed8ccf8-33e5-45a2-9200-4dc1a5565494.png", + "1ab263d2-ea24-4fe7-9383-f227aadc8c47.png", + "561d2d94-ec96-4246-974a-d9abc6f2297a.png", + "9af6ae6e-a842-4baa-a01e-cec57045c367.png", + "1c6fc0f3-d4ef-423b-9bba-d4a5d59c05df.png", + "76a72b39-24ec-4044-aad8-49f381939063.png", + "08ca0b3f-17e9-476e-9c17-ff81616c6bd7.png", + "9b637968-8173-44da-8f41-3943c4d182f9.png", + "725eb22a-2c4b-44b0-8aaf-bef282232601.png", + "3e81b87f-10ee-4f74-8ba8-1b724df383fb.png", + "fc9c7e5a-7abb-4ff6-84f2-9fce43bc200f.png", + "a8f33495-cd01-4b66-9c7e-3ba5edec6565.png", + "8585099d-cf7f-4c1c-8f36-937939dba42e.png", + "fe8afe85-5153-48cb-80e0-88de2a577f0c.png", + "46c59505-7dec-48f2-a0d1-c36ac213890e.png", + "95b636b0-8afb-4430-8f6a-1f4e0f4eb808.png", + "5ab4d96a-5401-45d8-977c-b3fef4e55ca9.png", + "8c8dd1cd-6c84-4fa8-b51b-ac736fda7a6c.png", + "76c7b19f-b375-48db-a1df-d79485a86d94.png", +] + +FLOOR_TEX_NAMES = [ + "8e4ea598-7170-4d24-ad12-42d45ef17a3b.png", + "9d7e7eac-9d81-4b04-8a07-ec35f9e7b58d.png", + "83c7c8bf-9277-4f59-88bd-1a4f428262ef.png", + "28359684-bb12-4b99-86b2-8c0998ee8fec.png", + "8ebc0bbe-1656-465e-b31e-766d1aceaec2.png", + "ada4e736-880d-4372-b148-218dc114c7fe.png", + "8a12dcf7-fc25-4341-9ea0-e583f1cc3d71.png", + "28f34ad5-b4f1-4b81-99cc-b04ed28d653b.png", + "b5350f4e-9521-4af1-a03f-a39e5d8b1796.png", + "14b4a5c3-69e0-425c-b8c5-ce495ab87409.png", + "022ec5c1-324e-4217-9f03-92b0e2f9c74f.png", + "9f345d0f-a768-4def-bebf-b818cf0c68dc.png", + "49de13f1-9488-4893-8398-48b0a5f27453.png", + "a938167f-6cb2-4e87-94f5-185eac06ff21.png", + "2aa2a926-fe72-4221-bd30-16e0a0cc9324.png", + "1671701f-60d2-4c71-95cc-8bdbb9f57ff9.png", + "8b24233c-7658-4d52-809d-a6fc71f37554.png", + "9582e8cc-89f5-464f-b183-2f21b8f0f267.png", + "8184ce85-7db2-4b23-908b-1170cc6830cf.png", + "32a18f41-8e7c-4a9d-b5ac-a7ba19a9ed35.png", + "56c9fb44-a8ee-469d-85d4-6d419f9dcba3.png", + "7ff039e9-7563-4ef0-b2ec-ce3d0d259a99.png", + "dbdd0778-8700-4967-bb52-75bbfa7eb29c.png", + "50578da0-60d8-4e12-800e-3df2fbf1bd5a.png", + "cedd99bd-8f8f-4d60-98e8-75e0af9b7e4f.png", + "b6c12637-3bd8-41d4-a787-3c2c271f4221.png", + "22c6be8e-a027-47dc-b2a1-3284cf5baad0.png", + "ed301cb6-fc33-4a6a-a2fd-4ce27a1f5bac.png", + "fc6bffaf-b9fd-4d51-a795-cb95d280dcab.png", + "310661bb-e74a-4b55-b999-ae1e2855990f.png", + "c327867a-02ea-4629-8059-181d3f341dc2.png", + "67a6f678-5f4b-4999-88fd-d0587299eb90.png", + "c65c9338-2903-4c6a-8015-dc606d24e659.png", + "e584ce4a-ff4d-461f-989e-5e4d21da42de.png", + "8776902b-74c1-4a54-94f2-320b4e89b5df.png", + "b588fa60-819c-4ae7-84bb-8f3de009ee1b.png", + "bdddfbd0-acc5-4e73-becb-c91f69986201.png", + "1f13ee23-d3f8-4fe4-b24d-97c4dece35c5.png", + "447fc81b-73c3-4502-8de7-9db654e62902.png", + "f78f9be1-385c-43ed-a89b-a4f11d45695f.png", + "c82d1a06-f78d-4e79-9b3e-23c4756d555d.png", + "573d34d2-a045-455c-b525-34a8571808eb.png", + "07f74135-07ab-4e29-bb00-4782f15ab59f.png", + "bec253e6-b2f0-48f2-afba-9207388a7937.png", + "0139f959-a4a8-4504-b6d2-f9351afd5941.png", + "8373a547-a792-438e-b941-f01ca1f0fb5d.png", + "b37ff2ac-f755-42f1-bdd4-a3a0f30fbfc6.png", + "f068688f-4b20-4d2f-b33a-9732b5050f72.png", + "c707d14d-3089-4a3e-a5b2-1088eda621bc.png", + "81ea9eea-29ea-4516-9e0d-e7ed0df98f5d.png", + "9aa36664-4ac6-4a50-b0e0-05c96f52c58e.png", + "c85db92d-b5a4-4fc8-aabd-9d4c82f3f444.png", + "df431f5c-699e-47ff-9161-b6e264a82163.png", + "4d8ea3e7-4a0b-4015-802c-cbbd0b12ba2e.png", + "3a34566d-b31f-4d3d-a86a-8038fde33b8c.png", + "83c6fd2f-caa2-4d53-b4d2-e19a7f12e6b4.png", + "ef044eea-9ebe-475e-bc05-d4e9d9255e39.png", + "02b897ed-2381-403a-aef1-095096993039.png", + "bb9ea1a0-7bfb-4aa2-85ee-0dbdb5001fa3.png", + "2afa8673-57cc-4953-b178-b57eedd9ad0a.png", + "2066e385-7798-47b3-89cc-1eaad15c75c4.png", + "45639cb9-7ac7-4d8c-a8a1-719d3a53d531.png", + "8f7fabcb-6875-4437-9d9c-27a2552c10dd.png", + "ce8ccc5f-20b9-4d06-aee6-fe85a6c02eaa.png", + "11fa953e-c11d-4dad-8e51-47cc6dc67aeb.png", + "8f51e06a-7bd0-4d2f-9a20-7821a975559a.png", + "1ef4cfa4-cf52-4efd-9fb3-6698650ee239.png", + "4d974231-cd17-4da5-ad9a-7faf83c2d683.png", + "cadaada3-e8f1-4bc7-af71-342215edbbb1.png", + "fb9b36a4-d87a-4c7f-a06c-a1e94869b96b.png", + "5daabcbd-0ce4-4dba-9342-c74d3da4fadf.png", + "612b00d2-819f-46ac-a599-38672184c842.png", + "0b5b5a9a-1435-4dfe-b6f4-19f4dbae1e8e.png", + "11f6a3bb-c36c-45c2-a429-501ac0cabc02.png", + "cf96c697-41f0-4d3c-a1d4-17d0d82719d0.png", + "81d9e9f2-8ff4-4d45-b1dd-d3afd3c62fb0.png", + "82036c07-5321-47c8-974c-27d58e526ba1.png", + "e793023f-7e5f-4211-9724-9022d3c8f920.png", + "0c01c256-4779-4093-a0b9-3347c31ef53f.png", + "9db099e2-56cb-4bec-becc-eb69c298866e.png", + "05f75518-7b70-4098-8983-aca459f33ddb.png", + "7c935010-badd-4fa4-8089-4fc9728dfe96.png", + "f9d057b1-5843-4b68-a58b-9fe87291a72f.png", + "9354be03-5a87-4ce8-85bc-8b0157abeb1c.png", + "9bfe963b-6d17-4704-8a9f-c2de48491b70.png", + "3b70d093-e264-4550-b5e5-f750ba577b78.png", + "67837bbb-05ae-4665-90e5-572130b7fc86.png", + "d339c422-36d0-40f3-8393-24076abb279c.png", + "5ccc395f-efd5-44af-b5f9-885789e26661.png", + "6d58d55a-34cc-455f-8b4c-004fabef6e11.png", + "5729f1d0-0796-4d82-99f7-76a171266fae.png", + "1e6da165-23cb-4426-91cf-450b3ac74e49.png", + "86ae5f3b-1a9c-4895-87eb-b526b403f332.png", + "4e53b13b-317a-484c-9b8b-7417453e45ff.png", + "8ddb08c1-facb-4fb1-841b-bde4e47fe584.png", + "41c3dbec-db54-4417-bb76-f51a4349943e.png", + "a2881fcf-1af3-46e9-87b0-c198fad703d1.png", + "808ec0fb-fcf8-4629-9296-38530521a95e.png", + "7c411449-a3c6-48e4-ab30-d08bca5938d6.png", + "0df28fee-6cef-48ae-9e8e-c0f0f3482412.png", +] + +WALL_TEX_NAMES = [ + "plain copy 49.png", + "18a6abbd-8ca1-43d9-9a0a-8424a7d1e016.png", + "plain copy 2.png", + "0882d081-d8be-49c0-aad6-3f5eff92265b.png", + "plain copy 39.png", + "7a19bf00-4f43-4e39-8fe6-977df7c6d147.png", + "plain copy 8.png", + "9b6f9830-a89d-4a42-965f-581dd0a12617.png", + "bcf9bf9b-ac75-408e-ab2e-516391c39d8e.png", + "plain copy 51.png", + "845424a1-4603-47d7-892c-426c2d427f0d.png", + "6e961263-5c90-41f9-87d3-b9e132c9583a.png", + "c72ea705-e088-4665-9683-6a8685758aef.png", + "plain copy 22.png", + "plain copy 44.png", + "plain copy 10.png", + "df17f0f3-68bb-46e2-ae9f-86cf84f48b04.png", + "plain copy 53.png", + "0906d773-7c22-4173-9edc-efc6e2da88e0.png", + "8995f82f-2435-4395-8ecd-a00824edd923.png", + "0adf5feb-6a2f-4417-811a-b7d70d42fb34.png", + "plain copy 5.png", + "536410ee-0460-43b0-9e8e-799e96439a0d.png", + "plain copy 11.png", + "plain copy 19.png", + "plain copy 17.png", + "plain copy.png", + "plain copy 31.png", + "Lance_Z._white_square_tiles_texture_image_ikea_high_quality_rea_f41b5937-af3e-4df8-b19d-ae4fa942f741.png", + "f6353155-1a10-41a1-be1d-149368938757.png", + "b1a7c75f-6b03-4b10-99cd-3299d7b6beb5.png", + "plain copy 52.png", + "7844f4b6-7d34-46b4-8ea4-19ab954ca58f.png", + "0dd40625-0cf8-4523-92cd-063c96108a23.png", + "plain copy 40.png", + "plain copy 21.png", + "plain copy 36.png", + "plain copy 37.png", + "plain copy 41.png", + "plain copy 23.png", + "1b8b8a44-ce4e-4156-978b-ad66bf4a6f45.png", + "plain copy 46.png", + "d208d65f-4d99-4963-8140-d54180844c8c.png", + "0aa2c331-8025-4417-a157-91467143c85b.png", + "d4775c13-15ea-496d-b5fc-19d2a9cab128.png", + "11760e4b-5f86-46cb-82ae-c87cc6f434d1.png", + "plain copy 3.png", + "plain copy 30.png", + "plain copy 9.png", + "0af727bd-14b4-4f7d-9fee-19f7f001ad34.png", + "67d1229f-7689-4dd6-ab2b-d003e0cd3cb7.png", + "plain copy 33.png", + "plain copy 4.png", + "2149f068-ca27-40ed-b53d-07e53210e678.png", + "plain copy 38.png", + "6b215002-fd31-4f1a-859a-d5d98a2a0c52.png", + "4fe97e2e-ae88-4dc9-8321-3529a2108508.png", + "Lance_Z._white_square_tiles_ikea_high_quality_realistic_ec4bd31e-d76d-4512-8b0d-a86dd8dd6aad.png", + "plain copy 6.png", + "plain copy 13.png", + "0d7afefe-58c8-4161-bf56-0974c7e806a2.png", + "plain copy 28.png", + "314f4070-0b2f-4433-98e7-dbdf18a8bff2.png", + "plain copy 18.png", + "dae6863d-b653-4998-8239-c6a6bb24362c.png", + "497cbc0b-a80a-42b3-8f5e-3bc97c145255.png", + "plain copy 20.png", + "4874a0d3-f5f2-46ea-a1d3-824b2f56f8ce.png", + "plain copy 50.png", + "plain copy 12.png", + "7c7c9950-576a-45fd-b3d1-74cca30f6fe7.png", + "8474c563-65b7-408b-976f-b19b38a44f90.png", + "Lance_Z._white_square_tiles_texture_image_ikea_high_quality_rea_ce2dcd92-29d7-4176-b7fa-79d91dab133b.png", + "738a1240-97f3-4fa6-97df-0ecc4b7aac26.png", + "plain copy 32.png", + "plain copy 29.png", + "a4046f8f-a2d6-4ef4-aa39-2ec541cbd246.png", + "plain copy 25.png", + "cbf05cdc-5d1c-472b-9891-0e4802553359.png", + "plain copy 16.png", + "plain copy 47.png", + "4bb0ad30-b60a-44a6-a259-058fab19b422.png", + "77abb443-a1b8-4b02-96de-1a7bc68d4f3f.png", + "plain copy 27.png", + "plain copy 24.png", + "plain copy 43.png", + "35ded0fe-73a7-4e82-8c01-32f79f5214a3.png", + "4b9d5219-38a0-4303-8837-29c4c51eed54.png", + "8949ad7c-2b89-444c-a758-b513f25937e1.png", + "plain copy 48.png", + "plain copy 45.png", + "plain copy 35.png", + "plain copy 26.png", + "plain copy 42.png", + "f7c0d850-4b56-484f-85ce-e9c4bd01ec22.png", + "9ec0b130-598a-4471-99ee-f68ee49a4a9f.png", + "b1dcb5d2-434e-4bd1-9329-eb1c2a6c039d.png", + "cf0d9763-3596-48de-af34-5f3647d812df.png", + "plain copy 14.png", + "fda88519-7a09-466d-84a2-19b216562dcb.png", +] + + +def get_random_textures(rng, frac=1.0): + """ + This function returns a dictionary of random textures for cabinet, counter top, floor, and wall. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + frac (float): Fraction of textures to select from the list of available textures + Default: 1.0 (select from all textures) + + Returns: + textures (dict): Dictionary of texture paths + """ + + end_ind = int(frac * 100) + ind = rng.integers(0, end_ind) + + textures = dict( + cab_tex=os.path.join(TEXTURES_DIR, "cabinet", CABINET_TEX_NAMES[ind]), + counter_tex=os.path.join(TEXTURES_DIR, "counter", COUNTER_TOP_TEX_NAMES[ind]), + floor_tex=os.path.join(TEXTURES_DIR, "floor", FLOOR_TEX_NAMES[ind]), + wall_tex=os.path.join(TEXTURES_DIR, "wall", WALL_TEX_NAMES[ind]), + ) + + return textures + + +def replace_counter_top_texture(rng, initial_state: str, new_counter_top_texture_file: str = None): + """ + This function replaces the counter top textures during playback. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + initial_state (str): Initial env XML string + + new_counter_top_texture_file (str): New texture file for counter top: i.e "marble/dark_marble.png" + If None (default), will replace with a random texture from marble directory + """ + + root = ET.fromstring(initial_state) + asset = root.find("asset") + + if new_counter_top_texture_file is None: + new_counter_top_texture_file = get_random_textures(rng)["counter_tex"] + else: + new_counter_top_texture_file = os.path.join(TEXTURES_DIR, new_counter_top_texture_file) + + # step 1: find the name of texture that will be replaced + counter_tex_name = None + for mat in asset.findall("material"): + name = mat.get("name") + if "counter_top" in name: + counter_tex_name = mat.get("texture") + break + assert counter_tex_name is not None + + # step 2: find and replace texture element + CTOP_TEX_NAME = "counter_top_replacement_texture" + for tex in asset.findall("texture"): + name = tex.get("name") + if name == counter_tex_name: + tex.set("name", CTOP_TEX_NAME) + tex.set("file", str(new_counter_top_texture_file)) + + # step 3: reference new textures in materials + for mat in asset.findall("material"): + name = mat.get("name") + if "counter_top" in name: + mat.set("texture", CTOP_TEX_NAME) + + return ET.tostring(root).decode("utf-8") + + +def replace_cab_textures(rng, initial_state: str, new_cab_texture_file: str = None): + """ + This function replaces the cabinet and counter base textures during playback. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + initial_state (str): Initial env XML string + + new_cab_texture_file (str): New texture file for counter base and cabinets: i.e "cabinet/..." + If None (default), will replace with a random texture from flat or wood directories + """ + + root = ET.fromstring(initial_state) + asset = root.find("asset") + + if new_cab_texture_file is None: + new_cab_texture_file = get_random_textures(rng)["cab_tex"] + else: + new_cab_texture_file = os.path.join(TEXTURES_DIR, new_cab_texture_file) + + CAB_TEX_NAME_2D = "cab_replacement_texture_2d" + tex_2d = find_elements( + asset, tags="texture", attribs={"name": CAB_TEX_NAME_2D}, return_first=True + ) + if tex_2d is not None: + tex_2d.set("file", str(new_cab_texture_file)) + else: + tex_2d = ET.Element( + "texture", type="2d", name=CAB_TEX_NAME_2D, file=str(new_cab_texture_file) + ) + asset.append(tex_2d) + + CAB_TEX_NAME_CUBE = "cab_replacement_texture_cube" + tex_cube = find_elements( + asset, tags="texture", attribs={"name": CAB_TEX_NAME_CUBE}, return_first=True + ) + if tex_cube is not None: + tex_cube.set("file", str(new_cab_texture_file)) + else: + tex_cube = ET.Element( + "texture", + type="cube", + name=CAB_TEX_NAME_CUBE, + file=str(new_cab_texture_file), + ) + asset.append(tex_cube) + + for mat in asset.findall("material"): + name = mat.get("name") + if "counter_base" in name: + mat.set("texture", CAB_TEX_NAME_CUBE) + elif "housing" in name: + mat.set("texture", CAB_TEX_NAME_CUBE) + elif ( + "stack" in name + or "cab" in name + or "shelves" in name + or "bottom" in name + or ("top" in name and "counter" not in name and "stove" not in name) + ): + if "handle" in name or "transparent" in name: + continue + elif "door" in name: + mat.set("texture", CAB_TEX_NAME_2D) + elif "shelves" in name: + mat.set("texture", CAB_TEX_NAME_2D) + else: + mat.set("texture", CAB_TEX_NAME_CUBE) + + return ET.tostring(root).decode("utf-8") + + +def replace_floor_texture(rng, initial_state: str, new_floor_texture_file: str = None): + """ + This function replaces the counter top textures during playback. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + initial_state (str): Initial env XML string + + new_floor_texture_file (str): New texture file for counter top: i.e "wood/dark_wood_planks_2.png" + If None (default), will replace with a random texture from wood directory + """ + + root = ET.fromstring(initial_state) + asset = root.find("asset") + + if new_floor_texture_file is None: + new_floor_texture_file = get_random_textures(rng)["floor_tex"] + else: + new_floor_texture_file = os.path.join(TEXTURES_DIR, new_floor_texture_file) + + # step 1: find the name of texture that will be replaced + floor_tex_name = None + for mat in asset.findall("material"): + name = mat.get("name") + if "floor" in name and "backing" not in name: + floor_tex_name = mat.get("texture") + break + assert floor_tex_name is not None + + # step 2: find and replace texture element + FLOOR_TEX_NAME = "floor_replacement_texture" + for tex in asset.findall("texture"): + name = tex.get("name") + if name == floor_tex_name: + tex.set("name", FLOOR_TEX_NAME) + tex.set("file", str(new_floor_texture_file)) + tex.set("type", "2d") + + # step 3: reference new textures in materials + for mat in asset.findall("material"): + name = mat.get("name") + if "floor" in name and "backing" not in name: + mat.set("texture", FLOOR_TEX_NAME) + mat.set("texrepeat", "2 2") + + return ET.tostring(root).decode("utf-8") + + +def replace_wall_texture(rng, initial_state: str, new_wall_texture_file: str = None): + """ + This function replaces the counter top textures during playback. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + initial_state (str): Initial env XML string + + new_wall_texture_file (str): New texture file for counter top: i.e "wood/dark_wood_planks_2.png" + If None (default), will replace with a random texture from wood directory + """ + + root = ET.fromstring(initial_state) + asset = root.find("asset") + + if new_wall_texture_file is None: + new_wall_texture_file = get_random_textures(rng)["wall_tex"] + else: + new_wall_texture_file = os.path.join(TEXTURES_DIR, new_wall_texture_file) + + # step 1: find the name of texture that will be replaced + wall_tex_name = None + for mat in asset.findall("material"): + name = mat.get("name") + if "wall" in name and "floor" not in name and "backing" not in name: + wall_tex_name = mat.get("texture") + break + assert wall_tex_name is not None + + # step 2: add new texture element + WALL_TEX_NAME = "wall_replacement_texture" + for tex in asset.findall("texture"): + name = tex.get("name") + if name == wall_tex_name: + tex.set("name", WALL_TEX_NAME) + tex.set("file", str(new_wall_texture_file)) + tex.set("type", "2d") + + # step 3: reference new textures in materials + for mat in asset.findall("material"): + name = mat.get("name") + if "wall" in name and "floor" not in name and "backing" not in name: + mat.set("texture", WALL_TEX_NAME) + mat.set("texrepeat", "3 3") + + return ET.tostring(root).decode("utf-8") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/transform_utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/transform_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2dc6892d22b5170ee5d630ff85c41280ddb720aa --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/transform_utils.py @@ -0,0 +1,56 @@ +from robosuite.utils.transform_utils import * + + +def unmake_pose(pose): + """ + Split homogenous pose matrices back into translation vectors and rotation matrices. + + Args: + pose (np.array): batch of pose matrices with last 2 dimensions of (4, 4) + + Returns: + pos (np.array): batch of position vectors with last dimension of 3 + rot (np.array): batch of rotation matrices with last 2 dimensions of (3, 3) + """ + return pose[..., :3, 3], pose[..., :3, :3] + + +def standardize_quat(quaternions): + """ + Convert a unit quaternion to a standard form: one in which the real + part is non negative. + + Args: + quaternions: Quaternions with real part last (e.g. xyzw), + as tensor of shape (..., 4). + + Returns: + Standardized quaternions as tensor of shape (..., 4). + """ + # if isinstance(quaternions, torch.Tensor): + # return torch.where(quaternions[..., 3:4] < 0, -quaternions, quaternions) + return np.where(quaternions[..., 3:4] < 0, -quaternions, quaternions) + + +def pose_in_world_to_pose_in_ref(pos_in_world, rot_in_world, ref_pos, ref_rot): + """ + Takes a pose in world frame and a reference pose (in world frame) and + transforms the pose to be with respect to the reference frame. + """ + + # Let O be the frame of the item of interest, R be the reference frame, + # and W be the world frame. Then, + # + # T^O_R = (T^R_W)^-1 T^O_W + pose_in_world = make_pose(pos_in_world, rot_in_world) + ref_pose = make_pose(ref_pos, ref_rot) + world_in_ref = pose_inv(ref_pose) + return np.matmul(world_in_ref, pose_in_world) + + +def extract_top_down_angle(rotation_matrix): + """ + Gets top-down angle about z-axis for a given 3D rotation matrix, assuming + that the rotation matrix corresponds to a simple rotation about z-axis. + """ + return np.arctan2(rotation_matrix[1, 0], rotation_matrix[0, 0]) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/README.md b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/README.md new file mode 100644 index 0000000000000000000000000000000000000000..770a519c87571a33b1186d770cc17c619ce524fc --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/README.md @@ -0,0 +1,30 @@ +# MuJoCo USD Integration + +USD is file format originally introduced by Pixar to compose 3D scenes in virtual worlds. We implement the ability to export MuJoCo models and trajectories as USD files for visualization with external renderers such as NVIDIA Omniverse and Blender. + +## Installation + +We assume that users have already installed MuJoCo either directly with pip or from source. For information on how to build MuJoCo from source, please visit this [reference](https://mujoco.readthedocs.io/en/stable/python.html#building-from-source). We also assume Python>=3.8. + +Using the USD bridge functionality requires the installation of additional libraries. Specifically, we utilize the `open3d` and `usd-core` packages. These can be installed directly using pip. + +```bash +pip install open3d +pip install usd-core +``` + +## Getting Started + +We provide a demo script to get started with generating USD files. This demo script is located at `python/mujoco/usd/demo.py`. In this script, we load a the `cards.xml` model and step through it for a given number of steps. At each step, we make a call to the USD exporter to store information for any state changes including the positions and orientations of geoms in the scene. + +## TODOs and Known Bugs + +TODOs: + +- Include tendons and contact forces in USD file +- Include references to third party materials for NVIDIA Omniverse in USD file +- Including custom defined matrials for NVIDIA Omniverse +- Bridge for modeling environments and assets from third party modeling engines to MuJoCo + +Known issues 🐛: +- Texture mapping for non-UV objects not consistent with MuJoCo renderer when ported to new renderers \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..981ddeef54d2acf88184035bad291e59e256a100 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/__init__.py @@ -0,0 +1,4 @@ +from .component import * +from .exporter import * +from .shapes import * +from .utils import * diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/component.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/component.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0f90a45d9a6e7357b826e2284720e598a11014 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/component.py @@ -0,0 +1,429 @@ +# Copyright 2024 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +from typing import List, Optional, Tuple + +import mujoco +import numpy as np + +# TODO: b/288149332 - Remove once USD Python Binding works well with pytype. +# pytype: disable=module-attr +# from open3d import open3d as o3d +# import open3d as o3d +from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade, Vt + +import robocasa.utils.usd.shapes as shapes_component +import robocasa.utils.usd.utils as utils_component + + +class USDMesh: + def __init__( + self, + stage: Usd.Stage, + model: mujoco.MjModel, + geom: mujoco.MjvGeom, + obj_name: str, + dataid: int, + rgba: np.ndarray = np.array([1, 1, 1, 1]), + texture_file: Optional[str] = None, + ): + self.stage = stage + self.model = model + self.geom = geom + self.obj_name = obj_name + self.rgba = rgba + self.dataid = dataid + self.texture_file = texture_file + + xform_path = f"/World/Mesh_Xform_{obj_name}" + mesh_path = f"{xform_path}/Mesh_{obj_name}" + self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) + self.usd_mesh = UsdGeom.Mesh.Define(stage, mesh_path) + self.usd_prim = stage.GetPrimAtPath(mesh_path) + + # setting mesh structure properties + mesh_vert, mesh_face, mesh_facenum = self._get_mesh_geometry() + self.usd_mesh.GetPointsAttr().Set(mesh_vert) + self.usd_mesh.GetFaceVertexCountsAttr().Set([3 for _ in range(mesh_facenum)]) + self.usd_mesh.GetFaceVertexIndicesAttr().Set(mesh_face) + + # setting mesh uv properties + mesh_texcoord, mesh_facetexcoord = self._get_uv_geometry() + self.texcoords = UsdGeom.PrimvarsAPI(self.usd_mesh).CreatePrimvar( + "UVMap", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying + ) + self.texcoords.Set(mesh_texcoord) + self.texcoords.SetIndices(Vt.IntArray(mesh_facetexcoord.tolist())) + + self._attach_material() + + # defining ops required by update function + self.transform_op = self.usd_xform.AddTransformOp() + + def get_facetexcoord_ranges(self, nmesh, arr): + facetexcoords_ranges = [0] + running_sum = 0 + for i in range(nmesh): + running_sum += arr[i] * 3 + facetexcoords_ranges.append(running_sum) + return facetexcoords_ranges + + def _get_uv_geometry(self): + mesh_texcoord_adr_from = self.model.mesh_texcoordadr[self.dataid] + mesh_texcoord_adr_to = ( + self.model.mesh_texcoordadr[self.dataid + 1] + if self.dataid < self.model.nmesh - 1 + else len(self.model.mesh_texcoord) + ) + mesh_texcoord = self.model.mesh_texcoord[mesh_texcoord_adr_from:mesh_texcoord_adr_to] + + mesh_facetexcoord_ranges = self.get_facetexcoord_ranges( + self.model.nmesh, self.model.mesh_facenum + ) + + mesh_facetexcoord = self.model.mesh_facetexcoord.flatten() + mesh_facetexcoord = mesh_facetexcoord[ + mesh_facetexcoord_ranges[self.dataid] : mesh_facetexcoord_ranges[self.dataid + 1] + ] + + mesh_facetexcoord[mesh_facetexcoord == len(mesh_texcoord)] = 0 + + return mesh_texcoord, mesh_facetexcoord + + def _get_mesh_geometry(self): + mesh_vert_adr_from = self.model.mesh_vertadr[self.dataid] + mesh_vert_adr_to = ( + self.model.mesh_vertadr[self.dataid + 1] + if self.dataid < self.model.nmesh - 1 + else len(self.model.mesh_vert) + ) + mesh_vert = self.model.mesh_vert[mesh_vert_adr_from:mesh_vert_adr_to] + + mesh_face_adr_from = self.model.mesh_faceadr[self.dataid] + mesh_face_adr_to = ( + self.model.mesh_faceadr[self.dataid + 1] + if self.dataid < self.model.nmesh - 1 + else len(self.model.mesh_face) + ) + mesh_face = self.model.mesh_face[mesh_face_adr_from:mesh_face_adr_to] + + mesh_facenum = self.model.mesh_facenum[self.dataid] + + return mesh_vert, mesh_face, mesh_facenum + + def _attach_material(self): + mtl_path = Sdf.Path(f"/World/_materials/Material_{self.obj_name}") + mtl = UsdShade.Material.Define(self.stage, mtl_path) + + if self.texture_file: + bsdf_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Principled_BSDF")) + image_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Image_Texture")) + uvmap_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("uvmap")) + + # setting the bsdf shader attributes + bsdf_shader.CreateIdAttr("UsdPreviewSurface") + bsdf_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource( + image_shader.ConnectableAPI(), "rgb" + ) + bsdf_shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(float(self.rgba[-1])) + bsdf_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(self.geom.shininess) + bsdf_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( + 1.0 - self.geom.shininess + ) + + mtl.CreateSurfaceOutput().ConnectToSource(bsdf_shader.ConnectableAPI(), "surface") + + self.usd_mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) + UsdShade.MaterialBindingAPI(self.usd_mesh).Bind(mtl) + + # setting the image texture attributes + image_shader.CreateIdAttr("UsdUVTexture") + image_shader.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.texture_file) + image_shader.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set("sRGB") + image_shader.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") + image_shader.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") + image_shader.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource( + uvmap_shader.ConnectableAPI(), "result" + ) + image_shader.CreateOutput("rgb", Sdf.ValueTypeNames.Float3) + + # setting uvmap shader attributes + uvmap_shader.CreateIdAttr("UsdPrimvarReader_float2") + uvmap_shader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set("UVMap") + uvmap_shader.CreateOutput("results", Sdf.ValueTypeNames.Float2) + else: + bsdf_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Principled_BSDF")) + + # settings the bsdf shader attributes + bsdf_shader.CreateIdAttr("UsdPreviewSurface") + + bsdf_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set( + tuple(self.rgba[0:3]) + ) + bsdf_shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(float(self.rgba[-1])) + bsdf_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(self.geom.shininess) + bsdf_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( + 1.0 - self.geom.shininess + ) + + mtl.CreateSurfaceOutput().ConnectToSource(bsdf_shader.ConnectableAPI(), "surface") + + self.usd_mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) + UsdShade.MaterialBindingAPI(self.usd_mesh).Bind(mtl) + + def update(self, pos: np.ndarray, mat: np.ndarray, visible: bool, frame: int): + transformation_mat = utils_component.create_transform_matrix( + rotation_matrix=mat, translation_vector=pos + ).T + self.transform_op.Set(Gf.Matrix4d(transformation_mat.tolist()), frame) + self.update_visibility(visible, frame) + + def update_visibility(self, visible: bool, frame: int): + if visible: + self.usd_prim.GetAttribute("visibility").Set("inherited", frame) + else: + self.usd_prim.GetAttribute("visibility").Set("invisible", frame) + + +class USDPrimitiveMesh: + def __init__( + self, + mesh_config: List[dict], + stage: Usd.Stage, + geom: mujoco.MjvGeom, + obj_name: str, + rgba: np.ndarray = np.array([1, 1, 1, 1]), + texture_file: Optional[str] = None, + ): + self.mesh_config = mesh_config + self.stage = stage + self.geom = geom + self.obj_name = obj_name + self.rgba = rgba + self.texture_file = texture_file + + self.usd_prim = Usd.Prim() + self.usd_mesh = UsdGeom.Mesh() + self.prim_mesh = None + self.transform_op = Gf.Matrix4d(1.0) + + _, self.prim_mesh = shapes_component.mesh_generator(mesh_config) + + xform_path = f"/World/{self.obj_name}_Xform" + mesh_path = f"{xform_path}/{obj_name}" + self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) + self.usd_mesh = UsdGeom.Mesh.Define(stage, mesh_path) + self.usd_prim = stage.GetPrimAtPath(mesh_path) + + self.prim_mesh.translate(-self.prim_mesh.get_center()) + + mesh_vert, mesh_face, mesh_facenum = self._get_mesh_geometry() + self.usd_mesh.GetPointsAttr().Set(mesh_vert) + self.usd_mesh.GetFaceVertexCountsAttr().Set([3 for _ in range(mesh_facenum)]) + self.usd_mesh.GetFaceVertexIndicesAttr().Set(mesh_face) + + # setting mesh uv properties + mesh_texcoord, mesh_facetexcoord = self._get_uv_geometry() + self.texcoords = UsdGeom.PrimvarsAPI(self.usd_mesh).CreatePrimvar( + "UVMap", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying + ) + + self.texcoords.Set(mesh_texcoord) + self.texcoords.SetIndices(Vt.IntArray([i for i in range(mesh_facenum * 3)])) + + self._set_refinement_properties() + + # setting attributes for the shape + self._attach_material() + + # defining ops required by update function + self.transform_op = self.usd_xform.AddTransformOp() + + def _set_refinement_properties(self): + self.usd_prim.GetAttribute("subdivisionScheme").Set("none") + + def _get_uv_geometry(self): + + assert self.prim_mesh + + x_scale, y_scale = self.geom.texrepeat + + mesh_texcoord = np.array(self.prim_mesh.triangle_uvs) + mesh_facetexcoord = np.asarray(self.prim_mesh.triangles) + + x_multiplier, y_multiplier = 1, 1 + if self.geom.texuniform: + x_multiplier, y_multiplier = self.geom.size[:2] + + mesh_texcoord[:, 0] *= x_scale * x_multiplier + mesh_texcoord[:, 1] *= y_scale * y_multiplier + + return mesh_texcoord, mesh_facetexcoord.flatten() + + def _get_mesh_geometry(self): + + assert self.prim_mesh + + # get mesh geometry from the open3d mesh model + mesh_vert = np.asarray(self.prim_mesh.vertices) + mesh_face = np.asarray(self.prim_mesh.triangles) + + return mesh_vert, mesh_face, len(mesh_face) + + def _attach_material(self): + mtl_path = Sdf.Path(f"/World/_materials/Material_{self.obj_name}") + mtl = UsdShade.Material.Define(self.stage, mtl_path) + if self.texture_file: + bsdf_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Principled_BSDF")) + image_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Image_Texture")) + uvmap_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("uvmap")) + + # setting the bsdf shader attributes + bsdf_shader.CreateIdAttr("UsdPreviewSurface") + bsdf_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource( + image_shader.ConnectableAPI(), "rgb" + ) + bsdf_shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(float(self.rgba[-1])) + bsdf_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(self.geom.shininess) + bsdf_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( + 1.0 - self.geom.shininess + ) + + mtl.CreateSurfaceOutput().ConnectToSource(bsdf_shader.ConnectableAPI(), "surface") + + self.usd_mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) + UsdShade.MaterialBindingAPI(self.usd_mesh).Bind(mtl) + + # setting the image texture attributes + image_shader.CreateIdAttr("UsdUVTexture") + image_shader.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.texture_file) + image_shader.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set("sRGB") + image_shader.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") + image_shader.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") + image_shader.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource( + uvmap_shader.ConnectableAPI(), "result" + ) + image_shader.CreateOutput("rgb", Sdf.ValueTypeNames.Float3) + + # setting uvmap shader attributes + uvmap_shader.CreateIdAttr("UsdPrimvarReader_float2") + uvmap_shader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set("UVMap") + uvmap_shader.CreateOutput("results", Sdf.ValueTypeNames.Float2) + else: + bsdf_shader = UsdShade.Shader.Define(self.stage, mtl_path.AppendPath("Principled_BSDF")) + + # settings the bsdf shader attributes + bsdf_shader.CreateIdAttr("UsdPreviewSurface") + bsdf_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set( + tuple(self.rgba[:3]) + ) + bsdf_shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(float(self.rgba[-1])) + bsdf_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(self.geom.shininess) + bsdf_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( + 1.0 - self.geom.shininess + ) + + mtl.CreateSurfaceOutput().ConnectToSource(bsdf_shader.ConnectableAPI(), "surface") + + self.usd_mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) + UsdShade.MaterialBindingAPI(self.usd_mesh).Bind(mtl) + + def update(self, pos: np.ndarray, mat: np.ndarray, visible: bool, frame: int): + transformation_mat = utils_component.create_transform_matrix( + rotation_matrix=mat, translation_vector=pos + ).T + self.transform_op.Set(Gf.Matrix4d(transformation_mat.tolist()), frame) + self.update_visibility(visible, frame) + + def update_visibility(self, visible: bool, frame: int): + if visible: + self.usd_prim.GetAttribute("visibility").Set("inherited", frame) + else: + self.usd_prim.GetAttribute("visibility").Set("invisible", frame) + + +class USDSphereLight: + def __init__(self, stage: Usd.Stage, obj_name: str, radius: Optional[float] = 0.3): + self.stage = stage + + xform_path = f"/World/Light_Xform_{obj_name}" + light_path = f"{xform_path}/Light_{obj_name}" + self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) + self.usd_light = UsdLux.SphereLight.Define(stage, light_path) + self.usd_prim = stage.GetPrimAtPath(light_path) + + # we assume in mujoco that all lights are point lights + self.usd_light.GetRadiusAttr().Set(radius) + self.usd_light.GetTreatAsPointAttr().Set(False) + self.usd_light.GetNormalizeAttr().Set(True) + + # defining ops required by update function + self.translate_op = self.usd_xform.AddTranslateOp() + + def update(self, pos: np.ndarray, intensity: int, color: np.ndarray, frame: int): + self.translate_op.Set(Gf.Vec3d(pos.tolist()), frame) + + if not np.any(pos): + intensity = 0 + + self.usd_light.GetIntensityAttr().Set(intensity) + self.usd_light.GetColorAttr().Set(Gf.Vec3d(color.tolist())) + + +class USDDomeLight: + def __init__(self, stage: Usd.Stage, obj_name: str): + self.stage = stage + + xform_path = f"/World/Light_Xform_{obj_name}" + light_path = f"{xform_path}/Light_{obj_name}" + self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) + self.usd_light = UsdLux.DomeLight.Define(stage, light_path) + self.usd_prim = stage.GetPrimAtPath(light_path) + + # we assume in mujoco that all lights are point lights + self.usd_light.GetNormalizeAttr().Set(True) + + def update(self, intensity: int, color: np.ndarray, frame: int): + self.usd_light.GetIntensityAttr().Set(intensity) + self.usd_light.GetExposureAttr().Set(0.0) + self.usd_light.GetColorAttr().Set(Gf.Vec3d(color.tolist())) + + +class USDCamera: + def __init__(self, stage: Usd.Stage, obj_name: str): + self.stage = stage + + xform_path = f"/World/Camera_Xform_{obj_name}" + camera_path = f"{xform_path}/Camera_{obj_name}" + self.usd_xform = UsdGeom.Xform.Define(stage, xform_path) + self.usd_camera = UsdGeom.Camera.Define(stage, camera_path) + self.usd_prim = stage.GetPrimAtPath(camera_path) + + # defining ops required by update function + self.transform_op = self.usd_xform.AddTransformOp() + + # self.usd_camera.CreateFocalLengthAttr().Set(18.14756) # default in omniverse + self.usd_camera.CreateFocalLengthAttr().Set(12) + self.usd_camera.CreateFocusDistanceAttr().Set(400) + + self.usd_camera.GetHorizontalApertureAttr().Set(12) + + self.usd_camera.GetClippingRangeAttr().Set(Gf.Vec2f(1e-4, 1e6)) + + def update(self, cam_pos: np.ndarray, cam_mat: np.ndarray, frame: int): + + transformation_mat = utils_component.create_transform_matrix( + rotation_matrix=cam_mat, translation_vector=cam_pos + ).T + self.transform_op.Set(Gf.Matrix4d(transformation_mat.tolist()), frame) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/demo.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/demo.py new file mode 100644 index 0000000000000000000000000000000000000000..629895e9b9566c303a85a20889fd2b60ea50db6d --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/demo.py @@ -0,0 +1,58 @@ +import argparse +from pathlib import Path + +import mujoco +from tqdm import tqdm + +from robocasa.utils.usd import exporter + + +def generate_usd_trajectory(args): + + # load a model to mujoco + model_path = args.model_path + m = mujoco.MjModel.from_xml_path(model_path) + d = mujoco.MjData(m) + + # create an instance of the USDExporter + exp = exporter.USDExporter( + model=m, + output_directory_name=Path(args.model_path).stem, + output_directory_root=args.output_directory_root, + camera_names=args.camera_names, + ) + + # step through the model for length steps + for i in tqdm(range(args.length)): + mujoco.mj_step(m, d) + exp.update_scene(d) + + exp.save_scene(filetype=args.export_extension) + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + + parser.add_argument("--model_path", type=str, required=True, help="path to mjcf xml model") + + parser.add_argument("--length", type=int, default=100, help="length of trajectory to render") + + parser.add_argument( + "--output_directory_root", + type=str, + default="../usd_trajectories/", + help="location where to create usd files", + ) + + parser.add_argument("--camera_names", type=str, nargs="+", help="cameras to include in usd") + + parser.add_argument( + "--export_extension", + type=str, + default="usd", + help="extension of exported file (can be usd, usda, or usdc)", + ) + + args = parser.parse_args() + generate_usd_trajectory(args) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..cca598887d8dff2aa3189cb71a5f7ed9907bcea9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter.py @@ -0,0 +1,403 @@ +# Copyright 2024 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +import os +from typing import List, Optional, Tuple, Union + +import mujoco +import numpy as np +import scipy +import termcolor +import tqdm +from PIL import Image as im +from PIL import ImageOps + +# TODO: b/288149332 - Remove once USD Python Binding works well with pytype. +# pytype: disable=module-attr +from pxr import Sdf, Usd, UsdGeom + +import robocasa.utils.usd.component as component_module +import robocasa.utils.usd.shapes as shapes_module + + +class USDExporter: + def __init__( + self, + model: mujoco.MjModel, + height: int = 480, + width: int = 480, + max_geom: int = 10000, + output_directory_name: str = "mujoco_usdpkg", + output_directory_root: str = "./", + light_intensity: int = 10000, + camera_names: Optional[List[str]] = None, + specialized_materials_file: Optional[str] = None, + verbose: bool = True, + ): + """Initializes a new USD Exporter + + Args: + model: an MjModel instance. + height: image height in pixels. + width: image width in pixels. + max_geom: Optional integer specifying the maximum number of geoms that + can be rendered in the same scene. If None this will be chosen + automatically based on the estimated maximum number of renderable + geoms in the model. + output_directory_name: name of root directory to store outputted frames + and assets generated by the USD renderer. + output_directory_root: path to root directory storing generated frames + and assets by the USD renderer. + verbose: decides whether to print updates. + """ + + buffer_width = model.vis.global_.offwidth + buffer_height = model.vis.global_.offheight + + if width > buffer_width: + raise ValueError( + f""" + Image width {width} > framebuffer width {buffer_width}. Either reduce the image + width or specify a larger offscreen framebuffer in the model XML using the + clause: + + + """.lstrip() + ) + + if height > buffer_height: + raise ValueError( + f""" + Image height {height} > framebuffer height {buffer_height}. Either reduce the + image height or specify a larger offscreen framebuffer in the model XML using + the clause: + + + """.lstrip() + ) + + self.model = model + self.height = height + self.width = width + self.max_geom = max_geom + self.output_directory_name = output_directory_name + self.output_directory_root = output_directory_root + self.light_intensity = light_intensity + self.camera_names = camera_names + self.specialized_materials_file = specialized_materials_file + self.verbose = verbose + + self.frame_count = 0 # maintains how many times we have saved the scene + self.updates = 0 + + self.geom_name2usd = {} + + # initializing rendering requirements + self.renderer = mujoco.Renderer(model, height, width, max_geom) + self._initialize_usd_stage() + self._scene_option = mujoco.MjvOption() # using default scene option + + # initializing output_directories + self._initialize_output_directories() + + # loading required textures for the scene + self._load_textures() + + @property + def usd(self): + return self.stage.GetRootLayer().ExportToString() + + @property + def scene(self): + return self.renderer.scene + + def _initialize_usd_stage(self): + self.stage = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(self.stage, UsdGeom.Tokens.z) + self.stage.SetStartTimeCode(0) + # add as user input + self.stage.SetTimeCodesPerSecond(60.0) + + default_prim = UsdGeom.Xform.Define(self.stage, Sdf.Path("/World")).GetPrim() + self.stage.SetDefaultPrim(default_prim) + + def _initialize_output_directories(self): + self.output_directory_path = os.path.join( + self.output_directory_root, self.output_directory_name + ) + if not os.path.exists(self.output_directory_path): + os.makedirs(self.output_directory_path) + + self.frames_directory = os.path.join(self.output_directory_path, "frames") + if not os.path.exists(self.frames_directory): + os.makedirs(self.frames_directory) + + self.assets_directory = os.path.join(self.output_directory_path, "assets") + if not os.path.exists(self.assets_directory): + os.makedirs(self.assets_directory) + + if self.verbose: + print( + termcolor.colored( + "Writing output frames and assets to" f" {self.output_directory_path}", + "green", + ) + ) + + def update_scene( + self, + data: mujoco.MjData, + scene_option: Optional[mujoco.MjvOption] = None, + ): + """Updates the scene with latest sim data + + Args: + data: structure storing current simulation state + scene_option: we use this to determine which geom groups to activate + """ + + self.frame_count += 1 + + scene_option = scene_option or self._scene_option + + # update the mujoco renderer + self.renderer.update_scene(data, scene_option=scene_option) + + # TODO: update scene options + if self.updates == 0: + self._initialize_usd_stage() + + self._load_lights() + self._load_cameras() + + self._update_geoms() + self._update_lights() + self._update_cameras(data, scene_option=scene_option) + + self.updates += 1 + + def _load_textures(self): + # TODO: remove code once added internally to mujoco + data_adr = 0 + self.texture_files = [] + for texture_id in tqdm.tqdm(range(self.model.ntex)): + texture_height = self.model.tex_height[texture_id] + texture_width = self.model.tex_width[texture_id] + pixels = 3 * texture_height * texture_width + img = im.fromarray( + self.model.tex_rgb[data_adr : data_adr + pixels].reshape( + texture_height, texture_width, 3 + ) + ) + img = ImageOps.flip(img) + + texture_file_name = f"texture_{texture_id}.png" + + img.save(os.path.join(self.assets_directory, texture_file_name)) + + relative_path = os.path.relpath(self.assets_directory, self.frames_directory) + img_path = os.path.join( + relative_path, texture_file_name + ) # relative path, TODO: switch back to this + + self.texture_files.append(img_path) + + data_adr += pixels + + if self.verbose: + print( + termcolor.colored( + f"Completed writing {self.model.ntex} textures to" f" {self.assets_directory}", + "green", + ) + ) + + def _load_geom(self, geom: mujoco.MjvGeom): + + geom_name = self._get_geom_name(geom.objtype, geom.objid) + + assert geom_name not in self.geom_name2usd + + texture_file = self.texture_files[geom.texid] if geom.texid != -1 else None + + if geom.type == mujoco.mjtGeom.mjGEOM_MESH: + usd_geom = component_module.USDMesh( + stage=self.stage, + model=self.model, + geom=geom, + obj_name=geom_name, + dataid=self.model.geom_dataid[geom.objid], + rgba=geom.rgba, + texture_file=texture_file, + ) + else: + mesh_config = shapes_module.mesh_config_generator( + name=geom_name, geom_type=geom.type, size=geom.size + ) + usd_geom = component_module.USDPrimitiveMesh( + mesh_config=mesh_config, + stage=self.stage, + geom=geom, + obj_name=geom_name, + rgba=geom.rgba, + texture_file=texture_file, + ) + + self.geom_name2usd[geom_name] = usd_geom + + def _update_geoms(self): + + geom_names = set(self.geom_name2usd.keys()) + + for i in range(self.scene.ngeom): + geom = self.scene.geoms[i] + geom_name = mujoco.mj_id2name(self.model, geom.objtype, geom.objid) + if not geom_name: + geom_name = "None" + geom_name += f"_{geom.objid}" + + # iterate through all geoms in the scene and makes update + for i in range(self.scene.ngeom): + geom = self.scene.geoms[i] + geom_name = self._get_geom_name(geom.objtype, geom.objid) + + if geom_name not in self.geom_name2usd: + self._load_geom(geom) + if self.geom_name2usd[geom_name]: + self.geom_name2usd[geom_name].update_visibility(False, 0) + + if self.geom_name2usd[geom_name]: + self.geom_name2usd[geom_name].update( + pos=geom.pos, + mat=geom.mat, + visible=geom.rgba[3] > 0, + frame=self.updates, + ) + if geom_name in geom_names: + geom_names.remove(geom_name) + + for geom_name in geom_names: + if self.geom_name2usd[geom_name]: + self.geom_name2usd[geom_name].update_visibility(False, self.updates) + + def _load_lights(self): + # initializes an usd light object for every light in the scene + self.usd_lights = [] + for i in range(self.scene.nlight): + light = self.scene.lights[i] + if not np.allclose(light.pos, [0, 0, 0]): + self.usd_lights.append + (component_module.USDSphereLight(stage=self.stage, obj_name=str(i))) + else: + self.usd_lights.append(None) + + def _update_lights(self): + for i in range(self.scene.nlight): + light = self.scene.lights[i] + + if np.allclose(light.pos, [0, 0, 0]): + continue + + if i >= len(self.usd_lights) or self.usd_lights[i] is None: + continue + + self.usd_lights[i].update( + pos=light.pos, + intensity=self.light_intensity, + color=light.diffuse, + frame=self.updates, + ) + + def _load_cameras(self): + self.usd_cameras = [] + if self.camera_names is not None: + for name in self.camera_names: + self.usd_cameras.append(component_module.USDCamera(stage=self.stage, obj_name=name)) + + def _update_cameras( + self, + data: mujoco.MjData, + scene_option: Optional[mujoco.MjvOption] = None, + ): + for i in range(len(self.usd_cameras)): + + camera = self.usd_cameras[i] + camera_name = self.camera_names[i] + + self.renderer.update_scene(data, scene_option=scene_option, camera=camera_name) + + avg_camera = mujoco.mjv_averageCamera(self.scene.camera[0], self.scene.camera[1]) + + forward = avg_camera.forward + up = avg_camera.up + right = np.cross(forward, up) + + R = np.eye(3) + R[:, 0] = right + R[:, 1] = up + R[:, 2] = -forward + + camera.update(cam_pos=avg_camera.pos, cam_mat=R, frame=self.updates) + + def add_light( + self, + pos: List[float], + intensity: int, + objid: int, + radius: Optional[float] = 1.0, + color: Optional[np.ndarray] = np.array([0.3, 0.3, 0.3]), + obj_name: Optional[str] = "light_1", + light_type: Optional[str] = "sphere", + ): + + if light_type == "sphere": + new_light = component_module.USDSphereLight( + stage=self.stage, obj_name=str(objid), radius=radius + ) + + new_light.update(pos=np.array(pos), intensity=intensity, color=color, frame=0) + elif light_type == "dome": + new_light = component_module.USDDomeLight(stage=self.stage, obj_name=str(objid)) + + new_light.update(intensity=intensity, color=color, frame=0) + + def add_camera( + self, + pos: List[float], + rotation_xyz: List[float], + objid: int, + obj_name: Optional[str] = "camera_1", + ): + new_camera = component_module.USDCamera(stage=self.stage, obj_name=str(objid)) + + r = scipy.spatial.transform.Rotation.from_euler("xyz", rotation_xyz, degrees=True) + new_camera.update(cam_pos=np.array(pos), cam_mat=r.as_matrix(), frame=0) + + def save_scene(self, filetype: str = "usd"): + assert filetype in ["usd", "usda", "usdc"] + self.stage.SetEndTimeCode(self.frame_count) + self.stage.Export( + f"{self.output_directory_root}/{self.output_directory_name}/frames/frame_{self.frame_count}_.{filetype}" + ) + if self.verbose: + print( + termcolor.colored(f"Completed writing frame_{self.frame_count}.{filetype}", "green") + ) + + def _get_geom_name(self, objtype, objid): + geom_name = mujoco.mj_id2name(self.model, objtype, objid) + if not geom_name: + geom_name = "None" + geom_name += f"_{objid}" + return geom_name diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter_test.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter_test.py new file mode 100644 index 0000000000000000000000000000000000000000..40ce8056b94b24db52afb702d2a1cb7c69389b07 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/exporter_test.py @@ -0,0 +1,71 @@ +# Copyright 2024 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for the MuJoCo USD Exporter.""" + +import logging +import os + +import mujoco +from absl.testing import absltest +from etils import epath + +# Open3D and USD are not fully supported on all MuJoCo architectures. +# pylint: disable=python.style(g-import-not-at-top) +execute_test = True +try: + from pxr import Usd + + from robocasa.utils.usd import exporter as exporter_module +except ImportError: + logging.warning("Skipping test due to missing import") + execute_test = False +# pylint: enable=python.style(g-import-not-at-top) + + +class ExporterTest(absltest.TestCase): + def test_usd_export(self): + if not execute_test: + return + + output_dir = os.getenv("TEST_UNDECLARED_OUTPUTS_DIR") + xml = """ + + + + + + +""" + model = mujoco.MjModel.from_xml_string(xml) + data = mujoco.MjData(model) + exporter = exporter_module.USDExporter( + model, + output_directory_name="mujoco_usdpkg", + output_directory_root=output_dir, + ) + exporter.update_scene(data) + exporter.save_scene("export.usda") + + with open( + os.path.join(output_dir, "mujoco_usdpkg/frames", "frame_1_.export.usda"), + "r", + ) as f: + golden_path = os.path.join(epath.resource_path("mujoco"), "testdata", "usd_golden.usda") + with open(golden_path, "r") as golden_file: + self.assertEqual(f.read(), golden_file.read()) + + +if __name__ == "__main__": + absltest.main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/shapes.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f7d981de42d4baa88c46b458b641bd163aee9b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/shapes.py @@ -0,0 +1,138 @@ +import copy +import pprint + +import mujoco +import numpy as np +import open3d as o3d + + +def create_hemisphere( + radius: float, resolution: int = 20, theta_steps: int = 50, phi_steps: int = 50 +): + + points = [] + for i in range(phi_steps + 1): + phi = np.pi / 2 * i / phi_steps + for j in range(theta_steps + 1): + theta = 2 * np.pi * j / theta_steps + x = radius * np.sin(phi) * np.cos(theta) + y = radius * np.sin(phi) * np.sin(theta) + z = radius * np.cos(phi) + points.append([x, y, z]) + + pcd = o3d.geometry.PointCloud() + pcd.points = o3d.utility.Vector3dVector(points) + + mesh = pcd.compute_convex_hull()[0] + + return mesh + + +def mesh_config_generator(name: str, geom_type: mujoco.mjtGeom, size: np.ndarray): + + if geom_type == mujoco.mjtGeom.mjGEOM_PLANE: + return { + "name": name, + "box": { + "width": size[0] * 2 if size[0] > 0 else 100, + "height": size[1] * 2 if size[1] > 0 else 100, + "depth": 0.001, + "map_texture_to_each_face": True, + }, + } + elif geom_type == mujoco.mjtGeom.mjGEOM_SPHERE: + return {"name": name, "sphere": {"radius": float(size[0])}} + elif geom_type == mujoco.mjtGeom.mjGEOM_CAPSULE: + cylinder = mesh_config_generator(name, mujoco.mjtGeom.mjGEOM_CYLINDER, size) + return { + "name": name, + "cylinder": cylinder["cylinder"], + "left_hemisphere": { + "radius": size[0], + "transform": {"translate": (0, 0, -size[2]), "rotate": (np.pi, 0, 0)}, + }, + "right_hemisphere": { + "radius": size[0], + "transform": {"translate": (0, 0, size[2])}, + }, + } + elif geom_type == mujoco.mjtGeom.mjGEOM_ELLIPSOID: + sphere = mesh_config_generator(name, mujoco.mjtGeom.mjGEOM_SPHERE, [1.0]) + sphere["sphere"]["transform"] = {"scale": tuple(size)} + return { + "name": name, + "sphere": sphere["sphere"], + } + elif geom_type == mujoco.mjtGeom.mjGEOM_CYLINDER: + return { + "name": name, + "cylinder": { + "radius": size[0], + "height": size[2] * 2, + }, + } + elif geom_type == mujoco.mjtGeom.mjGEOM_BOX: + return { + "name": name, + "box": { + "width": size[0] * 2, + "height": size[1] * 2, + "depth": size[2] * 2, + }, + } + else: + raise NotImplemented( + f"{geom_type} primitive geom type not implemented with USD integration" + ) + + +def mesh_generator(mesh_config: dict): + + assert "name" in mesh_config + + mesh = None + + for shape, config in mesh_config.items(): + + if shape == "name": + continue + + if "box" in shape: + prim_mesh = o3d.geometry.TriangleMesh.create_box( + width=mesh_config[shape]["width"], + height=mesh_config[shape]["height"], + depth=mesh_config[shape]["depth"], + create_uv_map=True, + map_texture_to_each_face=True, + ) + elif "hemisphere" in shape: + prim_mesh = create_hemisphere(radius=mesh_config[shape]["radius"]) + elif "sphere" in shape: + prim_mesh = o3d.geometry.TriangleMesh.create_sphere( + radius=mesh_config[shape]["radius"], create_uv_map=True + ) + elif "cylinder" in shape: + prim_mesh = o3d.geometry.TriangleMesh.create_cylinder( + radius=mesh_config[shape]["radius"], + height=mesh_config[shape]["height"], + create_uv_map=True, + ) + + if "transform" in config: + + if "rotate" in config["transform"]: + R = mesh.get_rotation_matrix_from_xyz(config["transform"]["rotate"]) + prim_mesh.rotate(R, center=(0, 0, 0)) + if "scale" in config["transform"]: + prim_mesh.vertices = o3d.utility.Vector3dVector( + np.asarray(prim_mesh.vertices) * np.array(config["transform"]["scale"]) + ) + if "translate" in config["transform"]: + prim_mesh.translate(config["transform"]["translate"]) + + if not mesh: + mesh = prim_mesh + else: + mesh += prim_mesh + + return mesh_config["name"], mesh diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/utils.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8c4408c2ac5d23a107ffd4578be03ffd65ceaf46 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/usd/utils.py @@ -0,0 +1,27 @@ +# Copyright 2024 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +import numpy as np + + +def create_transform_matrix(rotation_matrix, translation_vector): + # Ensure rotation_matrix and translation_vector are NumPy arrays + rotation_matrix = np.array(rotation_matrix) + translation_vector = np.array(translation_vector) + + transform_matrix = np.eye(4) + transform_matrix[:3, :3] = rotation_matrix + transform_matrix[:3, 3] = translation_vector + + return transform_matrix diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/visuals_utls.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/visuals_utls.py new file mode 100644 index 0000000000000000000000000000000000000000..8b46fefbf1efb02a560774c01622786f33da8670 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/utils/visuals_utls.py @@ -0,0 +1,31 @@ +from dataclasses import dataclass + +import numpy as np + +from robocasa.models.objects.objects import MJCFObject + + +@dataclass(frozen=True) +class Gradient: + rgba_a: np.ndarray = np.array([0, 0, 0, 1]) + rgba_b: np.ndarray = np.array([1, 1, 1, 1]) + + def sample_linear(self, t: float) -> np.ndarray: + return (1 - t) * self.rgba_a + t * self.rgba_b + + def sample_per_channel(self, t: tuple[float, float, float, float]): + return [np.interp(t[i], [0, 1], [self.rgba_a[i], self.rgba_b[i]]) for i in range(4)] + + +def randomize_materials_rgba( + rng: np.random.Generator, mjcf_obj: MJCFObject, gradient: Gradient, linear: bool +): + for asset in mjcf_obj.asset: + if asset.tag == "material": + if linear: + t = rng.uniform(0, 1) + rgba = gradient.sample_linear(t) + else: + t = rng.uniform(low=[0, 0, 0, 1], high=[1, 1, 1, 1]).tolist() + rgba = gradient.sample_per_channel(t) + asset.set("rgba", f"{rgba[0]:.3f} {rgba[1]:.3f} {rgba[2]:.3f} {rgba[3]:.3f}") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c3b45ba39ff8f6f44f59372e1ebafe984471acd2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/__init__.py @@ -0,0 +1 @@ +from robocasa.wrappers.ik_wrapper import IKWrapper diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/ik_wrapper.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/ik_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..24a714f26f991ec788fd883a0b81469fb31ae3e8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/robocasa/wrappers/ik_wrapper.py @@ -0,0 +1,226 @@ +import xml.etree.ElementTree as ET +from copy import deepcopy + +import numpy as np + +from robocasa.models.grippers import G1ThreeFingerLeftHand, G1ThreeFingerRightHand +from robosuite.examples.third_party_controller.mink_controller import IKSolverMink +from robosuite.models.grippers import InspireLeftHand, InspireRightHand +from robosuite.models.grippers import FourierLeftHand, FourierRightHand +from robosuite.utils.mjcf_utils import new_body, new_geom, new_site +from robosuite.wrappers import VisualizationWrapper +import robosuite.utils.transform_utils as T + + +class IKWrapper(VisualizationWrapper): + def __init__(self, env, indicator_configs=None, ik_indicator=False): + self.ik_indicator = ik_indicator + if ik_indicator: + indicator_configs = [] + for i in range(2): + indicator_configs.append( + { + "name": f"indicator_x_{i}", + "type": "capsule", + "pos": [0.012, 0, 0], + "size": [0.003, 0.012], + "rgba": [1, 0.5, 0.5, 0.8], + "quat": [0, 0.7071, 0, 0.7071], + } + ) + indicator_configs.append( + { + "name": f"indicator_y_{i}", + "type": "capsule", + "pos": [0, 0.012, 0], + "size": [0.003, 0.012], + "rgba": [0.5, 1, 0.5, 0.8], + "quat": [0, 0, 0.7071, 0.7071], + } + ) + indicator_configs.append( + { + "name": f"indicator_z_{i}", + "type": "capsule", + "pos": [0, 0, 0.012], + "size": [0.003, 0.012], + "rgba": [0.5, 0.5, 1, 0.8], + } + ) + super().__init__(env, indicator_configs=indicator_configs) + else: + # Fall back to VisualizationWrapper + super().__init__env, indicator_configs() + + def step(self, action): + if self.ik_indicator: + composite_controller = self.robots[0].composite_controller + if composite_controller.name == "BASIC": + # indicators will be set by calling `set_target_poses_outside_env` + pass + elif composite_controller.name in [ + "WHOLE_BODY_MINK_IK", + "WHOLE_BODY_EXTERNAL_IK", + "HYBRID_WHOLE_BODY_MINK_IK", + ]: + assert composite_controller.joint_action_policy.input_ref_frame == "base" + input_action = action[: composite_controller.joint_action_policy.control_dim] + input_action = input_action.reshape( + len(composite_controller.joint_action_policy.site_names), -1 + ) + input_pos = input_action[:, :3] + input_ori = input_action[:, 3:] + input_quat_wxyz = np.array( + [np.roll(T.axisangle2quat(input_ori[i]), 1) for i in range(len(input_ori))] + ) + base_pos = self.sim.data.body_xpos[self.sim.model.body_name2id("robot0_base")] + base_ori = self.sim.data.body_xmat[ + self.sim.model.body_name2id("robot0_base") + ].reshape(3, 3) + base_pose = T.make_pose(base_pos, base_ori) + for _, name in enumerate(self.get_indicator_names()): + # indicators for x,y,z-axis share the same pose + i = int(name.split("_")[-1]) + input_pose = T.make_pose( + input_pos[i], T.quat2mat(np.roll(input_quat_wxyz[i], -1)) + ) + target_pose = np.dot(base_pose, input_pose) + self.set_indicator_pos(name, target_pose[:3, 3]) + self.set_indicator_ori(name, target_pose[:3, :3]) + else: + assert ( + False + ), f"Unsupported composite controller {composite_controller.name} for IKWrapper" + + ret = super().step(action) + + return ret + + def set_target_poses_outside_env(self, input_poses): + if self.env.robots[0].robot_model.default_base in ["NullBase", "NoActuationBase"]: + base_name = "robot0_base" + elif self.env.robots[0].robot_model.default_base == "FloatingLeggedBase": + base_name = "mobilebase0_support" + else: + assert False, f"Unsupported base type: {self.env.robots[0].robot_model.default_base}" + base_id = self.sim.model.body_name2id(base_name) + base_pos = self.sim.data.body_xpos[base_id] + base_ori = self.sim.data.body_xmat[base_id].reshape(3, 3) + base_pose = T.make_pose(base_pos, base_ori) + for _, name in enumerate(self.get_indicator_names()): + i = int(name.split("_")[-1]) + input_pose = input_poses[i].copy() + input_pose[3, 3] = 1 + target_pose = np.dot(base_pose, input_pose) + self.set_indicator_pos(name, target_pose[:3, 3]) + self.set_indicator_ori(name, target_pose[:3, :3]) + + # TODO: this will fix the duplicated body issue in the public robosuite repo + def _add_indicators_to_model(self, xml): + """ + Adds indicators to the mujoco simulation model + + Args: + xml (string): MJCF model in xml format, for the current simulation to be loaded + """ + if self.indicator_configs is not None: + root = ET.fromstring(xml) + worldbody = root.find("worldbody") + + from robosuite.utils.mjcf_utils import ( + find_elements, + find_parent, + new_element, + ) + + for arm in ["right", "left"]: + gripper = self.env.robots[0].gripper[arm] + if ( + not isinstance(gripper, InspireLeftHand) + and not isinstance(gripper, InspireRightHand) + and not isinstance(gripper, FourierLeftHand) + and not isinstance(gripper, FourierRightHand) + and not isinstance(gripper, G1ThreeFingerLeftHand) + and not isinstance(gripper, G1ThreeFingerRightHand) + ): + continue + + eef = find_elements( + root=worldbody, + tags="body", + attribs={"name": f"gripper0_{arm}_eef"}, + return_first=True, + ) + mount = find_parent(worldbody, eef) + for i in range(4): + elem = find_elements( + root=worldbody, + tags="site", + attribs={"name": f"robot0_{arm}_pinch_spheres_{i}"}, + return_first=True, + ) + if elem is not None: + continue + if ( + isinstance(gripper, InspireLeftHand) + or isinstance(gripper, InspireRightHand) + or isinstance(gripper, FourierLeftHand) + or isinstance(gripper, FourierRightHand) + ): + mount.append( + new_element( + tag="site", + name=f"robot0_{arm}_pinch_spheres_{i}", + pos=f"-0.09 -0.10 {-0.03 + i * 0.02}", + size="0.01 0.01 0.01", + rgba="1 0.5 0.5 1", + type="sphere", + group="1", + ) + ) + else: + if arm == "right": + mount.append( + new_element( + tag="site", + name=f"robot0_{arm}_pinch_spheres_{i}", + pos=f"0.15 0.05 {-0.03 + i * 0.02}", + size="0.01 0.01 0.01", + rgba="1 0.5 0.5 1", + type="sphere", + group="1", + ) + ) + else: + mount.append( + new_element( + tag="site", + name=f"robot0_{arm}_pinch_spheres_{i}", + pos=f"0.15 -0.05 {-0.03 + i * 0.02}", + size="0.01 0.01 0.01", + rgba="1 0.5 0.5 1", + type="sphere", + group="1", + ) + ) + + for indicator_config in self.indicator_configs: + config = deepcopy(indicator_config) + + from robosuite.utils.mjcf_utils import find_elements + + body = find_elements( + root=worldbody, + tags="body", + attribs={"name": config["name"] + "_body"}, + ) + if body is not None: + continue + + indicator_body = new_body(name=config["name"] + "_body") + indicator_body.append(new_site(**config)) + worldbody.append(indicator_body) + + xml = ET.tostring(root, encoding="utf8").decode("utf8") + + return xml diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/setup.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ede7806d670ec18646d5a79881229026eac8b79e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/dexmg/gr00trobocasa/setup.py @@ -0,0 +1,29 @@ +from setuptools import find_packages, setup + + +setup( + name="robocasa", + packages=[package for package in find_packages() if package.startswith("robocasa")], + install_requires=[ + "numpy==1.26.4", + "numba==0.61.0", + "scipy>=1.2.3", + "mujoco==3.2.6", + "pygame", + "Pillow", + "opencv-python", + "pyyaml", + "pynput", + "tqdm", + "termcolor", + "imageio", + "h5py", + "lxml", + "hidapi", + ], + eager_resources=["*"], + include_package_data=True, + python_requires=">=3", + description="Gr00t RoboCasa for loco-manipulation", + version="0.2.0", +) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.bashrc b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.bashrc new file mode 100644 index 0000000000000000000000000000000000000000..999e74e973aa66d3a6934fc71c87c967008842f8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.bashrc @@ -0,0 +1,163 @@ +# ~/.bashrc: executed by bash(1) for non-login shells. +# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc) +# for examples + +# If not running interactively, don't do anything +case $- in + *i*) ;; + *) return;; +esac + +# don't put duplicate lines or lines starting with space in the history. +# See bash(1) for more options +HISTCONTROL=ignoreboth + +# append to the history file, don't overwrite it +shopt -s histappend + +# for setting history length see HISTSIZE and HISTFILESIZE in bash(1) +HISTSIZE=1000 +HISTFILESIZE=2000 + +# check the window size after each command and, if necessary, +# update the values of LINES and COLUMNS. +shopt -s checkwinsize + +# If set, the pattern "**" used in a pathname expansion context will +# match all files and zero or more directories and subdirectories. +#shopt -s globstar + +# make less more friendly for non-text input files, see lesspipe(1) +[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)" + +# set variable identifying the chroot you work in (used in the prompt below) +if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then + debian_chroot=$(cat /etc/debian_chroot) +fi + +# set a fancy prompt (non-color, unless we know we "want" color) +case "$TERM" in + xterm-color|*-256color) color_prompt=yes;; +esac + +# uncomment for a colored prompt, if the terminal has the capability; turned +# off by default to not distract the user: the focus in a terminal window +# should be on the output of commands, not on the prompt +force_color_prompt=yes + +if [ -n "$force_color_prompt" ]; then + if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then + # We have color support; assume it's compliant with Ecma-48 + # (ISO/IEC-6429). (Lack of such support is extremely rare, and such + # a case would tend to support setf rather than setaf.) + color_prompt=yes + else + color_prompt= + fi +fi + +if [ "$color_prompt" = yes ]; then + PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ' +else + PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ' +fi +unset color_prompt force_color_prompt + +# If this is an xterm set the title to user@host:dir +case "$TERM" in +xterm*|rxvt*) + PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1" + ;; +*) + ;; +esac + +# enable color support of ls and also add handy aliases +if [ -x /usr/bin/dircolors ]; then + test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" + alias ls='ls --color=auto' + #alias dir='dir --color=auto' + #alias vdir='vdir --color=auto' + + alias grep='grep --color=auto' + alias fgrep='fgrep --color=auto' + alias egrep='egrep --color=auto' +fi + +# colored GCC warnings and errors +export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01' + +# Set terminal type for color support +export TERM=xterm-256color + +# some more ls aliases +alias ll='ls -alF' +alias la='ls -A' +alias l='ls -CF' + +# Add an "alert" alias for long running commands. Use like so: +# sleep 10; alert +alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' + +# Alias definitions. +# You may want to put all your additions into a separate file like +# ~/.bash_aliases, instead of adding them here directly. +# See /usr/share/doc/bash-doc/examples in the bash-doc package. + +if [ -f ~/.bash_aliases ]; then + . ~/.bash_aliases +fi + +# enable programmable completion features (you don't need to enable +# this, if it's already enabled in /etc/bash.bashrc and /etc/profile +# sources /etc/bash.bashrc). +if ! shopt -oq posix; then + if [ -f /usr/share/bash-completion/bash_completion ]; then + . /usr/share/bash-completion/bash_completion + elif [ -f /etc/bash_completion ]; then + . /etc/bash_completion + fi +fi + +# useful commands +bind '"\e[A": history-search-backward' +bind '"\e[B": history-search-forward' + +# Store the last 10 directories in a history file +CD_HISTFILE=~/.cd_history +CD_HISTSIZE=10 + +cd() { + local histfile="${CD_HISTFILE:-$HOME/.cd_history}" + local max="${CD_HISTSIZE:-10}" + + case "$1" in + --) [ -f "$histfile" ] && tac "$histfile" | nl -w2 -s' ' || echo "No directory history yet."; return ;; + -[0-9]*) + local idx=${1#-} + local dir=$(tac "$histfile" 2>/dev/null | sed -n "${idx}p") + [ -n "$dir" ] && builtin cd "$dir" || echo "Invalid selection: $1" + return ;; + esac + + builtin cd "$@" || return + + [[ $(tail -n1 "$histfile" 2>/dev/null) != "$PWD" ]] && echo "$PWD" >> "$histfile" + tail -n "$max" "$histfile" > "${histfile}.tmp" && mv "${histfile}.tmp" "$histfile" +} + +# Make decoupled_wbc importable +export PYTHONPATH="${DECOUPLED_WBC_DIR}:${PYTHONPATH}" + +# Manus to LD_LIBRARY_PATH +export LD_LIBRARY_PATH=$DECOUPLED_WBC_DIR/decoupled_wbc/control/teleop/device/SDKClient_Linux/ManusSDK/lib:$LD_LIBRARY_PATH + +# CUDA support +export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:/usr/lib:/lib/x86_64-linux-gnu:/lib64:/lib:$LD_LIBRARY_PATH + +# decoupled_wbc aliases +alias dg="python $DECOUPLED_WBC_DIR/decoupled_wbc/scripts/deploy_g1.py" +alias rsl="python $DECOUPLED_WBC_DIR/decoupled_wbc/control/main/teleop/run_sim_loop.py" +alias rgcl="python $DECOUPLED_WBC_DIR/decoupled_wbc/control/main/teleop/run_g1_control_loop.py" +alias rtpl="python $DECOUPLED_WBC_DIR/decoupled_wbc/control/main/teleop/run_teleop_policy_loop.py" +alias tgcl="pytest $DECOUPLED_WBC_DIR/decoupled_wbc/tests/control/main/teleop/test_g1_control_loop.py -s" diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.tmux.conf b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.tmux.conf new file mode 100644 index 0000000000000000000000000000000000000000..0da4a3179e38280c422ea673e6193b6fed83466f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/.tmux.conf @@ -0,0 +1,84 @@ +# Enable mouse mode +set -g mouse on + +# Start window numbering at 0 (default) +set -g base-index 0 +setw -g pane-base-index 0 + +# Increase scrollback buffer size +set -g history-limit 50000 + +# Use Alt-arrow keys without prefix key to switch panes +bind -n M-Left select-pane -L +bind -n M-Right select-pane -R +bind -n M-Up select-pane -U +bind -n M-Down select-pane -D + +# Use Alt-1,2,3... to switch windows +bind -n M-1 select-window -t 1 +bind -n M-2 select-window -t 2 +bind -n M-3 select-window -t 3 +bind -n M-4 select-window -t 4 +bind -n M-5 select-window -t 5 +bind -n M-6 select-window -t 6 +bind -n M-7 select-window -t 7 +bind -n M-8 select-window -t 8 +bind -n M-9 select-window -t 9 + +# Split panes using Alt-| and Alt-- +bind -n M-| split-window -h +bind -n M-- split-window -v + +# Easy config reload +bind -n M-r source-file ~/.tmux.conf \; display-message "Config reloaded!" + +# Status bar customization +set -g status-style bg=colour240,fg=colour255 +set -g status-left "#[fg=colour255,bg=colour240] #S #[fg=colour240,bg=colour238]" +set -g status-right "#[fg=colour255,bg=colour240] %H:%M #[fg=colour240,bg=colour238]" + +# Window status format +setw -g window-status-format "#[fg=colour255,bg=colour238] #I:#W " +setw -g window-status-current-format "#[fg=colour238,bg=colour255]#[fg=colour238,bg=colour255] #I:#W #[fg=colour255,bg=colour238]" + +# Pane border colors +set -g pane-border-style fg=colour240 +set -g pane-active-border-style fg=colour255 + +# Message text +set -g message-style bg=colour238,fg=colour255 + +# Clock mode +setw -g clock-mode-colour colour255 + +# Enable focus events +set -g focus-events on + +# Increase escape time +set -sg escape-time 0 + +# Enable true color support +set -ga terminal-overrides ",*256col*:Tc" + +# Set default terminal mode to 256 colors +set -g default-terminal "screen-256color" + +# Display a message when a window is created +set -g display-time 4000 + +# Automatically set window title +setw -g automatic-rename on +set -g set-titles on +set -g set-titles-string "#T" + +# Enable clipboard integration +set -g @plugin 'tmux-plugins/tmux-yank' + +# List of plugins +set -g @plugin 'tmux-plugins/tpm' +set -g @plugin 'tmux-plugins/tmux-sensible' +set -g @plugin 'tmux-plugins/tmux-resurrect' +set -g @plugin 'tmux-plugins/tmux-continuum' + +# Initialize TMUX plugin manager (keep this line at the very bottom of tmux.conf) +run '~/.tmux/plugins/tpm/tpm' \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/70-manus-hid.rules b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/70-manus-hid.rules new file mode 100644 index 0000000000000000000000000000000000000000..3c2bb3270d6b329c8a35d6846b8644afeb669d75 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/70-manus-hid.rules @@ -0,0 +1,5 @@ + # HIDAPI/libusb + SUBSYSTEMS=="usb", ATTRS{idVendor}=="3325", MODE:="0666" + + # HIDAPI/hidraw + KERNEL=="hidraw*", ATTRS{idVendor}=="3325", MODE:="0666" \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/Dockerfile.deploy b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/Dockerfile.deploy new file mode 100644 index 0000000000000000000000000000000000000000..239127c85d8be57c5de415f31538f288133e8f05 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/Dockerfile.deploy @@ -0,0 +1,130 @@ +FROM nvgear/ros-2:latest + +# Accept build argument for username +ARG USERNAME +ARG USERID +ARG HOME_DIR +ARG WORKTREE_NAME + +# Create user with the same name as host +RUN if [ "$USERID" != "0" ]; then \ + useradd -m -u ${USERID} -s /bin/bash ${USERNAME} && \ + echo "${USERNAME} ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers && \ + # Add user to video and render groups for GPU access + usermod -a -G video,render ${USERNAME} || true; \ + fi + +# Copy .bashrc with color settings before switching user +COPY --chown=${USERNAME}:${USERNAME} decoupled_wbc/docker/.bashrc ${HOME_DIR}/.bashrc + +# Install Manus udev rules +COPY --chown=${USERNAME}:${USERNAME} decoupled_wbc/docker/70-manus-hid.rules /etc/udev/rules.d/70-manus-hid.rules + +# Copy tmux configuration +COPY --chown=${USERNAME}:${USERNAME} decoupled_wbc/docker/.tmux.conf ${HOME_DIR}/.tmux.conf + +# Switch to user +USER ${USERNAME} + +# Install tmux plugin manager and uv in parallel +RUN git clone https://github.com/tmux-plugins/tpm ${HOME_DIR}/.tmux/plugins/tpm & \ + curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=${HOME_DIR}/.cargo/bin sh & \ + wait + +# Install tmux plugins automatically +RUN ${HOME_DIR}/.tmux/plugins/tpm/bin/install_plugins || true + +# Add uv to PATH +ENV PATH="${HOME_DIR}/.cargo/bin:$PATH" +ENV UV_PYTHON=${HOME_DIR}/venv/bin/python + +# Create venv +RUN uv venv --python 3.10 ${HOME_DIR}/venv + +# Install hardware-specific packages (x86 only - not available on ARM64/Orin) +USER root +COPY --chown=${USERNAME}:${USERNAME} decoupled_wbc/control/teleop/device/pico/XRoboToolkit_PC_Service_1.0.0_ubuntu_22.04_amd64.deb ${HOME_DIR}/XRoboToolkit_PC_Service_1.0.0_ubuntu_22.04_amd64.deb +COPY --chown=${USERNAME}:${USERNAME} decoupled_wbc/control/teleop/device/pico/roboticsservice_1.0.0.0_arm64.deb ${HOME_DIR}/roboticsservice_1.0.0.0_arm64.deb + +RUN if [ "$(dpkg --print-architecture)" = "amd64" ]; then \ + # Ultra Leap setup + wget -qO - https://repo.ultraleap.com/keys/apt/gpg | gpg --dearmor | tee /etc/apt/trusted.gpg.d/ultraleap.gpg && \ + echo 'deb [arch=amd64] https://repo.ultraleap.com/apt stable main' | tee /etc/apt/sources.list.d/ultraleap.list && \ + apt-get update && \ + echo "yes" | DEBIAN_FRONTEND=noninteractive apt-get install -y ultraleap-hand-tracking libhidapi-dev && \ + # Space Mouse udev rules + echo 'KERNEL=="hidraw*", SUBSYSTEM=="hidraw", MODE="0664", GROUP="plugdev"' > /etc/udev/rules.d/99-hidraw-permissions.rules && \ + usermod -aG plugdev ${USERNAME}; \ + # Pico setup + apt-get install -y xdg-utils && \ + dpkg -i ${HOME_DIR}/XRoboToolkit_PC_Service_1.0.0_ubuntu_22.04_amd64.deb; \ + else \ + echo "Skipping x86-only hardware packages on $(dpkg --print-architecture)"; \ + fi + +USER ${USERNAME} +# Install hardware Python packages (x86 only) with caching +RUN --mount=type=cache,target=${HOME_DIR}/.cache/uv,uid=${USERID},gid=${USERID} \ + if [ "$(dpkg --print-architecture)" = "amd64" ]; then \ + # Ultra Leap Python bindings + git clone https://github.com/ultraleap/leapc-python-bindings ${HOME_DIR}/leapc-python-bindings && \ + cd ${HOME_DIR}/leapc-python-bindings && \ + UV_CONCURRENT_DOWNLOADS=8 uv pip install -r requirements.txt && \ + MAKEFLAGS="-j$(nproc)" ${HOME_DIR}/venv/bin/python -m build leapc-cffi && \ + uv pip install leapc-cffi/dist/leapc_cffi-0.0.1.tar.gz && \ + uv pip install -e leapc-python-api && \ + # Space Mouse Python package + uv pip install pyspacemouse && \ + # Pico Python bindings + git clone https://github.com/XR-Robotics/XRoboToolkit-PC-Service-Pybind.git ${HOME_DIR}/XRoboToolkit-PC-Service-Pybind && \ + cd ${HOME_DIR}/XRoboToolkit-PC-Service-Pybind && \ + uv pip install setuptools pybind11 && \ + sed -i "s|pip install|uv pip install|g" setup_ubuntu.sh && \ + sed -i "s|pip uninstall|uv pip uninstall|g" setup_ubuntu.sh && \ + sed -i "s|python setup.py install|${HOME_DIR}/venv/bin/python setup.py install|g" setup_ubuntu.sh && \ + bash setup_ubuntu.sh; \ + fi + +# Install Python dependencies using uv with caching +RUN --mount=type=cache,target=${HOME_DIR}/.cache/uv,uid=${USERID},gid=${USERID} \ + UV_CONCURRENT_DOWNLOADS=8 uv pip install --upgrade pip ipython jupyter notebook debugpy + + +# Copy entire project to the workspace directory where it will be mounted at runtime +# NOTE: The build context must be the project root for this to work +# Use dynamic worktree name to match runtime mount path +COPY --chown=${USERNAME}:${USERNAME} . ${HOME_DIR}/Projects/${WORKTREE_NAME} + +# Install Python dependencies inside the venv with caching - split into separate commands +RUN --mount=type=cache,target=${HOME_DIR}/.cache/uv,uid=${USERID},gid=${USERID} \ + UV_CONCURRENT_DOWNLOADS=8 uv pip install \ + -e ${HOME_DIR}/Projects/${WORKTREE_NAME}/external_dependencies/unitree_sdk2_python + +# Unlike pip, uv downloads LFS files by default. There's a bug in uv that causes LFS files +# to fail to download (https://github.com/astral-sh/uv/issues/3312). So we need to set +# UV_GIT_LFS=1 to prevent uv from downloading LFS files. +# Install project packages (decoupled_wbc + gear_sonic) with caching +RUN --mount=type=cache,target=${HOME_DIR}/.cache/uv,uid=${USERID},gid=${USERID} \ + GIT_LFS_SKIP_SMUDGE=1 UV_CONCURRENT_DOWNLOADS=8 uv pip install \ + -e "${HOME_DIR}/Projects/${WORKTREE_NAME}/decoupled_wbc[full,dev]" \ + -e "${HOME_DIR}/Projects/${WORKTREE_NAME}/gear_sonic[sim]" + +# Clone and install robosuite with specific branch +RUN --mount=type=cache,target=${HOME_DIR}/.cache/uv,uid=${USERID},gid=${USERID} \ + git clone https://github.com/xieleo5/robosuite.git ${HOME_DIR}/robosuite && \ + cd ${HOME_DIR}/robosuite && \ + git checkout leo/support_g1_locomanip && \ + UV_CONCURRENT_DOWNLOADS=8 uv pip install -e . + +# Install gr00trobocasa +RUN --mount=type=cache,target=${HOME_DIR}/.cache/uv,uid=${USERID},gid=${USERID} \ + UV_CONCURRENT_DOWNLOADS=8 uv pip install -e ${HOME_DIR}/Projects/${WORKTREE_NAME}/decoupled_wbc/dexmg/gr00trobocasa + +# Configure bash environment with virtual environment and ROS2 setup +RUN echo "source ${HOME_DIR}/venv/bin/activate" >> ${HOME_DIR}/.bashrc && \ + echo "source /opt/ros/humble/setup.bash" >> ${HOME_DIR}/.bashrc && \ + echo "export ROS_LOCALHOST_ONLY=1" >> ${HOME_DIR}/.bashrc && \ + echo "export PYTHONPATH=${HOME_DIR}/Projects/${WORKTREE_NAME}:\${PYTHONPATH}" >> ${HOME_DIR}/.bashrc + +# Default command (can be overridden at runtime) +CMD ["/bin/bash"] diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/Dockerfile.deploy.base b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/Dockerfile.deploy.base new file mode 100644 index 0000000000000000000000000000000000000000..360d2c59c8d0112e661603defa2d95a9a270ae48 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/Dockerfile.deploy.base @@ -0,0 +1,155 @@ +# Multi-architecture Dockerfile for NVIDIA CUDA +# Supports linux/amd64 and linux/arm64 +FROM nvidia/cuda:12.4.0-runtime-ubuntu22.04 + +# Build info - ARGs need to be redeclared after FROM to use in RUN commands +ARG TARGETPLATFORM +ARG BUILDPLATFORM +RUN echo "Building for $TARGETPLATFORM on $BUILDPLATFORM" + +# Avoid prompts from apt +ENV DEBIAN_FRONTEND=noninteractive + +# Install minimal system dependencies +RUN apt-get update && \ + apt-get install -y \ + # Basic tools + build-essential \ + curl \ + gdb \ + git \ + git-lfs \ + net-tools \ + sudo \ + wget \ + iputils-ping \ + vim \ + unzip \ + # System services + udev \ + # Graphics and X11 + libgl1-mesa-dri \ + libgl1-mesa-glx \ + libglu1-mesa \ + mesa-utils \ + libxcb-cursor0 \ + x11-apps \ + xauth \ + # EGL and GPU access + libegl1 \ + libegl1-mesa \ + libegl1-mesa-dev \ + libgl1-mesa-dev \ + libgles2-mesa-dev \ + libglvnd-dev \ + mesa-common-dev \ + # XCB and Qt platform dependencies + libxcb-icccm4 \ + libxcb-image0 \ + libxcb-keysyms1 \ + libxcb-randr0 \ + libxcb-render-util0 \ + libxcb-shape0 \ + libxcb-xfixes0 \ + libxcb-xinerama0 \ + libxcb-xinput0 \ + libxcb-xkb1 \ + libxkbcommon-x11-0 \ + # D-Bus and system dependencies + libdbus-1-3 \ + # Other dependencies + libncurses5-dev \ + libudev-dev \ + libusb-1.0-0-dev \ + # Python 3.10 and pip + python3.10 \ + python3.10-venv \ + python3.10-distutils \ + python3-pip \ + expect \ + # ffmpeg and related libraries + ffmpeg \ + libavcodec-dev \ + libavformat-dev \ + libavdevice-dev \ + libavfilter-dev \ + libavutil-dev \ + libswresample-dev \ + libswscale-dev \ + # opencv + libgtk2.0-dev \ + # Clean up + && rm -rf /var/lib/apt/lists/* + +# --- Install ROS 2 Humble (following official instructions) --- +# Enable required repositories +RUN apt-get update && apt-get install -y software-properties-common \ + && add-apt-repository universe \ + # Add ROS 2 GPG key and repository + && apt-get install -y curl gnupg lsb-release \ + && curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg \ + && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu $(. /etc/os-release && echo $UBUNTU_CODENAME) main" > /etc/apt/sources.list.d/ros2.list \ + # Upgrade system to avoid removal of critical packages (see ROS 2 docs) + && apt-get update \ + && apt-get upgrade -y \ + # Install ROS 2 Humble desktop + && apt-get install -y ros-humble-desktop \ + # (Optional) Install development tools + && apt-get install -y ros-dev-tools \ + # Install Eclipse Cyclone DDS RMW implementation + && apt-get install -y ros-humble-rmw-cyclonedds-cpp \ + # Clean up + && rm -rf /var/lib/apt/lists/* + +# Source ROS 2 setup in bashrc for all users +RUN echo 'source /opt/ros/humble/setup.bash' >> /etc/bash.bashrc + +# Clone, build, and install CycloneDDS 0.10.x +RUN git clone --branch releases/0.10.x https://github.com/eclipse-cyclonedds/cyclonedds /opt/cyclonedds && \ + mkdir -p /opt/cyclonedds/build /opt/cyclonedds/install && \ + cd /opt/cyclonedds/build && \ + cmake .. -DCMAKE_INSTALL_PREFIX=../install && \ + cmake --build . --target install && \ + # Clean up build files to reduce image size + rm -rf /opt/cyclonedds/build + +# Set CYCLONEDDS_HOME for all users +ENV CYCLONEDDS_HOME=/opt/cyclonedds/install + +# Install uv +RUN curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/opt/uv sh + +# Add uv to PATH +ENV PATH="/opt/uv:$PATH" +ENV UV_PYTHON=/opt/venv/bin/python + +# Fix dpkg state and install tmux +RUN dpkg --configure -a && apt-get update && apt-get install -y tmux && rm -rf /var/lib/apt/lists/* + +# Create NVIDIA ICD config for EGL if it doesn't exist +# Note: This might need platform-specific handling for ARM64 +RUN if [ ! -f /usr/share/glvnd/egl_vendor.d/10_nvidia.json ]; then \ + mkdir -p /usr/share/glvnd/egl_vendor.d && \ + printf '{\n "file_format_version" : "1.0.0",\n "ICD" : {\n "library_path" : "libEGL_nvidia.so.0"\n }\n}' | tee /usr/share/glvnd/egl_vendor.d/10_nvidia.json > /dev/null; \ + fi + +# Platform-specific configurations +RUN case "$TARGETPLATFORM" in \ + "linux/arm64") \ + echo "Configuring for ARM64 platform" && \ + # Add any ARM64-specific configurations here + echo "export GPU_FORCE_64BIT_PTR=1" >> /etc/environment \ + ;; \ + "linux/amd64") \ + echo "Configuring for AMD64 platform" && \ + # Add any AMD64-specific configurations here + echo "AMD64 platform configured" \ + ;; \ + *) \ + echo "Unknown platform: $TARGETPLATFORM" \ + ;; \ + esac + +# Add labels for better image management +LABEL org.opencontainers.image.title="Multi-Arch CUDA Runtime with ROS 2 Humble" +LABEL org.opencontainers.image.description="Multi-architecture Docker image with CUDA runtime and ROS 2 Humble" diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/build_deploy_base.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/build_deploy_base.sh new file mode 100644 index 0000000000000000000000000000000000000000..9d4a5d43ac94dc0f3bcbbfaa69d2f75ec7893f13 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/build_deploy_base.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +# Multi-architecture Docker build script +# Supports linux/amd64 + +set -e + +# Configuration +IMAGE_NAME="nvgear/ros-2" +TAG="${1:-latest}" +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +DOCKERFILE="$SCRIPT_DIR/Dockerfile.deploy.base" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +echo -e "${GREEN}Building multi-architecture Docker image: ${IMAGE_NAME}:${TAG}${NC}" + +# Ensure we're using the multiarch builder +echo -e "${YELLOW}Setting up multiarch builder...${NC}" +sudo docker buildx use multiarch-builder 2>/dev/null || { + echo -e "${YELLOW}Creating multiarch builder...${NC}" + sudo docker buildx create --name multiarch-builder --use --bootstrap +} + +# Show supported platforms +echo -e "${YELLOW}Supported platforms:${NC}" +sudo docker buildx inspect --bootstrap | grep Platforms + +# Build for multiple architectures +echo -e "${GREEN}Starting multi-arch build...${NC}" +sudo docker buildx build \ + --platform linux/amd64 \ + --file "${DOCKERFILE}" \ + --tag "${IMAGE_NAME}:${TAG}" \ + --push \ + . + +# Alternative: Build and load locally (only works for single platform) +# docker buildx build \ +# --platform linux/amd64 \ +# --file "${DOCKERFILE}" \ +# --tag "${IMAGE_NAME}:${TAG}" \ +# --load \ +# . + +echo -e "${GREEN}Multi-arch build completed successfully!${NC}" +echo -e "${GREEN}Image: ${IMAGE_NAME}:${TAG}${NC}" +echo -e "${GREEN}Platforms: linux/amd64${NC}" + +# Verify the manifest +echo -e "${YELLOW}Verifying multi-arch manifest...${NC}" +sudo docker buildx imagetools inspect "${IMAGE_NAME}:${TAG}" \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/bash.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/bash.sh new file mode 100644 index 0000000000000000000000000000000000000000..4ff46bf02bc792f607c62aff076a8a2d4b055a4c --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/bash.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -e # Exit on error + +echo "Dependencies installed successfully. Starting interactive bash shell..." +exec /bin/bash diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/deploy.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/deploy.sh new file mode 100644 index 0000000000000000000000000000000000000000..b624c6b2c6ccb8947989c1a6b6d9113beafb06c0 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/deploy.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -e # Exit on error + +# Run the deployment script +# Check for script existence before running +DEPLOY_SCRIPT="decoupled_wbc/scripts/deploy_g1.py" +if [ -f "$DEPLOY_SCRIPT" ]; then + echo "Running deployment script at $DEPLOY_SCRIPT" + echo "Using python from $(which python)" + echo "Deploy args: $@" + exec python "$DEPLOY_SCRIPT" "$@" +else + echo "ERROR: Deployment script not found at $DEPLOY_SCRIPT" + echo "Current directory structure:" + find . -type f -name "*.py" | grep -i deploy + echo "Available script options:" + find . -type f -name "*.py" | sort + echo "Starting a bash shell for troubleshooting..." + exec /bin/bash +fi diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/install_deps.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/install_deps.sh new file mode 100644 index 0000000000000000000000000000000000000000..fd7280db3a5e8e5ed8a65bde7befea62cc585126 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/entrypoint/install_deps.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -e + +# Source virtual environment and ROS2 +source ${HOME}/venv/bin/activate +source /opt/ros/humble/setup.bash +export ROS_LOCALHOST_ONLY=1 + +# Install external dependencies +echo "Current directory: $(pwd)" +echo "Installing dependencies..." + +# Install Unitree SDK and LeRobot +if [ -d "external_dependencies/unitree_sdk2_python" ]; then + cd external_dependencies/unitree_sdk2_python/ + uv pip install -e . --no-deps + cd ../.. +fi + +# Install project packages +if [ -f "decoupled_wbc/pyproject.toml" ]; then + UV_GIT_LFS=1 uv pip install -e "decoupled_wbc[full,dev]" -e "gear_sonic[sim]" +fi diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/image_name.txt b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/image_name.txt new file mode 100644 index 0000000000000000000000000000000000000000..10b5635afccc1b018dcf0be55a1837d39c57ce68 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/image_name.txt @@ -0,0 +1 @@ +nvcr.io/nvidian/gr00t_wbc:base diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/kill_all_containers.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/kill_all_containers.sh new file mode 100644 index 0000000000000000000000000000000000000000..1043070f399be790a5e318a6238a6a00fc5d0e67 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/kill_all_containers.sh @@ -0,0 +1,79 @@ +#!/bin/bash + +# Script to kill all running Docker containers +# Usage: ./kill_all_containers.sh [--force] + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Function to print colored output +print_info() { + echo -e "${GREEN}[INFO]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# Check if Docker is running +if ! sudo docker info >/dev/null 2>&1; then + print_error "Docker is not running or not accessible. Please start Docker first." + exit 1 +fi + +# Get list of running containers +RUNNING_CONTAINERS=$(sudo docker ps -q) + +if [ -z "$RUNNING_CONTAINERS" ]; then + print_info "No running containers found." + exit 0 +fi + +# Count running containers +CONTAINER_COUNT=$(echo "$RUNNING_CONTAINERS" | wc -l | tr -d ' ') + +print_info "Found $CONTAINER_COUNT running container(s):" +sudo docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Names}}\t{{.Status}}" + +# Check for --force flag +FORCE_KILL=false +if [ "$1" = "--force" ]; then + FORCE_KILL=true + print_warning "Force mode enabled. Containers will be killed without confirmation." +fi + +# Ask for confirmation unless --force is used +if [ "$FORCE_KILL" = false ]; then + echo + read -p "Are you sure you want to kill all running containers? (y/N): " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + print_info "Operation cancelled." + exit 0 + fi +fi + +# Kill all running containers +print_info "Killing all running containers..." +if sudo docker kill $RUNNING_CONTAINERS; then + print_info "Successfully killed all running containers." +else + print_error "Failed to kill some containers. You may need to run with sudo or check Docker permissions." + exit 1 +fi + +# Optional: Remove stopped containers (commented out by default) +# Uncomment the following lines if you also want to remove the stopped containers +# print_info "Removing stopped containers..." +# sudo docker container prune -f + +print_info "Done!" \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/kill_decoupled_wbc_processors.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/kill_decoupled_wbc_processors.sh new file mode 100644 index 0000000000000000000000000000000000000000..b9dd4c1b6e8694520a2b22dc650b04139dde102b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/kill_decoupled_wbc_processors.sh @@ -0,0 +1,192 @@ +#!/bin/bash + +# kill_decoupled_wbc_processors.sh +# Kill decoupled_wbc processes in current container to prevent message passing conflicts + +# Note: Don't use 'set -e' as tmux/pgrep commands may return non-zero exit codes + +# Configuration +DRY_RUN=false +FORCE=false +QUIET=false +declare -A FOUND_PROCESSES + +# Default to verbose mode if no arguments +[[ $# -eq 0 ]] && { QUIET=false; DRY_RUN=false; } + +# Parse arguments +while [[ $# -gt 0 ]]; do + case $1 in + --dry-run) DRY_RUN=true ;; + --force) FORCE=true ;; + --verbose|-v) VERBOSE=true ;; + --help|-h) + echo "Usage: $0 [--dry-run] [--force] [--verbose] [--help]" + echo "Kill decoupled_wbc processes to prevent message passing conflicts" + exit 0 ;; + *) echo "Unknown option: $1"; exit 1 ;; + esac + shift +done + +# Colors (only if not quiet) +if [[ "$QUIET" != true ]]; then + RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m' +else + RED=''; GREEN=''; YELLOW=''; BLUE=''; NC='' +fi + +# Show processes by pattern (for preview) +show_processes_by_pattern() { + local pattern="$1" desc="$2" + local pids=$(pgrep -f "$pattern" 2>/dev/null || true) + + [[ -z "$pids" ]] && return 0 + + echo -e "${YELLOW}$desc processes:${NC}" + + for pid in $pids; do + local cmd=$(ps -p $pid -o cmd= 2>/dev/null || echo "Process not found") + echo " PID $pid: $cmd" + done +} + +# Kill processes by pattern (silent killing) +kill_by_pattern() { + local pattern="$1" desc="$2" signal="${3:-TERM}" + local pids=$(pgrep -f "$pattern" 2>/dev/null || true) + + [[ -z "$pids" ]] && return 0 + + for pid in $pids; do + # Kill if not dry run + [[ "$DRY_RUN" != true ]] && kill -$signal $pid 2>/dev/null + done +} + +# Show tmux sessions (for preview) +show_tmux() { + local pattern="$1" + local sessions=$(tmux list-sessions 2>/dev/null | grep "$pattern" | cut -d: -f1 || true) + + [[ -z "$sessions" ]] && return 0 + + echo -e "${YELLOW}Tmux sessions:${NC}" + + for session in $sessions; do + echo " Session: $session" + done +} + +# Kill tmux sessions (silent killing) +kill_tmux() { + local pattern="$1" + local sessions=$(tmux list-sessions 2>/dev/null | grep "$pattern" | cut -d: -f1 || true) + + [[ -z "$sessions" ]] && return 0 + + for session in $sessions; do + [[ "$DRY_RUN" != true ]] && tmux kill-session -t "$session" 2>/dev/null + done +} + +# Show processes by port (for preview) +show_processes_by_port() { + local port="$1" desc="$2" + local pids=$(lsof -ti:$port 2>/dev/null || true) + + [[ -z "$pids" ]] && return 0 + + echo -e "${YELLOW}$desc (port $port):${NC}" + + for pid in $pids; do + local cmd=$(ps -p $pid -o cmd= 2>/dev/null || echo "Process not found") + echo " PID $pid: $cmd" + done +} + +# Kill processes by port (silent killing) +kill_by_port() { + local port="$1" desc="$2" + local pids=$(lsof -ti:$port 2>/dev/null || true) + + [[ -z "$pids" ]] && return 0 + + for pid in $pids; do + [[ "$DRY_RUN" != true ]] && kill -TERM $pid 2>/dev/null + done +} + +# Check if any processes exist +has_processes() { + # Check for processes + local has_tmux=$(tmux list-sessions 2>/dev/null | grep "g1_deployment" || true) + local has_control=$(pgrep -f "run_g1_control_loop.py" 2>/dev/null || true) + local has_teleop=$(pgrep -f "run_teleop_policy_loop.py" 2>/dev/null || true) + local has_camera=$(pgrep -f "camera_forwarder.py" 2>/dev/null || true) + local has_rqt=$(pgrep -f "rqt.*image_view" 2>/dev/null || true) + local has_port=$(lsof -ti:5555 2>/dev/null || true) + + [[ -n "$has_tmux" || -n "$has_control" || -n "$has_teleop" || -n "$has_camera" || -n "$has_rqt" || -n "$has_port" ]] +} + +# Main execution +main() { + # Check if any processes exist first + if ! has_processes; then + # No processes to kill, exit silently + exit 0 + fi + + # Show header and processes to be killed + if [[ "$QUIET" != true ]]; then + echo -e "${BLUE}=== decoupled_wbc Process Killer ===${NC}" + [[ "$DRY_RUN" == true ]] && echo -e "${BLUE}=== DRY RUN MODE ===${NC}" + + # Show what will be killed + show_tmux "g1_deployment" + show_processes_by_pattern "run_g1_control_loop.py" "G1 control loop" + show_processes_by_pattern "run_teleop_policy_loop.py" "Teleop policy" + show_processes_by_pattern "camera_forwarder.py" "Camera forwarder" + show_processes_by_pattern "rqt.*image_view" "RQT viewer" + show_processes_by_port "5555" "Inference server" + + # Ask for confirmation + if [[ "$FORCE" != true && "$DRY_RUN" != true ]]; then + echo + echo -e "${RED}WARNING: This will terminate the above decoupled_wbc processes!${NC}" + read -p "Continue? [Y/n]: " -n 1 -r + echo + # Default to Y - only abort if user explicitly types 'n' or 'N' + [[ $REPLY =~ ^[Nn]$ ]] && { echo "Aborted."; exit 0; } + fi + echo + fi + + # Kill processes (silently) + kill_tmux "g1_deployment" + kill_by_pattern "run_g1_control_loop.py" "G1 control loop" + kill_by_pattern "run_teleop_policy_loop.py" "Teleop policy" + kill_by_pattern "camera_forwarder.py" "Camera forwarder" + kill_by_pattern "rqt.*image_view" "RQT viewer" + kill_by_port "5555" "Inference server" + + # Force kill remaining (SIGKILL) + [[ "$DRY_RUN" != true ]] && { + sleep 1 + kill_by_pattern "run_g1_control_loop.py" "G1 control loop" "KILL" + kill_by_pattern "run_teleop_policy_loop.py" "Teleop policy" "KILL" + kill_by_pattern "camera_forwarder.py" "Camera forwarder" "KILL" + } + + # Summary (unless quiet) + [[ "$QUIET" != true ]] && { + if [[ "$DRY_RUN" == true ]]; then + echo -e "${BLUE}=== DRY RUN COMPLETE ===${NC}" + else + echo -e "${GREEN}All decoupled_wbc processes terminated${NC}" + fi + } +} + +main "$@" diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/publish.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/publish.sh new file mode 100644 index 0000000000000000000000000000000000000000..a9d909e8dc30bc627d7270649706a815f050717e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/publish.sh @@ -0,0 +1,3 @@ +#!/bin/bash +image_name=$(cat image_name.txt) +docker push "$@" $image_name \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/run_docker.sh b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/run_docker.sh new file mode 100644 index 0000000000000000000000000000000000000000..b53db26ff881369d3c12e10f33faaa4c6d0ad333 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/docker/run_docker.sh @@ -0,0 +1,455 @@ +#!/bin/bash + +# Docker run script for decoupled_wbc with branch-based container isolation +# +# Usage: +# ./docker/run_docker.sh [OPTIONS] (run from inside decoupled_wbc/) +# +# Options: +# --build Build Docker image +# --clean Clean containers +# --deploy Run in deploy mode +# --install Pull prebuilt Docker image +# --push Push built image to Docker Hub +# --branch Use branch-specific container names +# +# Branch-based Container Isolation (when --branch flag is used): +# - Each git branch gets its own isolated containers +# - Container names include branch identifier (e.g., decoupled_wbc-deploy-user-main) +# - Works with git worktrees, separate clones, or nested repositories +# - Clean and build operations only affect the current branch + +# Exit on error +set -e + +# Default values +BUILD=false +CLEAN=false +DEPLOY=false +INSTALL=false +# Flag to push the built Docker image to Docker Hub +# This should be used when someone updates the Docker image dependencies +# because this image is used for CI/CD pipelines +# When true, the image will be tagged and pushed to docker.io/nvgear/gr00t_wbc:latest +DOCKER_HUB_PUSH=false +# Flag to build the docker with root user +# This could cause some of your local files to be owned by root +# If you get error like "PermissionError: [Errno 13] Permission denied:" +# You can run `sudo chown -R $USER:$USER .` in local machine to fix it +ROOT=false +BRANCH_MODE=false +EXTRA_ARGS=() +PROJECT_NAME="decoupled_wbc" +PROJECT_SLUG=$(echo "$PROJECT_NAME" | tr '[:upper:]' '[:lower:]') +REMOTE_IMAGE="nvgear/gr00t_wbc:latest" + +# Parse command line arguments +while [[ $# -gt 0 ]]; do + case $1 in + --build) + BUILD=true + shift + ;; + --clean) + CLEAN=true + shift + ;; + --deploy) + DEPLOY=true + shift + ;; + --install) + INSTALL=true + shift + ;; + --push) + DOCKER_HUB_PUSH=true + shift + ;; + --root) + ROOT=true + shift + ;; + --branch) + BRANCH_MODE=true + shift + ;; + *) + # Collect all unknown arguments as extra args for the deployment script + EXTRA_ARGS+=("$1") + shift + ;; + esac +done + +if [ "$INSTALL" = true ] && [ "$BUILD" = true ]; then + echo "Cannot use --install and --build together. Choose one." + exit 1 +fi + + +# Function to get branch name for container naming +function get_branch_id { + # Check if we're in a git repository + if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then + # Get current branch name (returns "HEAD" in detached state) + local branch_name=$(git rev-parse --abbrev-ref HEAD) + # Replace forward slashes with dashes for valid container names + echo "${branch_name//\//-}" + else + # Default: no branch identifier (not in git repo) + echo "" + fi +} + +# Architecture detection helpers +is_arm64() { [ "$(dpkg --print-architecture)" = "arm64" ]; } +is_amd64() { [ "$(dpkg --print-architecture)" = "amd64" ]; } + +# Get current user's username and UID +if [ "$ROOT" = true ]; then + USERNAME=root + USERID=0 + DOCKER_HOME_DIR=/root + CACHE_FROM=${PROJECT_SLUG}-deploy-cache-root +else + USERNAME=$(whoami) + USERID=$(id -u) + DOCKER_HOME_DIR=/home/${USERNAME} + CACHE_FROM=${PROJECT_SLUG}-deploy-cache +fi +# Get input group ID for device access +INPUT_GID=$(getent group input | cut -d: -f3) + +# Get script directory for path calculations +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +# Function to get the actual project directory (worktree-aware) +function get_project_dir { + # For worktrees, use the actual worktree root path + if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then + git rev-parse --show-toplevel + else + # Fallback to script-based detection (go up two levels: docker/ -> decoupled_wbc/ -> project root) + dirname "$(dirname "$SCRIPT_DIR")" + fi +} + +# Get branch identifier +BRANCH_ID=$(get_branch_id) + +# Set project directory (needs to be after branch detection) +PROJECT_DIR="$(get_project_dir)" + +# Function to generate container name with optional branch support +function get_container_name { + local container_type="$1" + if [[ -n "$BRANCH_ID" ]] && [[ "$BRANCH_MODE" = true ]]; then + echo "${PROJECT_SLUG}-${container_type}-${USERNAME}-${BRANCH_ID}" + else + echo "${PROJECT_SLUG}-${container_type}-${USERNAME}" + fi +} + +# Set common variables used throughout the script +DEPLOY_CONTAINER=$(get_container_name "deploy") +BASH_CONTAINER=$(get_container_name "bash") +WORKTREE_NAME=$(basename "$PROJECT_DIR") + +# Debug output for branch detection +if [[ -n "$BRANCH_ID" ]] && [[ "$BRANCH_MODE" = true ]]; then + echo "Branch mode enabled - using branch: $BRANCH_ID" + echo "Project directory: $PROJECT_DIR" +elif [[ -n "$BRANCH_ID" ]]; then + echo "Branch mode disabled - using default containers" + echo "Project directory: $PROJECT_DIR" +else + echo "Running outside git repository" + echo "Project directory: $PROJECT_DIR" +fi + +# Get host's hostname and append -docker +HOSTNAME=$(hostname)-docker + +function clean_container { + echo "Cleaning up Docker containers..." + + # Stop containers + sudo docker stop $DEPLOY_CONTAINER 2>/dev/null || true + sudo docker stop $BASH_CONTAINER 2>/dev/null || true + # Remove containers + echo "Removing containers..." + sudo docker rm $DEPLOY_CONTAINER 2>/dev/null || true + sudo docker rm $BASH_CONTAINER 2>/dev/null || true + echo "Containers cleaned!" +} + + +# Function to install Docker Buildx if needed +function install_docker_buildx { + # Check if Docker Buildx is already installed + if sudo docker buildx version &> /dev/null; then + echo "Docker Buildx is already installed." + return 0 + fi + + echo "Installing Docker Buildx..." + + # Create directories and detect architecture + mkdir -p ~/.docker/cli-plugins/ && sudo mkdir -p /root/.docker/cli-plugins/ + ARCH=$(dpkg --print-architecture) + [[ "$ARCH" == "arm64" ]] && BUILDX_ARCH="linux-arm64" || BUILDX_ARCH="linux-amd64" + + # Get version (with fallback) + BUILDX_VERSION=$(curl -s https://api.github.com/repos/docker/buildx/releases/latest | grep tag_name | cut -d '"' -f 4) + BUILDX_VERSION=${BUILDX_VERSION:-v0.13.1} + + # Download and install for both user and root + curl -L "https://github.com/docker/buildx/releases/download/${BUILDX_VERSION}/buildx-${BUILDX_VERSION}.${BUILDX_ARCH}" -o ~/.docker/cli-plugins/docker-buildx + sudo cp ~/.docker/cli-plugins/docker-buildx /root/.docker/cli-plugins/docker-buildx + chmod +x ~/.docker/cli-plugins/docker-buildx && sudo chmod +x /root/.docker/cli-plugins/docker-buildx + + # Create builder + sudo docker buildx create --use --name mybuilder || true + sudo docker buildx inspect --bootstrap + + echo "Docker Buildx installation complete!" +} + +# Function to install NVIDIA Container Toolkit if needed +function install_nvidia_toolkit { + # Check if NVIDIA Container Toolkit is already installed + if command -v nvidia-container-toolkit &> /dev/null; then + echo "NVIDIA Container Toolkit is already installed." + return 0 + fi + + echo "Installing NVIDIA Container Toolkit..." + + # Add the package repositories + distribution=$(. /etc/os-release;echo $ID$VERSION_ID) + + # Check if GPG key exists and remove it if it does + if [ -f "/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg" ]; then + echo "Removing existing NVIDIA GPG key..." + sudo rm /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg + fi + + # Add new GPG key + curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg + + # Add repository + curl -s -L https://nvidia.github.io/nvidia-container-runtime/$distribution/nvidia-container-runtime.list | \ + sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \ + sudo tee /etc/apt/sources.list.d/nvidia-container-runtime.list + + # Install nvidia-container-toolkit and docker if needed + sudo apt-get update + sudo apt-get install -y nvidia-container-toolkit + + # Install docker if not already installed + if ! command -v docker &> /dev/null; then + sudo apt-get install -y docker.io + fi + + # Configure Docker to use the NVIDIA runtime + sudo nvidia-ctk runtime configure --runtime=docker + + # Restart the Docker daemon + sudo systemctl restart docker + + echo "NVIDIA Container Toolkit installation complete!" +} + + +# Function to build Docker image for current branch +function build_docker_image { + echo "Building Docker image: $DEPLOY_CONTAINER" + + sudo docker buildx build \ + --build-arg USERNAME=$USERNAME \ + --build-arg USERID=$USERID \ + --build-arg HOME_DIR=$DOCKER_HOME_DIR \ + --build-arg WORKTREE_NAME=$WORKTREE_NAME \ + --cache-from $CACHE_FROM \ + -t $DEPLOY_CONTAINER \ + -f "$SCRIPT_DIR/Dockerfile.deploy" \ + --load \ + "$PROJECT_DIR" + + # Tag for persistent cache + # sudo docker tag $DEPLOY_CONTAINER $CACHE_FROM + echo "Docker image build complete!" +} + +# Build function +function build_with_cleanup { + echo "Building Docker image..." + echo "Removing existing containers and images..." + clean_container + # Tag for persistent cache before deleting the image + sudo docker tag $DEPLOY_CONTAINER $CACHE_FROM 2>/dev/null || true + sudo docker rmi $DEPLOY_CONTAINER 2>/dev/null || true + echo "Images cleaned!" + + install_docker_buildx + install_nvidia_toolkit + build_docker_image +} + +function install_remote_image { + echo "Installing Docker image from remote registry: $REMOTE_IMAGE" + echo "Removing existing containers to ensure a clean install..." + clean_container + sudo docker pull "$REMOTE_IMAGE" + sudo docker tag "$REMOTE_IMAGE" "$DEPLOY_CONTAINER" + sudo docker tag "$REMOTE_IMAGE" "$CACHE_FROM" 2>/dev/null || true + echo "Docker image install complete!" +} + +# Clean up if requested +if [ "$CLEAN" = true ]; then + clean_container + exit 0 +fi + +# Build if requested +if [ "$BUILD" = true ]; then + build_with_cleanup +fi + +if [ "$INSTALL" = true ]; then + install_remote_image +fi + +if [ "$DOCKER_HUB_PUSH" = true ]; then + echo "Pushing Docker image to Docker Hub: docker.io/${REMOTE_IMAGE}" + sudo docker tag $DEPLOY_CONTAINER docker.io/${REMOTE_IMAGE} + sudo docker push docker.io/${REMOTE_IMAGE} + echo "Docker image pushed to Docker Hub!" + exit 0 +fi + +# Setup X11 display forwarding +setup_x11() { + # Set display if missing and X server available + if [ -z "$DISPLAY" ] && command -v xset >/dev/null 2>&1 && xset q >/dev/null 2>&1; then + export DISPLAY=:1 + echo "No DISPLAY set, using :1" + fi + + # Enable X11 forwarding if possible + if [ -n "$DISPLAY" ] && command -v xhost >/dev/null 2>&1 && xhost +local:docker 2>/dev/null; then + echo "X11 forwarding enabled" + return 0 + else + echo "Headless environment - X11 disabled" + export DISPLAY="" + return 1 + fi +} + +X11_ENABLED=false +setup_x11 && X11_ENABLED=true + +# Mount entire /dev directory for dynamic device access (including hidraw for joycon) +# This allows JoyCon controllers to be detected even when connected after container launch +sudo chmod g+r+w /dev/input/* + +# Detect GPU setup and set appropriate environment variables +echo "Detecting GPU setup..." +GPU_ENV_VARS="" + +# Check if we have both integrated and discrete GPUs (hybrid/Optimus setup) +HAS_AMD_GPU=$(lspci | grep -i "vga\|3d\|display" | grep -i amd | wc -l) +HAS_INTEL_GPU=$(lspci | grep -i "vga\|3d\|display" | grep -i intel | wc -l) +HAS_NVIDIA_GPU=$(lspci | grep -i "vga\|3d\|display" | grep -i nvidia | wc -l) + +if [[ "$HAS_INTEL_GPU" -gt 0 ]] || [[ "$HAS_AMD_GPU" -gt 0 ]] && [[ "$HAS_NVIDIA_GPU" -gt 0 ]]; then + echo "Detected hybrid GPU setup (Intel/AMD integrated + NVIDIA discrete)" + echo "Setting NVIDIA Optimus environment variables for proper rendering offload..." + GPU_ENV_VARS="-e __NV_PRIME_RENDER_OFFLOAD=1 \ + -e __VK_LAYER_NV_optimus=NVIDIA_only" +else + GPU_ENV_VARS="" +fi + +# Set GPU runtime based on architecture +if is_arm64; then + echo "Detected ARM64 architecture (Jetson Orin), using device access instead of nvidia runtime..." + GPU_RUNTIME_ARGS="--device /dev/nvidia0 --device /dev/nvidiactl --device /dev/nvidia-modeset --device /dev/nvidia-uvm --device /dev/nvidia-uvm-tools" +else + GPU_RUNTIME_ARGS="--gpus all --runtime=nvidia" +fi + +# Common Docker run parameters +DOCKER_RUN_ARGS="--hostname $HOSTNAME \ + --user $USERNAME \ + --group-add $INPUT_GID \ + $GPU_RUNTIME_ARGS \ + --ipc=host \ + --network=host \ + --privileged \ + --device=/dev \ + $GPU_ENV_VARS \ + -p 5678:5678 \ + -e DISPLAY=$DISPLAY \ + -e NVIDIA_VISIBLE_DEVICES=all \ + -e NVIDIA_DRIVER_CAPABILITIES=graphics,compute,utility \ + -e __GLX_VENDOR_LIBRARY_NAME=nvidia \ + -e USERNAME=$USERNAME \ + -e DECOUPLED_WBC_DIR="$DOCKER_HOME_DIR/Projects/$WORKTREE_NAME" \ + -e PYTHONPATH="$DOCKER_HOME_DIR/Projects/$WORKTREE_NAME" \ + -v /dev/bus/usb:/dev/bus/usb \ + -v /tmp/.X11-unix:/tmp/.X11-unix \ + -v $HOME/.ssh:$DOCKER_HOME_DIR/.ssh \ + -v $HOME/.gear:$DOCKER_HOME_DIR/.gear \ + -v $HOME/.Xauthority:$DOCKER_HOME_DIR/.Xauthority \ + -v $PROJECT_DIR:$DOCKER_HOME_DIR/Projects/$(basename "$PROJECT_DIR") + --device /dev/snd \ + --group-add audio \ + -e PULSE_SERVER=unix:/run/user/$(id -u)/pulse/native \ + -v /run/user/$(id -u)/pulse/native:/run/user/$(id -u)/pulse/native \ + -v $HOME/.config/pulse/cookie:/home/$USERNAME/.config/pulse/cookie" + +# Check if RL mode first, then handle container logic +if [ "$DEPLOY" = true ]; then + # Deploy mode - use decoupled_wbc-deploy-${USERNAME} container + + # Always clean up old processes and create a new container + # Kill all decoupled_wbc processes across containers to prevent message passing conflicts + "$SCRIPT_DIR/kill_decoupled_wbc_processors.sh" + echo "Creating new deploy container..." + + # Clean up old processes and create a fresh deploy container + # Remove existing deploy container if it exists + if sudo docker ps -a --format '{{.Names}}' | grep -q "^$DEPLOY_CONTAINER$"; then + echo "Removing existing deploy container..." + sudo docker rm -f $DEPLOY_CONTAINER + fi + sudo docker run -it --rm $DOCKER_RUN_ARGS \ + -w $DOCKER_HOME_DIR/Projects/$WORKTREE_NAME \ + --name $DEPLOY_CONTAINER \ + $DEPLOY_CONTAINER \ + /bin/bash -ic 'exec "$0" "$@"' \ + "${DOCKER_HOME_DIR}/Projects/${WORKTREE_NAME}/decoupled_wbc/docker/entrypoint/deploy.sh" \ + "${EXTRA_ARGS[@]}" +else + # Bash mode - use decoupled_wbc-bash-${USERNAME} container + if sudo docker ps -a --format '{{.Names}}' | grep -q "^$BASH_CONTAINER$"; then + echo "Bash container exists, starting it..." + sudo docker start $BASH_CONTAINER > /dev/null + sudo docker exec -it $BASH_CONTAINER /bin/bash + else + echo "Creating new bash container with auto-install decoupled_wbc..." + sudo docker run -it $DOCKER_RUN_ARGS \ + -w $DOCKER_HOME_DIR/Projects/$WORKTREE_NAME \ + --name $BASH_CONTAINER \ + $DEPLOY_CONTAINER \ + /bin/bash -ic 'exec "$0"' \ + "${DOCKER_HOME_DIR}/Projects/${WORKTREE_NAME}/decoupled_wbc/docker/entrypoint/bash.sh" + fi +fi + +# Cleanup X11 permissions +$X11_ENABLED && xhost -local:docker 2>/dev/null diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/pyproject.toml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..aa27309f726d5d4fa030a08b204b61257f84f351 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/pyproject.toml @@ -0,0 +1,93 @@ +[build-system] +requires = ["setuptools>=67", "wheel", "pip"] +build-backend = "setuptools.build_meta" + +[project] +name = "decoupled_wbc" +dynamic = ["version"] +readme = "../README.md" +classifiers = [ + "Intended Audience :: Science/Research", + "Development Status :: 3 - Alpha", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3", + "Topic :: Scientific/Engineering :: Artificial Intelligence", +] +authors = [ + {name = "NVIDIA Gear Lab"} +] +requires-python = ">=3.10" +dependencies = [ + "numpy==1.26.4", + "scipy==1.15.3", + "torch", +] +license = {file = "../LICENSE"} + +[project.optional-dependencies] +# Full: all dependencies for the complete decoupled_wbc project +# Usage: pip install -e "decoupled_wbc[full]" +full = [ + "av>=14.2", + "pyttsx3==2.90", + "matplotlib", + "hydra-core", + "ray[default]", + "click", + "gymnasium", + "mujoco", + "termcolor", + "flask", + "python-socketio>=5.13.0", + "flask_socketio", + "loguru", + "meshcat", + "meshcat-shapes", + "onnxruntime", + "rerun-sdk==0.21.0", + "pygame", + "sshkeyboard", + "msgpack", + "msgpack-numpy", + "pyzmq", + "PyQt6; platform_machine != 'aarch64'", + "pin", + "pin-pink", + "pyrealsense2; sys_platform != 'darwin'", + "pyrealsense2-macosx; sys_platform == 'darwin'", + "qpsolvers[osqp,quadprog]", + "tyro", + "cv-bridge", + "lark", + "lerobot @ git+https://github.com/huggingface/lerobot.git@a445d9c9da6bea99a8972daa4fe1fdd053d711d2", + "datasets==3.6.0", + "pandas", + "evdev; sys_platform == 'linux'", + "pyyaml", +] +dev = [ + "pytest==7.4.0", + "build", + "setuptools", + "wheel", + "ruff", + "black", + "ipdb", +] + +[project.scripts] +decoupled_wbc = "decoupled_wbc.control.teleop.gui.cli:cli" + +[tool.setuptools.packages.find] +where = [".."] +include = ["decoupled_wbc*"] + +[tool.setuptools] +include-package-data = true + +[tool.setuptools.package-data] +decoupled_wbc = ["py.typed", "**/*.json", "**/*.yaml"] + +[tool.setuptools.dynamic] +version = {attr = "decoupled_wbc.version.VERSION"} + diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/deploy_g1.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/deploy_g1.py new file mode 100644 index 0000000000000000000000000000000000000000..b2fa6be9c42f4bf6f10cb90ec1d6e70cb51ebf07 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/deploy_g1.py @@ -0,0 +1,472 @@ +from pathlib import Path +import signal +import subprocess +import sys +import time + +import tyro + +from decoupled_wbc.control.main.teleop.configs.configs import DeploymentConfig +from decoupled_wbc.control.utils.run_real_checklist import show_deployment_checklist + + +class G1Deployment: + """ + Unified deployment manager for G1 robot with one-click operation. + Handles camera setup, control loop, teleoperation, and data collection. + Uses tmux for process management and I/O handling. + """ + + def __init__(self, config: DeploymentConfig): + self.config = config + + # Process directories + self.project_root = Path(__file__).resolve().parent.parent + + # Tmux session name + self.session_name = "g1_deployment" + + # Create tmux session if it doesn't exist + self._create_tmux_session() + + def _create_tmux_session(self): + """Create a new tmux session if it doesn't exist""" + # Check if session exists + result = subprocess.run( + ["tmux", "has-session", "-t", self.session_name], capture_output=True, text=True + ) + + if result.returncode != 0: + # Create new session + subprocess.run(["tmux", "new-session", "-d", "-s", self.session_name]) + print(f"Created new tmux session: {self.session_name}") + + # Set up the default window for control, data collection, and teleop + # First rename the default window (which is 0) to our desired name + subprocess.run( + ["tmux", "rename-window", "-t", f"{self.session_name}:0", "control_data_teleop"] + ) + # Split the window horizontally (left and right) + subprocess.run(["tmux", "split-window", "-t", f"{self.session_name}:0", "-h"]) + # Split the right pane vertically (top and bottom) + subprocess.run(["tmux", "split-window", "-t", f"{self.session_name}:0.1", "-v"]) + # Select the left pane (control) + subprocess.run(["tmux", "select-pane", "-t", f"{self.session_name}:0.0"]) + + def _run_in_tmux(self, name, cmd, wait_time=2, pane_index=None): + """Run a command in a new tmux window or pane""" + if pane_index is not None: + # Run in existing window's pane + target = f"{self.session_name}:0.{pane_index}" + else: + # Create new window + subprocess.run(["tmux", "new-window", "-t", self.session_name, "-n", name]) + target = f"{self.session_name}:{name}" + + # Set up trap for Ctrl+\ in the window + trap_cmd = f"trap 'tmux kill-session -t {self.session_name}' QUIT" + + # Set environment variable for the tmux session name + env_cmd = f"export DECOUPLED_WBC_TMUX_SESSION={self.session_name}" + + # Construct the command with proper escaping and trap + cmd_str = " ".join(str(x) for x in cmd) + full_cmd = f"{trap_cmd}; {env_cmd}; {cmd_str}" + + # Send command to tmux window/pane + subprocess.run(["tmux", "send-keys", "-t", target, full_cmd, "C-m"]) + + # Wait for process to start + time.sleep(wait_time) + + # Check if process is still running + result = subprocess.run( + ["tmux", "list-panes", "-t", target, "-F", "#{pane_dead}"], + capture_output=True, + text=True, + ) + + if result.stdout.strip() == "1": + print(f"ERROR: {name} failed to start!") + return False + + return True + + def start_camera_sensor(self): + """Start the camera sensor in local mode if we are using replay video""" + if self.config.egoview_replay_dummy is None and self.config.head_replay_dummy is None: + return + + print("Starting camera sensor in local mode...") + cmd = [ + sys.executable, + str(self.project_root / "control/sensor/composed_camera.py"), + "--egoview_camera", + self.config.egoview_replay_dummy, + "--head_camera", + self.config.head_replay_dummy, + "--port", + str(self.config.camera_port), + "--host", + "localhost", + ] + + if not self._run_in_tmux("camera_sensor", cmd): + print("ERROR: Camera sensor failed to start!") + print("Continuing without camera sensor...") + else: + print("Camera sensor started successfully.") + + def start_camera_viewer(self): + """Start the ROS rqt camera viewer""" + if not self.config.view_camera: + return + + print("Starting camera viewer...") + # Use rqt directly instead of ros2 run + cmd = [ + sys.executable, + str(self.project_root / "control/main/teleop/run_camera_viewer.py"), + "--camera_host", + self.config.camera_host, + "--camera_port", + str(self.config.camera_port), + "--fps", + str(self.config.fps), + ] + + if not self._run_in_tmux("camera_viewer", cmd): + print("ERROR: Camera viewer failed to start!") + print("Continuing without camera viewer...") + else: + print("Camera viewer started successfully.") + + def start_sim_loop(self): + """Start the simulation loop in a separate process""" + print("Starting simulation loop...") + cmd = [ + sys.executable, + str(self.project_root / "control/main/teleop/run_sim_loop.py"), + "--wbc_version", + self.config.wbc_version, + "--interface", + self.config.interface, + "--simulator", + self.config.simulator, + "--sim_frequency", + str(self.config.sim_frequency), + "--env_name", + self.config.env_name, + "--camera_port", + str(self.config.camera_port), + ] + + # Handle boolean flags + if self.config.enable_waist: + cmd.append("--enable_waist") + else: + cmd.append("--no-enable_waist") + + if self.config.with_hands: + cmd.append("--with_hands") + else: + cmd.append("--no-with_hands") + + if self.config.image_publish: + cmd.append("--enable_image_publish") + cmd.append("--enable_offscreen") + else: + cmd.append("--no-enable_image_publish") + + if self.config.enable_onscreen: + cmd.append("--enable_onscreen") + else: + cmd.append("--no-enable_onscreen") + + if not self._run_in_tmux("sim_loop", cmd, wait_time=5): + print("ERROR: Simulation loop failed to start!") + self.cleanup() + sys.exit(1) + + print("Simulation loop started successfully. Waiting for warmup for 10 seconds...") + time.sleep(10) # Wait for sim loop to warm up + + def start_control_loop(self): + """Start the G1 control loop""" + print("Starting G1 control loop...") + cmd = [ + sys.executable, + str(self.project_root / "control/main/teleop/run_g1_control_loop.py"), + "--wbc_version", + self.config.wbc_version, + "--wbc_model_path", + self.config.wbc_model_path, + "--wbc_policy_class", + self.config.wbc_policy_class, + "--interface", + self.config.interface, + "--simulator", + "None" if self.config.sim_in_single_process else self.config.simulator, + "--control_frequency", + str(self.config.control_frequency), + ] + + # Handle boolean flag using presence/absence pattern + if self.config.enable_waist: + cmd.append("--enable_waist") + else: + cmd.append("--no-enable_waist") + + if self.config.with_hands: + cmd.append("--with_hands") + else: + cmd.append("--no-with_hands") + + if self.config.high_elbow_pose: + cmd.append("--high_elbow_pose") + else: + cmd.append("--no-high_elbow_pose") + + # Gravity compensation configuration + # Note: This is where gravity compensation is actually applied since the control loop + # contains the G1Body that interfaces directly with the robot motors + if self.config.enable_gravity_compensation: + cmd.append("--enable_gravity_compensation") + # Add joint groups if specified + if self.config.gravity_compensation_joints: + cmd.extend( + ["--gravity_compensation_joints"] + self.config.gravity_compensation_joints + ) + else: + cmd.append("--no-enable_gravity_compensation") + + if not self._run_in_tmux("control", cmd, wait_time=3, pane_index=0): + print("ERROR: Control loop failed to start!") + self.cleanup() + sys.exit(1) + + print("Control loop started successfully.") + print("Controls: 'i' for initial pose, ']' to activate locomotion") + + def start_policy(self): + """Start either teleop or inference policy based on configuration""" + if not self.config.enable_upper_body_operation: + print("Upper body operation disabled in config.") + return + + self.start_teleop() + + def start_teleop(self): + """Start the teleoperation policy""" + print("Starting teleoperation policy...") + cmd = [ + sys.executable, + str(self.project_root / "control/main/teleop/run_teleop_policy_loop.py"), + "--body_control_device", + self.config.body_control_device, + "--hand_control_device", + self.config.hand_control_device, + "--body_streamer_ip", + self.config.body_streamer_ip, + "--body_streamer_keyword", + self.config.body_streamer_keyword, + ] + + # Handle boolean flags using tyro syntax + if self.config.enable_waist: + cmd.append("--enable_waist") + else: + cmd.append("--no-enable_waist") + + if self.config.high_elbow_pose: + cmd.append("--high_elbow_pose") + else: + cmd.append("--no-high_elbow_pose") + + if self.config.enable_visualization: + cmd.append("--enable_visualization") + else: + cmd.append("--no-enable_visualization") + + if self.config.enable_real_device: + cmd.append("--enable_real_device") + else: + cmd.append("--no-enable_real_device") + + if not self._run_in_tmux("teleop", cmd, pane_index=2): + print("ERROR: Teleoperation policy failed to start!") + print("Continuing without teleoperation...") + else: + print("Teleoperation policy started successfully.") + print("Press 'l' in the control loop terminal to start teleoperation.") + + def start_data_collection(self): + """Start the data collection process""" + if not self.config.data_collection: + print("Data collection disabled in config.") + return + + print("Starting data collection...") + cmd = [ + sys.executable, + str(self.project_root / "control/main/teleop/run_g1_data_exporter.py"), + "--data_collection_frequency", + str(self.config.data_collection_frequency), + "--root_output_dir", + self.config.root_output_dir, + "--lower_body_policy", + self.config.wbc_version, + "--wbc_model_path", + self.config.wbc_model_path, + "--camera_host", + self.config.camera_host, + "--camera_port", + str(self.config.camera_port), + ] + + if not self._run_in_tmux("data", cmd, pane_index=1): + print("ERROR: Data collection failed to start!") + print("Continuing without data collection...") + else: + print("Data collection started successfully.") + print("Press 'c' in the control loop terminal to start/stop recording data.") + + def start_webcam_recording(self): + """Start webcam recording for real robot deployment monitoring""" + if not self.config.enable_webcam_recording or self.config.env_type != "real": + return + + print("Starting webcam recording for deployment monitoring...") + cmd = [ + sys.executable, + str(self.project_root / "scripts/run_webcam_recorder.py"), + "--output_dir", + self.config.webcam_output_dir, + ] + + if not self._run_in_tmux("webcam", cmd): + print("ERROR: Webcam recording failed to start!") + print("Continuing without webcam recording...") + else: + print("Webcam recording started successfully.") + print("External camera recording deployment activities to logs_experiment/") + + def deploy(self): + """ + Run the complete deployment process + """ + print("Starting G1 deployment with config:") + print(f" Robot IP: {self.config.robot_ip}") + print(f" WBC Version: {self.config.wbc_version}") + print(f" Interface: {self.config.interface}") + print(f" Policy Mode: {self.config.upper_body_operation_mode}") + print(f" With Hands: {self.config.with_hands}") + print(f" View Camera: {self.config.view_camera}") + print(f" Enable Waist: {self.config.enable_waist}") + print(f" High Elbow Pose: {self.config.high_elbow_pose}") + print(f" Gravity Compensation: {self.config.enable_gravity_compensation}") + if self.config.enable_gravity_compensation: + print(f" Gravity Comp Joints: {self.config.gravity_compensation_joints}") + print( + f" Webcam Recording: {self.config.enable_webcam_recording and self.config.env_type == 'real'}" + ) + print(f" Sim in Single Process: {self.config.sim_in_single_process}") + if self.config.sim_in_single_process: + print(f" Image Publish: {self.config.image_publish}") + + # Check if this is a real robot deployment and run safety checklist + if self.config.env_type == "real": + if not show_deployment_checklist(): + sys.exit(1) + + # Register signal handler for clean shutdown + signal.signal(signal.SIGINT, self.signal_handler) + + # Start components in sequence + # Start sim loop first if sim_in_single_process is enabled + if self.config.sim_in_single_process: + self.start_sim_loop() + + self.start_control_loop() + self.start_camera_viewer() + self.start_policy() # This will start either teleop or inference policy + self.start_data_collection() + self.start_webcam_recording() # Only runs for real robot deployment + + print("\n--- G1 DEPLOYMENT COMPLETE ---") + print("All systems running in tmux session:", self.session_name) + print("Press Ctrl+b then d to detach from the session") + print("Press Ctrl+\\ in any window to shutdown all components.") + + try: + # Automatically attach to the tmux session and switch to control window + subprocess.run( + [ + "tmux", + "attach", + "-t", + self.session_name, + ";", + "select-window", + "-t", + "control_data_teleop", + ] + ) + except KeyboardInterrupt: + print("\nShutdown requested...") + self.cleanup() + sys.exit(0) + + # Keep main thread alive to handle signals + try: + while True: + # Check if tmux session still exists + result = subprocess.run( + ["tmux", "has-session", "-t", self.session_name], capture_output=True, text=True + ) + + if result.returncode != 0: + print("Tmux session terminated. Exiting.") + break + + time.sleep(1) + except KeyboardInterrupt: + print("\nShutdown requested...") + finally: + self.cleanup() + + def cleanup(self): + """Clean up tmux session""" + print("Cleaning up tmux session...") + try: + # Kill the tmux session + subprocess.run(["tmux", "kill-session", "-t", self.session_name], timeout=5) + print("Tmux session terminated successfully.") + except subprocess.TimeoutExpired: + print("Warning: Tmux session termination timed out, forcing kill...") + subprocess.run(["tmux", "kill-session", "-t", self.session_name, "-9"]) + except Exception as e: + print(f"Warning: Error during cleanup: {e}") + print("Cleanup complete.") + + def signal_handler(self, sig, frame): + """Handle SIGINT (Ctrl+C) gracefully""" + print("\nShutdown signal received...") + self.cleanup() + sys.exit(0) + + +def main(): + """Main entry point with automatic CLI generation from G1Config dataclass""" + # This single line automatically generates a complete CLI from the dataclass! + config = tyro.cli(DeploymentConfig) + + # Run deployment with the configured settings + deployment = G1Deployment(config) + deployment.deploy() + + +if __name__ == "__main__": + # Edited outside docker + + main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/leap_tracking_example.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/leap_tracking_example.py new file mode 100644 index 0000000000000000000000000000000000000000..04fde4b504afc4307f3fc221450166406d8ccf43 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/leap_tracking_example.py @@ -0,0 +1,50 @@ +"""Prints the palm position of each hand, every frame. When a device is +connected we set the tracking mode to desktop and then generate logs for +every tracking frame received. The events of creating a connection to the +server and a device being plugged in also generate logs. +""" + +import time + +import leap + + +class MyListener(leap.Listener): + def on_connection_event(self, event): + print("Connected") + + def on_device_event(self, event): + try: + with event.device.open(): + info = event.device.get_info() + except leap.LeapCannotOpenDeviceError: + info = event.device.get_info() + + print(f"Found device {info.serial}") + + def on_tracking_event(self, event): + print(f"Frame {event.tracking_frame_id} with {len(event.hands)} hands.") + for hand in event.hands: + hand_type = "left" if str(hand.type) == "HandType.Left" else "right" + print( + f"Hand id {hand.id} is a {hand_type} hand with position ({hand.palm.position.x}, " + f"{hand.palm.position.y}, {hand.palm.position.z})." + ) + + +def main(): + my_listener = MyListener() + + connection = leap.Connection() + connection.add_listener(my_listener) + + running = True + + with connection.open(): + connection.set_tracking_mode(leap.TrackingMode.Desktop) + while running: + time.sleep(1) + + +if __name__ == "__main__": + main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/run_webcam_recorder.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/run_webcam_recorder.py new file mode 100644 index 0000000000000000000000000000000000000000..18e1965d93bd509ca02519293c57da306162ea34 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/scripts/run_webcam_recorder.py @@ -0,0 +1,392 @@ +#!/usr/bin/env python3 +""" +Simple webcam recorder with optional preview window. +Usage: + webcam_recorder.py [--output-dir DIR] [--no-preview] + webcam_recorder.py --help +""" + +import argparse +from datetime import datetime +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + + +class WebcamRecorder: + def __init__(self, debug=False): + self.process = None + self.debug = debug + + def _debug_print(self, message): + """Print debug message only if debug mode is enabled.""" + if self.debug: + print(f"[webcam_recorder] {message}", file=sys.stderr) + + def _info_print(self, message): + """Print info message always.""" + print(f"[webcam_recorder] {message}", file=sys.stderr) + + def find_webcam(self): + """Find available webcam device.""" + # Check container status only in debug mode + if self.debug and (os.path.exists("/.dockerenv") or os.environ.get("CONTAINER")): + self._debug_print("Running in Docker container") + # Check if we have video group permissions + try: + import grp + + groups = os.getgroups() + video_gid = grp.getgrnam("video").gr_gid + if video_gid in groups: + self._debug_print("Has video group permissions ✓") + else: + self._debug_print("Warning: Not in video group") + except Exception: + pass + + # Check /dev/v4l/by-id for Logitech webcam first + by_id_path = Path("/dev/v4l/by-id") + if by_id_path.exists(): + self._debug_print("Checking /dev/v4l/by-id for devices...") + for device in by_id_path.iterdir(): + if device.is_symlink(): + device_name = device.name + if "Logitech" in device_name or "046d" in device_name: + resolved_device = str(device.resolve()) + self._debug_print( + f"Found Logitech device: {device_name} -> {resolved_device}" + ) + if self._is_video_capture_device(resolved_device): + return resolved_device + + # No Logitech found, try any webcam + for device in by_id_path.iterdir(): + if device.is_symlink() and "metadata" not in device.name: + resolved_device = str(device.resolve()) + self._debug_print(f"Checking device: {device.name} -> {resolved_device}") + if self._is_video_capture_device(resolved_device): + return resolved_device + + # Fallback to /dev/video* - prioritize external cameras + self._debug_print("Scanning /dev/video* devices...") + external_devices = [] + integrated_devices = [] + + for i in range(20): + device = f"/dev/video{i}" + if os.path.exists(device): + # Check if we can access the device + if not os.access(device, os.R_OK): + self._debug_print(f"Found {device} but no read access") + continue + + # Check if it's a video capture device (not metadata) + if self._is_video_capture_device(device): + # Check device name to prioritize external cameras + device_name = self._get_device_name(device) + if device_name: + if any( + keyword in device_name.lower() + for keyword in ["logitech", "brio", "c920", "c930", "c925"] + ): + self._info_print(f"Found external camera: {device} ({device_name})") + external_devices.append(device) + elif ( + "integrated" in device_name.lower() or "internal" in device_name.lower() + ): + self._debug_print(f"Found integrated camera: {device} ({device_name})") + integrated_devices.append(device) + else: + self._debug_print(f"Found unknown camera: {device} ({device_name})") + external_devices.append(device) # Assume external if unknown + else: + self._debug_print(f"Found camera: {device} (no name info)") + external_devices.append(device) + + # Return external camera first, then integrated as fallback + if external_devices: + self._info_print(f"Using external camera: {external_devices[0]}") + return external_devices[0] + elif integrated_devices: + self._info_print( + "No external camera found - integrated camera available but not preferred" + ) + self._info_print( + "Please connect an external camera (Logitech, Brio, etc.) for recording" + ) + return None + + return None + + def _get_device_name(self, device): + """Get the friendly name of a video device.""" + try: + # Extract device number from /dev/videoX + device_num = device.split("video")[-1] + name_path = f"/sys/class/video4linux/video{device_num}/name" + if os.path.exists(name_path): + with open(name_path, "r") as f: + return f.read().strip() + except Exception: + pass + return None + + def _is_video_capture_device(self, device): + """Check if a device is a video capture device (not metadata).""" + try: + # Try v4l2-ctl first if available + if subprocess.run(["which", "v4l2-ctl"], capture_output=True).returncode == 0: + result = subprocess.run( + ["v4l2-ctl", "--device=" + device, "--info"], capture_output=True, timeout=2 + ) + if result.returncode == 0: + output = result.stdout.decode() + # Look for "Video Capture" capability in Device Caps, not just general Capabilities + lines = output.split("\n") + in_device_caps = False + for line in lines: + if "Device Caps" in line: + in_device_caps = True + continue + if in_device_caps: + if line.strip().startswith("Video Capture"): + # Double-check with ffmpeg + ffmpeg_result = subprocess.run( + [ + "ffmpeg", + "-f", + "v4l2", + "-i", + device, + "-frames:v", + "1", + "-f", + "null", + "-", + ], + capture_output=True, + timeout=2, + ) + return ffmpeg_result.returncode == 0 + # Stop checking if we hit another section + elif line.strip() and not line.startswith("\t"): + break + + # Fallback: try ffmpeg directly if v4l2-ctl not available + self._debug_print(f"Testing {device} with ffmpeg...") + ffmpeg_result = subprocess.run( + [ + "ffmpeg", + "-f", + "v4l2", + "-i", + device, + "-frames:v", + "1", + "-f", + "null", + "-", + ], + capture_output=True, + timeout=5, + ) + if ffmpeg_result.returncode == 0: + self._debug_print(f"{device} is a working video capture device") + return True + else: + stderr_output = ffmpeg_result.stderr.decode() + # Check if it's just a metadata device + if ( + "metadata" in stderr_output.lower() + or "not a capture device" in stderr_output.lower() + ): + self._debug_print(f"{device} is metadata device, skipping") + return False + else: + self._debug_print(f"{device} failed ffmpeg test: {stderr_output[:100]}") + return False + except Exception as e: + self._debug_print(f"Error testing {device}: {e}") + pass + return False + + def test_camera_format(self, device): + """Test camera and determine best format.""" + # Try default format + result = subprocess.run( + ["ffmpeg", "-f", "v4l2", "-i", device, "-frames:v", "1", "-f", "null", "-"], + capture_output=True, + ) + if result.returncode == 0: + return [] # Default format works + + # Try MJPEG format + result = subprocess.run( + [ + "ffmpeg", + "-f", + "v4l2", + "-input_format", + "mjpeg", + "-i", + device, + "-frames:v", + "1", + "-f", + "null", + "-", + ], + capture_output=True, + ) + if result.returncode == 0: + return ["-input_format", "mjpeg"] + + raise RuntimeError(f"Cannot access camera at {device}") + + def record(self, output_dir="./logs_experiment", preview=True): + """Start recording from webcam.""" + # Find webcam + device = self.find_webcam() + if not device: + self._info_print("No webcam found") + return False + + self._info_print(f"Recording from: {device}") + + # Test camera format + try: + format_args = self.test_camera_format(device) + except RuntimeError as e: + self._info_print(str(e)) + return False + + # Create output directory with date subfolder and filename + now = datetime.now() + date_folder = now.strftime("%Y_%m_%d") + output_path = Path(output_dir) / date_folder + output_path.mkdir(parents=True, exist_ok=True) + timestamp = now.strftime("%Y_%m_%d_%H_%M_%S") + output_file = output_path / f"robot_video_{timestamp}.mp4" + + self._info_print(f"Saving to: {output_file}") + if self.debug: + self._debug_print(f"Absolute path: {output_file.absolute()}") + + # Check if preview is possible + if preview and not os.environ.get("DISPLAY"): + self._debug_print("No DISPLAY found, disabling preview") + preview = False + + # Build ffmpeg command + cmd = ( + ["ffmpeg", "-loglevel", "error", "-f", "v4l2"] + + format_args + + ["-i", device, "-c:v", "libx264", "-preset", "ultrafast"] + ) + + if preview: + # Try with preview first + preview_cmd = cmd + ["-f", "tee", "-map", "0:v", f"[f=mp4]{output_file}|[f=nut]pipe:"] + + try: + ffmpeg_proc = subprocess.Popen( + preview_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL + ) + ffplay_proc = subprocess.Popen( + [ + "ffplay", + "-loglevel", + "quiet", + "-f", + "nut", + "-i", + "pipe:", + "-window_title", + "Webcam Preview", + ], + stdin=ffmpeg_proc.stdout, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + # Wait a bit to see if it starts successfully + time.sleep(0.5) + if ffmpeg_proc.poll() is None and ffplay_proc.poll() is None: + self.process = ffplay_proc # Kill ffplay to stop both + self._info_print("Recording with preview started") + return True + else: + self._debug_print("Preview failed, falling back to no-preview mode") + # Clean up failed processes + try: + ffmpeg_proc.kill() + ffplay_proc.kill() + except Exception: + pass + except Exception as e: + self._debug_print(f"Preview error: {e}, using no-preview mode") + + # Record without preview + cmd.append(str(output_file)) + self.process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + + # Verify it's running + time.sleep(0.5) + if self.process.poll() is None: + self._info_print("Recording started (no preview)") + return True + else: + stderr = self.process.stderr.read().decode() if self.process.stderr else "" + self._info_print(f"Failed to start recording: {stderr}") + return False + + def stop(self): + """Stop recording.""" + if self.process: + self.process.terminate() + try: + self.process.wait(timeout=5) + except subprocess.TimeoutExpired: + self.process.kill() + self._info_print("Recording stopped") + self.process = None + + +def main(): + parser = argparse.ArgumentParser(description="Simple webcam recorder") + parser.add_argument( + "--output-dir", default="./logs_experiment", help="Output directory for recordings" + ) + parser.add_argument("--no-preview", action="store_true", help="Disable preview window") + parser.add_argument("--test", action="store_true", help="Enable debug output") + args = parser.parse_args() + + recorder = WebcamRecorder(debug=args.test) + + # Set up signal handlers for clean shutdown + def signal_handler(signum, frame): + print("\nStopping recording...", file=sys.stderr) + recorder.stop() + sys.exit(0) + + signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) + + # Start recording + if recorder.record(args.output_dir, preview=not args.no_preview): + print("Press Ctrl+C to stop recording", file=sys.stderr) + # Keep running until interrupted + try: + signal.pause() + except KeyboardInterrupt: + pass + else: + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/.gitattributes b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..c94badc6679d5e0d0f3d067543d6aa329df62b89 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/.gitattributes @@ -0,0 +1 @@ +*.stl filter=lfs diff=lfs merge=lfs -text diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/.gitignore b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c01bd8c24797ba34341797d59e804c99da7016a8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/.gitignore @@ -0,0 +1 @@ +*/__pycache__/ diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/README.md b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/README.md new file mode 100644 index 0000000000000000000000000000000000000000..588b2a4f5eac2567b6bbe2b749510d4076ba283b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/README.md @@ -0,0 +1,5 @@ +urdf to mjcf: +``` +pip install urdf2mjcf +urdf2mjcf path_to_urdf +``` \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/requirements.txt b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..40bc58afbb3313013234e3d845fbfd3c3d2dd728 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/requirements.txt @@ -0,0 +1,8 @@ +mujoco==3.3.4 +matplotlib==3.10.3 +numpy==2.2.6 +trimesh +ipdb +open3d +onnxruntime +keyboard \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/README.md b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6fe48cea75d8dbec798e07457693601205ab9f13 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/README.md @@ -0,0 +1,30 @@ +# Unitree G1 Description (URDF & MJCF) + +## Overview + +This package includes a universal humanoid robot description (URDF & MJCF) for the [Unitree G1](https://www.unitree.com/g1/), developed by [Unitree Robotics](https://www.unitree.com/). + +MJCF/URDF for the G1 robot: + +| MJCF/URDF file name | `mode_machine` | Hip roll reduction ratio | Update status | dof#leg | dof#waist | dof#arm | dof#hand | +| ----------------------------- | :------------: | :----------------------: | ------------- | :-----: | :-------: | :-----: | :------: | +| `g1_23dof` | 1 | 14.5 | Beta | 6*2 | 1 | 5*2 | 0 | +| `g1_29dof` | 2 | 14.5 | Beta | 6*2 | 3 | 7*2 | 0 | +| `g1_29dof_with_hand` | 2 | 14.5 | Beta | 6*2 | 3 | 7*2 | 7*2 | +| `g1_29dof_lock_waist` | 3 | 14.5 | Beta | 6*2 | 1 | 7*2 | 0 | +| `g1_23dof_rev_1_0` | 4 | 22.5 | Up-to-date | 6*2 | 1 | 5*2 | 0 | +| `g1_29dof_rev_1_0` | 5 | 22.5 | Up-to-date | 6*2 | 3 | 7*2 | 0 | +| `g1_29dof_with_hand_rev_1_0` | 5 | 22.5 | Up-to-date | 6*2 | 3 | 7*2 | 7*2 | +| `g1_29dof_lock_waist_rev_1_0` | 6 | 22.5 | Up-to-date | 6*2 | 1 | 7*2 | 0 | +| `g1_dual_arm` | 9 | null | Up-to-date | 0 | 0 | 7*2 | 0 | + +## Visulization with [MuJoCo](https://github.com/google-deepmind/mujoco) + +1. Open MuJoCo Viewer + + ```bash + pip install mujoco + python -m mujoco.viewer + ``` + +2. Drag and drop the MJCF/URDF model file (`g1_XXX.xml`/`g1_XXX.urdf`) to the MuJoCo Viewer. diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.urdf b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.urdf new file mode 100644 index 0000000000000000000000000000000000000000..aae5441336316faae7865ec4de514129317b9eeb --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.urdf @@ -0,0 +1,1262 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.xml new file mode 100644 index 0000000000000000000000000000000000000000..0e6fd214fb058887fb247c3eb70c5bba952ac29f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.xml @@ -0,0 +1,429 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.yaml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4a5d5cb26553747ddaf92eaa3eacf656f1f3e5f2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1.yaml @@ -0,0 +1,34 @@ +# Policy and model paths +policy_path: "policy/deploy.onnx" +xml_path: "g1.xml" + +# Simulation parameters +simulation_duration: 1000.0 +simulation_dt: 0.002 +control_decimation: 10 + +# PD gains +# PD gains +kps: [150, 150, 150, 200, 40, 40, + 150, 150, 150, 200, 40, 40] +kds: [2.0, 2.0, 2.0, 4.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 4.0, 2.0, 2.0] + +# Default joint angles for legs +default_angles: [-0.1, 0.0, 0.0, 0.3, -0.2, 0.0, + -0.1, 0.0, 0.0, 0.3, -0.2, 0.0] +# Scaling factors +ang_vel_scale: 0.25 +dof_pos_scale: 1.0 +dof_vel_scale: 0.05 +action_scale: 0.25 +cmd_scale: [2.0, 2.0, 0.25] + +# Number of actions and observations +num_actions: 12 +num_obs: 456 # 76 * 6 (observation dimension * history length) +obs_history_len: 6 + +# Initial commands +cmd_init: [0.0, 0.0, 0.0] +height_cmd: 0.74 \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1_gear_wbc.xml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1_gear_wbc.xml new file mode 100644 index 0000000000000000000000000000000000000000..b5879a3c400eead549758283b00dbc9da46e414d --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1_gear_wbc.xml @@ -0,0 +1,415 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1_gear_wbc.yaml b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1_gear_wbc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d629c837a57cf80364311b4469f1a348d5e09313 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/g1_gear_wbc.yaml @@ -0,0 +1,40 @@ +# Policy and model paths +policy_path: "policy/ft92.onnx" #best ft 49 71? 75 +walk_policy_path: "policy/ft109.onnx" #best ft 49 71? 75 +xml_path: "g1_gear_wbc.xml" + +# Simulation parameters +simulation_duration: 1000.0 +simulation_dt: 0.005 +control_decimation: 4 + +# PD gains +# PD gains +kps: [150, 150, 150, 200, 40, 40, + 150, 150, 150, 200, 40, 40, + 250.0, 250.0, 250.0] +kds: [2.0, 2.0, 2.0, 4.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 4.0, 2.0, 2.0, + 5.0, 5.0, 5.0] + +# Default joint angles for legs +default_angles: [-0.1, 0.0, 0.0, 0.3, -0.2, 0.0, + -0.1, 0.0, 0.0, 0.3, -0.2, 0.0, + 0.0, 0.0, 0.0] +# Scaling factors +ang_vel_scale: 0.5 +dof_pos_scale: 1.0 +dof_vel_scale: 0.05 +action_scale: 0.25 +cmd_scale: [2.0, 2.0, 0.5] + +# Number of actions and observations +num_actions: 15 +num_obs: 516 # 516 # 76 * 6 (observation dimension * history length) +obs_history_len: 6 + +# Initial commands +cmd_init: [0.0, 0.0, 0.0] +height_cmd: 0.74 +rpy_cmd: [0.0, 0.0, 0.0] +freq_cmd: 0.75 \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/policy/NVIDIA Open Model License b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/policy/NVIDIA Open Model License new file mode 100644 index 0000000000000000000000000000000000000000..0fd2c70949deb2f1d9094e98185b75ab10c60fa4 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/resources/robots/g1/policy/NVIDIA Open Model License @@ -0,0 +1,62 @@ +NVIDIA Open Model License Agreement + +Last Modified: October 24, 2025 + +This NVIDIA Open Model License Agreement (the “Agreement”) is a legal agreement between the Legal Entity You represent, or if no entity is identified, You and NVIDIA Corporation and its Affiliates (“NVIDIA”) and governs Your use of the Models that NVIDIA provides to You under this Agreement. NVIDIA and You are each a “party” and collectively the “parties.” + +NVIDIA models released under this Agreement are intended to be used permissively and enable the further development of AI technologies. Subject to the terms of this Agreement, NVIDIA confirms that: + +Models are commercially usable. +You are free to create and distribute Derivative Models. +NVIDIA does not claim ownership to any outputs generated using the Models or Derivative Models. +By using, reproducing, modifying, distributing, performing or displaying any portion or element of the Model or Derivative Model, or otherwise accepting the terms of this Agreement, you agree to be bound by this Agreement. + +Definitions. The following definitions apply to this Agreement: + +"Derivative Model" means all (a) modifications to the Model, (b) works based on the Model, and (c) any other derivative works of the Model. An output is not a Derivative Model. + +"Legal Entity" means the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of fifty percent (50%) or more of the outstanding shares, or (c) beneficial ownership of such entity. + +“Model” means the machine learning model, software, checkpoints, learnt weights, algorithms, parameters, configuration files and documentation shared under this Agreement. + +"NVIDIA Cosmos Model" means a multimodal Model shared under this Agreement + +"Special-Purpose Model" means a Model that is only competent in a narrow set of purpose-specific tasks and should not be used for unintended or general-purpose applications + +“You” or “Your” means an individual or Legal Entity exercising permissions granted by this Agreement. + +Conditions for Use, License Grant, AI Ethics and IP Ownership. + +Conditions for Use. The Model and any Derivative Model are subject to additional terms as described in Section 2 and Section 3 of this Agreement and govern Your use. If You institute copyright or patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model or a Derivative Model constitutes direct or contributory copyright or patent infringement, then any licenses granted to You under this Agreement for that Model or Derivative Model will terminate as of the date such litigation is filed. If You bypass, disable, reduce the efficacy of, or circumvent any technical limitation, safety guardrail or associated safety guardrail hyperparameter, encryption, security, digital rights management, or authentication mechanism (collectively “Guardrail”) contained in the Model without a substantially similar Guardrail appropriate for your use case, your rights under this Agreement will automatically terminate. NVIDIA may indicate in relevant documentation that a Model is a Special-Purpose Model. NVIDIA may update this Agreement to comply with legal and regulatory requirements at any time and You agree to either comply with any updated license or cease Your copying, use, and distribution of the Model and any Derivative Model. + +License Grant. The rights granted herein are explicitly conditioned on Your full compliance with the terms of this Agreement. Subject to the terms and conditions of this Agreement, NVIDIA hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, revocable (as stated in Section 2.1) license to publicly perform, publicly display, reproduce, use, create derivative works of, make, have made, sell, offer for sale, distribute (through multiple tiers of distribution) and import the Model. + +AI Ethics. Use of the Models under the Agreement must be consistent with NVIDIA’s Trustworthy AI terms found at https://www.nvidia.com/en-us/agreements/trustworthy-ai/terms/. + +NVIDIA owns the Model and any Derivative Models created by NVIDIA. Subject to NVIDIA’s underlying ownership rights in the Model or its Derivative Models, You are and will be the owner of Your Derivative Models. NVIDIA claims no ownership rights in outputs. You are responsible for outputs and their subsequent uses. Except as expressly granted in this Agreement, (a) NVIDIA reserves all rights, interests and remedies in connection with the Model and (b) no other license or right is granted to you by implication, estoppel or otherwise. + +Redistribution. You may reproduce and distribute copies of the Model or Derivative Models thereof in any medium, with or without modifications, provided that You meet the following conditions: + +If you distribute the Model, You must give any other recipients of the Model a copy of this Agreement and include the following attribution notice within a “Notice” text file with such copies: “Licensed by NVIDIA Corporation under the NVIDIA Open Model License”; + +If you distribute or make available a NVIDIA Cosmos Model, or a product or service (including an AI model) that contains or uses a NVIDIA Cosmos Model, use a NVIDIA Cosmos Model to create a Derivative Model, or use a NVIDIA Cosmos Model or its outputs to create, train, fine tune, or otherwise improve an AI model, you will include “Built on NVIDIA Cosmos” on a related website, user interface, blogpost, about page, or product documentation; and + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Models as a whole, provided Your use, reproduction, and distribution of the Model otherwise complies with the conditions stated in this Agreement. + +Separate Components. The Models may include or be distributed with components provided with separate legal notices or terms that accompany the components, such as an Open Source Software License or other third-party license. The components are subject to the applicable other licenses, including any proprietary notices, disclaimers, requirements and extended use rights; except that this Agreement will prevail regarding the use of third-party Open Source Software License, unless a third-party Open Source Software License requires its license terms to prevail. “Open Source Software License” means any software, data or documentation subject to any license identified as an open source license by the Open Source Initiative (https://opensource.org), Free Software Foundation (https://www.fsf.org) or other similar open source organization or listed by the Software Package Data Exchange (SPDX) Workgroup under the Linux Foundation (https://www.spdx.org). + +Trademarks. This Agreement does not grant permission to use the trade names, trademarks, service marks, or product names of NVIDIA, except as required for reasonable and customary use in describing the origin of the Model and reproducing the content of the “Notice” text file. + +Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, NVIDIA provides the Model on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for reviewing Model documentation, including any Special-Purpose Model limitations, and determining the appropriateness of using or redistributing the Model, Derivative Models and outputs. You assume any risks associated with Your exercise of permissions under this Agreement. + +Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, will NVIDIA be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this Agreement or out of the use or inability to use the Model, Derivative Models or outputs (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if NVIDIA has been advised of the possibility of such damages. + +Indemnity. You will indemnify and hold harmless NVIDIA from and against any claim by any third party arising out of or related to your use or distribution of the Model, Derivative Models or outputs. + +Feedback. NVIDIA appreciates your feedback, and You agree that NVIDIA may use it without restriction or compensation to You. + +Governing Law. This Agreement will be governed in all respects by the laws of the United States and the laws of the State of Delaware, without regard to conflict of laws principles or the United Nations Convention on Contracts for the International Sale of Goods. The state and federal courts residing in Santa Clara County, California will have exclusive jurisdiction over any dispute or claim arising out of or related to this Agreement, and the parties irrevocably consent to personal jurisdiction and venue in those courts; except that, either party may apply for injunctive remedies or an equivalent type of urgent legal relief in any jurisdiction. + +Trade and Compliance. You agree to comply with all applicable export, import, trade and economic sanctions laws and regulations, as amended, including without limitation U.S. Export Administration Regulations and Office of Foreign Assets Control regulations. These laws include restrictions on destinations, end-users and end-use. + +Version Release Date: October 24, 2025 \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/scripts/run_mujoco_gear_wbc.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/scripts/run_mujoco_gear_wbc.py new file mode 100644 index 0000000000000000000000000000000000000000..d3206f5a8200e36c9d24b1dfa3d1f7a4b7ccffe9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/scripts/run_mujoco_gear_wbc.py @@ -0,0 +1,315 @@ +import collections +import os +import threading +import time + +import mujoco +import mujoco.viewer +import numpy as np +import onnxruntime as ort +from pynput import keyboard as pkb +import torch +import yaml + + +class GearWbcController: + def __init__(self, config_path): + self.CONFIG_PATH = config_path + self.cmd_lock = threading.Lock() + self.config = self.load_config(os.path.join(self.CONFIG_PATH, "g1_gear_wbc.yaml")) + + self.control_dict = { + "loco_cmd": self.config["cmd_init"], + "height_cmd": self.config["height_cmd"], + "rpy_cmd": self.config.get("rpy_cmd", [0.0, 0.0, 0.0]), + "freq_cmd": self.config.get("freq_cmd", 1.5), + } + + self.model = mujoco.MjModel.from_xml_path(self.config["xml_path"]) + self.data = mujoco.MjData(self.model) + self.model.opt.timestep = self.config["simulation_dt"] + self.n_joints = self.data.qpos.shape[0] - 7 + self.torso_index = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_BODY, "torso_link") + self.base_index = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_BODY, "pelvis") + self.action = np.zeros(self.config["num_actions"], dtype=np.float32) + self.target_dof_pos = self.config["default_angles"].copy() + self.policy = self.load_onnx_policy(self.config["policy_path"]) + self.walk_policy = self.load_onnx_policy(self.config["walk_policy_path"]) + self.gait_indices = torch.zeros((1), dtype=torch.float32) + self.counter = 0 + self.just_started = 0.0 + self.walking_mask = False + self.frozen_FL = False + self.frozen_FR = False + self.single_obs, self.single_obs_dim = self.compute_observation( + self.data, self.config, self.action, self.control_dict, self.n_joints + ) + self.obs_history = collections.deque( + [np.zeros(self.single_obs_dim, dtype=np.float32)] * self.config["obs_history_len"], + maxlen=self.config["obs_history_len"], + ) + self.obs = np.zeros(self.config["num_obs"], dtype=np.float32) + self.keyboard_listener(self.control_dict, self.config) + + def keyboard_listener(self, control_dict, config): + """Listen to key press events and update cmd and height_cmd""" + + def on_press(key): + try: + k = key.char + except AttributeError: + return # Special keys ignored + + with self.cmd_lock: + if k == "w": + control_dict["loco_cmd"][0] += 0.1 + elif k == "s": + control_dict["loco_cmd"][0] -= 0.1 + elif k == "a": + control_dict["loco_cmd"][1] += 0.1 + elif k == "d": + control_dict["loco_cmd"][1] -= 0.1 + elif k == "q": + control_dict["loco_cmd"][2] += 0.1 + elif k == "e": + control_dict["loco_cmd"][2] -= 0.1 + elif k == "z": + control_dict["loco_cmd"][:] = config["cmd_init"] + control_dict["height_cmd"] = config["height_cmd"] + control_dict["rpy_cmd"][:] = config["rpy_cmd"] + control_dict["freq_cmd"] = config["freq_cmd"] + elif k == "1": + control_dict["height_cmd"] += 0.05 + elif k == "2": + control_dict["height_cmd"] -= 0.05 + elif k == "3": + control_dict["rpy_cmd"][0] += 0.2 + elif k == "4": + control_dict["rpy_cmd"][0] -= 0.2 + elif k == "5": + control_dict["rpy_cmd"][1] += 0.2 + elif k == "6": + control_dict["rpy_cmd"][1] -= 0.2 + elif k == "7": + control_dict["rpy_cmd"][2] += 0.2 + elif k == "8": + control_dict["rpy_cmd"][2] -= 0.2 + elif k == "m": + control_dict["freq_cmd"] += 0.1 + elif k == "n": + control_dict["freq_cmd"] -= 0.1 + + print( + f"Current Commands: loco_cmd = {control_dict['loco_cmd']}, height_cmd = {control_dict['height_cmd']}, rpy_cmd = {control_dict['rpy_cmd']}, freq_cmd = {control_dict['freq_cmd']}" + ) + + listener = pkb.Listener(on_press=on_press) + listener.daemon = True + listener.start() + + def load_config(self, config_path): + with open(config_path, "r") as f: + config = yaml.safe_load(f) + + for path_key in ["policy_path", "xml_path", "walk_policy_path"]: + config[path_key] = os.path.join(CONFIG_PATH, config[path_key]) + + array_keys = ["kps", "kds", "default_angles", "cmd_scale", "cmd_init"] + for key in array_keys: + config[key] = np.array(config[key], dtype=np.float32) + + return config + + def pd_control(self, target_q, q, kp, target_dq, dq, kd): + return (target_q - q) * kp + (target_dq - dq) * kd + + def quat_rotate_inverse(self, q, v): + w, x, y, z = q + q_conj = np.array([w, -x, -y, -z]) + return np.array( + [ + v[0] * (q_conj[0] ** 2 + q_conj[1] ** 2 - q_conj[2] ** 2 - q_conj[3] ** 2) + + v[1] * 2 * (q_conj[1] * q_conj[2] - q_conj[0] * q_conj[3]) + + v[2] * 2 * (q_conj[1] * q_conj[3] + q_conj[0] * q_conj[2]), + v[0] * 2 * (q_conj[1] * q_conj[2] + q_conj[0] * q_conj[3]) + + v[1] * (q_conj[0] ** 2 - q_conj[1] ** 2 + q_conj[2] ** 2 - q_conj[3] ** 2) + + v[2] * 2 * (q_conj[2] * q_conj[3] - q_conj[0] * q_conj[1]), + v[0] * 2 * (q_conj[1] * q_conj[3] - q_conj[0] * q_conj[2]) + + v[1] * 2 * (q_conj[2] * q_conj[3] + q_conj[0] * q_conj[1]) + + v[2] * (q_conj[0] ** 2 - q_conj[1] ** 2 - q_conj[2] ** 2 + q_conj[3] ** 2), + ] + ) + + def get_gravity_orientation(self, quat): + gravity_vec = np.array([0.0, 0.0, -1.0]) + return self.quat_rotate_inverse(quat, gravity_vec) + + def compute_observation(self, d, config, action, control_dict, n_joints): + command = np.zeros(7, dtype=np.float32) + command[:3] = control_dict["loco_cmd"][:3] * config["cmd_scale"] + command[3] = control_dict["height_cmd"] + # command[4] = control_dict['freq_cmd'] + command[4:7] = control_dict["rpy_cmd"] + + # # gait indice + # is_static = np.linalg.norm(command[:3]) < 0.1 + # just_entered_walk = (not is_static) and (not self.walking_mask) + # self.walking_mask = not is_static + + # if just_entered_walk: + # self.just_started = 0.0 + # self.gait_indices = torch.tensor([-0.25]) + # if not is_static: + # self.just_started += 0.02 + # else: + # self.just_started = 0.0 + + # if not is_static: + # self.frozen_FL = False + # self.frozen_FR = False + + # self.gait_indices = torch.remainder(self.gait_indices + 0.02 * command[4], 1.0) + + # # Parameters + # duration = 0.5 + # phase = 0.5 + + # # Gait indices + # gait_FR = self.gait_indices.clone() + # gait_FL = torch.remainder(gait_FR + phase, 1.0) + + # if self.just_started < (0.5 / command[4]): + # gait_FR = torch.tensor([0.25]) + # gait_pair = [gait_FL.clone(), gait_FR.clone()] + + # for i, fi in enumerate(gait_pair): + # if fi.item() < duration: + # gait_pair[i] = fi * (0.5 / duration) + # else: + # gait_pair[i] = 0.5 + (fi - duration) * (0.5 / (1 - duration)) + + # # Clock signal + # clock = [torch.sin(2 * np.pi * fi) for fi in gait_pair] + + # for i, (clk, frozen_mask_attr) in enumerate( + # zip(clock, ['frozen_FL', 'frozen_FR']) + # ): + # frozen_mask = getattr(self, frozen_mask_attr) + # # Freeze condition: static and at sin peak + # if is_static and (not frozen_mask) and clk.item() > 0.98: + # setattr(self, frozen_mask_attr, True) + # clk = torch.tensor([1.0]) + # if getattr(self, frozen_mask_attr): + # clk = torch.tensor([1.0]) + # clock[i] = clk + + # self.clock_inputs = torch.stack(clock).unsqueeze(0) + qj = d.qpos[7 : 7 + n_joints].copy() + dqj = d.qvel[6 : 6 + n_joints].copy() + quat = d.qpos[3:7].copy() + omega = d.qvel[3:6].copy() + # omega = self.data.xmat[self.base_index].reshape(3, 3).T @ self.data.cvel[self.base_index][3:6] + padded_defaults = np.zeros(n_joints, dtype=np.float32) + L = min(len(config["default_angles"]), n_joints) + padded_defaults[:L] = config["default_angles"][:L] + + qj_scaled = (qj - padded_defaults) * config["dof_pos_scale"] + dqj_scaled = dqj * config["dof_vel_scale"] + gravity_orientation = self.get_gravity_orientation(quat) + omega_scaled = omega * config["ang_vel_scale"] + + torso_quat = self.data.xquat[self.torso_index] + torso_omega = ( + self.data.xmat[self.torso_index].reshape(3, 3).T @ self.data.cvel[self.torso_index][3:6] + ) + torso_omega_scaled = torso_omega * config["ang_vel_scale"] + torso_gravity_orientation = self.get_gravity_orientation(torso_quat) + + single_obs_dim = 86 + single_obs = np.zeros(single_obs_dim, dtype=np.float32) + single_obs[0:7] = command[:7] + single_obs[7:10] = omega_scaled + single_obs[10:13] = gravity_orientation + # single_obs[14:17] = 0.#torso_omega_scaled + # single_obs[17:20] = 0.#torso_gravity_orientation + single_obs[13 : 13 + n_joints] = qj_scaled + single_obs[13 + n_joints : 13 + 2 * n_joints] = dqj_scaled + single_obs[13 + 2 * n_joints : 13 + 2 * n_joints + 15] = action + # single_obs[20+2*n_joints+15:20+2*n_joints+15+2] = self.clock_inputs.cpu().numpy().reshape(2) + + return single_obs, single_obs_dim + + def load_onnx_policy(self, path): + model = ort.InferenceSession(path) + + def run_inference(input_tensor): + ort_inputs = {model.get_inputs()[0].name: input_tensor.cpu().numpy()} + ort_outs = model.run(None, ort_inputs) + return torch.tensor(ort_outs[0], device="cuda:0") + + return run_inference + + def run(self): + + self.counter = 0 + + with mujoco.viewer.launch_passive(self.model, self.data) as viewer: + start = time.time() + while viewer.is_running() and time.time() - start < self.config["simulation_duration"]: + step_start = time.time() + + leg_tau = self.pd_control( + self.target_dof_pos, + self.data.qpos[7 : 7 + self.config["num_actions"]], + self.config["kps"], + np.zeros_like(self.config["kps"]), + self.data.qvel[6 : 6 + self.config["num_actions"]], + self.config["kds"], + ) + self.data.ctrl[: self.config["num_actions"]] = leg_tau + + if self.n_joints > self.config["num_actions"]: + arm_tau = self.pd_control( + np.zeros(self.n_joints - self.config["num_actions"], dtype=np.float32), + self.data.qpos[7 + self.config["num_actions"] : 7 + self.n_joints], + np.full(self.n_joints - self.config["num_actions"], 100.0), + np.zeros(self.n_joints - self.config["num_actions"]), + self.data.qvel[6 + self.config["num_actions"] : 6 + self.n_joints], + np.full(self.n_joints - self.config["num_actions"], 0.5), + ) + self.data.ctrl[self.config["num_actions"] :] = arm_tau + + mujoco.mj_step(self.model, self.data) + + self.counter += 1 + if self.counter % self.config["control_decimation"] == 0: + with self.cmd_lock: + current_cmd = self.control_dict + + single_obs, _ = self.compute_observation( + self.data, self.config, self.action, current_cmd, self.n_joints + ) + self.obs_history.append(single_obs) + + for i, hist_obs in enumerate(self.obs_history): + self.obs[i * self.single_obs_dim : (i + 1) * self.single_obs_dim] = hist_obs + + obs_tensor = torch.from_numpy(self.obs).unsqueeze(0) + if (np.linalg.norm(np.array(current_cmd["loco_cmd"]))) <= 0.05: + self.action = self.policy(obs_tensor).cpu().detach().numpy().squeeze() + else: + self.action = self.walk_policy(obs_tensor).cpu().detach().numpy().squeeze() + self.target_dof_pos = ( + self.action * self.config["action_scale"] + self.config["default_angles"] + ) + + viewer.sync() + # time.sleep(max(0, self.model.opt.timestep - (time.time() - step_start))) + + +if __name__ == "__main__": + CONFIG_PATH = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "resources", "robots", "g1" + ) + controller = GearWbcController(CONFIG_PATH) + controller.run() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/scripts/run_mujoco_gear_wbc_gait.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/scripts/run_mujoco_gear_wbc_gait.py new file mode 100644 index 0000000000000000000000000000000000000000..df85a0c858fbb3c46a71c2b190e1fab7ce3e65bd --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/sim2mujoco/scripts/run_mujoco_gear_wbc_gait.py @@ -0,0 +1,311 @@ +import collections +import os +import threading +import time + +import mujoco +import mujoco.viewer +import numpy as np +import onnxruntime as ort +from pynput import keyboard as pkb +import torch +import yaml + + +class GearWbcController: + def __init__(self, config_path): + self.CONFIG_PATH = config_path + self.cmd_lock = threading.Lock() + self.config = self.load_config(os.path.join(self.CONFIG_PATH, "g1_gear_wbc.yaml")) + + self.control_dict = { + "loco_cmd": self.config["cmd_init"], + "height_cmd": self.config["height_cmd"], + "rpy_cmd": self.config.get("rpy_cmd", [0.0, 0.0, 0.0]), + "freq_cmd": self.config.get("freq_cmd", 1.5), + } + + self.model = mujoco.MjModel.from_xml_path(self.config["xml_path"]) + self.data = mujoco.MjData(self.model) + self.model.opt.timestep = self.config["simulation_dt"] + self.n_joints = self.data.qpos.shape[0] - 7 + self.torso_index = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_BODY, "torso_link") + self.base_index = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_BODY, "pelvis") + self.action = np.zeros(self.config["num_actions"], dtype=np.float32) + self.target_dof_pos = self.config["default_angles"].copy() + self.policy = self.load_onnx_policy(self.config["policy_path"]) + self.gait_indices = torch.zeros((1), dtype=torch.float32) + self.counter = 0 + self.just_started = 0.0 + self.walking_mask = False + self.frozen_FL = False + self.frozen_FR = False + self.single_obs, self.single_obs_dim = self.compute_observation( + self.data, self.config, self.action, self.control_dict, self.n_joints + ) + self.obs_history = collections.deque( + [np.zeros(self.single_obs_dim, dtype=np.float32)] * self.config["obs_history_len"], + maxlen=self.config["obs_history_len"], + ) + self.obs = np.zeros(self.config["num_obs"], dtype=np.float32) + self.keyboard_listener(self.control_dict, self.config) + + def keyboard_listener(self, control_dict, config): + """Listen to key press events and update cmd and height_cmd""" + + def on_press(key): + try: + k = key.char + except AttributeError: + return # Special keys ignored + + with self.cmd_lock: + if k == "w": + control_dict["loco_cmd"][0] += 0.2 + elif k == "s": + control_dict["loco_cmd"][0] -= 0.2 + elif k == "a": + control_dict["loco_cmd"][1] += 0.5 + elif k == "d": + control_dict["loco_cmd"][1] -= 0.5 + elif k == "q": + control_dict["loco_cmd"][2] += 0.5 + elif k == "e": + control_dict["loco_cmd"][2] -= 0.5 + elif k == "z": + control_dict["loco_cmd"][:] = config["cmd_init"] + control_dict["height_cmd"] = config["height_cmd"] + control_dict["rpy_cmd"][:] = config["rpy_cmd"] + control_dict["freq_cmd"] = config["freq_cmd"] + elif k == "1": + control_dict["height_cmd"] += 0.05 + elif k == "2": + control_dict["height_cmd"] -= 0.05 + elif k == "3": + control_dict["rpy_cmd"][0] += 0.2 + elif k == "4": + control_dict["rpy_cmd"][0] -= 0.2 + elif k == "5": + control_dict["rpy_cmd"][1] += 0.2 + elif k == "6": + control_dict["rpy_cmd"][1] -= 0.2 + elif k == "7": + control_dict["rpy_cmd"][2] += 0.2 + elif k == "8": + control_dict["rpy_cmd"][2] -= 0.2 + elif k == "m": + control_dict["freq_cmd"] += 0.1 + elif k == "n": + control_dict["freq_cmd"] -= 0.1 + + print( + f"Current Commands: loco_cmd = {control_dict['loco_cmd']}, height_cmd = {control_dict['height_cmd']}, rpy_cmd = {control_dict['rpy_cmd']}, freq_cmd = {control_dict['freq_cmd']}" + ) + + listener = pkb.Listener(on_press=on_press) + listener.daemon = True + listener.start() + + def load_config(self, config_path): + with open(config_path, "r") as f: + config = yaml.safe_load(f) + + for path_key in ["policy_path", "xml_path"]: + config[path_key] = os.path.join(CONFIG_PATH, config[path_key]) + + array_keys = ["kps", "kds", "default_angles", "cmd_scale", "cmd_init"] + for key in array_keys: + config[key] = np.array(config[key], dtype=np.float32) + + return config + + def pd_control(self, target_q, q, kp, target_dq, dq, kd): + return (target_q - q) * kp + (target_dq - dq) * kd + + def quat_rotate_inverse(self, q, v): + w, x, y, z = q + q_conj = np.array([w, -x, -y, -z]) + return np.array( + [ + v[0] * (q_conj[0] ** 2 + q_conj[1] ** 2 - q_conj[2] ** 2 - q_conj[3] ** 2) + + v[1] * 2 * (q_conj[1] * q_conj[2] - q_conj[0] * q_conj[3]) + + v[2] * 2 * (q_conj[1] * q_conj[3] + q_conj[0] * q_conj[2]), + v[0] * 2 * (q_conj[1] * q_conj[2] + q_conj[0] * q_conj[3]) + + v[1] * (q_conj[0] ** 2 - q_conj[1] ** 2 + q_conj[2] ** 2 - q_conj[3] ** 2) + + v[2] * 2 * (q_conj[2] * q_conj[3] - q_conj[0] * q_conj[1]), + v[0] * 2 * (q_conj[1] * q_conj[3] - q_conj[0] * q_conj[2]) + + v[1] * 2 * (q_conj[2] * q_conj[3] + q_conj[0] * q_conj[1]) + + v[2] * (q_conj[0] ** 2 - q_conj[1] ** 2 - q_conj[2] ** 2 + q_conj[3] ** 2), + ] + ) + + def get_gravity_orientation(self, quat): + gravity_vec = np.array([0.0, 0.0, -1.0]) + return self.quat_rotate_inverse(quat, gravity_vec) + + def compute_observation(self, d, config, action, control_dict, n_joints): + command = np.zeros(8, dtype=np.float32) + command[:3] = control_dict["loco_cmd"][:3] * config["cmd_scale"] + command[3] = control_dict["height_cmd"] + command[4] = control_dict["freq_cmd"] + command[5:8] = control_dict["rpy_cmd"] + + # gait indice + is_static = np.linalg.norm(command[:3]) < 0.1 + just_entered_walk = (not is_static) and (not self.walking_mask) + self.walking_mask = not is_static + + if just_entered_walk: + self.just_started = 0.0 + self.gait_indices = torch.tensor([-0.25]) + if not is_static: + self.just_started += 0.02 + else: + self.just_started = 0.0 + + if not is_static: + self.frozen_FL = False + self.frozen_FR = False + + self.gait_indices = torch.remainder(self.gait_indices + 0.02 * command[4], 1.0) + + # Parameters + duration = 0.5 + phase = 0.5 + + # Gait indices + gait_FR = self.gait_indices.clone() + gait_FL = torch.remainder(gait_FR + phase, 1.0) + + if self.just_started < (0.5 / command[4]): + gait_FR = torch.tensor([0.25]) + gait_pair = [gait_FL.clone(), gait_FR.clone()] + + for i, fi in enumerate(gait_pair): + if fi.item() < duration: + gait_pair[i] = fi * (0.5 / duration) + else: + gait_pair[i] = 0.5 + (fi - duration) * (0.5 / (1 - duration)) + + # Clock signal + clock = [torch.sin(2 * np.pi * fi) for fi in gait_pair] + + for i, (clk, frozen_mask_attr) in enumerate(zip(clock, ["frozen_FL", "frozen_FR"])): + frozen_mask = getattr(self, frozen_mask_attr) + # Freeze condition: static and at sin peak + if is_static and (not frozen_mask) and clk.item() > 0.98: + setattr(self, frozen_mask_attr, True) + clk = torch.tensor([1.0]) + if getattr(self, frozen_mask_attr): + clk = torch.tensor([1.0]) + clock[i] = clk + + self.clock_inputs = torch.stack(clock).unsqueeze(0) + qj = d.qpos[7 : 7 + n_joints].copy() + dqj = d.qvel[6 : 6 + n_joints].copy() + quat = d.qpos[3:7].copy() + omega = d.qvel[3:6].copy() + # omega = self.data.xmat[self.base_index].reshape(3, 3).T @ self.data.cvel[self.base_index][3:6] + padded_defaults = np.zeros(n_joints, dtype=np.float32) + L = min(len(config["default_angles"]), n_joints) + padded_defaults[:L] = config["default_angles"][:L] + + qj_scaled = (qj - padded_defaults) * config["dof_pos_scale"] + dqj_scaled = dqj * config["dof_vel_scale"] + gravity_orientation = self.get_gravity_orientation(quat) + omega_scaled = omega * config["ang_vel_scale"] + + torso_quat = self.data.xquat[self.torso_index] + torso_omega = ( + self.data.xmat[self.torso_index].reshape(3, 3).T @ self.data.cvel[self.torso_index][3:6] + ) + torso_omega_scaled = torso_omega * config["ang_vel_scale"] + torso_gravity_orientation = self.get_gravity_orientation(torso_quat) + + single_obs_dim = 95 + single_obs = np.zeros(single_obs_dim, dtype=np.float32) + single_obs[0:8] = command[:8] + single_obs[8:11] = omega_scaled + single_obs[11:14] = gravity_orientation + single_obs[14:17] = 0.0 # torso_omega_scaled + single_obs[17:20] = 0.0 # torso_gravity_orientation + single_obs[20 : 20 + n_joints] = qj_scaled + single_obs[20 + n_joints : 20 + 2 * n_joints] = dqj_scaled + single_obs[20 + 2 * n_joints : 20 + 2 * n_joints + 15] = action + single_obs[20 + 2 * n_joints + 15 : 20 + 2 * n_joints + 15 + 2] = ( + self.clock_inputs.cpu().numpy().reshape(2) + ) + + return single_obs, single_obs_dim + + def load_onnx_policy(self, path): + model = ort.InferenceSession(path) + + def run_inference(input_tensor): + ort_inputs = {model.get_inputs()[0].name: input_tensor.cpu().numpy()} + ort_outs = model.run(None, ort_inputs) + return torch.tensor(ort_outs[0], device="cuda:0") + + return run_inference + + def run(self): + + self.counter = 0 + + with mujoco.viewer.launch_passive(self.model, self.data) as viewer: + start = time.time() + while viewer.is_running() and time.time() - start < self.config["simulation_duration"]: + step_start = time.time() + + leg_tau = self.pd_control( + self.target_dof_pos, + self.data.qpos[7 : 7 + self.config["num_actions"]], + self.config["kps"], + np.zeros_like(self.config["kps"]), + self.data.qvel[6 : 6 + self.config["num_actions"]], + self.config["kds"], + ) + self.data.ctrl[: self.config["num_actions"]] = leg_tau + + if self.n_joints > self.config["num_actions"]: + arm_tau = self.pd_control( + np.zeros(self.n_joints - self.config["num_actions"], dtype=np.float32), + self.data.qpos[7 + self.config["num_actions"] : 7 + self.n_joints], + np.full(self.n_joints - self.config["num_actions"], 100.0), + np.zeros(self.n_joints - self.config["num_actions"]), + self.data.qvel[6 + self.config["num_actions"] : 6 + self.n_joints], + np.full(self.n_joints - self.config["num_actions"], 0.5), + ) + self.data.ctrl[self.config["num_actions"] :] = arm_tau + + mujoco.mj_step(self.model, self.data) + + self.counter += 1 + if self.counter % self.config["control_decimation"] == 0: + with self.cmd_lock: + current_cmd = self.control_dict + + single_obs, _ = self.compute_observation( + self.data, self.config, self.action, current_cmd, self.n_joints + ) + self.obs_history.append(single_obs) + + for i, hist_obs in enumerate(self.obs_history): + self.obs[i * self.single_obs_dim : (i + 1) * self.single_obs_dim] = hist_obs + + obs_tensor = torch.from_numpy(self.obs).unsqueeze(0) + self.action = self.policy(obs_tensor).cpu().detach().numpy().squeeze() + self.target_dof_pos = ( + self.action * self.config["action_scale"] + self.config["default_angles"] + ) + + viewer.sync() + # time.sleep(max(0, self.model.opt.timestep - (time.time() - step_start))) + + +if __name__ == "__main__": + CONFIG_PATH = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "resources", "robots", "g1" + ) + controller = GearWbcController(CONFIG_PATH) + controller.run() diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/conftest.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..d614373289a85f3d006369b3da67029e71d8cc3b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/conftest.py @@ -0,0 +1,15 @@ +import pytest + + +def pytest_addoption(parser): + parser.addoption( + "--tensorboard-log-dir", + action="store", + default="logs/Gr00t_TRL_loco/.tensorboard", + help="Directory containing tensorboard logs", + ) + + +@pytest.fixture +def tensorboard_log_dir(request): + return request.config.getoption("--tensorboard-log-dir") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/teleop/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/teleop/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/teleop/test_g1_control_loop.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/teleop/test_g1_control_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..15ab9c42416cb500e0140901df6c220e84e714e2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/teleop/test_g1_control_loop.py @@ -0,0 +1,469 @@ +import argparse +import os +from pathlib import Path +import signal +import subprocess +import threading +import time + +import numpy as np +import pytest +import rclpy +from scipy.spatial.transform import Rotation as R +from std_msgs.msg import String as RosStringMsg + +from decoupled_wbc.control.main.constants import ( + CONTROL_GOAL_TOPIC, + KEYBOARD_INPUT_TOPIC, + STATE_TOPIC_NAME, +) +from decoupled_wbc.control.utils.ros_utils import ROSMsgPublisher, ROSMsgSubscriber +from decoupled_wbc.control.utils.term_color_constants import GREEN_BOLD, RESET, YELLOW_BOLD +from decoupled_wbc.data.viz.rerun_viz import RerunViz + + +class KeyboardPublisher: + def __init__(self, topic_name: str = KEYBOARD_INPUT_TOPIC): + assert rclpy.ok(), "Expected ROS2 to be initialized in this process..." + executor = rclpy.get_global_executor() + self.node = executor.get_nodes()[0] + self.publisher = self.node.create_publisher(RosStringMsg, topic_name, 1) + + def publish(self, key: str): + msg = RosStringMsg() + msg.data = key + self.publisher.publish(msg) + + +def is_robot_fallen_from_quat(mujoco_quat): + # Convert MuJoCo [w, x, y, z] → SciPy [x, y, z, w] + w, x, y, z = mujoco_quat + scipy_quat = [x, y, z, w] + + r = R.from_quat(scipy_quat) + roll, pitch, _ = r.as_euler("xyz", degrees=False) + + MAX_ROLL_PITCH = np.radians(60) + print(f"[Fall Check] roll={roll:.3f} rad, pitch={pitch:.3f} rad") + return abs(roll) > MAX_ROLL_PITCH or abs(pitch) > MAX_ROLL_PITCH + + +class LocomotionRunner: + def __init__(self, test_mode: str = "squat"): + self.test_mode = test_mode + if not rclpy.ok(): + rclpy.init(args=None) + self.node = rclpy.create_node(f"EvalDriver_{test_mode}_{int(time.time())}") + + # gracefully shutdown the spin thread when the test is done + self._stop_event = threading.Event() + + self.spin_thread = threading.Thread(target=self._spin_loop, daemon=False) + self.spin_thread.start() + + self.keyboard_event_publisher = KeyboardPublisher(KEYBOARD_INPUT_TOPIC) + self.control_publisher = ROSMsgPublisher(CONTROL_GOAL_TOPIC) + self.state_subscriber = ROSMsgSubscriber(STATE_TOPIC_NAME) + print(f"{test_mode} test initialized...") + + def _spin_loop(self): + try: + while rclpy.ok() and not self._stop_event.is_set(): + rclpy.spin_once(self.node) + except rclpy.executors.ExternalShutdownException: + print("[INFO] Spin thread exiting due to shutdown.") + finally: + print("spin loop stopped...") + + def warm_up(self): + """Stabilize and release the robot.""" + print("waiting for 2 seconds...") + time.sleep(2) + print(f"running {self.test_mode} test...") + self.activate() + print("activated...") + time.sleep(1) + self.release() + print("released...") + time.sleep(5) + + def _run_walk_test(self): + self.walk_forward() # speed up to 0.2 m/s + time.sleep(1) + self.walk_forward() # speed up to 0.4 m/s + + rate = self.node.create_rate(0.5) + start_time = time.time() + while rclpy.ok() and (time.time() - start_time) < 10.0: + obs = self.state_subscriber.get_msg() + + if is_robot_fallen_from_quat(obs["torso_quat"]): + print("robot fallen...") + return 0 + elif self._check_success_condition(obs): + print(f"robot reaching target ({self.test_mode})...") + return 1, {} + else: + rate.sleep() + + print("test timed out after 10 seconds...") + return 0, {} + + def _run_squat_test(self): + rate = self.node.create_rate(0.5) + start_time = time.time() + while rclpy.ok() and (time.time() - start_time) < 10.0: + obs = self.state_subscriber.get_msg() + + if is_robot_fallen_from_quat(obs["torso_quat"]): + print("robot fallen...") + return 0, {} + elif self._check_success_condition(obs): + print(f"robot reaching target ({self.test_mode})...") + return 1, {} + else: + self.go_down() + rate.sleep() + + print("test timed out after 10 seconds...") + return 0, {} + + def cmd_to_velocity(self, cmd_list): + cmd_to_velocity = { + "w": np.array([0.2, 0.0, 0.0]), + "s": np.array([-0.2, 0.0, 0.0]), + "q": np.array([0.0, 0.2, 0.0]), + "e": np.array([0.0, -0.2, 0.0]), + "z": np.array([0.0, 0.0, 0.0]), + } + + accumulated_velocity = np.array([0.0, 0.0, 0.0]) + velocity_list = [] + for cmd in cmd_list: + if cmd == "z": + accumulated_velocity = [0.0, 0.0, 0.0] + elif cmd in ["CHECK", "SKIP"]: + accumulated_velocity = velocity_list[-1] + else: + accumulated_velocity += cmd_to_velocity[cmd] + velocity_list.append(accumulated_velocity.copy()) + + return velocity_list + + def _run_stop_test(self): + base_vel_thres = 0.25 + + cmd_list = ( + ["w", "w", "w", "w", "s", "s", "s", "z", "SKIP", "CHECK"] + + ["s", "s", "q", "w", "w", "w", "e", "s", "s", "z", "SKIP", "CHECK"] + + ["q", "q", "w", "q", "e", "s", "s", "e", "w", "z", "SKIP", "CHECK"] + + ["w", "w", "w", "w", "w", "s", "s", "s", "s", "z", "SKIP", "CHECK"] + ) + + success_flag = 1 + + statistics = { + "floating_base_pose": {"state": []}, + "floating_base_vel": {"state": [], "cmd": []}, + "timestamp": [], + } + for cmd in cmd_list: + self.keyboard_event_publisher.publish(cmd) + time.sleep(0.5) + obs = self.state_subscriber.get_msg() + statistics["floating_base_pose"]["state"].append( + np.linalg.norm(obs["floating_base_pose"]) + ) + statistics["floating_base_vel"]["state"].append( + np.linalg.norm(obs["floating_base_vel"]) + ) + statistics["timestamp"].append(time.time()) + + if cmd == "CHECK" and np.linalg.norm(obs["floating_base_vel"]) > base_vel_thres: + print( + f" [{YELLOW_BOLD}WARNING{RESET}] robot is not stopped fully. " + f"Current base velocity: {np.linalg.norm(obs['floating_base_vel']):.3f} > {base_vel_thres:.3f}" + ) + # success_flag = 0 # robot is not stopped + + time.sleep(0.5) + + vel_cmd = self.cmd_to_velocity(cmd_list) + vel_cmd = [np.linalg.norm(v) for v in vel_cmd] + statistics["floating_base_vel"]["cmd"] = vel_cmd + return success_flag, statistics + + def _run_eef_track_test(self): + from decoupled_wbc.control.policy.lerobot_replay_policy import LerobotReplayPolicy + + parquet_path = ( + Path(__file__).parent.parent.parent.parent / "replay_data" / "g1_pnpbottle.parquet" + ) + replay_policy = LerobotReplayPolicy(parquet_path=str(parquet_path)) + + freq = 50 + rate = self.node.create_rate(freq) + + statistics = { + # "floating_base_pose": {"state": [], "cmd": []}, + "eef_base_pose": {"state": [], "cmd": []}, + "timestamp": [], + } + + for ii in range(500): + action = replay_policy.get_action() + action = replay_policy.action_to_cmd(action) + action["timestamp"] = time.monotonic() + action["target_time"] = time.monotonic() + ii / freq + self.control_publisher.publish(action) + obs = self.state_subscriber.get_msg() + if obs is None: + print("no obs...") + continue + gt_obs = replay_policy.get_observation() + + # statistics["floating_base_pose"]["state"].append(obs["floating_base_pose"]) + # statistics["floating_base_pose"]["cmd"].append(np.zeros_like(obs["floating_base_pose"])) + statistics["eef_base_pose"]["state"].append(obs["wrist_pose"]) + statistics["eef_base_pose"]["cmd"].append(gt_obs["wrist_pose"]) + statistics["timestamp"].append(time.time()) + + pos_err = np.linalg.norm(obs["wrist_pose"][:3] - gt_obs["wrist_pose"][:3]) + if pos_err > 1e-1: + print( + f" [{YELLOW_BOLD}WARNING{RESET}] robot failed to track the eef, " + f"error: {pos_err:.3f} ({self.test_mode})..." + ) + return 0, statistics + + if is_robot_fallen_from_quat(obs["torso_quat"]): + print("robot fallen...") + return 0, statistics + else: + rate.sleep() + + return 1, statistics + + def run(self): + self.warm_up() + + test_mode_to_func = { + "squat": self._run_squat_test, + "walk": self._run_walk_test, + "stop": self._run_stop_test, + "eef_track": self._run_eef_track_test, + } + + result, statistics = test_mode_to_func[self.test_mode]() + + self.post_process(statistics) + return result + + def _check_success_condition(self, obs): + if self.test_mode == "squat": + return obs["floating_base_pose"][2] < 0.4 + elif self.test_mode == "walk": + return np.linalg.norm(obs["floating_base_pose"][0:2]) > 1.0 + return False + + def activate(self): + self.keyboard_event_publisher.publish("]") + + def release(self): + self.keyboard_event_publisher.publish("9") + + def go_down(self): + self.keyboard_event_publisher.publish("2") + + def walk_forward(self): + self.keyboard_event_publisher.publish("w") + + def walk_stop(self): + self.keyboard_event_publisher.publish("z") + + def post_process(self, statistics): + if len(statistics) == 0: + return + + # plot the statistics + plot_keys = [key for key in statistics.keys() if key != "timestamp"] + viz = RerunViz( + image_keys=[], + tensor_keys=plot_keys, + window_size=10.0, + app_name=f"{self.test_mode}_test", + ) + + for ii in range(len(statistics[plot_keys[0]]["state"])): + tensor_data = {} + for k in plot_keys: + if "state" in statistics[k] and "cmd" in statistics[k]: + tensor_data[k] = np.array( + (statistics[k]["state"][ii], statistics[k]["cmd"][ii]) + ).reshape(2, -1) + else: + tensor_data[k] = np.asarray(statistics[k]["state"][ii]).reshape(1, -1) + viz.plot_tensors( + tensor_data, + statistics["timestamp"][ii], + ) + + if self.test_mode == "stop": + base_velocity = statistics["floating_base_vel"]["state"] + base_velocity_cmd = statistics["floating_base_vel"]["cmd"] + + base_velocity_tracking_err = [] + for v_cmd, v in zip(base_velocity_cmd, base_velocity): # TODO: check if this is correct + if v_cmd.max() < 1e-4: + base_velocity_tracking_err.append(v) + print( + f" [{GREEN_BOLD}INFO{RESET}] Base velocity tracking when stopped: " + f"{np.mean(base_velocity_tracking_err):.3f}" + ) + + if self.test_mode == "eef_track": + eef_pose = statistics["eef_base_pose"]["state"] + eef_pose_cmd = statistics["eef_base_pose"]["cmd"] + eef_pose_tracking_err = [] + for p_cmd, p in zip(eef_pose_cmd, eef_pose): + eef_pose_tracking_err.append(np.linalg.norm(p - p_cmd)) + print( + f" [{GREEN_BOLD}INFO{RESET}] Eef pose tracking error: {np.mean(eef_pose_tracking_err):.3f}" + ) + + def shutdown(self): + self._stop_event.set() + self.spin_thread.join() + del self.state_subscriber + del self.keyboard_event_publisher + # Don't shutdown ROS between tests - let pytest handle it + + +def start_g1_control_loop(): + proc = subprocess.Popen( + [ + "python3", + "decoupled_wbc/control/main/teleop/run_g1_control_loop.py", + "--keyboard_dispatcher_type", + "ros", + "--enable-offscreen", + ], + preexec_fn=os.setsid, + ) + time.sleep(10) + return proc + + +def run_test(test_mode: str): + """Run a single test with the specified mode.""" + proc = start_g1_control_loop() + print(f"G1 control loop started for {test_mode} test...") + + test = LocomotionRunner(test_mode) + result = test.run() + + print("Shutting down...") + test.shutdown() + proc.send_signal(signal.SIGKILL) + proc.wait() + + return result + + +def test_squat(): + """Pytest function for squat test.""" + result = run_test("squat") + assert result == 1, "Squat test failed - robot either fell or didn't reach target height" + + +def test_walk(): + """Pytest function for walk test.""" + result = run_test("walk") + assert result == 1, "Walk test failed - robot either fell or didn't reach target distance" + + +@pytest.mark.skip(reason="skipping test for now, cicd test always gets killed") +def test_stop(): + """Pytest function for walking to a nearby position and stop test.""" + result = run_test("stop") + assert result == 1, "Stop test failed - robot either fell or didn't reach target distance" + + +@pytest.mark.skip(reason="skipping test for now, cicd test always gets killed") +def test_eef_track(): + """Pytest function for eef track test.""" + result = run_test("eef_track") + assert result == 1, "Eef track test failed - robot either fell or didn't reach target distance" + + +def main(): + parser = argparse.ArgumentParser(description="Run locomotion tests") + parser.add_argument("--squat", action="store_true", help="Run squat test only") + parser.add_argument("--walk", action="store_true", help="Run walk test only") + parser.add_argument("--stop", action="store_true", help="Run stop test only") + parser.add_argument("--eef_track", action="store_true", help="Run eef track test only") + + args = parser.parse_args() + + if args.squat and args.walk: + print("Error: Cannot specify both --squat and --walk") + return 1 + + if args.squat: + print("Running squat test only...") + result = run_test("squat") + if result == 1: + print("✓ Squat test PASSED") + return 0 + else: + print("✗ Squat test FAILED") + return 1 + + elif args.walk: + print("Running walk test only...") + result = run_test("walk") + if result == 1: + print("✓ Walk test PASSED") + return 0 + else: + print("✗ Walk test FAILED") + return 1 + + elif args.stop: + print("Running stop test only...") + result = run_test("stop") + if result == 1: + print("✓ Stop test PASSED") + return 0 + else: + print("✗ Stop test FAILED") + return 1 + + elif args.eef_track: + print("Running eef track test only...") + result = run_test("eef_track") + if result == 1: + print("✓ Eef track test PASSED") + return 0 + else: + print("✗ Eef track test FAILED") + return 1 + + else: + print("Running both tests...") + squat_result = run_test("squat") + walk_result = run_test("walk") + + if squat_result == 1 and walk_result == 1: + print("✓ All tests PASSED") + return 0 + else: + print( + f"✗ Test results: squat={'PASSED' if squat_result == 1 else 'FAILED'}, " + f"walk={'PASSED' if walk_result == 1 else 'FAILED'}" + ) + return 1 + + +if __name__ == "__main__": + exit(main()) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/test_data_exporter_loop.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/test_data_exporter_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..827747382f40e0b863d7a65d7ae258c4ec684cb3 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/main/test_data_exporter_loop.py @@ -0,0 +1,403 @@ +import glob +import os +import tempfile +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest + +try: + from decoupled_wbc.control.main.teleop.run_g1_data_exporter import Gr00tDataCollector + from decoupled_wbc.control.robot_model.instantiation.g1 import instantiate_g1_robot_model + from decoupled_wbc.data.constants import RS_VIEW_CAMERA_HEIGHT, RS_VIEW_CAMERA_WIDTH + from decoupled_wbc.data.exporter import Gr00tDataExporter + from decoupled_wbc.data.utils import get_dataset_features +except ModuleNotFoundError as e: + if "No module named 'rclpy'" in str(e): + pytestmark = pytest.mark.skip(reason="ROS (rclpy) is not installed") + else: + raise e + + +import json + +# How does mocking ROS work? +# +# This test file uses mocking to simulate a ROS environment without requiring actual ROS hardware: +# +# 1. ros_ok_side_effect: Controls how long the ROS loop runs by returning a sequence of +# True/False values. [True, True, False] means "run for 2 iterations then stop" +# +# 2. MockROSMsgSubscriber: Simulates sensors (camera/state) by returning pre-defined data: +# +# 3. MockKeyboardListenerSubscriber: Simulates user input: +# - 'c' = start/stop recording +# - 'd' = discard episode +# - KeyboardInterrupt = simulate Ctrl+C +# - None = no input +# +# 4. MockROSEnvironment: A context manager that patches all ROS dependencies to use our mocks, +# allowing us to test ROS-dependent code without actual ROS running. + + +class MockROSMsgSubscriber: + def __init__(self, return_value: list[dict]): + self.return_value = return_value + self.counter = 0 + + def get_image(self): + if self.counter < len(self.return_value): + self.counter += 1 + return self.return_value[self.counter - 1] + else: + return None + + def get_msg(self): + if self.counter < len(self.return_value): + self.counter += 1 + return self.return_value[self.counter - 1] + else: + return None + + +class MockKeyboardListenerSubscriber: + def __init__(self, return_value: list[str]): + self.return_value = return_value + self.counter = 0 + + def get_keyboard_input(self): + return self.return_value[self.counter] + + def read_msg(self): + if self.counter < len(self.return_value): + result = self.return_value[self.counter] + if isinstance(result, KeyboardInterrupt): + raise result + self.counter += 1 + return result + return None + + +class MockROSEnvironment: + """Context manager for mocking ROS environment and subscribers.""" + + def __init__(self, ok_side_effect, keyboard_listener, img_subscriber, state_subscriber): + self.ok_side_effect = ok_side_effect + self.keyboard_listener = keyboard_listener + self.img_subscriber = img_subscriber + self.state_subscriber = state_subscriber + self.patches = [] + + def __enter__(self): + self.patches = [ + patch("rclpy.init"), + patch("rclpy.create_node"), + patch("rclpy.spin"), + patch("rclpy.ok", side_effect=self.ok_side_effect), + patch("rclpy.shutdown"), + patch( + "decoupled_wbc.control.main.teleop.run_g1_data_exporter.KeyboardListenerSubscriber", + return_value=self.keyboard_listener, + ), + patch( + "decoupled_wbc.control.main.teleop.run_g1_data_exporter.ROSImgMsgSubscriber", + return_value=self.img_subscriber, + ), + patch( + "decoupled_wbc.control.main.teleop.run_g1_data_exporter.ROSMsgSubscriber", + return_value=self.state_subscriber, + ), + ] + + for p in self.patches: + p.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + for p in reversed(self.patches): + p.stop() + return False + + +def verify_parquet_files_exist(file_path: str, num_episodes: int): + parquet_files = glob.glob(os.path.join(file_path, "data/chunk-*/episode_*.parquet")) + assert ( + len(parquet_files) == num_episodes + ), f"Expected {num_episodes} parquet files, but found {len(parquet_files)}" + + +def verify_video_files_exist(file_path: str, observation_keys: list[str], num_episodes: int): + for observation_key in observation_keys: + video_files = glob.glob( + os.path.join(file_path, f"videos/chunk-*/{observation_key}/episode_*.mp4") + ) + assert ( + len(video_files) == num_episodes + ), f"Expected {num_episodes} video files, but found {len(video_files)}" + + +def verify_metadata_files(file_path: str): + files_to_check = ["episodes.jsonl", "info.json", "tasks.jsonl", "modality.json"] + for file in files_to_check: + assert os.path.exists(os.path.join(file_path, "meta", file)), f"meta/{file} not created" + + +@pytest.fixture +def lerobot_features(): + robot_model = instantiate_g1_robot_model() + return get_dataset_features(robot_model) + + +@pytest.fixture +def modality_config(): + return { + "state": {"feature1": {"start": 0, "end": 4}, "feature2": {"start": 4, "end": 9}}, + "action": {"feature1": {"start": 0, "end": 4}, "feature2": {"start": 4, "end": 9}}, + "video": {"rs_view": {"original_key": "observation.images.ego_view"}}, + "annotation": {"human.task_description": {"original_key": "task_index"}}, + } + + +def _get_image_stream_data(episode_length: int, frame_rate: int, img_height: int, img_width: int): + return [ + { + "image": np.zeros((img_height, img_width, 3), dtype=np.uint8), + "timestamp": (i * 1 / frame_rate), + } + for i in range(episode_length) + ] + + +def _get_state_act_stream_data( + episode_length: int, frame_rate: int, state_dim: int, action_dim: int +): + return [ + { + "q": np.zeros(state_dim), + "action": np.zeros(action_dim), + "timestamp": (i * 1 / frame_rate), + "navigate_command": np.zeros(3, dtype=np.float64), + "base_height_command": 0.0, + "wrist_pose": np.zeros(14, dtype=np.float64), + "action.eef": np.zeros(14, dtype=np.float64), + } + for i in range(episode_length) + ] + + +def test_control_loop_happy_path_workflow(lerobot_features, modality_config): + """ + This test records a single episode and saves it to disk. + """ + episode_length = 10 + frame_rate = 20 + img_stream_data = _get_image_stream_data( + episode_length, frame_rate, RS_VIEW_CAMERA_HEIGHT, RS_VIEW_CAMERA_WIDTH + ) + robot_model = instantiate_g1_robot_model() + state_act_stream_data = _get_state_act_stream_data( + episode_length, frame_rate, robot_model.num_joints, robot_model.num_joints + ) + + keyboard_sub_output = [None for _ in range(episode_length)] + keyboard_sub_output[0] = "c" # Start recording + keyboard_sub_output[-1] = "c" # Stop recording and save + + # --------- Save the first episode --------- + mock_img_sub = MockROSMsgSubscriber(img_stream_data) + mock_state_sub = MockROSMsgSubscriber(state_act_stream_data) + mock_keyboard_listner = MockKeyboardListenerSubscriber(keyboard_sub_output) + + with tempfile.TemporaryDirectory() as temp_dir: + dataset_dir = os.path.join(temp_dir, "dataset") + + data_exporter = Gr00tDataExporter.create( + save_root=dataset_dir, + fps=frame_rate, + features=lerobot_features, + modality_config=modality_config, + task="test", + ) + + ros_ok_side_effect = [True] * (episode_length + 1) + [False] + with MockROSEnvironment( + ros_ok_side_effect, mock_keyboard_listner, mock_img_sub, mock_state_sub + ): + data_collector = Gr00tDataCollector( + camera_topic_name="mock_camera_topic", + state_topic_name="mock_state_topic", + data_exporter=data_exporter, + frequency=frame_rate, + ) + + # mocking to avoid actual sleeping + data_collector.rate = MagicMock() + + data_collector.run() + + verify_parquet_files_exist(dataset_dir, 1) + verify_video_files_exist(dataset_dir, data_exporter.meta.video_keys, 1) + verify_metadata_files(dataset_dir) + + # --------- Save the second episode --------- + # we reset the mock subscribers and re-run the control loop + # This immitates the case where the user starts recording a new episode on an existing dataset + mock_img_sub = MockROSMsgSubscriber(img_stream_data) + mock_state_sub = MockROSMsgSubscriber(state_act_stream_data) + ros_ok_side_effect = [True] * (episode_length + 1) + [False] + mock_keyboard_listner = MockKeyboardListenerSubscriber(keyboard_sub_output) + with MockROSEnvironment( + ros_ok_side_effect, mock_keyboard_listner, mock_img_sub, mock_state_sub + ): + data_collector = Gr00tDataCollector( + camera_topic_name="mock_camera_topic", + state_topic_name="mock_state_topic", + data_exporter=data_exporter, + frequency=frame_rate, + ) + + # mocking to avoid actual sleeping + data_collector.rate = MagicMock() + + data_collector.run() + + # now there should be 2 episodes in the dataset + verify_parquet_files_exist(dataset_dir, 2) + verify_video_files_exist(dataset_dir, data_exporter.meta.video_keys, 2) + verify_metadata_files(dataset_dir) + + +def test_control_loop_keyboard_interrupt_workflow(lerobot_features, modality_config): + """ + This test simulates a keyboard interruption in the middle of recording. + Expected behavior: + - The episode is saved to disk + - The episode is marked as discarded + """ + episode_length = 15 + frame_rate = 20 + img_stream_data = _get_image_stream_data( + episode_length, frame_rate, RS_VIEW_CAMERA_HEIGHT, RS_VIEW_CAMERA_WIDTH + ) + robot_model = instantiate_g1_robot_model() + state_act_stream_data = _get_state_act_stream_data( + episode_length, frame_rate, robot_model.num_joints, robot_model.num_joints + ) + + keyboard_sub_output = [None for _ in range(episode_length)] + keyboard_sub_output[0] = "c" # Start recording + keyboard_sub_output[5] = KeyboardInterrupt() # keyboard interruption in the middle of recording + + mock_img_sub = MockROSMsgSubscriber(img_stream_data) + mock_state_sub = MockROSMsgSubscriber(state_act_stream_data) + mock_keyboard_listener = MockKeyboardListenerSubscriber(keyboard_sub_output) + + with tempfile.TemporaryDirectory() as temp_dir: + dataset_dir = os.path.join(temp_dir, "dataset") + + data_exporter = Gr00tDataExporter.create( + save_root=dataset_dir, + fps=frame_rate, + features=lerobot_features, + modality_config=modality_config, + task="test", + ) + + ros_ok_side_effect = [True] * episode_length + [False] + with MockROSEnvironment( + ros_ok_side_effect, mock_keyboard_listener, mock_img_sub, mock_state_sub + ): + data_collector = Gr00tDataCollector( + camera_topic_name="mock_camera_topic", + state_topic_name="mock_state_topic", + data_exporter=data_exporter, + frequency=frame_rate, + ) + + data_collector.rate = MagicMock() + # try: + data_collector.run() + # except KeyboardInterrupt: + # pass + + verify_parquet_files_exist(dataset_dir, 1) + verify_video_files_exist(dataset_dir, data_exporter.meta.video_keys, 1) + verify_metadata_files(dataset_dir) + + # verify that the episode is marked as discarded + ep_info = json.load(open(os.path.join(dataset_dir, "meta", "info.json"))) + assert ep_info["discarded_episode_indices"][0] == 0 + assert ep_info["total_frames"] == 5 + assert ep_info["total_episodes"] == 1 + + +def test_discarded_episode_workflow(lerobot_features, modality_config): + """ + This test simulates a case where the user discards an episode in the middle of recording. + Expected behavior: + - Record 3 episodes, discard episode 0 and 2 + - There should be 3 episodes saved to disk + - Episode 0 and 2 should be flagged as discarded + """ + episode_length = 17 + frame_rate = 20 + robot_model = instantiate_g1_robot_model() + state_dim = robot_model.num_joints + action_dim = robot_model.num_joints + img_stream_data = _get_image_stream_data( + episode_length, frame_rate, RS_VIEW_CAMERA_HEIGHT, RS_VIEW_CAMERA_WIDTH + ) + state_act_stream_data = _get_state_act_stream_data( + episode_length, frame_rate, state_dim, action_dim + ) + + keyboard_sub_output = [None for _ in range(episode_length)] + keyboard_sub_output[0] = "c" # Start recording episode index 0 + keyboard_sub_output[5] = "x" # Discard episode index 0 + keyboard_sub_output[7] = "c" # Start recording episode index 1 + keyboard_sub_output[10] = "c" # stop recording and save episode index 1 + keyboard_sub_output[12] = "c" # start recording episode index 2 + keyboard_sub_output[15] = "x" # discard episode index 2 + + mock_img_sub = MockROSMsgSubscriber(img_stream_data) + mock_state_sub = MockROSMsgSubscriber(state_act_stream_data) + mock_keyboard_listener = MockKeyboardListenerSubscriber(keyboard_sub_output) + + with tempfile.TemporaryDirectory() as temp_dir: + dataset_dir = os.path.join(temp_dir, "dataset") + + data_exporter = Gr00tDataExporter.create( + save_root=dataset_dir, + fps=frame_rate, + features=lerobot_features, + modality_config=modality_config, + task="test", + ) + + ros_ok_side_effect = [True] * episode_length + [False] + with MockROSEnvironment( + ros_ok_side_effect, mock_keyboard_listener, mock_img_sub, mock_state_sub + ): + data_collector = Gr00tDataCollector( + camera_topic_name="mock_camera_topic", + state_topic_name="mock_state_topic", + data_exporter=data_exporter, + frequency=frame_rate, + ) + + data_collector.rate = MagicMock() + try: + data_collector.run() + except Exception: + pass + + # vrify if the episode is marked as discarded + ep_info = json.load(open(os.path.join(dataset_dir, "meta", "info.json"))) + assert len(ep_info["discarded_episode_indices"]) == 2 + assert ep_info["discarded_episode_indices"][0] == 0 + assert ep_info["discarded_episode_indices"][1] == 2 + + # verify that all episodes are saved regardless of being discarded + verify_parquet_files_exist(dataset_dir, 3) + verify_video_files_exist(dataset_dir, data_exporter.meta.video_keys, 3) + verify_metadata_files(dataset_dir) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/test_interpolation_policy.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/test_interpolation_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5cbf08ac1f0a46589a96808c686f972c4ba12e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/test_interpolation_policy.py @@ -0,0 +1,47 @@ +from pathlib import Path +import pickle + +import numpy as np +import pytest + +from decoupled_wbc.control.policy.interpolation_policy import ( + InterpolationPolicy, +) + + +def get_test_data_path(filename: str) -> str: + """Get the absolute path to a test data file.""" + test_dir = Path(__file__).parent + return str(test_dir / ".." / ".." / ".." / "replay_data" / filename) + + +@pytest.fixture +def logged_data(): + """Load the logged data from file.""" + data_path = get_test_data_path("interpolation_data.pkl") + with open(data_path, "rb") as f: + return pickle.load(f) + + +def test_replay_logged_data(logged_data): + """Test that the wrapper produces the same pose commands as logged data.""" + init_args = logged_data["init_args"] + interp = InterpolationPolicy( + init_time=init_args["curr_t"], + init_values={"target_pose": init_args["curr_pose"]}, + max_change_rate=np.inf, + ) + + # Test all data points including the first one + for c in logged_data["calls"]: + # Get the action from wrapper + if c["type"] == "get_action": + action = interp.get_action(**c["args"]) + expected_action = c["result"] + np.testing.assert_allclose( + action["target_pose"], expected_action["q"], rtol=1e-9, atol=1e-9 + ) + # print(action, expected_action) + + else: + interp.set_goal(**c["args"]) diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/test_interpolation_ramp_up.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/test_interpolation_ramp_up.py new file mode 100644 index 0000000000000000000000000000000000000000..2c35e7261cdaa07a9e218761a200ed380d0558b8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/test_interpolation_ramp_up.py @@ -0,0 +1,78 @@ +import numpy as np +import pytest + +from decoupled_wbc.control.policy.interpolation_policy import ( + InterpolationPolicy, +) + + +def test_trajectory_interpolation(): + """ + Test that the InterpolationPolicy correctly interpolates between waypoints. + + Initial pose is at all zeros. + At t=4sec, the index 27 position (right_shoulder_yaw_joint) should be -1.5. + We run at 100Hz to see all intermediate waypoints. + + Notes: + - The trajectory data is at 'trajectory_data.npy' in the current directory + - The visualization is at 'trajectory.png' in the current directory + """ + # Create a pose with 32 joints (all zeros initially) + num_joints = 32 + initial_pose = np.zeros(num_joints) + + # Initial time (use a fixed value for reproducibility) + initial_time = 0.0 + + # Create the wrapper with initial pose + interpolator = InterpolationPolicy( + init_time=initial_time, + init_values={"target_pose": initial_pose}, + max_change_rate=np.inf, + ) + + # Target pose: all zeros except index 27 which should be -1.5 + target_pose = np.zeros(num_joints) + target_pose[27] = -1.5 # right_shoulder_yaw_joint + target_time = 4.0 # 4 seconds from now + + # Set the planner command to schedule the waypoint + interpolator.set_goal( + { + "target_pose": target_pose, + "target_time": target_time, + "interpolation_garbage_collection_time": initial_time, + } + ) + + # Sample the trajectory at 100Hz + frequency = 100 + dt = 1.0 / frequency + sample_times = np.arange(initial_time, target_time + dt, dt) + + # Collect the interpolated poses + sampled_poses = [] + for t in sample_times: + action = interpolator.get_action(t) + sampled_poses.append(action["target_pose"]) + + # Convert to numpy array for easier analysis + sampled_poses = np.array(sampled_poses) + + # Check specific requirements + # Verify we actually moved from 0 to -1.5 + joint_27_positions = sampled_poses[:, 27] + assert joint_27_positions[0] == pytest.approx(0.0) + assert joint_27_positions[-1] == pytest.approx(-1.5) + + # Calculate the absolute changes between each step + changes = np.abs(np.diff(joint_27_positions)) + assert np.all(changes < 0.004), "Joint 27 position should change by less than 0.004" + + # Print some statistics about the trajectory + print(f"Total time steps: {len(sample_times)}") + print(f"Joint 27 trajectory start: {joint_27_positions[0]}") + print(f"Joint 27 trajectory end: {joint_27_positions[-1]}") + print(f"Joint 27 max velocity: {np.max(np.abs(np.diff(joint_27_positions) / dt))}") + print(f"Max velocity timestep: {np.argmax(np.abs(np.diff(joint_27_positions) / dt))}") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/trajectory_data.npy b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/trajectory_data.npy new file mode 100644 index 0000000000000000000000000000000000000000..cb9a22b85bf3b774d70891847f4043cffdfaf3b9 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/policy/interpolation_policy/trajectory_data.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bc643a044e0670a570a44ec5f8d2424f5b8b5541b63c41141636ea36d88fa21 +size 142128 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/robot_model/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/robot_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/robot_model/robot_model_test.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/robot_model/robot_model_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ac1aa8ae582255db1b1ef93c42a66f5f9aae46fe --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/robot_model/robot_model_test.py @@ -0,0 +1,911 @@ +# test_robot_model.py + +import numpy as np +import pinocchio as pin +import pytest + +from decoupled_wbc.control.robot_model import ReducedRobotModel +from decoupled_wbc.control.robot_model.instantiation.g1 import instantiate_g1_robot_model + + +@pytest.fixture +def g1_robot_model(): + """ + Fixture that creates and returns a G1 RobotModel instance. + """ + return instantiate_g1_robot_model() + + +def test_robot_model_initialization(g1_robot_model): + """ + Test initialization of the RobotModel and its main attributes. + """ + for robot_model in [g1_robot_model]: + # Check that the Pinocchio wrapper exists + assert robot_model.pinocchio_wrapper is not None + + # Check number of degrees of freedom (nq) + assert robot_model.num_dofs > 0 + + # Check we have the expected number of joints beyond the floating base + assert len(robot_model.joint_names) > 0 + + # Check that supplemental info is present + assert robot_model.supplemental_info is not None + + +def test_robot_model_joint_names(g1_robot_model): + """ + Test that joint_names is populated correctly + and that dof_index works. + """ + for robot_model in [g1_robot_model]: + # Extract joint names + joint_names = robot_model.joint_names + + # Pick the first joint name and get its index + first_joint_name = joint_names[0] + idx = robot_model.dof_index(first_joint_name) + assert idx >= 0 + + # Test that an unknown joint name raises an error + with pytest.raises(ValueError, match="Unknown joint name"): + _ = robot_model.dof_index("non_existent_joint") + + +def test_robot_model_forward_kinematics_valid_q(g1_robot_model): + """ + Test that cache_forward_kinematics works with a valid q. + """ + for robot_model in [g1_robot_model]: + nq = robot_model.num_dofs + + # Construct a valid configuration (e.g., zero vector) + q_valid = np.zeros(nq) + + # Should not raise any exception + robot_model.cache_forward_kinematics(q_valid) + + +def test_robot_model_forward_kinematics_invalid_q(g1_robot_model): + """ + Test that cache_forward_kinematics raises an error with an invalid q. + """ + for robot_model in [g1_robot_model]: + nq = robot_model.num_dofs + + # Construct an invalid configuration (wrong size) + q_invalid = np.zeros(nq + 1) + + with pytest.raises(ValueError, match="Expected q of length"): + robot_model.cache_forward_kinematics(q_invalid) + + +def test_robot_model_frame_placement(g1_robot_model): + """ + Test the frame_placement method with a valid and invalid frame name. + Also test that frame placements change with different configurations. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing") + + # Use the hand frame from supplemental info + test_frame = robot_model.supplemental_info.hand_frame_names["left"] + + # Test with zero configuration + q_zero = np.zeros(robot_model.num_dofs) + robot_model.cache_forward_kinematics(q_zero) + placement_zero = robot_model.frame_placement(test_frame) + assert isinstance(placement_zero, pin.SE3) + + # Test with non-zero configuration + q_non_zero = np.zeros(robot_model.num_dofs) + root_nq = 7 if robot_model.is_floating_base_model else 0 + + # Set a more significant configuration change + # Use π/2 for all joints to create a more noticeable difference + q_non_zero[root_nq:] = np.pi / 2 # 90 degrees for all joints + + robot_model.cache_forward_kinematics(q_non_zero) + placement_non_zero = robot_model.frame_placement(test_frame) + + # Verify that frame placements are different with different configurations + assert not np.allclose( + placement_zero.translation, placement_non_zero.translation + ) or not np.allclose(placement_zero.rotation, placement_non_zero.rotation) + + # Should raise an error for an invalid frame + with pytest.raises(ValueError, match="Unknown frame"): + robot_model.frame_placement("non_existent_frame") + + +# Tests for ReducedRobotModel +def test_reduced_robot_model_initialization(g1_robot_model): + """ + Test initialization of the ReducedRobotModel. + """ + for robot_model in [g1_robot_model]: + # Create a reduced model by fixing some actual joints from the robot + fixed_joints = robot_model.joint_names[:2] # Use first two joints from the robot + reduced_robot = ReducedRobotModel(robot_model, fixed_joints) + + # Check that the full robot is stored + assert reduced_robot.full_robot is robot_model + + # Check that fixed joints are stored correctly + assert reduced_robot.fixed_joints == fixed_joints + assert len(reduced_robot.fixed_values) == len(fixed_joints) + + # Check that the number of dofs is reduced + assert reduced_robot.num_dofs == robot_model.num_dofs - len(fixed_joints) + + +def test_reduced_robot_model_joint_names(g1_robot_model): + """ + Test that joint_names in ReducedRobotModel excludes fixed joints. + """ + for robot_model in [g1_robot_model]: + # Use actual joints from the robot + fixed_joints = robot_model.joint_names[:2] # Use first two joints from the robot + reduced_robot = ReducedRobotModel(robot_model, fixed_joints) + + # Check that fixed joints are not in the reduced model's joint names + for joint in fixed_joints: + assert joint not in reduced_robot.joint_names + + # Check that other joints are still present + for joint in robot_model.joint_names: + if joint not in fixed_joints: + assert joint in reduced_robot.joint_names + + +def test_reduced_robot_model_configuration_conversion(g1_robot_model): + """ + Test conversion between reduced and full configurations. + """ + for robot_model in [g1_robot_model]: + # Use actual joints from the robot + fixed_joints = robot_model.joint_names[:2] # Use first two joints from the robot + fixed_values = [0.5, 1.0] + reduced_robot = ReducedRobotModel(robot_model, fixed_joints, fixed_values) + + # Create a reduced configuration + q_reduced = np.zeros(reduced_robot.num_dofs) + q_reduced[0] = 0.3 # Set some value for testing + + # Convert to full configuration + q_full = reduced_robot.reduced_to_full_configuration(q_reduced) + + # Check that fixed joints have the correct values + for joint_name, value in zip(fixed_joints, fixed_values): + full_idx = robot_model.dof_index(joint_name) + assert q_full[full_idx] == value + + # Convert back to reduced configuration + q_reduced_back = reduced_robot.full_to_reduced_configuration(q_full) + + # Check that the conversion is reversible + np.testing.assert_array_almost_equal(q_reduced, q_reduced_back) + + +def test_reduced_robot_model_forward_kinematics(g1_robot_model): + """ + Test forward kinematics with the reduced model. + """ + for robot_model in [g1_robot_model]: + # Use actual joints from the robot + fixed_joints = robot_model.joint_names[:2] # Use first two joints from the robot + reduced_robot = ReducedRobotModel(robot_model, fixed_joints) + + # Create a reduced configuration + q_reduced = np.zeros(reduced_robot.num_dofs) + + # Should not raise any exception + reduced_robot.cache_forward_kinematics(q_reduced) + + # Check that frame placement works + model = robot_model.pinocchio_wrapper.model + if len(model.frames) > 1: + valid_frame = model.frames[1].name + placement = reduced_robot.frame_placement(valid_frame) + assert isinstance(placement, pin.SE3) + + +def test_robot_model_clip_configuration(g1_robot_model): + """ + Test that clip_configuration properly clips values to joint limits. + """ + for robot_model in [g1_robot_model]: + # Create a configuration with some values outside limits + q = np.zeros(robot_model.num_dofs) + root_nq = 7 if robot_model.is_floating_base_model else 0 + # Create extreme values for all joints + q[root_nq:] = np.array([100.0, -100.0, 50.0, -50.0] * (robot_model.num_joints // 4 + 1))[ + : robot_model.num_joints + ] + + # Clip the configuration + q_clipped = robot_model.clip_configuration(q) + + # Check that values are within limits + assert np.all(q_clipped[root_nq:] <= robot_model.upper_joint_limits) + assert np.all(q_clipped[root_nq:] >= robot_model.lower_joint_limits) + + +def test_robot_model_get_actuated_joints(g1_robot_model): + """ + Test getting body and hand actuated joints from configuration. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing actuated joints") + + # Create a test configuration + q = np.zeros(robot_model.num_dofs) + root_nq = 7 if robot_model.is_floating_base_model else 0 + q[root_nq:] = np.arange(robot_model.num_joints) # Set some values for joints + + # Test body actuated joints + body_joints = robot_model.get_body_actuated_joints(q) + assert len(body_joints) == len(robot_model.get_body_actuated_joint_indices()) + + # Test hand actuated joints + hand_joints = robot_model.get_hand_actuated_joints(q) + assert len(hand_joints) == len(robot_model.get_hand_actuated_joint_indices()) + + # Test left hand joints + left_hand_joints = robot_model.get_hand_actuated_joints(q, side="left") + assert len(left_hand_joints) == len(robot_model.get_hand_actuated_joint_indices("left")) + + # Test right hand joints + right_hand_joints = robot_model.get_hand_actuated_joints(q, side="right") + assert len(right_hand_joints) == len(robot_model.get_hand_actuated_joint_indices("right")) + + +def test_robot_model_get_configuration_from_actuated_joints(g1_robot_model): + """ + Test creating full configuration from actuated joint values. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing actuated joints") + + # Create test values for body and hands + body_values = np.ones(len(robot_model.get_body_actuated_joint_indices())) + hand_values = np.ones(len(robot_model.get_hand_actuated_joint_indices())) + left_hand_values = np.ones(len(robot_model.get_hand_actuated_joint_indices("left"))) + right_hand_values = np.ones(len(robot_model.get_hand_actuated_joint_indices("right"))) + + # Test with combined hand values + q = robot_model.get_configuration_from_actuated_joints( + body_actuated_joint_values=body_values, hand_actuated_joint_values=hand_values + ) + assert q.shape == (robot_model.num_dofs,) + + # Test with separate hand values + q = robot_model.get_configuration_from_actuated_joints( + body_actuated_joint_values=body_values, + left_hand_actuated_joint_values=left_hand_values, + right_hand_actuated_joint_values=right_hand_values, + ) + assert q.shape == (robot_model.num_dofs,) + + +def test_robot_model_reset_forward_kinematics(g1_robot_model): + """ + Test resetting forward kinematics to default configuration. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing") + + # Create a more significant configuration change + q = np.zeros(robot_model.num_dofs) + root_nq = 7 if robot_model.is_floating_base_model else 0 + # Set some extreme joint angles + q[root_nq:] = np.pi / 2 # 90 degrees for all joints + robot_model.cache_forward_kinematics(q) + + # Use a hand frame from supplemental info + test_frame = robot_model.supplemental_info.hand_frame_names["left"] + + # Reset to default + robot_model.reset_forward_kinematics() + # Get frame placement after reset + placement_default = robot_model.frame_placement(test_frame) + + # Check that frame placement matches what we get with q_zero + robot_model.cache_forward_kinematics(robot_model.q_zero) + placement_q_zero = robot_model.frame_placement(test_frame) + np.testing.assert_array_almost_equal( + placement_default.translation, placement_q_zero.translation + ) + np.testing.assert_array_almost_equal(placement_default.rotation, placement_q_zero.rotation) + + +# Additional tests for ReducedRobotModel +def test_reduced_robot_model_clip_configuration(g1_robot_model): + """ + Test that clip_configuration works in reduced space. + """ + for robot_model in [g1_robot_model]: + fixed_joints = robot_model.joint_names[:2] + reduced_robot = ReducedRobotModel(robot_model, fixed_joints) + + # Create a configuration with some values outside limits + q_reduced = np.zeros(reduced_robot.num_dofs) + root_nq = 7 if reduced_robot.full_robot.is_floating_base_model else 0 + # Create extreme values for all joints + q_reduced[root_nq:] = np.array( + [100.0, -100.0, 50.0, -50.0] * (reduced_robot.num_joints // 4 + 1) + )[: reduced_robot.num_joints] + + # Clip the configuration + q_clipped = reduced_robot.clip_configuration(q_reduced) + + # Check that values are within limits + assert np.all(q_clipped[root_nq:] <= reduced_robot.upper_joint_limits) + assert np.all(q_clipped[root_nq:] >= reduced_robot.lower_joint_limits) + + +def test_reduced_robot_model_get_actuated_joints(g1_robot_model): + """ + Test getting body and hand actuated joints from reduced configuration. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing actuated joints") + + fixed_joints = robot_model.joint_names[:2] + reduced_robot = ReducedRobotModel(robot_model, fixed_joints) + + # Create a test configuration + q_reduced = np.zeros(reduced_robot.num_dofs) + root_nq = 7 if reduced_robot.full_robot.is_floating_base_model else 0 + q_reduced[root_nq:] = np.arange(reduced_robot.num_joints) + + # Test body actuated joints + body_joints = reduced_robot.get_body_actuated_joints(q_reduced) + assert len(body_joints) == len(reduced_robot.get_body_actuated_joint_indices()) + + # Test hand actuated joints + hand_joints = reduced_robot.get_hand_actuated_joints(q_reduced) + assert len(hand_joints) == len(reduced_robot.get_hand_actuated_joint_indices()) + + +def test_reduced_robot_model_get_configuration_from_actuated_joints(g1_robot_model): + """ + Test creating reduced configuration from actuated joint values. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing actuated joints") + + fixed_joints = robot_model.joint_names[:2] + reduced_robot = ReducedRobotModel(robot_model, fixed_joints) + + # Create test values for body and hands + body_values = np.ones(len(reduced_robot.get_body_actuated_joint_indices())) + hand_values = np.ones(len(reduced_robot.get_hand_actuated_joint_indices())) + left_hand_values = np.ones(len(reduced_robot.get_hand_actuated_joint_indices("left"))) + right_hand_values = np.ones(len(reduced_robot.get_hand_actuated_joint_indices("right"))) + + # Test with combined hand values + q_reduced = reduced_robot.get_configuration_from_actuated_joints( + body_actuated_joint_values=body_values, hand_actuated_joint_values=hand_values + ) + assert q_reduced.shape == (reduced_robot.num_dofs,) + + # Test with separate hand values + q_reduced = reduced_robot.get_configuration_from_actuated_joints( + body_actuated_joint_values=body_values, + left_hand_actuated_joint_values=left_hand_values, + right_hand_actuated_joint_values=right_hand_values, + ) + assert q_reduced.shape == (reduced_robot.num_dofs,) + + # Verify that the values were set correctly in the reduced configuration + # Check body actuated joints + body_indices = reduced_robot.get_body_actuated_joint_indices() + np.testing.assert_array_almost_equal(q_reduced[body_indices], body_values) + + # Check left hand actuated joints + left_hand_indices = reduced_robot.get_hand_actuated_joint_indices("left") + np.testing.assert_array_almost_equal(q_reduced[left_hand_indices], left_hand_values) + + # Check right hand actuated joints + right_hand_indices = reduced_robot.get_hand_actuated_joint_indices("right") + np.testing.assert_array_almost_equal(q_reduced[right_hand_indices], right_hand_values) + + +def test_reduced_robot_model_reset_forward_kinematics(g1_robot_model): + """ + Test resetting forward kinematics in reduced model. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing") + + fixed_joints = robot_model.joint_names[:2] + reduced_robot = ReducedRobotModel(robot_model, fixed_joints) + + # Create a more significant configuration change + q_reduced = np.zeros(reduced_robot.num_dofs) + root_nq = 7 if reduced_robot.full_robot.is_floating_base_model else 0 + # Set some extreme joint angles + q_reduced[root_nq:] = np.pi / 2 # 90 degrees for all joints + reduced_robot.cache_forward_kinematics(q_reduced) + + # Reset to default + reduced_robot.reset_forward_kinematics() + + # Check that frame placement matches what we get with q_zero + reduced_robot.cache_forward_kinematics(reduced_robot.q_zero) + placement_q_zero = reduced_robot.frame_placement( + reduced_robot.supplemental_info.hand_frame_names["left"] + ) + placement_reset = reduced_robot.frame_placement( + reduced_robot.supplemental_info.hand_frame_names["left"] + ) + np.testing.assert_array_almost_equal( + placement_reset.translation, placement_q_zero.translation + ) + np.testing.assert_array_almost_equal(placement_reset.rotation, placement_q_zero.rotation) + + +def test_reduced_robot_model_from_fixed_groups(g1_robot_model): + """ + Test creating reduced model from fixed joint groups. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing joint groups") + + # Get a group name from the supplemental info + group_name = next(iter(robot_model.supplemental_info.joint_groups.keys())) + group_info = robot_model.supplemental_info.joint_groups[group_name] + + # Get all joints that should be fixed (including those from subgroups) + expected_fixed_joints = set() + # Add direct joints + expected_fixed_joints.update(group_info["joints"]) + # Add joints from subgroups + for subgroup_name in group_info["groups"]: + subgroup_joints = robot_model.get_joint_group_indices(subgroup_name) + expected_fixed_joints.update([robot_model.joint_names[idx] for idx in subgroup_joints]) + + # Test from_fixed_groups + reduced_robot = ReducedRobotModel.from_fixed_groups(robot_model, [group_name]) + assert reduced_robot.full_robot is robot_model + + # Verify that fixed joints are not in reduced model's joint names + for joint in expected_fixed_joints: + assert joint not in reduced_robot.joint_names + + # Verify that fixed joints maintain their values in configuration + q_reduced = np.ones(reduced_robot.num_dofs) # Set some non-zero values + q_full = reduced_robot.reduced_to_full_configuration(q_reduced) + + # Get the fixed values from the reduced model + fixed_values = dict(zip(reduced_robot.fixed_joints, reduced_robot.fixed_values)) + + # Check that all expected fixed joints have their values preserved + for joint in expected_fixed_joints: + full_idx = robot_model.dof_index(joint) + assert q_full[full_idx] == fixed_values[joint] + + # Test from_fixed_group (convenience method) + reduced_robot = ReducedRobotModel.from_fixed_group(robot_model, group_name) + assert reduced_robot.full_robot is robot_model + + # Verify that fixed joints are not in reduced model's joint names + for joint in expected_fixed_joints: + assert joint not in reduced_robot.joint_names + + # Verify that fixed joints maintain their values in configuration + q_reduced = np.ones(reduced_robot.num_dofs) # Set some non-zero values + q_full = reduced_robot.reduced_to_full_configuration(q_reduced) + + # Get the fixed values from the reduced model + fixed_values = dict(zip(reduced_robot.fixed_joints, reduced_robot.fixed_values)) + + # Check that all expected fixed joints have their values preserved + for joint in expected_fixed_joints: + full_idx = robot_model.dof_index(joint) + assert q_full[full_idx] == fixed_values[joint] + + +def test_reduced_robot_model_from_active_groups(g1_robot_model): + """ + Test creating reduced model from active joint groups. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing joint groups") + + # Get a group name from the supplemental info + group_name = next(iter(robot_model.supplemental_info.joint_groups.keys())) + group_info = robot_model.supplemental_info.joint_groups[group_name] + + # Get all joints that should be active (including those from subgroups) + expected_active_joints = set() + # Add direct joints + expected_active_joints.update(group_info["joints"]) + # Add joints from subgroups + for subgroup_name in group_info["groups"]: + subgroup_joints = robot_model.get_joint_group_indices(subgroup_name) + expected_active_joints.update([robot_model.joint_names[idx] for idx in subgroup_joints]) + + # Get all joints from the model + all_joints = set(robot_model.joint_names) + # The fixed joints should be all joints minus the active joints + expected_fixed_joints = all_joints - expected_active_joints + + # Test from_active_groups + reduced_robot = ReducedRobotModel.from_active_groups(robot_model, [group_name]) + assert reduced_robot.full_robot is robot_model + + # Verify that active joints are in reduced model's joint names + for joint in expected_active_joints: + assert joint in reduced_robot.joint_names + + # Verify that fixed joints are not in reduced model's joint names + for joint in expected_fixed_joints: + assert joint not in reduced_robot.joint_names + + # Verify that fixed joints maintain their values in configuration + q_reduced = np.ones(reduced_robot.num_dofs) # Set some non-zero values + q_full = reduced_robot.reduced_to_full_configuration(q_reduced) + + # Get the fixed values from the reduced model + fixed_values = dict(zip(reduced_robot.fixed_joints, reduced_robot.fixed_values)) + + # Check that all expected fixed joints have their values preserved + for joint in expected_fixed_joints: + full_idx = robot_model.dof_index(joint) + assert q_full[full_idx] == fixed_values[joint] + + # Test from_active_group (convenience method) + reduced_robot = ReducedRobotModel.from_active_group(robot_model, group_name) + assert reduced_robot.full_robot is robot_model + + # Verify that active joints are in reduced model's joint names + for joint in expected_active_joints: + assert joint in reduced_robot.joint_names + + # Verify that fixed joints are not in reduced model's joint names + for joint in expected_fixed_joints: + assert joint not in reduced_robot.joint_names + + # Verify that fixed joints maintain their values in configuration + q_reduced = np.ones(reduced_robot.num_dofs) # Set some non-zero values + q_full = reduced_robot.reduced_to_full_configuration(q_reduced) + + # Get the fixed values from the reduced model + fixed_values = dict(zip(reduced_robot.fixed_joints, reduced_robot.fixed_values)) + + # Check that all expected fixed joints have their values preserved + for joint in expected_fixed_joints: + full_idx = robot_model.dof_index(joint) + assert q_full[full_idx] == fixed_values[joint] + + +def test_reduced_robot_model_frame_placement(g1_robot_model): + """ + Test the frame_placement method in reduced model with a valid and invalid frame name. + Also test that frame placements change with different configurations. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing") + + # Create a reduced model by fixing some joints + fixed_joints = robot_model.joint_names[:2] + reduced_robot = ReducedRobotModel(robot_model, fixed_joints) + + # Use the hand frame from supplemental info + test_frame = reduced_robot.supplemental_info.hand_frame_names["left"] + + # Test with zero configuration + q_reduced_zero = np.zeros(reduced_robot.num_dofs) + reduced_robot.cache_forward_kinematics(q_reduced_zero) + placement_zero = reduced_robot.frame_placement(test_frame) + assert isinstance(placement_zero, pin.SE3) + + # Test with non-zero configuration + q_reduced_non_zero = np.zeros(reduced_robot.num_dofs) + root_nq = 7 if reduced_robot.full_robot.is_floating_base_model else 0 + + # Set a valid non-zero value for each joint + for i in range(root_nq, reduced_robot.num_dofs): + # Use a value that's within the joint limits + q_reduced_non_zero[i] = 0.5 # 0.5 radians is within most joint limits + + reduced_robot.cache_forward_kinematics(q_reduced_non_zero) + placement_non_zero = reduced_robot.frame_placement(test_frame) + + # Verify that frame placements are different with different configurations + assert not np.allclose( + placement_zero.translation, placement_non_zero.translation + ) or not np.allclose(placement_zero.rotation, placement_non_zero.rotation) + + # Should raise an error for an invalid frame + with pytest.raises(ValueError, match="Unknown frame"): + reduced_robot.frame_placement("non_existent_frame") + + +def test_robot_model_gravity_compensation_basic(g1_robot_model): + """ + Test basic gravity compensation functionality. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing gravity compensation") + + # Create a valid configuration + q = np.zeros(robot_model.num_dofs) + if robot_model.is_floating_base_model: + # Set floating base to upright position + q[:7] = [0, 0, 1.0, 0, 0, 0, 1] # [x, y, z, qx, qy, qz, qw] + + # Test gravity compensation for all joints + gravity_torques = robot_model.compute_gravity_compensation_torques(q) + + # Check output shape + assert gravity_torques.shape == (robot_model.num_dofs,) + + # For a humanoid robot with arms, there should be some non-zero gravity torques + assert np.any(np.abs(gravity_torques) > 1e-6), "Expected some non-zero gravity torques" + + +def test_robot_model_gravity_compensation_joint_groups(g1_robot_model): + """ + Test gravity compensation with different joint group specifications. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing gravity compensation") + + # Create a valid configuration + q = np.zeros(robot_model.num_dofs) + if robot_model.is_floating_base_model: + q[:7] = [0, 0, 1.0, 0, 0, 0, 1] + + # Get available joint groups + available_groups = list(robot_model.supplemental_info.joint_groups.keys()) + if not available_groups: + pytest.skip("No joint groups available for testing") + + test_group = available_groups[0] # Use first available group + + # Test with string input + gravity_str = robot_model.compute_gravity_compensation_torques(q, test_group) + assert gravity_str.shape == (robot_model.num_dofs,) + + # Test with list input + gravity_list = robot_model.compute_gravity_compensation_torques(q, [test_group]) + np.testing.assert_array_equal(gravity_str, gravity_list) + + # Test with set input + gravity_set = robot_model.compute_gravity_compensation_torques(q, {test_group}) + np.testing.assert_array_equal(gravity_str, gravity_set) + + # Test that compensation is selective (some joints should be zero) + group_indices = robot_model.get_joint_group_indices(test_group) + if len(group_indices) < robot_model.num_dofs: + # Check that only specified joints have compensation + non_zero_mask = np.abs(gravity_str) > 1e-6 + compensated_indices = np.where(non_zero_mask)[0] + # The compensated indices should be a subset of the group indices + assert len(compensated_indices) <= len(group_indices) + + +def test_robot_model_gravity_compensation_multiple_groups(g1_robot_model): + """ + Test gravity compensation with multiple joint groups. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing gravity compensation") + + # Create a valid configuration + q = np.zeros(robot_model.num_dofs) + if robot_model.is_floating_base_model: + q[:7] = [0, 0, 1.0, 0, 0, 0, 1] + + # Get available joint groups + available_groups = list(robot_model.supplemental_info.joint_groups.keys()) + if len(available_groups) < 2: + pytest.skip("Need at least 2 joint groups for testing") + + # Test with multiple groups + test_groups = available_groups[:2] + gravity_multiple = robot_model.compute_gravity_compensation_torques(q, test_groups) + assert gravity_multiple.shape == (robot_model.num_dofs,) + + # Test individual groups + gravity_1 = robot_model.compute_gravity_compensation_torques(q, test_groups[0]) + gravity_2 = robot_model.compute_gravity_compensation_torques(q, test_groups[1]) + + # The multiple group result should have at least as many non-zero elements + # as either individual group (could be more due to overlaps) + nonzero_multiple = np.count_nonzero(np.abs(gravity_multiple) > 1e-6) + nonzero_1 = np.count_nonzero(np.abs(gravity_1) > 1e-6) + nonzero_2 = np.count_nonzero(np.abs(gravity_2) > 1e-6) + assert nonzero_multiple >= max(nonzero_1, nonzero_2) + + +def test_robot_model_gravity_compensation_configuration_dependency(g1_robot_model): + """ + Test that gravity compensation changes with robot configuration. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing gravity compensation") + + # Get available joint groups - prefer arms if available + available_groups = list(robot_model.supplemental_info.joint_groups.keys()) + test_group = None + for group in ["arms", "left_arm", "right_arm"]: + if group in available_groups: + test_group = group + break + if test_group is None and available_groups: + test_group = available_groups[0] + if test_group is None: + pytest.skip("No joint groups available for testing") + + # Test with different configurations + q1 = np.zeros(robot_model.num_dofs) + q2 = np.zeros(robot_model.num_dofs) + + if robot_model.is_floating_base_model: + # Both configurations upright but different joint positions + q1[:7] = [0, 0, 1.0, 0, 0, 0, 1] + q2[:7] = [0, 0, 1.0, 0, 0, 0, 1] + + # Change arm joint positions specifically (not random joints) + # This ensures we actually change joints that affect the gravity compensation + try: + arm_indices = robot_model.get_joint_group_indices(test_group) + if len(arm_indices) >= 2: + # Change first two arm joints significantly + q2[arm_indices[0]] = np.pi / 4 # 45 degrees + q2[arm_indices[1]] = np.pi / 6 # 30 degrees + elif len(arm_indices) >= 1: + # Change first arm joint if only one available + q2[arm_indices[0]] = np.pi / 3 # 60 degrees + except Exception: + # Fallback to changing some joints if arm indices not available + if robot_model.is_floating_base_model and robot_model.num_dofs > 9: + q2[7] = np.pi / 4 + q2[8] = np.pi / 6 + elif not robot_model.is_floating_base_model and robot_model.num_dofs > 2: + q2[0] = np.pi / 4 + q2[1] = np.pi / 6 + + # Compute gravity compensation for both configurations + gravity_1 = robot_model.compute_gravity_compensation_torques(q1, test_group) + gravity_2 = robot_model.compute_gravity_compensation_torques(q2, test_group) + + # They should be different (unless all compensated joints didn't change) + # Allow for small numerical differences + assert not np.allclose( + gravity_1, gravity_2, atol=1e-10 + ), "Gravity compensation should change with configuration" + + +def test_robot_model_gravity_compensation_error_handling(g1_robot_model): + """ + Test error handling in gravity compensation. + """ + for robot_model in [g1_robot_model]: + # Test with wrong configuration size + q_wrong = np.zeros(robot_model.num_dofs + 1) + with pytest.raises(ValueError, match="Expected q of length"): + robot_model.compute_gravity_compensation_torques(q_wrong) + + # Test with invalid joint group + q_valid = np.zeros(robot_model.num_dofs) + if robot_model.is_floating_base_model: + q_valid[:7] = [0, 0, 1.0, 0, 0, 0, 1] + + with pytest.raises(RuntimeError, match="Error computing gravity compensation"): + robot_model.compute_gravity_compensation_torques(q_valid, "non_existent_group") + + # Test with mixed valid/invalid groups + if robot_model.supplemental_info is not None: + available_groups = list(robot_model.supplemental_info.joint_groups.keys()) + if available_groups: + valid_group = available_groups[0] + with pytest.raises(RuntimeError, match="Error computing gravity compensation"): + robot_model.compute_gravity_compensation_torques( + q_valid, [valid_group, "non_existent_group"] + ) + + +def test_robot_model_gravity_compensation_auto_clip(g1_robot_model): + """ + Test auto-clipping functionality in gravity compensation. + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing gravity compensation") + + # Create configuration with values outside joint limits + q = np.zeros(robot_model.num_dofs) + root_nq = 7 if robot_model.is_floating_base_model else 0 + + if robot_model.is_floating_base_model: + q[:7] = [0, 0, 1.0, 0, 0, 0, 1] # Valid floating base + + # Set extreme joint values (outside limits) + if robot_model.num_dofs > root_nq: + q[root_nq:] = 100.0 # Very large values + + # Should work with auto_clip=True (default) + try: + gravity_clipped = robot_model.compute_gravity_compensation_torques(q, auto_clip=True) + assert gravity_clipped.shape == (robot_model.num_dofs,) + except Exception as e: + pytest.skip(f"Auto-clip test skipped due to: {e}") + + # Test with auto_clip=False - might work or might not depending on limits + try: + gravity_no_clip = robot_model.compute_gravity_compensation_torques(q, auto_clip=False) + assert gravity_no_clip.shape == (robot_model.num_dofs,) + except Exception: + # This is expected if the configuration is invalid + pass + + +def test_robot_model_gravity_compensation_arms_specific(g1_robot_model): + """ + Test gravity compensation specifically for arm joints (if available). + """ + for robot_model in [g1_robot_model]: + # Skip if no supplemental info + if robot_model.supplemental_info is None: + pytest.skip("No supplemental info available for testing gravity compensation") + + available_groups = list(robot_model.supplemental_info.joint_groups.keys()) + + # Test arms specifically if available + if "arms" in available_groups: + q = np.zeros(robot_model.num_dofs) + if robot_model.is_floating_base_model: + q[:7] = [0, 0, 1.0, 0, 0, 0, 1] + + # Test arms gravity compensation + gravity_arms = robot_model.compute_gravity_compensation_torques(q, "arms") + assert gravity_arms.shape == (robot_model.num_dofs,) + + # Test left and right arms separately if available + if "left_arm" in available_groups and "right_arm" in available_groups: + gravity_left = robot_model.compute_gravity_compensation_torques(q, "left_arm") + gravity_right = robot_model.compute_gravity_compensation_torques(q, "right_arm") + + # Both arms should have non-zero compensation (for typical configurations) + if np.any(np.abs(gravity_arms) > 1e-6): + # If arms have compensation, at least one of left/right should too + assert np.any(np.abs(gravity_left) > 1e-6) or np.any( + np.abs(gravity_right) > 1e-6 + ) + else: + pytest.skip("No arm joint groups available for testing") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/teleop/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/teleop/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/teleop/test_teleop_retargeting_ik.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/teleop/test_teleop_retargeting_ik.py new file mode 100644 index 0000000000000000000000000000000000000000..ef3a832ca0dcf7198d46b0cff366b8397d6b5501 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/teleop/test_teleop_retargeting_ik.py @@ -0,0 +1,196 @@ +import time + +import numpy as np +import pytest + +from decoupled_wbc.control.robot_model.instantiation.g1 import instantiate_g1_robot_model +from decoupled_wbc.control.robot_model.robot_model import RobotModel +from decoupled_wbc.control.teleop.solver.hand.instantiation.g1_hand_ik_instantiation import ( + instantiate_g1_hand_ik_solver, +) +from decoupled_wbc.control.teleop.teleop_retargeting_ik import TeleopRetargetingIK + + +@pytest.fixture(params=["lower_body", "lower_and_upper_body"]) +def retargeting_ik(request): + waist_location = request.param + robot_model = instantiate_g1_robot_model(waist_location=waist_location) + left_hand_ik_solver, right_hand_ik_solver = instantiate_g1_hand_ik_solver() + return TeleopRetargetingIK( + robot_model=robot_model, + left_hand_ik_solver=left_hand_ik_solver, + right_hand_ik_solver=right_hand_ik_solver, + enable_visualization=False, # Change to true to visualize movements + body_active_joint_groups=["upper_body"], + ) + + +def generate_target_wrist_poses(mode: str, side: str, full_robot: RobotModel) -> dict: + """ + Args: + mode: One of "rotation" or "translation" + side: One of "left" or "right" - specifies which side to animate + Returns: + Dictionary mapping link names to target poses for both wrists + """ + + assert mode in ["rotation", "translation", "both"] + assert side in ["left", "right", "both"] + + # Set up initial state + full_robot.cache_forward_kinematics(full_robot.q_zero) + + # Get both wrist link names + left_wrist_link = full_robot.supplemental_info.hand_frame_names["left"] + right_wrist_link = full_robot.supplemental_info.hand_frame_names["right"] + + # Initialize default poses for both sides + left_default_pose = full_robot.frame_placement(left_wrist_link).np + right_default_pose = full_robot.frame_placement(right_wrist_link).np + + left_initial_pose_matrix = full_robot.frame_placement(left_wrist_link).np + right_initial_pose_matrix = full_robot.frame_placement(right_wrist_link).np + + # Constants + translation_cycle_duration = 4.0 + rotation_cycle_duration = 4.0 + total_duration = 12.0 + translation_amplitude = 0.1 + rotation_amplitude = np.deg2rad(60) # 30 degrees + + body_data_list = [] + for t in np.linspace(0, total_duration, 100): + rotation_matrix = np.eye(3) + current_left_translation_vector = left_initial_pose_matrix[:3, 3].copy() + current_right_translation_vector = right_initial_pose_matrix[:3, 3].copy() + + if mode == "rotation" or mode == "both": + # For rotation-only mode, start rotating immediately + rotation_axis_index = int(t // rotation_cycle_duration) % 3 + time_within_cycle = t % rotation_cycle_duration + angle = rotation_amplitude * np.sin( + (2 * np.pi / rotation_cycle_duration) * time_within_cycle + ) + + if rotation_axis_index == 0: # Roll + rotation_matrix = np.array( + [ + [1, 0, 0], + [0, np.cos(angle), -np.sin(angle)], + [0, np.sin(angle), np.cos(angle)], + ] + ) + elif rotation_axis_index == 2: # Pitch + rotation_matrix = np.array( + [ + [np.cos(angle), 0, np.sin(angle)], + [0, 1, 0], + [-np.sin(angle), 0, np.cos(angle)], + ] + ) + else: # Yaw + rotation_matrix = np.array( + [ + [np.cos(angle), -np.sin(angle), 0], + [np.sin(angle), np.cos(angle), 0], + [0, 0, 1], + ] + ) + + if mode == "translation" or mode == "both": + translation_axis_index = int(t // translation_cycle_duration) % 3 + time_within_cycle = t % translation_cycle_duration + offset = translation_amplitude * np.sin( + (2 * np.pi / translation_cycle_duration) * time_within_cycle + ) + current_left_translation_vector[translation_axis_index] += offset + current_right_translation_vector[translation_axis_index] += offset + + # Construct the 4x4 pose matrix for the animated side + left_animated_pose = np.eye(4) + left_animated_pose[:3, :3] = rotation_matrix + left_animated_pose[:3, 3] = current_left_translation_vector + + right_animated_pose = np.eye(4) + right_animated_pose[:3, :3] = rotation_matrix + right_animated_pose[:3, 3] = current_right_translation_vector + + # Create body_data dictionary with both wrists + body_data = {} + if side == "left": + body_data[left_wrist_link] = left_animated_pose + body_data[right_wrist_link] = right_default_pose + elif side == "right": + body_data[left_wrist_link] = left_default_pose + body_data[right_wrist_link] = right_animated_pose + elif side == "both": + body_data[left_wrist_link] = left_animated_pose + body_data[right_wrist_link] = right_animated_pose + + body_data_list.append(body_data) + + return body_data_list + + +@pytest.mark.parametrize("mode", ["translation", "rotation"]) +@pytest.mark.parametrize("side", ["both", "left", "right"]) +def test_ik_matches_fk(retargeting_ik, mode, side): + full_robot = retargeting_ik.full_robot + + # Generate target wrist poses + body_data_list = generate_target_wrist_poses(mode, side, full_robot) + + max_pos_error = 0 + max_rot_error = 0 + + for body_data in body_data_list: + + time_start = time.time() + + # Run IK to get joint angles + q = retargeting_ik.compute_joint_positions( + body_data, + left_hand_data=None, # Hand IK not tested + right_hand_data=None, # Hand IK not tested + ) + + time_end = time.time() + ik_time = time_end - time_start + print(f"IK time: {ik_time} s") + # Test commented out because of inconsistency in CI/CD computation time + # assert ik_time < 0.05, f"IK time too high for 20Hz loop: {ik_time} s" + + # Run FK to compute where the wrists actually ended up + full_robot.cache_forward_kinematics(q, auto_clip=False) + left_wrist_link = full_robot.supplemental_info.hand_frame_names["left"] + right_wrist_link = full_robot.supplemental_info.hand_frame_names["right"] + T_fk_left = full_robot.frame_placement(left_wrist_link).np + T_fk_right = full_robot.frame_placement(right_wrist_link).np + T_target_left = body_data[left_wrist_link] + T_target_right = body_data[right_wrist_link] + + # Check that FK translation matches target translation + pos_fk_left = T_fk_left[:3, 3] + pos_target_left = T_target_left[:3, 3] + pos_fk_right = T_fk_right[:3, 3] + pos_target_right = T_target_right[:3, 3] + + max_pos_error = max(max_pos_error, np.linalg.norm(pos_fk_left - pos_target_left)) + max_pos_error = max(max_pos_error, np.linalg.norm(pos_fk_right - pos_target_right)) + + # Check that FK rotation matches target rotation + rot_fk_left = T_fk_left[:3, :3] + rot_target_left = T_target_left[:3, :3] + rot_diff_left = rot_fk_left @ rot_target_left.T + rot_error_left = np.arccos(np.clip((np.trace(rot_diff_left) - 1) / 2, -1, 1)) + rot_fk_right = T_fk_right[:3, :3] + rot_target_right = T_target_right[:3, :3] + rot_diff_right = rot_fk_right @ rot_target_right.T + rot_error_right = np.arccos(np.clip((np.trace(rot_diff_right) - 1) / 2, -1, 1)) + + max_rot_error = max(max_rot_error, rot_error_left) + max_rot_error = max(max_rot_error, rot_error_right) + + assert max_pos_error < 0.01 and max_rot_error < np.deg2rad( + 1 + ), f"Max position error: {max_pos_error}, Max rotation error: {np.rad2deg(max_rot_error)} deg" diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/visualization/__init__.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/visualization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/visualization/test_meshcat_visualizer_env.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/visualization/test_meshcat_visualizer_env.py new file mode 100644 index 0000000000000000000000000000000000000000..fcebc67189bf3629e03cd8d9b739bd572ebbbbdb --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/control/visualization/test_meshcat_visualizer_env.py @@ -0,0 +1,88 @@ +import pathlib +import time + +import numpy as np +import pytest + +from decoupled_wbc.control.robot_model import RobotModel +from decoupled_wbc.control.robot_model.supplemental_info.g1.g1_supplemental_info import ( + G1SupplementalInfo, +) + + +@pytest.fixture +def env_fixture(): + """ + Pytest fixture that creates and yields the MeshcatVisualizerEnv. + After the test, it closes the environment to clean up. + """ + from decoupled_wbc.control.visualization.meshcat_visualizer_env import MeshcatVisualizerEnv + + root_dir = pathlib.Path(__file__).parent.parent.parent.parent + urdf_path = str( + root_dir / "decoupled_wbc/control/robot_model/model_data/g1/g1_29dof_with_hand.urdf" + ) + asset_path = str(root_dir / "decoupled_wbc/control/robot_model/model_data/g1") + robot_config = { + "asset_path": asset_path, + "urdf_path": urdf_path, + } + robot_model = RobotModel( + robot_config["urdf_path"], + robot_config["asset_path"], + supplemental_info=G1SupplementalInfo(), + ) + env = MeshcatVisualizerEnv(robot_model) + time.sleep(0.5) + yield env + env.close() + + +def test_meshcat_env_init(env_fixture): + """ + Test that the environment initializes without errors + and that reset() returns the proper data structure. + """ + env = env_fixture + initial_obs = env.reset() + assert isinstance(initial_obs, dict), "reset() should return a dictionary." + assert "q" in initial_obs, "The returned dictionary should contain key 'q'." + assert ( + len(initial_obs["q"]) == env.robot_model.num_dofs + ), "Length of 'q' should match the robot's DOF." + + +def test_meshcat_env_observation(env_fixture): + """ + Test that the observe() method returns a valid observation + conforming to the environment's observation space. + """ + env = env_fixture + observation = env.observe() + assert isinstance(observation, dict), "observe() should return a dictionary." + assert "q" in observation, "The returned dictionary should contain key 'q'." + assert ( + len(observation["q"]) == env.robot_model.num_dofs + ), "Length of 'q' should match the robot's DOF." + + +def test_meshcat_env_action(env_fixture): + """ + Test that we can queue an action and visualize it without error. + """ + env = env_fixture + # Build a dummy action within the action space + test_action = {"q": 0.2 * np.ones(env.robot_model.num_dofs)} + + # This should not raise an exception and should visualize the correct configuration + env.queue_action(test_action) + + +def test_meshcat_env_close(env_fixture): + """ + Test closing the environment. (Though the fixture calls env.close() + automatically, we can invoke it here to ensure it's safe to do so.) + """ + env = env_fixture + env.close() + # If close() triggers no exceptions, we're good. diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/data/test_exporter.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/data/test_exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5739eacf2f13301ff7c4cd4ff4f400320dbbb1 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/data/test_exporter.py @@ -0,0 +1,522 @@ +import json +from pathlib import Path +import shutil +import tempfile +import time + +from lerobot.common.datasets.lerobot_dataset import LeRobotDataset +import numpy as np +import pytest + +from decoupled_wbc.data.exporter import DataCollectionInfo, Gr00tDataExporter + + +@pytest.fixture +def test_features(): + """Fixture providing test features dict.""" + return { + "observation.images.ego_view": { + "dtype": "video", + "shape": [64, 64, 3], # Small images for faster tests + "names": ["height", "width", "channel"], + }, + "observation.state": { + "dtype": "float32", + "shape": (8,), + "names": ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8"], + }, + "action": { + "dtype": "float32", + "shape": (8,), + "names": ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8"], + }, + } + + +@pytest.fixture +def test_modality_config(): + return { + "state": {"feature1": {"start": 0, "end": 4}, "feature2": {"start": 4, "end": 9}}, + "action": {"feature1": {"start": 0, "end": 4}, "feature2": {"start": 4, "end": 9}}, + "video": {"rs_view": {"original_key": "observation.images.ego_view"}}, + "annotation": {"human.task_description": {"original_key": "task_index"}}, + } + + +@pytest.fixture +def test_data_collection_info(): + return DataCollectionInfo( + teleoperator_username="test_user", + support_operator_username="test_user", + robot_type="test_robot", + lower_body_policy="test_policy", + wbc_model_path="test_path", + ) + + +def get_test_frame(step: int): + """Generate a test frame with data that varies by step.""" + # Create a simple, small image that will encode quickly + img = np.ones((64, 64, 3), dtype=np.uint8) * (step % 255) + # Add a pattern to make each frame unique and verifiable + img[step % 64, :, :] = 255 - (step % 255) + + return { + "observation.images.ego_view": img, + "observation.state": np.ones(8, dtype=np.float32) * step, + "action": np.ones(8, dtype=np.float32) * step, + } + + +@pytest.fixture +def temp_dir(): + """Create a temporary directory for test data that's cleaned up after tests.""" + temp_dir = tempfile.mkdtemp() + yield Path(temp_dir) / "dataset" + shutil.rmtree(temp_dir) + + +class TestInterruptAndResume: + """Test class for simulating interruption and resumption of recording.""" + + # Skip this test if ffmpeg is not installed + @pytest.mark.skipif( + shutil.which("ffmpeg") is None, reason="ffmpeg not installed, skipping test" + ) + def test_interrupted_mid_episode( + self, temp_dir, test_features, test_modality_config, test_data_collection_info + ): + """ + Test that simulates a recording session that gets interrupted and then resumes. + + This test uses the actual Gr00tDataExporter implementation with no mocks. + """ + # Constants for the test + NUM_EPISODES = 2 + FRAMES_PER_EPISODE = 5 + + # Pick a random episode and frame to interrupt at + interrupt_episode = 1 + interrupt_frame = 3 + + print(f"Will interrupt at episode {interrupt_episode}, frame {interrupt_frame}") + + # Track what we've added to verify later + completed_episodes = [] + frames_added_first_session = 0 + + # Initial recording session + try: + # Start recording with real Gr00tDataExporter + exporter1 = Gr00tDataExporter.create( + save_root=temp_dir, + fps=30, + features=test_features, + modality_config=test_modality_config, + task="test_task", + robot_type="test_robot", + vcodec="libx264", # Use a common codec that should be available + data_collection_info=test_data_collection_info, + ) + + # Record episodes until interruption + for episode in range(NUM_EPISODES): + for frame in range(FRAMES_PER_EPISODE): + # Simulate interruption + if episode == interrupt_episode and frame == interrupt_frame: + print(f"Simulating interruption at episode {episode}, frame {frame}") + raise KeyboardInterrupt("Simulated interruption") + + # Add frame + exporter1.add_frame(get_test_frame(frame)) + frames_added_first_session += 1 + + # Save episode + exporter1.save_episode() + completed_episodes.append(episode) + + except KeyboardInterrupt: + print(f"Recording interrupted at episode {interrupt_episode}, frame {interrupt_frame}") + print(f"Completed episodes: {completed_episodes}") + # Don't consolidate since we're interrupted + pass + + # Verify what was recorded before interruption + assert len(completed_episodes) == interrupt_episode + assert ( + frames_added_first_session == interrupt_episode * FRAMES_PER_EPISODE + interrupt_frame + ) + + # Let file system operations complete + time.sleep(0.5) + + # Resume recording - create a new exporter pointing to the same directory + exporter2 = Gr00tDataExporter.create( + save_root=temp_dir, + fps=30, + features=test_features, + modality_config=test_modality_config, + task="test_task", + robot_type="test_robot", + vcodec="libx264", + ) + + # The interrupted episode had frames added but wasn't saved + # In a real scenario with the current implementation, we need to restart that episode + + # Record all episodes from the beginning + frames_added_second_session = 0 + episodes_saved_second_session = 0 + + for episode in range(NUM_EPISODES): + for frame in range(FRAMES_PER_EPISODE): + exporter2.add_frame(get_test_frame(frame)) + frames_added_second_session += 1 + + # Save episode + exporter2.save_episode() + episodes_saved_second_session += 1 + + # Verify the result + assert frames_added_second_session == NUM_EPISODES * FRAMES_PER_EPISODE + assert episodes_saved_second_session == NUM_EPISODES + + # Verify actual files were created + for episode_idx in range(NUM_EPISODES): + video_path = exporter2.root / exporter2.meta.get_video_file_path( + episode_idx, "observation.images.ego_view" + ) + assert video_path.exists(), f"Video file not found: {video_path}" + + @pytest.mark.skipif( + shutil.which("ffmpeg") is None, reason="ffmpeg not installed, skipping test" + ) + def test_interrupted_after_episode_completion( + self, temp_dir, test_features, test_modality_config, test_data_collection_info + ): + """ + Test specifically for the case when interruption happens after an episode is completed. + Uses the real Gr00tDataExporter implementation. + """ + # First session - record 1 complete episode and then interrupt + exporter1 = Gr00tDataExporter.create( + save_root=temp_dir, + fps=30, + features=test_features, + modality_config=test_modality_config, + task="test_task", + data_collection_info=test_data_collection_info, + vcodec="libx264", + ) + + # Record 1 complete episode + for frame in range(5): + exporter1.add_frame(get_test_frame(frame)) + exporter1.save_episode() + + # Let file system operations complete + time.sleep(0.5) + + # Verify the first episode was saved + video_path = exporter1.root / exporter1.meta.get_video_file_path( + 0, "observation.images.ego_view" + ) + assert video_path.exists(), f"First episode video file not found: {video_path}" + + # Second session - resume and record another episode + exporter2 = Gr00tDataExporter.create( + save_root=temp_dir, + fps=30, + features=test_features, + modality_config=test_modality_config, + task="test_task", + vcodec="libx264", + ) + + # Record the second episode + for frame in range(5): + exporter2.add_frame(get_test_frame(frame)) + exporter2.save_episode() + + # Verify the second episode was saved + video_path = exporter2.root / exporter2.meta.get_video_file_path( + 1, "observation.images.ego_view" + ) + assert video_path.exists(), f"Second episode video file not found: {video_path}" + + @pytest.mark.skipif( + shutil.which("ffmpeg") is None, reason="ffmpeg not installed, skipping test" + ) + def test_interrupted_no_episode_completion( + self, temp_dir, test_features, test_modality_config, test_data_collection_info + ): + """ + Test specifically for the case when interruption happens in the middle of recording an episode. + Uses the real Gr00tDataExporter implementation. + """ + # First session - add some frames and interrupt before saving + exporter1 = Gr00tDataExporter.create( + save_root=temp_dir, + fps=30, + features=test_features, + modality_config=test_modality_config, + task="test_task", + data_collection_info=test_data_collection_info, + vcodec="libx264", + ) + + # Add 3 frames but don't save + for frame in range(3): + exporter1.add_frame(get_test_frame(frame)) + # Don't save episode or consolidate to simulate interruption + # The episode buffer is only in memory and will be lost on interruption + + # Let file system operations complete + time.sleep(0.5) + + # Verify no episode was saved + video_path = exporter1.root / exporter1.meta.get_video_file_path( + 0, "observation.images.ego_view" + ) + assert not video_path.exists(), f"Episode should not have been saved: {video_path}" + + # Second session - will raise an error because no meta file exist, so we can't resume + with pytest.raises(ValueError): + _ = Gr00tDataExporter.create( + save_root=temp_dir, + fps=30, + features=test_features, + modality_config=test_modality_config, + task="test_task", + vcodec="libx264", + ) + + +@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed, skipping test") +def test_full_workflow(temp_dir, test_features, test_modality_config, test_data_collection_info): + """ + Test that simulates the complete workflow from the record_session.py example. + """ + NUM_EPISODES = 2 + FRAMES_PER_EPISODE = 3 + + # Create the exporter + exporter = Gr00tDataExporter.create( + save_root=temp_dir, + fps=20, + features=test_features, + modality_config=test_modality_config, + task="test_task", + data_collection_info=test_data_collection_info, + robot_type="dummy", + ) + + # Create a small dataset + for episode_index in range(NUM_EPISODES): + for frame_index in range(FRAMES_PER_EPISODE): + exporter.add_frame(get_test_frame(frame_index)) + exporter.save_episode() + + # check modality config + modality_config_path = exporter.root / "meta" / "modality.json" + assert modality_config_path.exists(), f"{modality_config_path} does not exists." + with open(modality_config_path, "rb") as f: + actual_modality_config = json.load(f) + + assert ( + actual_modality_config == test_modality_config + ), f"Modality configs don't match.\nActual: {actual_modality_config}\nExpected: {test_modality_config}" + + # Verify results + for episode_idx in range(NUM_EPISODES): + video_path = exporter.root / exporter.meta.get_video_file_path( + episode_idx, "observation.images.ego_view" + ) + assert video_path.exists(), f"Video file not found: {video_path}" + + # Check that the expected number of episodes exists + episode_count = 0 + for path in exporter.root.glob("**/*.mp4"): + episode_count += 1 + assert episode_count == NUM_EPISODES, f"Expected {NUM_EPISODES} episodes, found {episode_count}" + + # Check the values of the dataset + dataset = LeRobotDataset( + repo_id="dataset", + root=temp_dir, + ) + for episode_idx in range(NUM_EPISODES): + for frame_idx in range(FRAMES_PER_EPISODE): + expected_frame = get_test_frame(frame_idx) + actual_frame = dataset[episode_idx * FRAMES_PER_EPISODE + frame_idx] + print(actual_frame["observation.images.ego_view"]) + actual_image_frame = actual_frame["observation.images.ego_view"].permute(1, 2, 0) * 255 + assert np.allclose( + actual_image_frame.numpy(), expected_frame["observation.images.ego_view"], atol=10 + ) # Allow some tolerance for video compression + assert np.allclose( + actual_frame["observation.state"], expected_frame["observation.state"] + ) + assert np.allclose(actual_frame["action"], expected_frame["action"]) + + # validate data_collection_info + assert dataset.meta.info["data_collection_info"] == test_data_collection_info.to_dict() + + +@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed, skipping test") +def test_overwrite_existing_dataset_false( + temp_dir, test_features, test_modality_config, test_data_collection_info +): + """ + Test that appends to the existing dataset when overwrite_existing is set to false. + """ + # first dataset + FIRST_NUM_EPISODES = 2 + FIRST_FRAMES_PER_EPISODE = 3 + + exporter = Gr00tDataExporter.create( + save_root=temp_dir, + fps=20, + features=test_features, + modality_config=test_modality_config, + task="test_task", + data_collection_info=test_data_collection_info, + robot_type="dummy", + ) + # !! `overwrite_existing` should always be set to false by default + # So we're deliberately not setting the overwrite_existing argument here. + # This test ensures that + # i. the default behavior is overwrite_existing=False + # ii. the dataset appends to the existing dataset (instead of overwriting) + + # Create a first dataset + for episode_index in range(FIRST_NUM_EPISODES): + for frame_index in range(FIRST_FRAMES_PER_EPISODE): + exporter.add_frame(get_test_frame(frame_index)) + exporter.save_episode() + + # second dataset + del exporter + SECOND_NUM_EPISODES = 3 + SECOND_FRAMES_PER_EPISODE = 2 + + exporter = Gr00tDataExporter.create( + save_root=temp_dir, + fps=20, + features=test_features, + modality_config=test_modality_config, + task="test_task", + robot_type="dummy", + ) + for episode_index in range(SECOND_NUM_EPISODES): + for frame_index in range(SECOND_FRAMES_PER_EPISODE): + exporter.add_frame(get_test_frame(frame_index)) + exporter.save_episode() + + # verify that there are + EXPECTED_NUM_EPISODES = FIRST_NUM_EPISODES + SECOND_NUM_EPISODES + assert len(list(exporter.root.glob("**/*.mp4"))) == EXPECTED_NUM_EPISODES + assert len(list(exporter.root.glob("**/*.parquet"))) == EXPECTED_NUM_EPISODES + + +def test_overwrite_existing_dataset_true( + temp_dir, test_features, test_modality_config, test_data_collection_info +): + """ + Test that overwrites to an existing dataset when overwrite_existing=True. + """ + # first dataset + FIRST_NUM_EPISODES = 2 + FIRST_FRAMES_PER_EPISODE = 3 + + exporter = Gr00tDataExporter.create( + save_root=temp_dir, + fps=20, + features=test_features, + modality_config=test_modality_config, + task="test_task", + data_collection_info=test_data_collection_info, + robot_type="dummy", + ) + + # Create a first dataset + for episode_index in range(FIRST_NUM_EPISODES): + for frame_index in range(FIRST_FRAMES_PER_EPISODE): + exporter.add_frame(get_test_frame(frame_index)) + exporter.save_episode() + + # verify that the dataset is written to the disk + assert len(list(exporter.root.glob("**/*.mp4"))) == FIRST_NUM_EPISODES + assert len(list(exporter.root.glob("**/*.parquet"))) == FIRST_NUM_EPISODES + + # second dataset + SECOND_NUM_EPISODES = 3 + SECOND_FRAMES_PER_EPISODE = 2 + + # re-initialize the exporter + del exporter + exporter = Gr00tDataExporter.create( + save_root=temp_dir, + fps=20, + features=test_features, + modality_config=test_modality_config, + task="test_task", + data_collection_info=test_data_collection_info, + robot_type="dummy", + overwrite_existing=True, + ) + for episode_index in range(SECOND_NUM_EPISODES): + for frame_index in range(SECOND_FRAMES_PER_EPISODE): + exporter.add_frame(get_test_frame(frame_index)) + exporter.save_episode() + + # verify that the dataset is overwritten + assert len(list(exporter.root.glob("**/*.mp4"))) == SECOND_NUM_EPISODES + assert len(list(exporter.root.glob("**/*.parquet"))) == SECOND_NUM_EPISODES + + +def test_save_episode_as_discarded_and_skip( + temp_dir, test_features, test_modality_config, test_data_collection_info +): + """ + Test that verifies the functionality of saving an episode as discarded and skipping an episode. + """ + FIRST_NUM_EPISODES = 10 + FIRST_FRAMES_PER_EPISODE = 3 + + exporter = Gr00tDataExporter.create( + save_root=temp_dir, + fps=20, + features=test_features, + modality_config=test_modality_config, + task="test_task", + data_collection_info=test_data_collection_info, + robot_type="dummy", + ) + + # Create a first dataset + saved_episodes = 0 + discarded_episode_indices = [] + for episode_index in range(FIRST_NUM_EPISODES): + for frame_index in range(FIRST_FRAMES_PER_EPISODE): + exporter.add_frame(get_test_frame(frame_index)) + if episode_index % 3 == 0: + exporter.save_episode_as_discarded() + discarded_episode_indices.append(saved_episodes) + saved_episodes += 1 + elif episode_index % 3 == 1: + exporter.skip_and_start_new_episode() + else: + exporter.save_episode() + saved_episodes += 1 + + # verify that the dataset is written to the disk + assert len(list(exporter.root.glob("**/*.mp4"))) == saved_episodes + assert len(list(exporter.root.glob("**/*.parquet"))) == saved_episodes + + dataset = LeRobotDataset( + repo_id="dataset", + root=temp_dir, + ) + + assert dataset.meta.info["discarded_episode_indices"] == discarded_episode_indices diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/sim/test_sim_data_collection.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/sim/test_sim_data_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d801dffae5135152be4024251998451611c3ae --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/tests/sim/test_sim_data_collection.py @@ -0,0 +1,64 @@ +from decoupled_wbc.control.main.teleop.configs.configs import SyncSimDataCollectionConfig +from decoupled_wbc.control.main.teleop.run_sync_sim_data_collection import ( + main as data_collection_main, +) + + +def test_sim_data_collection_unit(robot_name="G1", task_name="GroundOnly"): + """ + Fast CI unit test for simulation data collection (50 steps, no tracking checks). + + This test validates that: + 1. Data collection completes successfully + 2. Upper body joints are moving (velocity check) + + Note: This test runs for only 50 steps and does not perform end effector tracking validation + for faster CI execution. + """ + config = SyncSimDataCollectionConfig() + config.robot = robot_name + config.task_name = task_name + config.enable_visualization = False + config.enable_real_device = False + config.enable_onscreen = False + config.save_img_obs = True + config.ci_test = True + config.ci_test_mode = "unit" + config.replay_data_path = "decoupled_wbc/tests/replay_data/all_joints_raw_data_replay.pkl" + config.remove_existing_dir = True + config.enable_gravity_compensation = True + res = data_collection_main(config) + assert res, "Data collection did not pass for all datasets" + + +def test_sim_data_collection_pre_merge(robot_name="G1", task_name="GroundOnly"): + """ + Pre-merge test for simulation data collection with end effector tracking validation (500 steps). + + This test validates that: + 1. Data collection completes successfully + 2. Upper body joints are moving (velocity check) + 3. End effector tracking error is within thresholds: + - G1 robots: + Max position error < 7cm (0.07m), Max rotation error < 17°, + Average position error < 5cm (0.05m), Average rotation error < 12° + """ + config = SyncSimDataCollectionConfig() + config.robot = robot_name + config.task_name = task_name + config.enable_visualization = False + config.enable_real_device = False + config.enable_onscreen = False + config.save_img_obs = True + config.ci_test = True + config.ci_test_mode = "pre_merge" + config.replay_data_path = "decoupled_wbc/tests/replay_data/all_joints_raw_data_replay.pkl" + config.remove_existing_dir = True + config.enable_gravity_compensation = True + res = data_collection_main(config) + assert res, "Data collection did not pass for all datasets" + + +if __name__ == "__main__": + # Run unit tests for fast CI + test_sim_data_collection_unit("G1", "GroundOnly") diff --git a/third-party/GR00T-WholeBodyControl/decoupled_wbc/version.py b/third-party/GR00T-WholeBodyControl/decoupled_wbc/version.py new file mode 100644 index 0000000000000000000000000000000000000000..4e48c3d68b4bba671b9cacf6c176a6f7de7fbc52 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/decoupled_wbc/version.py @@ -0,0 +1,11 @@ +_MAJOR = "0" +_MINOR = "1" +# On main and in a nightly release the patch should be one ahead of the last +# released build. +_PATCH = "0" +# This is mainly for nightly builds which have the suffix ".dev$DATE". See +# https://semver.org/#is-v123-a-semantic-version for the semantics. +_SUFFIX = "" + +VERSION_SHORT = "{0}.{1}".format(_MAJOR, _MINOR) +VERSION = "0.1.0" # or whatever version you want diff --git a/third-party/GR00T-WholeBodyControl/docs/Makefile b/third-party/GR00T-WholeBodyControl/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d0c3cbf1020d5c292abdedf27627c6abe25e2293 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/third-party/GR00T-WholeBodyControl/docs/README.md b/third-party/GR00T-WholeBodyControl/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0b8f83515c1f2b3dc5a713c06133f667184fd8a8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/README.md @@ -0,0 +1,74 @@ +# Documentation + +This directory contains the source code for the GR00T-WholeBodyControl documentation website. + +## Building Locally + +### Prerequisites + +Install the required Python packages: + +```bash +pip install sphinx sphinx-book-theme sphinx-design sphinxemoji \ + autodocsumm sphinxcontrib-bibtex myst-parser \ + sphinx-copybutton +``` + +### Build the Documentation + +```bash +cd docs +make html +``` + +The built documentation will be in `build/html/`. Open `build/html/index.html` in your browser. + +### Live Preview + +Start a local web server to preview: + +```bash +cd build/html +python -m http.server 8000 +``` + +Then open http://localhost:8000 + +### Clean Build + +To remove all built files and rebuild from scratch: + +```bash +make clean +make html +``` + +## Deployment + +The documentation is automatically built and deployed to GitHub Pages when changes are pushed to the `main` branch via the GitHub Actions workflow at `.github/workflows/docs.yml`. + +The live documentation will be available at: +**https://nvlabs.github.io/GR00T-WholeBodyControl/** + +## Documentation Structure + +- `source/` - All documentation source files + - `conf.py` - Sphinx configuration + - `index.rst` - Main landing page + - `_static/` - Static assets (CSS, images, logos) + - `tutorials/` - Tutorial pages + - `getting_started/` - Getting started guides + - `user_guide/` - User guide + - `api/` - API reference + - `resources/` - Additional resources + +## Writing Documentation + +- Use Markdown (`.md`) or reStructuredText (`.rst`) files +- Markdown is recommended for simplicity +- Place new files in the appropriate subdirectory +- Update `index.rst` to add new sections to the navigation + +## Theme + +The documentation uses the `sphinx_book_theme` with NVIDIA branding, matching the Isaac Lab documentation style. diff --git a/third-party/GR00T-WholeBodyControl/docs/requirements.txt b/third-party/GR00T-WholeBodyControl/docs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..125dc4e13da4cd086b6442a4c7353383d49e1944 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/requirements.txt @@ -0,0 +1,10 @@ +# Sphinx documentation build dependencies +sphinx>=7.0,<9.0 +sphinx-book-theme>=1.1.0 +myst-parser>=3.0.0 +autodocsumm>=0.2.12 +sphinxemoji>=0.3.1 +sphinxcontrib-bibtex>=2.6.0 +sphinxcontrib-video>=0.2.1 +sphinx-copybutton>=0.5.2 +sphinx-design>=0.6.0 diff --git a/third-party/GR00T-WholeBodyControl/docs/source/.nojekyll b/third-party/GR00T-WholeBodyControl/docs/source/.nojekyll new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third-party/GR00T-WholeBodyControl/docs/source/_static/Pipeline.jpg b/third-party/GR00T-WholeBodyControl/docs/source/_static/Pipeline.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b4b09c8f47dbf8b29f0e7b11adfa97c4f28fb958 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/_static/Pipeline.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cc0723465247529f551e80edda6fadc9975ebc03525b1b0f42e75c3172d582a +size 62446 diff --git a/third-party/GR00T-WholeBodyControl/docs/source/_static/css/custom.css b/third-party/GR00T-WholeBodyControl/docs/source/_static/css/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..d2e8f2bdf93b5a3776560386a41dd6cf8b4a906d --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/_static/css/custom.css @@ -0,0 +1,102 @@ +/* + * NVIDIA-styled theme for GR00T-WholeBodyControl + * Based on IsaacLab documentation styling + * Colors reference: https://clrs.cc/ + */ + +/* anything related to the light theme */ +html[data-theme="light"] { + --pst-color-primary: #76B900; + --pst-color-secondary: #5b8e03; + --pst-color-secondary-highlight: #5b8e03; + --pst-color-inline-code-links: #76B900; + --pst-color-info: var(--pst-color-primary); + --pst-color-info-highlight: var(--pst-color-primary); + --pst-color-info-bg: #daedb9; + --pst-color-attention: #ffc107; + --pst-color-text-base: #323232; + --pst-color-text-muted: #646464; + --pst-color-shadow: #d8d8d8; + --pst-color-border: #c9c9c9; + --pst-color-inline-code: #76B900; + --pst-color-target: #fbe54e; + --pst-color-background: #fff; + --pst-color-on-background: #fff; + --pst-color-surface: #f5f5f5; + --pst-color-on-surface: #e1e1e1; + --pst-color-link: var(--pst-color-primary); + --pst-color-link-hover: #789841; + --pst-color-table-row-hover-bg: #daedb9; + --pst-color-accent: var(--pst-color-primary); +} + +/* anything related to the dark theme */ +html[data-theme="dark"] { + --pst-color-primary: #76B900; + --pst-color-secondary: #c2f26f; + --pst-color-secondary-highlight: #c2f26f; + --pst-color-inline-code-links: #b6e664; + --pst-color-info: var(--pst-color-primary); + --pst-color-info-highlight: var(--pst-color-primary); + --pst-color-info-bg: #3a550b; + --pst-color-attention: #dca90f; + --pst-color-text-base: #cecece; + --pst-color-text-muted: #a6a6a6; + --pst-color-shadow: #212121; + --pst-color-border: silver; + --pst-color-inline-code: #76B900; + --pst-color-target: #472700; + --pst-color-background: #121212; + --pst-color-on-background: #1e1e1e; + --pst-color-surface: #212121; + --pst-color-on-surface: #373737; + --pst-color-link: var(--pst-color-primary); + --pst-color-link-hover: #aee354; + --pst-color-table-row-hover-bg: #3a550b; + --pst-color-accent: var(--pst-color-primary); +} + +a { + text-decoration: none !important; +} + +/* for the announcement link */ +.bd-header-announcement a, +.bd-header-version-warning a { + color: #7FDBFF; +} + +/* for the search box in the navbar */ +.form-control { + border-radius: 0 !important; + border: none !important; + outline: none !important; +} + +/* reduce padding for logo */ +.navbar-brand { + padding-top: 0.0rem !important; + padding-bottom: 0.0rem !important; +} + +.navbar-icon-links { + padding-top: 0.0rem !important; + padding-bottom: 0.0rem !important; +} + +/* Remove "Built with Sphinx" footer */ +.footer-item__copyright, +.footer-item__theme { + display: none !important; +} + +/* Hide Sphinx attribution in footer */ +div.footer-item:has(.theme-switcher) ~ div.footer-item { + display: none !important; +} + +/* Cleaner footer styling */ +footer.bd-footer { + border-top: 1px solid var(--pst-color-border); + padding-top: 1rem; +} diff --git a/third-party/GR00T-WholeBodyControl/docs/source/_static/favicon.ico b/third-party/GR00T-WholeBodyControl/docs/source/_static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..7b39f8af7af0831df98713dd0c28347049e4041f Binary files /dev/null and b/third-party/GR00T-WholeBodyControl/docs/source/_static/favicon.ico differ diff --git a/third-party/GR00T-WholeBodyControl/docs/source/api/index.md b/third-party/GR00T-WholeBodyControl/docs/source/api/index.md new file mode 100644 index 0000000000000000000000000000000000000000..991b7c36ce265e225c9e77e43043cac83154588e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/api/index.md @@ -0,0 +1,3 @@ +# API Reference + +Coming soon... diff --git a/third-party/GR00T-WholeBodyControl/docs/source/api/teleop.md b/third-party/GR00T-WholeBodyControl/docs/source/api/teleop.md new file mode 100644 index 0000000000000000000000000000000000000000..32f9c302221bb694ced8bcf88abd056d4940725d --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/api/teleop.md @@ -0,0 +1,3 @@ +# Teleoperation API + +Coming soon... diff --git a/third-party/GR00T-WholeBodyControl/docs/source/conf.py b/third-party/GR00T-WholeBodyControl/docs/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..f80cabaf1dc4ab528ff7597a04c14dbcd119e040 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/conf.py @@ -0,0 +1,145 @@ +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +import os +import sys + +# -- Project information ----------------------------------------------------- + +project = 'GR00T-WholeBodyControl' +copyright = '2026, NVIDIA' +author = 'NVIDIA GEAR Team' +release = '1.0.0' +version = '1.0' + +# -- General configuration --------------------------------------------------- + +extensions = [ + 'autodocsumm', + 'myst_parser', + 'sphinx.ext.napoleon', + 'sphinxemoji.sphinxemoji', + 'sphinx.ext.autodoc', + 'sphinx.ext.autosummary', + 'sphinx.ext.githubpages', + 'sphinx.ext.intersphinx', + 'sphinx.ext.mathjax', + 'sphinx.ext.todo', + 'sphinx.ext.viewcode', + 'sphinxcontrib.bibtex', + 'sphinx_copybutton', + 'sphinx_design', + 'sphinxcontrib.video', +] + +# mathjax hacks +mathjax3_config = { + "tex": { + "inlineMath": [["\\(", "\\)"]], + "displayMath": [["\\[", "\\]"]], + }, +} + +# emoji style +sphinxemoji_style = "twemoji" + +# supported file extensions for source files +source_suffix = { + '.rst': 'restructuredtext', + '.md': 'markdown', +} + +# BibTeX configuration +bibtex_bibfiles = [] + +# generate autosummary even if no references +autosummary_generate = True +autosummary_generate_overwrite = False + +# generate links to the documentation of objects in external projects +intersphinx_mapping = { + 'python': ('https://docs.python.org/3', None), + 'numpy': ('https://numpy.org/doc/stable/', None), + 'torch': ('https://pytorch.org/docs/stable/', None), +} + +templates_path = ['_templates'] +exclude_patterns = ['_build', '_templates', 'Thumbs.db', '.DS_Store'] + +# List of zero or more Sphinx-specific warning categories to be squelched +suppress_warnings = [ + "ref.python", +] + +# -- MyST Parser configuration ----------------------------------------------- + +myst_enable_extensions = [ + "colon_fence", + "deflist", + "tasklist", +] + +# -- Options for HTML output ------------------------------------------------- + +import sphinx_book_theme + +html_title = "GR00T-WholeBodyControl Documentation" +html_theme_path = [sphinx_book_theme.get_html_theme_path()] +html_theme = "sphinx_book_theme" +html_favicon = "_static/favicon.ico" +html_show_copyright = True +html_show_sphinx = False # This removes "Built with Sphinx" footer +html_last_updated_fmt = "" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] +html_css_files = ["css/custom.css"] + +html_theme_options = { + "path_to_docs": "docs/", + "collapse_navigation": True, + "repository_url": "https://github.com/NVlabs/GR00T-WholeBodyControl", + "use_repository_button": True, + "use_issues_button": True, + "use_edit_page_button": True, + "show_toc_level": 1, + "use_sidenotes": True, + "logo": { + "text": "GR00T-WholeBodyControl Documentation", + "image_light": "_static/NVIDIA-logo-white.png", + "image_dark": "_static/NVIDIA-logo-black.png", + }, + "icon_links": [ + { + "name": "GitHub", + "url": "https://github.com/NVlabs/GR00T-WholeBodyControl", + "icon": "fa-brands fa-square-github", + "type": "fontawesome", + }, + { + "name": "GEAR-SONIC Website", + "url": "https://nvlabs.github.io/GEAR-SONIC/", + "icon": "fa-solid fa-globe", + "type": "fontawesome", + }, + { + "name": "Paper", + "url": "https://arxiv.org/abs/2511.07820", + "icon": "fa-solid fa-file-pdf", + "type": "fontawesome", + }, + ], + "icon_links_label": "Quick Links", +} + +templates_path = [ + "_templates", +] + +# -- Internationalization ---------------------------------------------------- + +language = "en" diff --git a/third-party/GR00T-WholeBodyControl/docs/source/getting_started/download_models.md b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/download_models.md new file mode 100644 index 0000000000000000000000000000000000000000..c81937fd1ecec0a882770344983c338093676498 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/download_models.md @@ -0,0 +1,490 @@ +# Downloading Model Checkpoints + +Pre-trained GEAR-SONIC checkpoints (ONNX format) are hosted on Hugging Face: + +**[nvidia/GEAR-SONIC](https://huggingface.co/nvidia/GEAR-SONIC)** + +## Quick Download + +### Install the dependency + +```bash +pip install huggingface_hub +``` + +### Run the download script + +From the repo root: + +```bash +# Deployment (ONNX models + planner → gear_sonic_deploy/) +python download_from_hf.py + +# Low-latency teleoperation checkpoint (ONNX models + planner → gear_sonic_deploy/) +python download_from_hf.py --low-latency + +# SONIC v1.1 checkpoint (ONNX models + planner → gear_sonic_deploy/) +python download_from_hf.py --sonic-v1-1 + +# Training (checkpoint + SMPL data → sonic_release/ + data/smpl_filtered/) +python download_from_hf.py --training + +# Low-latency PyTorch checkpoint + config only +python download_from_hf.py --training --low-latency + +# SONIC v1.1 PyTorch checkpoint + configs only +python download_from_hf.py --training --sonic-v1-1 --no-smpl + +# Sample data only (1 walking sequence for quick testing) +python download_from_hf.py --sample + +# Training checkpoint only (skip 30GB SMPL download) +python download_from_hf.py --training --no-smpl +``` + +This downloads the **latest** policy encoder + decoder + kinematic planner into +`gear_sonic_deploy/`, preserving the same directory layout the deployment binary expects. + +--- + +## Options + +| Flag | Description | +|------|-------------| +| `--training` | Download training checkpoint + SMPL motion data (~30 GB) | +| `--low-latency` | Download the low-latency teleoperation checkpoint. For deployment, ONNX files go to `gear_sonic_deploy/policy/low_latency/`; with `--training`, the PyTorch checkpoint and configs go to `low_latency/`. | +| `--sonic-v1-1` | Download SONIC v1.1, which uses robot-heading-normalized targets and wrist-pose augmentation. Deployment files go to `gear_sonic_deploy/policy/sonic_v1_1/`; training files go to `sonic_v1_1/`. | +| `--sample` | Download sample motion data only (~4 MB) | +| `--no-planner` | Skip the kinematic planner download | +| `--no-smpl` | With `--training`, skip SMPL data (checkpoint only) | +| `--output-dir PATH` | Override the destination directory | +| `--token TOKEN` | HF token (alternative to `hf auth login`) | + +### Examples + +```bash +# Policy + planner (default) +python download_from_hf.py + +# Policy only +python download_from_hf.py --no-planner + +# Low-latency teleoperation policy only +python download_from_hf.py --low-latency --no-planner + +# SONIC v1.1 policy only +python download_from_hf.py --sonic-v1-1 --no-planner + +# Download into a custom directory +python download_from_hf.py --output-dir /data/gear-sonic +``` + +--- + +## Low-Latency Teleoperation Checkpoint + +The checkpoint published under `low_latency/` in +[`nvidia/GEAR-SONIC`](https://huggingface.co/nvidia/GEAR-SONIC) is configured +for responsive whole-body teleoperation. Its SMPL encoder uses **4 future +reference frames**, compared with **10 frames** in the default release. At +50 Hz (20 ms per frame), this reduces SMPL reference lookahead from +approximately **200 ms to 80 ms**. + +This is the controller's reference lookahead, not a measurement of total +end-to-end system latency. The checkpoint does not replace the default +top-level deployment policy. + +Download the deployment ONNX files: + +```bash +python download_from_hf.py --low-latency +``` + +This creates: + +``` +gear_sonic_deploy/ +└── policy/low_latency/ + ├── model_encoder.onnx + ├── model_decoder.onnx + └── observation_config.yaml +``` + +### C++ deployment inference + +Run the low-latency ONNX controller in simulation: + +```bash +cd gear_sonic_deploy +./deploy.sh \ + --cp policy/low_latency/model \ + --obs-config policy/low_latency/observation_config.yaml \ + sim +``` + +Run it for VLA or teleoperation on the real robot: + +```bash +cd gear_sonic_deploy +./deploy.sh \ + --cp policy/low_latency/model \ + --obs-config policy/low_latency/observation_config.yaml \ + --input-type zmq_manager \ + real +``` + +`deploy.sh` expects `--cp` to be the shared model prefix; it appends +`_encoder.onnx` and `_decoder.onnx` internally. The low-latency PyTorch +checkpoint is available as `low_latency/last.pt`: + +```bash +python download_from_hf.py --training --low-latency +``` + +### Python inference and evaluation + +For Python-side checkpoint evaluation in Isaac Lab, download the PyTorch +checkpoint and sample motions: + +```bash +python download_from_hf.py --training --low-latency +python download_from_hf.py --sample +``` + +Then run the low-latency checkpoint with `eval_agent_trl.py`: + +```bash +python gear_sonic/eval_agent_trl.py \ + +checkpoint=low_latency/last.pt \ + +headless=False \ + ++num_envs=1 \ + ++manager_env.observations.policy.enable_corruption=False \ + ++manager_env.observations.tokenizer.enable_corruption=False \ + "++manager_env.commands.motion.motion_lib_cfg.motion_file=sample_data/robot_filtered" \ + "++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=sample_data/smpl_filtered" +``` + +For the Python VLA tmux launcher, pass the same low-latency C++ deploy files +through launcher flags: + +```bash +python gear_sonic/scripts/launch_inference.py \ + --deploy-checkpoint policy/low_latency/model \ + --deploy-obs-config policy/low_latency/observation_config.yaml \ + --camera-host 192.168.123.164 \ + --prompt "pick up the cup" +``` + +The launcher still runs the ONNX controller through the C++ deployment pane; +the Python process coordinates the VLA client, camera client, keyboard control, +and optional data exporter. + +--- + +## SONIC v1.1 Checkpoint + +The checkpoint under `sonic_v1_1/` uses robot-heading-normalized target +orientations and was trained with wrist-pose augmentation. It is intended for +heading-stable whole-body teleoperation and SONIC-backed VLA policies trained +against this controller. + +Its SMPL and wrist encoders use **10 future frames at 20 ms spacing** +(approximately **200 ms** of reference lookahead). G1 and teleoperation +references use 10 frames at `step5`. This is not the low-latency checkpoint. + +Download the matching ONNX encoder, decoder, observation config, and planner: + +```bash +python download_from_hf.py --sonic-v1-1 +``` + +This creates: + +``` +gear_sonic_deploy/ +└── policy/sonic_v1_1/ + ├── model_encoder.onnx + ├── model_decoder.onnx + └── observation_config.yaml +``` + +Run the controller in simulation: + +```bash +cd gear_sonic_deploy +./deploy.sh \ + --cp policy/sonic_v1_1/model \ + --obs-config policy/sonic_v1_1/observation_config.yaml \ + sim +``` + +For the VLA launcher: + +```bash +python gear_sonic/scripts/launch_inference.py \ + --deploy-checkpoint policy/sonic_v1_1/model \ + --deploy-obs-config policy/sonic_v1_1/observation_config.yaml \ + --camera-host 192.168.123.164 \ + --prompt "pick up the cup" +``` + +Download the PyTorch checkpoint and configs without the shared 30 GB SMPL +dataset: + +```bash +python download_from_hf.py --training --sonic-v1-1 --no-smpl +``` + +Evaluate it with the matching release recipe: + +```bash +python gear_sonic/eval_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_v1_1 \ + +checkpoint=sonic_v1_1/last.pt \ + +headless=False \ + ++num_envs=1 \ + ++manager_env.observations.policy.enable_corruption=False \ + ++manager_env.observations.tokenizer.enable_corruption=False +``` + +Use the same `+exp` and `+checkpoint` values with `train_agent_trl.py` for +continued training. + +--- + +## Manual download via CLI + +If you prefer the Hugging Face CLI: + +```bash +pip install huggingface_hub[cli] + +# Policy only +hf download nvidia/GEAR-SONIC \ + model_encoder.onnx \ + model_decoder.onnx \ + observation_config.yaml \ + --local-dir gear_sonic_deploy + +# Everything (policy + planner) +hf download nvidia/GEAR-SONIC --local-dir gear_sonic_deploy +``` + +--- + +## Manual download via Python + +```python +from huggingface_hub import hf_hub_download + +REPO_ID = "nvidia/GEAR-SONIC" + +encoder = hf_hub_download(repo_id=REPO_ID, filename="model_encoder.onnx") +decoder = hf_hub_download(repo_id=REPO_ID, filename="model_decoder.onnx") +config = hf_hub_download(repo_id=REPO_ID, filename="observation_config.yaml") +planner = hf_hub_download(repo_id=REPO_ID, filename="planner_sonic.onnx") + +print("Policy encoder :", encoder) +print("Policy decoder :", decoder) +print("Obs config :", config) +print("Planner :", planner) +``` + +--- + +## SONIC Training Checkpoint + +The SONIC release training checkpoint and config are also available on Hugging Face, for evaluation or fine-tuning: + +### Download via CLI + +```bash +hf download nvidia/GEAR-SONIC \ + sonic_release/last.pt \ + sonic_release/config.yaml \ + --local-dir models +``` + +### Download via Python + +```python +from huggingface_hub import hf_hub_download + +REPO_ID = "nvidia/GEAR-SONIC" + +checkpoint = hf_hub_download(repo_id=REPO_ID, filename="sonic_release/last.pt") +config = hf_hub_download(repo_id=REPO_ID, filename="sonic_release/config.yaml") + +print("Checkpoint :", checkpoint) +print("Config :", config) +``` + +### Evaluate the checkpoint + +```bash +python gear_sonic/eval_agent_trl.py \ + +checkpoint=models/sonic_release/last.pt \ + +num_envs=1 headless=False +``` + +--- + +## Sample Motion Data (Quick Start) + +A small sample dataset (1 walking sequence) is included for quick testing without downloading the full Bones-SEED dataset. It contains all three data types needed for training: robot retargeted, SOMA skeleton, and SMPL. + +### Download via CLI + +```bash +# Sample data only +hf download nvidia/GEAR-SONIC \ + --include "sample_data/*" \ + --local-dir . + +# Sample data + training checkpoint +hf download nvidia/GEAR-SONIC \ + --include "sample_data/*" \ + --include "sonic_release/*" \ + --local-dir . +``` + +This creates: + +``` +sample_data/ +├── robot_filtered/210531/ # G1 retargeted motion (for motion tracking) +│ ├── walk_forward_amateur_001__A001.pkl +│ └── walk_forward_amateur_001__A001_M.pkl +├── soma_filtered/210531/ # SOMA skeleton motion +│ ├── walk_forward_amateur_001__A001.pkl +│ └── walk_forward_amateur_001__A001_M.pkl +└── smpl_filtered/ # SMPL human motion + ├── walk_forward_amateur_001__A001.pkl + └── walk_forward_amateur_001__A001_M.pkl +``` + +### Test training with sample data + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=16 headless=True \ + manager_env.commands.motion.motion_lib_cfg.motion_file=sample_data/robot_filtered \ + manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=sample_data/smpl_filtered +``` + +For full-scale training, download the complete [Bones-SEED](https://huggingface.co/datasets/bones-studio/seed) dataset and follow the [Training Guide](../user_guide/training.md). + +--- + +## SMPL Motion Data (Bones-SEED Filtered) + +The SMPL retargeted motion data used for training (131K sequences, filtered from the Bones-SEED dataset) is available as a split tar archive (~30GB total). + +### Download and extract + +```bash +# Download all parts +hf download nvidia/GEAR-SONIC --include "bones_seed_smpl/*" --local-dir . + +# Reassemble and extract +cat bones_seed_smpl/bones_seed_smpl.tar.part_* | tar xf - -C data/ +``` + +This extracts to `data/smpl_filtered/` with 131K `.pkl` files. + +Then point training to it: + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + +checkpoint=sonic_release/last.pt \ + num_envs=4096 headless=True \ + ++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=data/smpl_filtered +``` + +--- + +## Available files + +``` +nvidia/GEAR-SONIC/ +├── model_encoder.onnx # Policy encoder (ONNX, for deployment) +├── model_decoder.onnx # Policy decoder (ONNX, for deployment) +├── observation_config.yaml # Observation configuration (deployment) +├── planner_sonic.onnx # Kinematic planner (ONNX) +├── low_latency/ +│ ├── model_encoder.onnx # Low-latency policy encoder (ONNX) +│ ├── model_decoder.onnx # Low-latency policy decoder (ONNX) +│ ├── observation_config.yaml # Low-latency observation configuration +│ ├── last.pt # Low-latency training checkpoint +│ ├── config.yaml # Low-latency training config +│ └── model_config.yaml # Low-latency model config +├── sonic_v1_1/ +│ ├── model_encoder.onnx # SONIC v1.1 policy encoder (ONNX) +│ ├── model_decoder.onnx # SONIC v1.1 policy decoder (ONNX) +│ ├── observation_config.yaml # Matching deployment observations +│ ├── last.pt # SONIC v1.1 training checkpoint +│ ├── config.yaml # Resolved training config +│ └── model_config.yaml # Model architecture config +├── bones_seed_smpl/ # SMPL motion data (131K sequences, ~30GB split tar) +│ ├── bones_seed_smpl.tar.part_aa +│ ├── ... +│ └── bones_seed_smpl.tar.part_ag +├── sonic_release/ +│ ├── last.pt # Training checkpoint (for eval/fine-tuning) +│ └── config.yaml # Training config +└── sample_data/ # Sample motion data (1 walking sequence) + ├── robot_filtered/ # G1 retargeted motion + ├── soma_filtered/ # SOMA skeleton motion + └── smpl_filtered/ # SMPL human motion +``` + +The download script places deployment files into the layout the deployment binary expects: + +``` +gear_sonic_deploy/ +├── policy/release/ +│ ├── model_encoder.onnx +│ ├── model_decoder.onnx +│ └── observation_config.yaml +├── policy/low_latency/ +│ ├── model_encoder.onnx +│ ├── model_decoder.onnx +│ └── observation_config.yaml +├── policy/sonic_v1_1/ +│ ├── model_encoder.onnx +│ ├── model_decoder.onnx +│ └── observation_config.yaml +└── planner/target_vel/V2/ + └── planner_sonic.onnx +``` + +--- + +## Authentication + +The repository is **public** — no token required for downloading. + +If you hit rate limits or need to access private forks: + +```bash +# Option 1: CLI login (recommended — token is saved once) +hf login + +# Option 2: environment variable +export HF_TOKEN="hf_..." +python download_from_hf.py + +# Option 3: pass token directly +python download_from_hf.py --token hf_... +``` + +Get a free token at [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens). + +--- + +## Next steps + +After downloading, follow the [Quick Start](quickstart.md) guide to run the +deployment stack in MuJoCo simulation or on real hardware. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/getting_started/installation_deploy.md b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/installation_deploy.md new file mode 100644 index 0000000000000000000000000000000000000000..5b55a06e4307b1d97d024268d0a293b519d49439 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/installation_deploy.md @@ -0,0 +1,145 @@ +# Installation (Deployment) + +## Prerequisites + +**Required for all setups:** +- **Ubuntu 20.04/22.04/24.04** or other Debian-based Linux distributions +- **CUDA Toolkit** (for GPU acceleration) +- **TensorRT** (for inference optimization) — **Install this first!** +- **Jetpack 6** (for onboard deployment) +- Python 3.8+ +- Git with LFS support + +**Download TensorRT** from [NVIDIA Developer](https://developer.nvidia.com/tensorrt/download/10x): + +| Platform | TensorRT Version | +|---|---| +| x86_64 (Desktop) | **10.13** (required) | +| Jetson / G1 onboard Orin | **10.7** (required; requires JetPack 6 — [flashing guide](../references/jetpack6.md)) | + +```{tip} +Download the **TAR** package (not the DEB one) so you can extract TensorRT to any location. The archive is ~10 GB; consider using `pv` to monitor progress: +``` + +```{danger} +You **must** use the exact TensorRT versions listed above. Using a different version is known to produce incorrect inference results — the planner will output wrong motion, which can cause dangerous robot behavior. +``` + +```sh +sudo apt-get install -y pv +pv TensorRT-*.tar.gz | tar -xz -f - +``` + +Move the unzipped TensorRT to `~/TensorRT` (or similar) and add to your `~/.bashrc`: + +```sh +export TensorRT_ROOT=$HOME/TensorRT +``` + +## Clone the Repository + +```bash +git clone https://github.com/NVlabs/GR00T-WholeBodyControl.git +cd GR00T-WholeBodyControl +git lfs pull # make sure all large files are fetched +``` + +## Setup + +### Native Development (Recommended) + +**Advantages:** Direct system installation, faster builds, production-ready. + +```{warning} +For G1 onboard deployment, we require the onboard Orin to be upgraded to Jetpack 6 to support TensorRT. Please follow the [flashing guide](../references/jetpack6.md) for upgrading! +``` + +**Prerequisites:** +- Basic development tools (cmake, git, etc.) +- (Optional) ROS2 if you plan to use ROS2-based input/output + +**Setup steps:** + +1. **Install system dependencies:** + +```sh +cd gear_sonic_deploy +chmod +x scripts/install_deps.sh +./scripts/install_deps.sh +``` + +2. **Set up environment:** + +```sh +source scripts/setup_env.sh +``` + +The setup script will automatically: +- Configure TensorRT environment +- Set up all necessary paths + +For convenience, you can add the environment setup to your shell profile: + +```sh +echo "source $(pwd)/scripts/setup_env.sh" >> ~/.bashrc +``` + +3. **Build the project:** + +```sh +just build +``` + +### Docker (ROS2 Development Environment) + +We provide a unified Docker environment with ROS2 Humble, supporting x86_64 and Jetson platforms. + +**Prerequisites:** +- Docker installed and user added to docker group +- `TensorRT_ROOT` environment variable set on host +- For Jetson: JetPack 6.1+ (CUDA 12.6) + +**Quick Setup:** + +```sh +# 1. Add user to docker group (one-time setup) +sudo usermod -aG docker $USER +newgrp docker + +# 2. Set TensorRT path (add to ~/.bashrc for persistence) +export TensorRT_ROOT=/path/to/TensorRT + +# 3. Launch container +cd gear_sonic_deploy +./docker/run-ros2-dev.sh +``` + +**Options:** + +```sh +./docker/run-ros2-dev.sh # Standard build (fast) +./docker/run-ros2-dev.sh --rebuild # Force rebuild +./docker/run-ros2-dev.sh --with-opengl # Include OpenGL for visualization (RViz, Gazebo) +``` + +**Architecture Support:** +- **x86_64**: CUDA 12.4.1 (requires NVIDIA driver 550+) +- **Jetson**: CUDA 12.4.1 container on CUDA 12.6 host (forward compatible) + +**Inside the container:** + +```sh +source scripts/setup_env.sh # set up dependency +just build # Build +just --list # Show all commands +``` + +**Troubleshooting:** +- If you get "permission denied", ensure you're in the docker group +- TensorRT must be set on the **host** before starting container +- For Jetson: Run `source scripts/setup_env.sh` on host first (sets jetson_clocks) + + + + + diff --git a/third-party/GR00T-WholeBodyControl/docs/source/getting_started/installation_training.md b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/installation_training.md new file mode 100644 index 0000000000000000000000000000000000000000..e19321040bd11f99f1aeeca3670e40fd08af6a7e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/installation_training.md @@ -0,0 +1,125 @@ +# Installation (Training) + +This guide walks through setting up the SONIC training environment for whole-body humanoid control. + +## Prerequisites + +- **GPU**: NVIDIA GPU with CUDA 12.x (L40 recommended) +- **OS**: Ubuntu 22.04+ +- **Python**: 3.11 (required by Isaac Lab; sim/teleop/deploy scripts work on 3.10+) +- **Isaac Lab**: 2.3+ (required for simulation environments) + +## Install Isaac Lab + +SONIC training uses Isaac Lab for physics simulation. Follow the official +[Isaac Lab installation guide](https://isaac-sim.github.io/IsaacLab/main/source/setup/installation/index.html) +to install Isaac Lab. + +After installation, verify: + +```bash +python -c "import isaaclab; print(isaaclab.__version__)" +``` + +## Install gear_sonic (Training) + +From the repository root: + +```bash +pip install -e "gear_sonic/[training]" +``` + +This installs the training dependencies (Hydra, W&B, HuggingFace TRL, etc.) +on top of the Isaac Lab environment. + +## Download Model and Data from Hugging Face + +SONIC model checkpoints and SMPL motion data are hosted on +[Hugging Face](https://huggingface.co/nvidia/GEAR-SONIC). + +```bash +pip install huggingface_hub +python download_from_hf.py --training +``` + +This downloads: + +- **PyTorch checkpoint** (`sonic_release/last.pt`) for finetuning +- **SMPL motion data** (`data/smpl_filtered/`) for the SMPL encoder + +## Prepare Robot Motion Data + +SONIC trains on the [Bones-SEED](https://huggingface.co/datasets/bones-studio/seed) motion capture dataset +(142K+ motion sequences retargeted to the Unitree G1). + +### Step 1: Download and convert + +Download the **G1 retargeted CSVs** (29 DOF, 120 FPS) from +[Bones-SEED on HuggingFace](https://huggingface.co/datasets/bones-studio/seed), then convert: + +```bash +python gear_sonic/data_process/convert_soma_csv_to_motion_lib.py \ + --input /path/to/bones_seed/g1/csv/ \ + --output data/motion_lib_bones_seed/robot \ + --fps 30 --fps_source 120 --individual --num_workers 16 +``` + +### Step 2: Filter motions + +Remove motions the G1 robot cannot perform: + +```bash +python gear_sonic/data_process/filter_and_copy_bones_data.py \ + --source data/motion_lib_bones_seed/robot \ + --dest data/motion_lib_bones_seed/robot_filtered --workers 16 +``` + +This removes ~8.7% of motions (~130K of 142K remain). See the +[Training Guide](../user_guide/training.md) for details. + +Your data directory should look like: + +``` +/ +├── data/ +│ ├── motion_lib_bones_seed/ +│ │ └── robot_filtered/ # Filtered G1 motions (~130K PKLs) +│ └── smpl_filtered/ # SMPL motion data (from Hugging Face) +└── sonic_release/ # Released checkpoint (from Hugging Face) +``` + +> **Note**: Data processing scripts (`gear_sonic/data_process/`) do **not** require +> Isaac Lab and can be run on any machine with `pip install -e gear_sonic/`. + +## Verify Installation + +First, run the pre-flight check to verify all dependencies: + +```bash +python check_environment.py --training +``` + +Then run a quick smoke test with a small number of environments: + +```bash +# Interactive (with viewer) +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=16 headless=False \ + ++algo.config.num_learning_iterations=5 + +# Headless (server / no display) +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=16 headless=True \ + ++algo.config.num_learning_iterations=5 +``` + +After a minute of initialization you should see training metrics (rewards, errors) +printing to the console. + +## Full Training + +Once installation is verified, see the [Training Guide](../user_guide/training.md) +for full training commands (64+ GPU recommended), evaluation, ONNX export, and +SOMA encoder setup. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/getting_started/quickstart.md b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/quickstart.md new file mode 100644 index 0000000000000000000000000000000000000000..43383a4887734bacd1ee3e7547ac778a49693ba5 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/quickstart.md @@ -0,0 +1,155 @@ +# Quick Start + +Get started with SONIC in minutes! + +```{admonition} Prerequisites +:class: note +1. **Completed the [Installation Guide](installation_deploy)** — TensorRT is installed, the repo is cloned, and the C++ deployment is built. +2. **Downloaded the model checkpoints** — run `python download_from_hf.py` from the repo root. See [Downloading Model Checkpoints](download_models) for details. +``` + +```{admonition} Safety Warning +:class: danger +Robots can be dangerous. Ensure a clear safety zone, keep a safety operator ready to trigger an emergency stop in front of the keyboard, and use this software at your own risk. The authors and contributors are not responsible for any damage, injury, or loss caused by use or misuse of this project. +``` + +## Isaac Lab Eval + +Use Isaac Lab to sanity-check the released PyTorch checkpoint in simulation. Run these commands from the repo root inside your Isaac Lab Python environment. + +If you only downloaded the deployment ONNX files, first fetch the eval checkpoint and the small sample motion set: + +```sh +python download_from_hf.py --training --no-smpl +python download_from_hf.py --sample +``` + +To open the Isaac Sim viewer and watch the policy: + +```sh +python gear_sonic/eval_agent_trl.py \ + +checkpoint=sonic_release/last.pt \ + +headless=False \ + ++num_envs=1 \ + ++manager_env.observations.policy.enable_corruption=False \ + ++manager_env.observations.tokenizer.enable_corruption=False \ + "++manager_env.commands.motion.motion_lib_cfg.motion_file=sample_data/robot_filtered" \ + "++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=sample_data/smpl_filtered" +``` + +Leave this running while you inspect the viewer, then stop it with `Ctrl+C`. + +For a quick metrics run: + +```sh +python gear_sonic/eval_agent_trl.py \ + +checkpoint=sonic_release/last.pt \ + +headless=True \ + ++eval_callbacks=im_eval \ + ++run_eval_loop=False \ + ++num_envs=128 \ + ++manager_env.observations.policy.enable_corruption=False \ + ++manager_env.observations.tokenizer.enable_corruption=False \ + "+manager_env/terminations=tracking/eval" \ + "++manager_env.commands.motion.motion_lib_cfg.max_unique_motions=512" \ + "++manager_env.commands.motion.motion_lib_cfg.motion_file=sample_data/robot_filtered" \ + "++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=sample_data/smpl_filtered" +``` + +To render videos instead: + +```sh +python gear_sonic/eval_agent_trl.py \ + +checkpoint=sonic_release/last.pt \ + +headless=True \ + ++eval_callbacks=im_eval \ + ++run_eval_loop=False \ + ++num_envs=8 \ + ++manager_env.config.render_results=True \ + "++manager_env.config.save_rendering_dir=/tmp/sonic_renders" \ + ++manager_env.config.env_spacing=10.0 \ + "~manager_env/recorders=empty" "+manager_env/recorders=render" \ + ++manager_env.observations.policy.enable_corruption=False \ + ++manager_env.observations.tokenizer.enable_corruption=False \ + "++manager_env.commands.motion.motion_lib_cfg.motion_file=sample_data/robot_filtered" \ + "++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=sample_data/smpl_filtered" +``` + +Videos are written to `/tmp/sonic_renders`. For full-dataset evaluation and expected metrics, see the [Training Guide](../user_guide/training.md#evaluation). + + +## Sim2Sim in MuJoCo + + + +For testing in a MuJoCo simulator, run the simulation loop and deployment script in separate terminals. + +```{note} +The MuJoCo simulator (Terminal 1) runs on the **host** in a Python virtual environment — it is **not** inside the Docker container. The deployment binary (Terminal 2) can run either natively on the host or inside the Docker container. If you are using Docker, run Terminal 1 on the host and Terminal 2 inside the container. +``` + +### One-time setup: install the MuJoCo sim environment + +On the **host** (outside Docker), from the **repo root** (`GR00T-WholeBodyControl/`), run: + +```sh +bash install_scripts/install_mujoco_sim.sh +``` + +This creates a lightweight `.venv_sim` virtual environment with only the packages needed for the simulator (MuJoCo, Pinocchio, Unitree SDK2, etc.). + +### Running the sim2sim loop + +We highly recommend running through this process and getting familiar with the controls in simulation before deploying on real hardware. + +**Terminal 1 — MuJoCo simulator** (host, from repo root): + +```sh +source .venv_sim/bin/activate +python gear_sonic/scripts/run_sim_loop.py +``` + +**Terminal 2 — Deployment** (host or Docker, from `gear_sonic_deploy/`): + +```sh +bash deploy.sh sim +``` + +**Starting Control:** + +1. In Terminal 2 (deploy.sh), press **`]`** to start the policy. +2. Click on the MuJoCo viewer window, press **`9`** to drop the robot to the ground. +3. Go back to Terminal 2. Press **`T`** to play the current reference motion — the robot will execute it to completion. +4. Press **`N`** or **`P`** to switch to the next or previous motion sequence. +5. Press **`T`** again to play the new motion. +6. You can press **`T`** again to replay the same motion once it has finished. If you want to stop and go back to the first frame of the current motion, press **`R`** to restart it from the beginning. This can be used to stop the motion without terminating the policy. +7. When you are done or need an **emergency stop**, press **`O`** to stop control and exit. + +For more controls, see the tutorials for [Keyboard](../tutorials/keyboard.md), [Gamepad](../tutorials/gamepad.md), [ZMQ Streaming](../tutorials/zmq.md), and [Interface Manager](../tutorials/manager.md). + +## Real Robot + +To deploy on the real G1 robot, run: + +```sh +./deploy.sh real +``` + +## Online Visualization + +Start the visualizer and connect to a running `g1_deploy` executable: + +```sh +python visualize_motion.py --realtime_debug_url tcp://localhost:5557 +``` + +Notes: +- Default port: 5557 (change with `--zmq-out-port `) +- Default topic: `g1_debug` (change with `--zmq-out-topic ` on executable, `--realtime_debug_topic ` on visualizer) +- For physical robots, replace `localhost` with the robot's IP address + +For offline motion CSV visualization and logging details, see [Deployment Code & Program Flow](../references/deployment_code.md). + +For more advanced usage, see the tutorials for [Keyboard](../tutorials/keyboard.md), [Gamepad](../tutorials/gamepad.md), [ZMQ Streaming](../tutorials/zmq.md), [VR Whole-Body Teleop](../tutorials/vr_wholebody_teleop.md), and [Interface Manager](../tutorials/manager.md). diff --git a/third-party/GR00T-WholeBodyControl/docs/source/getting_started/vr_teleop_setup.md b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/vr_teleop_setup.md new file mode 100644 index 0000000000000000000000000000000000000000..e31ea1403cf548096230c1484c80ddb0cdcd8c11 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/getting_started/vr_teleop_setup.md @@ -0,0 +1,151 @@ +# VR Teleop Setup (PICO) + +This page covers the one-time hardware and software setup for PICO VR whole-body teleoperation. After completing these steps, proceed to the [ZMQ Manager tutorial](../tutorials/vr_wholebody_teleop.md) to run teleop in sim or on real hardware. + +--- + +## Required Hardware + +- [PICO 4 / PICO 4 Pro headset](https://www.picoxr.com/global/products/pico4) +- [2x PICO controllers](https://www.picoxr.com/global/products/pico4) +- [2x PICO motion trackers](https://www.picoxr.com/global/products/pico-motion-tracker) (strapped to ankles) +- A high-speed, low-latency Wi-Fi connection; teleoperation performance is heavily dependent on network quality. + +--- + +## Step 1: Install XRoboToolkit + +XRoboToolkit consists of a PC service (running on your workstation) and a PICO app (running on the headset) that streams body-tracking data. + +### PC Service + +The PC service must be installed and running on your workstation **before** the PICO can connect. + +**Ubuntu 22.04 (x86_64 workstation):** + +```bash +wget https://github.com/XR-Robotics/XRoboToolkit-PC-Service/releases/download/v1.0.0/XRoboToolkit_PC_Service_1.0.0_ubuntu_22.04_amd64.deb +sudo dpkg -i XRoboToolkit_PC_Service_1.0.0_ubuntu_22.04_amd64.deb +``` + +**Ubuntu 24.04 (x86_64 workstation):** + +```bash +wget https://github.com/XR-Robotics/XRoboToolkit-PC-Service/releases/download/v1.0.0/XRoboToolkit_PC_Service_1.0.0_ubuntu_24.04_amd64.deb +sudo dpkg -i XRoboToolkit_PC_Service_1.0.0_ubuntu_24.04_amd64.deb +``` + +**Jetson (aarch64, onboard):** + +```bash +sudo dpkg -i gear_sonic_deploy/thirdparty/roboticsservice_1.0.0.0_arm64.deb +``` + +See [XRoboToolkit-PC-Service releases](https://github.com/XR-Robotics/XRoboToolkit-PC-Service/releases) for other platforms or newer versions. + +### PICO App + +1. Wear the PICO headset to begin the setup and installation process. +2. Complete the quick setup on PICO. +3. Make sure the PICO is connected to Wi-Fi. +4. Open the browser application in the PICO. +5. Type **"xrobotoolkit"** in the search bar and select the GitHub page [https://github.com/XR-Robotics](https://github.com/XR-Robotics). + +```{image} ../_static/pico_setup/google_search_screenshot.png +:width: 600px +:align: center +``` + +6. Make sure **Developer Mode** is enabled (Settings → Developer). +7. **[INSIDE PICO]** Scroll down in the GitHub page until you see the APK download option and click with the PICO trigger to download it. + +```{tip} +Download [XRoboToolkit-PICO-1.1.1.apk](https://github.com/XR-Robotics/XRoboToolkit-Unity-Client/releases/download/v1.1.1/XRoboToolkit-PICO-1.1.1.apk) on PICO using the browser. ([Other Versions](https://github.com/XR-Robotics/XRoboToolkit-Unity-Client/releases)) +``` + +8. **[INSIDE PICO]** Open the manage downloads option on the top right section of the browser page and click to open the `XRoboToolkit-PICO-1.1.1.apk` download. +9. **[INSIDE PICO]** Select **Install** — the application will appear in the **Unknown** section of your library. + +--- + +## Step 2: Motion Tracker Setup + +```{image} ../_static/pico_setup/pico_setup_screenshot.png +:width: 600px +:align: center +``` + +1. Strap one PICO motion tracker to your left ankle and one to your right ankle. **Scrunch** down any baggy clothing so the trackers are visible. Make sure the side with the light indicator faces up. +2. Go to PICO settings. In the menu on the left, scroll down to the last option: **"Developer"**. Make sure **"Safeguard"** is turned off. + - If the Developer option is not active, tap on "Software" until it appears. +3. Click the **Wi-Fi icon** in the PICO menu. A picture of the headset will appear. Above the headset, there will be a small circular logo for the motion trackers. If there is no logo, open the **"Motion Tracker"** app itself. + - Headset and 2 controllers will populate — select **Motion Tracker** (small circle). +4. Next to each tracker, there is an **"i"** icon. Click on this and **unpair all trackers**. +5. Once all trackers are cleared, click the **"Pair"** button in the top right corner. +6. Press and hold the button on the top of each motion tracker for **6 seconds**. Once in pairing mode, the lights will flash red and blue. + +### Motion Tracker Calibration + +1. Wear the PICO headset over your eyes. +2. Press the blue **"Calibrate"** button and follow the two calibration sequences: + - **Sequence 1:** Stand stiff with the handheld controllers down by your sides. + - **Sequence 2:** Look down at the foot motion trackers until the headset cameras recognize them. +3. Once calibrated, wear the PICO headset around your forehead (ensuring PICO faces forward to continue detecting motion trackers). + +--- + +## Step 3: Install the PICO Teleop Environment + +From the **repo root**: + +```bash +bash install_scripts/install_pico.sh +``` + +This creates a `.venv_teleop` virtual environment (Python 3.10) that includes: +- `teleop` extra (ZMQ, Pinocchio, PyVista) +- `sim` extra (MuJoCo, tyro) +- XRoboToolkit SDK +- Unitree SDK2 Python bindings + +Activate it with: + +```bash +source .venv_teleop/bin/activate # prompt: (gear_sonic_teleop) +``` + +--- + +## Step 4: Connect the PICO to Your Workstation + +1. Open the Wi-Fi settings on both the laptop/PC and PICO and ensure they are on the **same Wi-Fi network**. Take note of the Wi-Fi IPv4 address. + - To find the PICO's Wi-Fi, select the control center on the bottom right of the menu. + +```{image} ../_static/pico_setup/internet.png +:width: 600px +:align: center +``` + +```{image} ../_static/pico_setup/pico_vr_screenshot.png +:width: 600px +:align: center +``` + +2. Open the **XRoboToolKit** application. Enter the IP address of the laptop by clicking **"Enter"** next to "PC Service:". You will know it is properly connected if **WORKING** appears next to "Status:". + - If your IP address is already inputted, select **"Reconnect"** where it says "Status:" in the Network section. + +3. Make sure the following boxes are ticked as shown in the picture below: + - **"Head"** and **"Controller"** under the "Tracking" section. + - For Data/Control, make sure to select the **"Send"** button. + - For "Pico Motion Tracker" make sure to select **"Full body"**. + +```{image} ../_static/pico_setup/xrrobot_setup.png +:width: 600px +:align: center +``` + +--- + +## Next Steps + +Your PICO hardware and software are now ready. Proceed to the [ZMQ Manager (`zmq_manager`) tutorial](../tutorials/vr_wholebody_teleop.md) to run whole-body teleoperation in simulation or on the real robot. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/index.rst b/third-party/GR00T-WholeBodyControl/docs/source/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..37d2d756d89960c072d480db8060b3f3d45edf3f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/index.rst @@ -0,0 +1,157 @@ +GR00T-WholeBodyControl Documentation +==================================== + +.. image:: https://img.shields.io/badge/License-Apache%202.0%20%7C%20NVIDIA%20Open%20Model-blue.svg + :target: resources/license.html + :alt: License + +.. image:: https://img.shields.io/badge/IsaacLab-2.3.0-blue.svg + :target: https://github.com/isaac-sim/IsaacLab/releases/tag/v2.3.0 + :alt: IsaacLab + +Welcome to the official documentation for **GR00T Whole-Body Control (WBC)**! This is a unified platform for developing and deploying advanced humanoid controllers. + + +What is GR00T-WholeBodyControl? +-------------------------------- + +This codebase serves as the foundation for: + +- **Decoupled WBC** models used in NVIDIA Isaac-Gr00t, Gr00t N1.5 and N1.6 (see :doc:`detailed reference `) +- **GEAR-SONIC Series**: State-of-the-art controllers from the GEAR team + +News +---- + +- **[2026-07-23]** **SONIC v1.1 checkpoint** — released a robot-heading-normalized SONIC controller trained with wrist-pose augmentation for whole-body teleoperation and SONIC-backed VLA execution. See the `Model Card `_ and `Download Models `_. +- **[06/16]** **Isaac Teleop Setup (CloudXR / DeviceIO, in-process)** — added bring-up docs for the in-process CloudXR path via ``isaacteleop[cloudxr]``, with no separate publisher container. See `Isaac Teleop Setup `_. +- **[2026-06-16]** **Low-latency teleoperation checkpoint** — released a SONIC checkpoint with 4-frame SMPL reference lookahead for more responsive whole-body teleoperation. See the `Model Card `_, `Download Models `_, and `VLA Inference `_ for usage. +- **[2026-05-07]** **End-to-end VLA workflow on G1** — collect teleop data, fine-tune Isaac-GR00T N1.7, and deploy with SONIC whole-body control. See `Data Collection `_, `VLA Workflow `_, and `VLA Inference `_. +- **[2026-04-14]** `Live web demo `_ — try SONIC interactively in your browser. Features `Kimodo `_ text-to-motion generation. +- **[2026-04-10]** Released **SONIC training code and checkpoint** on `HuggingFace `_. Train from scratch or finetune. **Additional embodiment support** and **VLA data collection pipeline**. See `Training Guide `_. +- **[2026-03-24]** C++ inference stack update: motor error monitoring, TTS alerts, ZMQ protocol v4, idle-mode readaptation. **ZMQ header size changed to 1280 bytes.** +- **[2026-03-16]** `BONES-SEED `_ open-sourced — 142K+ human motions (~288 hours) with G1 MuJoCo trajectories. +- **[2026-02-19]** Released GEAR-SONIC: pretrained checkpoints, C++ inference, VR teleoperation, and documentation. +- **[2025-11-12]** Initial release with Decoupled WBC for GR00T N1.5 and N1.6. + +GEAR-SONIC +---------- +.. image:: _static/sonic-preview-gif-480P.gif + :width: 100% + :align: center + + +.. raw:: html + +

+ Website + Paper + GitHub +

+ +**SONIC** is a humanoid behavior foundation model that gives robots a core set of motor skills learned from large-scale human motion data. Rather than building separate controllers for every motion, SONIC uses motion tracking as a scalable training task so a single unified policy can produce natural, whole-body movement and support a wide range of behaviors. + +🎯 Key Features: + +- 🚶 Natural whole-body locomotion (walking, crawling, dynamic movements) +- 🎮 Real-time VR teleoperation support +- 🤖 Foundation for higher-level planning and interaction +- 📦 Ready-to-deploy C++ inference stack + +Quick Start: Sim2Sim +-------------------- + +Quickly test the SONIC deployment stack in MuJoCo before deploying on real hardware. + +.. raw:: html + + + +.. tip:: + + **Get running in minutes!** Follow the :doc:`Installation ` and :doc:`Quickstart ` guides to see this in action on your machine. + +Documentation +------------- + +.. toctree:: + :maxdepth: 2 + :caption: Getting Started + + model_card + getting_started/installation_deploy + getting_started/download_models + getting_started/quickstart + getting_started/vr_teleop_setup + +.. toctree:: + :maxdepth: 2 + :caption: Tutorials + + tutorials/keyboard + tutorials/gamepad + tutorials/zmq + tutorials/manager + tutorials/isaac_teleop_publisher_setup + tutorials/vr_wholebody_teleop + tutorials/live_camera_teleop + tutorials/data_collection + tutorials/vla_workflow + tutorials/vla_inference + +.. toctree:: + :maxdepth: 2 + :caption: Training + + getting_started/installation_training + user_guide/training + user_guide/training_data + user_guide/new_embodiments + +.. toctree:: + :maxdepth: 2 + :caption: Best Practices + + user_guide/teleoperation + user_guide/troubleshooting + +.. toctree:: + :maxdepth: 2 + :caption: API Reference + +.. api/index +.. api/teleop + +.. toctree:: + :maxdepth: 2 + :caption: Reference Documentation + + references/index + user_guide/configuration + references/conventions + references/training_code + references/deployment_code + references/observation_config + references/motion_reference + references/planner_onnx + references/jetpack6 + references/decoupled_wbc + + +.. toctree:: + :maxdepth: 1 + :caption: Additional Resources + + resources/citations + resources/license + resources/support +.. resources/contributing + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/model_card.md b/third-party/GR00T-WholeBodyControl/docs/source/model_card.md new file mode 100644 index 0000000000000000000000000000000000000000..3bf2bd3bb72bb2e78dee7350ce99b497518dd8b1 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/model_card.md @@ -0,0 +1,140 @@ +# Model Card + +SONIC provides three released whole-body controller checkpoints for the +Unitree G1. Choose the model based on its reference representation and intended +deployment. + +## Available Models + +| Model | Hugging Face location | SMPL reference input | Intended use and comments | +|---|---|---|---| +| **Default SONIC (original release)** | Top-level `model_encoder.onnx`, `model_decoder.onnx`, and `observation_config.yaml`; training checkpoint at `sonic_release/last.pt` | 10 future frames at 20 ms spacing, approximately 200 ms of reference lookahead | Default general-purpose SONIC controller for motion tracking, planning, teleoperation, and compatibility with existing deployments. G1 and teleoperation future-reference observations use `step5`. | +| **Low-latency teleoperation** | [`low_latency/`](https://huggingface.co/nvidia/GEAR-SONIC/tree/main/low_latency) | 4 future frames at 20 ms spacing, approximately 80 ms of reference lookahead | Intended for more responsive whole-body teleoperation and VLA execution. G1 and teleoperation future-reference observations use `step1`. Use its encoder, decoder, and observation config together. | +| **SONIC v1.1** | [`sonic_v1_1/`](https://huggingface.co/nvidia/GEAR-SONIC/tree/main/sonic_v1_1) | 10 future frames at 20 ms spacing, approximately 200 ms of reference lookahead | Uses robot-heading-normalized target orientation and was trained with wrist-pose augmentation. Intended for heading-stable whole-body teleoperation and SONIC-backed VLA policies that use this controller. G1 and teleoperation future-reference observations use `step5`; this is not the low-latency model. | + +```{image} _static/sonic_v1_1_demo.gif +:alt: SONIC v1.1 whole-body teleoperation demo +:width: 100% +:align: center +``` + +*SONIC v1.1: Whole-body teleoperation mode with expressive wrist motion and +dynamic movement.* + +All three models use the SONIC universal-token controller, produce 64-dimensional +latent motion tokens, run the controller at 50 Hz, and support SMPL pose, G1 +motion reference, and teleoperation inputs. Deployment uses C++ and TensorRT; the +PyTorch checkpoints support Isaac Lab evaluation and continued training. + +```{note} +The lookahead values describe the reference horizon presented to the +controller. They are not measurements of total end-to-end teleoperation +latency, which also includes sensing, networking, preprocessing, and inference. +``` + +## Released Files + +| Model | Deployment files | PyTorch and configuration files | +|---|---|---| +| Default SONIC | `model_encoder.onnx`, `model_decoder.onnx`, `observation_config.yaml` | `sonic_release/last.pt`, `sonic_release/config.yaml` | +| Low-latency teleoperation | `low_latency/model_encoder.onnx`, `low_latency/model_decoder.onnx`, `low_latency/observation_config.yaml` | `low_latency/last.pt`, `low_latency/config.yaml`, `low_latency/model_config.yaml` | +| SONIC v1.1 | `sonic_v1_1/model_encoder.onnx`, `sonic_v1_1/model_decoder.onnx`, `sonic_v1_1/observation_config.yaml` | `sonic_v1_1/last.pt`, `sonic_v1_1/config.yaml`, `sonic_v1_1/model_config.yaml` | + +All files are hosted in +[`nvidia/GEAR-SONIC`](https://huggingface.co/nvidia/GEAR-SONIC). Model weights +are covered by the [NVIDIA Open Model License](resources/license.md). + +## Choosing a Model + +Use **Default SONIC** when you want the original release, the broadest +compatibility with existing deployment setups, or the standard motion-tracking +and planning controller. + +Use **Low-latency teleoperation** when responsiveness to streamed SMPL, VR, or +VLA commands is the priority. Its shorter reference horizon reduces commanded +motion lookahead, but it does not remove latency elsewhere in the system. + +Use **SONIC v1.1** for robot-heading-normalized whole-body +teleoperation or a SONIC-backed VLA policy trained against this controller. It +retains the 10-frame SMPL horizon and was trained with wrist-pose augmentation. + +## Usage + +Install the Hugging Face dependency from the repository root: + +```bash +pip install huggingface_hub +``` + +### Default SONIC + +```bash +python download_from_hf.py + +cd gear_sonic_deploy +./deploy.sh --input-type zmq_manager real +``` + +### Low-Latency Teleoperation + +```bash +python download_from_hf.py --low-latency + +cd gear_sonic_deploy +./deploy.sh \ + --cp policy/low_latency/model \ + --obs-config policy/low_latency/observation_config.yaml \ + --input-type zmq_manager \ + real +``` + +### SONIC v1.1 + +```bash +python download_from_hf.py --sonic-v1-1 + +cd gear_sonic_deploy +./deploy.sh \ + --cp policy/sonic_v1_1/model \ + --obs-config policy/sonic_v1_1/observation_config.yaml \ + --input-type zmq_manager \ + real +``` + +### Python VLA Launcher + +For the default model: + +```bash +python gear_sonic/scripts/launch_inference.py \ + --camera-host 192.168.123.164 \ + --prompt "pick up the cup" +``` + +For the low-latency model: + +```bash +python gear_sonic/scripts/launch_inference.py \ + --deploy-checkpoint policy/low_latency/model \ + --deploy-obs-config policy/low_latency/observation_config.yaml \ + --camera-host 192.168.123.164 \ + --prompt "pick up the cup" +``` + +For SONIC v1.1, replace the two `policy/low_latency/` paths above with +`policy/sonic_v1_1/`. + +See [Downloading Model Checkpoints](getting_started/download_models.md) for +PyTorch checkpoint evaluation and additional download options. + +## Limitations and Safety + +- The low-latency name refers to reduced controller reference lookahead, not a + benchmark of total system latency. +- SONIC v1.1 is not a low-latency checkpoint; it uses the + 10-frame SMPL reference horizon. +- Each ONNX encoder and decoder must be used with its matching observation + configuration. +- These checkpoints target the Unitree G1 embodiment. +- Test in simulation before deployment and keep a safety operator ready to + stop a physical robot. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/conventions.md b/third-party/GR00T-WholeBodyControl/docs/source/references/conventions.md new file mode 100644 index 0000000000000000000000000000000000000000..01d15b1f746b67463fe819f2e9cc35c6601d48fb --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/conventions.md @@ -0,0 +1,142 @@ +# Coordinate Frame and Rotation Conventions + +This page documents the coordinate frame, quaternion, and rotation conventions +used throughout the SONIC codebase. Getting these wrong causes silent bugs — +the robot will move but in the wrong direction or with wrong orientation. + +## Coordinate Frames + +### Isaac Lab / MuJoCo (simulation) + +- **Z-up**: Gravity is along -Z. Ground plane is XY. +- **Right-handed**: X forward, Y left, Z up. +- This is the convention used during training and evaluation. + +### SMPL / BVH (human motion data) + +- **Y-up**: Gravity is along -Y. Ground plane is XZ. +- When loading SMPL or BVH data, set `smpl_y_up: true` in the motion library + config. The motion library automatically converts Y-up to Z-up internally. + +### Summary + +| System | Up axis | Convention | +|--------|---------|------------| +| Isaac Lab | Z | Z-up, right-handed | +| MuJoCo | Z | Z-up, right-handed | +| SMPL body model | Y | Y-up | +| BVH motion files | Y | Y-up | +| Retargeted PKL data | Z | Z-up (already converted) | + +## Quaternion Convention + +### Scalar-first (wxyz) — default throughout SONIC + +The SONIC codebase uses **scalar-first (wxyz)** quaternions everywhere: + +``` +q = [w, x, y, z] +``` + +This applies to: + +- `gear_sonic/trl/utils/torch_transform.py` — all rotation utilities +- `gear_sonic/isaac_utils/rotations.py` — Isaac Lab rotation helpers (use `w_last=False`) +- Isaac Lab APIs (`body_quat_w`, `root_quat_w`, etc.) +- Motion library internal storage +- Retargeted PKL data (`root_rot` field) + +### Scalar-last (xyzw) — scipy only + +[SciPy's Rotation class](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.html) +uses **scalar-last (xyzw)** convention: + +``` +q = [x, y, z, w] +``` + +This is only used in the **data processing scripts** (`data_process/`) when +calling `scipy.spatial.transform.Rotation`. The scripts convert to wxyz +before saving: + +```python +# In data processing (scipy xyzw → wxyz for storage) +root_quat_xyzw = Rotation.from_euler("xyz", euler_angles).as_quat() # scipy: xyzw +root_quat_wxyz = root_quat_xyzw[:, [3, 0, 1, 2]] # convert to wxyz +``` + +### The `w_last` parameter + +Functions in `gear_sonic/isaac_utils/rotations.py` accept a `w_last` boolean: + +```python +quat_rotate(q, v, w_last=False) # q is wxyz (scalar-first) — this is the default +quat_rotate(q, v, w_last=True) # q is xyzw (scalar-last) +``` + +**Always use `w_last=False`** unless you're interfacing with scipy or a system +that explicitly uses xyzw. + +### Quick reference + +| System | Convention | Order | Identity | +|--------|-----------|-------|----------| +| SONIC (torch_transform.py) | wxyz | `[w, x, y, z]` | `[1, 0, 0, 0]` | +| Isaac Lab | wxyz | `[w, x, y, z]` | `[1, 0, 0, 0]` | +| SciPy | xyzw | `[x, y, z, w]` | `[0, 0, 0, 1]` | +| MuJoCo | wxyz | `[w, x, y, z]` | `[1, 0, 0, 0]` | +| ROS | xyzw | `[x, y, z, w]` | `[0, 0, 0, 1]` | + +### Converting between conventions + +```python +# wxyz → xyzw +q_xyzw = q_wxyz[..., [1, 2, 3, 0]] + +# xyzw → wxyz +q_wxyz = q_xyzw[..., [3, 0, 1, 2]] +``` + +## Rotation Representations + +The codebase uses multiple rotation representations depending on context: + +| Representation | Shape | Used in | +|---------------|-------|---------| +| Quaternion (wxyz) | `(..., 4)` | Simulation, motion library, observations | +| Axis-angle | `(..., 3)` | `pose_aa` field in motion PKLs | +| Rotation matrix | `(..., 3, 3)` | Forward kinematics, 6D rotation encoding | +| 6D rotation | `(..., 6)` | Some observation terms (first 2 columns of rotation matrix) | +| Euler angles | `(..., 3)` | CSV motion data input (converted immediately) | + +### Axis-angle in motion data + +The `pose_aa` field in retargeted PKL files stores per-body **local** rotations +as axis-angle vectors. The direction is the rotation axis, the magnitude is +the angle in radians: + +```python +pose_aa # (T, num_bodies, 3) — axis-angle per body, MuJoCo body order +``` + +## Joint Ordering + +Isaac Lab and MuJoCo traverse the kinematic tree in different orders. The +codebase provides bidirectional index mappings per robot: + +```python +from gear_sonic.envs.manager_env.robots.g1 import ( + G1_ISAACLAB_TO_MUJOCO_DOF, # Reorder DOFs: IsaacLab → MuJoCo + G1_MUJOCO_TO_ISAACLAB_DOF, # Reorder DOFs: MuJoCo → IsaacLab +) + +# Convert joint positions from IsaacLab order to MuJoCo order: +mujoco_joints = isaaclab_joints[..., G1_ISAACLAB_TO_MUJOCO_DOF] +``` + +Motion PKL data (`dof`, `pose_aa`) is stored in **MuJoCo order**. Isaac Lab +simulation uses **IsaacLab order**. The training pipeline handles the conversion +automatically via `order_converter.py`. + +See [Training on New Embodiments](../user_guide/new_embodiments.md) for how to +define these mappings for a new robot. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/decoupled_wbc.md b/third-party/GR00T-WholeBodyControl/docs/source/references/decoupled_wbc.md new file mode 100644 index 0000000000000000000000000000000000000000..2ff38a02dc1ff12a55177fbe9b829b5802cec41f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/decoupled_wbc.md @@ -0,0 +1,155 @@ +# Decoupled WBC + +Software stack for loco-manipulation experiments across multiple humanoid platforms, with primary support for the Unitree G1. This repository provides whole-body control policies, a teleoperation stack, and a data exporter. + +--- + +## System Installation + +### Prerequisites +- Ubuntu 22.04 +- NVIDIA GPU with a recent driver +- Docker and NVIDIA Container Toolkit (required for GPU access inside the container) + +### Repository Setup + +Install Git and Git LFS: + +```bash +sudo apt update +sudo apt install git git-lfs +git lfs install +``` + +Clone the repository: + +```bash +mkdir -p ~/Projects +cd ~/Projects +git clone https://github.com/NVlabs/GR00T-WholeBodyControl.git +cd decoupled_wbc +``` + +### Docker Environment + +We provide a Docker image with all dependencies pre-installed. + +Install a fresh image and start a container: + +```bash +./docker/run_docker.sh --install --root +``` + +This pulls the latest `decoupled_wbc` image from `docker.io/nvgear`. + +Start or re-enter a container: + +```bash +./docker/run_docker.sh --root +``` + +Use `--root` to run as the `root` user. To run as a normal user, build the image locally: + +```bash +./docker/run_docker.sh --build +``` + +--- + +## Running the Control Stack + +Once inside the container, the control policies can be launched directly. + +- Simulation: + +```bash +python decoupled_wbc/control/main/teleop/run_g1_control_loop.py +``` + +- Real robot: Ensure the host machine network is configured per the [G1 SDK Development Guide](https://support.unitree.com/home/en/G1_developer) and set a static IP at `192.168.123.222`, subnet mask `255.255.255.0`: + +```bash +python decoupled_wbc/control/main/teleop/run_g1_control_loop.py --interface real +``` + +Keyboard shortcuts (terminal window): +- `]`: Activate policy +- `o`: Deactivate policy +- `9`: Release / Hold the robot +- `w` / `s`: Move forward / backward +- `a` / `d`: Strafe left / right +- `q` / `e`: Rotate left / right +- `z`: Zero navigation commands +- `1` / `2`: Raise / lower the base height +- `backspace` (viewer): Reset the robot in the visualizer + +--- + +## Running the Teleoperation Stack + +The teleoperation policy primarily uses Pico controllers for coordinated hand and body control. It also supports other teleoperation devices, including LeapMotion and HTC Vive with Nintendo Switch Joy-Con controllers. + +Keep `run_g1_control_loop.py` running, and in another terminal run: + +```bash +python decoupled_wbc/control/main/teleop/run_teleop_policy_loop.py --hand_control_device=pico --body_control_device=pico +``` + +### Pico Setup and Controls + +Configure the teleop app on your Pico headset by following the [XR Robotics guidelines](https://github.com/XR-Robotics). + +The necessary PC software is pre-installed in the Docker container. Only the [XRoboToolkit-PC-Service](https://github.com/XR-Robotics/XRoboToolkit-PC-Service) component is needed. + +Prerequisites: Connect the Pico to the same network as the host computer. + +Controller bindings: +- `menu + left trigger`: Toggle lower-body policy +- `menu + right trigger`: Toggle upper-body policy +- `Left stick`: X/Y translation +- `Right stick`: Yaw rotation +- `L/R triggers`: Control hand grippers + +Pico unit test: + +```bash +python decoupled_wbc/control/teleop/streamers/pico_streamer.py +``` + +--- + +## Running the Data Collection Stack + +Run the full stack (control loop, teleop policy, and camera forwarder) via the deployment helper: + +```bash +python decoupled_wbc/scripts/deploy_g1.py \ + --interface sim \ + --camera_host localhost \ + --sim_in_single_process \ + --simulator robocasa \ + --image-publish \ + --enable-offscreen \ + --env_name PnPBottle \ + --hand_control_device=pico \ + --body_control_device=pico +``` + +The `tmux` session `g1_deployment` is created with panes for: +- `control_data_teleop`: Main control loop, data collection, and teleoperation policy +- `camera`: Camera forwarder +- `camera_viewer`: Optional live camera feed + +Operations in the `controller` window (`control_data_teleop` pane, left): +- `]`: Activate policy +- `o`: Deactivate policy +- `k`: Reset the simulation and policies +- `` ` ``: Terminate the tmux session +- `ctrl + d`: Exit the shell in the pane + +Operations in the `data exporter` window (`control_data_teleop` pane, right top): +- Enter the task prompt + +Operations on Pico controllers: +- `A`: Start/Stop recording +- `B`: Discard trajectory diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/deployment_code.md b/third-party/GR00T-WholeBodyControl/docs/source/references/deployment_code.md new file mode 100644 index 0000000000000000000000000000000000000000..3cb1ce9edf0fa52ffed2754d46621306412fab61 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/deployment_code.md @@ -0,0 +1,276 @@ +# C++ Deployment Program Flow + +This document describes how the main executables run, their arguments, and the logging/configuration options. + +## Program Pipeline + +High-level flow (matches current code): +- Input interfaces: `keyboard | gamepad | gamepad_manager | zmq | zmq_manager | ros2 | manager` +- Optional planner (when enabled) generates target animations +- Motion reader provides reference motions for non-planner mode +- Policy inference (TensorRT; optional encoder → decoder) +- Output publishing via `--output-type ` + +## Available Commands + +```sh +just build # Build main project +just clean # Clean build artifacts +just --list # Show all available commands +``` + +## Run + +### Frequency Test + +Load an ONNX model and print input/output info. This is a sanity check for model loading; the reported frequency is not TensorRT inference speed. + +```sh +# Basic usage with default settings (1000 iterations, random data) +just run freq_test policy/example/model_step_000000.onnx + +# Custom iterations and data mode +just run freq_test policy/example/model_step_000000.onnx 5000 random +``` + +**Usage:** `just run freq_test [iterations] [data_mode]` +- `model_file`: Path to ONNX model file (required) +- `iterations`: Number of inference iterations (default: 1000) +- `data_mode`: Input data type — `zeros|random|ones` (default: random) + +### Policy Deployment + +Deploy ONNX policy on G1 robot with motion reference control: + +```sh +# Example command (real robot) +just run g1_deploy_onnx_ref enP8p1s0 policy/release/model_decoder.onnx reference/example/ \ + --obs-config policy/release/observation_config.yaml \ + --encoder-file policy/release/model_encoder.onnx \ + --planner-file planner/target_vel/V2/planner_sonic.onnx \ + --input-type manager \ + --enable-motion-recording \ + --enable-csv-logs + +# MuJoCo simulation (disables CRC validation) +python ../gear_sonic/scripts/run_sim_loop.py +just run g1_deploy_onnx_ref lo policy/release/model_decoder.onnx reference/example/ \ + --obs-config policy/release/observation_config.yaml \ + --encoder-file policy/release/model_encoder.onnx \ + --planner-file planner/target_vel/V2/planner_sonic.onnx \ + --input-type manager \ + --enable-motion-recording \ + --enable-csv-logs \ + --disable-crc-check +``` + +**Usage:** `just run g1_deploy_onnx_ref [options...]` + +**Required Arguments:** +- `network_interface`: Network interface for DDS communication (e.g., `eth0`, `enp5s0`, `enP8p1s0`, `lo`) +- `model_file`: Path to ONNX policy model file +- `motion_data_path`: Path to motion data directory containing reference motions + +**Optional Arguments:** + +**Model Configuration:** +- `--obs-config `: Path to observation configuration YAML file +- `--encoder-file `: Path to ONNX encoder model file (optional, for token-based policies) +- `--planner-file `: Path to ONNX planner model file (required for ROS2, `gamepad_manager`, and `zmq_manager` planner mode) +- `--planner-precision <16|32>`: Floating point precision for planner (default: 32) +- `--policy-precision <16|32>`: Floating point precision for policy (default: 32) + +**Output Mode:** +- `--output-type `: Output interface for publishing control results + - `zmq` — Publish via ZMQ (default) + - `ros2` — Publish via ROS2 (only if built with ROS2 support) + - `all` — Create all available output interfaces simultaneously + +**Input Mode:** +- `--input-type `: Input interface type (default: `keyboard`) + - `keyboard` — Direct keyboard input + - `gamepad` — Wireless controller + - `gamepad_manager` — Gamepad + quick switching to ZMQ/ROS2 + - `zmq` — Network motion streaming + - `zmq_manager` — Dynamic switching between planner and network motion streaming + - `manager` — Dynamic switching between keyboard, gamepad, ZMQ, and ROS2 + - `ros2` — ROS2 topic control (requires planner, only if built with ROS2 support) + +**ZMQ Configuration (when using `--input-type zmq`, `zmq_manager`, `demo_gamepad_manager`, or `manager`):** +- `--zmq-host `: ZMQ server host (default: `localhost`) +- `--zmq-port `: ZMQ server port (default: `5556`) +- `--zmq-topic `: ZMQ topic/prefix (default: `pose`) +- `--zmq-conflate`: Enable ZMQ CONFLATE mode +- `--zmq-verbose`: Enable verbose ZMQ subscriber logging +- `--zmq-out-port`: Port to which control results will be published when using `--output-type zmq` (default: `5557`) +- `--zmq-out-topic`: Topic to which control results will be published when using `--output-type zmq` (default: `g1_debug`) + +**Simulation:** +- `--disable-crc-check`: Disable CRC validation (required for MuJoCo simulation) + +**Hand & Compliance Control:** +- `--set-compliance `: Set initial VR 3-point compliance (0.01 = rigid, 0.5 = compliant; default: `0.5,0.5,0.0`). Can specify 1 value (applied to both hands) or 3 comma-separated values (`left_wrist,right_wrist,head`). Runtime keyboard controls: `g/h` = left hand ±0.1, `b/v` = right hand ±0.1. +- `--max-close-ratio `: Set initial hand max close ratio (0.2–1.0; default: 1.0 = full closure allowed). Runtime keyboard controls: `x/c` = ±0.1. + +**Logging (CLI flags):** +- **Debug / analysis logs (write a single CSV file)**: + - `--target-motion-logfile `: Log the target motion tracked by the controller (visualize with `visualize_motion.py`) + - `--planner-motion-logfile `: Log planner-generated animation sequences + - `--policy-input-logfile `: Log policy input (observation) tensors + - `--record-input-file `: Record operator control inputs to CSV for later playback + - `--playback-input-file `: Play back previously recorded control inputs from CSV +- **State CSV logs (write a timestamped directory)**: + - `--logs-dir `: Base directory for state CSV logs (default: `logs/dd-mm-yy/hh-mm-ss`) + - `--enable-csv-logs`: Enable robot state CSV logging (default: OFF) + - `--enable-motion-recording`: Record the active motion stream(s) to `reference/recorded_motion/...` (default: OFF) + +## Logging (Details) + +The system provides multiple logging capabilities for debugging, analysis, and replay. + +### Motion Logging + +**Target Motion (`--target-motion-logfile `):** +- Logs the motion the controller is tracking each control frame (~50 Hz) +- CSV columns: `pos_x, pos_y, pos_z, rot_qw, rot_qx, rot_qy, rot_qz, dof_0, dof_1, ... dof_28` + - Global position (xyz) + - Global rotation quaternion (w, x, y, z) + - 29 joint angles (DoF) + +**Planner Motion (`--planner-motion-logfile `):** +- Logs animation sequences generated by the planner (~10 Hz planning updates) +- Each planner update produces a short sequence (e.g., ~100 frames) that is appended to the CSV +- Same CSV format as target motion +- Contains motion blending and replanning results + +**Motion Recording (`--enable-motion-recording`):** +- Automatically records the currently active motion stream(s) into timestamped folders under `reference/recorded_motion/YYYYMMDD/` + - **Streamed motion** (ZMQ pose topic): saved as `streamed_HHMMSS/` + - **Planner motion** (planner-generated sequence): saved as `planner_motion_HHMMSS/` +- Each recording folder contains `joint_pos.csv`, `joint_vel.csv`, `body_pos.csv`, `body_quat.csv`, etc. +- Useful for offline inspection / regression comparisons of closed-loop behavior + +### Visualization + +All motion CSV files (logged data and reference motions) can be visualized using the `visualize_motion.py` script: + +```sh +# Visualize logged motion data (single CSV file) +python visualize_motion.py --csv_path target_motion.csv + +# Visualize reference motion from motion data directory +python visualize_motion.py --motion_dir reference/example/high_jump_full_turn/ +``` + +The visualizer script can connect to a running `g1_deploy` executable to visualize target/measured robot motions in real time: + +```sh +python visualize_motion.py --realtime_debug_url tcp://localhost:5557 +``` + +This displays four G1 robots: target animation (colored), target with zero translation (green), measured sensor data (red), and motor temperature heatmap (white, with per-joint color indicators: green → yellow → orange → red/flashing by temperature). + +**Configuration:** +- Default port: 5557 (change with `--zmq-out-port `) +- Default topic: `g1_debug` (change with `--zmq-out-topic ` on executable, `--realtime_debug_topic ` on visualizer) +- For physical robots, replace `localhost` with the robot's IP address + +**Playback Controls:** +- **Space**: Pause/resume playback +- **`.`** (period): Step forward one frame +- **`,`** (comma): Step backward one frame +- **`r`**: Reset to frame 0 + +### Policy Input Logging + +**Policy Input (`--policy-input-logfile `):** +- Logs the raw observation tensor fed to the neural network policy +- Output: a single CSV file (one row per control step, all observation values) +- Useful for debugging observation configuration and input drift + +### Control Input Recording/Playback + +**Recording (`--record-input-file `):** +- Records control inputs (motion index, frame, operator state, planner state, movement commands) +- Logging starts when the control system is activated +- Tip: Wait a few seconds after lowering from gantry before starting control to give yourself setup time during playback + +**Playback (`--playback-input-file `):** +- Replays recorded control inputs for reproducible experiments +- Playback starts when the control system is activated +- Useful for testing policy changes with identical inputs + +### Robot State CSV Logger + +When enabled with `--enable-csv-logs`, the system logs detailed robot state at each control step (50 Hz). + +**Output Directory:** +- Default: `logs/dd-mm-yy/hh-mm-ss` (auto-generated timestamp) +- Custom: Use `--logs-dir ` to specify directory + +**Files Generated (split by signal type):** +- `base_quat.csv` — Base IMU quaternion (4 values: w, x, y, z) +- `base_ang_vel.csv` — Base angular velocity (3 values: x, y, z) +- `torso_quat.csv` — Torso IMU quaternion (4 values) +- `torso_ang_vel.csv` — Torso angular velocity (3 values) +- `q.csv` — Joint positions (29 joints) +- `dq.csv` — Joint velocities (29 joints) +- `action.csv` — Policy actions (29 joints) + +**CSV Format:** +- Columns: `index,time_ms,...` +- `time_ms`: Milliseconds since first log (0.0 at start, fractional allowed) +- Synchronized across all files using the same index/timestamp + +**Example:** + +```sh +just run g1_deploy_onnx_ref enp5s0 policy/model.onnx reference/motions/ \ + --obs-config policy/obs_config.yaml \ + --enable-csv-logs \ + --logs-dir logs/my_experiment +``` + +## Observation Configuration + +The system uses YAML configuration files to define which observations are fed to the policy. This allows flexible policy designs without code changes. + +**Basic Structure (`--obs-config `):** + +```yaml +observations: + - name: "body_joint_positions" + enabled: true + - name: "base_angular_velocity" + enabled: true + # ... other observations +``` + +**With Encoder (Token-Based Policies):** + +For policies that use encoded tokens, add an `encoder:` section: + +```yaml +observations: + - name: "token_state" # Encoder outputs (64-dim tokens) + enabled: true + - name: "base_angular_velocity" # Direct observations + enabled: true + +encoder: + dimension: 64 # Token output dimension + use_fp16: false # TensorRT precision (optional) + encoder_observations: + - name: "motion_joint_positions_10frame_step5" + enabled: true + # ... observations fed to encoder +``` + +Then run with `--encoder-file ` to load the encoder model. If omitted, tokens can be set externally via ROS2/ZMQ. + +**Complete Observation Reference:** + +For the full list of all available observation names, dimensions, and example configurations, see [Observation Configuration](observation_config.md). + +**Examples:** +- See `policy/observation_config_example.yaml` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/index.md b/third-party/GR00T-WholeBodyControl/docs/source/references/index.md new file mode 100644 index 0000000000000000000000000000000000000000..5c3cd242bccf85747a4709769e012e344073a4cf --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/index.md @@ -0,0 +1,11 @@ +# Reference Documentation + +These pages contain the original standalone documentation that previously lived as individual `README_*.md` files. They are preserved here as detailed references. + +- [Training Code Structure](training_code.md) — training codebase architecture, pipeline flow, configuration system, and key classes +- [Deployment Code & Program Flow](deployment_code.md) — CLI arguments, logging, observation config, and visualization tools +- [Observation Configuration](observation_config.md) — YAML config format, all observation types with dimensions, and how to create custom observations +- [Motion Reference Data](motion_reference.md) — reference motion file format, conversion, verification, and usage +- [Kinematic Planner ONNX Model](planner_onnx.md) — detailed input/output specification for the ONNX-exported kinematic planner +- [JetPack 6 Flashing Guide](jetpack6.md) — flash the Orin NX on the Unitree G1 +- [Decoupled WBC (N1.5 / N1.6)](decoupled_wbc.md) — the earlier Decoupled WBC stack used in Gr00t N1.5 and N1.6 diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/jetpack6.md b/third-party/GR00T-WholeBodyControl/docs/source/references/jetpack6.md new file mode 100644 index 0000000000000000000000000000000000000000..61b4f791db9c9bc71e33394432a6a042269293a4 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/jetpack6.md @@ -0,0 +1,126 @@ +# G1 JetPack 6 Flashing Guide + +## 1. Download Image + +1. **Download the required files** — get both the `.tar` file and the image file from [Jetpack 6.2](https://drive.google.com/drive/folders/1ho17ectOxi7FbaRFdpAbP4tet8BJWjbm). + +## 2. Unmount Orin NX's NVMe + +### Steps to Remove the NVMe SSD + +1. **Remove the back handle screws** + + Use a 5 mm T-handle Allen key to unscrew the two screws located at the back of the robot near the handle. + +2. **Remove the foam and plastic back cover** + + - Use the 2 mm hex tool from the Fanttik tool kit to remove the four screws holding the foam and plastic backing in place. + - Lift the backing off to expose the internal components. + +```{image} ../_static/screws.png +:width: 600px +:align: center +``` + +3. **Remove the NVMe screw on the Orin NX module** + + Use a Phillips screwdriver (also in the Fanttik tool kit) to remove the single screw securing the Orin NX's NVMe SSD. + +```{image} ../_static/ssd.png +:width: 600px +:align: center +``` + +4. **Remove the SSD card** + + Carefully slide out and remove the NVMe SSD from its slot. + +## 3. Flash the NVMe SSD + +**Mount the NVMe SSD from the Orin NX into the NVMe SSD enclosure adapter.** +(Adapter needed when burning image from a laptop) + +1. Check that the robot's SSD is unmounted. Run the following command to make sure the external SSD (where you will burn the image) is not mounted: + +```bash +sudo umount /dev/sda* +``` + +2. If the SSD was mounted, this command will safely unmount it so it's ready for imaging. + +3. Navigate to the folder where you have the image (`cd robot_NXUpgrade/`), then run the following command: + +```bash +bzip2 -dc g1-nx-j6.2.img.bz2 | sudo dd of=/dev/sda bs=4M status=progress conv=fsync +``` + +4. After it's done, eject the card with the following commands to safely unplug it: + +```bash +sudo sync +sudo udisksctl power-off -b /dev/sda +``` + +5. **Set the SSD card to the side and proceed with the second part of the flashing process!** + +## 4. Put the Robot Into Flashing Mode + +1. **Power on the G1** and wait until all three power indicator lights remain steadily lit. + +2. **Connect the robot to your laptop/desktop** using a USB-C cable. + +3. **Press and hold both white buttons** on the robot at the same time for two seconds. + +4. While still holding them, **release the top white button** and continue holding the **bottom button** for 2 seconds until the **three green lights change to two green lights**. + +```{image} ../_static/flashing.png +:width: 600px +:align: center +``` + +5. When only two lights are on, the robot is **now in flashing mode**. Open a new terminal on your computer and enter `lsusb`. You should see text containing `NVIDIA Corp. APX`. + +6. You can now proceed to run the following commands: + +```bash +sudo tar -xjvf Jetpack_6.2_nx.tar.bz2 +cd Jetpack_6.2_nx/Linux_for_Tegra +sudo ./flash_nx_module.sh +``` + +Wait patiently for about 8 minutes until it shows success. + +## 5. Reassemble the Robot + +1. After the flashing is complete, **power off the robot**. + +2. **Reinstall the Orin NX's NVMe SSD** back into its slot on the G1 robot and secure it with its screw. + +3. **Reattach the foam and plastic backing**, using the same tools you used to remove it. + +4. **Tighten all screws** to ensure the back cover and handle are securely in place. + +5. Turn on `maxn` mode on Jetson Orin using the command: + + +``` +sudo nvpmodel -m 0 +``` + +and use + + +``` +sudo jetson_clocks +sudo jetson_clocks --show +``` + +to check if it is already in Maxn model. + +## 6. Install Required JetPack Packages + +Install the packages needed for deployment: + +``` +sudo apt-get install -y nvidia-l4t-dla-compiler libcudla-dev-12-6 +``` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/motion_reference.md b/third-party/GR00T-WholeBodyControl/docs/source/references/motion_reference.md new file mode 100644 index 0000000000000000000000000000000000000000..8e218fea93aba2d2a6102ef20db6bd018f9b626c --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/motion_reference.md @@ -0,0 +1,295 @@ +# Motion Reference Data + +This page describes the motion reference data format used by the C++ deployment stack, how to create your own reference motions, and how to verify and deploy them. + +The deployment stack plays back pre-loaded **reference motions** — sequences of joint positions, velocities, and full body kinematics that the policy tracks. These motions are stored as CSV files in a structured folder hierarchy. You can generate them from any source (motion capture, simulation, retargeting pipeline, etc.) as long as the output matches the format described below. + +--- + +## Folder Structure + +Each motion dataset is a directory containing one subfolder per motion clip. The C++ reader (`MotionDataReader`) auto-discovers all subfolders at startup. + +``` +reference/my_motions/ +├── motion_name_1/ +│ ├── joint_pos.csv # Joint positions +│ ├── joint_vel.csv # Joint velocities +│ ├── body_quat.csv # Body quaternions +│ ├── body_pos.csv # Body positions +│ ├── metadata.txt # Body part indexes +│ ├── body_lin_vel.csv # Body linear velocities +│ ├── body_ang_vel.csv # Body angular velocities +│ ├── smpl_joint.csv # SMPL joint positions +│ ├── smpl_pose.csv # SMPL body poses +│ └── info.txt # Detailed motion information +└── motion_name_2/ + └── ... +``` + +The C++ reader scans the base directory for subfolders, reads each subfolder as one motion, and validates frame-count consistency across all files in that folder. +--- + +## File Formats + +The C++ reader loads whichever files are present and skips missing files gracefully. However, **in practice**, most policies require: +- `joint_pos.csv`, `joint_vel.csv` — for joint-based motion tracking +- `body_quat.csv` — for anchor orientation observations (the control loop will stop if this is missing when gathering observations) +- `body_pos.csv` — for heading computation and VR 3-point observations +- `metadata.txt` — for body part index alignment when body data is present + +A motion must have **at least one valid data source** (joint, body, or SMPL) to load at startup. + +### `joint_pos.csv` + +Joint positions in **IsaacLab order** (29 joints). Each row is one timestep at 50 Hz. The first row is a header. + +| Column | Description | +|--------|-------------| +| `joint_0` … `joint_28` | Joint angles in radians (IsaacLab ordering) | + +Shape: `(timesteps, 29)` + +### `joint_vel.csv` + +Joint velocities in **IsaacLab order** (29 joints). Each row is one timestep at 50 Hz. Frame count must match `joint_pos.csv`. + +| Column | Description | +|--------|-------------| +| `joint_vel_0` … `joint_vel_28` | Joint angular velocities in rad/s (IsaacLab ordering) | + +Shape: `(timesteps, 29)` + +### `body_pos.csv` + +Body part positions in the **world frame**. Each body contributes 3 columns (x, y, z). The number of bodies varies per motion. Needed for heading computation and VR 3-point observations. + +| Column | Description | +|--------|-------------| +| `body_0_x`, `body_0_y`, `body_0_z` | Position of body 0 (root/pelvis) in meters | +| `body_1_x`, `body_1_y`, `body_1_z` | Position of body 1 in meters | +| … | … | + +Shape: `(timesteps, num_bodies * 3)` + +**We assume the root/pelvis is always at column group 0** (the first 3 columns). + +### `body_quat.csv` + +Body part orientations as quaternions in the **world frame**. Each body contributes 4 columns. The quaternion ordering is **(w, x, y, z)**. **Required for most policies** — the `motion_anchor_orientation` observation (used by most policies) will fail and stop the control system if this file is missing. + +| Column | Description | +|--------|-------------| +| `body_0_w`, `body_0_x`, `body_0_y`, `body_0_z` | Quaternion of body 0 (root/pelvis) | +| `body_1_w`, `body_1_x`, `body_1_y`, `body_1_z` | Quaternion of body 1 | +| … | … | + +Shape: `(timesteps, num_bodies * 4)` + +**We assume the root/pelvis is always at column group 0** (the first 4 columns). + +```{note} +The number of bodies in `body_quat.csv` can differ from `body_pos.csv`. The C++ reader tracks them independently (`num_bodies` vs `num_body_quaternions`). However, the root body (first column group) must be present for heading computation to work. You can use zero if you don't need root pos. +``` + +### `metadata.txt` + +Contains the **body part indexes** array, which maps each column group in `body_pos.csv` / `body_quat.csv` to the corresponding IsaacLab body index. This is needed when body data is present. + +``` +Metadata for: motion_name +============================== + +Body part indexes: +[ 0 4 10 18 5 11 19 9 16 22 28 17 23 29] + +Total timesteps: 497 +``` + +The C++ reader parses `Body part indexes:` followed by a line of space-separated integers in brackets. For example, `[0, 4, 10, 18, ...]` means column group 0 → IsaacLab body 0 (pelvis/root), column group 1 → body 4, etc. + +For a **root-only** motion (only 1 body), use: + +``` +Body part indexes: +[0] +``` + +### `body_lin_vel.csv` / `body_ang_vel.csv` + +Body part linear and angular velocities in the world frame. Same layout as `body_pos.csv` (3 columns per body). The number of bodies must match `body_pos.csv`. + +### `smpl_joint.csv` + +SMPL joint positions (typically 24 joints × 3 coordinates). Each row is one timestep. + +Shape: `(timesteps, num_smpl_joints * 3)` + +### `smpl_pose.csv` + +SMPL body poses in axis-angle representation (typically 21 poses × 3 coordinates). Each row is one timestep. + +Shape: `(timesteps, num_smpl_poses * 3)` + +```{note} +The **current reference motion tracking pipeline uses joint-based tracking only** (encoder mode 0). To enable SMPL-based reference tracking (encoder mode 2), you would need to modify the code to detect the presence of SMPL data and switch the encoder mode accordingly. +``` + +### `info.txt` + +Human-readable summary with shapes, dtypes, and value ranges. Not read by the C++ stack — purely for documentation. + +--- + +## Creating Your Own Reference Motions + +You can generate reference motions from any source — the only requirement is producing CSV files in the format above. Common approaches: + +1. **Motion capture retargeting** — retarget human mocap to the G1 model, export joint positions/velocities and body kinematics. +2. **Simulation recording** — record joint states from an IsaacLab or MuJoCo simulation at 50 Hz. +3. **Procedural generation** — programmatically create joint trajectories. + +### Minimal Files Needed + +The **minimum** set of files to create a working motion for SONIC policy: + +1. **`joint_pos.csv`** — 29 joint positions (IsaacLab order), header + one row per timestep +2. **`joint_vel.csv`** — 29 joint velocities (IsaacLab order), header + one row per timestep +3. **`body_quat.csv`** — Root quaternion (w, x, y, z), header + one row per timestep +4. **`body_pos.csv`** — Root position (x, y, z), header + one row per timestep. You can use all zeros if you don't need position tracking. +5. **`metadata.txt`** — Body part indexes (just `[0]` for root-only) + +**Example files:** + +`joint_pos.csv`: +``` +joint_0,joint_1,joint_2,...,joint_28 +0.128441,0.102713,0.020116,...,0.045231 +0.130124,0.104532,0.021045,...,0.046112 +... +``` + +`joint_vel.csv`: +``` +joint_vel_0,joint_vel_1,...,joint_vel_28 +0.143671,0.143864,...,0.012345 +... +``` + +`body_quat.csv` (root quaternion only): +``` +body_0_w,body_0_x,body_0_y,body_0_z +0.999123,0.000456,0.001234,0.040567 +... +``` + +`body_pos.csv` (root position, can be all zeros): +``` +body_0_x,body_0_y,body_0_z +0.000000,0.000000,0.000000 +... +``` + +`metadata.txt`: +``` +Metadata for: my_motion +============================== + +Body part indexes: +[0] + +Total timesteps: 100 +``` + +This gives you a **root-only** motion (1 body = pelvis/root) that most policies can track. + + +### Provided Conversion Script + +A convenience script `reference/convert_motions.py` is included for converting **joblib pickle** (`.pkl`) files to this format. This is just one possible source — you can use any tool or pipeline that produces the correct CSV output. + +```bash +cd gear_sonic_deploy +python reference/convert_motions.py [output_dir] +``` + +The pickle should be a dictionary where each key is a motion name and each value contains `joint_pos`, `joint_vel`, `body_pos_w`, `body_quat_w`, `body_lin_vel_w`, `body_ang_vel_w`, `_body_indexes`, and `time_step_total`. + +--- + +## Verifying Reference Motions + +### MuJoCo Visualization + +Use the included visualizer to check that the motion looks correct on the G1 model: + +```bash +cd gear_sonic_deploy +python visualize_motion.py --motion_dir reference/my_motions/motion_name_1/ +``` + +**Controls:** +- **Space**: Pause / resume playback +- **R**: Reset to frame 0 +- **,** / **.**: Step backward / forward one frame +- **-** / **=**: Previous / next motion (if multiple loaded) + +Verify that: +- The robot stands upright and does not clip through the floor +- Joint angles look reasonable (no extreme poses) +- The motion plays smoothly without sudden jumps +- Body positions track the expected trajectory + +--- + +## Using Reference Motions + +### With `deploy.sh` + +Pass the motion directory via `--motion-data`: + +```bash +./deploy.sh --motion-data reference/my_motions/ sim +``` + +Or use the default motions (configured in `deploy.sh`): + +```bash +./deploy.sh sim +``` + +### At Runtime + +Once deployed, use the keyboard or gamepad to browse and play motions: + +- **T**: Play current motion +- **N / P**: Next / Previous motion +- **R**: Restart from frame 0 + +See the [Keyboard tutorial](../tutorials/keyboard.md) for the full control reference. + +--- + +## Validation Rules + +The C++ reader enforces the following during loading: + +- **Frame count consistency**: All CSV files within a motion folder must have the same number of rows (excluding headers). Mismatches cause the motion to be skipped with an error. +- **Joint count consistency**: `joint_pos.csv` and `joint_vel.csv` must have the same number of columns. +- **Body count consistency**: `body_lin_vel.csv` and `body_ang_vel.csv` must have the same number of body columns as `body_pos.csv`. +- **At least one data source**: A motion must have at least some valid data (joint, body, or SMPL) to be loaded. +- **Metadata parsing**: The `metadata.txt` file must contain a `Body part indexes:` line followed by a bracketed list of integers for the motion to have correct body-part alignment. + +If a motion fails validation, it is skipped and a warning is printed. The deployment continues with the remaining valid motions. + +--- + +## Notes + +- All data is at **50 Hz** (0.02 s per timestep), matching the control loop frequency. +- Joint ordering follows **IsaacLab convention** (not MuJoCo). The C++ stack handles the conversion internally when sending motor commands. +- Body quaternions use **(w, x, y, z)** ordering. +- The first body (column group 0) must correspond to the root/pelvis for heading computation and anchor orientation observations to work correctly. +- While the C++ reader can load motions without `body_quat.csv`, the control loop will fail during observation gathering if the policy observes `motion_anchor_orientation` (which most policies do). +- CSV files must have a **header row** as the first line — the C++ reader skips the first line of every CSV. +- Values are parsed as `double` precision internally. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/observation_config.md b/third-party/GR00T-WholeBodyControl/docs/source/references/observation_config.md new file mode 100644 index 0000000000000000000000000000000000000000..d0bba48367b6ad53caa5f48a313ea30278329987 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/observation_config.md @@ -0,0 +1,437 @@ +# Observation Configuration + +This page is the complete reference for configuring observations in the deployment system. It covers the YAML configuration format, the encoder system, every available observation type, and how to create your own custom observations. + +(obs-config-format)= +## Configuration Format + +Observations are configured via a YAML file passed with `--obs-config `. Each observation has a `name` (must match a registered observation) and an `enabled` flag. + +### Basic Structure + +```yaml +observations: + - name: "motion_joint_positions" + enabled: true + - name: "motion_joint_velocities" + enabled: true + - name: "motion_anchor_orientation" + enabled: true + - name: "base_angular_velocity" + enabled: true + - name: "body_joint_positions" + enabled: true + - name: "body_joint_velocities" + enabled: true + - name: "last_actions" + enabled: true +``` + +**Key rules:** + +- Observations are concatenated **in the order listed** to form the policy input vector. +- Offsets are calculated automatically — no manual offset management needed. +- The **total dimension** of all enabled observations must match your ONNX model's input size. +- Disabled observations (`enabled: false`) are skipped entirely. +- Reordering entries changes the layout of the input tensor (offsets shift accordingly). + +(obs-config-encoder)= +### With Encoder (Token-Based Policies) + +For policies that use an encoder to compress observations into a compact token, add an `encoder:` section: + +```yaml +observations: + - name: "token_state" # Encoder outputs (dimension set below) + enabled: true + - name: "base_angular_velocity" # Direct observations + enabled: true + - name: "body_joint_positions" + enabled: true + - name: "body_joint_velocities" + enabled: true + - name: "last_actions" + enabled: true + +encoder: + dimension: 64 # Token output dimension + use_fp16: false # TensorRT precision for encoder (optional) + encoder_observations: + - name: "motion_joint_positions_10frame_step5" + enabled: true + - name: "motion_joint_velocities_10frame_step5" + enabled: true + - name: "motion_anchor_orientation_10frame_step5" + enabled: true + - name: "motion_root_z_position_10frame_step5" + enabled: true + encoder_modes: # Optional: per-mode observation requirements + - name: "g1" + mode_id: 0 + required_observations: + - motion_joint_positions_10frame_step5 + - motion_joint_velocities_10frame_step5 + - motion_anchor_orientation_10frame_step5 + - motion_root_z_position_10frame_step5 +``` + +**Encoder fields:** + +| Field | Description | +|---|---| +| `dimension` | Token output dimension (must match encoder ONNX model output). Set to 0 or omit to disable encoder. | +| `use_fp16` | Use FP16 precision for encoder TensorRT engine (default: false). | +| `encoder_observations` | Observations fed to the encoder (superset of all modes). Same name/enabled format as policy observations. | +| `encoder_modes` | *(Optional)* Per-mode observation requirements. Observations not in a mode's `required_observations` are zero-filled, saving computation. | + +Run with `--encoder-file ` to load the encoder model. If omitted, `token_state` can be set externally via ROS2/ZMQ. + +See `policy/observation_config_example.yaml` for a complete annotated example. + +### Naming Convention + +Multi-frame observations follow the pattern: `{base_name}_{N}frame_step{S}` + +- **N** = number of frames gathered (temporal window size) +- **S** = step size between frames (in control ticks at 50 Hz, so step5 = 0.1 s apart) +- Without the suffix = single current frame only + +For example, `motion_joint_positions_10frame_step5` gathers 10 frames of joint positions, sampled every 5 ticks (0.1 s), giving a 0.9 s look-ahead window. If future frames exceed the motion length, the last frame is repeated. + +--- + +## Encoder & Token Observations + +These observations relate to the encoder (tokenizer) system. See [With Encoder](obs-config-encoder) above for the YAML format. + +| Name | Dim | Description | +|---|---|---| +| `token_state` | config | Encoder output tokens (dimension set by `encoder.dimension` in YAML). Populated by local encoder inference or externally via ZMQ/ROS2. | +| `encoder_mode` | 3 | Current encoder mode ID + 2 zero-padding values. | +| `encoder_mode_4` | 4 | Current encoder mode ID + 3 zero-padding values. | + +--- + +## Motion Reference Observations + +Gathered from the currently-active motion sequence (reference motions, planner output, or ZMQ stream). All joint data uses **IsaacLab joint ordering** (29 joints). + +### Joint Positions (from motion) + +| Name | Dim | Frames | Step | Description | +|---|---|---|---|---| +| `motion_joint_positions` | 29 | 1 | — | Current frame joint positions (rad) | +| `motion_joint_positions_3frame_step1` | 87 | 3 | 1 | 3-frame window, consecutive | +| `motion_joint_positions_5frame_step5` | 145 | 5 | 5 | 5-frame window, 0.1 s apart | +| `motion_joint_positions_10frame_step1` | 290 | 10 | 1 | 10-frame window, consecutive | +| `motion_joint_positions_10frame_step5` | 290 | 10 | 5 | 10-frame window, 0.1 s apart | +| `motion_joint_positions_lowerbody_10frame_step1` | 120 | 10 | 1 | Lower-body joints only (12 joints), consecutive | +| `motion_joint_positions_lowerbody_10frame_step5` | 120 | 10 | 5 | Lower-body joints only, 0.1 s apart | +| `motion_joint_positions_wrists_10frame_step1` | 60 | 10 | 1 | Wrist joints only (6 joints), consecutive | +| `motion_joint_positions_wrists_2frame_step1` | 12 | 2 | 1 | Wrist joints only, 2 consecutive frames | + +```{note} +When upper-body control is active (e.g., via ZMQ/ROS2 teleoperation), the upper-body joint positions in these observations are replaced with the externally-provided targets. +``` + +### Joint Velocities (from motion) + +| Name | Dim | Frames | Step | Description | +|---|---|---|---|---| +| `motion_joint_velocities` | 29 | 1 | — | Current frame joint velocities (rad/s). Zero when not playing. | +| `motion_joint_velocities_3frame_step1` | 87 | 3 | 1 | 3-frame window, consecutive | +| `motion_joint_velocities_5frame_step5` | 145 | 5 | 5 | 5-frame window, 0.1 s apart | +| `motion_joint_velocities_10frame_step1` | 290 | 10 | 1 | 10-frame window, consecutive | +| `motion_joint_velocities_10frame_step5` | 290 | 10 | 5 | 10-frame window, 0.1 s apart | +| `motion_joint_velocities_lowerbody_10frame_step1` | 120 | 10 | 1 | Lower-body joints only, consecutive | +| `motion_joint_velocities_lowerbody_10frame_step5` | 120 | 10 | 5 | Lower-body joints only, 0.1 s apart | +| `motion_joint_velocities_wrists_10frame_step1` | 60 | 10 | 1 | Wrist joints only, consecutive | + +### Anchor Orientation (from motion) + +Heading-corrected relative rotation from the robot's current base orientation to the reference motion orientation. Output is the first two columns of the 3×3 rotation matrix (6 values per frame). + +| Name | Dim | Frames | Step | Description | +|---|---|---|---|---| +| `motion_anchor_orientation` | 6 | 1 | — | Current frame anchor orientation (full base quaternion) | +| `motion_anchor_orientation_10frame_step1` | 60 | 10 | 1 | 10-frame window, consecutive | +| `motion_anchor_orientation_10frame_step5` | 60 | 10 | 5 | 10-frame window, 0.1 s apart | +| `motion_anchor_orientation_heading` | 6 | 1 | — | Current frame, heading-only quaternion (yaw extracted from robot base) | +| `motion_anchor_orientation_heading_10frame_step1` | 60 | 10 | 1 | Heading-only, 10-frame window, consecutive | +| `motion_anchor_orientation_heading_10frame_step5` | 60 | 10 | 5 | Heading-only, 10-frame window, 0.1 s apart | +| `motion_anchor_orientation_refheading` | 6 | 1 | — | Current frame, reference-heading quaternion (yaw from first future ref frame) | +| `motion_anchor_orientation_refheading_10frame_step1` | 60 | 10 | 1 | Ref-heading, 10-frame window, consecutive | +| `motion_anchor_orientation_refheading_10frame_step5` | 60 | 10 | 5 | Ref-heading, 10-frame window, 0.1 s apart | + +### Root Z Position (from motion) + +| Name | Dim | Frames | Step | Description | +|---|---|---|---|---| +| `motion_root_z_position` | 1 | 1 | — | Current frame root height (m) | +| `motion_root_z_position_3frame_step1` | 3 | 3 | 1 | 3-frame window, consecutive | +| `motion_root_z_position_10frame_step1` | 10 | 10 | 1 | 10-frame window, consecutive | +| `motion_root_z_position_10frame_step5` | 10 | 10 | 5 | 10-frame window, 0.1 s apart | + +--- + +## SMPL Observations + +Gathered from SMPL data in the motion sequence (optional — requires motions with `smpl_joint.csv` / `smpl_pose.csv`). + +### SMPL Joint Positions + +3D positions per SMPL joint (24 joints × 3 = 72 per frame). + +| Name | Dim | Frames | Step | Description | +|---|---|---|---|---| +| `smpl_joints` | 72 | 1 | — | Current frame, all 24 SMPL joints | +| `smpl_joints_2frame_step1` | 144 | 2 | 1 | 2 consecutive frames | +| `smpl_joints_5frame_step5` | 360 | 5 | 5 | 5-frame window, 0.1 s apart | +| `smpl_joints_10frame_step1` | 720 | 10 | 1 | 10-frame window, consecutive | +| `smpl_joints_10frame_step5` | 720 | 10 | 5 | 10-frame window, 0.1 s apart | +| `smpl_joints_lower_10frame_step1` | 270 | 10 | 1 | Lower-body SMPL joints only (9 joints), consecutive | + +### SMPL Poses (Axis-Angle) + +3D axis-angle per SMPL body part (21 poses × 3 = 63 per frame). + +| Name | Dim | Frames | Step | Description | +|---|---|---|---|---| +| `smpl_pose` | 63 | 1 | — | Current frame, all 21 SMPL poses | +| `smpl_pose_5frame_step5` | 315 | 5 | 5 | 5-frame window, 0.1 s apart | +| `smpl_pose_10frame_step1` | 630 | 10 | 1 | 10-frame window, consecutive | +| `smpl_pose_10frame_step5` | 630 | 10 | 5 | 10-frame window, 0.1 s apart | +| `smpl_elbow_wrist_poses_10frame_step1` | 120 | 10 | 1 | Elbow + wrist poses only (4 parts), consecutive | + +### SMPL Aliases + +These use the same gatherers as the motion observations but are intended for SMPL-based policies: + +| Name | Dim | Frames | Step | Description | +|---|---|---|---|---| +| `smpl_root_z_10frame_step1` | 10 | 10 | 1 | Root height, 10 consecutive frames | +| `smpl_anchor_orientation_10frame_step1` | 60 | 10 | 1 | Anchor orientation, 10 consecutive frames | +| `smpl_anchor_orientation_2frame_step1` | 12 | 2 | 1 | Anchor orientation, 2 consecutive frames | + +--- + +## VR Tracking Observations + +VR 3-point and 5-point tracking data. When an external source (ZMQ/ROS2) provides VR data, buffered values are used directly. Otherwise, positions and orientations are computed from the motion sequence's body data and normalised to the root body frame. + +### VR 3-Point + +| Name | Dim | Description | +|---|---|---| +| `vr_3point_local_target` | 9 | 3-point positions in root frame: `[left_wrist xyz, right_wrist xyz, head xyz]` | +| `vr_3point_local_target_compliant` | 9 | Same as above (identical during teleoperation) | +| `vr_3point_local_orn_target` | 12 | 3-point orientations in root frame: `[left quat wxyz, right quat wxyz, head quat wxyz]` | +| `vr_3point_compliance` | 3 | Compliance values: `[left_arm, right_arm, head]`. Keyboard-controlled (g/h/b/v keys), range [0.0, 0.5]. | + +### VR 5-Point + +| Name | Dim | Description | +|---|---|---| +| `vr_5point_local_target` | 15 | 5-point positions in root frame: `[left_wrist, right_wrist, head, left_ankle, right_ankle]` × xyz | +| `vr_5point_local_orn_target` | 20 | 5-point orientations in root frame: 5 quaternions × wxyz | + +--- + +## Robot State History Observations + +Gathered from the StateLogger ring buffer (measured sensor data from the real robot). These provide temporal context by sampling past states. + +### Single-Frame (Current State) + +| Name | Dim | Description | +|---|---|---| +| `base_angular_velocity` | 3 | IMU angular velocity (rad/s): `[roll_rate, pitch_rate, yaw_rate]` | +| `body_joint_positions` | 29 | Current joint positions from encoders (rad, IsaacLab order) | +| `body_joint_velocities` | 29 | Current joint velocities from encoders (rad/s, IsaacLab order) | +| `last_actions` | 29 | Previous policy output (normalised action values) | +| `gravity_dir` | 3 | Gravity direction in body frame (computed from base IMU quaternion) | + +### Multi-Frame History (4 frames, step 1) + +| Name | Dim | Description | +|---|---|---| +| `his_body_joint_positions_4frame_step1` | 116 | Joint positions: 4 consecutive ticks (29 × 4) | +| `his_body_joint_velocities_4frame_step1` | 116 | Joint velocities: 4 consecutive ticks | +| `his_last_actions_4frame_step1` | 116 | Past actions: 4 consecutive ticks | +| `his_base_angular_velocity_4frame_step1` | 12 | Angular velocity: 4 consecutive ticks (3 × 4) | +| `his_gravity_dir_4frame_step1` | 12 | Gravity direction: 4 consecutive ticks | + +### Multi-Frame History (10 frames, step 1) + +| Name | Dim | Description | +|---|---|---| +| `his_body_joint_positions_10frame_step1` | 290 | Joint positions: 10 consecutive ticks (29 × 10) | +| `his_body_joint_velocities_10frame_step1` | 290 | Joint velocities: 10 consecutive ticks | +| `his_last_actions_10frame_step1` | 290 | Past actions: 10 consecutive ticks | +| `his_base_angular_velocity_10frame_step1` | 30 | Angular velocity: 10 consecutive ticks (3 × 10) | +| `his_gravity_dir_10frame_step1` | 30 | Gravity direction: 10 consecutive ticks | + +--- + +## Creating Custom Observations + +You can add your own observation types by modifying the C++ source. The observation system is built around a **registry pattern** — you write a gatherer function, register it with a name and dimension, and then use that name in your YAML config. + +All observation code lives in `gear_sonic_deploy/src/g1/g1_deploy_onnx_ref/src/g1_deploy_onnx_ref.cpp` inside the `G1Deploy` class. + +### Step 1: Write a Gatherer Function + +A gatherer function reads from internal state (sensor data, motion data, etc.) and writes its output into a target buffer at a given offset. The signature is: + +```cpp +bool MyObservation(std::vector& target_buffer, size_t offset) { + // Write your observation values into target_buffer starting at offset. + // Return true on success, false on failure (will stop the control loop). +} +``` + +**Available data sources inside G1Deploy** (see member variables in `g1_deploy_onnx_ref.cpp` for the full list): + +| Source | Description | +|---|---| +| `state_logger_` | Ring buffer of past robot states — IMU, joints, velocities, actions, hand states, token state | +| `current_motion_` / `current_frame_` | Currently-active motion sequence and playback cursor | +| `operator_state` | Operator control flags (`.play`, `.start`, `.stop`) | +| `vr_*_buffer_`, `left_hand_joint_buffer_`, etc. | Buffered input interface data — VR tracking, hand joints, compliance, upper-body targets | +| `heading_state_buffer_`, `movement_state_buffer_` | Thread-safe buffers for heading and planner movement commands | + +**Example** — a custom observation that outputs the torso IMU angular velocity (3 values): + +```cpp +bool GatherTorsoAngularVelocity(std::vector& target_buffer, size_t offset) { + if (!state_logger_) { return false; } + + auto hist = state_logger_->GetLatest(1); + if (hist.empty()) { return false; } + + const auto& entry = hist[0]; + target_buffer[offset + 0] = entry.body_torso_ang_vel[0]; + target_buffer[offset + 1] = entry.body_torso_ang_vel[1]; + target_buffer[offset + 2] = entry.body_torso_ang_vel[2]; + return true; +} +``` + +### Step 2: Register in the Observation Registry + +Add your observation to the `GetObservationRegistry()` method in `g1_deploy_onnx_ref.cpp`. Each entry is a tuple of `{name, dimension, gatherer_lambda}`: + +```cpp +std::vector GetObservationRegistry() { + return { + // ... existing observations ... + + // Your custom observation: + {"torso_angular_velocity", 3, + [this](std::vector& buf, size_t offset) { + return GatherTorsoAngularVelocity(buf, offset); + }}, + }; +} +``` + +The **name** is the string you'll use in the YAML config. The **dimension** must be exact — the system validates that the total of all enabled observations matches the ONNX model input size. + +### Step 3: Use in YAML Config + +Once registered, your observation is available like any built-in one: + +```yaml +observations: + - name: "torso_angular_velocity" + enabled: true + # ... other observations ... +``` + +### Tips + +- **Dimension must be fixed.** The observation dimension is set at registration time and cannot change at runtime. If you need variable-size data, pad to a fixed maximum. +- **Don't allocate in the hot path.** Gatherer functions run at 50 Hz in the control loop. Avoid `new`, `malloc`, or resizing vectors. Pre-allocate buffers in the constructor or use stack arrays. +- **Return `false` carefully.** Returning `false` from a gatherer stops the entire control loop. Only return `false` for unrecoverable errors. For missing optional data, write zeros and return `true`. +- **Thread safety.** Gatherers run on the control thread. Reading from `state_logger_` and `DataBuffer` objects is thread-safe. Accessing `current_motion_` and `current_frame_` is protected by `current_motion_mutex_` (already held when `GatherObservations()` is called). +- **Multi-frame pattern.** If your observation needs temporal windows, follow the existing `GatherHis*` or `GatherMotion*MultiFrame` patterns — they accept `num_frames` and `step_size` parameters and register multiple variants (e.g., `my_obs`, `my_obs_4frame_step1`, `my_obs_10frame_step5`). +- **Encoder observations.** Custom observations can also be used as encoder inputs. Register them in the same registry — they'll be available for both `observations:` and `encoder_observations:` in the YAML config. +- **Rebuild after changes.** After modifying the C++ source, rebuild with `just build` from the `gear_sonic_deploy/` directory. + +--- + +## Example Configurations + +### Minimal (154D — default policy) + +```yaml +observations: + - name: "motion_joint_positions" # 29D + enabled: true + - name: "motion_joint_velocities" # 29D + enabled: true + - name: "motion_anchor_orientation" # 6D + enabled: true + - name: "base_angular_velocity" # 3D + enabled: true + - name: "body_joint_positions" # 29D + enabled: true + - name: "body_joint_velocities" # 29D + enabled: true + - name: "last_actions" # 29D + enabled: true +# Total: 154D +``` + +### Token-Based Policy with Encoder + +```yaml +observations: + - name: "token_state" # 64D (from encoder) + enabled: true + - name: "base_angular_velocity" # 3D + enabled: true + - name: "body_joint_positions" # 29D + enabled: true + - name: "body_joint_velocities" # 29D + enabled: true + - name: "last_actions" # 29D + enabled: true + +encoder: + dimension: 64 + use_fp16: false + encoder_observations: + - name: "motion_joint_positions_10frame_step5" # 290D + enabled: true + - name: "motion_joint_velocities_10frame_step5" # 290D + enabled: true + - name: "motion_anchor_orientation_10frame_step5" # 60D + enabled: true + - name: "motion_root_z_position_10frame_step5" # 10D + enabled: true +``` + +### VR Teleoperation Policy + +```yaml +observations: + - name: "token_state" # 64D + enabled: true + - name: "vr_3point_local_target" # 9D + enabled: true + - name: "vr_3point_local_orn_target" # 12D + enabled: true + - name: "vr_3point_compliance" # 3D + enabled: true + - name: "base_angular_velocity" # 3D + enabled: true + - name: "body_joint_positions" # 29D + enabled: true + - name: "body_joint_velocities" # 29D + enabled: true + - name: "last_actions" # 29D + enabled: true +``` + +See [Configuration Format](obs-config-format) above for YAML syntax details. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/planner_onnx.md b/third-party/GR00T-WholeBodyControl/docs/source/references/planner_onnx.md new file mode 100644 index 0000000000000000000000000000000000000000..d0d2e8c6fd567723af31894582ccb81ce5743cdb --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/planner_onnx.md @@ -0,0 +1,493 @@ +# Kinematic Planner ONNX Model Reference + +This page provides a detailed specification of the **Kinematic Planner** ONNX model inputs and outputs. The kinematic planner is the core motion generation component of the GEAR-SONIC system: given the robot's current state and high-level navigation commands, it produces a sequence of future whole-body poses (MuJoCo `qpos` frames) that the low-level whole-body controller then tracks. + +The ONNX model is part of the **C++ inference stack** and is called by the deployment runtime during operation. The C++ stack manages input construction, timing, and state management — certain combinations of inputs are invalid and are handled by the C++ layer to ensure safe operation. This page is intended for developers who want to understand the model interface at a deeper level or build custom integrations beyond the standard deployment pipeline. + +```{admonition} Training Code & Technical Report +:class: note +The kinematic planner training code and technical report will be released soon. This page documents the ONNX model interface for deployment integration. +``` + +--- + +## Overview + +The planner takes **11 input tensors** and produces **2 output tensors**. The 6 primary inputs are listed below; the remaining 5 are advanced inputs managed by the C++ stack and should not need to be modified in most cases. + +**Primary inputs:** + +| Tensor Name | Shape | Dtype | Default | +|-------------|-------|-------|---------| +| `context_mujoco_qpos` | `[1, 4, 36]` | `float32` | Required | +| `target_vel` | `[1]` | `float32` | `-1.0` (use mode default velocity) | +| `mode` | `[1]` | `int64` | Required | +| `movement_direction` | `[1, 3]` | `float32` | Required | +| `facing_direction` | `[1, 3]` | `float32` | Required | +| `height` | `[1]` | `float32` | `-1.0` (disable height control) | + +**Outputs:** + +| Tensor Name | Shape | Dtype | +|-------------|-------|-------| +| `mujoco_qpos` | `[1, N, 36]` | `float32` | +| `num_pred_frames` | scalar | `int64` | + +Where: +- **K** = `max_tokens - min_tokens + 1` (model-dependent; the range of allowed prediction horizons) +- **N** = maximum number of output frames (padded); only the first `num_pred_frames` frames are valid + +--- + +## Coordinate System + +The model operates in **MuJoCo's Z-up coordinate convention**: + +- **X** — forward +- **Y** — left +- **Z** — up + +All position and direction vectors in the inputs and outputs follow this convention. + +--- + +## Input Tensors + +(context_mujoco_qpos)= +### `context_mujoco_qpos` + +| Property | Value | +|----------|-------| +| **Shape** | `[1, 4, 36]` | +| **Dtype** | `float32` | +| **Description** | The planner's context input consisting of 4 consecutive MuJoCo `qpos` frames representing the recent states of the robot | + +This is the primary context input. It provides 4 frames of the robot's recent joint configuration at the simulation framerate. +The 36 dimensions of each frame are the standard MuJoCo `qpos` vector for the Unitree G1 (29-DOF) model: + +| Index | Field | Description | +|-------|-------|-------------| +| 0–2 | Root position | `(x, y, z)` in meters, Z-up world frame | +| 3–6 | Root quaternion | `(w, x, y, z)` orientation — MuJoCo convention | +| 7–35 | DOF positions | 29 joint angles in radians, following MuJoCo body tree order | + +```{admonition} Coordinate Frame +:class: note +All inputs — including `context_mujoco_qpos`, `movement_direction`, `facing_direction`, `specific_target_positions`, and `specific_target_headings` — should be provided in the **world coordinate frame**. The root quaternion uses MuJoCo's `(w, x, y, z)` ordering at indices 3 to 6. The model handles canonicalization internally. +``` + +### `target_vel` + +| Property | Value | +|----------|-------| +| **Shape** | `[1]` | +| **Dtype** | `float32` | +| **Description** | Desired locomotion speed override | + +Controls the target movement speed. When set to **zero or below** (e.g., `-1.0`), the model uses the default velocity for the selected mode. When set to a **positive value**, it overrides the mode's default speed (in meters per second). Note that the actual achieved speed may differ from the target due to the critically damped spring model and motion dynamics. + +| Value | Behavior | +|-------|----------| +| `<= 0.0` | Use the default velocity for the selected `mode` | +| `> 0.0` | Override with this target velocity (m/s) | + + +### `mode` + +| Property | Value | +|----------|-------| +| **Shape** | `[1]` | +| **Dtype** | `int64` | +| **Description** | Index selecting the motion style/behavior | + +Selects the motion style from the pre-loaded clip library. The mode index is clamped to the number of available clips at runtime. The default planner ships with the following modes: + +**Locomotion set:** + +| Index | Mode | Description | +|-------|------|-------------| +| 0 | `idle` | Standing still | +| 1 | `slowWalk` | Slow forward locomotion | +| 2 | `walk` | Normal walking speed | +| 3 | `run` | Running | + +**Squat / ground set:** + +| Index | Mode | Description | +|-------|------|-------------| +| 4 | `squat` | Squatting — requires `height` input (range ~0.4–0.8m) | +| 5 | `kneelTwoLeg` | Kneeling on both knees — requires `height` input (0.2m-0.4m) | +| 6 | `kneelOneLeg` | Kneeling on one knee — requires `height` input (0.2m-0.4m) | +| 7 | `lyingFacedown` | Lying face down — requires `height` input | +| 8 | `handCrawling` | Crawling on hands and knees | +| 14 | `elbowCrawling` | Crawling on elbows (more likely to overheat) | + +**Boxing set:** + +| Index | Mode | Description | +|-------|------|-------------| +| 9 | `idleBoxing` | Boxing stance (idle) | +| 10 | `walkBoxing` | Walking with boxing guard | +| 11 | `leftJab` | Left jab | +| 12 | `rightJab` | Right jab | +| 13 | `randomPunches` | Random punch sequence | +| 15 | `leftHook` | Left hook | +| 16 | `rightHook` | Right hook | + +**Style walks:** + +| Index | Mode | Description | +|-------|------|-------------| +| 17 | `happy` | Happy walking | +| 18 | `stealth` | Stealthy walking | +| 19 | `injured` | Limping walk | +| 20 | `careful` | Cautious walking | +| 21 | `objectCarrying` | Walking with hands reaching out | +| 22 | `crouch` | Crouched walking | +| 23 | `happyDance` | Dancing walk (only walk forward) | +| 24 | `zombie` | Zombie walk | +| 25 | `point` | Walking with hands pointing | +| 26 | `scared` | Scared walk | + +### `movement_direction` + +| Property | Value | +|----------|-------| +| **Shape** | `[1, 3]` | +| **Dtype** | `float32` | +| **Description** | Desired direction of movement in the MuJoCo world frame | + +A 3D direction vector `(x, y, z)` in the Z-up world coordinate system indicating where the robot should move. It is recommended to pass a normalized vector for good practice, though the model normalizes internally. Speed is controlled by `target_vel` and `mode`, not by the magnitude of this vector. + +- The planner uses the `(x, y)` components (horizontal plane) for computing the target root trajectory via a critically-damped spring model. +- When the magnitude is near zero (`< 1e-5`), the model falls back to using the `facing_direction` with a small scaling factor for in-place turning. + + +### `facing_direction` + +| Property | Value | +|----------|-------| +| **Shape** | `[1, 3]` | +| **Dtype** | `float32` | +| **Description** | Desired facing (heading) direction in the MuJoCo world frame | + +A 3D direction vector `(x, y, z)` indicating which direction the robot's torso should face. The target heading angle is computed as `atan2(y, x)` from this vector. Like `movement_direction`, this does not need to be normalized. + +This is independent of `movement_direction` — the robot can walk in one direction while facing another (e.g., strafing). + + +### `height` + +| Property | Value | +|----------|-------| +| **Shape** | `[1]` | +| **Dtype** | `float32` | +| **Description** | Desired root height for height-aware behaviors | + +Controls the target pelvis height for modes that support variable height (e.g., `squat`, `kneelTwoLeg`, `kneelOneLeg`, `lyingFacedown`). When a positive value is provided, the model searches the reference clip's keyframes and selects the one whose root height is closest to the requested value, using it as the target pose for motion generation. + +| Value | Behavior | +|-------|----------| +| `< 0.0` | Height control disabled; use the randomly-selected keyframe from the reference clip | +| `>= 0.0` | Find the closest height keyframe in the reference clip and use it as the target pose (meters) | + + +
+ +## Advanced Inputs + +These inputs are managed internally by the C++ deployment stack and **should not be modified** under normal operation. They are documented here for completeness and for advanced users who need to build custom integrations. + +### `random_seed` + +| Property | Value | +|----------|-------| +| **Shape** | `[1]` | +| **Dtype** | `int64` | +| **Description** | Seed for controlling network randomness | + + +### `has_specific_target` + +| Property | Value | +|----------|-------| +| **Shape** | `[1, 1]` | +| **Dtype** | `int64` | +| **Description** | Flag indicating whether specific waypoint targets are provided | + +| Value | Behavior | +|-------|----------| +| `0` | Ignore `specific_target_positions` and `specific_target_headings`; use `movement_direction` / `facing_direction` | +| `1` | Use the provided specific target positions and headings as waypoint constraints | + +When enabled, the spring model's target root position and heading are overridden by the values in `specific_target_positions` and `specific_target_headings`. + + +### `specific_target_positions` + +| Property | Value | +|----------|-------| +| **Shape** | `[1, 4, 3]` | +| **Dtype** | `float32` | +| **Description** | 4 waypoint positions in MuJoCo world coordinates | + +Each waypoint is a 3D position `(x, y, z)` in the Z-up world frame. The 4 waypoints correspond to 4 frames (one token's worth) of target root positions. Only used when `has_specific_target = 1`. + + +### `specific_target_headings` + +| Property | Value | +|----------|-------| +| **Shape** | `[1, 4]` | +| **Dtype** | `float32` | +| **Description** | 4 waypoint heading angles in radians | + +Target heading (yaw) angles for each of the 4 waypoint frames. These are absolute angles in the Z-up world frame, measured as rotation around the Z-axis. Only used when `has_specific_target = 1`. The last waypoint's heading (`[:, -1]`) is used as the primary target heading for the spring model. + + +### `allowed_pred_num_tokens` + +| Property | Value | +|----------|-------| +| **Shape** | `[1, K]` where `K = max_tokens - min_tokens + 1` | +| **Dtype** | `int64` | +| **Description** | Binary mask controlling the allowed prediction horizon | + +A binary mask where each element corresponds to a possible number of predicted tokens. Index `i` maps to `min_tokens + i` tokens. A value of `1` means that prediction length is allowed; `0` means it is disallowed. + +Since each token represents 4 frames, the prediction horizon in frames is `num_tokens * 4`. In our default planner we have `min_tokens = 6` and `max_tokens = 16`: + +| Index | Tokens | Frames | +|-------|--------|--------| +| 0 | 6 | 24 | +| 1 | 7 | 28 | +| 2 | 8 | 32 | +| 3 | 9 | 36 | +| 4 | 10 | 40 | +| 5 | 11 | 44 | +| 6 | 12 | 48 | +| 7 | 13 | 52 | +| 8 | 14 | 56 | +| 9 | 15 | 60 | +| 10 | 16 | 64 | + +--- + +## Output Tensors + +### `mujoco_qpos` + +| Property | Value | +|----------|-------| +| **Shape** | `[1, N, 36]` | +| **Dtype** | `float32` | +| **Description** | Predicted motion sequence as MuJoCo `qpos` frames | + +The primary output: a sequence of whole-body pose frames in the same 36-dimensional MuJoCo `qpos` format as the input (see {ref}`context_mujoco_qpos ` for the dimension layout). + +```{admonition} Important: Use num_pred_frames to Truncate +:class: warning +The output tensor `mujoco_qpos` is **not truncated** — it contains the full padded buffer. Only the first `num_pred_frames` frames are valid predictions. When consuming this output, always slice: +``` + +```python +valid_qpos = mujoco_qpos[:, :num_pred_frames, :] +``` + +The poses are in the **global MuJoCo world frame** (not canonicalized). The model internally handles canonicalization, inference, and coordinate conversion, then transforms the output back to the original world frame. The first 4 predicted frames are blended with the input context for smooth transitions. + +The root quaternion in the output uses `(w, x, y, z)` ordering (MuJoCo convention). + + +### `num_pred_frames` + +| Property | Value | +|----------|-------| +| **Shape** | scalar | +| **Dtype** | `int64` | +| **Description** | Number of valid predicted frames in the `mujoco_qpos` output | + +This value equals `num_pred_tokens * 4`, where `num_pred_tokens` is the number of motion tokens the model decided to generate (constrained by `allowed_pred_num_tokens`). Use this value to slice the `mujoco_qpos` output. + +--- + +## Internal Pipeline + +1. **Canonicalization** — The input qpos is transformed to a body-relative frame by removing the first frame's heading rotation and horizontal position. This helps the model generalize across different starting orientations and positions. + +2. **Spring Model** — A critically-damped spring model generates smooth target root trajectories and heading angles from the high-level commands, using mode-dependent average velocities from the training clips. + +3. **Target Pose Selection** — Based on the `mode` and `random_seed`, a target pose is fetched from the pre-loaded clip library and aligned (rotated/translated) to match the spring model's predicted target position and heading. + +4. **Motion Inference** — The core motion model fills in the motion between the context (current state) and target (desired future state), producing a natural transition. + +5. **Post-processing** — The output is converted back to MuJoCo qpos in the original world frame, and the first 4 frames are blended with the input context for smooth transitions. + +--- + +## Deployment Integration + +This section describes how the C++ deployment stack uses the planner at runtime. Understanding this is useful for building custom integrations or modifying the replan behavior. + +### Threading Model + +The planner runs on a **dedicated thread at 10 Hz** (`planner_dt = 0.1s`), separate from the control loop (50 Hz) and input thread (100 Hz). The planner thread: + +1. Reads the latest `MovementState` from a thread-safe buffer (written by the input interface). +2. Decides whether a replan is needed. +3. If so, calls `UpdatePlanning()` which runs TensorRT inference. +4. Stores the result in a shared buffer that the control thread picks up on its next tick. + +### Initialization + +When the planner is first enabled (e.g., pressing **ENTER** on the keyboard interface), the planner thread: + +1. Reads the robot's current base quaternion and joint positions from the latest `LowState`. +2. Calls `Initialize()`, which: + - Sets up a 4-frame context at the default standing height with zero-yaw orientation. + - Runs an initial inference with `IDLE` mode and no movement. + - Resamples the 30 Hz output to 50 Hz. +3. The control thread detects the new planner motion and switches `current_motion_` to the planner output. + +### Context Construction + +The planner requires a 4-frame context (`context_mujoco_qpos` of shape `[1, 4, 36]`). During operation, this context is sampled from the **current planner motion** (not the robot state): + +- The context starts at `gen_frame = current_frame + motion_look_ahead_steps` (default look-ahead = 2 frames at 50 Hz). +- 4 frames are sampled at 30 Hz intervals from this starting point. +- Joint positions, body positions, and quaternions are linearly interpolated (quaternions via slerp) between 50 Hz motion frames to produce the 30 Hz context samples. + +### Replan Logic + +Not every planner tick triggers a replan. The decision follows this priority: + +**1. Always replan when** (regardless of static/non-static mode): +- Locomotion mode changed +- Facing direction changed +- Height changed + +**2. For non-static modes only**, also replan when any of the following is true: +- Movement speed changed +- Movement direction changed +- Periodic replan timer expired **and** movement speed is non-zero + +Static modes (Idle, Squat, Kneel, Lying, Idle Boxing) **never** trigger replans from the second category — they only replan on mode/facing/height changes from the first category. + +**Replan intervals** (periodic timer) vary by locomotion type to balance responsiveness and computational cost: + +| Locomotion Type | Replan Interval | +|----------------|-----------------| +| Running | 0.1 s (every planner tick) | +| Crawling | 0.2 s | +| Boxing (punches, hooks) | 1.0 s | +| All others (walk, squat, styled, etc.) | 1.0 s | + +The periodic timer only triggers a replan if the current movement speed is non-zero — a stationary robot in a non-static mode (e.g., Walk mode with speed 0) will not replan on the timer. + +### Output Resampling (30 Hz → 50 Hz) + +The planner model outputs frames at **30 Hz**. The deployment stack resamples them to **50 Hz** (the control loop rate) using linear interpolation: + +- For each 50 Hz frame, compute the corresponding fractional 30 Hz frame index. +- Linearly interpolate joint positions and body positions between the two nearest 30 Hz frames. +- Slerp-interpolate body quaternions. +- Compute joint velocities by finite differencing the resampled positions (`(pos[t+1] - pos[t]) * 50`). + +The resampled motion is stored in `planner_motion_50hz_` and has `num_pred_frames * 50/30` frames (rounded down). + +### Animation Blending + +When a new planner output arrives while the previous one is still playing, the control thread **blends** the old and new animations over an 8-frame cross-fade: + +1. The old animation is rebased so `current_frame` maps to frame 0. +2. The new animation is aligned to start at `gen_frame - current_frame` in the rebased timeline. +3. Over 8 frames starting from the blend point, a linearly increasing weight `w_new` (0 → 1) is applied: + - Joint positions/velocities: `w_old * old + w_new * new` + - Body positions: `w_old * old + w_new * new` + - Body quaternions: `slerp(old, new, w_new)` +4. After the blend region, the new animation takes over completely. +5. `current_frame` is reset to 0 on the blended result. + +This ensures smooth transitions between successive planner outputs without visible discontinuities. + +### TensorRT Acceleration + +The planner runs via **TensorRT** with CUDA graph capture for low-latency inference: + +1. At startup, the ONNX model is converted to a TensorRT engine (cached on disk). +2. A **CUDA graph** is captured during initialization — this records the entire inference pass (input copy → kernel launches → output copy) as a single replayable graph. +3. On each replan, inputs are copied to GPU via pinned memory (`TPinnedVector`), the CUDA graph is launched, and outputs are copied back. +4. FP16 precision is supported via `--planner-precision 16` (default is FP32). + +### Planner Model Versions + +The deployment stack supports multiple planner model versions, auto-detected from the model filename: + +| Version | Inputs | Modes | Description | +|---------|--------|-------|-------------| +| V0 | 6 | 4 (Idle, Slow Walk, Walk, Run) | Basic locomotion only | +| V1 | 11 | 20 | Adds squat/kneel/boxing/styled walks + height control + waypoint targets | +| V2 | 11 | 27 | All V1 modes + additional styled walking modes | + +The version is determined by the presence of `V0`, `V1`, or `V2` in the planner model filename. Version determines: +- The number of input tensors (6 vs 11) +- The valid range of `mode` values +- Whether `height`, `has_specific_target`, `specific_target_positions`, `specific_target_headings`, and `allowed_pred_num_tokens` inputs are used + +--- + +## Model Properties + +The exported ONNX model has the following properties: + +- **ONNX opset version**: 17 +- **Batch size**: 1 (fixed) + +The model is distributed as a single `.onnx` file, along with a `.pt` file containing reference input/output tensors that can be used for validation. + +```{admonition} Coming Soon +:class: note +The training code, export tooling, and a full technical report will be released soon. Stay tuned for updates. +``` + +--- + +## Usage Example + +```python +import onnxruntime as ort +import numpy as np + +# Load the ONNX model +session = ort.InferenceSession("kinematic_planner.onnx") + +# Primary inputs +inputs = { + "context_mujoco_qpos": current_qpos_buffer.astype(np.float32), # [1, 4, 36] + "target_vel": np.array([-1.0], dtype=np.float32), # -1.0 = use mode default + "mode": np.array([2], dtype=np.int64), # 2 = walk + "movement_direction": np.array([[1.0, 0.0, 0.0]], dtype=np.float32), # forward + "facing_direction": np.array([[1.0, 0.0, 0.0]], dtype=np.float32), # face forward + "height": np.array([-1.0], dtype=np.float32), # -1.0 = disabled + + # Advanced inputs (typically managed by the C++ stack) + "random_seed": np.array([1234], dtype=np.int64), + "has_specific_target": np.array([[0]], dtype=np.int64), + "specific_target_positions": np.zeros([1, 4, 3], dtype=np.float32), + "specific_target_headings": np.zeros([1, 4], dtype=np.float32), + "allowed_pred_num_tokens": np.ones([1, 11], dtype=np.int64), # K = 11 for default model +} + +# Run inference +mujoco_qpos, num_pred_frames = session.run(None, inputs) + +# Extract valid frames only +num_frames = int(num_pred_frames) +predicted_motion = mujoco_qpos[0, :num_frames, :] # [num_frames, 36] + +# Each row: [x, y, z, qw, qx, qy, qz, 29 joint angles in radians] +for frame in predicted_motion: + root_pos = frame[:3] + root_quat = frame[3:7] # (w, x, y, z) + joint_angles = frame[7:36] # 29 DOF positions +``` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/references/training_code.md b/third-party/GR00T-WholeBodyControl/docs/source/references/training_code.md new file mode 100644 index 0000000000000000000000000000000000000000..6c8bd5c6e58adae2ff674b05e64764216661913e --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/references/training_code.md @@ -0,0 +1,375 @@ +# Training Code Structure + +This page describes the Python training codebase under `gear_sonic/`, covering directory layout, the training pipeline, configuration system, key modules, and evaluation scripts. + +--- + +## Directory Layout + +``` +gear_sonic/ +├── train_agent_trl.py # Main training entry point +├── eval_agent_trl.py # Single-checkpoint evaluation +├── eval_exp.py # Checkpoint monitor (continuous eval) +├── config/ # Hydra configuration hierarchy +│ ├── base.yaml # Global defaults (seed, num_envs, paths) +│ ├── base_eval.yaml # Eval-specific global defaults +│ ├── eval_exp.yaml # Checkpoint monitor config +│ ├── base/ # Hydra plumbing (output dirs, resolvers) +│ ├── algo/ # PPO hyperparameters +│ ├── actor_critic/ # Actor-critic architecture configs +│ │ ├── encoders/ # Per-encoder MLP configs (g1, smpl, teleop) +│ │ ├── decoders/ # Decoder MLP configs (g1_kin, g1_dyn) +│ │ ├── critics/ # Critic backbone configs +│ │ ├── quantizers/ # FSQ quantizer config +│ │ └── universal_token/ # Assembled encoder+decoder+quantizer presets +│ ├── aux_losses/ # Auxiliary loss definitions +│ ├── callbacks/ # Training callback configs +│ ├── exp/ # Experiment presets (compose all pieces) +│ ├── manager_env/ # Environment MDP component configs +│ ├── opt/ # Logging options (wandb) +│ └── trainer/ # Trainer class selection +├── envs/ # IsaacLab environment wrappers +│ ├── manager_env/ +│ │ ├── modular_tracking_env_cfg.py # Scene, sensors, robot articulation +│ │ ├── robots/ # Per-robot configs (g1.py, h2.py) +│ │ └── mdp/ # MDP components (see below) +│ ├── wrapper/ +│ │ └── manager_env_wrapper.py # RL-facing env wrapper +│ └── env_utils/ # Joint ordering utilities +├── trl/ # Training modules (PPO, actor-critic, losses) +│ ├── trainer/ +│ │ ├── ppo_trainer.py # Base PPO trainer +│ │ └── ppo_trainer_aux_loss.py # PPO + auxiliary losses (SONIC) +│ ├── modules/ +│ │ ├── actor_critic_modules.py # Actor, Critic classes +│ │ ├── universal_token_modules.py # UniversalTokenModule (SONIC ATM) +│ │ ├── base_module.py # Shared MLP building blocks +│ │ └── data_utils.py # Batch/data helpers +│ ├── losses/ +│ │ └── token_losses.py # Reconstruction & latent auxiliary losses +│ ├── callbacks/ # Runtime callbacks +│ │ ├── im_eval_callback.py # Imitation evaluation metrics +│ │ ├── im_resample_callback.py # Adaptive motion resampling +│ │ ├── model_save_callback.py # Checkpoint saving +│ │ ├── wandb_callback.py # W&B logging +│ │ └── read_eval_callback.py # Read eval results from disk +│ └── utils/ # Math, rotation, scheduling utilities +├── utils/ # Shared utilities +│ ├── motion_lib/ # Motion library loading (PKL format) +│ ├── mujoco_sim/ # MuJoCo sim-to-sim bridge +│ └── teleop/ # VR teleoperation helpers +├── data/ # Robot models, URDF/USD assets +├── data_process/ # Motion data conversion scripts +└── scripts/ # MuJoCo sim loop, misc tools +``` + +--- + +## Training Pipeline + +Running `python gear_sonic/train_agent_trl.py +exp=manager/universal_token/all_modes/sonic_release` executes the following steps: + +### 1. Configuration Loading + +The entry point uses `@hydra.main(config_path="config", config_name="base")`. The `+exp=...` argument selects an experiment preset that composes all sub-configs: + +``` +base.yaml # Global defaults + └── +exp=manager/universal_token/all_modes/sonic_release + ├── /algo: ppo_im_phc # PPO hyperparameters + ├── /actor_critic: universal_token/all_mlp_v1 + │ ├── encoders/g1_mf_mlp, smpl_mlp, teleop_mlp + │ ├── decoders/g1_kin_mf_mlp, g1_dyn_mlp + │ ├── quantizers/fsq + │ └── critics/mlp + ├── /manager_env: base_env # Environment config + │ ├── observations/{tokenizer, policy, critic} + │ ├── rewards/tracking/base_5point_local_feet_acc + │ ├── terminations/tracking/base_adaptive_strict_ori_foot_xyz + │ └── events/tracking/level0_4 + ├── /aux_losses: universal_token/g1_recon_and_all_latent + ├── /trainer: trl_ppo_aux + └── /callbacks: model_save, wandb, read_eval, im_resample +``` + +### 2. Simulator and Accelerator Init + +After config resolution, the script: +1. Parses TRL `PPOConfig` / `ScriptArguments` / `ModelConfig` from the config dict. +2. Creates a HuggingFace `Accelerator` for multi-GPU support (DDP). +3. Launches the IsaacLab `AppLauncher` to start the Isaac Sim runtime. +4. Saves `config.yaml` and `meta.yaml` to the experiment directory. + +### 3. Environment Creation + +`create_manager_env()` instantiates the IsaacLab `ManagerBasedRLEnv` from the composed environment config, then wraps it with `ManagerEnvWrapper`: + +``` +ManagerBasedRLEnv (IsaacLab) + └── ManagerEnvWrapper + ├── Observation spaces (policy, critic, tokenizer groups) + ├── Motion command manager (motion_lib) + ├── Action transform module (optional, for pretrained ATM) + └── Keyboard / visualization hooks +``` + +### 4. Policy and Value Model Creation + +The actor and critic are instantiated from the algo config. For SONIC training, the actor backbone is `UniversalTokenModule`: + +```python +# Simplified from train_agent_trl.py +policy = custom_instantiate(config.algo.config.actor, env_config=env.config, ...) +value_model = custom_instantiate(config.algo.config.critic, env_config=env.config, ...) +``` + +The `Actor` wraps `UniversalTokenModule` as its backbone and adds a diagonal Gaussian distribution for exploration. The `Critic` wraps a separate MLP backbone. + +### 5. PPO Training Loop + +The `TRLAuxLossPPOTrainer.train()` method runs the main loop: + +``` +for iteration in range(num_learning_iterations): + # 1. Rollout: collect num_steps_per_env transitions + for step in range(num_steps_per_env): + actions = policy.rollout(obs_dict) + obs_dict, rewards, dones, infos = env.step(actions) + store(obs, actions, rewards, values, log_probs) + + # 2. GAE: compute advantages and returns + advantages = generalized_advantage_estimation(rewards, values, dones) + + # 3. PPO update: num_ppo_epochs over mini-batches + for epoch in range(num_ppo_epochs): + for mini_batch in shuffle_and_split(rollout_data): + policy_loss = clipped_surrogate_objective(...) + value_loss = clipped_value_loss(...) + aux_loss = sum(coef_i * aux_loss_i) # encoder reconstruction, etc. + total_loss = policy_loss + value_loss_coef * value_loss + + aux_loss_scale * aux_loss + optimizer.step(total_loss) + + # 4. Post-update: sync running stats, adaptive sampling, callbacks + update_scheduled_params(...) # learning rate, domain randomization + callbacks.on_step_end(...) # checkpointing, evaluation, logging +``` + +--- + +## Configuration System + +The configuration system uses [Hydra](https://hydra.cc/) with config groups and composition. + +### Hierarchy + +| Level | Path | Purpose | +|---|---|---| +| **Global** | `config/base.yaml` | Seed, num_envs, paths, wandb toggle | +| **Algorithm** | `config/algo/ppo_im_phc.yaml` | PPO hyperparameters, learning rates, epochs | +| **Actor-Critic** | `config/actor_critic/` | Network architecture (encoders, decoders, critic) | +| **Environment** | `config/manager_env/` | Observations, rewards, terminations, events | +| **Auxiliary Losses** | `config/aux_losses/` | Reconstruction and latent alignment losses | +| **Trainer** | `config/trainer/` | Trainer class selection (PPO or PPO+AuxLoss) | +| **Callbacks** | `config/callbacks/` | Checkpointing, evaluation, W&B logging | +| **Experiment** | `config/exp/` | Preset that composes all the above | + +### Experiment Presets + +Experiment configs live under `config/exp/` and use the `@package _global_` directive to set values at the root level. They compose all component configs via `defaults`: + +```yaml +# config/exp/manager/universal_token/all_modes/sonic_release.yaml +defaults: + - /algo: ppo_im_phc + - /manager_env: base_env + - override /actor_critic: universal_token/all_mlp_v1 + - override /manager_env/observations/tokenizer: unitoken_all_noz + - override /manager_env/observations/policy: local_dir_hist + - override /manager_env/rewards: tracking/base_5point_local_feet_acc + - override /manager_env/terminations: tracking/base_adaptive_strict_ori_foot_xyz + - override /manager_env/events: tracking/level0_4 + # ... +``` + +### Key Config Parameters + +| Parameter | Default | Description | +|---|---|---| +| `num_envs` | 4096 | Number of parallel simulation environments | +| `algo.config.num_learning_iterations` | 100000 | Total training iterations | +| `algo.config.num_steps_per_env` | 32 | Rollout horizon per iteration | +| `algo.config.num_learning_epochs` | 5 | PPO epochs per iteration | +| `algo.config.num_mini_batches` | 4 | Mini-batches per PPO epoch | +| `algo.config.actor_learning_rate` | 2e-5 | Actor learning rate | +| `algo.config.critic_learning_rate` | 1e-3 | Critic learning rate | +| `algo.config.clip_param` | 0.2 | PPO clipping parameter | +| `algo.config.init_noise_std` | 0.05 | Initial exploration noise std | +| `algo.config.save_interval` | 500 | Checkpoint save frequency (iterations) | + +--- + +## Universal Token Module + +The `UniversalTokenModule` implements SONIC's action transform module (ATM) -- the core architecture that maps diverse motion inputs into a shared token space. + +### Architecture + +``` + ┌─────────────┐ + G1 obs ───► │ G1 Encoder │──┐ + └─────────────┘ │ + ┌─────────────┐ │ ┌─────────┐ ┌─────────────┐ + Teleop obs───► │Teleop Encdr │──┼──► │ FSQ │──► │ G1 Dynamic │──► joint actions + └─────────────┘ │ │Quantizer│ │ Decoder │ + ┌─────────────┐ │ └─────────┘ └─────────────┘ + SMPL obs ───► │ SMPL Encoder│──┘ │ + └─────────────┘ │ ┌─────────────┐ + └───────► │G1 Kinematic │──► (aux loss only) + │ Decoder │ + └─────────────┘ +``` + +**Encoders** map different observation modalities into a shared latent space. Each encoder is an MLP that takes modality-specific tokenizer observations and outputs a fixed-size latent vector. During training, one encoder is sampled per environment according to `encoder_sample_probs`. + +**FSQ Quantizer** discretizes the continuous latent into a finite set of tokens using Finite Scalar Quantization. Each latent dimension is independently quantized to one of `fsq_level_list` discrete levels. This produces a compact, discrete token representation. + +**Decoders** reconstruct outputs from the quantized tokens plus proprioception: +- **G1 Dynamic Decoder** (`g1_dyn`): Produces joint-space actions fed to the actuators. This is the only decoder used at deployment time. +- **G1 Kinematic Decoder** (`g1_kin`): Reconstructs future motion frames from tokens. Used only during training to compute reconstruction auxiliary losses. + +### Latent Residual Mode + +For downstream tasks (e.g., object manipulation), an external policy can inject corrections into the token space without retraining the base ATM: + +| Mode | Behavior | +|---|---| +| `post_quantization` (default) | Residual added after FSQ quantization | +| `pre_quantization` | Residual added before FSQ; the sum gets quantized | +| `pre_quantization_replace` | Latent is replaced entirely by the residual | + +### Encoder Sampling + +During training, each environment is randomly assigned an encoder per episode according to `encoder_sample_probs`. The `encoder_index` observation tells the module which encoder produced the current token. At deployment, only one encoder is active (selected by the observation configuration). + +--- + +## Environment Structure + +The training environment is built on IsaacLab's `ManagerBasedRLEnv` and uses a modular MDP design where each component is configured independently via YAML. + +### MDP Components + +All MDP components live in `gear_sonic/envs/manager_env/mdp/`: + +| Module | Config path | Description | +|---|---|---| +| `observations.py` | `config/manager_env/observations/` | Observation terms for policy, critic, and tokenizer groups | +| `actions.py` | `config/manager_env/actions/` | Joint position action space | +| `rewards.py` | `config/manager_env/rewards/` | Reward terms (tracking, regularization) | +| `terminations.py` | `config/manager_env/terminations/` | Episode termination conditions | +| `events.py` | `config/manager_env/events/` | Domain randomization events | +| `commands.py` | `config/manager_env/commands/` | Motion command generation (motion library) | +| `curriculum.py` | `config/manager_env/curriculum/` | Curriculum schedules | +| `terrain.py` | (inline) | Terrain generation | +| `recorders.py` | `config/manager_env/recorders/` | Video recording | + +### Observation Groups + +Observations are split into groups, each with its own config file: + +| Group | Purpose | Example terms | +|---|---|---| +| **policy** | Direct input to the policy MLP | joint_pos, joint_vel, base_ang_vel, gravity_dir, last_actions | +| **critic** | Privileged observations for the value function | All policy obs + base_lin_vel, body_pos, body_ori | +| **tokenizer** | Input to the UniversalTokenModule encoders | Multi-future joint commands, SMPL joints, VR targets, anchor orientations | + +### Reward Terms + +Reward configs compose individual terms from `config/manager_env/rewards/terms/`. Key tracking rewards: + +| Term | Description | +|---|---| +| `tracking_relative_body_pos` | Track reference body positions (5-point: root, wrists, feet) | +| `tracking_relative_body_ori` | Track reference body orientations | +| `tracking_anchor_pos` | Track root anchor position | +| `tracking_anchor_ori` | Track root anchor orientation | +| `tracking_body_linvel` | Track reference body linear velocities | +| `tracking_body_angvel` | Track reference body angular velocities | +| `action_rate_l2` | Penalize action jerk | +| `feet_acc` | Penalize foot acceleration (smoothness) | + +### ManagerEnvWrapper + +`ManagerEnvWrapper` bridges the IsaacLab environment with the RL training loop. It handles: +- Flattening observation dicts for the policy +- Applying the optional pretrained action transform module +- Motion replay mode +- Debug visualization and keyboard controls + +--- + +## Evaluation Scripts + +### eval_agent_trl.py -- Single Checkpoint + +Loads a single checkpoint and runs evaluation in Isaac Sim. Automatically reads the training `config.yaml` from the checkpoint directory to reconstruct the full configuration. + +```bash +# Interactive visualization +python gear_sonic/eval_agent_trl.py +checkpoint=path/to/model.pt +headless=False ++num_envs=1 + +# Headless with video rendering +python gear_sonic/eval_agent_trl.py +checkpoint=path/to/model.pt +headless=True \ + ++num_envs=16 +run_once=True \ + ++manager_env.config.save_rendering_dir=path/to/output \ + ++manager_env.config.render_results=True \ + +manager_env/recorders=render +``` + +Key features: +- Merges training config with eval overrides (`eval_overrides` in config) +- Removes train-only events and terminations automatically +- Supports `+run_once=True` to exit after all environments complete one episode +- Handles `+metrics_file` to render worst-performing motions from a prior eval + +### eval_exp.py -- Checkpoint Monitor + +`CheckpointEvaluator` continuously monitors an experiment directory for new checkpoints and evaluates them sequentially. It runs as a companion process alongside training. + +```bash +python gear_sonic/eval_exp.py ++experiment_dir=path/to/experiment +``` + +For each new checkpoint, it: +1. Runs metrics evaluation (launches `eval_agent_trl.py` via subprocess) +2. Runs video rendering for the hardest motions +3. Logs results and videos to W&B (resuming the training run) +4. Marks each checkpoint as evaluated to avoid redundant work + +Configuration (`config/eval_exp.yaml`): + +| Parameter | Description | +|---|---| +| `experiment_dir` | Path to the training experiment directory | +| `scan_interval` | Seconds between checkpoint scans (default: 60) | +| `num_eval_envs` | Number of environments for metric evaluation | +| `num_render_videos` | Number of videos to render per checkpoint | +| `eval_frequency` | Only evaluate every N-th checkpoint (default: all) | +| `single_pass` | Evaluate pending checkpoints once and exit | + +--- + +## Key Classes Reference + +| Class | Module | Description | +|---|---|---| +| `Actor` | `trl/modules/actor_critic_modules.py` | Policy network: backbone + diagonal Gaussian. Maintains observation buffer for temporal models. | +| `Critic` | `trl/modules/actor_critic_modules.py` | Value function network: backbone + scalar output. Supports running mean/std normalization. | +| `UniversalTokenModule` | `trl/modules/universal_token_modules.py` | SONIC ATM: multi-encoder, FSQ quantizer, multi-decoder. Computes auxiliary reconstruction losses. | +| `TRLPPOTrainer` | `trl/trainer/ppo_trainer.py` | Base PPO trainer adapted from HuggingFace TRL. Handles rollout collection, GAE, and gradient updates. | +| `TRLAuxLossPPOTrainer` | `trl/trainer/ppo_trainer_aux_loss.py` | Extends `TRLPPOTrainer` with auxiliary loss support (reconstruction, latent alignment). | +| `PolicyAndValueWrapper` | `trl/trainer/ppo_trainer.py` | Wraps policy + value model into a single `nn.Module` for DDP-safe forward passes. | +| `ManagerEnvWrapper` | `envs/wrapper/manager_env_wrapper.py` | Bridges IsaacLab `ManagerBasedRLEnv` with the training loop. Handles obs flattening, action transforms, replay. | +| `CheckpointEvaluator` | `eval_exp.py` | Monitors experiment directory, evaluates new checkpoints, logs to W&B. | diff --git a/third-party/GR00T-WholeBodyControl/docs/source/resources/citations.md b/third-party/GR00T-WholeBodyControl/docs/source/resources/citations.md new file mode 100644 index 0000000000000000000000000000000000000000..b84152f007cba7088223c0d18fb342e524942266 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/resources/citations.md @@ -0,0 +1,12 @@ +# Citations + +If you use GEAR-SONIC in your research, please cite: + +```bibtex +@article{luo2025sonic, + title={SONIC: Supersizing Motion Tracking for Natural Humanoid Whole-Body Control}, + author={Luo, Zhengyi and Yuan, Ye and Wang, Tingwu and Li, Chenran and Chen, Sirui and Casta\~neda, Fernando and Cao, Zi-Ang and Li, Jiefeng and Minor, David and Ben, Qingwei and Da, Xingye and Ding, Runyu and Hogg, Cyrus and Song, Lina and Lim, Edy and Jeong, Eugene and He, Tairan and Xue, Haoru and Xiao, Wenli and Wang, Zi and Yuen, Simon and Kautz, Jan and Chang, Yan and Iqbal, Umar and Fan, Linxi and Zhu, Yuke}, + journal={arXiv preprint arXiv:2511.07820}, + year={2025} +} +``` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/resources/contributing.md b/third-party/GR00T-WholeBodyControl/docs/source/resources/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..5da54b5ac2074175560eca185d76361bf3dc1e0f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/resources/contributing.md @@ -0,0 +1,3 @@ +# Contributing + +We welcome contributions! Coming soon... diff --git a/third-party/GR00T-WholeBodyControl/docs/source/resources/license.md b/third-party/GR00T-WholeBodyControl/docs/source/resources/license.md new file mode 100644 index 0000000000000000000000000000000000000000..5339979a63e890d419d78e757eca4b9e150d437f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/resources/license.md @@ -0,0 +1,17 @@ +# License + +This project uses dual licensing. + +## Source Code + +The source code is licensed under the **Apache License 2.0**. + +## Model Weights + +The trained model checkpoints and weights are licensed under the **NVIDIA Open Model License**. + +See the complete [LICENSE](https://github.com/NVlabs/GR00T-WholeBodyControl/blob/main/LICENSE) file for the full text of both licenses. + +The NVIDIA Open Model License permits commercial use and allows you to create derivative models. When distributing models, you must include attribution and comply with [NVIDIA Trustworthy AI Terms](https://www.nvidia.com/en-us/agreements/trustworthy-ai/terms/). + +For licensing questions, contact [gear-wbc@nvidia.com](mailto:gear-wbc@nvidia.com). diff --git a/third-party/GR00T-WholeBodyControl/docs/source/resources/support.md b/third-party/GR00T-WholeBodyControl/docs/source/resources/support.md new file mode 100644 index 0000000000000000000000000000000000000000..0135ea3a6a8301eeed5c921e33f6b1662c04533a --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/resources/support.md @@ -0,0 +1,3 @@ +# Support + +For questions and issues, please contact the GEAR WBC team at [gear-wbc@nvidia.com](mailto:gear-wbc@nvidia.com). diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/data_collection.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/data_collection.md new file mode 100644 index 0000000000000000000000000000000000000000..4f7a40c9af029d8faefc466483505d941b1b45b2 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/data_collection.md @@ -0,0 +1,564 @@ +# Data Collection for VLA + +Record teleop demonstrations as [LeRobot](https://github.com/huggingface/lerobot) datasets for post-training with [Isaac-GR00T](https://github.com/NVIDIA/Isaac-GR00T). The data exporter runs alongside the SONIC deployment and VR teleop stack, capturing robot state, SMPL teleop poses, and camera images at a configurable frequency. + +```{admonition} Deployment model +:class: important +Everything runs **offboard on your workstation** except the **camera server**, which runs **onboard the robot computer** (e.g., Jetson Orin) where the physical cameras are connected. The camera server publishes JPEG frames over ZMQ to the workstation. +``` + +```{admonition} Supported cameras +:class: note +The tested and supported camera setup uses **Luxonis OAK cameras** (OAK-D, OAK-1, etc.). This includes a head/ego-view OAK camera and optional OAK wrist cameras. Other camera drivers (RealSense, USB webcam) are included in the codebase but have not been tested recently. + +A 3D-printable mount for the head/ego-view **OAK-D W** camera is available under [`hardware/camera_mount/`](https://github.com/NVlabs/GR00T-WholeBodyControl/blob/main/hardware/camera_mount/README.md) — see its README for print settings, the bill of materials, and how it mounts on the G1. +``` + +```{admonition} Prerequisites +:class: note +1. **Completed the [Quick Start](../getting_started/quickstart.md)** — you can run the sim2sim loop (includes [installing the deployment](../getting_started/installation_deploy.md) and [downloading model checkpoints](../getting_started/download_models.md)). +2. **Completed the [VR Teleop Setup](../getting_started/vr_teleop_setup.md)** — PICO hardware is calibrated and `.venv_teleop` is ready. +3. **Camera server running on the robot** — see [Camera Server Setup](#camera-server-setup-on-robot) below. For simulation, the MuJoCo sim loop publishes camera images automatically — no camera server needed. +``` + +--- + +## One-Time Setup (Workstation) + +On your **workstation** (where you run the C++ deployment, teleop, and data exporter), run the install script from the repo root to create a dedicated virtual environment with all data collection dependencies (LeRobot, PyAV, OpenCV, etc.): + +```sh +bash install_scripts/install_data_collection.sh +``` + +This creates `.venv_data_collection` using Python 3.10 via `uv`. It installs `gear_sonic[data_collection]` which includes `lerobot`, `av`, `opencv-python`, and other required packages. It also installs `espeak` (system package) for voice feedback during recording. + +```{tip} +This environment is separate from `.venv_teleop` and `.venv_sim` — the data exporter has heavier ML dependencies that are not needed for teleop or simulation. +``` + +--- + +## Camera Server Setup (On-Robot) + +The camera server is the **only component that runs on the robot computer** (e.g., Jetson Orin). Everything else — the C++ deployment, PICO teleop streamer, data exporter, and camera viewer — runs on your workstation. + +The camera server captures frames from the OAK cameras physically connected to the robot and publishes them over ZMQ to the workstation. + +### Step 1: Clone the repo on the robot + +SSH into your robot computer and clone this repository: + +```sh +git clone https://github.com/NVlabs/GR00T-WholeBodyControl.git +cd GR00T-WholeBodyControl +``` + +### Step 2: Run the install script + +The install script handles everything: creates the virtual environment, installs all +dependencies (including the DepthAI SDK for OAK cameras), detects connected cameras, +and optionally installs a systemd service so the camera server starts automatically +on boot. + +```sh +bash install_scripts/install_camera_server.sh +``` + +The script will: + +1. Create `.venv_camera` with `gear_sonic[camera]` (DepthAI, ZMQ, msgpack, OpenCV, tyro). +2. Detect connected OAK cameras and list their MxIDs. +3. Prompt you for each camera position (ego view, and optionally left/right wrist) and its device ID. +4. Ask whether to install the camera server as a **systemd service** (recommended). If you answer **y**, it generates the unit file, installs, enables, and starts the service automatically. + +After the script finishes, verify the service is running: + +```sh +sudo systemctl status composed_camera_server.service +journalctl -u composed_camera_server.service -f +``` + +```{note} +Other camera drivers (RealSense, USB webcam) are included in the codebase but have not been tested recently for data collection. If you need RealSense, install `pyrealsense2` into the venv after setup. See the driver files in `gear_sonic/camera/drivers/` for details. +``` + +### Manual setup (alternative) + +If you prefer not to use the install script, or need to reconfigure: + +**Finding camera device IDs:** + +Each OAK camera has a unique MxID. List all connected OAK devices: + +```sh +source .venv_camera/bin/activate +python -c "import depthai as dai; print(dai.Device.getAllAvailableDevices())" +``` + +Example output: + +```text +[XLinkDeviceState.X_LINK_BOOTED, MxId: 18443010E1ABC12300, ...] +``` + +**Starting the camera server manually:** + +```sh +source .venv_camera/bin/activate + +# Single camera (ego view only) +python -m gear_sonic.camera.composed_camera \ + --ego-view-camera oak \ + --ego-view-device-id \ + --port 5555 + +# Multiple cameras (ego view + wrist cameras) +python -m gear_sonic.camera.composed_camera \ + --ego-view-camera oak --ego-view-device-id \ + --left-wrist-camera oak --left-wrist-device-id \ + --right-wrist-camera oak --right-wrist-device-id \ + --port 5555 +``` + +Run `python -m gear_sonic.camera.composed_camera --help` for all options including `--fps`, `--use-mjpeg`, and `--mjpeg-quality`. + +**Manual systemd setup:** + +```sh +# 1. Edit the service file to match your camera setup +nano systemd/composed_camera_server.service + +# 2. Copy to systemd, enable, and start +sudo cp systemd/composed_camera_server.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable composed_camera_server.service +sudo systemctl start composed_camera_server.service +``` + +Once the systemd service is running, the camera server starts automatically whenever the robot boots — no manual intervention needed. + +### Connecting from the workstation + +On your workstation, the data exporter and camera viewer connect to the robot's camera server over the network. Pass the robot's IP address (the G1 robot's default IP is `192.168.123.164`): + +```sh +# Data exporter +python gear_sonic/scripts/run_data_exporter.py \ + --task-prompt "pick up the cup" \ + --camera-host 192.168.123.164 --camera-port 5555 + +# Camera viewer (to verify the feed) +python gear_sonic/scripts/run_camera_viewer.py \ + --camera-host 192.168.123.164 --camera-port 5555 +``` + +The tmux launcher also accepts `--camera-host`: + +```sh +python gear_sonic/scripts/launch_data_collection.py \ + --camera-host 192.168.123.164 \ + --task-prompt "pick up the cup" +``` + +### ZMQ message format + +The camera server publishes a single msgpack-encoded payload per frame cycle containing all camera images: + +```python +{ + "timestamps": {"ego_view": 1712345678.123, "left_wrist": 1712345678.125}, + "images": {"ego_view": "", "left_wrist": ""} +} +``` + +Images are JPEG-compressed (quality 80) and either base64-encoded strings or raw JPEG bytes (when MJPEG on-device encoding is enabled). The data exporter's `ComposedCameraClientSensor` handles both formats automatically. + +--- + +## Architecture + +The data exporter receives data from three ZMQ sources. The C++ deployment, PICO teleop, and data exporter all run **offboard on the workstation**. The camera server runs **onboard the robot** and streams frames to the workstation over the network. + +```text + Workstation (offboard) Robot (onboard) +┌──────────────────────┐ ┌──────────────────────┐ ┌───────────────┐ +│ C++ deploy │ │ pico_manager │ │ Camera │ +│ (zmq_output_handler)│ │ _thread_server.py │ │ server │ +│ │ │ │ │ (OAK cameras)│ +│ port 5557 │ │ port 5556 │ │ port 5555 │ +│ topics: g1_debug, │ │ topic: pose │ │ (JPEG/ZMQ) │ +│ robot_config│ │ (SMPL body params) │ │ │ +└──────────┬───────────┘ └──────────┬────────────┘ └──────┬────────┘ + │ │ │ + └────────────┬────────────┘───────────────────────┘ + │ (network) + ┌────────▼────────┐ + │ run_data_ │ + │ exporter.py │ + │ (workstation) │ + │ │ + │ LeRobot dataset│ + │ (parquet + mp4)│ + └─────────────────┘ +``` + +| Source | Runs on | ZMQ Topic | Default Port | Provides | +|---|---|---|---|---| +| C++ deployment | Workstation | `g1_debug` | 5557 | Joint positions, velocities, IMU quaternion | +| C++ deployment | Workstation | `robot_config` | 5557 | One-shot robot configuration at startup | +| PICO teleop streamer | Workstation | `pose` | 5556 | SMPL body parameters (teleop target poses) | +| Camera server | Robot | *(raw TCP)* | 5555 | JPEG-compressed camera images (ego view + optional wrist views) | + +--- + +## Running Data Collection + +There are two ways to run the data collection stack: an **all-in-one tmux launcher** (recommended) or **manual multi-terminal setup**. + +### Option A: All-in-One Tmux Launch (Recommended) + +The launcher starts all components in a single tmux session with four panes: + +```text +┌───────────────────────┬───────────────────────┐ +│ Pane 0: C++ Deploy │ Pane 2: Data Exporter │ +│ (gear_sonic_deploy) │ (.venv_data_collection)│ +├───────────────────────┼───────────────────────┤ +│ Pane 1: PICO Teleop │ Pane 3: Camera Viewer │ +│ (.venv_teleop) │ (.venv_data_collection)│ +└───────────────────────┴───────────────────────┘ +``` + +```{note} +Requires `tmux` to be installed (`sudo apt install tmux`). +``` + +**For simulation** (the launcher starts `run_sim_loop.py` in a separate tmux window automatically): + +```bash +python gear_sonic/scripts/launch_data_collection.py --sim +``` + +**For real robot** (camera server running on robot at `192.168.123.164`): + +```bash +python gear_sonic/scripts/launch_data_collection.py \ + --camera-host 192.168.123.164 \ + --task-prompt "pick up the cup" +``` + +**With wrist cameras** (records ego view + left/right wrist camera streams): + +```bash +python gear_sonic/scripts/launch_data_collection.py \ + --camera-host 192.168.123.164 \ + --task-prompt "pick up the cup" \ + --record-wrist-cameras +``` + +```{tip} +No need to activate a virtual environment first — the launcher automatically detects and uses `.venv_data_collection` if the required dependencies are not in the current Python. +``` + +The launcher auto-attaches to the tmux session. Use `Ctrl+b` then arrow keys to switch between panes. + +Common options: + +| Flag | Default | Description | +|---|---|---| +| `--task-prompt` | `"demo"` | Language task description (e.g., `"pick up the cup"`) | +| `--dataset-name` | *(auto: timestamp)* | Dataset name; omit to auto-generate | +| `--sim / --no-sim` | `False` | Run deploy.sh in sim mode (also starts the sim loop) | +| `--camera-host` | `localhost` | Camera server host (e.g., `192.168.123.164` for real robot) | +| `--camera-port` | `5555` | Camera server port | +| `--no-camera-viewer` | *(viewer on)* | Disable the camera viewer pane | +| `--data-exporter-frequency` | `50` | Recording frequency (Hz) | +| `--deploy-checkpoint` | *(default)* | Custom checkpoint path for deploy.sh | +| `--deploy-obs-config` | *(default)* | Custom observation config for deploy.sh | +| `--deploy-planner` | *(default)* | Custom planner model path for deploy.sh | +| `--deploy-motion-data` | *(default)* | Custom motion data path for deploy.sh | +| `--record-wrist-cameras` | `False` | Record left/right wrist camera streams in the dataset | +| `--no-text-to-speech` | *(on)* | Disable voice feedback via espeak | + +Run `python gear_sonic/scripts/launch_data_collection.py --help` for all options. + +```{tip} +The launcher automatically enables **mouse support** in the tmux session — click to select panes, scroll with the mouse wheel, and drag to resize pane borders. +``` + +**Session management:** + +| Action | Command | +|---|---| +| Switch panes | `Ctrl+b`, then arrow keys | +| Detach (keep running) | `Ctrl+b`, then `d` | +| Reattach | `tmux attach -t sonic_data_collection` | +| Kill session | `Ctrl+\` in any pane, or `tmux kill-session -t sonic_data_collection` | + +### Option B: Manual Multi-Terminal Setup + +If you prefer individual control over each process, run them in separate terminals: + +**Terminal 1 — MuJoCo Simulator** *(skip for real robot)*: + +```bash +source .venv_sim/bin/activate +python gear_sonic/scripts/run_sim_loop.py \ + --enable-image-publish --enable-offscreen --camera-port 5555 +``` + +The `--enable-image-publish` and `--enable-offscreen` flags are required so the +sim renders camera images and streams them over ZMQ on the specified port. +The data exporter subscribes to this port the same way it subscribes to a +physical camera server. + +For real robot deployment, skip this terminal and see [VR Whole-Body Teleop](vr_wholebody_teleop.md) instead. + +**Terminal 2 — C++ Deployment** (from `gear_sonic_deploy/`): + +```bash +cd gear_sonic_deploy +source scripts/setup_env.sh +./deploy.sh --input-type zmq_manager sim +# Wait until you see "Init done" +``` + +**Terminal 3 — PICO Teleop Streamer:** + +```bash +source .venv_teleop/bin/activate +python gear_sonic/scripts/pico_manager_thread_server.py --manager +``` + +**Terminal 4 — Data Exporter:** + +```bash +source .venv_data_collection/bin/activate +python gear_sonic/scripts/run_data_exporter.py --task-prompt "pick up the cup" +``` + +**Terminal 5 (optional) — Camera Viewer:** + +```bash +source .venv_data_collection/bin/activate +python gear_sonic/scripts/run_camera_viewer.py +``` + +All options are provided via CLI flags — no interactive prompts. Key flags: + +| Flag | Default | Description | +|---|---|---| +| `--task-prompt` | `"demo"` | Language task description for this session | +| `--dataset-name` | *(auto: timestamp)* | Dataset name. Omit to create a new one, or pass an existing name to append episodes | +| `--data-collection-frequency` | `50` | Recording frequency (Hz) | +| `--root-output-dir` | `outputs` | Parent directory for saved datasets | + +```{tip} +Datasets are saved under `//`. If `--dataset-name` +is not specified, a timestamped name is generated automatically. +``` + +### Recording Controls + +There are two ways to control recording: **PICO VR controllers** (recommended during teleop) or **keyboard over ZMQ**. + +**PICO VR Controllers (via `manager_state` topic):** + +| Input | Action | +|---|---| +| **Left Grip + A** | **Toggle** recording — starts a new episode, or stops and saves the current one | +| **Left Grip + B** | **Discard** the current episode (saved to disk but flagged for removal during post-processing) | + +These buttons work in any manager mode (POSE, PLANNER, etc.) and are independent of the mode-switching controls. + +**Keyboard over ZMQ:** + +| Key | Action | +|---|---| +| `c` | **Toggle** recording (same as Left Grip + A) | +| `x` | **Discard** episode (same as Left Grip + B — flagged for removal) | + +```{note} +Keyboard commands are sent via a separate ZMQ publisher (default port `5580`). The data exporter subscribes to this channel automatically. You can send keys from any ZMQ publisher on that port, or integrate with the C++ deployment's keyboard handler. +``` + +--- + +## Camera Viewer + +A standalone camera viewer is available for monitoring camera feeds and recording raw video independently of the data exporter. + +```bash +source .venv_data_collection/bin/activate +python gear_sonic/scripts/run_camera_viewer.py --camera-host localhost --camera-port 5555 +``` + +The viewer connects to the same ZMQ camera server used by the data exporter and displays all detected camera streams in a tiled OpenCV window. + +**Controls** (OpenCV window must be focused): + +| Key | Action | +|---|---| +| `R` | Start/stop video recording | +| `Q` | Quit | + +Recordings are saved to `camera_recordings/rec_/` with one MP4 per camera stream. This is useful for: +- Verifying camera placement and image quality before starting data collection +- Recording reference videos alongside the LeRobot dataset +- Debugging camera server connectivity + +Run `python gear_sonic/scripts/run_camera_viewer.py --help` for all options. + +--- + +## CLI Options + +All options can be viewed with `--help`: + +```bash +python gear_sonic/scripts/run_data_exporter.py --help +``` + +Key options: + +| Flag | Default | Description | +|---|---|---| +| `--task-prompt` | `"demo"` | Language task description for annotation | +| `--dataset-name` | *(auto: timestamp)* | Dataset name; omit to auto-generate, or reuse an existing name to append | +| `--data-collection-frequency` | `50` | Recording frequency in Hz | +| `--camera-host` | `localhost` | Camera server hostname | +| `--camera-port` | `5555` | Camera server port | +| `--sonic-zmq-host` | `localhost` | SMPL pose publisher host | +| `--sonic-zmq-port` | `5556` | SMPL pose publisher port | +| `--state-zmq-host` | `localhost` | Robot state publisher host | +| `--state-zmq-port` | `5557` | Robot state publisher port | +| `--root-output-dir` | `outputs` | Root directory for saved datasets | +| `--text-to-speech / --no-text-to-speech` | `True` | Voice feedback via espeak | + +--- + +## Output Format + +Datasets are saved in the [LeRobot v2.1](https://github.com/huggingface/lerobot) format under `//`: + +```text +outputs/2026-04-03-14-30-00-G1-robot01/ +├── data/ +│ ├── train-00000.parquet # Tabular data (joint states, actions, annotations) +│ └── ... +├── videos/ +│ ├── observation.images.ego_view/ +│ │ ├── episode_000000.mp4 # H264-encoded ego camera video +│ │ └── ... +│ ├── observation.images.left_wrist/ # (only with --record-wrist-cameras) +│ └── observation.images.right_wrist/ # (only with --record-wrist-cameras) +└── meta/ + ├── info.json # Dataset metadata (fps, features, sizes) + ├── modality.json # GR00T modality configuration + ├── episodes.jsonl # Per-episode metadata + └── tasks.jsonl # Task prompt definitions +``` + +### Recorded Data Channels + +Each frame contains: + +| Feature | Shape | Description | +|---|---|---| +| `observation.state.joint_position` | `(N,)` | Actuated joint positions (rad) | +| `observation.state.joint_velocity` | `(N,)` | Actuated joint velocities (rad/s) | +| `observation.state.body_rotation_6d` | `(6,)` | Base orientation (6D rotation) | +| `observation.state.projected_gravity` | `(3,)` | Gravity vector in body frame | +| `observation.images.ego_view` | `(480, 640, 3)` | Ego camera image (saved as MP4 video) | +| `observation.images.left_wrist` | `(480, 640, 3)` | Left wrist camera (only with `--record-wrist-cameras`) | +| `observation.images.right_wrist` | `(480, 640, 3)` | Right wrist camera (only with `--record-wrist-cameras`) | +| `action.joint_position` | `(N,)` | Teleop target joint positions | +| `action.body_rotation_6d` | `(6,)` | Teleop target body rotation | +| `annotation.human.action.task_description` | string | Task prompt for this frame | + +--- + +## Post-Processing Datasets + +After recording, you can clean and merge datasets using the processing script. +All commands below run in the **data collection virtual environment**: + +```bash +source .venv_data_collection/bin/activate +``` + +### Remove Discarded Episodes + +Episodes discarded during collection (`x` key or Left Grip + B) are saved to disk +but flagged in `meta/info.json`. By default, the processing script removes these +flagged episodes so they are excluded from fine-tuning: + +```bash +# Clean a single dataset (removes discarded episodes + stale SMPL frames) +python gear_sonic/scripts/process_dataset.py \ + --dataset-path outputs/my_dataset \ + --output-path outputs/my_dataset_cleaned +``` + +To keep discarded episodes (e.g., for inspection), pass `--no-remove-discarded`. + +### Remove Stale SMPL Frames + +Teleop pauses or ZMQ frame drops create frames where `teleop.smpl_pose` is all +zeros. The processing script detects these and also removes consecutive +frozen (identical) lead-in frames that precede them: + +```bash +# Clean a single dataset in-place +python gear_sonic/scripts/process_dataset.py \ + --dataset-path outputs/my_dataset + +# Clean and write to a new directory (non-destructive) +python gear_sonic/scripts/process_dataset.py \ + --dataset-path outputs/my_dataset \ + --output-path outputs/my_dataset_cleaned +``` + +```{warning} +If you collected data using **VR 3-point tracking mode** (VR_3PT), the +`teleop.smpl_pose` column will be all zeros because VR_3PT uses raw VR +positions/orientations instead of SMPL body parameters. In this case, you +**must** disable SMPL cleaning to avoid dropping all frames: + + python gear_sonic/scripts/process_dataset.py \ + --dataset-path outputs/my_dataset \ + --output-path outputs/my_dataset_cleaned \ + --no-remove-stale-smpl +``` + +### Merge Multiple Datasets + +Combine several recording sessions into a single dataset. The script +validates that all sessions share the same `script_config` (robot +configuration) before merging: + +```bash +# Merge by listing datasets on the command line +python gear_sonic/scripts/process_dataset.py \ + --dataset-path outputs/session1 outputs/session2 outputs/session3 \ + --output-path outputs/merged_dataset + +# Or use a text file (one dataset path per line, # for comments) +python gear_sonic/scripts/process_dataset.py \ + --dataset-list datasets.txt \ + --output-path outputs/merged_dataset +``` + +SMPL cleaning is applied by default during merging. When enabled, the script +removes entire frames where the SMPL teleop pose is stuck at zeros — this +happens during operator pauses or ZMQ packet-drop periods where the SMPL +stream stops updating. Consecutive frozen (identical) frames that lead into +a zero block are also removed, since they represent stale data right before +the dropout. To skip this cleaning and merge only, add `--no-remove-stale-smpl`. + +--- + +## Next Steps: Fine-tune and Deploy + +The output dataset is directly compatible with the [Isaac-GR00T](https://github.com/NVIDIA/Isaac-GR00T) post-training pipeline. To fine-tune a VLA model on your collected data and deploy it for autonomous inference, see the [VLA Workflow tutorial](vla_workflow.md). diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/gamepad.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/gamepad.md new file mode 100644 index 0000000000000000000000000000000000000000..a0b0541dfd4ec806320c8f24d54d48c5b559e3e1 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/gamepad.md @@ -0,0 +1,117 @@ +# Motion Tracking and Kinematic Planner with Gamepad Controls + +Control the robot using a Unitree wireless gamepad for reference motion playback and planner-based locomotion (using `--input-type gamepad`). + +```{admonition} Prerequisites +:class: note +Complete the [Installation Guide](../getting_started/installation_deploy) and build the project before proceeding. +``` + +```{warning} +The gamepad interface requires a physical Unitree wireless gamepad connected to the robot. It is **not available in sim2sim** — use the [keyboard interface](keyboard.md) to test in simulation first. +``` + +```{admonition} Emergency Stop +:class: danger +Press **Select** at any time to immediately stop control and exit. Always keep a hand ready to press **Select**. +``` + +## Launch + +```bash +# From gear_sonic_deploy/ +bash deploy.sh --input-type gamepad real +``` + +## Step-by-Step: Normal Mode (Reference Motion Tracking) + +Normal Mode plays back pre-loaded reference motions. This is the default mode when the program starts. + +1. Press **Start** to start the control system. +2. Press **A** to play the current reference motion — the robot executes it to completion. +4. Press **R1** to switch to the next motion sequence, or **L1** for the previous one. +5. Press **A** again to play the new motion. +6. To stop mid-motion and return to the first frame, press **B** — the robot pauses without terminating the policy. +7. Use **D-pad Left / Right** to nudge the heading (±0.1 rad per press). +8. Press **X** or **Y** to reinitialize the base quaternion and reset the heading to zero, i.e. robot will think the current facing is the facing at the first frame of the reference. +9. When done, press **Select** to stop control and exit. + +## Step-by-Step: Planner Mode (Real-time Motion Generation) + +Planner Mode gives you analog stick control — steer with the left stick, aim the facing direction with the right stick, and cycle through locomotion modes. + +1. From Normal Mode, press **F1** to switch to Planner Mode. The terminal will print `Planner enabled`. +2. The robot starts in Slow Walk mode (mode 1). Push the **left stick forward** to walk — movement direction is computed from the stick angle relative to the current facing direction. +3. Steer the **right stick left / right** to smoothly rotate the facing direction (continuous, ±0.02 rad per frame). +4. Press **R1** to cycle to the next movement mode (Idle → Slow Walk → Walk → Run → Squat → Kneel Two Legs → Kneel → Idle → …). Press **L1** to cycle backward. +5. Hold **R2** to increase speed (for standing modes 1–3) or height (for squat modes 4–6). Hold **L2** to decrease. Speed/height changes by ±0.02 per frame while held. +6. When the left stick is in the dead zone, standing modes automatically switch to Idle; squat/kneel modes hold their pose with speed 0. +7. To pause, press **B** — the robot resets to Idle immediately. +8. Press **F1** again to return to Normal Mode, or **Select** to stop and exit. + +## Control Reference + +### System Controls (Both Modes) + +| Button | Action | +|--------|--------| +| **Start** | Start control system | +| **Select** | Stop control and exit (emergency stop) | +| **F1** | Toggle between Normal / Planner modes | +| **X** or **Y** | Reinitialize base quaternion and reset heading | +| **D-pad Left / Right** | Adjust delta heading (±0.1 rad) | + +### Normal Mode Buttons + +| Button | Action | +|--------|--------| +| **A** | Play current motion to completion | +| **B** | Restart current motion from beginning (pause at frame 0) | +| **L1** / **R1** | Previous / Next motion sequence | + +### Planner Mode Buttons + +**Movement:** + +| Input | Action | +|-------|--------| +| **Left Stick** | Movement direction (computed from stick angle + facing direction) | +| **Right Stick** | Facing direction (continuous rotation, ±0.02 rad/frame) | + +**Mode & Speed:** + +| Button | Action | +|--------|--------| +| **L1** / **R1** | Previous / Next movement mode (cycles 0–6) | +| **L2** (hold) | Decrease speed (modes 1–3) or height (modes 4–6), ±0.02/frame | +| **R2** (hold) | Increase speed (modes 1–3) or height (modes 4–6), ±0.02/frame | +| **A** | Play / resume motion | + +**Emergency:** + +| Button | Action | +|--------|--------| +| **B** | Pause (reset to Idle) | +| **Select** | Stop control and exit | + +## Movement Modes + +The gamepad cycles through 7 modes with **L1** / **R1**. Use **L2** / **R2** (hold) to adjust speed or height. + +| ID | Mode | L2/R2 Adjusts | Range | +|----|------|---------------|-------| +| 0 | Idle | — | — | +| 1 | Slow Walk | speed | 0.2–0.8 m/s | +| 2 | Walk | speed | 0.8–1.5 m/s | +| 3 | Run | speed | 1.5–3.0 m/s | +| 4 | Squat | height | 0.1–0.8 m | +| 5 | Kneel (two legs) | — | — | +| 6 | Kneel | — | — | + +```{tip} +For lateral (side-stepping) movement, we recommend keeping the target velocity at around **0.4 m/s**. Higher velocities during strafing can cause the robot's feet to collide due to the cross-legged foot placement required for lateral steps. +``` + +```{note} +When entering Squat (mode 4) from an adjacent mode, the height automatically initializes to 0.8 m. +``` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/isaac_teleop_publisher_setup.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/isaac_teleop_publisher_setup.md new file mode 100644 index 0000000000000000000000000000000000000000..3becfc4aedb09743c85817f5e45ec94fb8a5d9ff --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/isaac_teleop_publisher_setup.md @@ -0,0 +1,197 @@ +# Isaac Teleop Setup (CloudXR / DeviceIO, in-process) + +This page documents the Isaac Teleop / CloudXR bring-up for **G1 with a Thor backpack** that drives `GR00T-WholeBodyControl` directly from the headset. Using `pico_manager_thread_server.py --input-source isaac-teleop`, the CloudXR runtime is hosted **in-process** via the `isaacteleop[cloudxr]` Python package. + +```{admonition} Scope +:class: important +Real-robot deployment is supported only on **G1 + Thor backpack**. Sim2Sim (MuJoCo) can run on both Thor and x86_64 workstations. +``` + +## Prerequisites + +1. **Completed the [Quick Start](../getting_started/quickstart.md)** — you can run the Sim2Sim loop (includes [installing the deployment](../getting_started/installation_deploy.md) and [downloading model checkpoints](../getting_started/download_models.md)). +2. **Completed the [VR Teleop Setup](../getting_started/vr_teleop_setup.md)** — `.venv_teleop` is ready and `install_pico.sh` has been run (on Thor for real-robot deployment; on your workstation for Sim2Sim). + +This page is a condensed, repo-specific version of the upstream [Isaac Teleop](https://nvidia.github.io/IsaacTeleop/) docs: + +- [Quick Start](https://nvidia.github.io/IsaacTeleop/main/getting_started/quick_start.html) +- [`isaacteleop[cloudxr]` Python API](https://nvidia.github.io/IsaacTeleop/main/) + +## Step 1: Prepare the Thor Host + +Install the prerequisites on Thor (skip any you've already done for the rest of the deploy): + +```bash +sudo apt install -y build-essential curl git-lfs +git lfs install +``` + +```{note} +The remainder of this step (max power mode, thermal check) uses Thor/Jetson-specific tools. If you are running Sim2Sim (MuJoCo) on an x86_64 workstation instead of real G1 hardware, skip ahead to Step 2. +``` + +For Thor performance, enable max power mode before teleoperation: + +```bash +sudo nvpmodel -m 0 +sudo jetson_clocks +``` + +Optional thermal / over-current check: + +```bash +cat /sys/class/hwmon/hwmon*/oc*_event_cnt +``` + +## Step 2: Confirm `isaacteleop[cloudxr]` Installed + +```{note} +This step is a checkpoint, not a new action. `install_pico.sh`, run during [VR Teleop Setup](../getting_started/vr_teleop_setup.md) Step 3, already installs `isaacteleop[cloudxr]`. If that step is complete, skip to Step 3 below; otherwise, complete it before continuing. +``` + +For reference, `install_pico.sh` installs the package from the public NVIDIA index: + +```bash +# Already wired into install_pico.sh; shown here for reference +uv pip install 'isaacteleop[cloudxr]~=1.3.0' --prerelease=allow \ + --extra-index-url https://pypi.nvidia.com +``` + +It also seeds `~/cloudxr.env` with `NV_DEVICE_PROFILE=Quest3` (override by editing the file). `CloudXRLauncher` reads this on startup. + +## Step 3: Start the C++ Deployment + +From `gear_sonic_deploy/`: + +```bash +export TensorRT_ROOT=$HOME/TensorRT # only if not already in ~/.bashrc +./docker/run-ros2-dev.sh + +# inside the container (setup_env.sh is sourced automatically): +just build # first run only + +# run one of these: +./deploy.sh --input-type zmq_manager real # real robot +./deploy.sh --input-type zmq_manager sim # Sim2Sim (MuJoCo) +# Wait until you see "Init done" +``` + +```{note} +For Sim2Sim, first start the MuJoCo simulator on the host as shown in the [Quick Start](../getting_started/quickstart.md) Sim2Sim section, or the deployment will have nothing to control. +``` + +## Step 4: Launch the Teleop Streamer + +From the **repo root**: + +```bash +source .venv_teleop/bin/activate +python gear_sonic/scripts/pico_manager_thread_server.py --manager \ + --input-source isaac-teleop + +# If running offboard with a display, add visualization: +# --vis_vr3pt --vis_smpl +``` + +On startup the streamer brings up the in-process CloudXR runtime and logs `Isaac Teleop session initialized.`, then repeats `waiting for Isaac Teleop body data (connect the headset to CloudXR)...` until you connect the client in Step 5. + +## Step 5: Connect the XR Client + +Connecting the client starts the body-data stream the streamer is waiting for. + +- Open the [Isaac Teleop Web Client](https://nvidia.github.io/IsaacTeleop/client/) in the headset browser +- Enter the IP address of the host running the streamer +- Accept the self-signed certificate at `https://:48322` +- On Thor, change **Video Codec** from the default **AV1** to **H.264** or **H.265 (HEVC)**. +- Return to the client page and click **Connect** + +Once connected, stand in the [calibration pose](vr_wholebody_teleop.md#calibration-pose) and press **A+B+X+Y** on the PICO controllers to start the policy; the first press also runs the startup calibration and enters PLANNER (locomotion) mode. Then press **A+X** to switch to POSE mode for whole-body teleop, where your motion maps directly to the robot. See [Complete PICO Controls](vr_wholebody_teleop.md#pico-controls) for the other modes and the emergency stop. + +For quick validation, the same client URL can also be opened in a desktop browser. + +If you prefer to run the WebXR client from source instead of the hosted client, follow the CloudXR/WebXR build instructions linked from the [Isaac Teleop Quick Start](https://nvidia.github.io/IsaacTeleop/main/getting_started/quick_start.html). + +## Step 6: Start Camera Visualization + +Stream cameras to the headset via upstream IsaacTeleop's `camera_viz.sh`. If you don't have the IsaacTeleop repo yet, clone it first: + +```bash +git clone --recurse-submodules https://github.com/NVIDIA/IsaacTeleop.git +``` + +Then create the environment for the camera visualization streamer: + +```bash +cd IsaacTeleop +examples/camera_viz/camera_viz.sh setup +source examples/camera_viz/.venv/bin/activate +cd examples/camera_viz +``` +### Optional: Camera Preview in a Window +If you have video preview available such as on Thor or desktop simulation, it might be best to test your camera first with the "window" mode: +```bash +./camera_viz.sh run configs/YOUR_CAMERA.yaml --mode window +``` + +Choosing the correct yaml configuration camera for your setup is critical. The v4l2.yaml configuration is default but other configs are available: +```bash +# run just one of these that best matches your camera +./camera_viz.sh run configs/v4l2.yaml --mode window +./camera_viz.sh run configs/oakd.yaml --mode window +./camera_viz.sh run configs/zed.yaml --mode window +./camera_viz.sh run configs/realsense.yaml --mode window +``` +If you do not see correct output for your camera, you may need to modify the closest yaml file to your setup or create your own in the configs folder. Consider the following: +- Having more than one camera connected will modify what channel the video should be served from. +- First, try the command "lsusb" to see if your camera is connected. +- Next, use "ls -1 /dev/video* to list all video device modes. +- If you are using a v4l2 setup (Video4Linux2), these cammands will help to debug what is possible: + - To see the association of channels to cameras: "v4l2-ctl --list-devices" + - For each node, see what it captures and in what pixel formats: "v4l2-ctl --device=/dev/video0 --list-formats" + - To see full details on formats and available resolutions: "v4l2-ctl --device=/dev/video0 --list-formats-ext" +Once you have this information, make sure the settings in your yaml config match. + +### XR Camera Streaming Command + +Once you are certain you have valid yaml configured, shut down any preview windows and run instead with "--mode xr", which will stream frames to Isaac Teleop: + +```bash +./camera_viz.sh run configs/[YOUR_CAMERA].yaml --mode xr +``` +This should also be consistent with the [instructions found at IsaacTeleop](https://nvidia.github.io/IsaacTeleop/main/references/camera_streaming.html). + +## Troubleshooting + +### `RuntimeError: Failed to get OpenXR system: -35` + +In this setup, that error usually means the XR client is not connected yet. Re-check: + +- The headset / web client is fully connected to `https://:48322` +- The CloudXR runtime subprocess is still alive (look for the `Isaac Teleop session initialized.` log) +- `~/cloudxr.env` exists and has the right `NV_DEVICE_PROFILE` for your headset + +### Client connects but the video encoder fails to initialize + +On Thor, this usually means the client's **Video Codec** is still set to its default, **AV1**. Switch the client to **H.264** or **H.265 (HEVC)** and reconnect (see Step 5). + +### `gear_sonic_deploy` build error + +If `just build` fails, rebuild from scratch inside the container (Step 3): + +```bash +rm -rf build +just build +``` + +### `isaacteleop` import error + +Re-run `install_pico.sh` to reinstall `isaacteleop[cloudxr]~=1.3.0` into `.venv_teleop`. If `pypi.nvidia.com` is unreachable, check your network and the `--extra-index-url` flag. + +### Body data not arriving + +The streamer logs `[IsaacTeleopReader] No DeviceIO data for 5.0s, flagging disconnect` if the headset stops feeding body data. Confirm: + +1. The headset is still connected to CloudXR (Step 5). +2. The Pico body trackers are paired and calibrated (see [VR Teleop Setup → Motion Tracker Setup](../getting_started/vr_teleop_setup.md)). +3. The first time the schema runs, watch for `[IsaacTeleopReader] Unrecognised body_data schema: type=...` — if you see it, the upstream `FullBodyTrackerPico.get_body_pose().data` shape changed and `_body_data_to_24x7()` in `gear_sonic/utils/teleop/input_readers.py` needs an extra branch for the new layout. + diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/keyboard.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/keyboard.md new file mode 100644 index 0000000000000000000000000000000000000000..7177c56329b9f0e952fce3d66bb6fbe7a66fa3e7 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/keyboard.md @@ -0,0 +1,253 @@ +# Motion Tracking and Kinematic Planner with Keyboard Controls + +
+ +
In-the-wild navigation demo using the kinematic planner with keyboard controls.
+
+ +```{video} ../_static/Keyboard_Guidance.mp4 +:width: 100% +``` +*Video: Keyboard control walkthrough — starting the control system, playing reference motions, and using planner mode for real-time locomotion.* + +Control the robot using keyboard commands for reference motion playback and planner-based locomotion (using `--input-type keyboard`). + +```{admonition} Prerequisites +:class: note +Complete the [Quick Start](../getting_started/quickstart.md) to have the sim2sim loop running. +``` + +```{admonition} Emergency Stop +:class: danger +Press **`O`** at any time to immediately stop control and exit. Always keep a hand near the keyboard ready to press **`O`**. +``` + +## Launch + +**Sim2Sim (MuJoCo):** + +```bash +# Terminal 1 — MuJoCo simulator (from repo root) +source .venv_sim/bin/activate +python gear_sonic/scripts/run_sim_loop.py + +# Terminal 2 — C++ deployment (from gear_sonic_deploy/) +bash deploy.sh --input-type keyboard sim +``` + +**Real Robot:** + +```bash +# From gear_sonic_deploy/ +bash deploy.sh --input-type keyboard real +``` + +## Step-by-Step: Normal Mode (Reference Motion Tracking) + +Normal Mode plays back pre-loaded reference motions. This is the default mode when the program starts. + +1. In Terminal 2, press **`]`** to start the control system. +2. In the MuJoCo window, press **`9`** to drop the robot to the ground. +3. Go back to Terminal 2, press **`T`** to play the current reference motion — the robot executes it to completion. +4. Press **`N`** to switch to the next motion sequence, or **`P`** for the previous one. +5. Press **`T`** again to play the new motion. +6. To replay the same motion, press **`T`** again after it finishes. To stop mid-motion and return to the first frame, press **`R`** — the robot pauses at the first frame without terminating the policy. +7. Use **`Q`** / **`E`** to nudge the heading left or right (±π/12 rad per press). +8. Press **`I`** to reinitialize the base quaternion and reset the heading to zero, i.e. robot will think the current facing is the facing at the first frame of the reference. +9. When done, press **`O`** to stop control and exit. + +## Step-by-Step: Planner Mode (Real-time Motion Generation) + +Planner Mode lets you control the robot in real time — choose a locomotion style, steer with WASD, and adjust speed and height on the fly. + +1. From Normal Mode, press **`ENTER`** to switch to Planner Mode. The terminal will print `Planner enabled`. +2. The robot starts in the **Locomotion** motion set. Press **`1`** for slow walk, **`2`** for walk, or **`3`** for run. +3. Press **`W`** to walk forward. The robot uses a momentum system — holding a direction key sets momentum to full; releasing it lets the robot gradually decelerate and return to idle. +4. Steer with **`A`** / **`D`** (adjust heading and moving direction together) or turn in place with **`Q`** / **`E`** (±π/6 rad per press, only facing direction). +5. Press **`,`** / **`.`** to strafe left / right. +6. Press **`S`** to move backward. +7. Adjust speed with **`9`** (decrease) / **`0`** (increase). Speed ranges depend on the current mode (see tables below). +8. Press **`N`** to cycle to the next motion set (Locomotion → Squat → Boxing → Styled Walking → …). Use **`P`** to go back. +9. Within a motion set, press **`1`**–**`8`** to pick a specific mode (see the Motion Sets section below). +10. For squat-type modes, adjust body height with **`-`** (lower) / **`=`** (higher), clamped to 0.2–0.8 m. +11. If you need an immediate halt, press **`R`**, **`` ` ``**, or **`~`** — this resets movement momentum to zero instantly. +12. Press **`ENTER`** again to return to Normal Mode, or **`O`** to stop and exit. + +## Control Reference + +### System Controls (Both Modes) + +| Key | Action | +|-----|--------| +| **]** | Start control system | +| **O** | Stop control and exit (emergency stop) | +| **ENTER** | Toggle between Normal / Planner modes | +| **I** | Reinitialize base quaternion and reset heading | +| **Z** | Toggle encoder mode (between mode 0 and mode 1, if encoder loaded) | +| **F** | Report motor temperatures (TTS voice alert) | + +### Normal Mode Keys + +| Key | Action | +|-----|--------| +| **T** | Play current motion to completion | +| **R** | Restart current motion from beginning (pause at frame 0) | +| **P** / **N** | Previous / Next motion sequence | +| **Q** / **E** | Adjust delta heading (at policy level) left / right (±π/12 rad) | + +### Planner Mode Keys + +**Movement:** + +| Key | Action | +|-----|--------| +| **W** / **S** | Move forward / backward | +| **A** / **D** | Adjust heading slightly and move forward (left / right) | +| **,** / **.** | Strafe left / right | + +**Heading:** + +| Key | Action | +|-----|--------| +| **Q** / **E** | Adjust facing direction (at planner level) left / right (±π/6 rad) | +| **J** / **L** | Adjust delta heading (at policy level) left / right (±π/12 rad) | + +**Mode & Speed:** + +| Key | Action | +|-----|--------| +| **N** / **P** | Next / Previous motion set | +| **1**–**8** | Select mode within the current set | +| **9** / **0** | Decrease / Increase movement speed | +| **-** / **=** | Decrease / Increase height (non-standing sets, 0.2–0.8 m) | +| **T** | Play motion | + +**Emergency:** + +| Key | Action | +|-----|--------| +| **R** / **`** / **~** | Emergency stop (immediate momentum reset) | + +## Motion Sets + +A **motion set** is a group of related movement styles (e.g., locomotion, gestures, or crouching). Selecting a mode within a set makes the robot behave in that style. Each set contains up to eight selectable modes. + +Cycle through motion sets with **`N`** (next) / **`P`** (previous). Within each set, press **`1`**–**`8`** to select a mode. For more details on the underlying planner model, mode indices, and input/output specifications, see the [Kinematic Planner ONNX Model Reference](../references/planner_onnx.md). + +### Set 0 — Locomotion (Standing) + +| Key | Mode | Speed Range | +|-----|------|-------------| +| **1** | Slow Walk | 0.2–0.8 m/s | +| **2** | Walk | — | +| **3** | Run | 1.5–3.0 m/s | +| **4** | Happy | — | +| **5** | Stealth | — | +| **6** | Injured | — | + +```{tip} +For lateral (side-stepping) movement using **`,`** / **`.`**, we recommend keeping the target velocity at around **0.4 m/s**. Higher velocities during strafing can cause the robot's feet to collide due to the cross-legged foot placement required for lateral steps. +``` + +
+
+ +
Happy styled walking.
+
+
+ +
Stealth styled walking.
+
+
+ +
Injured styled walking.
+
+
+ +
Running locomotion mode.
+
+
+ +### Set 1 — Squat / Ground + +Height adjustable with **`-`** / **`=`** (0.2–0.8 m). Initial height defaults to 0.8 m when entering this set. + +| Key | Mode | Speed Range | +|-----|------|-------------| +| **1** | Squat | static | +| **2** | Kneel (Two Legs) | static | +| **3** | Kneel (One Leg) | static | +| **4** | Hand Crawling | 0.4–1.0 m/s | +| **5** | Elbow Crawling | 0.7–1.0 m/s | + +
+
+ +
Kneeling mode with variable height control.
+
+
+ +
Hand crawling locomotion.
+
+
+ +
Elbow crawling locomotion.
+
+
+ +### Set 2 — Boxing + +| Key | Mode | Speed Range | +|-----|------|-------------| +| **1** | Idle Boxing | static | +| **2** | Walk Boxing | 0.7–1.5 m/s | +| **3** | Left Jab | 0.7–1.5 m/s | +| **4** | Right Jab | 0.7–1.5 m/s | +| **5** | Random Punches | 0.7–1.5 m/s | +| **6** | Left Hook | 0.7–1.5 m/s | +| **7** | Right Hook | 0.7–1.5 m/s | + +
+ +
Boxing mode demo.
+
+ +### Set 3 — Additional Styled Walking + +| Key | Mode | +|-----|------| +| **1** | Careful | +| **2** | Object Carrying | +| **3** | Crouch | +| **4** | Happy Dance | +| **5** | Zombie | +| **6** | Point | +| **7** | Scared | + +## Movement Momentum System + +The planner usage in keyboard mode uses a momentum-based movement system: +- Pressing a direction key (**W/S/A/D/,/.**) sets momentum to **1.0** (full speed). +- Each frame without a direction key press, momentum decays multiplicatively (×0.999). +- When momentum drops below **0.1**, the robot transitions to idle (for the Locomotion set) or holds the current static pose (for Squat and Boxing sets). +- Emergency stop (**R/`/~**) instantly resets momentum to zero. + +This means you don't need to hold a key down — a single press starts movement, and the robot coasts to a stop naturally. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/live_camera_teleop.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/live_camera_teleop.md new file mode 100644 index 0000000000000000000000000000000000000000..f58096361ff63601b61c3652b7950fa98cff8224 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/live_camera_teleop.md @@ -0,0 +1,423 @@ +# Live Camera Teleoperation with GEM-X + +Teleoperate the Unitree G1 from a **single RGB camera** — no motion-capture suit, no VR headset, no body trackers. [GEM-X](https://github.com/NVlabs/GEM-X) recovers your full-body 3D motion from the webcam image, this example converts that motion to SMPL and streams it over SONIC's ZMQ pose protocol (`--input-type zmq`), and the SONIC policy tracks it while keeping the robot balanced. + +
+ +
Live webcam teleoperation on a real G1 — the operator (left) is tracked by a single camera, with no suit, gloves, or headset. The robot is on a safety gantry, as recommended for a first hardware session.
+
+ +```{admonition} Prerequisites +:class: note +Complete the [Quick Start](../getting_started/quickstart.md) so the sim2sim loop runs. This tutorial drives the same interface described in [Streaming Motion Tracking](zmq.md) — read that page first if you have not used `--input-type zmq` before, since the keyboard controls and stream protocol are shared. +``` + +```{admonition} GEM-X is an external dependency +:class: important +GEM-X is **not** bundled with this repository and is not installed by any of the SONIC install scripts. You install it separately and point this example at it with `--gemx-root` (or `$GEMX_ROOT`). GEM-X is Apache-2.0 licensed. +``` + +--- + +## How It Works + +```text + Webcam ──RGB──► GEM-X rolling window ──SOMA──► soma_to_smpl.py + (1 camera) YOLOX → ViTPose (2D) 77 joints SOMA → SMPL, 24 joints + → diffusion denoiser root-local, Z-up + → SOMA decoder │ + │ ZMQ Protocol v3 + │ topic "pose" + │ tcp://:5556 + ▼ + SONIC C++ deployment + smpl encoder → WBC policy + │ + ▼ + Unitree G1 (sim or real) +``` + +| Stage | What happens | Output | +|---|---|---| +| Capture | OpenCV reads one frame from the camera | RGB image | +| Detect + 2D pose | YOLOX detection, then ViTPose keypoints (ONNX) | 77 2D keypoints | +| Lift to 3D | GEM-X diffusion denoiser runs over a rolling window of buffered frames | SOMA latent | +| Decode | GEM-X decoder produces body parameters, and the gravity-aligned root orientation is fused in | SOMA body params (77 joints) | +| Convert | `soma_to_smpl.py` maps SOMA → SMPL, rotates Y-up → Z-up, removes the root rotation | `smpl_joints` (24×3), `body_quat` | +| Stream | ZMQ `PUB` socket sends a Protocol v3 message per frame | wire message on topic `pose` | +| Track | SONIC's `smpl` encoder (mode 2) turns SMPL into latent commands the policy tracks | robot joint targets | + +### Why stream SMPL instead of joint angles + +SONIC ships a learned `smpl` encoder that was trained on human SMPL motion, so the human-to-robot mapping already lives **inside the policy**. Streaming SMPL hands that mapping to the encoder and keeps the online loop free of any per-frame retargeting or inverse-kinematics solve. + +The alternative — converting SOMA to G1 joint angles offline and streaming Protocol v1 — requires a retargeter in the loop, which is the expensive part. The conversion in `soma_to_smpl.py` mirrors `gear_sonic/scripts/pico_manager_thread_server.py:process_smpl_joints` exactly, so the streamed data is in-distribution for the same encoder the PICO path uses. + +### Files + +Everything lives in `gear_sonic/examples/live_camera_teleop/`: + +| File | Role | +|---|---| +| `webcam_stream.py` | Live loop: capture → GEM-X → convert → publish. Also the camera test tool. | +| `soma_to_smpl.py` | SOMA → SMPL conversion and the Protocol v3 ZMQ publisher. Imported, not run directly. | +| `soma_pt_to_sonic_v3.py` | Replays a saved GEM-X result (`hpe_results.pt`) — camera-free verification. | +| `README.md` | Short reference version of this tutorial. | + +--- + +## Prerequisites + +1. **SONIC deployment built and runnable** — see [Installation (Deployment)](../getting_started/installation_deploy.md) and [Quick Start](../getting_started/quickstart.md), which also covers [downloading the released checkpoint](../getting_started/download_models.md) whose `smpl` encoder this path uses. +2. **GEM-X installed** — cloned, its virtual environment built, and its checkpoint available. It is a separate repository that no SONIC install script sets up for you; Step 1 below covers it. +3. **A camera** — any UVC USB webcam or laptop camera. A video file works as a stand-in for everything except the live feel. + +--- + +## Step 1 — Install GEM-X and Set Up + +Follow the [GEM-X installation guide](https://github.com/NVlabs/GEM-X/blob/main/docs/INSTALL.md). The short version: + +```bash +git clone --recursive https://github.com/NVlabs/GEM-X.git +cd GEM-X + +pip install uv && uv venv .venv --python 3.12 && source .venv/bin/activate +uv pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126 +uv pip install -e third_party/soma && (cd third_party/soma && git lfs pull) +bash scripts/install_env.sh +``` + +Then two things this example needs on top of a stock GEM-X install: + +```bash +# 1. SOMA body-model assets must be reachable at inputs/soma_assets +mkdir -p inputs +ln -sfn "$PWD/third_party/soma/assets" inputs/soma_assets + +# 2. Extra Python deps for the ZMQ bridge +uv pip install pyzmq scipy +``` + +```{admonition} The soma_assets link is not optional +:class: warning +`webcam_stream.py` constructs `SomaLayer(data_root="/inputs/soma_assets")`. Without that path the run fails when the converter starts up, *after* the camera and the denoiser have already initialized — which looks like a late, confusing crash. Create the link before the first live run. + +Use an **absolute** target as shown. A relative target would be resolved against `inputs/`, not the repo root, and silently produce a dangling link. +``` + +GEM-X downloads its checkpoint from Hugging Face on first use, so the first run is slower than later ones. + +Finally, point the example at both repositories. The scripts live in the SONIC repo but import `gem` from GEM-X, so they run in **GEM-X's virtual environment** and locate SONIC by path: + +```bash +cd /path/to/GEM-X +source .venv/bin/activate + +export GEMX_ROOT=$PWD +export SONIC_ROOT=/path/to/GR00T-WholeBodyControl +``` + +```{admonition} Why SONIC_ROOT is required +:class: note +The conversion in `soma_to_smpl.py` reuses SONIC's own rotation helpers (`gear_sonic.isaac_utils.rotations`) so the SMPL convention matches the deployment bit for bit. Python puts the *script's* directory on `sys.path`, not the repo root, so `gear_sonic` is not importable from the GEM-X environment unless you set `$SONIC_ROOT` (or pass `--sonic-root`). Those helpers only need `torch` and `numpy` — you do **not** need to install `gear_sonic` into the GEM-X environment. +``` + +--- + +## Step 2 — Verify the Input Camera + +Do this before involving the robot. `webcam_stream.py` doubles as the camera test tool: `--kp-only` runs detection and 2D keypoints but skips the 3D denoiser, so it starts fast and needs no checkpoint. + +### Find the device + +```bash +ls /dev/video* +v4l2-ctl --list-devices # sudo apt install v4l-utils +v4l2-ctl -d /dev/video0 --list-formats-ext # modes the camera actually supports +``` + +The index in `/dev/videoN` is what you pass to `--source` (`/dev/video0` → `--source 0`). Many USB cameras expose several nodes for one physical device; the lowest-numbered one is usually the capture node. + +### Preview the tracking + +```bash +# Live overlay window, press q to quit +python "$SONIC_ROOT/gear_sonic/examples/live_camera_teleop/webcam_stream.py" \ + --source 0 --kp-only --show +``` + +You should see green keypoints tracking your body and a steady frame rate on the status line. Fix any missing or jumping keypoints here — the controller can only track what the estimator sees. + +### Request a capture mode + +A camera's default mode is often low-resolution or low-fps, which caps the teleop rate. Request one of the modes reported by `--list-formats-ext`: + +```bash +... --source 0 --resolution 1280x720 --cap-fps 30 +``` + +Cameras silently ignore unsupported settings, so the script logs the mode it actually negotiated. Check that line rather than assuming the request applied. + +(framing)= +### How to Position the Camera and the Operator + +Monocular estimation only knows what it can see, and the lower body is what the controller balances on: + +- Keep the **full body in frame, including the feet.** Cropped legs make the lower body unreliable. +- Stand roughly **2–3 m back**, camera near torso height, lens roughly level. +- **Even and front facing** light. Avoid strong backlight. +- **One person in frame** — the largest detection is the one tracked. +- **Face the same direction as the robot.** Orientation is streamed in the robot's own frame, so operator and robot should be aligned. + +--- + +## Step 3 — Dry Run Without a Camera + +`soma_pt_to_sonic_v3.py` replays a saved GEM-X result, which isolates the conversion and the wire format from anything camera-related. Produce an `hpe_results.pt` by running any GEM-X demo on a video, then: + +```bash +# Convert frame 0 and print the result — no ZMQ, no robot +python "$SONIC_ROOT/gear_sonic/examples/live_camera_teleop/soma_pt_to_sonic_v3.py" \ + --pt /path/to/hpe_results.pt --dry-run +``` + +Once that prints a sane 24-joint skeleton, replay it as a stream against the simulator (start Terminals 1 and 2 from the next section first): + +```bash +python "$SONIC_ROOT/gear_sonic/examples/live_camera_teleop/soma_pt_to_sonic_v3.py" \ + --pt /path/to/hpe_results.pt --fps 30 --loop +``` + +This is the fastest way to confirm the SONIC side is wired up correctly, and it is reproducible — the same input produces the same motion every time. + +--- + +## Step 4 — Teleop in Simulation + +Run **three terminals**. + +### Terminal 1 — MuJoCo simulator + +From the **repo root**: + +```bash +source .venv_sim/bin/activate +python gear_sonic/scripts/run_sim_loop.py +``` + +### Terminal 2 — C++ deployment + +From `gear_sonic_deploy/`: + +```bash +cd gear_sonic_deploy +source scripts/setup_env.sh +./deploy.sh --input-type zmq --zmq-host localhost sim +# Wait until you see "Init done" +``` + +```{admonition} Do not add --zmq-port or --zmq-topic here +:class: warning +`deploy.sh` forwards only `--input-type` and `--zmq-host`. The port and topic stay at the deployment defaults, `5556` and `pose` — exactly what this example publishes on, so no extra flags are needed. + +Unrecognized flags are not rejected; `deploy.sh` treats any unknown argument as the positional interface argument, so passing `--zmq-port 5556` can quietly override your `sim` / `real` selection depending on argument order. +``` + +(remote-streamer)= +```{admonition} Running GEM-X on another machine +:class: note +The example **binds** its ZMQ `PUB` socket (`tcp://*:5556`) and the deployment **connects** to it. So `--zmq-host` is the IP of the machine running `webcam_stream.py`, not the robot. Keep it on `localhost` when both run on the same workstation; pass the workstation's IP when the deployment runs onboard the robot. +``` + +### Terminal 3 — GEM-X Webcam Bridge + +From the **GEM-X repo**, with its environment active and both roots exported (Step 1): + +```bash +python "$SONIC_ROOT/gear_sonic/examples/live_camera_teleop/webcam_stream.py" \ + --source 0 --stream-sonic --window 30 --smooth 0.8 +``` + +Expect output along these lines: + +```text +[webcam] backends: vitpose=..., denoiser=... +[bridge] Using SONIC's pack_pose_message (exact wire format). +[webcam] streaming SMPL v3 to SONIC on tcp://*:5556 +[webcam] frame 42 | 12.3 fps | soma=yes +``` + +Two lines are worth reading carefully: + +- **`Using SONIC's pack_pose_message`** confirms `$SONIC_ROOT` resolved. If you instead see `gear_sonic not importable ... using built-in fallback packer`, the wire format is still byte-identical, but the conversion needs those same helpers — so fix `$SONIC_ROOT` rather than relying on the fallback. +- **`soma=yes`** means 3D output is flowing. The first couple of frames report `warmup/kp-only` while the rolling window fills. + +### Your first session + +With all three terminals running, drive the deployment from Terminal 2: + +1. Press **`]`** to start the control system. +2. In the MuJoCo window, press **`9`** to drop the robot to the ground. +3. Stand in front of the camera in a **relaxed, upright pose** with your whole body in frame. Check Terminal 3 shows `soma=yes`. +4. Back in Terminal 2, press **`ENTER`** to enable ZMQ streaming. The terminal prints `ZMQ STREAMING MODE: ENABLED` and the robot begins tracking you. +5. Start with **slow arm motions only.** Confirm the robot mirrors you in the expected direction before moving your legs or torso. +6. Press **`ENTER`** again to return to reference-motion mode, and **`O`** to stop and exit. + +```{admonition} Align yourself before enabling the stream +:class: danger +The robot snaps to whatever pose is streaming the moment you press **`ENTER`**. A large mismatch between the robot's current pose and yours produces sudden, aggressive motion — the same hazard described for POSE mode in the [PICO VR tutorial](vr_wholebody_teleop.md). Stand relaxed and upright, and verify tracking is stable, before enabling the stream. +``` + +--- + +## Step 5 — Teleop on the Real Robot + +```{admonition} Safety Warning +:class: danger +Only proceed once you can run a smooth session in simulation and are comfortable with the emergency stop. **Terminate `run_sim_loop.py` first** — a simulator and a real robot running at once will conflict. + +Bring the robot up on a gantry for the first real session, and keep a safety operator on **`O`** and the hardware E-stop. Review the [Whole-body Teleoperation Guide](../user_guide/teleoperation.md) before you start. +``` + +```{admonition} Expect the Robot to Walk Forward +:class: warning +Reaching your arms out in front of you, or making large, fast arm motions, shifts the streamed reference enough that the policy steps forward to keep its balance. On hardware that means the robot leaves the spot it started on, without any locomotion being commanded — so keep the space in front of it clear, do not stand directly in its path, and start with small arm motions close to your body. Work on this is in progress. +``` + +The real-robot workflow uses **two terminals** (no MuJoCo). + +### Terminal 1 — C++ deployment + +From `gear_sonic_deploy/`: + +```bash +cd gear_sonic_deploy +source scripts/setup_env.sh + +# 'real' auto-detects the robot network interface (192.168.123.x). +# If GEM-X runs on this workstation, localhost is correct: +./deploy.sh --input-type zmq --zmq-host localhost real + +# If the deployment runs onboard and GEM-X is on a workstation, +# point it at the workstation: +# ./deploy.sh --input-type zmq --zmq-host real + +# Wait until you see "Init done" +``` + +### Terminal 2 — GEM-X Webcam Bridge + +Identical to the simulation case: + +```bash +cd /path/to/GEM-X && source .venv/bin/activate +export GEMX_ROOT=$PWD SONIC_ROOT=/path/to/GR00T-WholeBodyControl + +python "$SONIC_ROOT/gear_sonic/examples/live_camera_teleop/webcam_stream.py" \ + --source 0 --stream-sonic --window 30 --smooth 0.8 +``` + +Then follow the same sequence: **`]`** to start, **`ENTER`** to enable streaming once tracking is stable, **`O`** to stop. + +--- + +## Controls Reference + +All keys are pressed in the **C++ deployment terminal** and are shared with [Streaming Motion Tracking](zmq.md). + +| Key | Action | +|---|---| +| **`]`** | Start the control system | +| **`ENTER`** | Toggle ZMQ streaming mode (camera tracking) on / off | +| **`Q`** / **`E`** | Adjust heading left / right (±0.1 rad per press) | +| **`I`** | Reinitialize base quaternion and reset heading to zero | +| **`T`** / **`N`** / **`P`** / **`R`** | Reference-motion playback (streaming mode off) | +| **`O`** | **Emergency stop** — halt control and exit | + +--- + +## Command-Line Reference + +### `webcam_stream.py` + +| Option | Default | Description | +|---|---|---| +| `--source` | `0` | Camera index (`ls /dev/video*`) or a video file path | +| `--stream-sonic` | off | Publish the Protocol v3 SMPL stream. Without it, nothing is sent to SONIC. | +| `--window` | `120` | Rolling-window length in frames. Dominates the frame rate — see [Tuning](#tuning). | +| `--smooth` | `0.75` | Temporal smoothing weight on the streamed reference (`0` = off) | +| `--port` | `5556` | ZMQ `PUB` port to bind. Matches the deployment default; change both or neither. | +| `--resolution` | camera default | Requested capture resolution, e.g. `1280x720` | +| `--cap-fps` | camera default | Requested capture frame rate | +| `--kp-only` | off | 2D keypoints only — skips the denoiser. Camera checks. | +| `--show` / `--save` | off | Live preview window / write an overlay mp4 | +| `--max-frames` | `0` | Stop after N frames (`0` = run until interrupted) | +| `--gemx-root` | `$GEMX_ROOT` | GEM-X repo root | +| `--sonic-root` | `$SONIC_ROOT` | SONIC repo root (see Step 1) | + +### `soma_pt_to_sonic_v3.py` + +| Option | Default | Description | +|---|---|---| +| `--pt` | *required* | Path to a saved GEM-X `hpe_results.pt` | +| `--fps` | `30` | Replay rate | +| `--loop` | off | Replay continuously | +| `--dry-run` | off | Convert frame 0, print it, and exit — no ZMQ | +| `--smooth` | `0.0` | Temporal smoothing (off by default, unlike the live path) | +| `--port` / `--max-frames` / `--gemx-root` / `--sonic-root` | — | As above | + +--- + +(tuning)= +## Tuning: Frame Rate vs. Stability + +The denoiser runs over the whole buffered window each frame, so cost grows with `--window` until the buffer is full. That makes `--window` the main throughput knob. + +| Symptom | Try | +|---|---| +| Frame rate too low | Lower `--window` (e.g. `30` → `20`); request a lighter capture mode with `--resolution` / `--cap-fps` | +| Robot jitters or takes small stepping motions | Raise `--smooth` toward `0.85`; improve lighting and [framing](#framing) | +| Robot feels laggy or "behind" you | Lower `--smooth`, lower `--window`, and move more deliberately | +| Legs or feet look wrong | Almost always framing — get the feet fully in frame and step further back | +| Robot drifts in heading | Press **`I`** to reinitialize the base quaternion, then nudge with **`Q`** / **`E`** | + +Start at `--window 30 --smooth 0.8` and adjust one knob at a time. + +--- + +## Troubleshooting + +| Symptom | Cause / fix | +|---|---| +| `Could not open video source: 0` | Wrong index (`ls /dev/video*`), or the user is not in the `video` group (`sudo usermod -aG video $USER`, then re-login) | +| Opens, but frames fail or hang | Another process holds the device (browser tab, earlier run). Check with `sudo fuser /dev/video0` | +| `ModuleNotFoundError: No module named 'gear_sonic'` | `$SONIC_ROOT` is unset or wrong — see Step 1 | +| `ModuleNotFoundError: No module named 'gem'` | Running in the wrong environment. Activate GEM-X's `.venv`, not a SONIC one. | +| Crash when the converter starts, referencing SOMA assets | The `inputs/soma_assets` link is missing or dangling — see Step 1 | +| `KeyError` about `identity_coeffs` / `scale_params` | The SOMA decode is incomplete; those parameters have no safe zero default, so the bridge refuses to stream a collapsed skeleton rather than sending garbage to the controller | +| Robot never moves after **`ENTER`** | No messages arriving. Check Terminal 3 prints `soma=yes`, that `--zmq-host` points at the machine running GEM-X, and that port `5556` is reachable | +| Very low frame rate | Camera negotiated a slow mode, or `--window` is too large — see [Tuning](#tuning) | +| `--show` fails on a headless box | No display; use `--save` instead | +| No keypoints detected | Body not fully in frame, too dark, or too far away | + +--- + +## Limitations + +- **No commanded root translation.** The stream carries root-local pose plus heading, not an explicit root translation, so walking the robot around by walking yourself is not supported. Combine with the [kinematic planner](keyboard.md) for locomotion and use the camera for upper-body motion. +- **Wrists and fingers are not tracked.** `smpl_pose` and the 6 wrist joints are streamed as zeros. GEM-X estimates hands, so wiring them through is a natural extension. +- **The robot walks forward to keep its balance.** Some arm motions — reaching out in front of you, or large, fast swings — shift the streamed reference far enough that the policy takes steps to stay upright. The robot then drifts from where it started even though no locomotion was commanded. Work on this is in progress. +- **Monocular lower body is the weakest signal.** Feet and depth are inherently less certain from one camera than from trackers, and that is exactly what the controller balances on. Framing matters more here than any parameter. +- **Single subject, static camera.** The largest detection is tracked, and the loop assumes a fixed camera. + +--- + +## Next Steps + +- [Streaming Motion Tracking](zmq.md) — the underlying ZMQ interface and full protocol reference +- [PICO VR Whole-body Teleop](vr_wholebody_teleop.md) — tracker-based teleoperation, for comparison +- [Whole-body Teleoperation Guide](../user_guide/teleoperation.md) — movement patterns and operating practices +- [Data Collection for VLA](data_collection.md) — recording teleoperation sessions as training data diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/manager.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/manager.md new file mode 100644 index 0000000000000000000000000000000000000000..9808046e0747f1edcc6a632db868e2120a45d51f --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/manager.md @@ -0,0 +1,119 @@ +# Interface Manager (All-In-One) + +Dynamically switch between keyboard, gamepad, and ZMQ input interfaces at runtime using hotkeys (`--input-type manager`). The manager owns all interfaces simultaneously and delegates to the currently active one. You can switch at any time without restarting the program. + +```{admonition} Prerequisites +:class: note +Complete the [Quick Start](../getting_started/quickstart.md) to have the sim2sim loop running. +``` + +```{admonition} Emergency Stop +:class: danger +Press **`O`** at any time to immediately stop control and exit — this works regardless of which interface is active, including when the gamepad is selected. Always keep a hand near the keyboard ready to press **`O`**. +``` + +## Launch + +**Sim2Sim (MuJoCo):** + +```bash +# Terminal 1 — MuJoCo simulator (from repo root) +source .venv_sim/bin/activate +python gear_sonic/scripts/run_sim_loop.py + +# Terminal 2 — C++ deployment (from gear_sonic_deploy/) +bash deploy.sh --input-type manager sim +``` + +**Real Robot:** + +```bash +# From gear_sonic_deploy/ +bash deploy.sh --input-type manager real +``` + +If you plan to use the ZMQ interface, add ZMQ flags: + +```bash +bash deploy.sh --input-type manager \ + --zmq-host \ + --zmq-port 5556 \ + --zmq-topic pose \ + sim +``` + +## Step-by-Step + +1. The manager starts in **Keyboard** mode by default. +2. Press **`]`** to start the control system (keyboard mode). Use the robot as described in the [Keyboard tutorial](keyboard.md). +3. To switch to gamepad, press **`Shift+2`** (types `@`). The terminal prints `Switched to: GAMEPAD (safety reset triggered)`. The robot returns to reference motion at frame 0 and the planner is disabled. +4. Use the gamepad controls as described in the [Gamepad tutorial](gamepad.md). +5. To switch to ZMQ streaming, press **`Shift+3`** (types `#`). A safety reset is triggered and the terminal prints `Switched to: ZMQ`. Use the ZMQ controls as described in the [ZMQ tutorial](zmq.md). +6. To switch back to keyboard at any time, press **`Shift+1`** (types `!`). +7. Press **`O`** to stop control and exit from any interface. + +## Switching Interfaces + +| Hotkey | Interface | Notes | +|--------|-----------|-------| +| **Shift+1** (`!`) | Keyboard | Default. Full keyboard controls (Normal + Planner modes). See [Keyboard tutorial](keyboard.md). | +| **Shift+2** (`@`) | Gamepad | Unitree wireless gamepad. See [Gamepad tutorial](gamepad.md). | +| **Shift+3** (`#`) | ZMQ | ZMQ streaming (requires `--zmq-host` etc.). See [ZMQ tutorial](zmq.md). | + +```{tip} +A **ROS2** interface is also available via **Shift+4** (`$`) when built with ROS2 support. It requires the planner to be loaded and falls back to Keyboard otherwise. The ROS2 interface is provided as a reference implementation for building custom ROS2-based control pipelines and may not receive the same level of updates as the other interfaces. +``` + +### What Happens When You Switch + +Each switch triggers a **safety reset** on **all** managed interfaces (not just the one you're switching to). This: + +- Disables the planner and returns to reference motion at frame 0 +- Resets heading and movement states +- Disables ZMQ streaming (if it was active) +- Prevents control discontinuities from stale state in the previous interface + +The safety reset ensures you always start from a clean state after switching, regardless of what the previous interface was doing. + +```{note} +All four interfaces are created at startup and stay alive across switches. Their internal state (e.g., gamepad mode, ZMQ connection) is preserved — only the planner/motion state is reset for safety. This means you don't need to re-establish the ZMQ connection or re-pair the gamepad when switching back. +``` + +## Global Controls + +These controls work at the manager level, **regardless of which interface is active**. They are intercepted by the manager before being passed to the active interface. + +### Emergency Stop + +| Key | Action | +|-----|--------| +| **O** / **o** | Immediate emergency stop — works even when gamepad or ZMQ is the active interface | +| **F** / **f** | Report motor temperatures (TTS voice alert) | + +### Compliance Controls + +These adjust hand compliance and grasp parameters globally. They are especially useful during teleoperation (ZMQ / ROS2) where the robot's hands interact with objects. + +| Key | Action | +|-----|--------| +| **G** / **H** | Increase / Decrease left hand compliance by 0.1 | +| **B** / **V** | Increase / Decrease right hand compliance by 0.1 | +| **X** / **C** | Increase / Decrease max hand close ratio by 0.1 | + +```{note} +Compliance controls are global — they affect the robot's hands no matter which interface is active. This lets you adjust compliance from the keyboard even while the gamepad or ZMQ is controlling the robot's movement. +``` + +## Interface-Specific Controls + +Once an interface is active, all its normal controls work as documented in its own tutorial: + +- **Keyboard** (`!`): All keys from the [Keyboard tutorial](keyboard.md) — T/R/P/N for motions, ENTER for planner, WASD for movement, etc. +- **Gamepad** (`@`): All buttons from the [Gamepad tutorial](gamepad.md) — Start, A/B, L1/R1, analog sticks, etc. +- **ZMQ** (`#`): ENTER to toggle streaming, T/P/N/R for reference motions when not streaming. See the [ZMQ tutorial](zmq.md). + +The only exceptions are: +- **`O`** is always intercepted by the manager for emergency stop (not passed to the active interface). +- **`G/H/B/V/X/C`** are always intercepted for compliance control. +- **`!/@ /#/$`** are always intercepted for interface switching. + diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vla_inference.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vla_inference.md new file mode 100644 index 0000000000000000000000000000000000000000..2a07e97fe48c970faf3900809fa0a16637654095 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vla_inference.md @@ -0,0 +1,386 @@ +# VLA Inference + +This guide covers running a trained Isaac-GR00T VLA policy on the Unitree G1 robot +using the Sonic whole-body control stack. + +## Overview + +The inference pipeline consists of: + +1. **Isaac-GR00T PolicyServer** — loads the VLA model and serves actions over ZMQ +2. **VLA inference client** (`run_vla_inference.py`) — reads camera + robot state, + queries the PolicyServer, and publishes actions to the C++ control loop +3. **C++ deploy** (`gear_sonic_deploy`) — executes whole-body control on the robot +4. **Camera server** — provides camera images over ZMQ (runs as a systemd service) +5. **Data exporter** (optional) — records episodes during inference + +``` +┌──────────────────────┐ +│ Isaac-GR00T │ +│ PolicyServer │ +│ (GPU machine) │ +└──────┬───────────────┘ + │ ZMQ REQ/REP + ▼ +┌─────────────────────┐ ZMQ TCP ┌──────────────────────┐ +│ VLA Inference │ ◄─────────── │ Camera Server │ +│ (run_vla_inference)│ │ (on robot) │ +└────┬───────────┬────┘ └──────────────────────┘ + │ │ + │ ZMQ PUB │ ZMQ SUB + │ (actions) │ (state) + ▼ ▼ +┌─────────────────────┐ +│ C++ Deploy │ +│ (gear_sonic_deploy)│ +└─────────────────────┘ +``` + +## Prerequisites + +### 1. Isaac-GR00T PolicyServer + +The PolicyServer runs on a machine with a GPU. It loads your finetuned VLA model +and serves inference over ZMQ. + +Install [Isaac-GR00T](https://github.com/NVIDIA/Isaac-GR00T) and start the server: + +```bash +# On the GPU machine (from the Isaac-GR00T repo) +uv run python gr00t/eval/run_gr00t_server.py \ + --model-path /path/to/your/finetuned_model \ + --embodiment-tag UNITREE_G1_SONIC \ + --device cuda:0 \ + --port 5550 +``` + +### 2. Inference Environment + +On the inference machine (can be the same as the PolicyServer or a separate PC): + +```bash +bash install_scripts/install_inference.sh +``` + +This creates `.venv_inference` with the Isaac-GR00T PolicyClient and all +inference dependencies. + +### 3. Camera Server + +The camera server should be running as a systemd service on the robot. +See [Data Collection](data_collection.md) for camera server setup. + +### 4. C++ Deploy + +The `gear_sonic_deploy` binary must be built. See the main README. + +### SONIC v1.1 Checkpoint + +Use the `sonic_v1_1/` checkpoint when the VLA policy was trained against +the robot-heading-normalized SONIC controller. It uses a 10-frame SMPL/wrist +reference horizon and was trained with wrist-pose augmentation. It is not the +low-latency checkpoint. + +```bash +python download_from_hf.py --sonic-v1-1 +``` + +Launch the matching C++ controller: + +```bash +cd gear_sonic_deploy +./deploy.sh \ + --cp policy/sonic_v1_1/model \ + --obs-config policy/sonic_v1_1/observation_config.yaml \ + --input-type zmq_manager \ + real +``` + +Or pass the same model pair to the Python launcher: + +```bash +python gear_sonic/scripts/launch_inference.py \ + --deploy-checkpoint policy/sonic_v1_1/model \ + --deploy-obs-config policy/sonic_v1_1/observation_config.yaml \ + --camera-host 192.168.123.164 \ + --prompt "pick up the cup" +``` + +### Low-Latency Teleoperation Checkpoint + +The `low_latency/` checkpoint is configured for responsive whole-body +teleoperation. Its SMPL encoder uses 4 future reference frames at 50 Hz +(approximately 80 ms of reference lookahead), compared with 10 frames +(approximately 200 ms) in the default release. This is reference lookahead, +not total end-to-end system latency. + +Download the deployment files from Hugging Face: + +```bash +python download_from_hf.py --low-latency +``` + +Then launch `gear_sonic_deploy` with the low-latency model prefix and matching +observation config: + +**C++ deploy:** + +```bash +cd gear_sonic_deploy +./deploy.sh \ + --cp policy/low_latency/model \ + --obs-config policy/low_latency/observation_config.yaml \ + --input-type zmq_manager \ + real +``` + +For simulation, replace `real` with `sim`. The `--cp` value is a model prefix: +`deploy.sh` appends `_encoder.onnx` and `_decoder.onnx` internally. + +**Python launcher:** + +```bash +python gear_sonic/scripts/launch_inference.py \ + --deploy-checkpoint policy/low_latency/model \ + --deploy-obs-config policy/low_latency/observation_config.yaml \ + --camera-host 192.168.123.164 \ + --prompt "pick up the cup" +``` + +The Python launcher starts the same C++ deploy command in a tmux pane, then runs +the Python VLA inference client, keyboard publisher, and optional data exporter. + +## Action Space + +The Sonic embodiment (`unitree_g1_sonic`) uses a 78-dimensional action +space: 64-dim motion token + 7-dim left hand joints + 7-dim right hand joints. + +## Quick Start — tmux Launcher + +The easiest way to run inference is with the all-in-one tmux launcher: + +```bash +# Real robot +python gear_sonic/scripts/launch_inference.py \ + --prompt "pick up the apple" \ + --camera-host 192.168.123.164 + +# Simulation +python gear_sonic/scripts/launch_inference.py --sim \ + --prompt "pick up the apple" + +# Without data recording +python gear_sonic/scripts/launch_inference.py \ + --no-data-exporter \ + --prompt "pick up the apple" +``` + +The launcher creates a tmux session with four panes: + +| Pane | Component | Description | +|------|-----------|-------------| +| 0 (top-left) | C++ Deploy | Whole-body controller | +| 1 (bottom-left) | Keyboard Publisher | Type keyboard commands here | +| 2 (top-right) | VLA Inference | Policy client + action loop | +| 3 (bottom-right) | Data Exporter | Records episodes (optional) | + +### Keyboard Controls + +Type these keys in the **Keyboard Publisher** pane (pane 1): + +| Key | Action | +|-----|--------| +| `k` | Start / stop the C++ control loop | +| `i` | Blend smoothly to initial pose and switch to POSE mode | +| `p` | Pause / resume policy inference | +| `[` | Toggle left hand open/closed (initial pose) | +| `]` | Toggle right hand open/closed (initial pose) | +| `t ` | Change the inference prompt (e.g., `t pick up the cup`) | +| `c` | Start recording an episode (data exporter) | +| `s` | Stop recording — success (data exporter) | +| `f` | Stop recording — failure / discard (data exporter) | + +### Typical Workflow + +1. Wait for all panes to initialize +2. Click on **pane 0** (C++ Deploy) and press Enter to confirm deployment +3. Switch to **pane 1** (Keyboard Publisher) +4. Press `k` to start the C++ control loop (starts in PLANNER mode) +5. Press `i` to blend to the initial pose (switches to POSE mode) + > The robot smoothly interpolates to the initial pose over 1 second. If your + > task starts from a different pose than the default, see + > [Customizing the Initial Pose](#customizing-the-initial-pose) below. +6. Press `p` to unpause the inference loop +7. The robot will begin executing VLA-predicted actions +8. Press `p` to pause, `k` to stop the control loop when done + +## Manual Setup (Without tmux) + +If you prefer to run each component in separate terminals: + +### Terminal 1 — Isaac-GR00T PolicyServer (GPU machine) + +```bash +# From the Isaac-GR00T repo +uv run python gr00t/eval/run_gr00t_server.py \ + --model-path /path/to/your/finetuned_model \ + --embodiment-tag UNITREE_G1_SONIC \ + --device cuda:0 \ + --port 5550 +``` + +### Terminal 2 — C++ Deploy + +```bash +cd gear_sonic_deploy +./deploy.sh --input-type zmq_manager real +``` + +Low-latency variant: + +```bash +python gear_sonic/scripts/launch_inference.py \ + --deploy-checkpoint policy/low_latency/model \ + --deploy-obs-config policy/low_latency/observation_config.yaml \ + --camera-host 192.168.123.164 \ + --prompt "pick up the apple" +``` + +Manual C++ deploy equivalent: + +```bash +cd gear_sonic_deploy +./deploy.sh \ + --cp policy/low_latency/model \ + --obs-config policy/low_latency/observation_config.yaml \ + --input-type zmq_manager \ + real +``` + +### Terminal 3 — VLA Inference + +```bash +source .venv_inference/bin/activate +python gear_sonic/scripts/run_vla_inference.py \ + --host \ + --port 5550 \ + --embodiment-tag unitree_g1_sonic \ + --prompt "pick up the apple" \ + --camera-host 192.168.123.164 +``` + +### Terminal 4 — Data Exporter (optional) + +```bash +source .venv_data_collection/bin/activate +python gear_sonic/scripts/run_data_exporter.py \ + --task-prompt "pick up the apple" \ + --camera-host 192.168.123.164 +``` + +## Configuration Reference + +### VLA Inference (`run_vla_inference.py`) + +| Flag | Default | Description | +|------|---------|-------------| +| `--host` | `localhost` | PolicyServer host | +| `--port` | `5550` | PolicyServer port | +| `--embodiment-tag` | `unitree_g1_sonic` | Embodiment tag | +| `--prompt` | `demo` | Language prompt | +| `--action-publish-rate` | `50` | Action publish rate (Hz) | +| `--action-horizon` | `40` | Actions per inference chunk | +| `--rate` | `2.5` | Inference rate (Hz) | +| `--camera-host` | `localhost` | Camera server host | +| `--camera-port` | `5555` | Camera server port | +| `--initial-pose-blend-duration` | `1.0` | Seconds to blend to initial pose (0 = instant snap) | +| `--verbose-timing` | `false` | Always print loop timing | + +### tmux Launcher (`launch_inference.py`) + +The launcher exposes all the above flags plus deploy and data exporter options. +Run `python gear_sonic/scripts/launch_inference.py --help` for the full list. + +## Remote PolicyServer + +When running the PolicyServer on a separate GPU machine: + +```bash +# On the inference machine, point to the remote server +python gear_sonic/scripts/launch_inference.py \ + --policy-host \ + --policy-port 5550 \ + --camera-host 192.168.123.164 \ + --prompt "pick up the apple" +``` + +Make sure port 5550 (or your chosen port) is accessible between the two machines. + +## Latency Compensation + +The inference loop automatically compensates for network and compute latency. +When a new action chunk arrives, the system calculates how many actions in the +chunk are already "stale" based on the time elapsed since inference started, +and skips to the appropriate action index. This is controlled by `--action-publish-rate` +and `--action-horizon`. + +## Customizing the Initial Pose + +When you press `i`, the inference client blends the robot smoothly from its +current configuration to a predefined **initial pose** encoded as a 64-dim +latent motion token. This pose should match the starting configuration your +demonstrations typically begin from. + +### When to Change the Initial Pose + +You should update the initial motion token if: + +- Your collected demonstrations start from a pose far from the default + (e.g., arms raised, holding an object, or a different standing stance) +- You switch to a different SONIC checkpoint (each checkpoint has its own + latent space — the same token produces different poses across checkpoints) +- The robot is snapping to a dangerous or unstable configuration on `i` press + +### Where to Change It + +Edit `gear_sonic/utils/inference/initial_poses.py`: + +```python +LATENT_INITIAL_MOTION_TOKEN = np.array( + [ + # Replace with your 64-dim token + ... + ], + dtype=np.float32, +) +``` + +### How to Find a Good Token + +1. **From data collection:** Look at the first action frame of a good demonstration + episode. The `action.motion_token` column in the parquet file at `frame_index=0` + gives you the latent token for that pose. + +2. **From the C++ deploy:** Put the robot in the desired starting pose via teleop, + then read the most recent latent token published on the ZMQ action channel. + +### Blend Duration + +The blend duration controls how quickly the robot transitions to the initial pose: + +```bash +# Default: 1 second smooth blend +python gear_sonic/scripts/run_vla_inference.py --initial-pose-blend-duration 1.0 + +# Faster blend (0.5 seconds) +python gear_sonic/scripts/run_vla_inference.py --initial-pose-blend-duration 0.5 + +# Instant snap (no interpolation, legacy behavior) +python gear_sonic/scripts/run_vla_inference.py --initial-pose-blend-duration 0 +``` + +```{warning} +Setting `--initial-pose-blend-duration` too low (or to 0) can cause jerky motion, +especially if the robot's current pose is far from the initial pose. The default +1-second blend is safe for most configurations. +``` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vla_workflow.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vla_workflow.md new file mode 100644 index 0000000000000000000000000000000000000000..450efa0de2e929a0344b1b33c435e9f7604842a7 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vla_workflow.md @@ -0,0 +1,208 @@ +# VLA Workflow: Collect, Fine-tune, Deploy + +This tutorial walks through the end-to-end workflow for training and deploying a +VLA policy on the Unitree G1 with SONIC whole-body control: + +1. **Collect** teleop demonstrations using the SONIC stack +2. **Fine-tune** the Isaac-GR00T N1.7 model on your collected data +3. **Deploy** the finetuned policy for autonomous inference + +```text ++-----------------+ +-----------------+ +-----------------+ +| 1. Collect | | 2. Fine-tune | | 3. Deploy | +| VR teleop + | --> | Isaac-GR00T | --> | PolicyServer + | +| data export | | N1.7 | | SONIC | ++-----------------+ +-----------------+ +-----------------+ +``` + +For examples of whole-body manipulation tasks accomplished with this workflow, see the +[VLA result videos on the GEAR-SONIC project page](https://nvlabs.github.io/GEAR-SONIC/#connection-to-vla-foundation-model). + +## How It Works: SONIC Latent Actions + +Instead of predicting raw joint angles, the VLA predicts **SONIC latent motion +tokens** — a compact 64-dimensional representation learned by the SONIC whole-body +controller. SONIC then decodes these latents into full-body joint commands at 50 Hz. + +```text ++-------------+ latent tokens +-------------+ joint commands +-------+ +| VLA Model | ----------------> | SONIC | -----------------> | Robot | +| 2.5 Hz | 64-dim x 40 | Decoder | 50 Hz | | +| | | C++ | | | ++-------------+ +-------------+ +-------+ +``` + +This means the VLA only needs to reason about *what* to do — SONIC handles the +*how*: balance, locomotion, and smooth whole-body coordination +all come for free from the pretrained controller. The result is a system that can +walk, reach, grasp, and manipulate simultaneously. + +The full action space per inference step is 78-dimensional: 64-dim motion token + +7-dim left hand joints + 7-dim right hand joints. + +## Step 1: Data Collection + +Collect teleop demonstrations using VR whole-body teleoperation. The data exporter +records robot state, camera images, and teleop actions as a LeRobot dataset. + +See the [Data Collection tutorial](data_collection.md) for full setup instructions +(camera server, VR teleop, recording controls). + +**Quick start:** + +```bash +python gear_sonic/scripts/launch_data_collection.py \ + --camera-host 192.168.123.164 \ + --task-prompt "pick up the soda can and place it in the bin" +``` + +**Output:** A LeRobot v2.1 dataset directory, e.g.: + +```text +outputs/2026-04-03-14-30-00-G1-robot01/ ++-- data/ +| +-- train-00000.parquet ++-- videos/ +| +-- observation.images.ego_view/ +| +-- episode_000000.mp4 ++-- meta/ + +-- info.json + +-- modality.json + +-- episodes.jsonl + +-- tasks.jsonl +``` + +```{tip} +Collect at least 50–100 demonstrations of the target task for reliable fine-tuning. +Use `--dataset-name` to append multiple sessions into the same dataset, or merge +sessions afterwards with `process_dataset.py`. +``` + +### Post-Process Before Fine-tuning + +After collection, run the processing script to remove discarded episodes +(flagged via `x` key during recording) and clean stale SMPL frames: + +```bash +source .venv_data_collection/bin/activate +python gear_sonic/scripts/process_dataset.py \ + --dataset-path outputs/2026-04-03-14-30-00-G1-robot01 \ + --output-path outputs/my_task_cleaned +``` + +This ensures only successful demonstrations are used for fine-tuning. + +## Step 2: Fine-tuning with Isaac-GR00T + +Fine-tune the GR00T N1.7 base model on your collected dataset using the +[Isaac-GR00T](https://github.com/NVIDIA/Isaac-GR00T) training pipeline. + +### Prerequisites + +- Clone and install [Isaac-GR00T](https://github.com/NVIDIA/Isaac-GR00T): + ```bash + git clone https://github.com/NVIDIA/Isaac-GR00T.git + cd Isaac-GR00T + uv sync --all-extras + ``` +- Multi-GPU machine (4+ GPUs recommended) +- The collected dataset accessible from the training machine + +### Launch Fine-tuning + +```bash +export NUM_GPUS=4 +uv run python \ + gr00t/experiment/launch_finetune.py \ + --base-model-path nvidia/GR00T-N1.7-3B \ + --dataset-path /path/to/your/collected_dataset \ + --embodiment-tag UNITREE_G1_SONIC \ + --modality-config-path gr00t/configs/data/embodiment_configs.py \ + --num-gpus $NUM_GPUS \ + --output-dir /path/to/output \ + --save-total-limit 5 \ + --save-steps 5000 \ + --max-steps 20000 \ + --use-wandb \ + --global-batch-size 32 \ + --color-jitter-params brightness 0.3 contrast 0.4 saturation 0.5 hue 0.08 \ + --dataloader-num-workers 4 +``` + +### Key Parameters + +| Flag | Description | +|------|-------------| +| `--base-model-path` | HuggingFace model ID or local path to pretrained weights | +| `--dataset-path` | Path to the LeRobot dataset from Step 1 | +| `--embodiment-tag` | Must match the dataset's embodiment (`UNITREE_G1_SONIC`) | +| `--modality-config-path` | Python file defining the modality configuration | +| `--num-gpus` | Number of GPUs for distributed training | +| `--max-steps` | Total training steps (20k is a good starting point) | +| `--global-batch-size` | Total batch size across all GPUs | +| `--save-steps` | Checkpoint save interval | +| `--use-wandb` | Enable Weights & Biases logging | + +### Monitoring + +With `--use-wandb`, training metrics (loss, learning rate, etc.) are logged to your +W&B project. Monitor the training loss curve — it should decrease steadily and +plateau before `--max-steps`. + +### Output + +Checkpoints are saved to `--output-dir`: + +```text +/path/to/output/ ++-- checkpoint-5000/ ++-- checkpoint-10000/ ++-- checkpoint-15000/ ++-- checkpoint-20000/ ++-- config.json ++-- processor_config.json +``` + +Use the final checkpoint (or the best-performing one based on your evaluation) for +deployment in Step 3. + +## Step 3: Deploy for Inference + +Deploy the finetuned model using the Isaac-GR00T PolicyServer and the SONIC +inference stack. See the [VLA Inference tutorial](vla_inference.md) for full +details on the inference pipeline, keyboard controls, and configuration. + +### Start the PolicyServer + +On the GPU machine, from the Isaac-GR00T repository: + +```bash +uv run python gr00t/eval/run_gr00t_server.py \ + --model-path /path/to/output/checkpoint-20000 \ + --embodiment-tag UNITREE_G1_SONIC \ + --device cuda:0 \ + --port 5550 +``` + +### Run Inference + +On the inference machine (from the GR00T-WholeBodyControl repository): + +```bash +python gear_sonic/scripts/launch_inference.py \ + --policy-host \ + --policy-port 5550 \ + --camera-host 192.168.123.164 \ + --prompt "pick up the soda can and place it in the bin" +``` + +## Summary + +| Step | Where | Key Command | +|------|-------|-------------| +| Collect | GR00T-WholeBodyControl | `launch_data_collection.py` | +| Fine-tune | Isaac-GR00T | `launch_finetune.py` | +| Deploy | Both repos | `run_gr00t_server.py` + `launch_inference.py` | + +For iterating on a task, repeat Steps 1–3: collect more data, fine-tune again +(or continue from an existing checkpoint), and redeploy. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vr_wholebody_teleop.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vr_wholebody_teleop.md new file mode 100644 index 0000000000000000000000000000000000000000..2de35e29f58bec9ba12714e2ae7be816514ee0c4 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/vr_wholebody_teleop.md @@ -0,0 +1,368 @@ +# PICO VR Whole-body Teleop + +Full whole-body teleoperation using PICO VR headset and controllers. To teleop, use the option `--input-type zmq_manager` during deployment. The `zmq_manager` input type switches between a **planner mode** (locomotion commands via ZMQ) and a **streamed motion mode** (full-body SMPL poses from PICO). + +## SONIC Low Latency + +The sequence below shows SONIC Low Latency running in whole-body teleoperation +mode, including a successful ground pickup. + +```{image} ../_static/sonic_low_latency_demo.gif +:alt: SONIC Low Latency whole-body teleoperation and ground pickup +:width: 640px +:align: center +``` + +```{admonition} Isaac Teleop / CloudXR Scope +:class: note +The same `zmq_manager` workflow can also drive the headset through Isaac Teleop / CloudXR by launching `gear_sonic/scripts/pico_manager_thread_server.py --input-source isaac-teleop`. The streamer hosts the CloudXR runtime in-process via `isaacteleop[cloudxr]` — no separate publisher container required. That path is currently supported only for **G1 with a Thor backpack**; a regular G1 setup is not supported yet. +``` + +```{admonition} Safety Warning +:class: danger +Whole-body teleoperation involves fast, agile motions. **Always** maintain a clear safety zone and keep a safety operator at the keyboard ready to trigger an emergency stop (**`O`** in the C++ terminal, or **A+B+X+Y** on the PICO controllers). + +You **must wear tight-fitting pants or leggings** to guarantee line-of-sight for the foot trackers — loose or baggy clothing can make tracking fail unpredictably and may result in dangerous motion. +``` + +```{video} ../_static/teleop/teleop_session_overview.mp4 +:width: 100% +``` +*Video: End-to-end teleoperation walkthrough — PICO calibration, policy engagement, and the robot balancing independently. See the [Teleoperation Guide](../user_guide/teleoperation.md) for detailed best practices.* + +## Prerequisites + +1. **Completed the [Quick Start](../getting_started/quickstart.md)** — you can run the sim2sim loop (includes [installing the deployment](../getting_started/installation_deploy.md) and [downloading model checkpoints](../getting_started/download_models.md)). +2. **Completed the [VR Teleop Setup](../getting_started/vr_teleop_setup.md)** — `.venv_teleop` is ready. For the default path, PICO hardware is installed, calibrated, and connected. For Isaac Teleop / CloudXR, the `isaacteleop[cloudxr]` package is also installed (handled by `install_pico.sh`) and the headset connects to the in-process CloudXR runtime — see [Isaac Teleop Setup](isaac_teleop_publisher_setup.md). + +--- + +## Step-by-Step: Teleop in SIM + +Run **three terminals** to teleoperate the simulated robot. + +### Terminal 1 — Launch virtual robot in MuJoCo Simulator + +From the **repo root**: + +```bash +# bash install_scripts/install_pico.sh + +source .venv_teleop/bin/activate +python gear_sonic/scripts/run_sim_loop.py +``` + +### Terminal 2 — C++ Deployment + +From `gear_sonic_deploy/`: + +```bash +cd gear_sonic_deploy +source scripts/setup_env.sh +./deploy.sh --input-type zmq_manager sim +# Wait until you see "Init done" +``` + +**Isaac Teleop / CloudXR alternative** (**G1 + Thor backpack only**) — run the C++ deployment from the project's ROS2 docker container instead of bare metal: + +```bash +cd gear_sonic_deploy +export TensorRT_ROOT=$HOME/TensorRT # only if not already in ~/.bashrc +./docker/run-ros2-dev.sh + +# inside the container (setup_env.sh is sourced automatically): +just build # first run only +./deploy.sh --input-type zmq_manager sim +# Wait until you see "Init done" +``` + +See [Installation (Deployment) → Docker (ROS2 Development Environment)](../getting_started/installation_deploy.md) for details on `run-ros2-dev.sh` and `TensorRT_ROOT`. + +```{note} +The `--zmq-host` flag defaults to `localhost`, which is correct when both C++ deployment scripts and teleop scripts (Terminal 3) run on the same machine. If the teleop script runs on a different machine, pass `--zmq-host `. +``` + +### Terminal 3 — PICO Teleop Streamer + +From the **repo root**: + +```bash +source .venv_teleop/bin/activate + +# With full visualization (recommended for first run): +python gear_sonic/scripts/pico_manager_thread_server.py --manager \ + --vis_vr3pt --vis_smpl + +# Without visualization (for headless / onboard practice): +# python gear_sonic/scripts/pico_manager_thread_server.py --manager +``` + +**Isaac Teleop / CloudXR alternative** (**G1 + Thor backpack only**) — connects the headset over CloudXR (no XRoboToolKit PC service required); the streamer launches the CloudXR runtime in-process via `isaacteleop[cloudxr]`: + +```bash +source .venv_teleop/bin/activate + +python gear_sonic/scripts/pico_manager_thread_server.py --manager \ + --input-source isaac-teleop + +# If running offboard with a display, add visualization: +# --vis_vr3pt --vis_smpl +``` + +When you turn on the visualization, wait for a window to pop up showing a Unitree G1 mesh with all joints at the default angles. If no window shows up on the default PICO path, double-check the PICO's XRoboToolKit IP configuration in the [VR Teleop Setup](../getting_started/vr_teleop_setup.md). If you are using Isaac Teleop instead, verify the headset is connected to the in-process CloudXR runtime — see [Isaac Teleop Setup](isaac_teleop_publisher_setup.md) for connection steps. + +### Your First Teleop Session + +1. **Assume the calibration pose** — stand upright, feet together, upper arms at your sides, forearms bent 90° forward (L-shape at each elbow), palms inward. See [Calibration Pose](#calibration-pose) for details. +2. Press **A + B + X + Y** simultaneously to engage the control policy and run the initial full calibration (`CALIB_FULL`). +3. Align your arms with the robot's current pose, then press **A + X** to enter full-body SMPL teleop (**POSE** mode). Move your arms and legs — the robot follows. +4. Press **A + X** again to fall back to **PLANNER** (idle) mode. +5. Press **A + B + X + Y** again to stop the robot. + +
+ +
Basic whole-body teleop workflow: calibration pose → engage → POSE mode → PLANNER idle → stop.
+
+ +--- + +(pico-controls)= + +## Complete PICO Controls + +### Modes & Calibration + +The system has **4 operating modes** and **2 calibration types**. + +**Modes:** + +| Mode | Encoder | Description | +|---|---|---| +| **OFF** | -- | Policy not running. Stand in [calibration pose](#calibration-pose), then press **A+B+X+Y** to start policy. | +| **POSE** | SMPL | Whole-body teleop — streaming the SMPL pose from PICO to the C++ deployment side. Your motion will directly map to the robot .| +| **PLANNER** | G1 | Locomotion planner active; upper body controller by planner. Joysticks control direction and heading in walking and running modes. | +| **PLANNER_FROZEN_UPPER** | G1 | Planner locomotion; upper body frozen at last POSE snapshot. | +| **VR_3PT** | TELEOP | Planner locomotion; upper body follows VR 3-point tracking (head + 2 hands). Depends on non-IK-based VR 3-point calibration. | + +**Calibration types** (non-IK workflow for minimal latency): + +| Type | What Is Calibrated | When Triggered | +|---|---|---| +| **CALIB_FULL** | Head + both wrists against **all-zero** reference pose. | Once on first **A+B+X+Y** (startup). | +| **CALIB** | Both wrists only against the **current robot pose**. | Each switch into VR_3PT via **Left Stick Click**. | + +### State Machine + +There are 4 modes and 2 control chains. Each chain forms a triangle: **A+X** (or **B+Y**) returns to POSE from *both* the planner node and its VR_3PT sub-mode. + +```text + ┌──────────────────────────────────────┐ + │ A+B+X+Y (any mode) ──► OFF │ + └──────────────────────────────────────┘ + + Startup: + OFF ──(A+B+X+Y)──► PLANNER ──(A+X)──► POSE + CALIB_FULL + + Chain 1 — G1 encoder listens to planner-generated full-body motion: PLANNER + + PLANNER ─── L-Stick (+CALIB) ──► VR_3PT + ▲ │ ◄─────── L-Stick ───────── │ + │ │ │ + │A+X │A+X A+X │ + │ ▼ ▼ + └─ POSE ◄──────────────────────────┘ + + Chain 2 — G1 encoder listens to planner-generated lower-body motion: PLANNER_FROZEN_UPPER + + PLANNER_FROZEN_UPPER ── L-Stick (+CALIB) ──► VR_3PT + ▲ │ ◄──────── L-Stick ────────── │ + │ │ │ + │B+Y │B+Y B+Y │ + │ ▼ ▼ + └── POSE ◄───────────────────────────────┘ +``` + +```{admonition} DANGER — Mode-Switching Safety +:class: danger +**Before switching into POSE or VR_3PT**, always align your body with the robot's current pose first!! + +- **POSE:** The robot instantly snaps to your physical pose. A large mismatch causes sudden, aggressive motion. +- **VR_3PT:** A misaligned calibration produces erratic, dangerous motion as soon as you move your arms. Check more info at section [per-switch-calib](#per-switch-calib) +``` + +(calibration-pose)= + +### VR_3PT Calibration Hint + +The `VR_3PT` mode depends on accurate calibration. Two calibration events occur: + +#### One-time `CALIB_FULL` (head + wrists) + +Before pressing **A + B + X + Y** for the first time, you **must** stand in the robot's **all-zero reference pose**. The system captures your PICO body-tracking frame as the zero-reference for all subsequent motion mapping. + +**The reference pose:** +1. **Stand upright**, feet together, looking straight forward. +2. **Upper arms** hang straight down, close to your torso. +3. **Forearms** bent 90° forward (L-shape at each elbow), palms facing inward. + +```{tip} +Launch the teleop script with `--vis_vr3pt` to see the robot's reference pose in a visualization window. Match your body to it before pressing the start combo. +``` + +(per-switch-calib)= +#### Per-switch `CALIB` (wrists only) + +Each time you enter `VR_3PT` via **Left Stick Click**, the system re-calibrates both wrists against the robot's **current** pose. Always align your arms with the robot before clicking. + +Below is an example of **bad calibration practice** — transitioning into VR_3PT without aligning your arms to the robot's current pose. The robot may not jump immediately, but will exhibit erratic and dangerous motion as soon as you move. + +
+ +
Bad practice: entering VR_3PT without arm alignment causes erratic, unsafe motion.
+
+ + + + +```{admonition} DANGER — Mode-Switching Safety +:class: danger +**Before switching into POSE or VR_3PT**, always align your body with the robot's current pose first. + +**Recovery from bad VR_3PT calibration:** +1. Freeze the upper body — switch back via **Left Stick Click**. +2. Re-align your arms with the robot's current (possibly distorted) pose. +3. Switch to **POSE** mode (**A+X**) to reset. +``` + +Below is the **recovery procedure** — if you accidentally enter a badly calibrated VR_3PT state, freeze the upper body (Left Stick Click back), then switch to POSE mode (A+X) to reset safely. + +
+ +
Recovery from bad VR_3PT calibration: freeze upper body → re-align → switch to POSE mode.
+
+ +### Quick-Start Cheatsheet + +| Action | Button | Notes | +|---|---|---| +| **Start / Stop policy** | **A+B+X+Y** | First press: engage + CALIB_FULL. Again: emergency stop → OFF. | +| **Toggle POSE** | **A+X** | Switches between PLANNER ↔ POSE. OR from VR_3PT (entered via PLANNER) → POSE. | +| **Toggle PLANNER_FROZEN_UPPER** | **B+Y** | Switches between POSE ↔ PLANNER_FROZEN_UPPER. OR from VR_3PT (entered via PLANNER_FROZEN_UPPER) → POSE. | +| **Toggle VR_3PT** | **Left Stick Click** | From any Planner mode → VR_3PT (triggers CALIB). Click again to return. | +| **Hand grasp** | **Trigger** (per hand) | Controls the corresponding hand's grasp. | + +### Joystick Controls (Planner Modes) + +Active in **PLANNER**, **PLANNER_FROZEN_UPPER**, and **VR_3PT**: + +| Input | Function | +|---|---| +| **Left Stick** | Move direction (forward / backward / strafe) | +| **Right Stick (horizontal)** | Yaw / heading (continuous accumulation) | +| **A + B** | Next locomotion mode | +| **X + Y** | Previous locomotion mode | + +**Locomotion modes** (cycled via A+B / X+Y): + +| ID | Mode | +|---|---| +| 0 | Idle [DEFAULT] | +| 1 | Slow Walk | +| 2 | Walk | +| 3 | Run | +| 4 | Squat | +| 5 | Kneel (two legs) | +| 6 | Kneel | +| 7 | Lying face-down | +| 8 | Crawling | +| 9–16 | Boxing variants (idle, walk, punches, hooks) | +| 17 | Forward Jump | +| 18 | Stealth Walk | +| 19 | Injured Walk | + +--- + +## Emergency Stop + +| Method | Action | +|---|---| +| **PICO controllers** | Press **A+B+X+Y** simultaneously → OFF | +| **Keyboard** (C++ terminal) | Press **`O`** for immediate stop | + +--- + +## Step-by-Step: Teleop on Real Robot + +```{admonition} Safety Warning +:class: danger +Only proceed once you can smoothly control the robot in simulation and are comfortable with emergency stops. **Terminate any running `run_sim_loop.py` process first** — simultaneous sim and real instances will conflict. +``` + +The real-robot workflow uses **two terminals** (no MuJoCo simulator). + +### Terminal 1 — C++ Deployment (Real Robot) + +From `gear_sonic_deploy/`: + +```bash +cd gear_sonic_deploy +source scripts/setup_env.sh + +# 'real' auto-detects the robot network interface (192.168.123.x). +# If auto-detection fails, pass the G1's IP directly: +# ./deploy.sh --input-type zmq_manager +./deploy.sh --input-type zmq_manager real + +# Wait until you see "Init done" +``` + +**Isaac Teleop / CloudXR alternative** (**G1 + Thor backpack only**) — run the C++ deployment from the project's ROS2 docker container instead of bare metal: + +```bash +cd gear_sonic_deploy +export TensorRT_ROOT=$HOME/TensorRT # only if not already in ~/.bashrc +./docker/run-ros2-dev.sh + +# inside the container (setup_env.sh is sourced automatically): +just build # first run only +./deploy.sh --input-type zmq_manager real +# Wait until you see "Init done" +``` + +```{note} +If the teleop script (Terminal 2) runs on a different machine, add `--zmq-host ` so the C++ side knows where the ZMQ publisher is. +``` + +### Terminal 2 — PICO Teleop Streamer + +From the **repo root**: + +```bash +# bash install_scripts/install_pico.sh + +source .venv_teleop/bin/activate +python gear_sonic/scripts/pico_manager_thread_server.py --manager + +# If running offboard with a display, add visualization: +# --vis_vr3pt --vis_smpl +``` + +**Isaac Teleop / CloudXR alternative** (**G1 + Thor backpack only**) — in-process CloudXR runtime via `isaacteleop[cloudxr]`, no XRoboToolKit PC service required: + +```bash +source .venv_teleop/bin/activate +python gear_sonic/scripts/pico_manager_thread_server.py --manager --input-source isaac-teleop +``` + +```{note} +Update the IP in the PICO's XRoboToolKit app to match this machine before starting the default PICO path. For Isaac Teleop, make sure the headset is connected to the in-process CloudXR runtime — see [Isaac Teleop Setup](isaac_teleop_publisher_setup.md). +``` + +Follow the same start sequence: calibration pose → **A+B+X+Y** → **A+X** for POSE mode. See [Complete PICO Controls](#pico-controls) for all available commands. diff --git a/third-party/GR00T-WholeBodyControl/docs/source/tutorials/zmq.md b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/zmq.md new file mode 100644 index 0000000000000000000000000000000000000000..4749e1f75369493543ea7735d0255c952ab0d0e3 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/tutorials/zmq.md @@ -0,0 +1,350 @@ +# Streaming Motion Tracking + +Stream motion data to the robot over ZMQ for reference motion tracking. This interface supports streaming either **SMPL-based poses** (e.g., from PICO) or **G1 whole-body joint positions** (qpos) from any external source (`--input-type zmq`). + +```{admonition} Prerequisites +:class: note +Complete the [Quick Start](../getting_started/quickstart.md) to have the sim2sim loop running. +``` + +```{admonition} Emergency Stop +:class: danger +Press **`O`** at any time to immediately stop control and exit. Always keep a hand near the keyboard ready to press **`O`**. +``` + +## Launch + +**Sim2Sim (MuJoCo):** + +```bash +# Terminal 1 — MuJoCo simulator (from repo root) +source .venv_sim/bin/activate +python gear_sonic/scripts/run_sim_loop.py + +# Terminal 2 — C++ deployment (from gear_sonic_deploy/) +bash deploy.sh --input-type zmq \ + --zmq-host \ + --zmq-port 5556 \ + --zmq-topic pose \ + sim +``` + +**Real Robot:** + +```bash +# From gear_sonic_deploy/ +bash deploy.sh --input-type zmq \ + --zmq-host \ + --zmq-port 5556 \ + --zmq-topic pose \ + real +``` + +## Step-by-Step + +1. Press **`]`** to start the control system. +2. By default you are in **reference motion mode** — use **`T`** to play motions, **`N`** / **`P`** to switch, **`R`** to restart (same as the [keyboard interface](keyboard.md)). +3. Press **`ENTER`** to toggle into **ZMQ streaming mode**. The terminal will print `ZMQ STREAMING MODE: ENABLED`. +4. The policy now tracks motion frames arriving from the ZMQ publisher in real time. Playback starts automatically. +5. Press **`ENTER`** again to switch back to reference motions. The terminal will print `ZMQ STREAMING MODE: DISABLED`, and the encode mode resets to `0` (joint-based). +6. Use **`Q`** / **`E`** to adjust the heading (±0.1 rad per press) in either mode. +7. Press **`I`** to reinitialize the base quaternion and reset the heading to zero. +8. When done, press **`O`** to stop control and exit. + +```{note} +**No planner support** — this interface uses pre-loaded and ZMQ-streamed reference motions only. For planner + ZMQ control (e.g., PICO VR teleoperation), use `--input-type zmq_manager` instead. See the [VR Whole-Body Teleop tutorial](vr_wholebody_teleop.md). +``` + +```{tip} +**Build your own streaming source.** The ZMQ stream protocol documented below is self-contained — any publisher that sends messages in this format can drive the robot. You can write your own motion capture retargeting pipeline, simulator bridge, or any other source that produces the required fields. No PICO hardware is needed. +``` + +## Using with PICO VR Teleop + +You can use `--input-type zmq` with the PICO teleop streamer for a simple, streaming-only whole-body teleoperation setup. In this mode, the PICO streams full-body SMPL poses over ZMQ and the deployment side tracks them directly — no locomotion planner, no PICO-button mode switching. All control is done from the keyboard. + +### Prerequisites + +1. **Completed the [Quick Start](../getting_started/quickstart.md)** — you can run the sim2sim loop. +2. **PICO VR hardware is set up** — headset and controllers are connected, body tracking is working, and `.venv_teleop` is installed. See the [VR Teleop Setup](../getting_started/vr_teleop_setup.md) for installation and calibration. + +### Launch (Sim2Sim) + +Run three terminals: + +**Terminal 1 — MuJoCo simulator** (from repo root): + +```bash +source .venv_sim/bin/activate +python gear_sonic/scripts/run_sim_loop.py +``` + +**Terminal 2 — C++ deployment** (from `gear_sonic_deploy/`): + +```bash +bash deploy.sh --input-type zmq \ + --zmq-host localhost \ + --zmq-port 5556 \ + --zmq-topic pose \ + sim +``` + +**Terminal 3 — PICO teleop streamer** (from repo root): + +```bash +source .venv_teleop/bin/activate + +# With visualization (recommended for first run): +python gear_sonic/scripts/pico_manager_thread_server.py \ + --manager --vis_smpl --vis_vr3pt + +# Without visualization (headless): +# python gear_sonic/scripts/pico_manager_thread_server.py --manager +``` + +### Launch (Real Robot) + +Run two terminals (no MuJoCo): + +**Terminal 1 — C++ deployment** (from `gear_sonic_deploy/`): + +```bash +bash deploy.sh --input-type zmq \ + --zmq-host \ + --zmq-port 5556 \ + --zmq-topic pose \ + real +``` + +Replace `` with `localhost` if the PICO streamer runs on the same machine, or the IP of the machine running Terminal 2. + +**Terminal 2 — PICO teleop streamer** (from repo root): + +```bash +source .venv_teleop/bin/activate +python gear_sonic/scripts/pico_manager_thread_server.py --manager +``` + +### Step-by-Step + +1. **Calibration pose**: Stand upright, feet together, upper arms at your sides, forearms bent 90° forward (L-shape at each elbow), palms facing inward. +2. On the PICO controllers, press **A + B + X + Y** simultaneously to initialize and calibrate the body tracking. +3. Press **A + X** on the PICO controllers to start streaming poses. +4. In Terminal 2 (C++ deployment), press **`]`** to start the control system. +5. In the MuJoCo window (sim only), press **`9`** to drop the robot to the ground. +6. Back in Terminal 2, press **`ENTER`** to enable ZMQ streaming. The terminal prints `ZMQ STREAMING MODE: ENABLED`. The robot begins tracking your PICO poses in real time. +7. Move your body — the robot mirrors your motions. Use the **Trigger** button on each PICO controller to close the corresponding robot hand. +8. To **pause** streaming (e.g., to reposition yourself), press **`ENTER`** again. The terminal prints `ZMQ STREAMING MODE: DISABLED`. The robot holds its last pose and stops tracking. You can move freely without affecting the robot. +9. To **resume**, press **`ENTER`** once more. The robot will snap to your current pose — **move back close to the robot's current pose before resuming** to avoid sudden jumps. +10. When done, press **`O`** to stop control and exit. + +```{admonition} DANGER — Resuming from Pause +:class: danger +When you press **`ENTER`** to resume streaming after a pause, the robot will immediately try to reach your current physical pose. If your body is in a very different position from the robot, the robot may perform sudden, aggressive motions. **Always move back close to the robot's current pose before pressing `ENTER` to resume.** +``` + +### PICO Buttons in ZMQ Mode + +In `--input-type zmq` mode, the C++ deployment side does **not** process PICO controller button combos directly. However, the buttons still affect the **Python streamer**, which controls what data gets published on the `pose` ZMQ topic. Since the deployment side tracks whatever arrives (or stops arriving) on that topic, several buttons still have an indirect effect on the robot. + +| PICO Button | Effect | +|-------------|--------| +| **A + B + X + Y** | Calibrate body tracking in the streamer. Press once to initialize; press again to stop streaming (emergency stop on the streamer side). | +| **A + X** | Toggle Pose mode in the streamer — starts or stops publishing pose data. When stopped, the robot holds its last pose. **Works as pause/resume.** | +| **Menu (hold)** | Pauses pose streaming in the streamer while held. The robot holds its last pose until you release. **Works as pause.** Move back close to the robot's current pose before releasing. | +| **Trigger** | Hand grasp — processed by the streamer and sent as `left_hand_joints` / `right_hand_joints` in the stream. | +| **B + Y** | Toggle Pose mode in the streamer (same effect as A+X) — starts or stops publishing pose data. **Works as pause/resume.** | + +All mode control on the deployment side is done from the keyboard: + +| Key | Action | +|-----|--------| +| **`]`** | Start control system | +| **`ENTER`** | Toggle streaming on/off (pause/resume) | +| **`O`** | Emergency stop — stop control and exit | +| **`I`** | Reinitialize base quaternion and reset heading | +| **`Q`** / **`E`** | Adjust heading (±0.1 rad) | +| **`F`** | Report motor temperatures (TTS voice alert) | + +```{note} +For the full PICO VR experience with planner support, locomotion modes, and PICO-controller-based mode switching, use `--input-type zmq_manager` instead. See the [VR Whole-Body Teleop tutorial](vr_wholebody_teleop.md). +``` + +## Controls + +| Key | Action | +|-----|--------| +| **]** | Start control system | +| **O** | Stop control and exit (emergency stop) | +| **ENTER** | Toggle between reference motions and ZMQ streaming | +| **I** | Reinitialize base quaternion and reset heading | +| **Q** / **E** | Adjust delta heading left / right (±0.1 rad) | +| **F** | Report motor temperatures (TTS voice alert) | + +*Reference motion mode only (streaming off):* + +| Key | Action | +|-----|--------| +| **T** | Play current motion to completion | +| **R** | Restart current motion from beginning (pause at frame 0) | +| **P** / **N** | Previous / Next motion sequence | + +## Stream Protocol Versions + +The encode mode is determined automatically by the ZMQ stream protocol version. **SONIC uses Protocol v1, v3, and v4.** Protocol v2 is available for custom applications. + +### Encode Mode Logic + +The encode mode only takes effect when the policy model has an **encoder** configured and loaded. At startup, each motion's encode mode is initialized based on encoder availability: + +| `encode_mode` | Meaning | +|----------------|---------| +| `-2` | No encoder / token state configured in the model — encode mode has no effect | +| `-1` | Encoder config exists (token state dimension > 0) but no encoder model file provided | +| `0` | Encoder loaded, joint-based mode (default) | +| `1` | Encoder loaded, teleop / 3 points upper-body mode | +| `2` | Encoder loaded, SMPL-based mode | + +When ZMQ streaming is active, the protocol version sets the encode mode on the streamed motion: v1 → `0`, v2/v3 → `2`. Protocol v4 bypasses the encoder entirely — it streams pre-computed tokens directly into the policy. This only affects inference if the model actually has an encoder (`encode_mode >= 0`). If no encoder is configured (`-2`), the value is set but has no effect on the inference pipeline. + +When switching back to reference motions (pressing **ENTER** to disable streaming), the encode mode resets to `0` (if the motion has an encoder, i.e. `encode_mode >= 0`). + +### Common Fields (All Versions) + +All versions require two common fields: + +| Field | Shape | Dtype | Description | +|-------|-------|-------|-------------| +| `body_quat` | `[N, 4]` or `[N, num_bodies, 4]` | `f32` / `f64` | Body quaternion(s) per frame (w, x, y, z) | +| `frame_index` | `[N]` | `i32` / `i64` | Monotonically increasing frame indices for alignment | + +```{warning} +Changing the protocol version mid-session is not allowed. If the publisher switches protocol versions while streaming, the interface will automatically disable ZMQ mode and return to reference motions for safety. + +Error message: `Protocol version changed from X to Y during active ZMQ session!` +``` + +### Protocol v1 — Joint-Based (Encode Mode 0) + +Streams raw G1 joint positions and velocities. Use this when your source provides direct qpos/qvel data (e.g., from another simulator or motion capture retargeting pipeline). + +**Required fields:** + +| Field | Shape | Dtype | Description | +|-------|-------|-------|-------------| +| `joint_pos` | `[N, 29]` | `f32` / `f64` | Joint positions in IsaacLab order (all 29 joints) | +| `joint_vel` | `[N, 29]` | `f32` / `f64` | Joint velocities in IsaacLab order (all 29 joints) | + +- `N` = number of frames per message (batch size). +- All 29 joint values must be provided and meaningful. +- Frame counts of `joint_pos` and `joint_vel` must match. + +**Common errors:** +- `Version 1 missing required fields (joint_pos, joint_vel)` — one or both fields are absent. +- `Frame count mismatch between joint_pos and joint_vel` — the `N` dimension differs. + +### Protocol v2 — SMPL-Based (Encode Mode 2) + +Streams SMPL body model data. This protocol is **not used by SONIC's built-in pipelines** — it is available for your own custom applications that produce SMPL representations, for example a plicy only observe the SMPL. + +**Required fields:** + +| Field | Shape | Dtype | Description | +|-------|-------|-------|-------------| +| `smpl_joints` | `[N, 24, 3]` | `f32` / `f64` | SMPL joint positions (24 joints × xyz) | +| `smpl_pose` | `[N, 21, 3]` | `f32` / `f64` | SMPL joint rotations in axis-angle (21 body poses × xyz) | + +- `joint_pos` and `joint_vel` are **optional** in v2. + +**Common errors:** +- `Version 2 missing required field 'smpl_joints'` or `'smpl_pose'` — required SMPL fields are absent. + +### Protocol v3 — Joint + SMPL Combined (Encode Mode 2) + +Combines both joint-level and SMPL data. This is what SONIC uses for whole-body teleoperation (e.g., PICO VR). + +**Required fields:** + +| Field | Shape | Dtype | Description | +|-------|-------|-------|-------------| +| `joint_pos` | `[N, 29]` | `f32` / `f64` | Joint positions in IsaacLab order | +| `joint_vel` | `[N, 29]` | `f32` / `f64` | Joint velocities in IsaacLab order | +| `smpl_joints` | `[N, 24, 3]` | `f32` / `f64` | SMPL joint positions (24 joints × xyz) | +| `smpl_pose` | `[N, 21, 3]` | `f32` / `f64` | SMPL joint rotations in axis-angle (21 body poses × xyz) | + +```{important} +In Protocol v3, **only the 6 wrist joints need meaningful values** in `joint_pos` — the remaining 23 joints can be zero. The wrist joint indices (in IsaacLab order) are: **[23, 24, 25, 26, 27, 28]** (3 joints per wrist × 2 wrists). The `joint_vel` values for non-wrist joints can also be zero. + +The SMPL fields (`smpl_joints`, `smpl_pose`) carry the primary motion data in v3; the wrist joints in `joint_pos` provide fine-grained wrist control that SMPL alone cannot capture. +``` + +- Frame counts across all four fields must be consistent. + +**Common errors:** +- `Version 3 missing required field 'joint_pos'` or `'joint_vel'` — joint fields are absent (unlike v2, they are required in v3). +- `Version 3 frame count mismatch between smpl_joints (X) and joint_pos (Y)` — the `N` dimension differs across fields. + +### Protocol v4 — Token-Only Streaming (Direct Latent Actions) + +Streams pre-computed motion tokens directly to the policy, bypassing the encoder entirely. Use this when your source produces encoded latent actions (e.g., from a separate encoder running on a different machine, or a generative model that outputs tokens directly). + +Unlike v1–v3, Protocol v4 does **not** carry motion frames — the reference motion on the robot side is left unchanged. The tokens are injected directly into the `token_state` observation slot of the decoder policy. + +**Required fields:** + +| Field | Shape | Dtype | Description | +|-------|-------|-------|-------------| +| `token_state` | `[D]` | `f32` / `f64` | Motion token array (dimension must match the encoder `dimension` in the observation config) | + +**Optional fields:** + +| Field | Shape | Dtype | Description | +|-------|-------|-------|-------------| +| `frame_index` | `[1]` | `i32` / `i64` | Frame index (for logging only, does not affect playback) | +| `left_hand_joints` | `[7]` or `[1, 7]` | `f32` / `f64` | Left hand 7-DOF Dex3 joint positions | +| `right_hand_joints` | `[7]` or `[1, 7]` | `f32` / `f64` | Right hand 7-DOF Dex3 joint positions | +| `body_quat_w` | `[4]` or `[1, 4]` | `f32` / `f64` | Body quaternion (w,x,y,z) for heading updates | + +- The `token_state` dimension is validated against the encoder configuration. A mismatch is logged as a warning. +- Hand joints, when provided, are applied to the robot directly (same as v1–v3 optional hand fields). +- `body_quat_w` can be used to update the heading reference during token streaming. + +**Common errors:** +- `Version 4 missing required field 'token_state'` — the `token_state` field is absent from the message. +- `Protocol version 4 with motion data is impossible!` — v4 message produced a motion sequence (should never happen; indicates a decoder bug). +- `Protocol version 4 with empty token data!` — `token_state` field was present but contained no data. + +```{warning} +Protocol v4 requires the policy to have an encoder configuration with `token_state` in its observations. If the model has no encoder (`encode_mode == -2`), the tokens will be received but have no effect. +``` + +### Protocol Summary + +| Protocol | Encode Mode | Used by SONIC | Required Fields | +|----------|-------------|---------------|-----------------| +| v1 | `0` (joint-based) | ✅ Yes | `joint_pos`, `joint_vel` | +| v2 | `2` (SMPL-based) | ❌ Custom only | `smpl_joints`, `smpl_pose` | +| v3 | `2` (SMPL-based) | ✅ Yes | `joint_pos`, `joint_vel`, `smpl_joints`, `smpl_pose` | +| v4 | N/A (bypasses encoder) | ✅ Yes | `token_state` | + +## Optional Stream Fields + +The following optional fields can be included in any protocol version: + +| Field | Shape | Dtype | Description | +|-------|-------|-------|-------------| +| `left_hand_joints` | `[7]` or `[1, 7]` | `f32` / `f64` | Left hand 7-DOF Dex3 joint positions | +| `right_hand_joints` | `[7]` or `[1, 7]` | `f32` / `f64` | Right hand 7-DOF Dex3 joint positions | +| `vr_position` | `[9]` or `[3, 3]` | `f32` / `f64` | VR 3-point tracking positions: left wrist, right wrist, head (xyz × 3) | +| `vr_orientation` | `[12]` or `[3, 4]` | `f32` / `f64` | VR 3-point orientations: left, right, head quaternions (wxyz × 3) | +| `catch_up` | scalar | `bool` / `u8` / `i32` | If `true` (default), resets playback when a large frame gap is detected | +| `heading_increment` | scalar | `f32` / `f64` | Incremental heading adjustment applied per message | + +## Configuration + +| Flag | Default | Description | +|------|---------|-------------| +| `--zmq-host` | `localhost` | ZMQ publisher host | +| `--zmq-port` | `5556` | ZMQ publisher port | +| `--zmq-topic` | `pose` | ZMQ topic prefix | +| `--zmq-conflate` | off | Keep only the latest message (drop stale frames) | diff --git a/third-party/GR00T-WholeBodyControl/docs/source/user_guide/configuration.md b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..05dffe77f52e109828a924d278f62a230eb267f8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/configuration.md @@ -0,0 +1,254 @@ +# Configuration Guide + +SONIC uses [Hydra](https://hydra.cc/) for hierarchical configuration. This guide +explains the config structure and the most important parameters to tune. + +## Config Hierarchy + +When you run a training command like: + +```bash +python gear_sonic/train_agent_trl.py +exp=manager/universal_token/all_modes/sonic_release +``` + +Hydra composes the final config from a chain of YAML files: + +``` +gear_sonic/config/ +├── base.yaml # Global defaults (seed, num_envs, paths) +├── base/ +│ ├── hydra.yaml # Hydra output directory settings +│ └── structure.yaml # Resolved experiment directory structure +├── algo/ +│ └── ppo_im_phc.yaml # PPO hyperparameters +├── manager_env/ +│ ├── base_env.yaml # Environment defaults (sim_dt, decimation, episode length) +│ ├── actions/tracking/base.yaml +│ ├── commands/tracking/base.yaml +│ │ └── terms/motion.yaml # Motion library, body names, future frames +│ ├── rewards/tracking/ +│ │ └── base_5point_local_feet_acc.yaml # Reward composition +│ │ └── terms/*.yaml # Individual reward terms with weights +│ ├── terminations/tracking/ +│ │ └── base_adaptive_strict_ori_foot_xyz.yaml # Termination composition +│ │ └── terms/*.yaml # Individual termination conditions +│ ├── events/tracking/ +│ │ └── level0_4.yaml # Domain randomization events +│ └── observations/ +│ ├── tokenizer/ # Encoder input observations +│ ├── policy/ # Policy (actor) observations +│ └── critic/ # Critic observations +├── actor_critic/ +│ └── universal_token/ # Network architecture (encoders, decoders, quantizer) +├── aux_losses/ +│ └── universal_token/ # Auxiliary loss terms +├── trainer/ +│ └── trl_ppo_aux.yaml # Trainer config (PPO with aux losses) +├── callbacks/ # Training callbacks (save, eval, W&B, resample) +└── exp/manager/universal_token/all_modes/ + ├── sonic_release.yaml # Original release experiment config + └── sonic_v1_1.yaml # SONIC v1.1 experiment config +``` + +The experiment config (`sonic_release.yaml`) sits at the top and overrides +specific values from the base configs. You can further override any value +from the command line with `++key=value`. + +## Overriding Config Values + +Hydra uses `++` prefix to force-override values (even nested ones): + +```bash +# Override a top-level value +python gear_sonic/train_agent_trl.py +exp=... num_envs=16 + +# Override a nested value (use dots for nesting) +python gear_sonic/train_agent_trl.py +exp=... \ + ++manager_env.commands.motion.motion_lib_cfg.motion_file=/path/to/data + +# Override a reward weight +python gear_sonic/train_agent_trl.py +exp=... \ + ++manager_env.rewards.tracking_anchor_pos.weight=1.0 +``` + +## Top Parameters to Tune + +### Training scale + +| Parameter | Default | Location | Description | +|-----------|---------|----------|-------------| +| `num_envs` | 4096 | `base.yaml` | Number of parallel environments. Reduce for debugging (`16`), increase for throughput. | +| `headless` | True | `base.yaml` | Set `False` to open the Isaac Lab viewer for visual debugging. | +| `seed` | 0 | `base.yaml` | Random seed for reproducibility. | + +### PPO hyperparameters + +| Parameter | Default | Location | Description | +|-----------|---------|----------|-------------| +| `algo.config.actor_learning_rate` | 2e-5 | `ppo_im_phc.yaml` | Actor learning rate. Lower for finetuning, higher for training from scratch. | +| `algo.config.critic_learning_rate` | 1e-3 | `ppo_im_phc.yaml` | Critic learning rate. Usually 10-100x the actor LR. | +| `algo.config.num_learning_epochs` | 5 | `ppo_im_phc.yaml` | PPO epochs per batch of experience. | +| `algo.config.num_mini_batches` | 4 | `ppo_im_phc.yaml` | Mini-batches per PPO epoch. | +| `algo.config.num_steps_per_env` | 24 | `sonic_release.yaml` | Rollout length (steps per env before PPO update). | +| `algo.config.gamma` | 0.99 | `ppo_im_phc.yaml` | Discount factor. | +| `algo.config.lam` | 0.95 | `ppo_im_phc.yaml` | GAE lambda. | +| `algo.config.clip_param` | 0.2 | `ppo_im_phc.yaml` | PPO clip parameter. | +| `algo.config.entropy_coef` | 0.01 | `ppo_im_phc.yaml` | Entropy bonus coefficient. | +| `algo.config.desired_kl` | 0.01 | `ppo_im_phc.yaml` | Target KL for adaptive learning rate schedule. | +| `algo.config.num_learning_iterations` | 100000 | `ppo_im_phc.yaml` | Total training iterations. | + +### Simulation + +| Parameter | Default | Location | Description | +|-----------|---------|----------|-------------| +| `manager_env.config.sim_dt` | 0.005 | `base_env.yaml` | Physics timestep (200 Hz). Smaller = more stable but slower. | +| `manager_env.config.decimation` | 4 | `base_env.yaml` | Policy runs every `decimation` sim steps (50 Hz policy at 200 Hz sim). | +| `manager_env.config.episode_length_s` | 10.0 | `base_env.yaml` | Episode length in seconds before timeout reset. | +| `manager_env.config.terrain_type` | trimesh | `sonic_release.yaml` | `plane` for flat ground, `trimesh` for rough terrain. | +| `manager_env.config.robot.type` | g1_model_12_dex | `sonic_release.yaml` | Robot type (must match `robot_mapping` in code). | + +### Motion data + +| Parameter | Default | Location | Description | +|-----------|---------|----------|-------------| +| `manager_env.commands.motion.motion_lib_cfg.motion_file` | — | `sonic_release.yaml` | Path to retargeted robot motion PKLs. | +| `manager_env.commands.motion.motion_lib_cfg.smpl_motion_file` | — | `sonic_release.yaml` | Path to SMPL motion PKLs (or `dummy`). | +| `manager_env.commands.motion.motion_lib_cfg.soma_motion_file` | — | `sonic_bones_seed.yaml` | Path to SOMA motion PKLs (4-encoder config only). | +| `manager_env.commands.motion.motion_lib_cfg.smpl_y_up` | true | `sonic_release.yaml` | Set `true` if SMPL data uses y-up coordinates. | +| `manager_env.commands.motion.motion_lib_cfg.target_fps` | 50 | `motion.yaml` | Target FPS for motion resampling. | +| `manager_env.commands.motion.motion_lib_cfg.asset.assetFileName` | g1_29dof_rev_1_0.xml | `motion.yaml` | MJCF file for motion library FK. Change for different robots. | + +### Motion command + +| Parameter | Default | Location | Description | +|-----------|---------|----------|-------------| +| `manager_env.commands.motion.num_future_frames` | 10 | `sonic_release.yaml` | Number of future reference frames provided to the policy. | +| `manager_env.commands.motion.dt_future_ref_frames` | 0.1 | `sonic_release.yaml` | Time spacing between future frames (seconds). | +| `manager_env.commands.motion.cat_upper_body_poses` | true | `sonic_release.yaml` | Augment lower-body motions with upper-body from different clips. | +| `manager_env.commands.motion.cat_upper_body_poses_prob` | 0.5 | `sonic_release.yaml` | Probability of upper-body augmentation per episode. | +| `manager_env.commands.motion.freeze_frame_aug` | true | `sonic_release.yaml` | Augment with frozen (static) reference frames. | + +### Observation history + +| Parameter | Default | Location | Description | +|-----------|---------|----------|-------------| +| `actor_prop_history_length` | 10 | `sonic_release.yaml` | Number of past proprioception frames stacked for actor. | +| `actor_actions_history_length` | 10 | `sonic_release.yaml` | Number of past actions stacked for actor. | +| `critic_prop_history_length` | 10 | `sonic_release.yaml` | Same, for critic. | +| `critic_actions_history_length` | 10 | `sonic_release.yaml` | Same, for critic. | + +### Reward weights + +All reward terms have a `weight` parameter. Positive weights encourage the behavior, +negative weights penalize it. The default weights for `base_5point_local_feet_acc`: + +| Reward term | Weight | Description | +|-------------|--------|-------------| +| `tracking_anchor_pos` | 0.5 | Root position tracking | +| `tracking_anchor_ori` | 0.5 | Root orientation tracking | +| `tracking_relative_body_pos` | 1.0 | Body position tracking (anchor-relative) | +| `tracking_relative_body_ori` | 1.0 | Body orientation tracking (anchor-relative) | +| `tracking_body_linvel` | 1.0 | Body linear velocity tracking | +| `tracking_body_angvel` | 1.0 | Body angular velocity tracking | +| `tracking_vr_5point_local` | 2.0 | 5-point (wrists + head + feet) local tracking | +| `action_rate_l2` | -0.1 | Smooth actions (penalize jerk) | +| `joint_limit` | -10.0 | Stay within joint limits | +| `undesired_contacts` | -0.1 | Penalize non-foot ground contacts | +| `anti_shake_ang_vel` | -0.005 | Penalize wrist/head jitter | +| `feet_acc` | -2.5e-6 | Penalize foot acceleration (smooth stepping) | + +Each reward term also has a `std` parameter controlling the Gaussian kernel +sharpness. Smaller `std` = stricter tracking (reward drops faster with error). + +Override example: +```bash +++manager_env.rewards.tracking_anchor_pos.weight=2.0 +++manager_env.rewards.tracking_anchor_pos.params.std=0.1 +``` + +### Termination thresholds + +Terminations end episodes early when tracking error exceeds a threshold. The +adaptive variants use a curriculum that tightens thresholds over training: + +| Termination | Threshold | Description | +|-------------|-----------|-------------| +| `anchor_pos` | 0.15 m | Root position deviation | +| `anchor_ori_full` | 0.2 rad | Root orientation deviation | +| `ee_body_pos` | 0.15 m | End-effector position deviation | +| `foot_pos_xyz` | 0.2 m | Foot position deviation | +| `motion_time_out` | — | Episode ends when motion clip finishes | + +Looser thresholds (larger values) make training easier initially. The adaptive +terminations automatically tighten as the policy improves. + +### Adaptive motion sampling + +The motion library supports adaptive sampling — motions the policy fails on are +sampled more frequently: + +| Parameter | Default | Description | +|-----------|---------|-------------| +| `adaptive_sampling.enable` | true | Enable adaptive sampling. | +| `adaptive_sampling.bin_size` | 50 | Window size for failure rate tracking. | +| `adaptive_sampling.adp_samp_failure_rate_max_over_mean` | 200 | Max/mean failure rate ratio cap. Prevents one hard motion from dominating. | + +### Saving and logging + +| Parameter | Default | Location | Description | +|-----------|---------|----------|-------------| +| `algo.config.save_interval` | 500 | `ppo_im_phc.yaml` | Save checkpoint every N iterations. | +| `algo.config.eval_frequency` | 500 | `ppo_im_phc.yaml` | Run evaluation every N iterations. | +| `use_wandb` | false | `base.yaml` | Enable Weights & Biases logging. | +| `base_dir` | logs_rl | `base.yaml` | Root directory for training outputs. | + +## Experiment Configs + +| Config | Encoders | Use case | +|--------|----------|----------| +| `sonic_release` | G1, teleop, SMPL | Default — matches the released checkpoint | +| `sonic_v1_1` | G1, teleop, SMPL | SONIC v1.1 with heading-normalized targets and wrist-pose augmentation | +| `sonic_bones_seed` | G1, teleop, SMPL, SOMA | Extended training with SOMA skeleton encoder | +| `sonic_h2` | G1, teleop, SMPL | H2 robot (31 DOF) | + +## Common Recipes + +### Debug a training run visually + +```bash +python gear_sonic/train_agent_trl.py +exp=... \ + num_envs=4 headless=False \ + algo.config.num_learning_iterations=10 +``` + +### Finetune with lower learning rate + +```bash +python gear_sonic/train_agent_trl.py +exp=... \ + +checkpoint=sonic_release/last.pt \ + ++algo.config.actor_learning_rate=5e-6 \ + ++algo.config.desired_kl=0.005 +``` + +### Train on flat ground only + +```bash +python gear_sonic/train_agent_trl.py +exp=... \ + ++manager_env.config.terrain_type=plane +``` + +### Relax termination thresholds for hard motions + +```bash +python gear_sonic/train_agent_trl.py +exp=... \ + ++manager_env.terminations.anchor_pos.params.threshold=0.3 \ + ++manager_env.terminations.ee_body_pos.params.threshold=0.3 +``` + +### Increase tracking precision + +```bash +python gear_sonic/train_agent_trl.py +exp=... \ + ++manager_env.rewards.tracking_relative_body_pos.params.std=0.1 \ + ++manager_env.rewards.tracking_anchor_pos.params.std=0.1 +``` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/user_guide/new_embodiments.md b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/new_embodiments.md new file mode 100644 index 0000000000000000000000000000000000000000..99b3c9bb75c34ede1ef6c08031a482712b6cf066 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/new_embodiments.md @@ -0,0 +1,471 @@ +# Training on New Embodiments + +SONIC's training pipeline is designed around the Unitree G1 (29 DOF) but can be +extended to other humanoid robots. This guide walks through every file you need +to touch, using the Unitree H2 (31 DOF) as a concrete example. + +## What You Need + +To train SONIC on a new robot, you need: + +1. **Robot model files** — URDF or USD (for Isaac Lab) and MJCF/XML (for the motion library) +2. **Retargeted motion data** — Human motions retargeted to your robot's skeleton (PKL format) +3. **Robot configuration** — Joint/body definitions, actuator parameters, action scales +4. **Experiment config** — Hydra YAML connecting everything together + +## Files You Need to Add or Modify + +Here is every file that needs attention, in the order you should work through them: + +| File | Action | Purpose | +|------|--------|---------| +| `gear_sonic/data/assets/robot_description/urdf//` | **Add** | URDF + mesh files for Isaac Lab simulation | +| `gear_sonic/data/assets/robot_description/mjcf/.xml` | **Add** | MuJoCo XML for motion library forward kinematics | +| `gear_sonic/envs/manager_env/robots/.py` | **Add** | Robot config: joints, actuators, mappings, action scales | +| `gear_sonic/envs/manager_env/robots/__init__.py` | **Modify** | Import your new robot module | +| `gear_sonic/envs/manager_env/modular_tracking_env_cfg.py` | **Modify** | Add robot to `robot_mapping` dict (~line 998) | +| `gear_sonic/trl/utils/order_converter.py` | **Modify** | Add converter class for joint/body reordering | +| `gear_sonic/config/exp/manager/universal_token/all_modes/sonic_.yaml` | **Add** | Experiment config | +| Config YAMLs (terminations, rewards, commands) | **Check** | Body names must exist on your robot | + +## Step 1: Robot Model Files + +Place your URDF and meshes under `gear_sonic/data/assets/robot_description/`: + +``` +gear_sonic/data/assets/robot_description/ +├── urdf/h2/ +│ ├── h2.urdf +│ └── meshes/ # STL/OBJ mesh files +└── mjcf/ + └── h2.xml # MuJoCo XML +``` + +The **URDF** is loaded by Isaac Lab for physics simulation. The **MJCF** is used +by the motion library to compute forward kinematics on reference motion data. +Both must represent the same robot with consistent joint names and tree structure. + +Make sure your URDF mesh paths are correct (relative paths like `meshes/pelvis.stl` +work best). If your URDF uses `package://` paths, update them to match the +directory layout. + +## Step 2: Robot Configuration + +Create `gear_sonic/envs/manager_env/robots/.py`. This is the most +important file — it defines how your robot integrates with the training pipeline. + +### Joint and body ordering + +Isaac Lab and MuJoCo traverse the kinematic tree in different orders. You must +define bidirectional index mappings. Get these by loading your URDF in Isaac Lab +and your MJCF in MuJoCo, printing the joint/body lists, and computing the +reorder indices. + +```python +# All bodies in IsaacLab traversal order (including root "pelvis") +H2_ISAACLAB_JOINTS = [ + "pelvis", + "left_hip_pitch_link", + "right_hip_pitch_link", + # ... all 32 bodies for H2 +] + +# Index arrays: position i in the output = position mapping[i] in the input +H2_ISAACLAB_TO_MUJOCO_DOF = [...] # len = num_dof (31 for H2) +H2_MUJOCO_TO_ISAACLAB_DOF = [...] +H2_ISAACLAB_TO_MUJOCO_BODY = [...] # len = num_bodies (32 for H2) +H2_MUJOCO_TO_ISAACLAB_BODY = [...] + +H2_ISAACLAB_TO_MUJOCO_MAPPING = { + "isaaclab_joints": H2_ISAACLAB_JOINTS, + "isaaclab_to_mujoco_dof": H2_ISAACLAB_TO_MUJOCO_DOF, + "mujoco_to_isaaclab_dof": H2_MUJOCO_TO_ISAACLAB_DOF, + "isaaclab_to_mujoco_body": H2_ISAACLAB_TO_MUJOCO_BODY, + "mujoco_to_isaaclab_body": H2_MUJOCO_TO_ISAACLAB_BODY, +} +``` + +**Getting the mappings right is critical.** If they are wrong, the policy will +receive scrambled observations and produce scrambled actions. Verify by loading a +known pose in both simulators and checking that joint values match after reordering. + +### Actuator parameters (KP/KD tuning) + +The actuator stiffness (KP) and damping (KD) are critical for sim-to-real +transfer and training stability. SONIC uses implicit PD actuators in Isaac Lab. + +```python +# Derive from motor specs — these need tuning for your robot +NATURAL_FREQ = 10 * 2.0 * 3.1415926535 # 10Hz natural frequency +DAMPING_RATIO = 2.0 # Overdamped for stability + +# Per-motor stiffness: KP = armature * omega^2 +STIFFNESS_5020 = ARMATURE_5020 * NATURAL_FREQ**2 +# Per-motor damping: KD = 2 * zeta * armature * omega +DAMPING_5020 = 2.0 * DAMPING_RATIO * ARMATURE_5020 * NATURAL_FREQ +``` + +**Tuning guidance:** + +- Start with the real motor's **armature** (rotor inertia) from the datasheet. +- The **natural frequency** controls responsiveness. 10 Hz is a good starting point + for humanoids. Increase for stiffer/faster tracking, decrease for compliance. +- The **damping ratio** should be >= 1.0 (critically damped or overdamped) to avoid + oscillation. 2.0 works well for SONIC. +- **Different joint groups need different gains.** Hip/knee motors are much stronger + than wrist motors. Group joints by motor type (see G1/H2 configs for examples). +- If training is unstable (robot explodes or falls immediately), your KP/KD values + are likely wrong. Try reducing KP or increasing KD. +- The **effort limits** (max torque) per joint should match the real motor specs. + +### Articulation config + +```python +H2_CFG = ArticulationCfg( + spawn=sim_utils.UrdfFileCfg( + asset_path="gear_sonic/data/assets/robot_description/urdf/h2/h2.urdf", + fix_base=False, + replace_cylinders_with_capsules=True, + activate_contact_sensors=True, + ... + ), + init_state=ArticulationCfg.InitialStateCfg( + pos=(0.0, 0.0, 1.04), # Standing height — must match your robot + joint_pos={ + ".*_knee_joint": -0.363, # Slight knee bend for stability + # ... default standing pose for all joints + }, + ), + actuators={ + "legs": ImplicitActuatorCfg( + joint_names_expr=[".*_hip_.*", ".*_knee_.*"], + effort_limit={...}, # Max torque per joint (Nm) + stiffness={...}, # KP values + damping={...}, # KD values + armature={...}, # Rotor inertia + ), + # ... one group per motor type (arms, waist, feet, etc.) + }, +) +``` + +**Important init_state notes:** + +- `pos` z-value is the spawn height. Set this so the robot starts standing with + feet slightly above ground. Too low = feet clip through ground on first frame. +- `joint_pos` should be a stable standing pose. Get this from your robot's real + default calibration pose or a MuJoCo keyframe. + +### Action scale + +Action scale maps normalized policy outputs to joint position targets. Compute +from effort limit and stiffness: + +```python +H2_ACTION_SCALE = {} +for joint_name in joint_names: + H2_ACTION_SCALE[joint_name] = effort_limit[joint_name] / stiffness[joint_name] +``` + +Larger action scale = larger joint movements per policy output. If the robot +moves too aggressively, reduce the action scale. + +### Register in __init__.py + +Add your module to `gear_sonic/envs/manager_env/robots/__init__.py` so it's +importable. + +### Register in modular_tracking_env_cfg.py + +Add your robot to the `robot_mapping` dict (around line 998): + +```python +from gear_sonic.envs.manager_env.robots import g1, h2 # Add your import + +robot_mapping = { + "g1_model_12_dex": {...}, + "h2": { + "robot_cfg": h2.H2_CFG, + "action_scale": h2.H2_ACTION_SCALE, + "isaaclab_to_mujoco_mapping": h2.H2_ISAACLAB_TO_MUJOCO_MAPPING, + }, +} +``` + +The string key (e.g., `"h2"`) is what you'll use as `robot.type` in the +experiment config. + +## Step 3: Order Converter + +In `gear_sonic/trl/utils/order_converter.py`, add a converter class. This is used +by the evaluation and export pipeline: + +```python +class H2Converter(IsaacLabMuJoCoConverter): + def __init__(self): + from gear_sonic.envs.manager_env.robots.h2 import ( + H2_ISAACLAB_JOINTS, H2_ISAACLAB_TO_MUJOCO_BODY, + H2_ISAACLAB_TO_MUJOCO_DOF, H2_MUJOCO_TO_ISAACLAB_BODY, + H2_MUJOCO_TO_ISAACLAB_DOF, + ) + self.JOINT_NAMES = H2_ISAACLAB_JOINTS + self.DOF_MAPPINGS = { + ("isaaclab", "mujoco"): H2_ISAACLAB_TO_MUJOCO_DOF, + ("mujoco", "isaaclab"): H2_MUJOCO_TO_ISAACLAB_DOF, + } + self.BODY_MAPPINGS = { + ("isaaclab", "mujoco"): H2_ISAACLAB_TO_MUJOCO_BODY, + ("mujoco", "isaaclab"): H2_MUJOCO_TO_ISAACLAB_BODY, + } + + # Bodies used for VR tracking and foot contact — update for your robot + VR_3POINTS_BODY_NAMES = ["torso_link", "left_wrist_pitch_link", "right_wrist_pitch_link"] + FOOT_BODY_NAMES = ["left_ankle_roll_link", "right_ankle_roll_link"] +``` + +Use lazy imports (inside `__init__`) to avoid circular dependencies. + +## Step 4: Body Name Compatibility + +This is a common source of errors. The training configs reference specific body +names that must exist on your robot. Check **all** of these: + +### Command config (`config/manager_env/commands/terms/motion.yaml`) + +```yaml +anchor_body: "pelvis" # Root body +vr_3point_body: ["left_wrist_yaw_link", "right_wrist_yaw_link", "torso_link"] +reward_point_body: ["pelvis", "left_wrist_yaw_link", "right_wrist_yaw_link", + "left_ankle_roll_link", "right_ankle_roll_link"] +body_names: [ # 14 tracked bodies + "pelvis", "left_hip_roll_link", "left_knee_link", "left_ankle_roll_link", + "right_hip_roll_link", "right_knee_link", "right_ankle_roll_link", + "torso_link", "left_shoulder_roll_link", "left_elbow_link", + "left_wrist_yaw_link", "right_shoulder_roll_link", "right_elbow_link", + "right_wrist_yaw_link", +] +``` + +### Termination configs (`config/manager_env/terminations/terms/`) + +- `ee_body_pos_adaptive.yaml`: references `left_ankle_roll_link`, `right_ankle_roll_link`, + `left_wrist_yaw_link`, `right_wrist_yaw_link` +- `foot_pos_xyz.yaml`: references `left_ankle_roll_link`, `right_ankle_roll_link` + +### Reward configs (`config/manager_env/rewards/terms/`) + +- `undesired_contacts.yaml`: regex pattern excluding specific bodies from contact + penalty — references ankle and wrist link names +- `anti_shake_ang_vel.yaml`: references `left_wrist_yaw_link`, `right_wrist_yaw_link`, + `head_link` + +### What to do if names differ + +If your robot uses different names for equivalent bodies (e.g., H2 has +`head_pitch_link` instead of G1's `head_link`), you have two options: + +1. **Override in experiment config** (recommended): Add overrides in your + `sonic_.yaml` for the specific fields that differ. + +2. **Create robot-specific config variants**: Copy the affected term YAML files + and create robot-specific versions (e.g., `anti_shake_ang_vel_h2.yaml`). + +For H2, most G1 body names happen to exist (both are Unitree humanoids), but +`head_link` does not — H2 has `head_yaw_link` instead. Override in the +experiment config: + +```yaml +manager_env: + rewards: + anti_shake_ang_vel: + params: + body_names: ["left_wrist_yaw_link", "right_wrist_yaw_link", "head_yaw_link"] +``` + +**Tip:** Run training with `num_envs=1` first. If a body name doesn't exist, Isaac +Lab will raise a clear error telling you which name failed. Fix it and retry. + +## Step 5: Motion Data + +SONIC expects retargeted motion data as PKL files (joblib format). Each file +contains a dict keyed by motion name: + +```python +{ + "motion_name": { + "root_trans_offset": np.ndarray, # (T, 3) — root translation + "pose_aa": np.ndarray, # (T, num_bodies, 3) — axis-angle per body + "dof": np.ndarray, # (T, num_dof) — joint positions in MuJoCo order + "root_rot": np.ndarray, # (T, 4) — root quaternion (wxyz) + "smpl_joints": np.ndarray, # (T, 24, 3) — SMPL joint positions (optional) + "fps": int, # Frame rate (typically 30) + } +} +``` + +**Important data format notes:** + +- `num_bodies` and `num_dof` must match your robot (e.g., 32 bodies / 31 DOF for H2). +- `dof` values must be in **MuJoCo joint order**, not IsaacLab order. +- `pose_aa` must be in **MuJoCo body order**. +- Mirrored variants (filename ending in `_M.pkl`) double your effective dataset + size and improve symmetry. +- The `smpl_joints` field is used by the SMPL encoder. Set it to zeros if you + don't have SMPL data. + +The motion library loads PKL files **recursively** from a directory: + +``` +data/h2_motions/ +├── session_01/ +│ ├── walk_forward_001.pkl +│ └── walk_forward_001_M.pkl +└── session_02/ + └── ... +``` + +### Source motion data + +The recommended source is [Bones-SEED](https://huggingface.co/datasets/bones-studio/seed) +— a large-scale human motion dataset (142K+ motions, ~288 hours) that provides: + +- **Raw BVH files** — full-body human motion capture +- **G1 retargeted CSVs** — already retargeted to the Unitree G1 (29 DOF) + +For a new robot, you need to **retarget** the raw human motions to your robot's +skeleton. This is the most labor-intensive step. + +### Retargeting options + +1. **[SOMA Retargeter](https://github.com/NVIDIA/soma-retargeter)** (recommended) — + NVIDIA's BVH-to-humanoid motion retargeting library built with Newton and + NVIDIA Warp. Supports any humanoid robot via JSON configuration. Includes a + viewer for inspecting source and retargeted motions side by side. This is + the same tool used to produce the Bones-SEED G1 retargeted data. + +2. **[GMR](https://github.com/YanjieZe/GMR)** (General Motion Retargeting) — + retargets human motions to arbitrary humanoid robots in real time on CPU. + Supports any URDF. A lighter-weight alternative. + +3. **This repo's data processing** (`gear_sonic/data_process/`) — converts + retargeted CSVs/BVHs into the PKL format SONIC expects. Use this as the + final step after retargeting: + + ```bash + # Convert retargeted CSVs to motion library PKLs + python gear_sonic/data_process/convert_soma_csv_to_motion_lib.py \ + --input /path/to/retargeted_csvs/ \ + --output data/my_robot_motions/robot \ + --fps 30 --fps_source 120 --individual --num_workers 16 + + # Filter out motions that are physically impossible for your robot + python gear_sonic/data_process/filter_and_copy_bones_data.py \ + --source data/my_robot_motions/robot \ + --dest data/my_robot_motions/robot_filtered + ``` + +### SMPL data (optional but recommended) + +The SMPL encoder gives the policy an additional human-skeleton input signal. +You need SMPL retargeted data matching the same motion keys as your robot data. + +- For Bones-SEED motions, pre-computed SMPL data is available on + [Hugging Face](https://huggingface.co/nvidia/GEAR-SONIC): + `python download_from_hf.py --training` +- If you use custom motions, extract SMPL joints from the BVH files: + + ```bash + python gear_sonic/data_process/extract_soma_joints_from_bvh.py \ + --input /path/to/bvh_files/ \ + --output data/my_robot_motions/soma \ + --fps 30 --num_workers 16 + ``` + +- If you don't have SMPL data, set `smpl_motion_file: dummy` in the config. + The training pipeline will generate minimal placeholder SMPL data from the + robot motions. This works but produces weaker SMPL encoder performance. + +## Step 6: Experiment Config + +Create `gear_sonic/config/exp/manager/universal_token/all_modes/sonic_.yaml`. +Start by copying `sonic_release.yaml` and modify: + +```yaml +# @package _global_ +defaults: + - /algo: ppo_im_phc + - /manager_env: base_env + # ... same defaults as sonic_release.yaml + +project_name: TRL_H2_Track # Change project name + +manager_env: + config: + robot: + type: h2 # Must match robot_mapping key + commands: + motion: + motion_lib_cfg: + motion_file: null # Provide on command line + asset: + assetFileName: "h2.xml" # Your MJCF filename +``` + +**Fields to review and potentially override:** + +- `robot.type` — must match the key in `robot_mapping` +- `motion_lib_cfg.asset.assetFileName` — your MJCF file +- `reward_point_body` / `reward_point_body_offset` — key bodies for reward computation +- `vr_3point_body` / `vr_3point_body_offset` — if doing VR teleoperation +- `upper_body_augment_prefixes` — remove if your motion data uses different naming +- Body names in reward/termination overrides — see Step 4 + +## Step 7: Train + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_h2 \ + num_envs=16 headless=False \ + ++manager_env.commands.motion.motion_lib_cfg.motion_file= +``` + +Start with `num_envs=16 headless=False` to visually verify the robot loads and +motions play correctly. Then scale up to `num_envs=4096 headless=True` for +full training. + +## Example: H2 (included) + +The codebase includes full H2 support as a reference: + +| Component | File | +|-----------|------| +| Robot config | `gear_sonic/envs/manager_env/robots/h2.py` | +| URDF + meshes | `gear_sonic/data/assets/robot_description/urdf/h2/` | +| MJCF | `gear_sonic/data/assets/robot_description/mjcf/h2.xml` | +| Experiment config | `gear_sonic/config/exp/manager/universal_token/all_modes/sonic_h2.yaml` | +| Order converter | `gear_sonic/trl/utils/order_converter.py` (`H2Converter`) | +| Robot mapping | `gear_sonic/envs/manager_env/modular_tracking_env_cfg.py` | + +## Checklist + +When adding a new robot, verify each of these: + +- [ ] URDF + meshes in `gear_sonic/data/assets/robot_description/urdf//` +- [ ] MJCF in `gear_sonic/data/assets/robot_description/mjcf/.xml` +- [ ] Robot config in `gear_sonic/envs/manager_env/robots/.py`: + - [ ] Joint/body name lists + - [ ] IsaacLab ↔ MuJoCo index mappings (verified correct!) + - [ ] `ArticulationCfg` with tuned KP/KD/effort for each motor group + - [ ] Correct init_state (standing height + default joint angles) + - [ ] Action scale dict +- [ ] Robot imported in `robots/__init__.py` +- [ ] Robot added to `robot_mapping` in `modular_tracking_env_cfg.py` +- [ ] Order converter class in `order_converter.py` +- [ ] Experiment config YAML with correct `robot.type` and `assetFileName` +- [ ] All body names in config YAMLs exist on your robot (check with `num_envs=1`) +- [ ] Human motion source data (e.g., [Bones-SEED](https://huggingface.co/datasets/bones-studio/seed) BVH/CSV files) +- [ ] Motions retargeted to your robot's skeleton (e.g., via [SOMA Retargeter](https://github.com/NVIDIA/soma-retargeter)) +- [ ] Retargeted data converted to PKL format (MuJoCo joint/body order) +- [ ] Motions filtered for physical feasibility (`filter_and_copy_bones_data.py`) +- [ ] Mirrored motion variants (`_M.pkl`) for symmetric training +- [ ] SMPL data matching the same motion keys (or `smpl_motion_file: dummy`) diff --git a/third-party/GR00T-WholeBodyControl/docs/source/user_guide/teleoperation.md b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/teleoperation.md new file mode 100644 index 0000000000000000000000000000000000000000..18ca824e3b472076f0856e9b6eb39b6cdadb15d6 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/teleoperation.md @@ -0,0 +1,245 @@ +# Whole-body Teleoperation Guide + +This guide covers best practices during whole-body teleoperation. + +```{admonition} Prerequisites +:class: note +Complete the [Quick Start](../getting_started/quickstart), [PICO Setup](../getting_started/vr_teleop_setup), and [Teleop Setup](../tutorials/vr_wholebody_teleop) +``` + +## Overview + +Whole-body teleoperation is very very hard to get right and there are a lot of moving parts. This guide will walk you through the details that are required during whole-body teleoperation. During whole-body teleoperation, the GEAR-SONIC policy will try to copy your motion **as much as possible**, including your foot movements! Thus, it can be quite **demanding and dangerous** if proper precautions are not taken. + +```{admonition} Safety Warning +:class: danger +The robot will track your full-body movements in real-time. Always maintain a clear 3-meter safety zone around the robot, keep a safety operator at the keyboard ready to press **`O`** for emergency stop and always be prepared to emergecy stop on the PICO controller on your own. Practice extensively in simulation before attempting on real hardware! +``` + +## Sample Teleoperation Session + +A typical whole-body teleoperation session follows this workflow: + + +```{video} ../_static/teleop/teleop_session_overview.mp4 +:width: 100% +``` +*Video: Full startup sequence — calibrating the PICO headset, engaging the policy, and the robot starting to balance independently on the gantry.* + +**Terminal 1 — MuJoCo Simulator** (or skip for real robot): +```bash +source .venv_teleop/bin/activate +python gear_sonic/scripts/run_sim_loop.py +``` + +**Terminal 2 — C++ Deployment**: +```bash +cd gear_sonic_deploy +# For simulation: +bash deploy.sh --input-type zmq_manager sim +# For real robot: +# bash deploy.sh --input-type zmq_manager real +``` + +**Terminal 3 — PICO Teleop Streamer**: +```bash +source .venv_teleop/bin/activate +python gear_sonic/scripts/pico_manager_thread_server.py --manager +``` + +**Operator Actions**: +1. **Put on PICO headset and controllers** — Ensure foot trackers are securely attached. +2. **Stand in calibration pose** — Upright, feet together, arms in down. Recalibrate often!!! +3. **Make robot stand loose but standing** - Put the G1 somehow slack on gantry (the policy will start and start balancing on its own). +4. **Press A+B+X+Y** on controllers — Initializes the policy and calibrates (enters Planner mode) +5. **Press A+X** — Switches to Pose mode (whole-body teleoperation active) +6. **Teleoperate** — Your movements are now mirrored by the robot +7. **Press A+B+X+Y** when done — Emergency stop and exit. Policy will stop!!! + +## Clothing Requirements + +**Critical:** You **must** wear **tight-fitting pants or leggings** during teleoperation. + +**Why this matters:** +- The PICO foot trackers use visual tracking and need a clear view of your leg/foot movements +- Loose, baggy, or flowing clothing (sweatpants, wide-leg pants, long skirts) will occlude the trackers +- Even brief tracking loss causes the robot to receive incorrect foot positions, leading to stumbling or dangerous motions + +**Recommended:** +- ✅ Athletic leggings or compression tights +- ✅ Fitted jeans or slim-fit pants + +**Not recommended:** +- ❌ Baggy sweatpants or cargo pants +- ❌ Wide-leg or flared pants +- ❌ Long dresses or skirts +- ❌ Any loose or flowing fabric around the legs + +**Upper body:** Normal fitted clothing is fine. Avoid very baggy sleeves that might interfere with controller tracking. + +**❗️❗️❗️Recalibrate Often** The tracking quality of PICO may get worse overtime. When seeing performance drop, always recalibrate! Also, when the PICO controller loses track, it may get stuck in a sitting/weird pose. Always make sure your tracked motion is correct (by viewing the PICO avatar) before starting the teleoperation policy! + +## WiFi Delays + +```{video} ../_static/teleop/teleop_natural_movement.mp4 +:width: 100% +``` +*Video: Demonstrating how natural vs. hesitant walking affects robot stability — stumbling caused by WiFi delays or unnatural movement.* + +**Network latency should be kept as low as possible.** We provide tools to detect delays. Network delays can significantly affect the GEAR-SONIC policy's performance, as the flow of movement for the robot will be interrupted mid-movement (say mid-stride during walking) and the robot can stumble or lose balance. + +**Best practices:** +- **Use Private WiFi Routers** Public and school wifis can easily have large delays. +- **Minimize WiFi hops** — Ideally the PICO and deployment machine are on the same local network +- **Check latency** — Monitor ZMQ message delays in the terminal output + + +**Expected latency:** +- **Good:** < 10ms (wired or strong local WiFi) +- **Acceptable:** 10-30ms (may notice slight lag) +- **Poor:** > 30ms (robot will struggle to track smooth motions, increased stumbling risk) + +**Checking network performance:** +The deployment terminal will show warnings if message delays exceed thresholds. Watch for messages like: +``` +WARNING: High ZMQ latency detected: 45ms +``` + +If you see persistent high latency warnings, improve your network setup before continuing. + +## Movement Patterns + +```{video} ../_static/teleop/teleop_walking.mp4 +:width: 100% +``` +*Video: Walking demo — forward, backward, running, and sideways movement with natural gait.* + +**Try to be as natural as possible.** The GEAR-SONIC policy is trained on natural human motion, so moving naturally gives the best results. Hesitating when moving actually lead to more stumbling! + +**Good movement practices:** + +1. **Walk naturally** — Use your normal gait with natural arm swing. Don't exaggerate or try to "help" the robot. + +2. **Transfer weight smoothly** — When stepping, shift your weight from one foot to the other just as you normally would. Be confident! + +3. **Use moderate speeds** — The robot can track fast motions, but start with walking at a comfortable pace. You can speed up/starts running once you're comfortable. + +**Common mistakes:** + +- ❌ **Overtly slow movements** — Don't slow down too much! +- ❌ **Trying to match the robot's movement** — Don't try to match the robot movement, as the robot will then try to match your movement and starts stumbling. Be natural! + +**Advanced movements:** + +```{video} ../_static/teleop/teleop_advanced.mp4 +:width: 100% +``` +*Video: Advanced movements — kneeling, dynamic leg motions, and challenging poses.* + +Once comfortable with basic walking: +- **Turning** — Turn naturally by rotating your torso and stepping in the new direction +- **Reaching** — Extend your arms smoothly to grab objects +- **Squatting** — Bend your knees and lower your body naturally +- **Sidestepping** — Step sideways with natural weight transfer + +## Calibration Best Practices + +The initial calibration is **critical** to successful teleoperation. + +**The calibration pose:** +1. **Stand upright** — Look straight ahead (not down at controllers) +2. **Feet together** — Foot parallel with no gaps. +3. **Upper arms down** — Hang straight down beside your torso + + +**Tips:** +- Hold the pose steady for 1-2 seconds after pressing A+B+X+Y +- If the robot seems offset throughout the session, recalibrate (stop with A+B+X+Y, then restart) + + +## Mode Switching Safety + +When switching between modes, **always match the robot's current pose first**. + +**Dangerous scenario:** +1. Robot is in Planner mode standing upright +2. You're crouching or reaching in a different pose +3. You press **A+X** to switch to Pose mode +4. **Robot violently tries to match your crouched pose** ⚠️ + +**Safe procedure:** +1. Before pressing **A+X**, look at the robot (or visualization) +2. Move your body to approximately match the robot's current pose +3. Then press **A+X** — transition will be smooth + +**Pause feature (Menu button):** + +```{video} ../_static/teleop/teleop_pause.mp4 +:width: 100% +``` +*Video: Using the Menu button to pause and resume pose streaming during teleoperation.* + +- Holding **Menu** pauses pose streaming +- **Before releasing Menu**, move your body back to match the robot's current pose +- Releasing Menu while in a very different pose causes sudden dangerous motions + +## Troubleshooting + +### Robot is not tracking my movements + +**Possible causes:** +- Foot trackers are not securely attached or have low battery +- Loose clothing is occluding the trackers +- Poor lighting conditions +- XRoboToolKit not running on PICO or configured incorrectly + +**Solutions:** +1. Check foot tracker placement and battery level +2. Verify you're wearing tight-fitting pants +3. Improve lighting (avoid very bright or very dark areas) +4. Restart XRoboToolKit on the PICO headset +5. Recalibrate + +### Robot makes sudden aggressive motions + +**Possible causes:** +- Switched modes while poses didn't match +- Tracking glitch or foot tracker occlusion +- Network packet loss causing delayed frames + +**Solutions:** +1. Recalibrate carefully before resuming +2. Always match robot's pose before switching modes +3. Check network latency and improve WiFi/wired connection + +### Tracking is jittery or stumbles + +**Possible causes:** +- Wireless delays +- IMU drift +- Joint encoder drift + + +**Solutions:** +1. Reduce WiFi interference (move away from other wireless devices) +2. Reclibrate robot + + +## Emergency Procedures + +### Emergency stop methods + +**Keyboard (deployment terminal):** +- Press **`O`** for immediate stop + +**PICO controllers:** +- Press **A + B + X + Y** simultaneously + +Both methods immediately halt the policy and exit control mode. + + +## Next Steps + +- **Understand input interfaces** — See tutorials for [Keyboard](../tutorials/keyboard.md), [Gamepad](../tutorials/gamepad.md), [ZMQ](../tutorials/zmq.md), [Manager](../tutorials/manager.md) +- **Learn about deployment** — See [Deployment Code & Program Flow](../references/deployment_code) +- **General troubleshooting** — See [Troubleshooting Guide](troubleshooting) \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/docs/source/user_guide/training.md b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/training.md new file mode 100644 index 0000000000000000000000000000000000000000..200803d409251d5e9865bf28e6d2388716bae32b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/training.md @@ -0,0 +1,339 @@ +# Training Guide + +This guide covers data processing, training, evaluation, and ONNX export for +SONIC whole-body controllers. + +## Overview + +SONIC uses a universal-token architecture to control a humanoid robot (Unitree +G1, 29 DOF) by imitating human motion capture data. Multiple parallel encoders +accept different motion input formats: + +- **G1**: Robot joint trajectories +- **Teleop**: VR 3-point tracking targets (head + two wrists) +- **SMPL**: Parametric human body model joint positions +- **SOMA**: BVH-derived skeleton joint positions (optional 4th encoder) + +All encoders project into a shared latent token space via FSQ (Finite Scalar +Quantization), and a single decoder produces joint actions regardless of input +modality. Training uses PPO with auxiliary losses in Isaac Lab simulation. + +| Config | Encoders | Use case | +|--------|----------|----------| +| `sonic_release` | G1, teleop, SMPL | **Default** — matches the released checkpoint | +| `sonic_v1_1` | G1, teleop, SMPL | SONIC v1.1 with heading-normalized targets and wrist-pose augmentation | +| `sonic_bones_seed` | G1, teleop, SMPL, SOMA | Extended training with SOMA skeleton encoder | + +Use `sonic_release` for finetuning and evaluation. The `sonic_bones_seed` +config adds a fourth SOMA encoder (see [Training with SOMA](#training-with-soma-encoder)). +Use `sonic_v1_1` with `sonic_v1_1/last.pt`. + +## Data Processing + +### Step 1: Convert motion data + +SONIC requires motion data in **motion_lib PKL format**. Convert Bones-SEED +CSV files: + +```bash +python gear_sonic/data_process/convert_soma_csv_to_motion_lib.py \ + --input /path/to/bones_seed/g1/csv/ \ + --output data/motion_lib_bones_seed/robot \ + --fps 30 \ + --fps_source 120 \ + --individual \ + --num_workers 16 +``` + +### Step 2: Filter motions + +Remove motions the G1 robot cannot perform (furniture interaction, vehicles, +acrobatics, elevated surfaces): + +```bash +python gear_sonic/data_process/filter_and_copy_bones_data.py \ + --source data/motion_lib_bones_seed/robot \ + --dest data/motion_lib_bones_seed/robot_filtered \ + --workers 16 +``` + +This removes ~8.7% of motions (~130K of 142K remain). Use `--dry-run` to +preview, or `--add-keywords` to add custom filters. + +### Data layout + +Place processed data at the repo root: + +``` +/ +├── data/motion_lib_bones_seed/ +│ ├── robot/ # Full motion library (142K PKLs) +│ └── robot_filtered/ # Filtered subset (~130K PKLs) +└── gear_sonic/ +``` + +## Training + +### Basic command + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=4096 headless=True \ + ++manager_env.commands.motion.motion_lib_cfg.motion_file= \ + ++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file= +``` + +For example, using the sample data from Hugging Face: + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=16 headless=True \ + ++manager_env.commands.motion.motion_lib_cfg.motion_file=sample_data/robot_filtered \ + ++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=sample_data/smpl_filtered +``` + +Or using the full dataset: + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=4096 headless=True \ + ++manager_env.commands.motion.motion_lib_cfg.motion_file=data/motion_lib_bones_seed/robot_filtered \ + ++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=data/smpl_filtered +``` + +### Finetuning from the released checkpoint + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + +checkpoint=sonic_release/last.pt \ + num_envs=4096 headless=True \ + ++manager_env.commands.motion.motion_lib_cfg.motion_file= \ + ++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file= +``` + +### Multi-GPU and multi-node training + +We recommend training with **64+ GPUs** for reasonable convergence times. +Single-node (8 GPU) training works but is significantly slower. + +```bash +# Single node (8 GPUs) +accelerate launch --num_processes=8 gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=4096 headless=True + +# Multi-node — use accelerate config for distributed setup +accelerate launch \ + --multi_gpu \ + --num_machines=8 \ + --num_processes=64 \ + --machine_rank=$MACHINE_RANK \ + --main_process_ip=$MASTER_ADDR \ + --main_process_port=$MASTER_PORT \ + gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=4096 headless=True +``` + +For multi-node setup, see the +[Accelerate distributed training guide](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) +and +[multi-node launcher docs](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch). + +### W&B logging + +Enabled by default. Key overrides: + +```bash +WANDB_MODE=offline python gear_sonic/train_agent_trl.py ... # offline mode + wandb.wandb_project=my_project wandb.wandb_entity=my_team # custom project + use_wandb=false # disable entirely +``` + +### Local debug run + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + num_envs=16 headless=False \ + ++algo.config.num_learning_iterations=100 +``` + +## Monitoring + +### Key metrics + +| Metric | Good range | Description | +|--------|-----------|-------------| +| `rewards/total` | 3.0+ | Total reward | +| `rewards/anchor_pos_err` | < 0.15 | Root position tracking error (m) | +| `rewards/body_pos_err` | < 0.10 | Body position tracking error (m) | +| `throughput/fps` | ~4000+ | Training throughput | + +### Checkpoints + +Saved every 2000 steps to: + +``` +logs_rl/TRL_G1_Track/-/ +├── model_step_002000.pt +├── config.yaml +└── ... +``` + +## Evaluation + +### Visualize reference motions + +Replay motions to verify data quality before training: + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + ++replay=True num_envs=4 headless=False +``` + +### Evaluate a checkpoint + +Two eval modes: **metrics** (success rate, MPJPE) and **render** (video output). + +For the released checkpoint, you must override motion paths since its +`config.yaml` has internal training paths. For your own checkpoints trained +with `sonic_release`, omit the motion overrides. + +```bash +# --- Metrics --- +python gear_sonic/eval_agent_trl.py \ + +checkpoint= \ + +headless=True \ + ++eval_callbacks=im_eval \ + ++run_eval_loop=False \ + ++num_envs=128 \ + "+manager_env/terminations=tracking/eval" \ + "++manager_env.commands.motion.motion_lib_cfg.max_unique_motions=512" +``` + +```bash +# --- Render videos --- +python gear_sonic/eval_agent_trl.py \ + +checkpoint= \ + +headless=True \ + ++eval_callbacks=im_eval \ + ++run_eval_loop=False \ + ++num_envs=8 \ + ++manager_env.config.render_results=True \ + "++manager_env.config.save_rendering_dir=/tmp/renders" \ + ++manager_env.config.env_spacing=10.0 \ + "~manager_env/recorders=empty" "+manager_env/recorders=render" +``` + +For the **released checkpoint only**, append this override to either command +(its embedded config has internal training paths): + +```bash + "++manager_env.commands.motion.motion_lib_cfg.motion_file=data/motion_lib_bones_seed/robot_filtered" +``` + +Videos are saved as `000000.mp4`, `000001.mp4`, etc. in `save_rendering_dir`. + +### Expected eval metrics + +*Training rewards* (W&B `Episode_Reward/`): + +| Metric | Converged | Description | +|--------|-----------|-------------| +| `tracking_vr_5point_local` | > 0.80 | 5-point tracking quality | +| `tracking_relative_body_pos` | > 0.44 | Upper-body position tracking | +| `tracking_anchor_pos` | > 0.14 | Root position tracking | +| `time_out` | > 0.90 | Episode completion rate | + +*Eval metrics* (from `eval_agent_trl.py`): + +| Metric | Converged | Description | +|--------|-----------|-------------| +| `success_rate` | > 0.97 | Motions tracked without early termination | +| `mpjpe_l` | < 30 mm | Local per-joint position error | +| `mpjpe_g` | < 200 mm | Global per-joint position error | + +A well-converged policy reaches >0.98 success rate and <29 mm mpjpe_l after +100K iterations. + +## ONNX Export + +Export a trained checkpoint to ONNX for C++ deployment: + +```bash +python gear_sonic/eval_agent_trl.py \ + +checkpoint= \ + +headless=True ++num_envs=1 \ + +export_onnx_only=true +``` + +For the released checkpoint, append the motion path overrides shown in the +eval section above. + +Output (in `exported/` next to the checkpoint): + +| File | Description | +|------|-------------| +| `*_smpl.onnx` | SMPL encoder + decoder (pose estimation input) | +| `*_g1.onnx` | G1 encoder + decoder (robot joint input) | +| `*_teleop.onnx` | Teleop encoder + decoder (VR tracking input) | +| `*_encoder.onnx` | All encoders combined | +| `*_decoder.onnx` | Decoder only | + +Use the encoder+decoder pair matching your input modality. See +[deployment code reference](../references/deployment_code.md) for C++ details. + +## Training with SOMA encoder + +The `sonic_bones_seed` config adds a fourth SOMA encoder for BVH-derived +skeleton joint positions. + +### SOMA data preparation + +```bash +# Extract SOMA joints from BVH +python gear_sonic/data_process/extract_soma_joints_from_bvh.py \ + --input /path/to/bones_seed/bvh/ \ + --output data/motion_lib_bones_seed/soma \ + --fps 30 --num_workers 16 --skip_existing + +# Filter to match robot data +python gear_sonic/data_process/filter_and_copy_bones_data.py \ + --source data/motion_lib_bones_seed/soma \ + --dest data/motion_lib_bones_seed/soma_filtered \ + --workers 16 +``` + +### Training + +Use multi-node training (64+ GPUs recommended): + +```bash +accelerate launch \ + --multi_gpu --num_machines=8 --num_processes=64 \ + --machine_rank=$MACHINE_RANK \ + --main_process_ip=$MASTER_ADDR \ + --main_process_port=$MASTER_PORT \ + gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_bones_seed \ + num_envs=4096 headless=True \ + ++manager_env.commands.motion.motion_lib_cfg.motion_file=data/motion_lib_bones_seed/robot_filtered \ + ++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file=data/smpl_filtered \ + ++manager_env.commands.motion.motion_lib_cfg.soma_motion_file=data/motion_lib_bones_seed/soma_filtered +``` + +Data layout for 4-encoder training: + +``` +data/ +├── motion_lib_bones_seed/ +│ ├── robot_filtered/ # ~130K PKLs (G1 retargeted) +│ └── soma_filtered/ # ~130K PKLs (SOMA skeleton) +└── smpl_filtered/ # ~131K PKLs (SMPL human) +``` diff --git a/third-party/GR00T-WholeBodyControl/docs/source/user_guide/training_data.md b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/training_data.md new file mode 100644 index 0000000000000000000000000000000000000000..b51eb3c464a1bbbf5060bcd4aed1f187ded7c345 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/training_data.md @@ -0,0 +1,69 @@ +# Training Data + +## BONES-SEED + +[BONES-SEED](https://huggingface.co/datasets/bones-studio/seed) (Skeletal Everyday Embodiment Dataset) is an open dataset of **142,220 annotated human motion animations** for humanoid robotics, created by [Bones Studio](https://bones.studio/datasets). It provides motion capture data in SOMA and Unitree G1 formats with natural language descriptions, temporal segmentation labels, and detailed skeletal metadata. + +| | | +|---|---| +| **Total motions** | 142,220 (71,132 original + 71,088 mirrored) | +| **Total duration** | ~288 hours (@ 120 fps) | +| **Performers** | 522 actors (253 F / 269 M) | +| **Age range** | 17–71 years | +| **Height range** | 145–199 cm | +| **Weight range** | 38–145 kg | +| **Output formats** | SOMA Uniform · SOMA Proportional · Unitree G1 MuJoCo-compatible | +| **Annotations** | Up to 6 NL descriptions per motion + temporal segmentation + skeletal metadata | + +### Relevance to SONIC + +BONES-SEED a large subset of SONIC training data: + +- **Unitree G1 joint trajectories** — retargeted for MuJoCo, directly usable for motion tracking training +- **Broad motion coverage** — locomotion, manipulation, dance, sports, communication, and everyday activities across 8 categories and 20 sub-categories +- **Rich language annotations** — up to 6 natural language descriptions per motion, enabling language-conditioned policy learning +- **Temporal segmentation** — per-motion phase labels with timestamps for structured skill decomposition +- **Performer diversity** — 522 actors spanning a wide range of body types, ages, and movement styles + +### Motion Categories + +| Package | Motions | Description | +|---------------|---------|-------------------------------------------------------------------------| +| Locomotion | 74,488 | Walking, jogging, jumping, climbing, crawling, turning, and transitions | +| Communication | 21,493 | Gestures, pointing, looking, and communicative body language | +| Interactions | 14,643 | Object manipulation, pick-and-place, carrying, and tool use | +| Dances | 11,006 | Full-body dance performances across multiple styles | +| Gaming | 8,700 | Game-inspired actions and dynamic movements | +| Everyday | 5,816 | Household tasks, consuming, sitting, reading, and daily activities | +| Sport | 3,993 | Athletic movements and sports-specific actions | +| Other | 2,081 | Stunts, martial arts, and edge-case motions | + +### Data Formats + +Every motion is available in three formats: + +- **SOMA Proportional (BVH)** — per-actor skeleton preserving original body proportions +- **SOMA Uniform (BVH)** — standardized skeleton shared across all motions for batch processing +- **Unitree G1 (CSV)** — joint-angle trajectories retargeted to the Unitree G1 humanoid + +### Download + +```bash +# Using the Hugging Face CLI +pip install huggingface_hub +huggingface-cli download bones-studio/seed --repo-type dataset --local-dir ./bones-seed +``` + +```python +# Using Python +from huggingface_hub import snapshot_download + +snapshot_download( + repo_id="bones-studio/seed", + repo_type="dataset", + local_dir="./bones-seed" +) +``` + +After downloading, extract the motion archives: + diff --git a/third-party/GR00T-WholeBodyControl/docs/source/user_guide/troubleshooting.md b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..a039b64c37fb265b573d74108df5b04838745df1 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/docs/source/user_guide/troubleshooting.md @@ -0,0 +1,296 @@ +# Troubleshooting + +Common issues and solutions. If your problem isn't listed here, check the +[GitHub issues](https://github.com/NVlabs/GR00T-WholeBodyControl/issues) page. + +--- + +## 1. `ModuleNotFoundError: No module named 'isaaclab'` + +**Symptom:** Training or eval script exits immediately with an import error. + +**Cause:** Isaac Lab is not installed, or you're running in the wrong Python +environment. Isaac Lab is not a pip dependency — it must be installed separately. + +**Fix:** + +1. Install Isaac Lab following the + [official guide](https://isaac-sim.github.io/IsaacLab/main/source/setup/installation/index.html). +2. Make sure you activate the correct conda/venv environment before running: + ```bash + conda activate env_isaaclab # or whatever you named it + python -c "import isaaclab; print(isaaclab.__version__)" + ``` + +--- + +## 2. Mesh files are tiny text files (Git LFS not installed) + +**Symptom:** Simulation crashes or renders an invisible/broken robot. Mesh files +(`.stl`, `.STL`) are ~130 bytes and contain text like `version https://git-lfs.github.com/spec/v1`. + +**Cause:** The repo was cloned without Git LFS. Large files (meshes, ONNX models) +are stored via Git LFS and need to be fetched separately. + +**Fix:** + +```bash +sudo apt install git-lfs +git lfs install +git lfs pull +``` + +Verify: `ls -la gear_sonic/data/assets/robot_description/urdf/g1/main.urdf` should +be ~60KB+, not ~130 bytes. + +--- + +## 3. `RuntimeError: size mismatch` when loading a checkpoint + +**Symptom:** Training or eval crashes with errors like: +``` +size mismatch for actor_module.decoders.g1_dyn.module.0.weight: + copying a param with shape torch.Size([2048, 994]) from checkpoint, + the shape in current model is torch.Size([4096, 994]) +``` + +**Cause:** The experiment config defines a different network architecture than +what the checkpoint was trained with. Common when the config overrides +`hidden_dims` to a different size. + +**Fix:** Make sure the experiment config matches the checkpoint's architecture. +Check the `config.yaml` saved alongside the checkpoint for the correct +`hidden_dims`, encoder/decoder settings, etc. The released `sonic_release` +checkpoint uses: + +```yaml +decoders: + g1_dyn: + params: + module_config_dict: + layer_config: + hidden_dims: [2048, 2048, 1024, 1024, 512, 512] +``` + +--- + +## 4. `trl` / `transformers` version conflict during pip install + +**Symptom:** `pip install -e "gear_sonic/[training]"` fails with a dependency +resolution error about incompatible `transformers` versions. + +**Cause:** `trl==0.28.0` requires `transformers>=4.56.2`. If you have an older +`transformers` pinned or installed, pip cannot resolve. + +**Fix:** + +```bash +pip install -e "gear_sonic/[training]" --upgrade +``` + +Or install in a fresh environment. If you need a specific `transformers` version +for another project, use a separate venv for SONIC training. + +--- + +## 5. TensorRT build fails (`TensorRT_ROOT` not set) + +**Symptom:** CMake error during C++ deployment build: +``` +Could not find a package configuration file provided by "TensorRT" +``` + +**Cause:** The `TensorRT_ROOT` environment variable is not set, or TensorRT is +not installed. + +**Fix:** + +1. Download the correct TensorRT version (TAR package, not DEB): + + | Platform | TensorRT Version | + |---|---| + | x86_64 (Desktop) | **10.13** (required) | + | Jetson / G1 onboard Orin | **10.7** (required; JetPack 6) | + +2. Extract and set the environment variable: + ```bash + export TensorRT_ROOT=$HOME/TensorRT + echo 'export TensorRT_ROOT=$HOME/TensorRT' >> ~/.bashrc + ``` + +--- + +## 6. Motion file path errors (`FileNotFoundError` or empty motion library) + +**Symptom:** Training crashes with `FileNotFoundError` on a motion path, or starts +but logs `0 motions loaded`. + +**Cause:** The experiment config has placeholder paths (e.g., +`data/motion_lib_bones_seed/robot_filtered`) that don't exist on your machine. +Motion data paths must be provided on the command line. + +**Fix:** Always pass motion data paths explicitly: + +```bash +python gear_sonic/train_agent_trl.py \ + +exp=manager/universal_token/all_modes/sonic_release \ + ++manager_env.commands.motion.motion_lib_cfg.motion_file= \ + ++manager_env.commands.motion.motion_lib_cfg.smpl_motion_file= +``` + +For quick testing, download the sample data from HuggingFace: + +```bash +hf download nvidia/GEAR-SONIC --include "sample_data/*" --local-dir . +``` + +--- + +## 7. Body name errors (`RuntimeError: body 'xxx' not found`) + +**Symptom:** Isaac Lab crashes with an error about a body/joint name not found +in the robot's articulation. + +**Cause:** A config YAML references a body name that doesn't exist on your robot. +This commonly happens when using G1 configs with a different robot (e.g., H2). + +**Fix:** Check which body name failed and find where it's referenced: + +```bash +grep -rn "the_failing_body_name" gear_sonic/config/ +``` + +Override the body name in your experiment config, or check the +[Training on New Embodiments](new_embodiments.md) guide for the full list of +config files that reference body names. + +--- + +## 8. Robot explodes or falls immediately on first frame + +**Symptom:** The robot ragdolls, flies away, or collapses instantly when +simulation starts. + +**Cause:** Usually one of: + +- **Init state height is wrong** — the robot spawns inside the ground or too high. + Check `init_state.pos` in your robot config (the z-value is spawn height). +- **KP/KD values are wrong** — if stiffness (KP) is too low, joints have no + holding torque. If too high, the simulation becomes unstable. See + [Training on New Embodiments](new_embodiments.md) for tuning guidance. +- **Action scale is too large** — the policy outputs move joints too aggressively. + Reduce `action_scale` values. +- **Default joint angles are wrong** — the robot starts in an impossible pose. + Check `init_state.joint_pos` matches a stable standing configuration. + +**Debug:** Run with `num_envs=1 headless=False` and watch the first few frames. + +--- + +## 9. Robot behaves weirdly during deployment (wrong TensorRT version) + +**Symptom:** The robot stands but moves erratically, drifts, or produces +unnatural motions during C++ deployment — even though the same checkpoint works +correctly in Isaac Lab or MuJoCo simulation. + +**Cause:** You are using a different TensorRT version than required. TensorRT +version mismatches produce **silently wrong inference results** — the model runs +without errors but outputs incorrect actions. + +**Fix:** You **must** use the exact TensorRT versions: + +| Platform | Required Version | +|---|---| +| x86_64 (Desktop) | **TensorRT 10.13** | +| Jetson / G1 onboard Orin | **TensorRT 10.7** (JetPack 6) | + +Verify your version: + +```bash +echo $TensorRT_ROOT +ls $TensorRT_ROOT/lib/libnvinfer.so* +``` + +If the version is wrong, download the correct one from +[NVIDIA Developer](https://developer.nvidia.com/tensorrt/download/10x) and +rebuild the C++ deployment binary. + +--- + +## 10. `ChannelFactory create domain error` in MuJoCo sim + +**Symptom:** `run_sim_loop.py` crashes with: +``` +[ChannelFactory] create domain error. msg: Occurred upon initialisation +of a cyclonedds.domain.Domain +``` + +**Cause:** CycloneDDS domain initialization conflict. The SimulatorFactory +reinitializes a channel that was already created. + +**Fix:** This is a known issue ([#77](https://github.com/NVlabs/GR00T-WholeBodyControl/issues/77)). +Workaround: comment out the duplicate channel init in the simulator factory, +or ensure no other DDS process is using the same domain on your machine. + +--- + +## 11. SMPL tracking is unstable or drifts + +**Symptom:** The robot follows G1 motion tracking well but drifts or becomes +unstable when using SMPL encoder inputs. + +**Cause:** SMPL data may have mismatched coordinate conventions (y-up vs z-up), +incorrect joint ordering, or the SMPL-to-robot retargeting quality is poor. + +**Fix:** + +- Verify `smpl_y_up: true` is set in your config if your SMPL data uses y-up + coordinates. +- Check that the SMPL PKL files have the correct shape: `smpl_joints` should be + `(T, 24, 3)`. +- Try training with `smpl_motion_file: dummy` first to confirm the robot + encoder works before adding SMPL. + +--- + +## 12. MuJoCo viewer renders incorrectly in Docker + +**Symptom:** MuJoCo window is black, garbled, or shows rendering artifacts when +running inside Docker on a machine with an Intel display controller. + +**Cause:** GPU passthrough or display driver conflict between the Intel iGPU and +NVIDIA dGPU inside Docker. + +**Fix:** Force NVIDIA GPU rendering: + +```bash +export __NV_PRIME_RENDER_OFFLOAD=1 +export __GLX_VENDOR_LIBRARY_NAME=nvidia +``` + +Or run with `--gpus all -e DISPLAY=$DISPLAY` in your Docker run command. See +[#25](https://github.com/NVlabs/GR00T-WholeBodyControl/issues/25) for details. + +--- + +## 13. `deploy.sh` fails to bind ZMQ port 5557 on Orin + +**Symptom:** `deploy.sh` exits with a ZMQ bind error on port 5557. + +**Cause:** A Unitree system service (`iphone_server.service`) is already listening on port 5557. + +**Fix:** + +```bash +sudo systemctl stop iphone_server.service +``` + +Then re-run the deployment. The service restarts on the next boot; to keep it stopped across reboots use `sudo systemctl disable iphone_server.service`. + +--- + +## Still stuck? + +- Search [existing issues](https://github.com/NVlabs/GR00T-WholeBodyControl/issues) +- Open a [new issue](https://github.com/NVlabs/GR00T-WholeBodyControl/issues/new) + with your error message, Python version, and OS diff --git a/third-party/GR00T-WholeBodyControl/download_from_hf.py b/third-party/GR00T-WholeBodyControl/download_from_hf.py new file mode 100644 index 0000000000000000000000000000000000000000..118a9093ff4da1d18a6cf3077516a8f04aaa7eb8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/download_from_hf.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +""" +Download GEAR-SONIC model checkpoints and training data from Hugging Face Hub. + +Repository: https://huggingface.co/nvidia/GEAR-SONIC + +Usage: + python download_from_hf.py # ONNX models for deployment + python download_from_hf.py --low-latency # Low-latency ONNX models + python download_from_hf.py --sonic-v1-1 # SONIC v1.1 ONNX models + python download_from_hf.py --training # PyTorch checkpoint + SMPL data + python download_from_hf.py --sample # Sample data only (quick start) + python download_from_hf.py --output-dir /path # custom output directory + python download_from_hf.py --no-planner # skip planner model +""" + +import argparse +import os +import shutil +import subprocess +import sys +from pathlib import Path + +REPO_ID = "nvidia/GEAR-SONIC" + +# (filename in HF repo, local destination relative to output_dir) +POLICY_FILES = [ + ("model_encoder.onnx", "policy/release/model_encoder.onnx"), + ("model_decoder.onnx", "policy/release/model_decoder.onnx"), + ("observation_config.yaml", "policy/release/observation_config.yaml"), +] + +LOW_LATENCY_POLICY_FILES = [ + ("low_latency/model_encoder.onnx", "policy/low_latency/model_encoder.onnx"), + ("low_latency/model_decoder.onnx", "policy/low_latency/model_decoder.onnx"), + ("low_latency/observation_config.yaml", "policy/low_latency/observation_config.yaml"), +] + +SONIC_V1_1_POLICY_FILES = [ + ("sonic_v1_1/model_encoder.onnx", "policy/sonic_v1_1/model_encoder.onnx"), + ("sonic_v1_1/model_decoder.onnx", "policy/sonic_v1_1/model_decoder.onnx"), + ( + "sonic_v1_1/observation_config.yaml", + "policy/sonic_v1_1/observation_config.yaml", + ), +] + +PLANNER_FILE = ("planner_sonic.onnx", "planner/target_vel/V2/planner_sonic.onnx") + +TRAINING_FILES = [ + ("sonic_release/last.pt", "sonic_release/last.pt"), + ("sonic_release/config.yaml", "sonic_release/config.yaml"), +] + +LOW_LATENCY_TRAINING_FILES = [ + ("low_latency/last.pt", "low_latency/last.pt"), + ("low_latency/config.yaml", "low_latency/config.yaml"), + ("low_latency/model_config.yaml", "low_latency/model_config.yaml"), +] + +SONIC_V1_1_TRAINING_FILES = [ + ("sonic_v1_1/last.pt", "sonic_v1_1/last.pt"), + ("sonic_v1_1/config.yaml", "sonic_v1_1/config.yaml"), + ("sonic_v1_1/model_config.yaml", "sonic_v1_1/model_config.yaml"), +] + +SMPL_TAR_PARTS_PREFIX = "bones_seed_smpl/bones_seed_smpl.tar.part_" +SMPL_TAR_PARTS = [f"{SMPL_TAR_PARTS_PREFIX}a{c}" for c in "abcdefg"] + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Download GEAR-SONIC checkpoints from Hugging Face Hub" + ) + parser.add_argument( + "--output-dir", + type=Path, + default=None, + help=( + "Directory to save files. " + "Defaults to gear_sonic_deploy/ (deploy) or repo root (training)." + ), + ) + parser.add_argument( + "--no-planner", + action="store_true", + help="Skip downloading the kinematic planner ONNX model", + ) + parser.add_argument( + "--training", + action="store_true", + help="Download training checkpoint + SMPL motion data (~30 GB)", + ) + variant_group = parser.add_mutually_exclusive_group() + variant_group.add_argument( + "--low-latency", + action="store_true", + help=( + "Download the low-latency SONIC variant. For deployment, files are " + "placed under gear_sonic_deploy/policy/low_latency/. With --training, " + "downloads low_latency/last.pt and its configs." + ), + ) + variant_group.add_argument( + "--sonic-v1-1", + dest="sonic_v1_1", + action="store_true", + help=( + "Download the SONIC v1.1 teleoperation variant with " + "robot-heading-normalized targets and " + "wrist-pose augmentation. For deployment, files are placed under " + "gear_sonic_deploy/policy/sonic_v1_1/. With --training, downloads " + "sonic_v1_1/last.pt and its configs." + ), + ) + parser.add_argument( + "--sample", + action="store_true", + help="Download sample motion data only (1 walking sequence, ~4 MB)", + ) + parser.add_argument( + "--no-smpl", + action="store_true", + help="With --training, skip SMPL data download (checkpoint only)", + ) + parser.add_argument( + "--token", + default=None, + help="Hugging Face token (or set HF_TOKEN env var / run `hf auth login`)", + ) + return parser.parse_args() + + +def _ensure_huggingface_hub(): + try: + from huggingface_hub import hf_hub_download, snapshot_download + return hf_hub_download, snapshot_download + except ImportError: + print("huggingface_hub is not installed. Install it with:") + print(" pip install huggingface_hub") + sys.exit(1) + + +def download_file(hf_hub_download, repo_id, hf_filename, local_dest, token=None): + """Download hf_filename from the Hub and place it at local_dest.""" + print(f" Downloading {hf_filename} ...", flush=True) + cached = hf_hub_download( + repo_id=repo_id, + filename=hf_filename, + token=token, + ) + local_dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(cached, local_dest) + print(f" -> {local_dest}") + + +def download_and_extract_smpl(hf_hub_download, repo_id, output_dir, token=None): + """Download split tar parts and extract SMPL data.""" + parts_dir = output_dir / "bones_seed_smpl" + parts_dir.mkdir(parents=True, exist_ok=True) + + print(f" Downloading {len(SMPL_TAR_PARTS)} parts (~30 GB total) ...", flush=True) + part_paths = [] + for hf_filename in SMPL_TAR_PARTS: + local_name = Path(hf_filename).name + local_dest = parts_dir / local_name + if local_dest.exists(): + print(f" (cached) {local_name}") + part_paths.append(local_dest) + continue + cached = hf_hub_download(repo_id=repo_id, filename=hf_filename, token=token) + shutil.copy2(cached, local_dest) + part_paths.append(local_dest) + print(f" Downloaded {local_name}") + + # Reassemble and extract + data_dir = output_dir / "data" + data_dir.mkdir(parents=True, exist_ok=True) + print(f" Extracting to {data_dir}/smpl_filtered/ ...", flush=True) + + # cat parts | tar xf - -C data/ + cat_cmd = f"cat {parts_dir}/bones_seed_smpl.tar.part_*" + tar_cmd = f"tar xf - -C {data_dir}" + result = subprocess.run( + f"{cat_cmd} | {tar_cmd}", + shell=True, + capture_output=True, + text=True, + ) + if result.returncode != 0: + print(f" ERROR: Extraction failed: {result.stderr}") + sys.exit(1) + + # Count extracted files + smpl_dir = data_dir / "smpl_filtered" + if smpl_dir.exists(): + n_files = sum(1 for f in smpl_dir.iterdir() if f.suffix == ".pkl") + print(f" -> {smpl_dir} ({n_files} PKL files)") + else: + print(f" WARNING: Expected {smpl_dir} but directory not found") + + # Clean up tar parts + print(" Cleaning up tar parts ...") + shutil.rmtree(parts_dir) + + +def download_sample_data(snapshot_download, repo_id, output_dir, token=None): + """Download sample motion data (1 walking sequence).""" + print(" Downloading sample data ...", flush=True) + snapshot_download( + repo_id=repo_id, + allow_patterns="sample_data/*", + local_dir=str(output_dir), + token=token, + ) + sample_dir = output_dir / "sample_data" + if sample_dir.exists(): + n_files = sum(1 for _ in sample_dir.rglob("*.pkl")) + print(f" -> {sample_dir} ({n_files} PKL files)") + + +def main(): + args = parse_args() + if args.sample and (args.low_latency or args.sonic_v1_1): + print( + "ERROR: model variant flags cannot be combined with --sample", + file=sys.stderr, + ) + sys.exit(2) + + hf_hub_download, snapshot_download = _ensure_huggingface_hub() + if args.low_latency: + variant = "low_latency" + elif args.sonic_v1_1: + variant = "sonic_v1_1" + else: + variant = "default" + + repo_root = Path(__file__).resolve().parent + + if args.training or args.sample: + output_dir = args.output_dir if args.output_dir else repo_root + else: + output_dir = args.output_dir if args.output_dir else repo_root / "gear_sonic_deploy" + + print("=" * 60) + print(" GEAR-SONIC — Hugging Face Model Downloader") + print(f" Repository : {REPO_ID}") + print(f" Output dir : {output_dir}") + if args.training: + print(f" Mode : {variant.replace('_', '-')} training checkpoint") + elif args.sample: + print(f" Mode : sample data (quick start)") + else: + print(f" Mode : {variant.replace('_', '-')} deployment (ONNX models)") + print("=" * 60) + + if args.sample: + print("\n[Sample Data]") + download_sample_data(snapshot_download, REPO_ID, output_dir, token=args.token) + + elif args.training: + print("\n[Checkpoint]") + training_files = { + "default": TRAINING_FILES, + "low_latency": LOW_LATENCY_TRAINING_FILES, + "sonic_v1_1": SONIC_V1_1_TRAINING_FILES, + }[variant] + for hf_filename, local_rel in training_files: + download_file( + hf_hub_download, REPO_ID, hf_filename, + output_dir / local_rel, token=args.token, + ) + + if args.low_latency: + print("\n[SMPL Motion Data] Skipped (not part of low-latency checkpoint download)") + elif not args.no_smpl: + print("\n[SMPL Motion Data]") + download_and_extract_smpl(hf_hub_download, REPO_ID, output_dir, token=args.token) + else: + print("\n[SMPL Motion Data] Skipped (--no-smpl)") + + else: + print("\n[Policy]") + policy_files = { + "default": POLICY_FILES, + "low_latency": LOW_LATENCY_POLICY_FILES, + "sonic_v1_1": SONIC_V1_1_POLICY_FILES, + }[variant] + for hf_filename, local_rel in policy_files: + download_file( + hf_hub_download, REPO_ID, hf_filename, + output_dir / local_rel, token=args.token, + ) + + if not args.no_planner: + print("\n[Planner]") + hf_filename, local_rel = PLANNER_FILE + download_file( + hf_hub_download, REPO_ID, hf_filename, + output_dir / local_rel, token=args.token, + ) + + print("\n" + "=" * 60) + print(" Done! Files saved under:") + print(f" {output_dir}") + print("=" * 60) + + +if __name__ == "__main__": + main() diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/CLAUDE.md b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..6cedca535b76a4397ad65a7a96411cb4063ad047 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/CLAUDE.md @@ -0,0 +1,108 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +This project provides Python bindings for the XRoboToolkit PC Service SDK, enabling Python applications to extract XR state data including controller poses, hand tracking, and body motion capture from XR devices (primarily PICO headsets). + +## Architecture + +The project consists of: + +- **Core C++ Bindings** (`bindings/py_bindings.cpp`): Pybind11-based C++ module that wraps the PXREARobotSDK +- **SDK Integration**: Uses the XRoboToolkit-PC-Service SDK (cloned from external repository) +- **Build System**: CMake-based build with Python setuptools integration +- **Multi-platform Support**: Linux (x86_64/aarch64) and Windows + +Key components: +- `PXREARobotSDK.h`: Main SDK header providing device connectivity and data parsing +- `py_bindings.cpp`: Thread-safe C++ wrapper with mutex-protected global state variables +- JSON parsing using nlohmann/json for device state data +- Callback-based data updates from the SDK + +## Build Commands + +### Ubuntu/Linux Setup and Build +```bash +# Full setup (downloads dependencies and builds) +bash setup_ubuntu.sh + +# Manual build after setup +python setup.py install + +# Clean build artifacts +python setup.py clean +``` + +### Windows Setup and Build +```batch +# Full setup (downloads dependencies and builds) +setup_windows.bat + +# Manual build after setup +python setup.py install +``` + +### Development Commands +```bash +# Uninstall existing package +pip uninstall -y xrobotoolkit_sdk + +# Install pybind11 dependency +conda install -c conda-forge pybind11 +# or +pip install pybind11 + +# Build and install +python setup.py install +``` + +## Data Flow and Threading + +The SDK uses a callback-based architecture: +- `OnPXREAClientCallback`: Main callback function that receives JSON data from connected devices +- Global state variables (poses, button states, etc.) are updated in real-time +- Thread-safe access via mutex locks for each data category +- Data parsing from comma-separated pose strings to arrays + +## Key Functions and Data Types + +### Controller Data +- Poses: `std::array` (x,y,z,qx,qy,qz,qw) +- Buttons: Menu, Primary, Secondary, Axis Click +- Analog: Trigger, Grip, Axis (x,y) + +### Hand Tracking +- 26 joints per hand with 7 values each (position + quaternion) +- Hand scale factor + +### Body Tracking +- 24 body joints with pose, velocity, acceleration data +- IMU timestamps for each joint +- Availability flag for body tracking system + +## Dependencies + +### Required +- pybind11 (Python binding framework) +- CMake (build system) +- XRoboToolkit-PC-Service SDK (automatically downloaded during setup) + +### Platform-specific Libraries +- Linux: `libPXREARobotSDK.so` +- Windows: `PXREARobotSDK.dll` and `PXREARobotSDK.lib` + +## Testing + +No formal test suite is included. Test functionality using the example scripts in `examples/`: +- `example.py`: Basic controller and headset pose testing +- `example_body_tracking.py`: Body tracking functionality +- `run_binding_continuous.py`: Continuous data capture + +## Important Notes + +- The SDK requires active XR device connection (PICO headset) +- Body tracking requires at least two Pico Swift devices +- All data access is thread-safe but real-time dependent on device connectivity +- The project builds a Python extension module that must be installed to site-packages \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/CMakeLists.txt b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..654b7b6015322b9964810c5ea5541a6dad3bf335 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/CMakeLists.txt @@ -0,0 +1,54 @@ +cmake_minimum_required(VERSION 3.14) + +project(MyPybind11Project LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +cmake_host_system_information(RESULT ISA_NAME QUERY OS_PLATFORM) # Added: Important for UNIX specific logic +message(STATUS "OS_PLATFORM (ISA_NAME): ${ISA_NAME}") + +include(GNUInstallDirs) # Add this line +find_package(pybind11 REQUIRED) + +# Python Bindings for py_bindings.cpp +pybind11_add_module(xrobotoolkit_sdk MODULE bindings/py_bindings.cpp) + +# Link xrobotoolkit_sdk module against pybind11 +target_link_libraries(xrobotoolkit_sdk PRIVATE pybind11::module) + +# Add include directories and link libraries for PXREARobotSDK to xrobotoolkit_sdk target +if(WIN32) + target_include_directories(xrobotoolkit_sdk PUBLIC + ${PROJECT_SOURCE_DIR}/include + ) + target_link_directories(xrobotoolkit_sdk PUBLIC ${PROJECT_SOURCE_DIR}/lib) + target_link_libraries(xrobotoolkit_sdk PUBLIC + PXREARobotSDK.dll # Assuming this is how PXREARobotSDK is linked, mirroring ConsoleDemo + ) +endif() + +if(UNIX) + # ISA_NAME is set by cmake_host_system_information above + if(ISA_NAME STREQUAL "aarch64") + target_include_directories(xrobotoolkit_sdk PUBLIC + ${PROJECT_SOURCE_DIR}/include/aarch64 + ) + target_link_directories(xrobotoolkit_sdk PUBLIC ${PROJECT_SOURCE_DIR}/lib/aarch64) + else() + target_include_directories(xrobotoolkit_sdk PUBLIC + ${PROJECT_SOURCE_DIR}/include + ) + target_link_directories(xrobotoolkit_sdk PUBLIC ${PROJECT_SOURCE_DIR}/lib) + endif() + target_link_libraries(xrobotoolkit_sdk PUBLIC + PXREARobotSDK + ) +endif() + +# Install the Python module +install(TARGETS xrobotoolkit_sdk + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} # Installs to /lib + # You might want a Python-specific path like: + # DESTINATION lib/python${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}/site-packages +) diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/LICENSE b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c0973fd2fae63464a24d96e09da74aa7fb61720b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 XR Robotics + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/README.md b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9d7a937dd07961c8595ee9196d8dcbcfcbd19e46 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/README.md @@ -0,0 +1,169 @@ +# XRoboToolkit-PC-Service-Pybind + +This project provides a python interface to extract XR state using XRoboToolkit-PC-Service sdk. + +## Requirements + +- [`pybind11`](https://github.com/pybind/pybind11) +- [`XRoboRoolkit PC Service`](https://github.com/XR-Robotics/XRoboToolkit-PC-Service#) + +## Building the Project +### Ubuntu 22.04 + +``` +conda remove --name xr --all +conda create -n xr python=3.10 +conda activate xr + +mkdir -p tmp +cd tmp +git clone https://github.com/XR-Robotics/XRoboToolkit-PC-Service.git +cd XRoboToolkit-PC-Service/RoboticsService/PXREARobotSDK +bash build.sh +cd ../../../.. + +mkdir -p lib +mkdir -p include +cp tmp/XRoboToolkit-PC-Service/RoboticsService/PXREARobotSDK/PXREARobotSDK.h include/ +cp -r tmp/XRoboToolkit-PC-Service/RoboticsService/PXREARobotSDK/nlohmann include/nlohmann/ +cp tmp/XRoboToolkit-PC-Service/RoboticsService/PXREARobotSDK/build/libPXREARobotSDK.so lib/ +# rm -rf tmp + +# Build the project +conda install -c conda-forge pybind11 + +pip uninstall -y xrobotoolkit_sdk +python setup.py install +``` +### Linux Ubuntu 22.04 arm64 version (Nvidia orin supported) +``` +bash setup_orin.sh +``` +### Windows + +**Ensure pybind11 is installed before running the following command.** + +``` +setup_windows.bat +``` + +## Using the Python Bindings + +**1. Get Controller and Headset Poses** + +```python +import xrobotoolkit_sdk as xrt + +xrt.init() + +left_pose = xrt.get_left_controller_pose() +right_pose = xrt.get_right_controller_pose() +headset_pose = xrt.get_headset_pose() + +print(f"Left Controller Pose: {left_pose}") +print(f"Right Controller Pose: {right_pose}") +print(f"Headset Pose: {headset_pose}") + +xrt.close() +``` + +**2. Get Controller Inputs (Triggers, Grips, Buttons, Axes)** + +```python +import xrobotoolkit_sdk as xrt + +xrt.init() + +# Triggers and Grips +left_trigger = xrt.get_left_trigger() +right_grip = xrt.get_right_grip() +print(f"Left Trigger: {left_trigger}, Right Grip: {right_grip}") + +# Buttons +a_button_pressed = xrt.get_A_button() +x_button_pressed = xrt.get_X_button() +print(f"A Button Pressed: {a_button_pressed}, X Button Pressed: {x_button_pressed}") + +# Axes +left_axis = xrt.get_left_axis() +right_axis_click = xrt.get_right_axis_click() +print(f"Left Axis: {left_axis}, Right Axis Clicked: {right_axis_click}") + +# Timestamp +timestamp = xrt.get_time_stamp_ns() +print(f"Current Timestamp (ns): {timestamp}") + +xrt.close() +``` + +**3. Get hand tracking state** +```python +import xrobotoolkit_sdk as xrt + +xrt.init() + +# Left Hand State +left_hand_tracking_state = xrt.get_left_hand_tracking_state() +print(f"Left Hand State: {left_hand_tracking_state}") + +# Left Hand isActive +left_hand_is_active = xrt.get_left_hand_is_active() +print(f"Left Hand isActive: {left_hand_is_active}") + +# Right Hand State +right_hand_tracking_state = xrt.get_right_hand_tracking_state() +print(f"Right Hand State: {right_hand_tracking_state}") + +# Right Hand isActive +right_hand_is_active = xrt.get_right_hand_is_active() +print(f"Right Hand isActive: {right_hand_is_active}") + +xrt.close() +``` + +**4. Get whole body motion tracking (please refer to this example when check Full Body tracking mode in UNITY app)** +```python +import xrobotoolkit_sdk as xrt + +xrt.init() + +# Check if body tracking data is available +if xrt.is_body_data_available(): + # Get body joint poses (24 joints, 7 values each: x,y,z,qx,qy,qz,qw) + body_poses = xrt.get_body_joints_pose() + print(f"Body joints pose data: {body_poses}") + + # Get body joint velocities (24 joints, 6 values each: vx,vy,vz,wx,wy,wz) + body_velocities = xrt.get_body_joints_velocity() + print(f"Body joints velocity data: {body_velocities}") + + # Get body joint accelerations (24 joints, 6 values each: ax,ay,az,wax,way,waz) + body_accelerations = xrt.get_body_joints_acceleration() + print(f"Body joints acceleration data: {body_accelerations}") + + # Get IMU timestamps for each joint + imu_timestamps = xrt.get_body_joints_timestamp() + print(f"IMU timestamps: {imu_timestamps}") + + # Get body data timestamp + body_timestamp = xrt.get_body_timestamp_ns() + print(f"Body data timestamp: {body_timestamp}") + + # Example: Get specific joint data (Head joint is index 15) + head_pose = body_poses[15] # Head joint + x, y, z, qx, qy, qz, qw = head_pose + print(f"Head pose: Position({x:.3f}, {y:.3f}, {z:.3f}) Rotation({qx:.3f}, {qy:.3f}, {qz:.3f}, {qw:.3f})") +else: + print("Body tracking data not available. Make sure:") + print("1. PICO headset is connected") + print("2. Body tracking is enabled in the control panel") + print("3. At least two Pico Swift devices are connected and calibrated") + +xrt.close() +``` + +**Body Joint Indices (similar to SMPL, 24 joints total):** +- 0: Pelvis, 1: Left Hip, 2: Right Hip, 3: Spine1, 4: Left Knee, 5: Right Knee +- 6: Spine2, 7: Left Ankle, 8: Right Ankle, 9: Spine3, 10: Left Foot, 11: Right Foot +- 12: Neck, 13: Left Collar, 14: Right Collar, 15: Head, 16: Left Shoulder, 17: Right Shoulder +- 18: Left Elbow, 19: Right Elbow, 20: Left Wrist, 21: Right Wrist, 22: Left Hand, 23: Right Hand diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/bindings/py_bindings.cpp b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/bindings/py_bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f7c9d9b200c47c942ba2027e4cde10fae847e7c --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/bindings/py_bindings.cpp @@ -0,0 +1,546 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "PXREARobotSDK.h" + + +using json = nlohmann::json; + +std::array LeftControllerPose; +std::array RightControllerPose; +std::array HeadsetPose; + +std::array, 26> LeftHandTrackingState; +double LeftHandScale = 1.0; +int LeftHandIsActive = 0; +std::array, 26> RightHandTrackingState; +double RightHandScale = 1.0; +int RightHandIsActive = 0; + +// Whole body motion data - 24 joints for body tracking +std::array, 24> BodyJointsPose; // Position and rotation for each joint +std::array, 24> BodyJointsVelocity; // Velocity and angular velocity for each joint +std::array, 24> BodyJointsAcceleration; // Acceleration and angular acceleration for each joint +std::array BodyJointsTimestamp; // IMU timestamp for each joint +int64_t BodyTimeStampNs = 0; // Body data timestamp +bool BodyDataAvailable = false; // Flag to indicate if body data is available + +std::array, 3> MotionTrackerPose; // Position and rotation for each joint +std::array, 3> MotionTrackerVelocity; // Velocity and angular velocity for each joint +std::array, 3> MotionTrackerAcceleration; // Acceleration and angular acceleration for each joint +std::array MotionTrackerSerialNumbers; // Serial numbers of the motion trackers +int64_t MotionTimeStampNs = 0; // Motion data timestamp +int NumMotionDataAvailable = 0; // number of motion trackers + + +bool LeftMenuButton; +double LeftTrigger; +double LeftGrip; +std::array LeftAxis{0.0, 0.0}; +bool LeftAxisClick; +bool LeftPrimaryButton; +bool LeftSecondaryButton; + +bool RightMenuButton; +double RightTrigger; +double RightGrip; +std::array RightAxis{0.0, 0.0}; +bool RightAxisClick; +bool RightPrimaryButton; +bool RightSecondaryButton; + +int64_t TimeStampNs; + +std::mutex leftMutex; +std::mutex rightMutex; +std::mutex headsetPoseMutex; +std::mutex timestampMutex; +std::mutex leftHandMutex; +std::mutex rightHandMutex; +std::mutex bodyMutex; // Mutex for body tracking data +std::mutex motionMutex; + + + +std::array stringToPoseArray(const std::string& poseStr) { + std::array result{0}; + std::stringstream ss(poseStr); + std::string value; + int i = 0; + while (std::getline(ss, value, ',') && i < 7) { + result[i++] = std::stod(value); + } + return result; +} + +std::array stringToVelocityArray(const std::string& velocityStr) { + std::array result{0}; + std::stringstream ss(velocityStr); + std::string value; + int i = 0; + while (std::getline(ss, value, ',') && i < 6) { + result[i++] = std::stod(value); + } + return result; +} + +void OnPXREAClientCallback(void* context, PXREAClientCallbackType type, int status, void* userData) +{ + switch (type) + { + case PXREAServerConnect: + std::cout << "server connect\n" << std::endl; + break; + case PXREAServerDisconnect: + std::cout << "server disconnect\n" << std::endl; + break; + case PXREADeviceFind: + std::cout << "device found\n" << (const char*)userData << std::endl; + break; + case PXREADeviceMissing: + std::cout << "device missing\n" << (const char*)userData << std::endl; + break; + case PXREADeviceConnect: + std::cout << "device connect\n" << (const char*)userData << status << std::endl; + break; + case PXREADeviceStateJson: + auto& dsj = *((PXREADevStateJson*)userData); + + + try { + json data = json::parse(dsj.stateJson); + if (data.contains("value")) { + auto value = json::parse(data["value"].get()); + if (value["Controller"].contains("left")) { + auto& left = value["Controller"]["left"]; + { + std::lock_guard lock(leftMutex); + LeftControllerPose = stringToPoseArray(left["pose"].get()); + LeftTrigger = left["trigger"].get(); + LeftGrip = left["grip"].get(); + LeftMenuButton = left["menuButton"].get(); + LeftAxis[0] = left["axisX"].get(); + LeftAxis[1] = left["axisY"].get(); + LeftAxisClick = left["axisClick"].get(); + LeftPrimaryButton = left["primaryButton"].get(); + LeftSecondaryButton = left["secondaryButton"].get(); + } + } + if (value["Controller"].contains("right")) { + auto& right = value["Controller"]["right"]; + { + std::lock_guard lock(rightMutex); + RightControllerPose = stringToPoseArray(right["pose"].get()); + RightTrigger = right["trigger"].get(); + RightGrip = right["grip"].get(); + RightMenuButton = right["menuButton"].get(); + RightAxis[0] = right["axisX"].get(); + RightAxis[1] = right["axisY"].get(); + RightAxisClick = right["axisClick"].get(); + RightPrimaryButton = right["primaryButton"].get(); + RightSecondaryButton = right["secondaryButton"].get(); + } + } + if (value.contains("Head")) { + auto& headset = value["Head"]; + { + std::lock_guard lock(headsetPoseMutex); + HeadsetPose = stringToPoseArray(headset["pose"].get()); + } + } + if (value.contains("timeStampNs")) { + std::lock_guard lock(timestampMutex); + TimeStampNs = value["timeStampNs"].get(); + } + if (value["Hand"].contains("leftHand")) { + auto& leftHand = value["Hand"]["leftHand"]; + { + std::lock_guard lock(leftHandMutex); + + LeftHandScale = leftHand["scale"].get(); + LeftHandIsActive = leftHand["isActive"].get(); + for (int i = 0; i < 26; i++) { + LeftHandTrackingState[i] = stringToPoseArray(leftHand["HandJointLocations"][i]["p"].get()); + } + } + } + if (value["Hand"].contains("rightHand")) { + auto& rightHand = value["Hand"]["rightHand"]; + { + std::lock_guard lock(rightHandMutex); + RightHandScale = rightHand["scale"].get(); + RightHandIsActive = rightHand["isActive"].get(); + for (int i = 0; i < 26; i++) { + RightHandTrackingState[i] = stringToPoseArray(rightHand["HandJointLocations"][i]["p"].get()); + } + } + } + // Parse Body data for whole body motion capture + if (value.contains("Body")) { + auto& body = value["Body"]; + { + std::lock_guard lock(bodyMutex); + + if (body.contains("timeStampNs")) { + BodyTimeStampNs = body["timeStampNs"].get(); + } + + if (body.contains("joints") && body["joints"].is_array()) { + auto joints = body["joints"]; + int jointCount = std::min(static_cast(joints.size()), 24); + + for (int i = 0; i < jointCount; i++) { + auto& joint = joints[i]; + + // Parse pose (position and rotation) + if (joint.contains("p")) { + BodyJointsPose[i] = stringToPoseArray(joint["p"].get()); + } + + // Parse velocity and angular velocity + if (joint.contains("va")) { + BodyJointsVelocity[i] = stringToVelocityArray(joint["va"].get()); + } + + // Parse acceleration and angular acceleration + if (joint.contains("wva")) { + BodyJointsAcceleration[i] = stringToVelocityArray(joint["wva"].get()); + } + + // Parse IMU timestamp + if (joint.contains("t")) { + BodyJointsTimestamp[i] = joint["t"].get(); + } + } + + BodyDataAvailable = true; + } + } + } + //parse individual tracker data + if (value.contains("Motion")) { + auto& motion = value["Motion"]; + { + std::lock_guard lock(motionMutex); + if (motion.contains("timeStampNs")) { + MotionTimeStampNs = motion["timeStampNs"].get(); + } + if (motion.contains("joints") && motion["joints"].is_array()) { + auto joints = motion["joints"]; + NumMotionDataAvailable = std::min(static_cast(joints.size()), 3); + + for (int i = 0; i < NumMotionDataAvailable; i++) { + auto& joint = joints[i]; + + // Parse pose (position and rotation) + if (joint.contains("p")) { + MotionTrackerPose[i] = stringToPoseArray(joint["p"].get()); + } + + // Parse velocity and angular velocity + if (joint.contains("va")) { + MotionTrackerVelocity[i] = stringToVelocityArray(joint["va"].get()); + } + + // Parse acceleration and angular acceleration + if (joint.contains("wva")) { + MotionTrackerAcceleration[i] = stringToVelocityArray(joint["wva"].get()); + } + + if (joint.contains("sn")) { + MotionTrackerSerialNumbers[i] = joint["sn"].get(); + } + } + + } + } + } + } + } catch (const json::exception& e) { + std::cerr << "JSON parsing error: " << e.what() << std::endl; + } + break; + } +} + +void init() { + if (PXREAInit(NULL, OnPXREAClientCallback, PXREAFullMask) != 0) { + throw std::runtime_error("PXREAInit failed"); + } +} + +void deinit() { + PXREADeinit(); +} + +std::array getLeftControllerPose() { + std::lock_guard lock(leftMutex); + return LeftControllerPose; +} + +std::array getRightControllerPose() { + std::lock_guard lock(rightMutex); + return RightControllerPose; +} + +std::array getHeadsetPose() { + std::lock_guard lock(headsetPoseMutex); + return HeadsetPose; +} + +double getLeftTrigger() { + std::lock_guard lock(leftMutex); + return LeftTrigger; +} + +double getLeftGrip() { + std::lock_guard lock(leftMutex); + return LeftGrip; +} + +double getRightTrigger() { + std::lock_guard lock(rightMutex); + return RightTrigger; +} + +double getRightGrip() { + std::lock_guard lock(rightMutex); + return RightGrip; +} + +bool getLeftMenuButton() { + std::lock_guard lock(leftMutex); + return LeftMenuButton; +} + +bool getRightMenuButton() { + std::lock_guard lock(rightMutex); + return RightMenuButton; +} + +bool getLeftAxisClick() { + std::lock_guard lock(leftMutex); + return LeftAxisClick; +} + +bool getRightAxisClick() { + std::lock_guard lock(rightMutex); + return RightAxisClick; +} + +std::array getLeftAxis() { + std::lock_guard lock(leftMutex); + return LeftAxis; +} + + +std::array getRightAxis() { + std::lock_guard lock(rightMutex); + return RightAxis; +} + +bool getLeftPrimaryButton() { + std::lock_guard lock(leftMutex); + return LeftPrimaryButton; +} + +bool getRightPrimaryButton() { + std::lock_guard lock(rightMutex); + return RightPrimaryButton; +} + +bool getLeftSecondaryButton() { + std::lock_guard lock(leftMutex); + return LeftSecondaryButton; +} + +bool getRightSecondaryButton() { + std::lock_guard lock(rightMutex); + return RightSecondaryButton; +} + +int64_t getTimeStampNs() { + std::lock_guard lock(timestampMutex); + return TimeStampNs; +} + +std::array, 26> getLeftHandTrackingState() { + std::lock_guard lock(leftHandMutex); + return LeftHandTrackingState; +} + +int getLeftHandScale() { + std::lock_guard lock(leftHandMutex); + return LeftHandScale; +} + +int getLeftHandIsActive() { + std::lock_guard lock(leftHandMutex); + return LeftHandIsActive; +} + +std::array, 26> getRightHandTrackingState() { + std::lock_guard lock(rightHandMutex); + return RightHandTrackingState; +} + +int getRightHandScale() { + std::lock_guard lock(rightHandMutex); + return RightHandScale; +} + +int getRightHandIsActive() { + std::lock_guard lock(rightHandMutex); + return RightHandIsActive; +} + +// Body tracking functions +bool isBodyDataAvailable() { + std::lock_guard lock(bodyMutex); + return BodyDataAvailable; +} + +std::array, 24> getBodyJointsPose() { + std::lock_guard lock(bodyMutex); + return BodyJointsPose; +} + +std::array, 24> getBodyJointsVelocity() { + std::lock_guard lock(bodyMutex); + return BodyJointsVelocity; +} + +std::array, 24> getBodyJointsAcceleration() { + std::lock_guard lock(bodyMutex); + return BodyJointsAcceleration; +} + +std::array getBodyJointsTimestamp() { + std::lock_guard lock(bodyMutex); + return BodyJointsTimestamp; +} + +int64_t getBodyTimeStampNs() { + std::lock_guard lock(bodyMutex); + return BodyTimeStampNs; +} + +int numMotionDataAvailable() { + std::lock_guard lock(motionMutex); + return NumMotionDataAvailable; +} + +std::vector> getMotionTrackerPose() { + std::lock_guard lock(motionMutex); + std::vector> result; + for (int i = 0; i < NumMotionDataAvailable; i++) { + result.push_back(MotionTrackerPose[i]); + } + return result; +} + +std::vector> getMotionTrackerVelocity() { + std::lock_guard lock(motionMutex); + std::vector> result; + for (int i = 0; i < NumMotionDataAvailable; i++) { + result.push_back(MotionTrackerVelocity[i]); + } + return result; +} + +std::vector> getMotionTrackerAcceleration() { + std::lock_guard lock(motionMutex); + std::vector> result; + for (int i = 0; i < NumMotionDataAvailable; i++) { + result.push_back(MotionTrackerAcceleration[i]); + } + return result; +} + +std::vector getMotionTrackerSerialNumbers() { + std::lock_guard lock(motionMutex); + std::vector result; + for (int i = 0; i < NumMotionDataAvailable; i++) { + result.push_back(MotionTrackerSerialNumbers[i]); + } + return result; +} + +int64_t getMotionTimeStampNs() { + std::lock_guard lock(motionMutex); + return MotionTimeStampNs; +} + +int DeviceControlJsonWrapper(const std::string& dev_id, const std::string& json_str) { + const int rc = PXREADeviceControlJson(dev_id.c_str(), json_str.c_str()); + if (rc != 0) { + throw std::runtime_error("device_control_json failed"); + } + return rc; // 0 +} + +int SendBytesToDeviceWrapper(const std::string& dev_id, pybind11::bytes blob) { + std::string s = blob; // copy Python bytes to std::string + const int rc = PXREASendBytesToDevice(dev_id.c_str(), s.data(), static_cast(s.size())); + if (rc != 0) { + throw std::runtime_error("send_bytes_to_device failed"); + } + return rc; // 0 +} + + +PYBIND11_MODULE(xrobotoolkit_sdk, m) { + m.def("init", &init, "Initialize the PXREARobot SDK."); + m.def("close", &deinit, "Deinitialize the PXREARobot SDK."); + m.def("get_left_controller_pose", &getLeftControllerPose, "Get the left controller pose."); + m.def("get_right_controller_pose", &getRightControllerPose, "Get the right controller pose."); + m.def("get_headset_pose", &getHeadsetPose, "Get the headset pose."); + m.def("get_left_trigger", &getLeftTrigger, "Get the left trigger value."); + m.def("get_left_grip", &getLeftGrip, "Get the left grip value."); + m.def("get_right_trigger", &getRightTrigger, "Get the right trigger value."); + m.def("get_right_grip", &getRightGrip, "Get the right grip value."); + m.def("get_left_menu_button", &getLeftMenuButton, "Get the left menu button state."); + m.def("get_right_menu_button", &getRightMenuButton, "Get the right menu button state."); + m.def("get_left_axis_click", &getLeftAxisClick, "Get the left axis click state."); + m.def("get_right_axis_click", &getRightAxisClick, "Get the right axis click state."); + m.def("get_left_axis", &getLeftAxis, "Get the left axis values (x, y)."); + m.def("get_right_axis", &getRightAxis, "Get the right axis values (x, y)."); + m.def("get_X_button", &getLeftPrimaryButton, "Get the left primary button state."); + m.def("get_A_button", &getRightPrimaryButton, "Get the right primary button state."); + m.def("get_Y_button", &getLeftSecondaryButton, "Get the left secondary button state."); + m.def("get_B_button", &getRightSecondaryButton, "Get the right secondary button state."); + m.def("get_time_stamp_ns", &getTimeStampNs, "Get the timestamp in nanoseconds."); + m.def("get_left_hand_tracking_state", &getLeftHandTrackingState, "Get the left hand state."); + m.def("get_right_hand_tracking_state", &getRightHandTrackingState, "Get the right hand state."); + m.def("get_left_hand_is_active", &getLeftHandIsActive, "Get the left hand tracking quality (0 = low, 1 = high)."); + m.def("get_right_hand_is_active", &getRightHandIsActive, "Get the right hand tracking quality (0 = low, 1 = high)."); + + // Body tracking functions + m.def("is_body_data_available", &isBodyDataAvailable, "Check if body tracking data is available."); + m.def("get_body_joints_pose", &getBodyJointsPose, "Get the body joints pose data (24 joints, 7 values each: x,y,z,qx,qy,qz,qw)."); + m.def("get_body_joints_velocity", &getBodyJointsVelocity, "Get the body joints velocity data (24 joints, 6 values each: vx,vy,vz,wx,wy,wz)."); + m.def("get_body_joints_acceleration", &getBodyJointsAcceleration, "Get the body joints acceleration data (24 joints, 6 values each: ax,ay,az,wax,way,waz)."); + m.def("get_body_joints_timestamp", &getBodyJointsTimestamp, "Get the body joints IMU timestamp data (24 joints)."); + m.def("get_body_timestamp_ns", &getBodyTimeStampNs, "Get the body data timestamp in nanoseconds."); + + // Motion tracker functions + m.def("num_motion_data_available", &numMotionDataAvailable, "Check if motion tracker data is available."); + m.def("get_motion_tracker_pose", &getMotionTrackerPose, "Get the motion tracker pose data (3 trackers, 7 values each: x,y,z,qx,qy,qz,qw)."); + m.def("get_motion_tracker_velocity", &getMotionTrackerVelocity, "Get the motion tracker velocity data (3 trackers, 6 values each: vx,vy,vz,wx,wy,wz)."); + m.def("get_motion_tracker_acceleration", &getMotionTrackerAcceleration, "Get the motion tracker acceleration data (3 trackers, 6 values each: ax,ay,az,wax,way,waz)."); + m.def("get_motion_tracker_serial_numbers", &getMotionTrackerSerialNumbers, "Get the serial numbers of the motion trackers."); + m.def("get_motion_timestamp_ns", &getMotionTimeStampNs, "Get the motion data timestamp in nanoseconds."); + + + // send json bytes functions + m.def("device_control_json", &DeviceControlJsonWrapper, "Send a JSON control command to a device"); + m.def("send_bytes_to_device", &SendBytesToDeviceWrapper, "Send raw bytes to a device"); + + m.doc() = "Python bindings for PXREARobot SDK using pybind11."; +} \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example.py b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example.py new file mode 100644 index 0000000000000000000000000000000000000000..52ddbdb7a3c596265ca562af9b36994fcb58fcd8 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example.py @@ -0,0 +1,47 @@ +# 1. Get Controller and Headset Poses + +import xrobotoolkit_sdk as xrt + +xrt.init() + +left_pose = xrt.get_left_controller_pose() +right_pose = xrt.get_right_controller_pose() +headset_pose = xrt.get_headset_pose() + +print(f"Left Controller Pose: {left_pose}") +print(f"Right Controller Pose: {right_pose}") +print(f"Headset Pose: {headset_pose}") + + +# 2. Get Controller Inputs (Triggers, Grips, Buttons, Axes)** + + + +# Triggers and Grips +left_trigger = xrt.get_left_trigger() +right_grip = xrt.get_right_grip() +print(f"Left Trigger: {left_trigger}, Right Grip: {right_grip}") + +# Buttons +a_button_pressed = xrt.get_A_button() +x_button_pressed = xrt.get_X_button() +print(f"A Button Pressed: {a_button_pressed}, X Button Pressed: {x_button_pressed}") + +# Axes +left_axis = xrt.get_left_axis() +right_axis_click = xrt.get_right_axis_click() +print(f"Left Axis: {left_axis}, Right Axis Clicked: {right_axis_click}") + +# Timestamp +timestamp = xrt.get_time_stamp_ns() +print(f"Current Timestamp (ns): {timestamp}") + + +# 3. Get hand tracking state + +# Left Hand State +left_hand_tracking_state = xrt.get_left_hand_tracking_state() +print(f"Left Hand State: {left_hand_tracking_state}") +# Right Hand State +right_hand_tracking_state = xrt.get_right_hand_tracking_state() +print(f"Right Hand State: {right_hand_tracking_state}") diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example_body_tracking.py b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example_body_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..289eadd388bb0291e8c5153bb19369355ae8c447 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example_body_tracking.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +""" +Example script demonstrating whole body motion tracking with XRoboToolkit SDK. + +This script shows how to: +1. Check if body tracking data is available +2. Get body joint poses (position and rotation) +3. Get body joint velocities and accelerations +4. Get IMU timestamps for each joint +5. Get body data timestamp +6. Save data to structured format (pickle/json) + +Body Joint Indices (24 joints total): +0: Pelvis, 1: Left Hip, 2: Right Hip, 3: Spine1, 4: Left Knee, 5: Right Knee, +6: Spine2, 7: Left Ankle, 8: Right Ankle, 9: Spine3, 10: Left Foot, 11: Right Foot, +12: Neck, 13: Left Collar, 14: Right Collar, 15: Head, 16: Left Shoulder, 17: Right Shoulder, +18: Left Elbow, 19: Right Elbow, 20: Left Wrist, 21: Right Wrist, 22: Left Hand, 23: Right Hand +""" + +import xrobotoolkit_sdk as xrt +import time +import argparse +import csv +import os +import json +import pickle +from datetime import datetime + + +def main(): + + xrt.init() + + while not xrt.is_body_data_available(): + time.sleep(0.01) + + if xrt.is_body_data_available(): + print("Body tracking data is available!") + + # Joint names for reference + joint_names = [ + "Pelvis", "Left_Hip", "Right_Hip", "Spine1", "Left_Knee", "Right_Knee", + "Spine2", "Left_Ankle", "Right_Ankle", "Spine3", "Left_Foot", "Right_Foot", + "Neck", "Left_Collar", "Right_Collar", "Head", "Left_Shoulder", "Right_Shoulder", + "Left_Elbow", "Right_Elbow", "Left_Wrist", "Right_Wrist", "Left_Hand", "Right_Hand" + ] + + + body_poses = xrt.get_body_joints_pose() # list of [x, y, z, qx, qy, qz, qw] + body_velocities = xrt.get_body_joints_velocity() # vx, vy, vz, wx, wy, wz + body_accelerations = xrt.get_body_joints_acceleration() # ax, ay, az, wax, way, waz + imu_timestamps = xrt.get_body_joints_timestamp() # list of [timestamp] + body_timestamp = xrt.get_body_timestamp_ns() # timestamp in ns + + saved_data = [] + length = 500 + step_idx = 0 + while len(saved_data) < length: + + # Sample data at specified rate + if xrt.is_body_data_available(): + # Get all body tracking data + body_poses = xrt.get_body_joints_pose() + body_velocities = xrt.get_body_joints_velocity() + body_accelerations = xrt.get_body_joints_acceleration() + imu_timestamps = xrt.get_body_joints_timestamp() + body_timestamp = xrt.get_body_timestamp_ns() + + + body_pose_dict = {} + for i, joint_name in enumerate(joint_names): + pos = [body_poses[i][0], body_poses[i][1], body_poses[i][2]] + rot = [body_poses[i][6], body_poses[i][3], body_poses[i][4], body_poses[i][5]] # scalar first + body_pose_dict[joint_name] = [pos, rot] + + saved_data.append(body_pose_dict) + step_idx += 1 + time.sleep(1/50) + print(f"Step {step_idx} of {length}") + + with open('body_tracking_data.pkl', 'wb') as f: + pickle.dump(saved_data, f) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example_motion_tracker.py b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example_motion_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..c054972cabc8dd62f7dfa8e5140598cb1d976c07 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/example_motion_tracker.py @@ -0,0 +1,17 @@ +import xrobotoolkit_sdk as xrt + +xrt.init() +num_motion_data = xrt.num_motion_data_available() +print(f"Number of Motion Trackers: {num_motion_data}") +if num_motion_data > 0: + motion_tracker_pose = xrt.get_motion_tracker_pose() + motion_tracker_velocity = xrt.get_motion_tracker_velocity() + motion_tracker_acceleration = xrt.get_motion_tracker_acceleration() + motion_tracker_serial_numbers = xrt.get_motion_tracker_serial_numbers() + motion_timestamp_ns = xrt.get_motion_timestamp_ns() + + print(f"Motion Tracker Pose: {motion_tracker_pose}") + print(f"Motion Tracker Velocity: {motion_tracker_velocity}") + print(f"Motion Tracker Acceleration: {motion_tracker_acceleration}") + print(f"Motion Tracker Serial Numbers: {motion_tracker_serial_numbers}") + print(f"Motion Timestamp (ns): {motion_timestamp_ns}") diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/run_binding_continuous.py b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/run_binding_continuous.py new file mode 100644 index 0000000000000000000000000000000000000000..b3132178b4796c06e7944746d5ae44aed1e86eaa --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/run_binding_continuous.py @@ -0,0 +1,111 @@ +import sys +import time + +import xrobotoolkit_sdk as xrt + + +def run_tests(): + print("Starting Python binding test...") + + try: + print("Initializing SDK...") + xrt.init() + print("SDK Initialized successfully.") + + print("\n--- Testing all functions for 10 iterations ---") + for i in range(100): + print(f"\n--- Iteration {i+1} ---") + + # Poses + left_pose = xrt.get_left_controller_pose() + right_pose = xrt.get_right_controller_pose() + headset_pose = xrt.get_headset_pose() + print(f"Left Controller Pose: {left_pose}") + print(f"Right Controller Pose: {right_pose}") + print(f"Headset Pose: {headset_pose}") + + # Triggers + left_trigger = xrt.get_left_trigger() + right_trigger = xrt.get_right_trigger() + print(f"Left Trigger: {left_trigger}") + print(f"Right Trigger: {right_trigger}") + + # Grips + left_grip = xrt.get_left_grip() + right_grip = xrt.get_right_grip() + print(f"Left Grip: {left_grip}") + print(f"Right Grip: {right_grip}") + + # Menu Buttons + left_menu = xrt.get_left_menu_button() + right_menu = xrt.get_right_menu_button() + print(f"Left Menu Button: {left_menu}") + print(f"Right Menu Button: {right_menu}") + + # Axis Clicks + left_axis_click = xrt.get_left_axis_click() + right_axis_click = xrt.get_right_axis_click() + print(f"Left Axis Click: {left_axis_click}") + print(f"Right Axis Click: {right_axis_click}") + + # Axes + left_axis = xrt.get_left_axis() + right_axis = xrt.get_right_axis() + print(f"Left Axis (X, Y): {left_axis}") + print(f"Right Axis (X, Y): {right_axis}") + + # Primary Buttons (X, A) + x_button = xrt.get_X_button() # Left Primary + a_button = xrt.get_A_button() # Right Primary + print(f"X Button (Left Primary): {x_button}") + print(f"A Button (Right Primary): {a_button}") + + # Secondary Buttons (Y, B) + y_button = xrt.get_Y_button() # Left Secondary + b_button = xrt.get_B_button() # Right Secondary + print(f"Y Button (Left Secondary): {y_button}") + print(f"B Button (Right Secondary): {b_button}") + + # Left Hand State + left_hand_state = xrt.get_left_hand_tracking_state() + print(f"Left Hand State: {left_hand_state}") + # Right Hand State + right_hand_state = xrt.get_right_hand_tracking_state() + print(f"Right Hand State: {right_hand_state}") + + # Timestamp + timestamp = xrt.get_time_stamp_ns() + print(f"Timestamp (ns): {timestamp}") + + num_motion_data = xrt.num_motion_data_available() + print(f"Number of Motion Trackers: {num_motion_data}") + if num_motion_data > 0: + motion_tracker_pose = xrt.get_motion_tracker_pose() + motion_tracker_velocity = xrt.get_motion_tracker_velocity() + motion_tracker_acceleration = xrt.get_motion_tracker_acceleration() + motion_tracker_serial_numbers = xrt.get_motion_tracker_serial_numbers() + motion_timestamp_ns = xrt.get_motion_timestamp_ns() + + print(f"Motion Tracker Pose: {motion_tracker_pose}") + print(f"Motion Tracker Velocity: {motion_tracker_velocity}") + print(f"Motion Tracker Acceleration: {motion_tracker_acceleration}") + print(f"Motion Tracker Serial Numbers: {motion_tracker_serial_numbers}") + print(f"Motion Timestamp (ns): {motion_timestamp_ns}") + + time.sleep(0.5) # Wait for 0.5 seconds before the next iteration + + print("\nAll iterations complete.") + + except RuntimeError as e: + print(f"Runtime Error: {e}", file=sys.stderr) + except Exception as e: + print(f"An unexpected error occurred: {e}", file=sys.stderr) + finally: + print("\nClosing SDK...") + xrt.close() + print("SDK closed.") + print("Test finished.") + + +if __name__ == "__main__": + run_tests() diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/send_json_example.py b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/send_json_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5d515e799f44cd3bd87b7d72271c9d61875cdc89 --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/send_json_example.py @@ -0,0 +1,29 @@ +import json, time +import xrobotoolkit_sdk as xrt +from datetime import datetime + +xrt.init() # 建链、启动心跳与服务端反馈流 + +dev_id = "TestDevice" # your device ID in unity app + +# send JSON + +for i in range(3): + print("start sending") + start = int(time.time() * 1e3) + cmd = {"functionName": "set_robot", "value": {"mode": "teach"}, "timestamp_ns": start} + jsonfile= json.dumps(cmd) + jsontime = int(time.time()*1e3) + xrt.device_control_json(dev_id,jsonfile) + end = int(time.time()*1e3) + + print("json process time", jsontime - start) + + print("current time difference ", end-start) +# send bytes +print("send_bytes_to_device rc =", xrt.send_bytes_to_device(dev_id, b"\xAA\x55\x10\x00")) + + + + + diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/test_hand_isactive.py b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/test_hand_isactive.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1caa11831f1c93c4a7f5d70311589d62941f4b --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/examples/test_hand_isactive.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +""" +Test script for hand tracking isActive functionality. + +This script demonstrates how to use the new isActive functions to check +hand tracking quality for both left and right hands. +""" + +import xrobotoolkit_sdk as xrt +import time + +def main(): + try: + # Initialize the SDK + print("Initializing XRoboToolkit SDK...") + xrt.init() + + print("Testing hand tracking isActive functionality...") + print("isActive values: 0 = low quality, 1 = high quality") + print("Press Ctrl+C to stop\n") + + while True: + # Get hand tracking states + left_hand_state = xrt.get_left_hand_tracking_state() + right_hand_state = xrt.get_right_hand_tracking_state() + + # Get hand tracking quality (isActive) + left_hand_active = xrt.get_left_hand_is_active() + right_hand_active = xrt.get_right_hand_is_active() + + + print(f"Left Hand: isActive={left_hand_active}") + print(f"Right Hand: isActive={right_hand_active}") + + # Show hand tracking quality status + left_quality = "HIGH" if left_hand_active == 1 else "LOW" + right_quality = "HIGH" if right_hand_active == 1 else "LOW" + + print(f"Left Hand Quality: {left_quality}") + print(f"Right Hand Quality: {right_quality}") + + # Example of first joint position for reference + if len(left_hand_state) > 0: + left_wrist_pos = left_hand_state[0][:3] # x, y, z + print(f"Left Wrist Position: ({left_wrist_pos[0]:.3f}, {left_wrist_pos[1]:.3f}, {left_wrist_pos[2]:.3f})") + + if len(right_hand_state) > 0: + right_wrist_pos = right_hand_state[0][:3] # x, y, z + print(f"Right Wrist Position: ({right_wrist_pos[0]:.3f}, {right_wrist_pos[1]:.3f}, {right_wrist_pos[2]:.3f})") + + print("-" * 50) + time.sleep(1) + + except KeyboardInterrupt: + print("\nStopping hand tracking test...") + except Exception as e: + print(f"Error: {e}") + finally: + print("Closing SDK...") + xrt.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/PXREARobotSDK.h b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/PXREARobotSDK.h new file mode 100644 index 0000000000000000000000000000000000000000..955f28dc29187a48f726ddc7c3361af850fd654d --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/PXREARobotSDK.h @@ -0,0 +1,120 @@ +/** + * @file PXREARobotSDK.h + * @brief Robot SDK header file for client-side communication + */ +#ifndef PXREACLIENTSDK_H +#define PXREACLIENTSDK_H +#ifdef _WIN32 +#if defined(PXREACLIENTSDK_LIBRARY) +# define PXREACLIENTSDK_EXPORT __declspec(dllexport) +#else +# define PXREACLIENTSDK_EXPORT __declspec(dllimport) +#endif +#endif + +#ifdef __linux__ +#if defined(PXREACLIENTSDK_LIBRARY) +# define PXREACLIENTSDK_EXPORT __attribute__((visibility("default"))) +#else +# define PXREACLIENTSDK_EXPORT __attribute__((visibility("default"))) +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +enum PXREAClientCallbackType +{ + /// @brief Server connected + PXREAServerConnect = 1<<2, + /// @brief Server disconnected + PXREAServerDisconnect = 1<<3, + /// @brief Device online + PXREADeviceFind = 1<<4, + /// @brief Device offline + PXREADeviceMissing = 1<<5, + /// @brief Device connected + PXREADeviceConnect = 1<<9, + /// @brief Device state in JSON format + PXREADeviceStateJson = 1<<25, + /// @brief Custom message + PXREADeviceCustomMessage = 1<<26, + /// @brief Mask for enabling all callbacks + PXREAFullMask = 0xffffffff +}; + + + + + + + + +/// @brief Device state in JSON format +typedef struct { + /// @brief Device serial number + char devID[32]; + /// @brief JSON string containing device state information + char stateJson[16352]; +}PXREADevStateJson; + + +typedef struct { + /// @brief Device serial number + char devID[32]; + /// @brief Data size + uint64_t dataSize; + /// @brief Data pointer, valid within callback + const char* dataPtr; +}PXREADevCustomMessage; + + + + +/** + * @brief Client callback for receiving server messages + * @param context Callback context, passed from #Init parameter 1 context + * @param type Callback type + * @param status Callback status code + * @param userData Callback data pointer, determined by parameter 2 type + */ +typedef void(*pfPXREAClientCallback)(void* context,PXREAClientCallbackType type,int status,void* userData); + +/** + * @brief SDK initialization interface + * @details Connect to service and register callback + * @param context Callback context for passing user-defined data to callback function + * @param cliCallback Callback function pointer for listening to server messages + * @param mask Callback mask for filtering certain server messages + */ +PXREACLIENTSDK_EXPORT int PXREAInit(void* context,pfPXREAClientCallback cliCallback,unsigned mask); +/** + * @brief Termination interface + * @details Disconnect from service + */ +PXREACLIENTSDK_EXPORT int PXREADeinit(); + +/** + * @brief Send JSON format command to device + * @param devID Device serial number + * @param parameterJson Function and parameters in JSON format, refer to robot SDK documentation for specific usage + * @return 0 Success + * @return -1 Failure + */ +PXREACLIENTSDK_EXPORT int PXREADeviceControlJson(const char *devID,const char *parameterJson); +/** + * @brief Send byte stream to specified device + * @note This command is suitable for SDK caller's custom messages + * @param devID Device serial number + * @param data Starting address of byte stream + * @param len Length of byte stream + * @return 0 Success + * @return -1 Failure + */ +PXREACLIENTSDK_EXPORT int PXREASendBytesToDevice(const char* devID,const char* data,unsigned len); +#ifdef __cplusplus +} +#endif + +#endif // PXREACLIENTSDK_H diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/aarch64/PXREARobotSDK.h b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/aarch64/PXREARobotSDK.h new file mode 100644 index 0000000000000000000000000000000000000000..955f28dc29187a48f726ddc7c3361af850fd654d --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/aarch64/PXREARobotSDK.h @@ -0,0 +1,120 @@ +/** + * @file PXREARobotSDK.h + * @brief Robot SDK header file for client-side communication + */ +#ifndef PXREACLIENTSDK_H +#define PXREACLIENTSDK_H +#ifdef _WIN32 +#if defined(PXREACLIENTSDK_LIBRARY) +# define PXREACLIENTSDK_EXPORT __declspec(dllexport) +#else +# define PXREACLIENTSDK_EXPORT __declspec(dllimport) +#endif +#endif + +#ifdef __linux__ +#if defined(PXREACLIENTSDK_LIBRARY) +# define PXREACLIENTSDK_EXPORT __attribute__((visibility("default"))) +#else +# define PXREACLIENTSDK_EXPORT __attribute__((visibility("default"))) +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +enum PXREAClientCallbackType +{ + /// @brief Server connected + PXREAServerConnect = 1<<2, + /// @brief Server disconnected + PXREAServerDisconnect = 1<<3, + /// @brief Device online + PXREADeviceFind = 1<<4, + /// @brief Device offline + PXREADeviceMissing = 1<<5, + /// @brief Device connected + PXREADeviceConnect = 1<<9, + /// @brief Device state in JSON format + PXREADeviceStateJson = 1<<25, + /// @brief Custom message + PXREADeviceCustomMessage = 1<<26, + /// @brief Mask for enabling all callbacks + PXREAFullMask = 0xffffffff +}; + + + + + + + + +/// @brief Device state in JSON format +typedef struct { + /// @brief Device serial number + char devID[32]; + /// @brief JSON string containing device state information + char stateJson[16352]; +}PXREADevStateJson; + + +typedef struct { + /// @brief Device serial number + char devID[32]; + /// @brief Data size + uint64_t dataSize; + /// @brief Data pointer, valid within callback + const char* dataPtr; +}PXREADevCustomMessage; + + + + +/** + * @brief Client callback for receiving server messages + * @param context Callback context, passed from #Init parameter 1 context + * @param type Callback type + * @param status Callback status code + * @param userData Callback data pointer, determined by parameter 2 type + */ +typedef void(*pfPXREAClientCallback)(void* context,PXREAClientCallbackType type,int status,void* userData); + +/** + * @brief SDK initialization interface + * @details Connect to service and register callback + * @param context Callback context for passing user-defined data to callback function + * @param cliCallback Callback function pointer for listening to server messages + * @param mask Callback mask for filtering certain server messages + */ +PXREACLIENTSDK_EXPORT int PXREAInit(void* context,pfPXREAClientCallback cliCallback,unsigned mask); +/** + * @brief Termination interface + * @details Disconnect from service + */ +PXREACLIENTSDK_EXPORT int PXREADeinit(); + +/** + * @brief Send JSON format command to device + * @param devID Device serial number + * @param parameterJson Function and parameters in JSON format, refer to robot SDK documentation for specific usage + * @return 0 Success + * @return -1 Failure + */ +PXREACLIENTSDK_EXPORT int PXREADeviceControlJson(const char *devID,const char *parameterJson); +/** + * @brief Send byte stream to specified device + * @note This command is suitable for SDK caller's custom messages + * @param devID Device serial number + * @param data Starting address of byte stream + * @param len Length of byte stream + * @return 0 Success + * @return -1 Failure + */ +PXREACLIENTSDK_EXPORT int PXREASendBytesToDevice(const char* devID,const char* data,unsigned len); +#ifdef __cplusplus +} +#endif + +#endif // PXREACLIENTSDK_H diff --git a/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/aarch64/nlohmann/json.hpp b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/aarch64/nlohmann/json.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8b72ea6539f40e4e3f7762d17e30c67f2a8308ed --- /dev/null +++ b/third-party/GR00T-WholeBodyControl/external_dependencies/XRoboToolkit-PC-Service-Pybind_X86_and_ARM64/include/aarch64/nlohmann/json.hpp @@ -0,0 +1,24765 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 3 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 3 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // nullptr_t +#include // exception +#if JSON_DIAGNOSTICS + #include // accumulate +#endif +#include // runtime_error +#include // to_string +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + + +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-FileCopyrightText: 2016-2021 Evan Nemerson +// SPDX-License-Identifier: MIT + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions (except those affecting ABI) +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// #include + + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifndef JSON_HAS_STATIC_RTTI + #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 + #define JSON_HAS_STATIC_RTTI 1 + #else + #define JSON_HAS_STATIC_RTTI 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType, \ + class CustomBaseClass> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_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, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1); + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +// inspired from https://stackoverflow.com/a/26745591 +// allows to call any std function as if (e.g. with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 +#endif + +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != StringType::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +template +inline StringType escape(StringType s) +{ + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +template +static void unescape(StringType& s) +{ + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // size_t + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static JSON_INLINE_VARIABLE constexpr T value{}; +}; + +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif + +template +inline constexpr std::array make_array(Args&& ... args) +{ + return std::array {{static_cast(std::forward(args))...}}; +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval +#include // tuple +#include // char_traits + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // random_access_iterator_tag + +// #include + +// #include + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); + +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); + +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.3 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2023 Niels Lohmann +// SPDX-License-Identifier: MIT + +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector + + // #include + + + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN + + /*! + @brief default JSONSerializer template argument + + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; + + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector, // cppcheck-suppress syntaxError + class CustomBaseClass = void> + class basic_json; + + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; + + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; + + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; + + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; + + NLOHMANN_JSON_NAMESPACE_END + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +NLOHMANN_JSON_NAMESPACE_BEGIN +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ + +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; + +///////////////// +// char_traits // +///////////////// + +// Primary template of char_traits calls std char_traits +template +struct char_traits : std::char_traits +{}; + +// Explicitly define char traits for unsigned char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = unsigned char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(EOF); + } +}; + +// Explicitly define char traits for signed char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = signed char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(EOF); + } +}; + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + + static constexpr auto value = + conjunction < + is_constructible, + is_detected_exact>::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& + is_complete_type < + detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template