@vuer-ai/mujoco-ts
v0.1.1
Published
[](https://www.npmjs.com/package/@vuer-ai/mujoco-ts)
Keywords
Readme
React MuJoCo Component
React / react-three-fiber components for MuJoCo in the browser. The physics is
the official MuJoCo 4.0.1 WebAssembly bindings
(google-deepmind/mujoco wasm/),
self-built and stripped by wasm/build.sh: about 1.0 MB brotli,
single-threaded, no COOP/COEP needed. An adapter keeps the mujoco-ts
Model / State / Simulation API. The physics can run on the main thread
(default) or in a Web Worker.
Upgrading from 0.0.80 (vendored MuJoCo 3.3.6)? Read MIGRATION.md.
Installation
npm install @vuer-ai/mujoco-tsPeer dependencies: @vuer-ai/vuer ^0.0.103 || ^0.1.0, react / react-dom ^19,
@react-three/fiber ^9, @react-three/drei ^10, @react-three/xr ^6,
three >=0.178.0, leva ^0.10, zustand ^5.
Developing
pnpm install --frozen-lockfile # pnpm 10 (see "packageManager")
pnpm build # tsc + vite library build -> dist/ (index + dialSchemas entries)
pnpm test # vitest, against the committed mujoco-wasm/
pnpm check:specs --pack # after build: no workspace:/latest specs; every exports path is packedUsage
import {MuJoCoModel, MuJoCoProvider} from "@vuer-ai/mujoco-ts";
// can present the MuJoCo instance via the following:
<MuJoCoModel
ref={modelRef}
speed={speed}
src={`agility_cassie/scene.xml`}
assets={[
"agility_cassie/cassie.xml",
"agility_cassie/assets/achilles-rod.obj",
"agility_cassie/assets/cassie-texture.png",
"agility_cassie/assets/foot-crank.obj",
"agility_cassie/assets/foot.obj",
"agility_cassie/assets/heel-spring.obj",
"agility_cassie/assets/hip-pitch.obj",
"agility_cassie/assets/hip-roll.obj",
"agility_cassie/assets/hip-yaw.obj",
"agility_cassie/assets/knee-spring.obj",
"agility_cassie/assets/knee.obj",
"agility_cassie/assets/pelvis.obj",
"agility_cassie/assets/plantar-rod.obj",
"agility_cassie/assets/shin.obj",
"agility_cassie/assets/tarsus.obj"
]}/>Backends: main thread or Web Worker
<MuJoCo src="scene.xml" assets={[...]} /> // backend="main" (default)
<MuJoCo src="scene.xml" assets={[...]} backend="worker" /> // physics in a Web Worker| | main (default) | worker |
|---|---|---|
| Where mj_step runs | main thread | a module Web Worker (started from a blob: URL) |
| sim.qpos, sim.xpos, ... | live views into WebAssembly memory | JS mirrors, updated in place after each batch (typed arrays move as transferables) |
| sim.step(), forward(), resetData() | synchronous | queued; sent as one batch per microtask. await sim.flush() waits for the result. |
| Writes to ctrl, qpos, xfrc_applied, mocap_pos, ... | immediate | visible at once on the main thread; sent to the worker in order with the commands |
| jac*, mulM, getState, ... | yes | throw (use main) |
| Cross-origin isolation | not needed | not needed (no SharedArrayBuffer) |
Both backends free the model and data (.delete()) when the provider
unmounts or src changes.
Using the engine without React
import { loadMujocoModule, loadSimulation } from '@vuer-ai/mujoco-ts';
const mujoco = await loadMujocoModule(); // official module, shared
const files = new Map([['scene.xml', xmlBytes], ['assets/mesh.obj', objBytes]]);
const { model, sim } = loadSimulation(mujoco, 'scene.xml', files); // MjVFS, no Emscripten FS
for (let i = 0; i < 100; i++) sim.step();
console.log(sim.qpos, model.nbody);
sim.free();The official API is also there: sim.mjModel, sim.mjData and sim.mujoco
(mujoco.mj_step(sim.mjModel, sim.mjData), ...).
Where the wasm comes from
dist/mujoco.wasm ships next to the bundle and is fetched at run time
(new URL('./mujoco.wasm', import.meta.url)). If your bundler moves it (for
example Vite dev with a pre-bundled dependency), pass the URL yourself:
import wasmUrl from '@vuer-ai/mujoco-ts/mujoco.wasm?url';
<MuJoCo wasmUrl={wasmUrl} ... /> // or configureMujoco({ wasmUrl })The providers import the wasm glue lazily inside effects, so SSR never loads it.
Notes on File Path
The src attribute is the path to the MuJoCo XML file. We use the
parent director of this entrypoint file as the root directory, and
reference all assets relative to this root directory.
Therefore during download, we remove the common prefix assets have
with the root directory, and use the remaining path as the target
location. For instance, in the example above, the scene.xml file
is the entrypoint. Therefore we will download agility_cassie/cassie.xml
into the same directory as scene.xml inside the virtual file system
of the WebAssembly runtime.
Force Application
MuJoCo-TS provides multiple ways to apply forces and torques to bodies in your simulation.
Coordinate Systems
MuJoCo and Three.js use different coordinate systems:
- MuJoCo: X-forward, Y-left, Z-up
- Three.js: X-right, Y-up, Z-backward
Use these conversion functions:
const toMujocoCoords = (vec: THREE.Vector3) => {
return new THREE.Vector3(vec.x, -vec.z, vec.y);
};
const fromMujocoCoords = (vec: THREE.Vector3) => {
return new THREE.Vector3(vec.x, vec.z, -vec.y);
};Force Application Methods
1. Direct Force Application
Apply forces and torques at specific points using sim.applyForce():
sim.applyForce(
fx, fy, fz, // Force vector in world coordinates (N)
tx, ty, tz, // Torque vector in world coordinates (Nm)
px, py, pz, // Application point in world coordinates (m)
bodyId // Body ID to apply force to
);
// Example: Apply 10N force at body center
const bodyId = 2;
const bodyPos = sim.xpos.slice(bodyId * 3, bodyId * 3 + 3);
sim.applyForce(10, 0, 0, 0, 0, 0, bodyPos[0], bodyPos[1], bodyPos[2], bodyId);2. Generalized Forces (qfrc_applied)
Apply forces/torques directly to degrees of freedom:
// Apply torque to a hinge joint
const jointId = 3;
const dofAddress = model.jnt_dofadr[jointId];
sim.qfrc_applied[dofAddress] = 5.0; // 5 Nm torque
// Multi-DoF joints (e.g., ball joint)
sim.qfrc_applied[dofAddress + 0] = 1.0; // Roll
sim.qfrc_applied[dofAddress + 1] = 2.0; // Pitch
sim.qfrc_applied[dofAddress + 2] = 3.0; // Yaw3. Body Wrenches (xfrc_applied)
Apply wrenches at body centers of mass:
// Apply force and torque to body 2
const bodyId = 2;
const baseIndex = bodyId * 6;
sim.xfrc_applied[baseIndex + 0] = 10; // fx
sim.xfrc_applied[baseIndex + 1] = 0; // fy
sim.xfrc_applied[baseIndex + 2] = 5; // fz
sim.xfrc_applied[baseIndex + 3] = 0; // tx
sim.xfrc_applied[baseIndex + 4] = 2; // ty
sim.xfrc_applied[baseIndex + 5] = 0; // tzReact Components
AnchorActuator Component
Provides a visual interface for applying forces:
import {AnchorActuator} from '@vuer-ai/mujoco-ts';
<AnchorActuator
bodyId={2}
enabled={true}
scale={20}
forceDestination={[1, 1, 1]}
showForceVector={true}
showForceText={true}
showPivotControls={true}
/>ForceManager Hook
Register custom force handlers that run every simulation step:
import {useForceManager} from '@vuer-ai/mujoco-ts';
const MyForceComponent = () => {
const [addForceUpdateHandler] = useForceManager();
useEffect(() => {
const applyMyForce = () => {
sim.applyForce(10, 0, 0, 0, 0, 0, 0, 0, 0, bodyId);
};
const removeHandler = addForceUpdateHandler(applyMyForce);
return removeHandler; // Cleanup on unmount
}, []);
};Working with Geoms
Forces are applied to bodies, not geoms. To apply force at a geom location:
// Get the body that owns this geom
const geomId = 5;
const bodyId = model.geom_bodyid[geomId];
// Get geom position
const geomPos = sim.xgeom.slice(geomId * 3, geomId * 3 + 3);
// Apply force at geom location
sim.applyForce(fx, fy, fz, 0, 0, 0, geomPos[0], geomPos[1], geomPos[2], bodyId);Best Practices
- Always convert coordinates between Three.js and MuJoCo systems
- Clear forces when not needed:
sim.qfrc_applied.fill(0) - Validate IDs before applying forces to avoid segfaults
- Consider timestep when calculating force magnitudes
- Use the appropriate method:
applyForce()for point forcesqfrc_appliedfor joint controlxfrc_appliedfor body-level wrenches
Building the WebAssembly module
mujoco-wasm/ holds the committed build (mujoco.js, mujoco.wasm,
mujoco.d.ts) and BUILD_INFO.json, which records the pins, the flags and
the sha256 of each file. node wasm/verify.mjs checks the files against it.
pip install cmake ninja # plus node >= 18
bash wasm/build.sh # default variant -> mujoco-wasm/
bash wasm/build.sh --all # every variant -> .wasm-build/out/, prints the size table
bash wasm/build.sh release-oz release # selected variantsThe pins are in wasm/versions.env: MuJoCo tag 4.0.1
(commit 4ed093a9), emsdk 4.0.10. The script clones both into .wasm-build/
(or uses $EMSDK), checks the versions, builds the static libraries with
CMake, and compiles the official wasm/codegen/generated/bindings.cc after
wasm/strip_bindings.py removes the unused modules. It then links with em++,
runs wasm-opt, and writes BUILD_INFO.json. The build is single-threaded
(no pthreads), with no --profiling-funcs, no ASSERTIONS and no DWARF.
Paths are mapped (-ffile-prefix-map) and the link runs in a fixed directory,
so the output does not depend on where you build. Two clean trees in
different directories produced byte-identical files. One known limit: the
LLVM/Binaryen placement of wasm exception-handling try/delegate blocks in
two functions varies between link runs. Over 10 rebuilds this gave 4 distinct
mujoco.wasm hashes, all of the same size and with the same code otherwise,
and the JS glue was identical. This happened with BINARYEN_CORES=1,
--thinlto-jobs=1, --threads=1 and PYTHONHASHSEED=0 too. So
BUILD_INFO.json records the hash of the committed file. verify.mjs checks
it in PR CI, and the wasm-build workflow only warns when a rebuild differs.
CI: .github/workflows/ci.yml runs on PRs and only typechecks the engine
and runs the unit tests against the committed wasm. The emsdk build is in
.github/workflows/wasm-build.yml. It runs only by hand
(workflow_dispatch) or on a wasm-v* tag, caches emsdk, uploads the
result and, on a tag, attaches it to a GitHub release. To update the
committed build, run the script (or download the CI artifact), commit
mujoco-wasm/, and check that node wasm/verify.mjs passes.
Sizes
Sizes of each variant: raw, gzip -9 and brotli -11 (wasm/sizes.mjs).
"total" is wasm plus JS glue, after brotli. Built with MuJoCo 4.0.1 and
emsdk 4.0.10.
| Variant | What changes | wasm raw | wasm gzip | wasm brotli | js raw | js brotli | total brotli |
|---|---|---:|---:|---:|---:|---:|---:|
| 0.0.80 (old) | Vendored zalo build, MuJoCo 3.3.6 | 2.61 MB | 872 KB | 657 KB | 124 KB | 27 KB | 684 KB |
| upstream | Upstream wasm/CMakeLists.txt link flags, single-threaded: -O3, ASSERTIONS=1, -g + source map, JS exceptions, FS | 10.80 MB | 2.77 MB | 2.05 MB | 284 KB | 55 KB | 2.11 MB |
| oz | -Oz for the libraries and the link, ASSERTIONS=0, no DWARF or profiling funcs, JS exceptions, FS | 3.17 MB | 1.10 MB | 876 KB | 124 KB | 26 KB | 902 KB |
| oz-wasmopt | + wasm-opt -Oz --converge | 3.17 MB | 1.10 MB | 876 KB | 124 KB | 26 KB | 902 KB |
| oz-closure | + --closure=1 on the glue | 3.17 MB | 1.10 MB | 876 KB | 55 KB | 17 KB | 893 KB |
| nofs | + no FORCE_FILESYSTEM, no FS/MEMFS export | 3.17 MB | 1.10 MB | 876 KB | 51 KB | 15 KB | 892 KB |
| wasm-eh | + -fwasm-exceptions (libraries and link) | 2.80 MB | 1.05 MB | 838 KB | 40 KB | 14 KB | 851 KB |
| strip-vis | + strip the Mjv* / mjv_* / mjr* bindings | 2.72 MB | 1.01 MB | 810 KB | 40 KB | 14 KB | 824 KB |
| release-oz | + strip mjSpec (MjSpec, Mjs*, mjs_*) | 2.62 MB | 1009 KB | 788 KB | 40 KB | 14 KB | 802 KB |
| release-oz-emmalloc | + -sMALLOC=emmalloc | 2.61 MB | 1007 KB | 787 KB | 40 KB | 14 KB | 801 KB |
| release (default) | As release-oz, but -O2 | 4.03 MB | 1.33 MB | 1020 KB | 41 KB | 14 KB | 1.01 MB |
| release-o3 | As release-oz, but -O3 | 4.12 MB | 1.40 MB | 1.02 MB | 40 KB | 14 KB | 1.03 MB |
What each step saves (brotli, wasm + glue):
| Step | Saves | Note |
|---|---:|---|
| upstream → oz: -Oz for the libraries and the link; no ASSERTIONS, no -g or source map, -sENVIRONMENT=web,worker,node, no ccall/cwrap | 1.23 MB (−58 %) | Most of the gain. The upstream build keeps ASSERTIONS=1 and DWARF. |
| wasm-opt -Oz --converge after the link | 0 | emcc already runs wasm-opt -Oz; a second pass finds nothing. It stays in the script as a no-op guard. |
| --closure=1 (JS glue) | 9 KB | Glue 124 KB → 55 KB raw. |
| No FORCE_FILESYSTEM and no FS/MEMFS export (MjVFS only) | 1 KB | The bindings still link a small FS for mj_loadXML. |
| -fwasm-exceptions instead of JS exceptions | 41 KB | Native wasm exception handling (all evergreen browsers). It is also faster: no JS round trip on invoke_*. |
| Strip the visualizer bindings (Mjv*, mjv_*, mjr* enums) | 27 KB | mujoco-ts renders with three.js. |
| Strip the mjSpec editing API (MjSpec, Mjs*, mjs_*, parseXMLString, mj_compile) | 22 KB | Loading uses mj_loadXML + MjVFS. → release-oz, 802 KB. |
| -sMALLOC=emmalloc | 1 KB | Slower allocator; not used. |
| -O2 instead of -Oz (the default release) | −232 KB | -Oz makes mj_step about 30 % slower than the 0.0.80 build; -O2 matches it. -O3 gives no further speed. |
The default (release, -O2) is 1.01 MB brotli, inside the 1.1 MB budget,
and steps as fast as 0.0.80. release-oz (802 KB) is there when bytes matter
more than step time. For reference, the 0.0.80 build (MuJoCo 3.3.6, zalo
bindings) is 684 KB brotli; it did not have mjSpec, the 4.0 collision and
solver code, or the named-access bindings.
Parity and speed
node scripts/parity-bench.mjs (local, heavy; not in PR CI) loads the same
models in the old 0.0.80 build (from origin/main) and in the new build. It
compares qpos after N steps and reports µs per step (median of interleaved
runs). node test/browser/run.mjs --old <0.0.80 tree> runs the r3f layer in
headless Chromium on both backends and on the old build. Results are in the
PR description.
Dial Schema Generation
MuJoCo-TS uses dial annotations for generating UI control schemas. To regenerate schemas after modifying component props: Install the dial CLI globally:
npm install -g @vuer-ai/dial-cliand then you can generate the schemas
pnpm dialThis generates metadata/schema.dial from the @dial annotations in MuJoCo.tsx.
QA Pairs
A QA Pair is a library paired with its primary consumer — the package or app you run to manually verify that the library works end-to-end.
| Library | QA Consumer | How to Test |
|---------|------------|-------------|
| @vuer-ai/mujoco-ts | example/ | Run the bundled example app: cd example && yarn develop |
Credits
Built with ❤️ by Ge Yang, Yajvan Ravan, Marvin Luo, and Gio Huh at FortyFive labs.
