mujoco 3.2.5 → 3.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +440 -0
  2. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,440 @@
1
+ # MuJoCo JavaScript Bindings
2
+
3
+ These are the canonical JavaScript and TypeScript bindings for the MuJoCo
4
+ physics engine.
5
+
6
+ This package provides a high-level API that allows you to interact with the core
7
+ MuJoCo engine compiled into a high-performance WebAssembly (WASM) module. These
8
+ bindings are developed and maintained by Google DeepMind and are always up to
9
+ date with the latest developments in MuJoCo. For brevity, the documentation
10
+ below will often refer to “JavaScript” but the concepts apply equally to
11
+ TypeScript.
12
+
13
+ > [!IMPORTANT]
14
+ > _These bindings are still a WIP. For details, see the [Future Work](#future-work)
15
+ > section. Also note that development has primarily taken place on Linux using
16
+ > Google Chrome. If you're working on a different OS or browser, you may
17
+ > encounter some rough edges. We have successfully tested the bindings on MacOS
18
+ > in CI but as of November 13th 2025 Windows in untested (the instructions here
19
+ > have worked on one Windows 11 machine but have failed on other machines)._
20
+
21
+ ## Prerequisites
22
+
23
+ > [!NOTE]
24
+ > Run all the commands in this README from the top-level directory.
25
+
26
+ - To compile the [`bindings.cc`](codegen/generated/bindings.cc) file, which
27
+ generates the `.wasm` WebAssembly file, `.js` JavaScript import, and `.d.ts`
28
+ TypeScript declaration file, you will need Emscripten SDK version `4.0.10`.
29
+ Later versions may work but are untested. To set up the SDK, do the
30
+ following, you can run this anywhere but the rest of the commands in this
31
+ README only work in the shell where you source the `emsdk_env.sh` script.
32
+
33
+ ```sh
34
+ git clone https://github.com/emscripten-core/emsdk.git
35
+ ./emsdk/emsdk install 4.0.10
36
+ ./emsdk/emsdk activate 4.0.10
37
+ source ./emsdk/emsdk_env.sh
38
+ ```
39
+
40
+ - To easily run the JavaScript tests and the demo application, `node` and `npm`
41
+ are required. We recommend managing these using
42
+ [nvm](https://github.com/nvm-sh/nvm). There are also various JavaScript
43
+ dependencies needed for the tests, demo, and bindings build process. These
44
+ dependencies are expected to be located in the `wasm` folder. To install
45
+ them and ensure they can be found by later commands, run the following:
46
+
47
+ ```sh
48
+ npm install --prefix ./wasm
49
+ export PATH="$(pwd)/wasm/node_modules/.bin:$PATH"
50
+ ```
51
+
52
+ - To modify the bindings `python3` is required because the [`bindings.cc`](codegen/generated/bindings.cc)
53
+ file is generated by a Python script. To run the bindings generator tests,
54
+ `absl` is required and `pytest` will be helpful. Set up a Python environment
55
+ with these dependencies as follows:
56
+
57
+ ```sh
58
+ python3 -m venv .venv
59
+ source .venv/bin/activate
60
+ pip install -r python/build_requirements.txt
61
+ ```
62
+
63
+ > [!TIP]
64
+ > _Emscripten is well-documented. We recommend reading the sections covering the
65
+ > [Emscripten Compiler Settings](https://emscripten.org/docs/tools_reference/settings_reference.html),
66
+ > the [Emscripten SDK](https://emscripten.org/docs/tools_reference/emsdk.html),
67
+ > and the [Embind](https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html)
68
+ > library. To understand the limitations and caveats related to using the
69
+ > browser as a platform, see the
70
+ > [Porting](https://emscripten.org/docs/porting/index.html#porting) section._
71
+
72
+ ## User Guide
73
+
74
+ ### Bindings Generation
75
+
76
+ The [`bindings.cc`](codegen/generated/bindings.cc) file is compiled to generate
77
+ to `.wasm` WebAssembly file, `.js` JavaScript import, and `.d.ts` TypeScript
78
+ declaration file. These are the files you'll use to call MuJoCo from JavaScript.
79
+ To generate them ensure the npm and Emscripten SDK prerequisites are set up and
80
+ then run the following:
81
+
82
+ ```sh
83
+ emcmake cmake -B build && cmake --build build
84
+ ```
85
+
86
+ This command will generate the following folders under the project root:
87
+
88
+ - `build`: contains MuJoCo compiled using Emscripten.
89
+ - `wasm/dist`: contains the WebAssembly module, `.js` and `.d.ts` files.
90
+
91
+ ### Example Application
92
+
93
+ After generating the bindings you will be ready to write web applications using
94
+ MuJoCo. We have provided a basic web application that uses Three.js to render a
95
+ simple simulation, to try it run this command:
96
+
97
+ ```sh
98
+ npm run dev:demo --prefix ./wasm
99
+ ```
100
+
101
+ You may prefer to write your entire app in C++ and compile it using Emscripten.
102
+ If you do this, you won’t need to use these bindings, since you’ll be writing
103
+ minimal JavaScript, and the granularity of these bindings may be inappropriate
104
+ (e.g., you might want to call multiple MuJoCo functions in the C++ callback
105
+ invoked by `requestAnimationFrame`).
106
+
107
+ We have also found that a hybrid approach can be helpful, as it is often more
108
+ convenient to work with browser APIs directly in JavaScript. If you choose to
109
+ write your application in C++ and compile it using Emscripten, you may want to
110
+ copy a subset of the `EMSCRIPTEN_BINDINGS` from `bindings.cc` into your
111
+ application’s source file.
112
+
113
+ The package is ESM (`type: module`) and ships TypeScript types.
114
+ Ensure your bundler or dev server serves the `.wasm` asset at runtime.
115
+
116
+ ### Named Access
117
+
118
+ The bindings support named access methods, similar to the Python bindings,
119
+ allowing convenient access to model and data elements by name or index. For
120
+ example, you can access a geometry by name using `model.geom('mygeom')` or a
121
+ joint using `data.jnt('myjoint')`.
122
+
123
+ For more details and examples of how to use named access, please refer to the [named access tests](tests/bindings_test.ts#L1876-L2378) and [documentation](https://mujoco.readthedocs.io/en/stable/python.html#named-access).
124
+
125
+ ### Memory Management
126
+ Embind-wrapped C++ object handles created or returned into JavaScript live on the
127
+ WebAssembly heap and are **not** garbage-collected by the JS runtime.
128
+
129
+ Any heap-allocated C++ object exposed to JS (e.g. via `new Module.MyClass(...)`
130
+ or returned as a pointer/reference from a binding) must be explicitly freed
131
+ when no longer needed to avoid memory leaks.
132
+
133
+ Use the generated `.delete()` method on wrapped instances to destroy the
134
+ underlying C++ object:
135
+
136
+ ```typescript
137
+ const obj = new Module.MyClass(...);
138
+ // ... use obj ...
139
+ obj.delete(); // free the C++ memory
140
+ ```
141
+
142
+ Be careful to call `.delete()` exactly once per created object (double-delete
143
+ is an error). In JS code paths that may throw or return early, ensure
144
+ deletion happens in finally blocks or wrap lifetime management to avoid leaks.
145
+
146
+ > [!IMPORTANT]
147
+ > _Embind's documentation strongly recommends that JavaScript code explicitly deletes any C++ object handles it has received._
148
+
149
+ ### Copy vs. Reference
150
+
151
+ When interacting with MuJoCo objects through the WASM bindings, it's important to understand how data is accessed. Properties on objects like `MjModel` and `MjData` can expose data in two ways: by copy or by reference.
152
+
153
+ #### 1. By Copy (Value-based access)
154
+
155
+ Some properties return a copy of the data at the time of access. This is common for complex data structures that need to be marshalled from C++ to JavaScript.
156
+
157
+ A key example is `MjData.contact`. When you access `data.contact`, you get an object containing a copy of the contacts at that specific moment in the simulation.
158
+
159
+ If you step the simulation forward, they will not be updated. You must access `data.contact` again to get the new contact information.
160
+
161
+ The object you get is a JavaScript proxy interface generated by [Emscripten’s Embind library](https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#built-in-type-conversions) when you expose a `std::vector` using `register_vector<T>`. It is essentially a "bridge" object.
162
+
163
+ ```typescript
164
+ export interface MjContactVec extends ClassHandle {
165
+ /** Appends a new element to the end of the vector, increasing its length by one. */
166
+ push_back(_0: MjContact): void;
167
+ /** Resizes the vector to contain the specified number of elements, filling new slots with the provided value. */
168
+ resize(_0: number, _1: MjContact): void;
169
+ /** Returns the total number of elements currently stored in the vector. */
170
+ size(): number;
171
+ /** Retrieves the element at the specified index, or returns undefined if the index is out of bounds. */
172
+ get(_0: number): MjContact | undefined;
173
+ /** Overwrites the element at the specified index; returns true if successful or false if the index is invalid. */
174
+ set(_0: number, _1: MjContact): boolean;
175
+ }
176
+ ```
177
+
178
+ Example:
179
+ ```typescript
180
+ // Gets contacts at the current time.
181
+ const contacts = data.contact;
182
+
183
+ // Step the simulation
184
+ mujoco.mj_step(model, data);
185
+
186
+ // `contacts` is now stale. To get the new contacts, you must access the property again:
187
+ const newContacts = data.contact;
188
+
189
+ // Remember to delete all created objects when they are no longer needed.
190
+ contacts.delete();
191
+ newContacts.delete();
192
+ ```
193
+
194
+ #### 2. By Reference (View-based access)
195
+
196
+ Many properties, especially large numerical arrays, return a live view directly into the WebAssembly memory. This is highly efficient as it avoids copying large amounts of data.
197
+
198
+ A key example is `MjData.qpos` (joint positions). When you get a reference to this array, it points directly to the simulation's state data. Any changes in the simulation (e.g., after a call to `mj_step`) will be immediately reflected in this array.
199
+
200
+ ```typescript
201
+ // `qpos` is a live view into the simulation state.
202
+ const qpos = data.qpos;
203
+
204
+ console.log(qpos[0]); // Print initial position
205
+
206
+ // Step the simulation
207
+ mujoco.mj_step(model, data);
208
+
209
+ // `qpos` is automatically updated.
210
+ console.log(qpos[0]); // Print new position
211
+
212
+ // Remember to delete all created objects when they are no longer needed.
213
+ data.delete();
214
+ ```
215
+
216
+ ### Data Layout: Row-Major Matrices
217
+
218
+ When a function from the MuJoCo C API returns a matrix (or needs a matrix as input), these are represented in the JavaScript bindings as flat, one-dimensional `TypedArray`'s. The elements are stored in row-major order.
219
+
220
+ For example, a 3x10 matrix will be returned as a flat array with 30 elements. The first 10 elements represent the first row, the next 10 represent the second row, and so on.
221
+
222
+ Example: Accessing an element at `(row, col)`
223
+ ```typescript
224
+ // A 3x10 matrix stored as a flat array.
225
+ const matrix: Float64Array = ...;
226
+ const nRows = 3;
227
+ const nCols = 10;
228
+
229
+ // To access the element at row `i` and column `j`:
230
+ const element = matrix[i * nCols + j];
231
+ ```
232
+
233
+ ### Working with Out Parameters
234
+
235
+ Many functions in the MuJoCo C API use "out parameters" to return data. This means instead of returning a value, they write the result into one of the arguments passed to them by reference (using pointers). In our JavaScript bindings, you'll need to handle these cases specifically.
236
+
237
+ There are two main scenarios you'll encounter:
238
+
239
+ #### 1. Array-like Out Parameters
240
+
241
+ When a function expects a pointer to a primitive type (like `mjtNum*` or `int*`) to write an array of values, you need to pre-allocate memory for the result on the JavaScript side. We provide helper classes for this: `mujoco.Uint8Buffer`, `mujoco.DoubleBuffer`, `mujoco.FloatBuffer`, and `mujoco.IntBuffer`.
242
+
243
+ Here's how to use them:
244
+
245
+ 1. Create a buffer: Instantiate the appropriate buffer class with an initial array of the correct size (e.g., an array of zeros).
246
+ 2. Call the function: Pass the buffer instance to the function as the out parameter.
247
+ 3. Access the result: Use the `.getView()` method on the buffer to get a `TypedArray` view of the data written by the C++ function.
248
+ 4. Free the memory: When you are done with the buffer, you must call the `.delete()` method to free the underlying memory and prevent memory leaks.
249
+
250
+ Example: Rotating a vector
251
+
252
+ The function `mju_rotVecQuat` rotates a vector `vec` by a quaternion `quat` and stores the result in the `res` out parameter.
253
+
254
+ ```typescript
255
+ // Create a buffer to hold the 3D vector result.
256
+ const res = new mujoco.DoubleBuffer([0, 0, 0]);
257
+
258
+ const vec = [1, 0, 0];
259
+ const quat = [0.707, 0, 0, 0.707]; // 90-degree rotation around z-axis
260
+
261
+ try {
262
+ // Call the function with the buffer as the out parameter.
263
+ mujoco.mju_rotVecQuat(res, vec, quat);
264
+
265
+ // Get the result as a Float64Array.
266
+ const resultView = res.getView();
267
+ console.log(resultView); // Expected: approximately [0, 1, 0]
268
+
269
+ } finally {
270
+ // IMPORTANT: Free the memory allocated for the buffer.
271
+ res.delete();
272
+ }
273
+ ```
274
+
275
+ #### 2. Struct Out Parameters (e.g., mjvCamera*, mjvScene*)
276
+
277
+ When a function modifies a struct passed by pointer, you should pass an instance of the corresponding JavaScript wrapper class. The underlying C++ struct will be modified in place.
278
+
279
+ Example: Updating a scene
280
+
281
+ The function `mjv_updateScene` populates an `mjvScene` object with information from `mjModel` and `mjData`.
282
+ ```typescript
283
+ // Create instances of the necessary structs.
284
+ const model = mujoco.MjModel.loadFromXML(xmlContent);
285
+ const data = new mujoco.MjData(model);
286
+ const scene = new mujoco.MjvScene(model, 1000);
287
+ const option = new mujoco.MjvOption();
288
+ const perturb = new mujoco.MjvPerturb();
289
+ const camera = new mujoco.MjvCamera();
290
+
291
+ // ... (step simulation, etc.)
292
+
293
+ // Update the scene. The 'scene' object is modified by the function.
294
+ mujoco.mjv_updateScene(
295
+ model,
296
+ data,
297
+ option,
298
+ perturb,
299
+ camera,
300
+ mujoco.mjtCatBit.mjCAT_ALL.value,
301
+ scene
302
+ );
303
+
304
+ console.log('Number of geoms in scene:', scene.ngeom);
305
+
306
+ // Remember to delete all created objects when they are no longer needed.
307
+ scene.delete();
308
+ camera.delete();
309
+ perturb.delete();
310
+ option.delete();
311
+ data.delete();
312
+ model.delete();
313
+ ```
314
+
315
+ As with buffers, you are responsible for managing the memory of these struct instances and must call `.delete()` on them when you are finished.
316
+
317
+ ### Enums
318
+ Access via `.value`:
319
+ ```javascript
320
+ mujoco.mjtDisableBit.mjDSBL_CLAMPCTRL.value
321
+ ```
322
+
323
+ ### Constants
324
+ Scalar constants will be accessed the same way they are on python, simply:
325
+
326
+ ```javascript
327
+ mujoco.mjNEQDATA
328
+ ```
329
+
330
+ Due to Embind limitations, more complex constants that are not scalar, but are represented in more dimensions are exposed as functions. E.g to use `mujoco.mjFRAMESTRING` you will need to call a function:
331
+
332
+ ```javascript
333
+ mujoco.get_mjFRAMESTRING()
334
+ ```
335
+
336
+ This will return a javascript array representation of the values in MuJoCo `mjFRAMESTRING`.
337
+
338
+ ## Development
339
+
340
+ In order to change the bindings you will need to change the [`bindings.cc`](codegen/generated/bindings.cc)
341
+ file but this should not be done manually. The file is generated using the
342
+ Python scripts and template files in the [`codegen`](codegen) folder, to edit
343
+ the bindings you will need to change those files and re-generate [`bindings.cc`](codegen/generated/bindings.cc)
344
+ using this command:
345
+
346
+ ```sh
347
+ PYTHONPATH=python/mujoco python3 -m wasm.codegen.update
348
+ ```
349
+
350
+ The codegen scripts use MuJoCo’s Python introspect library to generate the
351
+ Embind `EMSCRIPTEN_BINDINGS` block that binds C++ functions and classes to
352
+ JavaScript. The functions and classes that are bound are wrappers around
353
+ MuJoCo's C API. These wrappers provide a convenient place to add features like
354
+ bounds checking and nice error reporting.
355
+
356
+ ### Testing
357
+
358
+ 1. **JavaScript API tests.**
359
+ These verify that a wide variety of MuJoCo functions and classes work
360
+ correctly when called from JavaScript. Run the tests as follows:
361
+
362
+ ```sh
363
+ npm run test --prefix ./wasm
364
+ ```
365
+
366
+ 2. **JavaScript API benchmark tests.**
367
+ The current benchmark tests check JavaScript/C++ shared memory buffers
368
+ performance. We will increase the coverage of the benchmarks overtime. Run
369
+ the benchmarks using this command:
370
+
371
+ ```sh
372
+ npm run benchmark --prefix ./wasm
373
+ ```
374
+
375
+ 3. **Bindings generator tests.**
376
+ These are relevant when developing or extending the bindings. The following
377
+ command finds and runs all `test_*.py` or `*_test.py` files in the `wasm`
378
+ folder:
379
+
380
+ ```sh
381
+ PYTHONPATH=python/mujoco python3 -m pytest ./wasm
382
+ ```
383
+
384
+ ### Debugging
385
+
386
+ We provide a “sandbox” app where you can quickly write code to run in your
387
+ browser. Write your code in the [`main.ts`](tests/sandbox/main.ts) file and use
388
+ the following command to execute it in your browser:
389
+
390
+ ```sh
391
+ npm run dev:sandbox --prefix ./wasm
392
+ ```
393
+
394
+ The page will be blank since the script only logs to the console output. You
395
+ can add your code at the indicated placeholder and use Chrome DevTools for
396
+ debugging. It is possible to set up a debug workflow where stack traces and
397
+ stepping through code across language boundaries work correctly. Our current
398
+ method to do this only works internally at Google, but it should be possible to
399
+ replicate the experience with open-source tooling — community suggestions are
400
+ welcome!
401
+
402
+ ## Versioning
403
+ Package versions follow the official MuJoCo release versions.
404
+ For example:
405
+
406
+ | npm version | MuJoCo version |
407
+ |-------------|----------------|
408
+ | 3.5.0 | 3.5.0 |
409
+
410
+ ## Future Work
411
+
412
+ 1. **Bind all useful APIs.**
413
+ These bindings are not yet complete. While the main MuJoCo APIs (`mj_step`,
414
+ `mj_loadXML`, etc.) are well tested, other APIs (e.g., functions from
415
+ `mjspec.h`) remain untested in real web applications (though test code for
416
+ the `mjspec` bindings does exist).
417
+
418
+ 2. **Improve the developer experience.**
419
+ There is still work to be done to improve the developer experience when
420
+ developing the WASM bindings. The most obvious issue is that bindings
421
+ generation is not yet fully automated. As a result, it is currently less
422
+ convenient than we'd like to identify and apply the changes needed to update
423
+ the bindings. The goal is to eventually automate all binding code generation
424
+ and clearly communicate what changes are required in the WASM bindings as a
425
+ result of C++ updates. This problem should only affect developers working on
426
+ the MuJoCo engine in C++, not end users writing JavaScript.
427
+
428
+ 3. **Improve the documentation.**
429
+ The documentation in this README will eventually be merged into the main
430
+ MuJoCo documentation once the bindings are complete and named access is
431
+ implemented. We also intend to review the bindings APIs and make adjustments
432
+ to minimize differences with the Python bindings (while respecting language
433
+ idioms) to reduce the amount of additional documentation required.
434
+
435
+ 4. **Improve the [example](#example-application).**
436
+ We aim to provide an example application that can be easily modified and
437
+ embedded into a paper project page (see [this example](https://kzakka.com/robopianist/)).
438
+ This could be achieved by extending the Three.js example or by compiling the
439
+ MuJoCo platform C++ code using the Emscripten toolchain. Community
440
+ suggestions and contributions are welcome!
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mujoco",
3
- "version": "3.2.5",
3
+ "version": "3.2.6",
4
4
  "description": "MuJoCo WASM bindings",
5
5
  "repository": {
6
6
  "type": "git",