Download chess-sim/code/sim/make_scene.py from Machanize/playful: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/datasets/Machanize/playful/resolve/main/chess-sim/code/sim/make_scene.py
- Command line
-
hf download hf://datasets/Machanize/playful/chess-sim/code/sim/make_scene.py
-
curl -L -o make_scene.py https://huggingface.co/datasets/Machanize/playful/resolve/main/chess-sim/code/sim/make_scene.py
14.8 kB
| """Generate the MuJoCo chess scene for the SO-101 arm. | |
| Outputs: | |
| sim/assets/so101/so101.xml patched copy of the upstream arm (wrist camera added, base raised onto deck) | |
| sim/chess_scene.xml full scene: table, rover deck, arm, board with 64 named square sites, | |
| 32 free chess pieces, capture bin, cameras, lights | |
| Run: .venv/bin/python sim/make_scene.py | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from dataclasses import dataclass | |
| import re | |
| from pathlib import Path | |
| import numpy as np | |
| import scene_environment as environment | |
| HERE = Path(__file__).resolve().parent | |
| ARM_DIR = HERE / "assets" / "so101" | |
| UPSTREAM = ARM_DIR / "so101_camera_upstream.xml" | |
| ARM_OUT = ARM_DIR / "so101.xml" | |
| SCENE_OUT = HERE / "chess_scene.xml" | |
| # Arm parts whose single upstream collision hull is replaced by several hulls: | |
| # finger slabs (prepare_gripper_assets.py) and link decompositions (prepare_arm_collision.py). | |
| ARM_HULLS = json.loads((ARM_DIR / "collision" / "manifest.json").read_text())["parts"] | |
| # ---------------------------------------------------------------- geometry parameters (metres) | |
| DECK_H = 0.06 # rover deck height; arm base sits on top of it | |
| SQUARE = 0.025 # square size -> 20 cm board | |
| BOARD_T = 0.008 # board thickness | |
| BORDER = 0.012 # wooden border around the playing area | |
| BOARD_CENTER = (0.21, 0.0) # x forward from arm base, y left | |
| # Capture tray on the robot's right. At the Phase 1 spot (0.13, -0.20) the forearm hit | |
| # the rover camera stalk on 8 of 9 release points; here all 9 clear it by 7 mm or more, | |
| # and the tray stays at least 1 cm from the board under board-pose randomisation. | |
| BIN_CENTER = (0.20, -0.18) | |
| ROBOT_PLAYS = "black" # robot sits at rank 8 side; human at rank 1 | |
| class Layout: | |
| """Board and tray geometry. The default is the nominal scene (chess_scene.xml); | |
| phase 2 compiles random variants of it (piece_sets.sample_variant).""" | |
| square: float = SQUARE | |
| board_t: float = BOARD_T | |
| border: float = BORDER | |
| tray_half: tuple = (0.045, 0.035) # outer half extents of the tray floor | |
| tray_rim: float = 0.020 # height of the rim centreline | |
| NOMINAL = Layout() | |
| TIMESTEP = 1 / 600 # 20 physics steps per 30 fps frame | |
| # Stiff piece contacts: the gripper servo squeezes with up to 3.35 N m, about 40 N | |
| # at the fingertips, which sank 2-3 mm into softer contacts. solmix makes these | |
| # values dominate the arm's softer defaults in jaw-piece contacts. | |
| PIECE_SOLREF = "0.005 1" | |
| PIECE_SOLIMP = "0.97 0.995 0.0005" | |
| FILES = "abcdefgh" | |
| LIGHT_SQ = "0.98 0.97 0.94 1" | |
| DARK_SQ = "0.95 0.93 0.90 1" | |
| WHITE_PIECE = "0.93 0.88 0.76 1" | |
| BLACK_PIECE = "0.14 0.11 0.09 1" | |
| # Geometry, grasp points and estimated inertials come from the prepared mesh assets. | |
| CHESS_DIR = HERE / "assets" / "chess" | |
| PIECES = json.loads((CHESS_DIR / "manifest.json").read_text())["pieces"] | |
| BACK_RANK = ["rook", "knight", "bishop", "queen", "king", "bishop", "knight", "rook"] | |
| def square_xy(file_idx: int, rank_idx: int, square: float = SQUARE) -> tuple[float, float]: | |
| """Board-local xy of a square centre. file_idx 0..7 = a..h, rank_idx 0..7 = 1..8. | |
| Robot (black) faces +x toward the human. Rank 8 is nearest the robot (small x). | |
| From black's seat, file a is on the right (-y). The robot playing white is the | |
| board turned half a turn (phase 2 randomises the board yaw). | |
| """ | |
| x = (3.5 - rank_idx) * square # rank 1 farthest (+x), rank 8 nearest | |
| y = (file_idx - 3.5) * square # a at -y, h at +y | |
| if ROBOT_PLAYS == "white": | |
| x, y = -x, -y | |
| return x, y | |
| def lookat_xyaxes(pos, target, up=(0, 0, 1)) -> str: | |
| pos, target, up = map(np.asarray, (pos, target, up)) | |
| f = target - pos | |
| f /= np.linalg.norm(f) | |
| right = np.cross(f, up) | |
| right /= np.linalg.norm(right) | |
| up_cam = np.cross(right, f) | |
| return " ".join(f"{v:.5f}" for v in (*right, *up_cam)) | |
| def fmt(*vals) -> str: | |
| return " ".join(f"{v:.5f}" for v in vals) | |
| # ---------------------------------------------------------------- arm patch | |
| def write_arm() -> None: | |
| xml = UPSTREAM.read_text() | |
| # compiler settings come from the scene file | |
| xml = xml.replace('<compiler angle="radian" meshdir="." autolimits="true"/>', "") | |
| xml = xml.replace('<compiler angle="radian" meshdir="assets" autolimits="true"/>', "") | |
| # raise the base onto the rover deck | |
| assert '<body name="base" pos="0 0 0"' in xml | |
| xml = xml.replace('<body name="base" pos="0 0 0"', f'<body name="base" pos="0 0 {DECK_H}"') | |
| # wrist camera: the mount body's +z axis points along the lens. MuJoCo cameras look down -z, | |
| # so xyaxes maps cam x -> body x, cam y -> -body y, giving cam z = -body z with the jaws at the image bottom. | |
| cam = ('<camera name="wrist" pos="0 0 0.024" xyaxes="1 0 0 0 -1 0" fovy="80"/>\n' | |
| ' <!-- Part wrist_camera_so101_v1 -->') | |
| assert xml.count("<!-- Part wrist_camera_so101_v1 -->") == 1 | |
| xml = xml.replace("<!-- Part wrist_camera_so101_v1 -->", cam) | |
| # Only the printed-part finish changes; source meshes and joint/actuator data stay intact. | |
| xml = xml.replace('rgba="1 0.82 0.12 1"', | |
| 'rgba="0.88 0.67 0.13 1" specular="0.12" shininess="0.2"') | |
| # Contact shapes: each finger's single convex hull fills the gap between the jaws, and | |
| # the bulky links' hulls are 1.7-4.3x the part, so the hand "hits" the shoulder in empty | |
| # space. Each is replaced by several hulls in the same frame and class. | |
| hull_meshes = [] | |
| for part, info in ARM_HULLS.items(): | |
| files = info["collision"] | |
| pattern = re.compile(rf'( *)<geom type="mesh" class="collision" ((?:pos="[^"]*" quat="[^"]*" )?)' | |
| rf'mesh="{part}" (material="[^"]*")/>') | |
| match = pattern.search(xml) | |
| assert match and len(pattern.findall(xml)) == 1, part | |
| indent, frame, material = match.groups() | |
| geoms = [f'{indent}<geom type="mesh" class="collision" {frame}mesh="{part}_col_{i}" {material}/>' | |
| for i in range(len(files))] | |
| xml = xml[:match.start()] + "\n".join(geoms) + xml[match.end():] | |
| hull_meshes += [f' <mesh name="{part}_col_{i}" file="{f}"/>' for i, f in enumerate(files)] | |
| assert xml.count(" <asset>\n") == 1 | |
| xml = xml.replace(" <asset>\n", " <asset>\n" + "\n".join(hull_meshes) + "\n") | |
| ARM_OUT.write_text(xml) | |
| # ---------------------------------------------------------------- scene pieces | |
| def chess_assets() -> str: | |
| meshes = [] | |
| for kind, p in PIECES.items(): | |
| meshes.append(f'<mesh name="chess_{kind}" file="../chess/{p["visual"]}"/>') | |
| for i, file in enumerate(p["collision"]): | |
| meshes.append(f'<mesh name="chess_{kind}_col_{i}" file="../chess/{file}"/>') | |
| return "\n ".join(meshes) | |
| def piece_body(name: str, kind: str, color: str, x: float, y: float, z: float, | |
| quat: str = "1 0 0 0") -> str: | |
| p = PIECES[kind] | |
| # Group 2: visible mesh, never collides. Group 3: convex contact parts, | |
| # hidden by the renderer/viewer but still active in physics. | |
| geoms = [f'<geom name="{name}_visual" type="mesh" mesh="chess_{kind}" ' | |
| f'rgba="{color}" material="piece_mat" group="2" ' | |
| 'contype="0" conaffinity="0" mass="0"/>'] | |
| for i, _ in enumerate(p["collision"]): | |
| geoms.append(f'<geom name="{name}_collision_{i}" type="mesh" ' | |
| f'mesh="chess_{kind}_col_{i}" group="3" rgba="0.2 0.7 0.3 0.35" ' | |
| 'mass="0" friction="0.7 0.005 0.0001" condim="4" ' | |
| f'solref="{PIECE_SOLREF}" solimp="{PIECE_SOLIMP}" solmix="1000"/>') | |
| inertia = " ".join(f"{v:.10g}" for v in p["fullinertia_kg_m2"]) | |
| com = " ".join(f"{v:.10g}" for v in p["center_of_mass_m"]) | |
| return f""" <body name="{name}" pos="{fmt(x, y, z)}" quat="{quat}"> | |
| <freejoint name="{name}_free"/> | |
| <inertial pos="{com}" mass="{p['mass_kg']}" fullinertia="{inertia}"/> | |
| <site name="{name}_grasp" pos="0 0 {p['grasp_z_m']:.7f}" size="0.002" group="4"/> | |
| {chr(10).join(geoms)} | |
| </body>""" | |
| def build_scene(layout: Layout = NOMINAL) -> str: | |
| SQUARE, BOARD_T, BORDER = layout.square, layout.board_t, layout.border | |
| bx, by = BOARD_CENTER | |
| half = 4 * SQUARE | |
| board_top = BOARD_T # board body origin at table level; squares' top face at BOARD_T | |
| # squares + sites (children of board body) | |
| squares, sites = [], [] | |
| for r in range(8): | |
| for f in range(8): | |
| x, y = square_xy(f, r, SQUARE) | |
| name = f"{FILES[f]}{r+1}" | |
| dark = (f + r) % 2 == 0 | |
| material = "dark_square_mat" if dark else "light_square_mat" | |
| squares.append( | |
| f'<geom name="sq_{name}" type="box" size="{SQUARE/2:.4f} {SQUARE/2:.4f} {BOARD_T/2:.4f}" ' | |
| f'pos="{fmt(x, y, BOARD_T/2)}" rgba="{DARK_SQ if dark else LIGHT_SQ}" material="{material}"/>' | |
| ) | |
| sites.append(f'<site name="sq_{name}" pos="{fmt(x, y, BOARD_T)}" size="0.003" group="4"/>') | |
| # pieces in the starting position (world coordinates) | |
| pieces, piece_qpos = [], [] | |
| for f in range(8): | |
| for color, rank_back, rank_pawn, tag in (("white", 0, 1, "w"), ("black", 7, 6, "b")): | |
| rgba = WHITE_PIECE if color == "white" else BLACK_PIECE | |
| kind = BACK_RANK[f] | |
| # The normalized knight faces +y; turn it toward the opponent (+x for black). | |
| toward_positive_x = (color == "black") == (ROBOT_PLAYS == "black") | |
| quat = "0.7071067812 0 0 -0.7071067812" if toward_positive_x else "0.7071067812 0 0 0.7071067812" | |
| x, y = square_xy(f, rank_back, SQUARE) | |
| pieces.append(piece_body(f"{tag}_{kind}_{FILES[f]}", kind, rgba, bx + x, by + y, board_top + 0.0005, quat)) | |
| piece_qpos.append(f"{fmt(bx + x, by + y, board_top + 0.0005)} {quat}") | |
| x, y = square_xy(f, rank_pawn, SQUARE) | |
| pieces.append(piece_body(f"{tag}_pawn_{FILES[f]}", "pawn", rgba, bx + x, by + y, board_top + 0.0005, quat)) | |
| piece_qpos.append(f"{fmt(bx + x, by + y, board_top + 0.0005)} {quat}") | |
| # Folded rest pose. The earlier (-1.15, 1.1, 1.5) put the gripper servo's contact hull | |
| # 1 mm inside the shoulder's; this one keeps 7 mm under +-0.06 rad of jitter. | |
| home_arm = "0 -1.2 0.95 1.45 0 0.3" | |
| # cameras | |
| overhead_pos = environment.OVERHEAD_POS | |
| overhead_xy = lookat_xyaxes(overhead_pos, (bx, by, BOARD_T), up=(-1, 0, 0)) | |
| rover_xy = lookat_xyaxes(environment.ROVER_CAMERA_POS, (bx, by, BOARD_T + 0.01)) | |
| side_xy = lookat_xyaxes((0.58, -0.85, 0.62), (0.12, 0.0, 0.18)) | |
| human_xy = lookat_xyaxes((0.72, 0.0, 0.32), (0.22, 0.0, 0.0)) | |
| return f"""<mujoco model="so101_chess"> | |
| <!-- Generated by sim/make_scene.py. Do not edit by hand. --> | |
| <compiler angle="radian" meshdir="assets/so101" autolimits="true"/> | |
| <option timestep="{TIMESTEP:.10f}" cone="elliptic" impratio="10" gravity="0 0 -9.81"/> | |
| <statistic center="0.12 0 0.18" extent="0.9"/> | |
| <visual> | |
| <headlight active="0"/> | |
| <global azimuth="150" elevation="-25" offwidth="1280" offheight="960"/> | |
| <quality shadowsize="8192" offsamples="4"/> | |
| <map znear="0.001" shadowclip="1" shadowscale="0.6"/> | |
| </visual> | |
| <asset> | |
| {chess_assets()} | |
| <material name="piece_mat" specular="0.25" shininess="0.35"/> | |
| <texture type="skybox" builtin="gradient" rgb1="0.70 0.72 0.74" rgb2="0.78 0.79 0.78" width="256" height="1536"/> | |
| {environment.assets()} | |
| </asset> | |
| <include file="assets/so101/so101.xml"/> | |
| <worldbody> | |
| <!-- Window key light, ceiling fill, and subtle room bounce. No mirror planes. --> | |
| <light name="window_key" pos="0.20 -0.65 1.10" dir="0 0.5 -1" diffuse="0.34 0.33 0.31" specular="0.10 0.10 0.10" cutoff="75" castshadow="true"/> | |
| <light name="ceiling_fill" pos="0.2 0.35 1.25" dir="0 -0.2 -1" diffuse="0.15 0.16 0.18" specular="0.03 0.03 0.03" cutoff="90" castshadow="false"/> | |
| <light name="room_bounce" directional="true" dir="0 0 -1" ambient="0.55 0.55 0.55" diffuse="0 0 0" specular="0 0 0" castshadow="false"/> | |
| <!-- Off in the nominal scene; phase 2 lighting randomisation switches them on. --> | |
| <light name="ceiling_2" pos="-0.2 -0.3 1.3" dir="0 0 -1" diffuse="0 0 0" specular="0 0 0" cutoff="70" castshadow="false"/> | |
| <light name="desk_lamp" pos="0.3 0.45 0.45" dir="0 -0.5 -1" diffuse="0 0 0" specular="0 0 0" cutoff="45" castshadow="false"/> | |
| <light name="sun" directional="true" dir="0.3 0.4 -1" diffuse="0 0 0" specular="0 0 0" castshadow="false"/> | |
| <light name="fill_2" pos="0.9 0.0 0.9" dir="-1 0 -0.6" diffuse="0 0 0" specular="0 0 0" cutoff="80" castshadow="false"/> | |
| {environment.room()} | |
| {environment.stand(DECK_H, rover_xy)} | |
| {environment.camera_rig(overhead_pos, overhead_xy)} | |
| {environment.cables()} | |
| {environment.clutter()} | |
| <!-- chessboard: static body, moved by editing model body_pos/body_quat at reset for randomisation --> | |
| <body name="board" pos="{fmt(bx, by, 0)}"> | |
| <site name="board_center" pos="0 0 {BOARD_T}" size="0.004" group="4"/> | |
| <geom name="board_border" type="box" size="{half+BORDER:.4f} {half+BORDER:.4f} {(BOARD_T-0.001)/2:.4f}" pos="0 0 {(BOARD_T-0.001)/2:.4f}" material="border_mat"/> | |
| {chr(10).join(" " + s for s in squares)} | |
| {chr(10).join(" " + s for s in sites)} | |
| {environment.board_details(half, BORDER, BOARD_T)} | |
| </body> | |
| <!-- capture tray on the robot's right --> | |
| <body name="bin" pos="{fmt(BIN_CENTER[0], BIN_CENTER[1], 0)}"> | |
| {environment.tray(*layout.tray_half, layout.tray_rim)} | |
| <site name="bin_drop" pos="0 0 0.05" size="0.004" group="4"/> | |
| </body> | |
| <!-- pieces: free bodies, starting position --> | |
| {chr(10).join(pieces)} | |
| <!-- viewing cameras --> | |
| <camera name="side" pos="0.58 -0.85 0.62" xyaxes="{side_xy}" fovy="45"/> | |
| <camera name="human" pos="0.72 0.0 0.32" xyaxes="{human_xy}" fovy="45"/> | |
| <camera name="scene" pos="0.94 -1.08 0.80" xyaxes="{lookat_xyaxes((0.94, -1.08, 0.80), (0.12, 0.0, 0.16))}" fovy="45"/> | |
| <camera name="board_detail" pos="0.46 -0.30 0.27" xyaxes="{lookat_xyaxes((0.46, -0.30, 0.27), (bx, by, 0.015))}" fovy="36"/> | |
| </worldbody> | |
| <keyframe> | |
| <!-- arm folded at home, pieces in the starting position; ctrl holds the arm there --> | |
| <key name="home" qpos="{home_arm} {' '.join(piece_qpos)}" ctrl="{home_arm}"/> | |
| </keyframe> | |
| </mujoco> | |
| """ | |
| def main() -> None: | |
| write_arm() | |
| SCENE_OUT.write_text(build_scene()) | |
| import mujoco | |
| m = mujoco.MjModel.from_xml_path(str(SCENE_OUT)) | |
| print(f"wrote {SCENE_OUT.relative_to(HERE.parent)}: nbody={m.nbody} ngeom={m.ngeom} nsite={m.nsite} ncam={m.ncam} nq={m.nq}") | |
| if __name__ == "__main__": | |
| main() | |