Skip to content
Physical AI
Chapter 03 28 min read

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:

  1. 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.
  2. 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.
  3. 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:

ElementWhat 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.

arm.urdf (fragment)
<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>
xml

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 .mtl material 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.

FormatDescribesEcosystemActuators and sensorsClosed loops
MJCFRobot and sceneMuJoCoBuilt in, detailedThrough equality constraints
URDFOne robot (tree)ROS, many toolsExtension tags onlyNo
SDFWhole worldGazeboSensors built inAllowed by the format
STL / OBJSurface shape onlyEverywhere——

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:

  • contype and conaffinity bitmasks decide which geoms can collide. Setting both to 0 makes a geom visual-only.
  • group sorts geoms into display groups, so the viewer can show collision shapes, visual shapes or both.
  • A visual geom is often given mass="0" or density="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:

TypeDegrees of freedomEntries in qposEntries in qvelExample
hinge1 rotation1 (angle, rad)1 (rad/s)Knee, elbow
slide1 translation1 (m)1 (m/s)Linear actuator
ball3 rotations4 (quaternion)3 (angular velocity)Shoulder in a character model
free3 translations + 3 rotations7 (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 mm in kilograms.
  • Centre of mass, a point in the body frame.
  • Rotational inertia, a 3×33\times3 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 m=1 kgm = 1\ \text{kg} and length L=0.5 mL = 0.5\ \text{m} rotating about one end. Its inertia about that end is

I=13mL2=13⋅1⋅0.52≈0.083 kg⋅m2.I = \tfrac{1}{3} m L^2 = \tfrac{1}{3}\cdot 1 \cdot 0.5^2 \approx 0.083\ \text{kg·m}^2 .

Holding it horizontal against gravity needs a torque of mgL2=1⋅9.81⋅0.25≈2.45 N⋅mm g \tfrac{L}{2} = 1 \cdot 9.81 \cdot 0.25 \approx 2.45\ \text{N·m}. 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:

  • friction on a geom: sliding, torsional and rolling coefficients (default 1 0.005 0.0001).
  • solref and solimp: how soft and how damped a contact or limit is.
  • damping, frictionloss and armature on joints.
  • margin and gap for 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:

  1. Decide the kinematic tree. Group CAD parts into rigid bodies. Everything bolted together becomes one body. Each motor axis becomes a joint.
  2. 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.
  3. Export meshes. One visual mesh per body (STL or OBJ), in a known unit, with the origin placed at the body frame.
  4. 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.
  5. 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.
  6. Model actuators. Choose actuator types, gains, control ranges, force limits, gear ratios and armature. On real hardware these come from motor datasheets and measurements.
  7. 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.
  1. CAD assemblyparts, materials
  2. Bodies and jointskinematic tree
  3. Mass propertiesm, CoM, inertia
  4. Meshes + collision primitivesSTL/OBJ + capsules
  5. URDF / MJCFplus actuators, sensors
  6. Identified modeltuned to hardware
From CAD to a simulation-ready model. The later steps are where most of the sim-to-real effort goes.

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.

single_joint_arm.xml
<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>
xml

Reading it top to bottom:

  • <compiler angle="radian"/> matters because MJCF interprets angles in degrees by default (in range, euler and similar attributes). The state arrays are always in radians regardless.
  • <option> sets model.opt.timestep = 0.002 (also MuJoCo's default), gravity and the integrator.
  • The plane geom on the world body is the floor. A plane is infinite for collision; size only affects how it is drawn.
  • fromto places a capsule between two points, with size as its radius. Because mass is 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 sensordata a 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:

FieldSizeMeaning
timescalarSimulated time in seconds
qposnqGeneralized positions: joint angles, plus position and quaternion for free joints
qvelnvGeneralized velocities
qaccnvGeneralized accelerations computed by forward dynamics
ctrlnuControl inputs, one per actuator, written by your code
actnaActuator activations, for actuators with internal dynamics
actuator_forcenuScalar force produced by each actuator
qfrc_actuatornvActuator forces mapped onto the joints
qfrc_applied, xfrc_appliednv, nbody×6External forces you can apply (pushes, perturbations)
sensordatansensordataAll sensor outputs, concatenated
xpos, xquat, xmatper bodyWorld-frame position and orientation of every body
ncon, contactscalar, arrayNumber 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 w,x,y,zw, x, y, z), 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, nq=7+12=19n_q = 7 + 12 = 19 and nv=6+12=18n_v = 6 + 12 = 18. 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

  • qacc is an output. Forward dynamics computes it from the equation of motion, M(q) q¨=τactuator+τpassive−c(q,q˙)+J⊤fcontactM(q)\,\ddot q = \tau_{actuator} + \tau_{passive} - c(q,\dot q) + J^\top f_{contact}, where MM is the mass matrix, cc collects gravity, Coriolis and centrifugal terms, and J⊤fJ^\top f is the contribution of contact and constraint forces.
  • ctrl is an input. MuJoCo never writes it. Your controller or policy writes it before each step. If a ctrlrange is set and limiting is active, out-of-range values are clamped when the force is computed, while the array keeps what you wrote.
  • sensordata is an output, filled in during the step. Each sensor occupies model.sensor_dim[i] consecutive entries starting at model.sensor_adr[i].
  • time advances by model.opt.timestep on every mj_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_step1 does 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_step2 does the rest: actuator forces from ctrl, the acceleration including contact and constraint forces, acceleration-dependent sensors, and finally integration of qvel, qpos and time.

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.
  • implicit and implicitfast: treat velocity-dependent forces (including actuator damping such as a position servo's kv) implicitly, which improves stability with stiff damping. The MuJoCo documentation recommends implicitfast for 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:

load.py
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 capsule
python

Now run a simple control loop. A PD controller written in Python computes a torque and writes it into data.ctrl:

pd_loop.py
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)
python

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:

named_access.py
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_RK4
python

How 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 qq:

length=gear⋅q,force=gain⋅u+b0+b1⋅length+b2⋅length˙,τjoint=gear⋅force\text{length} = \text{gear}\cdot q,\qquad \text{force} = \text{gain}\cdot u + b_0 + b_1\cdot\text{length} + b_2\cdot\dot{\text{length}},\qquad \tau_{joint} = \text{gear}\cdot\text{force}

where uu 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.

ActuatorGainBias b1b_1, b2b_2ctrl meansJoint torque (gear = 1)
<motor>10, 0Torqueτ=u\tau = u
<position kp kv>kpk_p−kp-k_p, −kv-k_vTarget angleτ=kp(u−q)−kvq˙\tau = k_p(u - q) - k_v\dot q
<velocity kv>kvk_v0, −kv-k_vTarget velocityτ=kv(u−q˙)\tau = k_v(u - \dot q)
<general>gainprmbiasprmWhatever you defineAffine in uu, length, velocity

Worked numbers for the arm above, held horizontal (q=0q = 0, gravity torque −2.45 N⋅m-2.45\ \text{N·m}):

  • Motor, gear 1. ctrl = 2.45 holds the arm level. ctrl = 3 accelerates it upward at (3−2.45)/0.083≈6.6 rad/s2(3 - 2.45)/0.083 \approx 6.6\ \text{rad/s}^2.
  • Motor, gear 10. The same ctrl = 3 now 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.8 means "go to 0.8 rad". The servo pushes harder the further the arm is from the target. Against gravity it settles where 30 (0.8−q)=2.45cos⁡q30\,(0.8 - q) = 2.45\cos q, which is about q≈0.74q \approx 0.74 rad. That steady-state error is a property of a pure proportional servo, not a bug.
  • Velocity, kv = 2. ctrl = 2 asks for 2 rad/s. Nothing holds position, so when you set ctrl = 0 the arm sags under gravity until the velocity error alone balances the weight.

Limits matter as much as gains:

  • ctrlrange with ctrllimited clamps the control signal. In current MuJoCo the default is ctrllimited="auto", which turns limiting on when a ctrlrange is given.
  • forcerange with forcelimited clamps the actuator force, before the gear is applied. This is how motor torque saturation is usually modelled. A position servo with a large kp and a small forcerange behaves like a strong spring that runs out of strength.
  • gear scales both the actuator's effective length and its output force, so with gear ≠1\neq 1 a position actuator's ctrl is a target in actuator units (gear⋅q\text{gear}\cdot q), 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:

  1. 1CAD Modelparts, materials, assemblies
  2. 2Geometry and Physical Propertiesmeshes, primitives, mass, inertia
  3. 3MJCF/URDFrobot description
  4. 4MuJoCo ModelmjModel: compiled, fixed
  5. 5Physics Solvermj_step: dynamics + contact
  6. 6Updated Robot StatemjData: qpos, qvel, time
  7. 7Sensor Datasensordata
  8. 8Controlleryour code or a policy
  9. 9Actuator Commandsdata.ctrl

Loops back: Actuator Commands → CAD Model

The first four steps happen once, when the model is built and loaded. Steps 5 to 9 repeat every timestep: the actuator commands feed back into the physics solver.

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.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

How a MuJoCo-style model (one body, one hinge joint, one actuator, jointpos/jointvel sensors) turns a control value in data.ctrl into torque, motion and sensor readings, and how motor, position and velocity actuators interpret the same ctrl number differently.

How it works

The model mirrors the MJCF shown beside it: a capsule link of mass m and length L hangs from a hinge whose axis is (0, −1, 0), so q = 0 is horizontal and positive q raises the arm. The browser treats the link as a thin uniform rod (I = mL²/3); MuJoCo would compute the full capsule inertia, including its rounded ends.

Each tick is one mj_step. The actuator force is computed with MuJoCo's affine actuator model, force = gain·ctrl + bias₁·(gear·q) + bias₂·(gear·q̇), clamped to forcerange and multiplied by the gear to give joint torque. Forward dynamics gives q̈ = (τ_act + τ_gravity − d·q̇) / I. The Euler option is semi-implicit, like MuJoCo's: velocity is updated first (with joint damping treated implicitly), then position. RK4 is the classic four-stage Runge–Kutta method.

As in MuJoCo, qacc, actuator_force and sensordata are filled in from the state at the start of the step, while qpos, qvel and time hold the integrated result.

Adjustable parameters

  • Actuator type: motor, position, velocity
  • ctrl (torque −10…10 N·m, target angle −π…π rad, or target velocity −8…8 rad/s)
  • Link mass (0.1–3 kg) and length (0.2–0.6 m)
  • Joint damping (0–2 N·m·s/rad)
  • Gear (0.5–10)
  • kp (0–300 N·m/rad) and kv (0–10 N·m·s/rad)
  • forcerange ±5 on/off, gravity on/off
  • Timestep (0.5–40 ms) and integrator (Euler, RK4)

Known limitations

  • A browser re-implementation of the equations for one hinge, not MuJoCo. No contacts, constraints, joint limits or armature.
  • Thin-rod inertia instead of MuJoCo's capsule inertia, so the numbers differ slightly from a real MuJoCo run of the same XML.
  • Euler here is implicit only in joint damping, like MuJoCo's Euler. MuJoCo's implicit and implicitfast integrators (which also treat actuator damping such as kv implicitly) are not implemented.
  • The XML viewer is a faithful description of the model, but the page does not parse it. Edits go from the sliders to the XML, not the other way round.

Equations

I q¨=τact−mgL2cos⁡q−d q˙,I=13mL2I\,\ddot q = \tau_{act} - m g \tfrac{L}{2}\cos q - d\,\dot q, \qquad I = \tfrac{1}{3} m L^2
force=clip⁡(g0 u+b1 (gear q)+b2 (gear q˙)),τact=gear⋅force\text{force} = \operatorname{clip}\big(g_0\,u + b_1\,(\text{gear}\,q) + b_2\,(\text{gear}\,\dot q)\big), \quad \tau_{act} = \text{gear}\cdot\text{force}
motor: g0=1, b=0position: g0=kp, b1=−kp, b2=−kvvelocity: g0=kv, b2=−kv\text{motor: } g_0{=}1,\ b{=}0 \quad \text{position: } g_0{=}k_p,\ b_1{=}{-k_p},\ b_2{=}{-k_v} \quad \text{velocity: } g_0{=}k_v,\ b_2{=}{-k_v}
q˙k+1=q˙k+h τact+τg−d q˙kI+h d,qk+1=qk+h q˙k+1\dot q_{k+1} = \dot q_k + h\,\frac{\tau_{act} + \tau_g - d\,\dot q_k}{I + h\,d}, \qquad q_{k+1} = q_k + h\,\dot q_{k+1}

Core update rule

// One mj_step of the arm (lib/sim/ch03-arm.ts)
const u = clamp(ctrl, ctrlrange);
const force = clip(gain * u + b1 * gear * q + b2 * gear * qd, forcerange);
const tauAct = gear * force;
const tauG = -m * g * (L / 2) * Math.cos(q);
qacc = (tauAct + tauG - damping * qd) / I;   // forward dynamics
sensordata = [q, qd];                        // jointpos, jointvel
// semi-implicit Euler with implicit joint damping
qd += h * (tauAct + tauG - damping * qd) / (I + h * damping);
q  += h * qd;
time += h;

Explained in Chapter 3: MuJoCo Internals

Things to try:

  • Motor mode, gravity on. Find the torque that holds the arm level. It should be close to mgL/2m g L/2. Then double the mass and find it again.
  • Position mode. Set a target of 0.8 rad and note where the arm settles. Increase kp and the steady-state error shrinks. Set kv to 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 = 300 and 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: time advances by one timestep, and sensordata lags qpos by 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 mjData and 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_vel and imu_lin_acc and 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 nq>nvn_q > n_v.

“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.
  • mjModel holds everything fixed (geometry, masses, gains, opt.timestep); mjData holds everything that changes (time, qpos, qvel, qacc, ctrl, sensordata, contacts).
  • qpos has nq entries and qvel has nv. 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, sensordata reflects the state at the start of the step.
  • What ctrl means depends on the actuator: torque for motor, target angle for position, target velocity for velocity, scaled by gear and clamped by ctrlrange and forcerange.

References and further reading