MuJoCo Spec Editing: Building & Modifying Models
[!TIP]
Official MuJoCo documentation (doc/*.rst): Read short chapters like
../../programming/modeledit.rst
(.. _meOverview:) and ../../overview.rst directly
when in a MuJoCo checkout; for large reference files like
../../modeling.rst (.. _ProceduralModeling:,
.. _Mechanisms:, .. _CTuning:),
../../XMLreference.rst,
../../python.rst (.. _PyModelEdit:), and
../../APIreference/functions.rst, grep
the literal .. _Label: anchor. Outside a checkout, the same doc/*.rst tree
ships offline in pip install mujoco at
pathlib.Path(mujoco.__file__).parent / 'doc'; otherwise fetch
https://mujoco.readthedocs.io/en/latest/<path>.html (or /en/stable/ for
released pages; functions.rst renders inside
APIreference/APIfunctions.html, and Sphinx anchors lowercase the label,
e.g. .. _meOverview: → #meoverview) and browse repo paths (../../../)
under https://github.com/google-deepmind/mujoco/tree/main/.
Related skills:
- mujoco-deformables — Deformable
<flexcomp>,
<flex>, and <skin> modeling (1D rods, 2D cloth/shells, 3D FEM soft
bodies, and attachments).
- mujoco-python — Simulation lifecycle, stepping, and
diagnostics.
- mujoco-rendering — Offscreen image rendering and
camera setup.
- mujoco-studio — Interactive viewers and Studio
plugins.
1. Procedural Modeling with MjSpec
MjSpec is a mutable C++ and Python data structure that mirrors the MJCF XML
schema, allowing models to be constructed and modified programmatically.
import mujoco
spec = mujoco.MjSpec()
# Add a body with a freejoint and sphere geom
body = spec.worldbody.add_body(name='ball', pos=[0, 0, 1.0])
body.add_freejoint()
body.add_geom(type=mujoco.mjtGeom.mjGEOM_SPHERE, size=[0.1], rgba=[1, 0, 0, 1])
# Compile to MjModel
model = spec.compile()
In C++:
#include <mujoco/mujoco.h>
mjSpec* spec = mj_makeSpec();
mjsBody* body = mjs_addBody(mjs_findBody(spec, "world"), nullptr);
body->pos[2] = 1.0;
mjs_addFreeJoint(body);
mjsGeom* geom = mjs_addGeom(body, nullptr);
geom->type = mjGEOM_SPHERE;
geom->size[0] = 0.1;
mjModel* model = mj_compile(spec, nullptr);
if (!model) printf("%s\n", mjs_getError(spec));
mj_deleteSpec(spec);
2. Building Hierarchies: Bodies, Geoms, Joints & Sites
Adding Elements
body = spec.worldbody.add_body(name='arm', pos=[0, 0, 0.5])
# Geom with capsule shape
geom = body.add_geom(
name='arm_geom',
type=mujoco.mjtGeom.mjGEOM_CAPSULE,
size=[0.05, 0.25],
rgba=[0.2, 0.6, 1.0, 1.0],
)
# Hinge joint
joint = body.add_joint(
name='shoulder',
type=mujoco.mjtJoint.mjJNT_HINGE,
axis=[0, 1, 0],
range=[-1.57, 1.57],
)
# Sensor site and camera
site = body.add_site(name='grip_site', pos=[0, 0, 0.25])
cam = body.add_camera(name='tool_cam', pos=[0, -0.5, 0.25], xyaxes=[1, 0, 0, 0, 0, 1])
Geom Dimensions Reference
| Geom Type |
size Parameter Semantics |
mjGEOM_SPHERE |
[radius] |
mjGEOM_CAPSULE |
[radius, half_length] (or [radius] if using fromto) |
mjGEOM_CYLINDER |
[radius, half_length] (or [radius] if using fromto) |
mjGEOM_BOX |
[half_x, half_y, half_z] |
mjGEOM_ELLIPSOID |
[radius_x, radius_y, radius_z] |
mjGEOM_PLANE |
[half_x, half_y, grid_spacing] |
[!WARNING]
When fromto=[x1, y1, z1, x2, y2, z2] is specified for capsules or cylinders,
size takes only one value ([radius]); length is calculated from endpoints.
Orientation Keywords
Only one orientation specification can be used at a time:
quat=[w, x, y, z] (native representation)
euler=[a1, a2, a3] (sequence set by spec.compiler.eulerseq, default 'xyz')
axisangle=[x, y, z, angle]
xyaxes=[x_x, x_y, x_z, y_x, y_y, y_z]
zaxis=[x, y, z]
Angles in euler and axisangle are in degrees unless
spec.compiler.degree = False (see modeling.rst,
.. _COrientation:, and XMLreference.rst,
.. _body-geom:).
3. Sub-model Composition & Attachments
Compose models modularly by attaching sub-specs with prefix namespaces (see
programming/modeledit.rst,
.. _meAttachment: and .. _meAttributeMerging:):
parent = mujoco.MjSpec()
child = mujoco.MjSpec()
child_body = child.worldbody.add_body(name='gripper')
child_body.add_geom(size=[0.05], type=mujoco.mjtGeom.mjGEOM_SPHERE)
# Attach child spec to a mount site on the parent
mount_site = parent.worldbody.add_site(name='mount', pos=[0, 0, 1.0])
parent.attach(child, site=mount_site, prefix='gripper_')
# Child body is renamed to 'gripper_gripper' in parent
Cross-Spec Equality Constraints
When linking bodies from two different child specs (e.g. dual-arm setups),
attach both children to the common parent first, then declare constraints on the
parent spec:
left_mount = parent.worldbody.add_frame(pos=[0, 0.3, 0])
right_mount = parent.worldbody.add_frame(pos=[0, -0.3, 0])
parent.attach(arm1_spec, frame=left_mount, prefix='left_')
parent.attach(arm2_spec, frame=right_mount, prefix='right_')
eq = parent.add_equality(
type=mujoco.mjtEq.mjEQ_CONNECT,
objtype=mujoco.mjtObj.mjOBJ_BODY,
name1='left_hand',
name2='right_hand',
)
eq.data[0:3] = [0, 0, 0] # connect anchor, in name1's body frame
[!NOTE]
attach() requires exactly one of frame= or site=; omitting both raises
ValueError.
4. Deleting & Dynamically Modifying Elements
Deleting Elements
Pass the element object to spec.delete(); deleting a body removes its subtree:
spec.delete(spec.body('unwanted_body'))
spec.delete(spec.geom('old_geom'))
spec.delete(spec.joint('redundant_joint'))
spec.delete(spec.actuator('motor'))
State-Preserving Recompilation
When changing model architecture at runtime, use spec.recompile to keep
existing physics state:
# Add new tool to robot
spec.worldbody.add_geom(name='tool_tip', size=[0.02], type=mujoco.mjtGeom.mjGEOM_SPHERE)
# Recompile keeping positions/velocities intact
model, data = spec.recompile(model, data)
5. Actuators & Servos
Always explicitly set the transmission type (trntype):
# 1. Torque Motor
motor = spec.add_actuator(
name='torque_actuator',
target='shoulder',
trntype=mujoco.mjtTrn.mjTRN_JOINT,
)
motor.set_to_motor()
# 2. Stiff Position Servo (Recommended for position control)
servo = spec.add_actuator(
name='pos_servo',
target='shoulder',
trntype=mujoco.mjtTrn.mjTRN_JOINT,
)
servo.set_to_position(kp=200.0, dampratio=1.0) # Pair with implicitfast (kv defaults to 0)
servo.forcelimited = True
servo.forcerange = [-50.0, 50.0] # Peak torque in Nm
servo.ctrllimited = True
servo.ctrlrange = [-1.57, 1.57] # Target angle in radians
# 3. Velocity Actuator
vel = spec.add_actuator(
name='vel_driver',
target='wheel_joint',
trntype=mujoco.mjtTrn.mjTRN_JOINT,
)
vel.set_to_velocity(kv=10.0)
[!CAUTION]
The helper functions set_to_position() and set_to_motor() configure gains
but do not set the transmission. You must always specify
trntype=mujoco.mjtTrn.mjTRN_JOINT (or another valid transmission type). See
modeling.rst (.. _CActuators:, .. _CActShortcuts:)
and XMLreference.rst (.. _actuator:).
6. Default Classes (Inheritance & Styling)
Default classes (MjsDefault) provide cascaded styling and properties (see
modeling.rst, .. _CDefault:, and
programming/modeledit.rst, .. _meDefault:):
# Create child class under root 'main' class
main_class = spec.default
rubber = spec.add_default('rubber', main_class)
rubber.geom.friction = [1.5, 0.01, 0.001]
rubber.geom.density = 1200.0
# Assign class at creation
body.add_geom(rubber, name='tire', type=mujoco.mjtGeom.mjGEOM_CYLINDER, size=[0.1, 0.05])
# Assign class post-creation (must pass MjsDefault object, NOT a string)
other_geom.classname = rubber
Baseline Tuning Overrides (<option> & Root <default>)
Several internal defaults (Euler, pyramidal cones with impratio=1, soft
solref="0.02 1", zero joint armature/damping) are kept for backwards
compatibility rather than new robotics models. Override them at the top of a
project (full rationale and priority-ordered parameter guide in
modeling.rst, .. _CTuning:, .. _CTuningDefaults:,
.. _CTuningGlobal:, .. _CTuningModel:):
spec.option.integrator = mujoco.mjtIntegrator.mjINT_IMPLICITFAST # DISCRETE for flex elasticity
spec.option.cone = mujoco.mjtCone.mjCONE_ELLIPTIC
spec.option.impratio = 10.0
spec.default.geom.solref = [0.005, 1.0] # Keep solref[0] >= 2 * timestep
spec.default.joint.armature = 0.01 # Reflected rotor inertia (I_rotor * N^2)
spec.default.joint.damping = 0.1 # Implicit in M + h*D at zero solver cost
Keep the default solimp: raising solimp[0] (e.g. to 0.95) halves rest
penetration and creep but costs solver iterations, so reach for it only after
solref and elliptic cones.
7. Collisions & Friction Tuning
Collision Filtering Bitmasks
Two geoms collide if and only if:
(g1.contype & g2.conaffinity) || (g2.contype & g1.conaffinity)
# Visual-only geom: never collides; set mass=0 if omitting <inertial> so it
# does not add water-density (1000 kg/m^3) mass (inertiagrouprange defaults to "0 5")
body.add_geom(size=[0.1], contype=0, conaffinity=0, group=1, mass=0)
# Team A collides only with Team B
geom_a = body.add_geom(size=[0.1], contype=1, conaffinity=2)
geom_b = body.add_geom(size=[0.1], contype=2, conaffinity=1)
Contact Dimension (condim) & Friction
condim |
Active Friction Components |
Friction Index Used |
| 1 |
Normal force only (frictionless) |
— |
| 3 |
Tangential sliding friction |
friction[0] |
| 4 |
Tangential + torsional (twisting) |
friction[0:2] |
| 6 |
Tangential + torsional + rolling |
friction[0:3] |
# High-friction contact for grasping
finger.add_geom(
type=mujoco.mjtGeom.mjGEOM_CAPSULE,
size=[0.01, 0.03],
condim=4,
friction=[1.2, 0.02, 0.0001],
)
For contact softness, solver impedance/reference tuning (solref, solimp,
priority/mixing), and why parent-child geoms omit collisions by default, read
modeling.rst (.. _CTuning:, .. _CTuningModel:,
.. _CSolver:, .. _CContact:) and overview.rst
(.. _SurprisingCollisions:, .. _Soft:, .. _Units:).
8. Procedural Meshes, Materials & Sensors
Procedural Meshes
vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32)
faces = np.array([[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]], dtype=np.int32)
mesh = spec.add_mesh(name='tetra', uservert=vertices.flatten(), userface=faces.flatten())
body.add_geom(type=mujoco.mjtGeom.mjGEOM_MESH, meshname='tetra')
Concave collision meshes are replaced by their convex hulls (unless using SDF
plugins); prefer primitives (sphere, capsule, box, cylinder) for both
speed and cleaner normals, or pre-decompose non-convex assets offline with
CoACD or mjfit (see computation/index.rst,
.. _coChecking: and .. _coDecomposition:).
Procedural Sensors
# IMU Accelerometer and Gyroscope
spec.add_sensor(name='torso_acc', type=mujoco.mjtSensor.mjSENS_ACCELEROMETER,
objtype=mujoco.mjtObj.mjOBJ_SITE, objname='imu_site')
spec.add_sensor(name='torso_gyro', type=mujoco.mjtSensor.mjSENS_GYRO,
objtype=mujoco.mjtObj.mjOBJ_SITE, objname='imu_site')
9. Common Gotchas & Best Practices
- Non-zero geom sizes: Geoms with radius or half-extents of zero cause
immediate compilation errors.
classname takes an object: geom.classname = 'rubber' raises a
TypeError. Pass the MjsDefault instance: geom.classname = rubber.
- Always assign
recompile(): spec.recompile(m, d) produces newly
allocated model and data instances. Reassign them:
m, d = spec.recompile(m, d) (see
programming/modeledit.rst,
.. _meRecompilation:).
- Declare high-contact "hub" bodies first (reverse-Cholesky fill-in):
When a moving body with DOFs (e.g., an actuated tray, sieve, container, or
robot base) contacts many independent clutter bodies, declare the hub body
before the independent bodies so
mju_cholFactorSparse factors the
mass/Hessian arrowhead in $O(N)$ with zero fill-in rather than $O(N^3)$.
Static geoms on worldbody have 0 DOFs and are unaffected — see the full
derivation in modeling.rst (.. _CBodyOrdering:).
- Never add joints (including
<freejoint/>) to the parent body of an
unpinned <flexcomp> (except dof="2d" or "radial"). See
mujoco-deformables for all <flexcomp>, <pin>,
and <elasticity> rules.
10. Reference Models & Key References
Reference MJCF Models & Fixtures
Before authoring complex mechanisms or specialized elements from scratch, check
existing models:
- Built-in showcase models (
../../../model/, or online at
https://github.com/google-deepmind/mujoco/tree/main/model):
model/humanoid/, model/tendon_arm/arm26.xml, model/car/car.xml,
model/slider_crank/slider_crank.xml, model/flex/ (cables, cloth, soft
bodies — see mujoco-deformables),
model/replicate/ (newton_cradle.xml, particle.xml, bunnies.xml),
model/plugin/ (actuator, sensor, SDF), model/tactile/,
model/adhesion/, model/sleep/, model/speculative/, and
model/plastic/.
- MuJoCo Menagerie (models.rst,
.. _Menagerie:):
Production robot descriptions (Franka Panda/FR3, UR5e/UR10e, Unitree
G1/H1/Go2, Spot, Barkour, Shadow Hand, Robotiq 2F-85, ALOHA 2, Skydio X2,
Flybody) at https://github.com/google-deepmind/mujoco_menagerie.
- Minimal test fixtures (
../../../test/**/testdata/, or online under
https://github.com/google-deepmind/mujoco/tree/main/test): Focused
single-feature XMLs in test/user/testdata/ (MjSpec & compiler),
test/xml/testdata/ (parent.xml / child.xml attachment fixtures,
OpenUSD), and test/engine/testdata/ (collisions.xml, connect.xml,
equality_site.xml, catenary.xml).
Documentation
- MjSpec & Procedural Model Editing
(
.. _meOverview:, .. _meAttachment:, .. _meAttributeMerging:,
.. _meDefault:, .. _meRecompilation:)
- Python Model Editing & OpenUSD Bindings
(
.. _PyModelEdit:, .. _PyEditConvenience:, .. _PyMJCF:,
.. _PyUSDexport:) and OpenUSD Guide
- MJCF Modeling Guide (
.. _CDefault:,
.. _COrientation:, .. _CSolver:, .. _CContact:, .. _CBodyOrdering:,
.. _CActuators:, .. _CDeformable:, .. _CTuning:,
.. _CTuningDefaults:, .. _CTuningGlobal:, .. _CTuningModel:) and
Modeling Pitfalls & Units (.. _Clarifications:,
.. _Units:, .. _SurprisingCollisions:, .. _Soft:)
- MJCF XML Schema Reference (
.. _body-geom:,
.. _body-joint:, .. _actuator:, .. _equality:, .. _body-flexcomp:,
.. _replicate:)
- Engine Plugins & Resource Providers
(
.. _exExtension:, .. _exSDF:)
- C Model Editing API Functions
(
.. _Parseandcompile:, .. _Attachment:, .. _AddTreeElements:,
.. _AddNonTreeElements:)
Source Code & Notebook Examples
1---2name: mujoco-spec-editing3description: >-4 MuJoCo procedural model authoring, editing, and tuning with MjSpec5 (`mujoco.MjSpec` in Python and `mjSpec` in C++):6 bodies, geoms, joints, sites, cameras, sub-model attachment with prefix7 namespaces, actuators (position servos, motors, velocity drives, trntype),8 baseline option/default overrides (implicitfast, elliptic cones, solref,9 solimp, armature, damping), collision bitmasks (contype, conaffinity),10 friction (condim), default classes (MjsDefault), procedural meshes, deletion,11 spec recompilation (spec.recompile). Use only for authoring or tuning MuJoCo12 MJCF/MjSpec13 models, adding bodies/geoms/actuators, and attaching sub-models.14 Don't use for designing custom non-MuJoCo XML/scene-graph APIs when MuJoCo15 `MjSpec` is not used, deformable flex/cloth/cable modeling16 (mujoco-deformables), stepping simulations (mujoco-python), or rendering17 (mujoco-rendering).18metadata:19 source: https://skillmd.com/skills/google-deepmind/mujoco-spec-editing20---2122# MuJoCo Spec Editing: Building & Modifying Models2324> [!TIP]25>26> **Official MuJoCo documentation (`doc/*.rst`):** Read short chapters like27> [`../../programming/modeledit.rst`](../../programming/modeledit.rst)28> (`.. _meOverview:`) and [`../../overview.rst`](../../overview.rst) directly29> when in a MuJoCo checkout; for large reference files like30> [`../../modeling.rst`](../../modeling.rst) (`.. _ProceduralModeling:`,31> `.. _Mechanisms:`, `.. _CTuning:`),32> [`../../XMLreference.rst`](../../XMLreference.rst),33> [`../../python.rst`](../../python.rst) (`.. _PyModelEdit:`), and34> [`../../APIreference/functions.rst`](../../APIreference/functions.rst), grep35> the literal `.. _Label:` anchor. Outside a checkout, the same `doc/*.rst` tree36> ships offline in `pip install mujoco` at37> `pathlib.Path(mujoco.__file__).parent / 'doc'`; otherwise fetch38> `https://mujoco.readthedocs.io/en/latest/<path>.html` (or `/en/stable/` for39> released pages; `functions.rst` renders inside40> `APIreference/APIfunctions.html`, and Sphinx anchors lowercase the label,41> e.g. `.. _meOverview:` → `#meoverview`) and browse repo paths (`../../../`)42> under `https://github.com/google-deepmind/mujoco/tree/main/`.43>44> **Related skills:**45>46> - [mujoco-deformables](../deformables/SKILL.md) — Deformable `<flexcomp>`,47> `<flex>`, and `<skin>` modeling (1D rods, 2D cloth/shells, 3D FEM soft48> bodies, and attachments).49> - [mujoco-python](../python/SKILL.md) — Simulation lifecycle, stepping, and50> diagnostics.51> - [mujoco-rendering](../rendering/SKILL.md) — Offscreen image rendering and52> camera setup.53> - [mujoco-studio](../studio/SKILL.md) — Interactive viewers and Studio54> plugins.5556## 1. Procedural Modeling with MjSpec5758`MjSpec` is a mutable C++ and Python data structure that mirrors the MJCF XML59schema, allowing models to be constructed and modified programmatically.6061```python62import mujoco6364spec = mujoco.MjSpec()6566# Add a body with a freejoint and sphere geom67body = spec.worldbody.add_body(name='ball', pos=[0, 0, 1.0])68body.add_freejoint()69body.add_geom(type=mujoco.mjtGeom.mjGEOM_SPHERE, size=[0.1], rgba=[1, 0, 0, 1])7071# Compile to MjModel72model = spec.compile()73```7475In C++:76```cpp77#include <mujoco/mujoco.h>7879mjSpec* spec = mj_makeSpec();80mjsBody* body = mjs_addBody(mjs_findBody(spec, "world"), nullptr);81body->pos[2] = 1.0;82mjs_addFreeJoint(body);83mjsGeom* geom = mjs_addGeom(body, nullptr);84geom->type = mjGEOM_SPHERE;85geom->size[0] = 0.1;8687mjModel* model = mj_compile(spec, nullptr);88if (!model) printf("%s\n", mjs_getError(spec));89mj_deleteSpec(spec);90```9192## 2. Building Hierarchies: Bodies, Geoms, Joints & Sites9394### Adding Elements9596```python97body = spec.worldbody.add_body(name='arm', pos=[0, 0, 0.5])9899# Geom with capsule shape100geom = body.add_geom(101 name='arm_geom',102 type=mujoco.mjtGeom.mjGEOM_CAPSULE,103 size=[0.05, 0.25],104 rgba=[0.2, 0.6, 1.0, 1.0],105)106107# Hinge joint108joint = body.add_joint(109 name='shoulder',110 type=mujoco.mjtJoint.mjJNT_HINGE,111 axis=[0, 1, 0],112 range=[-1.57, 1.57],113)114115# Sensor site and camera116site = body.add_site(name='grip_site', pos=[0, 0, 0.25])117cam = body.add_camera(name='tool_cam', pos=[0, -0.5, 0.25], xyaxes=[1, 0, 0, 0, 0, 1])118```119120### Geom Dimensions Reference121122| Geom Type | `size` Parameter Semantics |123| :--- | :--- |124| `mjGEOM_SPHERE` | `[radius]` |125| `mjGEOM_CAPSULE` | `[radius, half_length]` (or `[radius]` if using `fromto`) |126| `mjGEOM_CYLINDER` | `[radius, half_length]` (or `[radius]` if using `fromto`) |127| `mjGEOM_BOX` | `[half_x, half_y, half_z]` |128| `mjGEOM_ELLIPSOID`| `[radius_x, radius_y, radius_z]` |129| `mjGEOM_PLANE` | `[half_x, half_y, grid_spacing]` |130131> [!WARNING]132>133> When `fromto=[x1, y1, z1, x2, y2, z2]` is specified for capsules or cylinders,134> `size` takes only **one value** (`[radius]`); length is calculated from endpoints.135136### Orientation Keywords137138Only **one** orientation specification can be used at a time:139- `quat=[w, x, y, z]` (native representation)140- `euler=[a1, a2, a3]` (sequence set by `spec.compiler.eulerseq`, default `'xyz'`)141- `axisangle=[x, y, z, angle]`142- `xyaxes=[x_x, x_y, x_z, y_x, y_y, y_z]`143- `zaxis=[x, y, z]`144145Angles in `euler` and `axisangle` are in degrees unless146`spec.compiler.degree = False` (see [modeling.rst](../../modeling.rst),147`.. _COrientation:`, and [XMLreference.rst](../../XMLreference.rst),148`.. _body-geom:`).149150## 3. Sub-model Composition & Attachments151152Compose models modularly by attaching sub-specs with prefix namespaces (see153[programming/modeledit.rst](../../programming/modeledit.rst),154`.. _meAttachment:` and `.. _meAttributeMerging:`):155156```python157parent = mujoco.MjSpec()158child = mujoco.MjSpec()159160child_body = child.worldbody.add_body(name='gripper')161child_body.add_geom(size=[0.05], type=mujoco.mjtGeom.mjGEOM_SPHERE)162163# Attach child spec to a mount site on the parent164mount_site = parent.worldbody.add_site(name='mount', pos=[0, 0, 1.0])165parent.attach(child, site=mount_site, prefix='gripper_')166# Child body is renamed to 'gripper_gripper' in parent167```168169### Cross-Spec Equality Constraints170171When linking bodies from two different child specs (e.g. dual-arm setups),172attach both children to the common parent first, then declare constraints on the173parent spec:174175```python176left_mount = parent.worldbody.add_frame(pos=[0, 0.3, 0])177right_mount = parent.worldbody.add_frame(pos=[0, -0.3, 0])178parent.attach(arm1_spec, frame=left_mount, prefix='left_')179parent.attach(arm2_spec, frame=right_mount, prefix='right_')180181eq = parent.add_equality(182 type=mujoco.mjtEq.mjEQ_CONNECT,183 objtype=mujoco.mjtObj.mjOBJ_BODY,184 name1='left_hand',185 name2='right_hand',186)187eq.data[0:3] = [0, 0, 0] # connect anchor, in name1's body frame188```189190> [!NOTE]191>192> `attach()` requires exactly one of `frame=` or `site=`; omitting both raises193> `ValueError`.194195## 4. Deleting & Dynamically Modifying Elements196197### Deleting Elements198199Pass the element object to `spec.delete()`; deleting a body removes its subtree:200201```python202spec.delete(spec.body('unwanted_body'))203spec.delete(spec.geom('old_geom'))204spec.delete(spec.joint('redundant_joint'))205spec.delete(spec.actuator('motor'))206```207208### State-Preserving Recompilation209210When changing model architecture at runtime, use `spec.recompile` to keep211existing physics state:212213```python214# Add new tool to robot215spec.worldbody.add_geom(name='tool_tip', size=[0.02], type=mujoco.mjtGeom.mjGEOM_SPHERE)216217# Recompile keeping positions/velocities intact218model, data = spec.recompile(model, data)219```220221## 5. Actuators & Servos222223Always explicitly set the transmission type (`trntype`):224225```python226# 1. Torque Motor227motor = spec.add_actuator(228 name='torque_actuator',229 target='shoulder',230 trntype=mujoco.mjtTrn.mjTRN_JOINT,231)232motor.set_to_motor()233234# 2. Stiff Position Servo (Recommended for position control)235servo = spec.add_actuator(236 name='pos_servo',237 target='shoulder',238 trntype=mujoco.mjtTrn.mjTRN_JOINT,239)240servo.set_to_position(kp=200.0, dampratio=1.0) # Pair with implicitfast (kv defaults to 0)241servo.forcelimited = True242servo.forcerange = [-50.0, 50.0] # Peak torque in Nm243servo.ctrllimited = True244servo.ctrlrange = [-1.57, 1.57] # Target angle in radians245246# 3. Velocity Actuator247vel = spec.add_actuator(248 name='vel_driver',249 target='wheel_joint',250 trntype=mujoco.mjtTrn.mjTRN_JOINT,251)252vel.set_to_velocity(kv=10.0)253```254255> [!CAUTION]256>257> The helper functions `set_to_position()` and `set_to_motor()` configure gains258> but do **not** set the transmission. You must always specify259> `trntype=mujoco.mjtTrn.mjTRN_JOINT` (or another valid transmission type). See260> [modeling.rst](../../modeling.rst) (`.. _CActuators:`, `.. _CActShortcuts:`)261> and [XMLreference.rst](../../XMLreference.rst) (`.. _actuator:`).262263## 6. Default Classes (Inheritance & Styling)264265Default classes (`MjsDefault`) provide cascaded styling and properties (see266[modeling.rst](../../modeling.rst), `.. _CDefault:`, and267[programming/modeledit.rst](../../programming/modeledit.rst), `.. _meDefault:`):268269```python270# Create child class under root 'main' class271main_class = spec.default272rubber = spec.add_default('rubber', main_class)273rubber.geom.friction = [1.5, 0.01, 0.001]274rubber.geom.density = 1200.0275276# Assign class at creation277body.add_geom(rubber, name='tire', type=mujoco.mjtGeom.mjGEOM_CYLINDER, size=[0.1, 0.05])278279# Assign class post-creation (must pass MjsDefault object, NOT a string)280other_geom.classname = rubber281```282283### Baseline Tuning Overrides (`<option>` & Root `<default>`)284285Several internal defaults (`Euler`, `pyramidal` cones with `impratio=1`, soft286`solref="0.02 1"`, zero joint `armature`/`damping`) are kept for backwards287compatibility rather than new robotics models. Override them at the top of a288project (full rationale and priority-ordered parameter guide in289[modeling.rst](../../modeling.rst), `.. _CTuning:`, `.. _CTuningDefaults:`,290`.. _CTuningGlobal:`, `.. _CTuningModel:`):291292```python293spec.option.integrator = mujoco.mjtIntegrator.mjINT_IMPLICITFAST # DISCRETE for flex elasticity294spec.option.cone = mujoco.mjtCone.mjCONE_ELLIPTIC295spec.option.impratio = 10.0296297spec.default.geom.solref = [0.005, 1.0] # Keep solref[0] >= 2 * timestep298spec.default.joint.armature = 0.01 # Reflected rotor inertia (I_rotor * N^2)299spec.default.joint.damping = 0.1 # Implicit in M + h*D at zero solver cost300```301302Keep the default `solimp`: raising `solimp[0]` (e.g. to `0.95`) halves rest303penetration and creep but costs solver iterations, so reach for it only after304`solref` and elliptic cones.305306## 7. Collisions & Friction Tuning307308### Collision Filtering Bitmasks309310Two geoms collide if and only if:311`(g1.contype & g2.conaffinity) || (g2.contype & g1.conaffinity)`312313```python314# Visual-only geom: never collides; set mass=0 if omitting <inertial> so it315# does not add water-density (1000 kg/m^3) mass (inertiagrouprange defaults to "0 5")316body.add_geom(size=[0.1], contype=0, conaffinity=0, group=1, mass=0)317318# Team A collides only with Team B319geom_a = body.add_geom(size=[0.1], contype=1, conaffinity=2)320geom_b = body.add_geom(size=[0.1], contype=2, conaffinity=1)321```322323### Contact Dimension (`condim`) & Friction324325| `condim` | Active Friction Components | Friction Index Used |326| :--- | :--- | :--- |327| 1 | Normal force only (frictionless) | — |328| 3 | Tangential sliding friction | `friction[0]` |329| 4 | Tangential + torsional (twisting) | `friction[0:2]` |330| 6 | Tangential + torsional + rolling | `friction[0:3]` |331332```python333# High-friction contact for grasping334finger.add_geom(335 type=mujoco.mjtGeom.mjGEOM_CAPSULE,336 size=[0.01, 0.03],337 condim=4,338 friction=[1.2, 0.02, 0.0001],339)340```341342For contact softness, solver impedance/reference tuning (`solref`, `solimp`,343`priority`/mixing), and why parent-child geoms omit collisions by default, read344[modeling.rst](../../modeling.rst) (`.. _CTuning:`, `.. _CTuningModel:`,345`.. _CSolver:`, `.. _CContact:`) and [overview.rst](../../overview.rst)346(`.. _SurprisingCollisions:`, `.. _Soft:`, `.. _Units:`).347348## 8. Procedural Meshes, Materials & Sensors349350### Procedural Meshes351352```python353vertices = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32)354faces = np.array([[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]], dtype=np.int32)355mesh = spec.add_mesh(name='tetra', uservert=vertices.flatten(), userface=faces.flatten())356body.add_geom(type=mujoco.mjtGeom.mjGEOM_MESH, meshname='tetra')357```358359Concave collision meshes are replaced by their convex hulls (unless using SDF360plugins); prefer primitives (`sphere`, `capsule`, `box`, `cylinder`) for both361speed and cleaner normals, or pre-decompose non-convex assets offline with362`CoACD` or `mjfit` (see [computation/index.rst](../../computation/index.rst),363`.. _coChecking:` and `.. _coDecomposition:`).364365### Procedural Sensors366367```python368# IMU Accelerometer and Gyroscope369spec.add_sensor(name='torso_acc', type=mujoco.mjtSensor.mjSENS_ACCELEROMETER,370 objtype=mujoco.mjtObj.mjOBJ_SITE, objname='imu_site')371spec.add_sensor(name='torso_gyro', type=mujoco.mjtSensor.mjSENS_GYRO,372 objtype=mujoco.mjtObj.mjOBJ_SITE, objname='imu_site')373```374375## 9. Common Gotchas & Best Practices3763771. **Non-zero geom sizes**: Geoms with radius or half-extents of zero cause378 immediate compilation errors.3792. **`classname` takes an object**: `geom.classname = 'rubber'` raises a380 `TypeError`. Pass the `MjsDefault` instance: `geom.classname = rubber`.3813. **Always assign `recompile()`**: `spec.recompile(m, d)` produces newly382 allocated model and data instances. Reassign them:383 `m, d = spec.recompile(m, d)` (see384 [programming/modeledit.rst](../../programming/modeledit.rst),385 `.. _meRecompilation:`).3864. **Declare high-contact "hub" bodies first (reverse-Cholesky fill-in)**:387 When a moving body with DOFs (e.g., an actuated tray, sieve, container, or388 robot base) contacts many independent clutter bodies, declare the hub body389 **before** the independent bodies so `mju_cholFactorSparse` factors the390 mass/Hessian arrowhead in $O(N)$ with zero fill-in rather than $O(N^3)$.391 Static geoms on `worldbody` have 0 DOFs and are unaffected — see the full392 derivation in [modeling.rst](../../modeling.rst) (`.. _CBodyOrdering:`).3935. **Never add joints (including `<freejoint/>`) to the parent body of an394 unpinned `<flexcomp>`** (except `dof="2d"` or `"radial"`). See395 [mujoco-deformables](../deformables/SKILL.md) for all `<flexcomp>`, `<pin>`,396 and `<elasticity>` rules.397398## 10. Reference Models & Key References399400### Reference MJCF Models & Fixtures401402Before authoring complex mechanisms or specialized elements from scratch, check403existing models:404405- **Built-in showcase models (`../../../model/`, or online at406 https://github.com/google-deepmind/mujoco/tree/main/model)**:407 `model/humanoid/`, `model/tendon_arm/arm26.xml`, `model/car/car.xml`,408 `model/slider_crank/slider_crank.xml`, `model/flex/` (cables, cloth, soft409 bodies — see [mujoco-deformables](../deformables/SKILL.md)),410 `model/replicate/` (`newton_cradle.xml`, `particle.xml`, `bunnies.xml`),411 `model/plugin/` (actuator, sensor, SDF), `model/tactile/`,412 `model/adhesion/`, `model/sleep/`, `model/speculative/`, and413 `model/plastic/`.414- **MuJoCo Menagerie ([models.rst](../../models.rst), `.. _Menagerie:`)**:415 Production robot descriptions (Franka Panda/FR3, UR5e/UR10e, Unitree416 G1/H1/Go2, Spot, Barkour, Shadow Hand, Robotiq 2F-85, ALOHA 2, Skydio X2,417 Flybody) at https://github.com/google-deepmind/mujoco_menagerie.418- **Minimal test fixtures (`../../../test/**/testdata/`, or online under419 https://github.com/google-deepmind/mujoco/tree/main/test)**: Focused420 single-feature XMLs in `test/user/testdata/` (`MjSpec` & compiler),421 `test/xml/testdata/` (`parent.xml` / `child.xml` attachment fixtures,422 OpenUSD), and `test/engine/testdata/` (`collisions.xml`, `connect.xml`,423 `equality_site.xml`, `catenary.xml`).424425### Documentation426427- [MjSpec & Procedural Model Editing](../../programming/modeledit.rst)428 (`.. _meOverview:`, `.. _meAttachment:`, `.. _meAttributeMerging:`,429 `.. _meDefault:`, `.. _meRecompilation:`)430- [Python Model Editing & OpenUSD Bindings](../../python.rst)431 (`.. _PyModelEdit:`, `.. _PyEditConvenience:`, `.. _PyMJCF:`,432 `.. _PyUSDexport:`) and [OpenUSD Guide](../../OpenUSD/index.rst)433- [MJCF Modeling Guide](../../modeling.rst) (`.. _CDefault:`,434 `.. _COrientation:`, `.. _CSolver:`, `.. _CContact:`, `.. _CBodyOrdering:`,435 `.. _CActuators:`, `.. _CDeformable:`, `.. _CTuning:`,436 `.. _CTuningDefaults:`, `.. _CTuningGlobal:`, `.. _CTuningModel:`) and437 [Modeling Pitfalls & Units](../../overview.rst) (`.. _Clarifications:`,438 `.. _Units:`, `.. _SurprisingCollisions:`, `.. _Soft:`)439- [MJCF XML Schema Reference](../../XMLreference.rst) (`.. _body-geom:`,440 `.. _body-joint:`, `.. _actuator:`, `.. _equality:`, `.. _body-flexcomp:`,441 `.. _replicate:`)442- [Engine Plugins & Resource Providers](../../programming/extension.rst)443 (`.. _exExtension:`, `.. _exSDF:`)444- [C Model Editing API Functions](../../APIreference/functions.rst)445 (`.. _Parseandcompile:`, `.. _Attachment:`, `.. _AddTreeElements:`,446 `.. _AddNonTreeElements:`)447448### Source Code & Notebook Examples449450- `python/mjspec.ipynb` (`MjSpec` tutorial & `dm_control` `PyMJCF`451 reimplementation; see [python.rst](../../python.rst), `.. _PyMJCF:`),452 [MjSpec Tests](../../../python/mujoco/specs_test.py), and453 [C++ Compile Sample](../../programming/samples.rst) (`.. _saCompile:`)