How MuJoCo Works Internally
Robot description formats, mjModel and mjData, and what actually happens inside mj_step().
Chapter 2 explained what any physics engine does: store a state, compute forces, solve for accelerations and step forward in time. This chapter opens up one specific engine, MuJoCo, which is widely used in legged-robot research and appears throughout Menlo's Asimov documentation (its processor-in-the-loop setup includes a MuJoCo bridge). You will see how a robot is described to it, how that description becomes numbers in memory, what happens inside one call to mj_step(), and how a control value written by your code turns into a torque at a joint.
By the end you should be able to read a MuJoCo model file, predict the sizes of the arrays it produces, and write a short Python loop that reads sensors and sends commands.
What MuJoCo is
MuJoCo stands for Multi-Joint dynamics with Contact. It is a physics engine written in C, designed for simulating articulated bodies (robots, animals, humans) that touch things. It was created by Emo Todorov and colleagues and described in a 2012 paper. DeepMind acquired it in 2021 and released it as open source under the Apache 2.0 licence in 2022. It ships with official Python bindings (pip install mujoco), which is how most robotics researchers use it.
Three design decisions shape everything in this chapter:
- Generalized coordinates. MuJoCo describes a robot by its joint angles and joint velocities, not by the free 3-D position of every part. A 12-joint leg system with a floating base is described by a few dozen numbers, and joints cannot come apart because there is nothing in the representation that would let them.
- Contact as optimisation. Contacts, friction and joint limits are solved together as one convex optimisation problem at each step. Contacts are slightly soft by design, which makes the solution unique and the simulation stable at large time steps.
- Separation of model and data. Everything that is fixed (geometry, masses, joint types, actuator gains) lives in one structure. Everything that changes while the simulation runs (positions, velocities, forces, sensor readings) lives in another. Most of this chapter follows from that split.
MuJoCo is a library, not an application
MuJoCo has no built-in notion of a "robot program". It gives you functions that advance a model in time and structures you can read and write. The control loop, the reward function, the policy and the logging are your code. The interactive viewer that ships with it is a convenience on top of the same library.
Why a robot needs a description
A physics engine cannot simulate a picture. It needs a precise answer to questions such as:
- Which parts are rigid bodies, and how are they connected?
- Which way does each joint rotate, and where is its axis?
- How heavy is each part, where is its centre of mass, and how hard is it to spin (its inertia)?
- Which shapes can touch the ground or each other?
- Where are the motors, how strong are they, and what does a control signal mean to them?
- Where are the sensors, and what do they measure?
A robot description is a text file that answers all of these. Engineers write it once (or generate it from CAD), and the simulator compiles it into an internal model. Several description formats exist because different tools grew up in different ecosystems.
Robot description formats
MJCF: MuJoCo's native format
MJCF (MuJoCo XML Format) is the format MuJoCo was designed around. An MJCF file is XML with a <mujoco> root element. The most important child elements are:
| Element | What it holds |
|---|---|
<compiler> | How to interpret the file: angle units, mesh directories, whether to compute inertia from geometry |
<option> | Simulation settings: timestep, gravity, integrator, solver settings |
<default> | Reusable default attribute values, organised in classes |
<asset> | Meshes, textures and materials referenced elsewhere |
<worldbody> | The kinematic tree: nested <body> elements with their <joint>, <geom>, <inertial> and <site> children |
<actuator> | Motors and servos, each attached to a joint (or tendon, or site) |
<sensor> | Virtual sensors, each attached to a joint, site, body or actuator |
<contact>, <equality>, <tendon> | Contact exclusions, constraints such as closed loops, and cables |
Bodies nest inside bodies. A <body> inside another body is its child, and the joint declared inside a body connects that body to its parent. This nesting is the kinematic tree, which makes MJCF compact: a whole leg is a few nested blocks.
MJCF also has features that the other formats lack: actuator models with gains and limits, a rich set of sensors, default classes, tendons, equality constraints that close kinematic loops, and fine control of contact softness. If you are only targeting MuJoCo, MJCF is the format to use.
URDF: the ROS standard
URDF (Unified Robot Description Format) is the robot format of the ROS ecosystem. It is also XML, but it is organised differently: a flat list of <link> elements (rigid bodies) and <joint> elements, where each joint names a parent link and a child link.
<robot name="arm">
<link name="base"/>
<link name="upper_arm">
<inertial>
<origin xyz="0.25 0 0"/>
<mass value="1.0"/>
<inertia ixx="0.0005" ixy="0" ixz="0" iyy="0.021" iyz="0" izz="0.021"/>
</inertial>
<visual>
<geometry><mesh filename="package://arm/meshes/upper_arm.stl" scale="0.001 0.001 0.001"/></geometry>
</visual>
<collision>
<origin xyz="0.25 0 0" rpy="0 1.5708 0"/>
<geometry><cylinder radius="0.03" length="0.5"/></geometry>
</collision>
</link>
<joint name="shoulder" type="revolute">
<parent link="base"/>
<child link="upper_arm"/>
<axis xyz="0 -1 0"/>
<limit lower="-1.57" upper="1.57" effort="10" velocity="5"/>
</joint>
</robot>URDF joint types are revolute (with limits), continuous (unlimited rotation), prismatic, fixed, floating and planar. All units are SI: metres, kilograms, radians. URDF can only describe a tree. A closed kinematic chain, such as a parallel linkage, cannot be written directly and has to be approximated or handled by the simulator. URDF also has no standard way to describe actuator dynamics or most sensors. Those are added through simulator-specific extension tags.
MuJoCo can load many URDF files directly and convert them into its own model. Because URDF lacks MuJoCo's actuators, sensors and contact parameters, a typical workflow is to load the URDF once, save the result as MJCF (mujoco.mj_saveLastXML), and then edit the MJCF by hand.
SDF: worlds for Gazebo and other simulators
SDF (the Simulation Description Format, or SDFormat) comes from the Gazebo simulator. Where URDF describes one robot, SDF describes a whole world: several models, lights, terrain, physics settings and plugins. Its model structure uses links and joints like URDF, but it adds explicit frames and poses, sensor elements (cameras, IMUs, lidars), and it is not limited to tree-shaped mechanisms in the specification. Whether a particular physics engine can simulate a closed loop described in SDF is a separate question. You will meet SDF if you work with Gazebo or with robots whose vendors ship SDF models. MuJoCo does not load SDF natively, so SDF models are usually converted through URDF or by hand.
Mesh files: STL and OBJ
Description files say what a body is. Mesh files say what shape it has, as a surface of triangles.
- STL stores a list of triangles, each with three vertices and a normal. It has no units, no colours (in the common binary form) and no materials. CAD tools usually export STL in millimetres, while MuJoCo and URDF assume metres. That is why mesh references often carry
scale="0.001 0.001 0.001". A forgotten scale makes a 30 cm leg 300 m long. - OBJ is a text format storing vertices, faces, normals and texture coordinates, optionally with a companion
.mtlmaterial file. It is common for visual meshes that need textures.
MuJoCo reads both. One detail matters a lot: for collision, MuJoCo uses the convex hull of a mesh, not the mesh itself. A U-shaped bracket collides as if it were filled in. Concave parts that must collide correctly have to be split into several convex pieces, or replaced by primitives.
| Format | Describes | Ecosystem | Actuators and sensors | Closed loops |
|---|---|---|---|---|
| MJCF | Robot and scene | MuJoCo | Built in, detailed | Through equality constraints |
| URDF | One robot (tree) | ROS, many tools | Extension tags only | No |
| SDF | Whole world | Gazebo | Sensors built in | Allowed by the format |
| STL / OBJ | Surface shape only | Everywhere | — | — |
Visual geometry versus collision geometry
Every body can carry two kinds of shape, and they serve different masters.
Visual geometry is what you see. It can be a detailed mesh straight from CAD, with tens of thousands of triangles, fillets, screw heads and logos. It costs rendering time but has no effect on physics.
Collision geometry is what the physics engine uses to detect contact. It should be as simple as possible: spheres, capsules, boxes, cylinders and a few convex meshes. Simple shapes make collision detection fast, and, just as importantly, they make contact predictable. A foot modelled as a detailed mesh can touch the ground at one random vertex in one step and three in the next, producing jittery forces. A capsule touches the ground along a smooth curve.
In MJCF there is no separate <visual> and <collision> element. Every <geom> can do both, and attributes decide its role. The convention is:
contypeandconaffinitybitmasks decide which geoms can collide. Setting both to 0 makes a geom visual-only.groupsorts geoms into display groups, so the viewer can show collision shapes, visual shapes or both.- A visual geom is often given
mass="0"ordensity="0"so it does not contribute to the inertia.
Menlo's Asimov simulation uses capsule-based foot and toe collision geometry with explicit foot and toe contact points and tuned contact parameters. The documentation states a preference for explicit primitives over detailed mesh collision, to get conservative and repeatable contact.
Bodies, joints, actuators and sensors
Bodies
A body is a rigid object with a position, an orientation, a mass and an inertia. Bodies form a tree rooted at the special worldbody, which never moves. Each body has its own coordinate frame, defined relative to its parent with pos and quat (or euler, axisangle). Geoms, sites and child bodies are placed in that frame.
A site is a massless marker frame attached to a body. Sites do not collide or weigh anything. They exist to mark points of interest: where an IMU is mounted, where a foot touches down, where a tendon attaches. Many sensors are attached to sites.
Joints
A joint gives a body degrees of freedom relative to its parent. A body with no joint is welded to its parent. MuJoCo has four joint types:
| Type | Degrees of freedom | Entries in qpos | Entries in qvel | Example |
|---|---|---|---|---|
hinge | 1 rotation | 1 (angle, rad) | 1 (rad/s) | Knee, elbow |
slide | 1 translation | 1 (m) | 1 (m/s) | Linear actuator |
ball | 3 rotations | 4 (quaternion) | 3 (angular velocity) | Shoulder in a character model |
free | 3 translations + 3 rotations | 7 (position + quaternion) | 6 (linear + angular velocity) | Floating base of a walking robot |
The mismatch between the last two columns is not a typo; we return to it in qpos and qvel.
A joint can also carry passive properties: damping (a torque proportional to velocity), stiffness (a spring towards a reference angle), frictionloss (dry friction), armature (extra rotor inertia reflected through a gearbox) and range (limits).
Actuators
An actuator turns a control number into a generalized force. It is attached to a transmission, most often a joint. Each actuator adds exactly one entry to the control vector ctrl. What that number means (a torque, a target angle or a target velocity) depends on how the actuator is configured. This is important enough to get its own section below.
Sensors
A sensor is a function of the simulation state that writes numbers into the sensordata array. MuJoCo computes them from the exact simulated state. A jointpos sensor copies a joint angle. A gyro sensor at a site reports the angular velocity of that site in its own frame. An accelerometer reports the acceleration of the site minus gravity, in its own frame. Chapter 4 covers how these virtual readings relate to real sensors, and why the simulated ones are too perfect unless you add errors yourself.
Mass, inertia and physical properties
For the dynamics to be right, every moving body needs three things:
- Mass in kilograms.
- Centre of mass, a point in the body frame.
- Rotational inertia, a symmetric matrix describing how hard it is to rotate the body about each axis.
MuJoCo offers two ways to provide them. You can write an explicit <inertial> element with mass, pos and diaginertia (or fullinertia). Or you can let the compiler infer them from the collision geoms, using either a mass attribute on each geom or a density (default 1000 kg/m³, the density of water). The compiler integrates each shape and adds the results.
Internally, MuJoCo stores each body's inertia in its principal axes: a diagonal inertia body_inertia (three numbers) plus a rotation body_iquat that says how those axes are oriented. A full matrix you write in the file is diagonalised at compile time.
As a worked example, consider a uniform rod of mass and length rotating about one end. Its inertia about that end is
Holding it horizontal against gravity needs a torque of . Double the length and the holding torque doubles while the inertia quadruples, so the arm becomes slower to accelerate as well as harder to hold. These numbers are exactly what you can try in the laboratory below.
Other physical properties live on geoms and joints:
frictionon a geom: sliding, torsional and rolling coefficients (default1 0.005 0.0001).solrefandsolimp: how soft and how damped a contact or limit is.damping,frictionlossandarmatureon joints.marginandgapfor when contacts activate.
Wrong inertia is silent
A model with a mistyped inertia still simulates. It just moves wrongly: legs swing too fast, the base tips too easily. Always check model.body_mass and model.body_inertia after loading, and compare the total mass (sum(model.body_mass)) with the robot on a scale.
From CAD to a simulation-ready model
Robots are designed in CAD tools such as SolidWorks, Onshape or Fusion. Turning that design into a model MuJoCo can simulate is a pipeline with several decisions along the way:
- Decide the kinematic tree. Group CAD parts into rigid bodies. Everything bolted together becomes one body. Each motor axis becomes a joint.
- Export mass properties. CAD tools compute mass, centre of mass and inertia per body from part materials. These are a starting point. Wiring, fasteners, batteries and glue are usually missing, so measured masses are often higher.
- Export meshes. One visual mesh per body (STL or OBJ), in a known unit, with the origin placed at the body frame.
- Design collision geometry. Replace detailed parts with primitives by hand: capsules for limbs and feet, boxes for the torso. This step is where simulation engineers add the most judgement.
- Write the description. Tools such as Onshape-to-robot or SolidWorks URDF exporters can generate URDF automatically. Convert to MJCF, then add what URDF cannot express: actuators, sensors, contact parameters, default classes.
- Model actuators. Choose actuator types, gains, control ranges, force limits, gear ratios and armature. On real hardware these come from motor datasheets and measurements.
- Validate and identify. Compare simulated and real behaviour (a joint swinging under gravity, a leg tracking a step command) and tune parameters until they match. This is system identification, which Menlo's guide treats as its own topic.
- CAD assemblyparts, materials
- Bodies and jointskinematic tree
- Mass propertiesm, CoM, inertia
- Meshes + collision primitivesSTL/OBJ + capsules
- URDF / MJCFplus actuators, sensors
- Identified modeltuned to hardware
A complete single-joint robot
Here is a complete, valid MJCF model of a one-joint arm: a capsule link hanging from a hinge, driven by a torque motor, with joint position and velocity sensors. It is the model behind the interactive laboratory later in this chapter.
<mujoco model="single_joint_arm">
<!-- Interpret angles in radians (the MJCF default is degrees). -->
<compiler angle="radian"/>
<!-- 2 ms timestep, standard gravity along -z, MuJoCo's default integrator. -->
<option timestep="0.002" gravity="0 0 -9.81" integrator="Euler"/>
<worldbody>
<light pos="0 0 3"/>
<geom name="floor" type="plane" size="1 1 0.1"/>
<!-- The arm's body frame sits 1 m above the floor. -->
<body name="upper_arm" pos="0 0 1">
<!-- One rotational degree of freedom about -y: q = 0 is horizontal, q > 0 raises the arm. -->
<joint name="shoulder" type="hinge" axis="0 -1 0" damping="0.05"/>
<!-- 0.5 m capsule from the hinge along +x. Inertia is computed from this shape and mass. -->
<geom name="link" type="capsule" fromto="0 0 0 0.5 0 0" size="0.03" mass="1.0"/>
<!-- A massless marker at the tip, e.g. for a tip-position sensor. -->
<site name="tip" pos="0.5 0 0"/>
</body>
</worldbody>
<actuator>
<!-- Torque motor: joint torque = gear * ctrl, ctrl clamped to [-10, 10]. -->
<motor name="shoulder_motor" joint="shoulder" gear="1" ctrllimited="true" ctrlrange="-10 10"/>
</actuator>
<sensor>
<jointpos name="shoulder_pos" joint="shoulder"/>
<jointvel name="shoulder_vel" joint="shoulder"/>
</sensor>
</mujoco>Reading it top to bottom:
<compiler angle="radian"/>matters because MJCF interprets angles in degrees by default (inrange,eulerand similar attributes). The state arrays are always in radians regardless.<option>setsmodel.opt.timestep = 0.002(also MuJoCo's default), gravity and the integrator.- The
planegeom on the world body is the floor. A plane is infinite for collision;sizeonly affects how it is drawn. fromtoplaces a capsule between two points, withsizeas its radius. Becausemassis given, the compiler computes the inertia from the capsule shape with that total mass.- The motor has
gear="1", so one unit of control is one newton-metre at the joint. - The two sensors make
sensordataa two-element array:[angle, angular velocity].
This model has nq = 1, nv = 1, nu = 1 and nsensordata = 2. It has two bodies (nbody = 2), because the world counts as body 0.
How MuJoCo stores a model: mjModel and mjData
When MuJoCo loads an XML file, its compiler checks it, fills in defaults, computes inertias, builds convex hulls and lays everything out into flat arrays. The result is two C structures, exposed in Python as mujoco.MjModel and mujoco.MjData.
mjModel: everything that does not change
mjModel holds the compiled description: sizes (nq, nv, nu, nbody, ngeom, nsensor, ...), the option block (model.opt.timestep, model.opt.gravity, model.opt.integrator), and per-object arrays such as body_mass, body_inertia, geom_size, geom_friction, jnt_type, jnt_range, actuator_gear, actuator_ctrlrange and sensor_dim.
The simulation functions never write to mjModel. You can change values in it between steps, for example to randomise a mass or a friction coefficient. That is the basis of domain randomisation.
mjData: everything that does change
mjData holds the state and every intermediate result of the latest computation. The fields you will use most:
| Field | Size | Meaning |
|---|---|---|
time | scalar | Simulated time in seconds |
qpos | nq | Generalized positions: joint angles, plus position and quaternion for free joints |
qvel | nv | Generalized velocities |
qacc | nv | Generalized accelerations computed by forward dynamics |
ctrl | nu | Control inputs, one per actuator, written by your code |
act | na | Actuator activations, for actuators with internal dynamics |
actuator_force | nu | Scalar force produced by each actuator |
qfrc_actuator | nv | Actuator forces mapped onto the joints |
qfrc_applied, xfrc_applied | nv, nbody×6 | External forces you can apply (pushes, perturbations) |
sensordata | nsensordata | All sensor outputs, concatenated |
xpos, xquat, xmat | per body | World-frame position and orientation of every body |
ncon, contact | scalar, array | Number of active contacts and their details |
The state in the strict sense is small: time, qpos, qvel, act, plus a few warm-start values. Everything else in mjData (body positions, contact lists, sensor values) is derived from the state and recomputed every step. Copying qpos, qvel, act and time is enough to restore a simulation.
qpos and qvel: why nq and nv differ
For hinge and slide joints, one position number pairs with one velocity number. Orientations in 3-D are different. MuJoCo stores a free orientation as a unit quaternion (four numbers ), because quaternions have no singularities, unlike Euler angles. But a rotation has only three degrees of freedom, so its velocity is a three-number angular velocity.
So a free joint contributes 7 entries to qpos (3 position + 4 quaternion) and 6 to qvel (3 linear + 3 angular velocity). For a free joint, the linear part of qvel is expressed in the world frame and the angular part in the body's local frame. A ball joint contributes 4 and 3.
For a floating-base robot with 12 actuated hinge joints, and . That also means you cannot integrate positions with qpos += qvel * dt yourself. Quaternions must be integrated with mujoco.mj_integratePos, which handles the rotation correctly. To find where a particular joint lives in these arrays, use model.jnt_qposadr and model.jnt_dofadr, or the named accessors shown below.
qacc, ctrl, sensordata and time
qaccis an output. Forward dynamics computes it from the equation of motion, , where is the mass matrix, collects gravity, Coriolis and centrifugal terms, and is the contribution of contact and constraint forces.ctrlis an input. MuJoCo never writes it. Your controller or policy writes it before each step. If actrlrangeis set and limiting is active, out-of-range values are clamped when the force is computed, while the array keeps what you wrote.sensordatais an output, filled in during the step. Each sensor occupiesmodel.sensor_dim[i]consecutive entries starting atmodel.sensor_adr[i].timeadvances bymodel.opt.timestepon everymj_step.
What mj_step does
mujoco.mj_step(model, data) advances the simulation by one timestep. Internally it runs forward dynamics (compute accelerations from the current state and controls) and then integrates (update velocities and positions). It is literally the combination of two halves:
mj_step1does the position- and velocity-dependent work: forward kinematics (where is every body?), collision detection (which geoms touch?), building the mass matrix, computing passive forces, and evaluating position and velocity sensors.mj_step2does the rest: actuator forces fromctrl, the acceleration including contact and constraint forces, acceleration-dependent sensors, and finally integration ofqvel,qposandtime.
The split exists so that you can call mj_step1, read fresh kinematics and sensors, set ctrl based on them, and then call mj_step2, with no stale data in between. Most code just calls mj_step. The split is not available with the RK4 integrator.
One timing subtlety follows from this structure. After mj_step returns, qpos, qvel and time describe the new state, but sensordata, qacc and actuator_force were computed from the state at the start of the step. If you need sensors consistent with the current state, call mujoco.mj_forward(model, data), which runs the computation without integrating.
Timestep and integrators
model.opt.timestep is the size of each step. MuJoCo's default is 0.002 s (500 Hz). Smaller steps are more accurate and more stable but cost proportionally more computation.
Asimov's simulation runs physics at 200 Hz (which corresponds to a 5 ms step), the observation/IO path at 200 Hz, and the policy at 50 Hz.
model.opt.integrator chooses how the step is taken:
Euler(default): semi-implicit Euler. Velocity is updated first and the new velocity is used to update position. Joint damping is treated implicitly, which keeps heavily damped joints stable.RK4: fourth-order Runge–Kutta. Much more accurate for smooth motion, four times the cost per step, and less helpful when contacts dominate.implicitandimplicitfast: treat velocity-dependent forces (including actuator damping such as a position servo'skv) implicitly, which improves stability with stiff damping. The MuJoCo documentation recommendsimplicitfastfor most robotics models.
You can watch a timestep become too large in the laboratory: raise kp, lengthen the timestep, and the servo starts to oscillate and then explodes.
Using MuJoCo from Python
The examples use the official bindings (pip install mujoco). First, load the model and inspect its sizes:
import mujoco
XML = open("single_joint_arm.xml").read()
model = mujoco.MjModel.from_xml_string(XML) # or mujoco.MjModel.from_xml_path(...)
data = mujoco.MjData(model)
print(model.nq, model.nv, model.nu, model.nsensordata) # 1 1 1 2
print(model.opt.timestep) # 0.002
print(model.body("upper_arm").mass) # [1.]
print(model.body("upper_arm").inertia) # principal moments from the capsuleNow run a simple control loop. A PD controller written in Python computes a torque and writes it into data.ctrl:
import numpy as np
import mujoco
model = mujoco.MjModel.from_xml_path("single_joint_arm.xml")
data = mujoco.MjData(model)
motor = model.actuator("shoulder_motor").id
target, kp, kd = 0.8, 30.0, 2.0 # rad, N·m/rad, N·m·s/rad
for _ in range(int(3.0 / model.opt.timestep)): # 3 s of simulated time
q = data.sensor("shoulder_pos").data[0]
qd = data.sensor("shoulder_vel").data[0]
data.ctrl[motor] = kp * (target - q) - kd * qd # torque command (gear = 1)
mujoco.mj_step(model, data)
print(f"t = {data.time:.3f} s")
print("qpos ", data.qpos) # whole state vector
print("joint angle", data.joint("shoulder").qpos) # named view into qpos
print("sensordata ", data.sensordata) # [jointpos, jointvel]
print("contacts ", data.ncon)Note that the sensor values read at the top of each iteration come from the previous mj_step, so they describe the state one step earlier. For a 2 ms step this is a small delay, but it is a real one, and it is the same kind of delay a real control loop has.
Named access returns views into the underlying arrays, so writing through them changes the simulation:
mujoco.mj_resetData(model, data) # back to the initial state
data.joint("shoulder").qpos[0] = 0.5 # start the arm raised 0.5 rad
data.joint("shoulder").qvel[0] = 0.0
mujoco.mj_forward(model, data) # recompute derived quantities, no time step
print(data.site("tip").xpos) # world position of the tip marker
print(data.sensor("shoulder_pos").data) # now consistent with qpos: [0.5]
model.opt.timestep = 0.001 # options can be changed between steps
model.opt.integrator = mujoco.mjtIntegrator.mjINT_RK4How actuator commands are interpreted
The same number in data.ctrl can mean three completely different things, depending on the actuator. MuJoCo models every actuator with one general formula. For an actuator acting on a joint with angle :
where is the control value after clamping to ctrlrange, and the force is clamped to forcerange if force limiting is active. The shortcut elements <motor>, <position> and <velocity> are just preset choices of gain and bias.
| Actuator | Gain | Bias , | ctrl means | Joint torque (gear = 1) |
|---|---|---|---|---|
<motor> | 1 | 0, 0 | Torque | |
<position kp kv> | , | Target angle | ||
<velocity kv> | 0, | Target velocity | ||
<general> | gainprm | biasprm | Whatever you define | Affine in , length, velocity |
Worked numbers for the arm above, held horizontal (, gravity torque ):
- Motor, gear 1.
ctrl = 2.45holds the arm level.ctrl = 3accelerates it upward at . - Motor, gear 10. The same
ctrl = 3now produces 30 N·m. Gear models a gearbox or lever: it scales force up and the joint's apparent motion down by the same factor. - Position, kp = 30.
ctrl = 0.8means "go to 0.8 rad". The servo pushes harder the further the arm is from the target. Against gravity it settles where , which is about rad. That steady-state error is a property of a pure proportional servo, not a bug. - Velocity, kv = 2.
ctrl = 2asks for 2 rad/s. Nothing holds position, so when you setctrl = 0the arm sags under gravity until the velocity error alone balances the weight.
Limits matter as much as gains:
ctrlrangewithctrllimitedclamps the control signal. In current MuJoCo the default isctrllimited="auto", which turns limiting on when actrlrangeis given.forcerangewithforcelimitedclamps the actuator force, before the gear is applied. This is how motor torque saturation is usually modelled. A position servo with a largekpand a smallforcerangebehaves like a strong spring that runs out of strength.gearscales both the actuator's effective length and its output force, so with gear a position actuator'sctrlis a target in actuator units (), not joint units.
“A policy that outputs joint targets is sending torques.”
Not necessarily. If the model uses <position> actuators, the policy writes target angles into ctrl and MuJoCo's built-in servo converts them into torques with kp and kv. If it uses <motor> actuators, someone must write the PD law, as in the Python loop above. Menlo documents that Asimov's policy produces commanded joint targets; how those targets become motor commands, and with which gains, is not published.
The complete system pipeline
Putting all of this together, here is how a robot design flows into MuJoCo and how the simulation then loops:
- 1CAD Modelparts, materials, assemblies
- 2Geometry and Physical Propertiesmeshes, primitives, mass, inertia
- 3MJCF/URDFrobot description
- 4MuJoCo ModelmjModel: compiled, fixed
- 5Physics Solvermj_step: dynamics + contact
- 6Updated Robot StatemjData: qpos, qvel, time
- 7Sensor Datasensordata
- 8Controlleryour code or a policy
- 9Actuator Commandsdata.ctrl
Loops back: Actuator Commands → CAD Model
Interactive: the single-joint arm laboratory
The laboratory below re-implements the single-joint model in your browser. It is not MuJoCo, but it uses the same model structure, the same actuator formula and a MuJoCo-style semi-implicit Euler integrator, and it lays its state out the way mjData does. The XML panel regenerates from the sliders, so you can see which attribute each parameter corresponds to. If the physics of the arm itself (gravity torque, droop under PD control, torque saturation) is new to you, start with the torque-limited arm in Chapter 2 first.
Things to try:
- Motor mode, gravity on. Find the torque that holds the arm level. It should be close to . Then double the mass and find it again.
- Position mode. Set a target of 0.8 rad and note where the arm settles. Increase
kpand the steady-state error shrinks. Setkvto 0 and the arm overshoots and rings. - Gear. In motor mode, raise the gear from 1 to 5 with the same
ctrl. The torque readout scales by five. - forcerange. In position mode with
kp = 300, turn on the ±5 limit and command a large move. The torque plot flattens at the limit and the arm moves at a slower, saturated rate. - Timestep. With
kp = 300and Euler, raise the timestep towards 30 ms. The servo becomes unstable. Switch to RK4 and see how far you can push it. MuJoCo users meet exactly this trade-off. - Step once. Pause, then press step. Each press is one
mj_step:timeadvances by one timestep, andsensordatalagsqposby one step.
How MuJoCo connects to the rest of the stack
MuJoCo sits in the middle of the robot software stack. Upstream, it consumes a description built from CAD. Downstream, three consumers read from it:
- Sensor models read
mjDataand produce observations. In a training environment these are usually post-processed with noise and delays before the policy sees them (Chapter 4). - Communication bridges carry simulated values into real firmware for processor-in-the-loop testing (Chapter 5). Menlo documents a MuJoCo bridge that reads
imu_ang_velandimu_lin_accand sends them to firmware over UDP. - Training code wraps the model in an environment with resets, rewards and many parallel copies (Chapter 6 and Chapter 8).
A practical locomotion environment typically calls mj_step several times per policy action. With physics at 200 Hz and a policy at 50 Hz, as documented for Asimov, each action is held for four physics steps.
Limitations and common misconceptions
“The robot model is just the 3D mesh.”
The mesh is only for looks and, at most, for convex-hull collision. Dynamics come from masses, inertias, joint definitions and actuator models, which a mesh does not contain.
“qpos and qvel always have the same length.”
They do only when every joint is a hinge or slide. Free and ball joints store orientation as a quaternion (4 numbers) but angular velocity as 3 numbers, so .
“Simulated sensors behave like real ones.”
MuJoCo computes sensor values exactly from the simulated state. Real sensors have noise, bias, drift, latency and finite sampling rates. Unless you model these yourself, a policy trained in simulation sees cleaner data than it will ever see on hardware.
“Mesh collision is more accurate, so it is better.”
MuJoCo collides meshes through their convex hulls, so concave detail is lost anyway. Even with convex pieces, many small contact points make contact forces noisier. Many legged-robot models, including Asimov's as documented, use capsules for feet.
Other limitations to keep in mind:
- Soft contact. MuJoCo's contacts allow slight penetration by design. Contact parameters (
solref,solimp, friction) shape gait behaviour and have to be tuned. - Rigid bodies only in the standard pipeline. Compliant parts such as Asimov's passive toes have to be modelled as extra joints with stiffness and damping, or with MuJoCo's newer deformable features.
- Actuator models are simple. The built-in actuators are affine in control, length and velocity. Real motor effects such as speed-dependent torque limits, delay and backlash need extra modelling, which Menlo documents doing for saturation, friction and delay.
- Description formats are lossy to convert. URDF to MJCF loses nothing structural but gains nothing either: actuators, sensors and contact parameters must be added by hand.
Key takeaways
Key takeaways
- MuJoCo stands for Multi-Joint dynamics with Contact. It simulates articulated bodies in generalized coordinates and solves contact as an optimisation problem.
- Robots are described in MJCF (MuJoCo native), URDF (ROS) or SDF (Gazebo worlds), with STL/OBJ meshes for shape. Collision should use simple primitives; visual meshes can be detailed.
mjModelholds everything fixed (geometry, masses, gains,opt.timestep);mjDataholds everything that changes (time,qpos,qvel,qacc,ctrl,sensordata, contacts).qposhasnqentries andqvelhasnv. A free joint uses 7 and 6, because orientation is a quaternion.mj_step=mj_step1(kinematics, collision, position and velocity sensors) +mj_step2(actuation, acceleration, integration). Afterwards,sensordatareflects the state at the start of the step.- What
ctrlmeans depends on the actuator: torque formotor, target angle forposition, target velocity forvelocity, scaled bygearand clamped byctrlrangeandforcerange.
References and further reading
- MuJoCo documentation, Overview and Modeling.
- MuJoCo documentation, XML reference: every MJCF element and attribute, including actuators and sensors.
- MuJoCo documentation, Computation: the equations of motion, constraint solver and integrators.
- MuJoCo documentation, Simulation:
mj_step,mj_step1/mj_step2, state and control. - MuJoCo documentation, Python bindings, including named access.
- E. Todorov, T. Erez and Y. Tassa, "MuJoCo: A physics engine for model-based control," IROS 2012.
- ROS Wiki, URDF and the URDF XML specification.
- SDFormat specification, Open Robotics.
- Menlo, Understanding Your Simulation Environment.