### Basic MuJoCo Simulation in C Source: https://mujoco.readthedocs.io/en/stable Loads an MJCF model, makes the corresponding data, runs the simulation for 10 seconds, and then cleans up resources. This is a fundamental example for starting simulations. ```c #include "mujoco.h" #include "stdio.h" char error[1000]; mjModel* m; mjData* d; int main(void) { // load model from file and check for errors m = mj_loadXML("hello.xml", NULL, error, 1000); if (!m) { printf("%s\n", error); return 1; } // make data corresponding to model d = mj_makeData(m); // run simulation for 10 seconds while (d->time < 10) mj_step(m, d); // free model and data mj_deleteData(d); mj_deleteModel(m); return 0; } ``` -------------------------------- ### Minimal MuJoCo Simulation with MJWarp Source: https://mujoco.readthedocs.io/en/stable/mjwarp/index.html This example demonstrates a basic simulation setup using MJWarp. It initializes a model, creates simulation data for multiple worlds, sets initial velocities, and runs the simulation. ```python # Throw a ball at 100 different velocities. import mujoco import mujoco_warp as mjw import warp as wp _MJCF=r""" """ mjm = mujoco.MjModel.from_xml_string(_MJCF) m = mjw.put_model(mjm) d = mjw.make_data(mjm, nworld=100) # initialize velocities wp.copy(d.qvel, wp.array([[float(i) / 100, 0, 0, 0, 0, 0] for i in range(100)], dtype=float)) # simulate physics mjw.step(m, d) print(f'qpos:\n{d.qpos.numpy()}') ``` -------------------------------- ### Install mujoco-warp from Source Source: https://mujoco.readthedocs.io/en/stable/_sources/mjwarp/index.rst.txt Clone the repository and install dependencies using uv. ```shell git clone https://github.com/google-deepmind/mujoco_warp.git cd mujoco_warp uv sync --all-extras ``` -------------------------------- ### Cable Plugin Example Source: https://mujoco.readthedocs.io/en/stable/_sources/changelog.rst.txt An example XML file demonstrating the formation of plectoneme using the new cable plugin. ```xml ``` -------------------------------- ### Example Record Command Source: https://mujoco.readthedocs.io/en/stable/programming/samples.html An example of how to use the record command to create a 5-second animation at 60 frames per second, saving the output to rgb.out. ```bash record humanoid.xml 5 60 rgb.out ``` -------------------------------- ### Minimal MJWarp Simulation Example Source: https://mujoco.readthedocs.io/en/stable/_sources/mjwarp/index.rst.txt This snippet demonstrates a basic MJWarp simulation. It initializes a model and data for 100 parallel worlds, sets initial velocities, runs a simulation step, and prints the resulting positions. Ensure mujoco, mujoco_warp, and warp are installed. ```python # Throw a ball at 100 different velocities. import mujoco import mujoco_warp as mjw import warp as wp _MJCF=r""" " mjm = mujoco.MjModel.from_xml_string(_MJCF) m = mjw.put_model(mjm) d = mjw.make_data(mjm, nworld=100) # initialize velocities wp.copy(d.qvel, wp.array([[float(i) / 100, 0, 0, 0, 0, 0] for i in range(100)], dtype=float))) # simulate physics mjw.step(m, d) print(f'qpos:\n{d.qpos.numpy()}') ``` -------------------------------- ### Coil Example with Cable Plugin Source: https://mujoco.readthedocs.io/en/stable/_sources/changelog.rst.txt An example XML file demonstrating a curved equilibrium configuration using the cable plugin. ```xml ``` -------------------------------- ### Basic MuJoCo Simulation Setup Source: https://mujoco.readthedocs.io/en/stable/_sources/overview.rst.txt This C code snippet demonstrates the basic setup for simulating a MuJoCo model. It includes necessary headers and initializes the mjModel and mjData structures, which are fundamental for any MuJoCo simulation. ```c #include "mujoco.h" #include "stdio.h" char error[1000]; mjModel* m; mjData* d; ``` -------------------------------- ### Install MuJoCo Source: https://mujoco.readthedocs.io/en/stable/_sources/programming/index.rst.txt Install the built MuJoCo library and associated files to the specified installation directory after the build process is complete. ```shell cmake --install . ``` -------------------------------- ### Belt Example with Cable Plugin Source: https://mujoco.readthedocs.io/en/stable/_sources/changelog.rst.txt An example XML file demonstrating interaction between twist and anisotropy using the cable plugin. ```xml ``` -------------------------------- ### Minimal MuJoCo Example Source: https://mujoco.readthedocs.io/en/stable/_sources/python.rst.txt A basic example demonstrating how to load an XML model, initialize physics data, and run simulation steps. It includes loading assets from files and printing geom positions. ```python import mujoco XML=r""" """ ASSETS=dict() with open('/path/to/gizmo.stl', 'rb') as f: ASSETS['gizmo.stl'] = f.read() model = mujoco.MjModel.from_xml_string(XML, ASSETS) data = mujoco.MjData(model) while data.time < 1: mujoco.mj_step(model, data) print(data.geom_xpos) ``` -------------------------------- ### MuJoCo Record Example Source: https://mujoco.readthedocs.io/en/stable/_sources/programming/samples.rst.txt Example of using the 'record' command to create a 5-second animation at 60 frames per second, saving raw output to 'rgb.out'. ```Shell record humanoid.xml 5 60 rgb.out ``` -------------------------------- ### Minimal MuJoCo Viewer Launch Example Source: https://mujoco.readthedocs.io/en/stable/_sources/python.rst.txt A basic example demonstrating how to launch the MuJoCo viewer in passive mode and keep the physics simulation running for a limited time. It includes stepping the physics and toggling contact points visualization. ```python import time import mujoco import mujoco.viewer m = mujoco.MjModel.from_xml_path('/path/to/mjcf.xml') d = mujoco.MjData(m) with mujoco.viewer.launch_passive(m, d) as viewer: # Close the viewer automatically after 30 wall-seconds. start = time.time() while viewer.is_running() and time.time() - start < 30: step_start = time.time() # mj_step can be replaced with code that also evaluates # a policy and applies a control signal before stepping the physics. mujoco.mj_step(m, d) # Example modification of a viewer option: toggle contact points every two seconds. with viewer.lock(): viewer.opt.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT] = int(d.time % 2) ``` -------------------------------- ### Install MuJoCo XLA (MJX) Source: https://mujoco.readthedocs.io/en/stable/_sources/mjx.rst.txt Install the core MJX package using pip. ```shell pip install mujoco-mjx ``` -------------------------------- ### Install MJX with MuJoCo Warp support Source: https://mujoco.readthedocs.io/en/stable/_sources/mjx.rst.txt Install MJX with the optional MuJoCo Warp backend using pip. ```shell pip install mujoco-mjx[warp] ``` -------------------------------- ### Contact Margin and Gap Migration Example Source: https://mujoco.readthedocs.io/en/stable/changelog.html This example shows how to migrate old margin and gap values to new ones to maintain identical behavior after the redesign. The new semantics clarify geometric inflation and detection buffers. ```text margin_new = margin_old - gap_old gap_new = gap_old For example, a geom with the old attributes `margin="0.1" gap="0.1"` should be changed to `margin="0" gap="0.1"`. ``` -------------------------------- ### Example Model for Refsite Attribute Source: https://mujoco.readthedocs.io/en/stable/_sources/changelog.rst.txt This example model demonstrates Cartesian 6D end-effector control using the new refsite attribute for actuators with site transmission. ```xml ``` -------------------------------- ### Installing MuJoCo Bindings from Source Distribution Source: https://mujoco.readthedocs.io/en/stable/_sources/python.rst.txt Installs the MuJoCo Python bindings using pip from the generated source distribution tarball. Ensure MUJOCO_PATH and MUJOCO_PLUGIN_PATH environment variables are set to the correct MuJoCo library and plugin directories. ```shell cd dist MUJOCO_PATH=/PATH/TO/MUJOCO \ MUJOCO_PLUGIN_PATH=/PATH/TO/MUJOCO/PLUGIN \ pip install mujoco-x.y.z.tar.gz ``` -------------------------------- ### Basic Flexcomp Example Source: https://mujoco.readthedocs.io/en/stable/XMLreference.html This example demonstrates a simple flexcomp modeling a flexible double pendulum with one end pinned to the world. It defines a grid-based flexcomp with 3 points, where the first point is pinned. ```XML ``` -------------------------------- ### Minimal MJX Example: Throwing a Ball Source: https://mujoco.readthedocs.io/en/stable/_sources/mjx.rst.txt A minimal example demonstrating how to load a MuJoCo model, create an MJX data structure, and step the simulation using JAX for batched velocity inputs. This snippet requires JAX and MuJoCo. ```python # Throw a ball at 100 different velocities. import jax import mujoco from mujoco import mjx XML=r""" " model = mujoco.MjModel.from_xml_string(XML) mjx_model = mjx.put_model(model) @jax.vmap def batched_step(vel): mjx_data = mjx.make_data(mjx_model) qvel = mjx_data.qvel.at[0].set(vel) mjx_data = mjx_data.replace(qvel=qvel) pos = mjx.step(mjx_model, mjx_data).qpos[0] return pos vel = jax.numpy.arange(0.0, 1.0, 0.01) pos = jax.jit(batched_step)(vel) print(pos) ``` -------------------------------- ### Get MuJoCo Version Number Source: https://mujoco.readthedocs.io/en/stable/APIreference/APIfunctions.html Returns the version number of the MuJoCo library. For example, version 1.0.2 is encoded as 102. ```c int mj_version(void); ``` -------------------------------- ### Simple MuJoCo MJCF Model Source: https://mujoco.readthedocs.io/en/stable/_sources/overview.rst.txt This example defines a basic MuJoCo model including a world body, a light source, a ground plane, and a floating box with a free joint. It's a starting point for defining scenes in MuJoCo. ```xml ``` -------------------------------- ### Building MuJoCo Documentation Locally Source: https://mujoco.readthedocs.io/en/stable/programming/index.html Navigate to the 'doc' directory and install dependencies using pip to build the documentation locally. ```bash cd mujoco/doc pip install -r requirements.txt ``` -------------------------------- ### XML for Body-Level Randomization Example Source: https://mujoco.readthedocs.io/en/stable/_sources/mjwarp/index.rst.txt This XML defines a base MuJoCo model with an asset containing three meshes (mA, mB, mC) and a world body containing two geom slots. The first geom is assigned mesh 'mA', while the second is a disabled placeholder. This setup allows for body-level randomization by changing the assigned meshes and properties of these geoms. ```xml ``` -------------------------------- ### Running MuJoCo Code Samples Source: https://mujoco.readthedocs.io/en/stable/_sources/programming/index.rst.txt Examples of how to run the MuJoCo simulator executable from the command line on different operating systems. Ensure you are in the 'bin' subdirectory. ```Text Windows: simulate ..\model\humanoid\humanoid.xml Linux and macOS: ./simulate ../model/humanoid/humanoid.xml ``` -------------------------------- ### Example: Print XML Dependencies Source: https://mujoco.readthedocs.io/en/stable/changelog.html The `dependencies` sample utility prints the result of `mju_getXMLDependencies`. ```bash dependencies ``` -------------------------------- ### Install MuJoCo XLA (MJX) Source: https://mujoco.readthedocs.io/en/stable/mjx.html Install the MJX package using pip. To use MuJoCo Warp with MJX, install with the 'warp' extra. ```bash pip install mujoco-mjx ``` ```bash pip install mujoco-mjx[warp] ``` -------------------------------- ### Install mujoco-warp from PyPI Source: https://mujoco.readthedocs.io/en/stable/_sources/mjwarp/index.rst.txt Install the mujoco-warp package using pip. ```shell pip install mujoco-warp ``` -------------------------------- ### Check if Warp is Installed Source: https://mujoco.readthedocs.io/en/stable/_modules/mujoco/mjx/_src/io.html Raises a RuntimeError if the warp-lang library is not installed, preventing the use of the WARP implementation of MJX. ```python def _check_warp_installed(): if not mjxw.WARP_INSTALLED: raise RuntimeError( 'warp-lang is not installed. Cannot use WARP implementation of MJX.' ) ``` -------------------------------- ### Basic MuJoCo Simulation Loop (C/C++) Source: https://mujoco.readthedocs.io/en/stable/_sources/overview.rst.txt This C/C++ snippet shows the fundamental steps for loading an XML model, initializing simulation data, running the simulation for a specified duration, and cleaning up resources. ```c int main(void) { // load model from file and check for errors m = mj_loadXML("hello.xml", NULL, error, 1000); if (!m) { printf("%s\n", error); return 1; } // make data corresponding to model d = mj_makeData(m); // run simulation for 10 seconds while (d->time < 10) mj_step(m, d); // free model and data mj_deleteData(d); mj_deleteModel(m); return 0; } ``` -------------------------------- ### Example Model for Catenary Visualization Source: https://mujoco.readthedocs.io/en/stable/_sources/changelog.rst.txt This example model demonstrates the visualization of hanging tendons using the catenary curve. ```xml ``` -------------------------------- ### Using MjVfs Directly Source: https://mujoco.readthedocs.io/en/stable/python.html Shows how to use MjVfs by directly creating an instance and manually closing it. Remember to call `close()` when done. ```python import mujoco vfs = mujoco.MjVfs() vfs["model.xml"] = some_xml_string.encode("utf-8") spec = mujoco.MjSpec.from_file("model.xml", vfs=vfs) spec.compile(vfs=vfs) vfs.close() ``` -------------------------------- ### Install MuJoCo with USD support Source: https://mujoco.readthedocs.io/en/stable/_sources/python.rst.txt Install the optional dependencies for the USD exporter using pip. This includes 'usd-core' and 'pillow'. ```shell pip install mujoco[usd] ``` -------------------------------- ### Multithreaded Simulation Setup with OpenMP Source: https://mujoco.readthedocs.io/en/stable/_sources/programming/simulation.rst.txt This snippet demonstrates how to set up a multithreaded simulation environment using OpenMP. It includes preparing OpenMP, allocating per-thread mjData structures, executing a parallel section with worker threads, and cleaning up the allocated data. ```C // prepare OpenMP int nthread = omp_get_num_procs(); // get number of logical cores omp_set_dynamic(0); // disable dynamic scheduling omp_set_num_threads(nthread); // number of threads = number of logical cores // allocate per-thread mjData mjData* d[64]; for (int n=0; n < nthread; n++) d[n] = mj_makeData(m); // ... serial code, perhaps using its own mjData* dmain // parallel section #pragma omp parallel { int n = omp_get_thread_num(); // thread-private variable with thread id (0 to nthread-1) // ... initialize d[n] from results in serial code // thread function worker(m, d[n]); // shared mjModel (read-only), per-thread mjData (read-write) } // delete per-thread mjData for (int n=0; n < nthread; n++) mj_deleteData(d[n]); ``` -------------------------------- ### Configure MuJoCo Installation Path Source: https://mujoco.readthedocs.io/en/stable/_sources/programming/index.rst.txt Configure the MuJoCo build with CMake, specifying a custom installation directory using the CMAKE_INSTALL_PREFIX variable. ```shell cmake $PATH_TO_CLONED_REPO -DCMAKE_INSTALL_PREFIX= ``` -------------------------------- ### Basic USD Exporter Usage Source: https://mujoco.readthedocs.io/en/stable/python.html Demonstrates initializing USDExporter, stepping through a simulation, updating the scene with new frames, and saving the final USD file. Ensure optional dependencies are installed before use. ```python import mujoco from mujoco.usd import exporter m = mujoco.MjModel.from_xml_path('/path/to/mjcf.xml') d = mujoco.MjData(m) # Create the USDExporter exp = exporter.USDExporter(model=m) duration = 5 framerate = 60 while d.time < duration: # Step the physics mujoco.mj_step(m, d) if exp.frame_count < d.time * framerate: # Update the USD with a new frame exp.update_scene(data=d) # Export the USD file exp.save_scene(filetype="usd") ``` -------------------------------- ### Example Model for Weld Constraints Source: https://mujoco.readthedocs.io/en/stable/_sources/changelog.rst.txt This example model demonstrates various uses of the new weld attributes, including torquescale and anchor. ```xml ``` -------------------------------- ### Install MuJoCo Python Package Source: https://mujoco.readthedocs.io/en/stable/_sources/python.rst.txt Install the MuJoCo Python package using pip. This includes a copy of the MuJoCo library, so no separate download is needed. ```shell pip install mujoco ``` -------------------------------- ### Enable USD Support with Pre-built USD and pxr_DIR Source: https://mujoco.readthedocs.io/en/stable/OpenUSD/building.html Configure MuJoCo to use a pre-built USD library by passing the `MUJOCO_WITH_USD` and `pxr_DIR` flags. This command sets the flags and builds MuJoCo. ```bash cd ~/mujoco cmake -Bbuild -S. -DMUJOCO_WITH_USD=True -Dpxr_DIR=/path/to/my_usd_install_dir cmake --build build -j 64 ``` -------------------------------- ### Build USD with build_usd.py Script Source: https://mujoco.readthedocs.io/en/stable/OpenUSD/building.html Build USD using its `build_usd.py` script for more customization. It is recommended to use a separate installation directory outside the cloned repository. ```bash git clone https://github.com/PixarAnimationStudios/OpenUSD python OpenUSD/build_scripts/build_usd.py /path/to/my_usd_install_dir ``` -------------------------------- ### Initializing MuJoCo Viewer Scene Source: https://mujoco.readthedocs.io/en/stable/_sources/python.rst.txt Demonstrates initializing an mjvScene with specific parameters using a constructor overload that corresponds to a C initialization function. ```python mujoco.MjvScene(model, maxgeom=10) ``` -------------------------------- ### Generated XML for Flexcomp Example Source: https://mujoco.readthedocs.io/en/stable/_sources/XMLreference.rst.txt This snippet shows the XML structure generated after loading and saving the 'flexcomp' example. It details the automatically created bodies, joints, and the deformable flex element. ```xml ``` -------------------------------- ### Build MuJoCo Documentation Source: https://mujoco.readthedocs.io/en/stable/_sources/programming/index.rst.txt Build the MuJoCo documentation locally by navigating to the doc directory, installing requirements, and running the make command. ```shell cd mujoco/doc ``` ```shell pip install -r requirements.txt ``` ```shell make html ``` -------------------------------- ### Flexcomp Example: Flexible Double Pendulum Source: https://mujoco.readthedocs.io/en/stable/_sources/XMLreference.rst.txt This example demonstrates the usage of the 'flexcomp' element to model a flexible double pendulum with one end pinned to the world. It shows the initial XML definition. ```xml ``` -------------------------------- ### Launching Reset Kernels Source: https://mujoco.readthedocs.io/en/stable/_modules/mujoco_warp/_src/io.html Demonstrates launching various reset kernels for different simulation components like applied forces, mass matrices, mocap data, contacts, and world states. These are conditional on a reset input. ```python reset_input = reset or wp.ones(d.nworld, dtype=bool) wp.launch(reset_xfrc_applied, dim=(d.nworld, m.nbody, 6), inputs=[reset_input], outputs=[d.xfrc_applied]) wp.launch( reset_qM, dim=(d.nworld, d.qM.shape[1], d.qM.shape[2]), inputs=[reset_input], outputs=[d.qM], ) # set mocap_pos/quat = body_pos/quat for mocap bodies wp.launch( reset_mocap, dim=(d.nworld, m.nbody), inputs=[m.body_mocapid, m.body_pos, m.body_quat, reset_input], outputs=[d.mocap_pos, d.mocap_quat], ) # clear contacts wp.launch( reset_contact, dim=d.naconmax, inputs=[d.nacon, reset_input, d.contact.efc_address.shape[1]], outputs=[ d.contact.dist, d.contact.pos, d.contact.frame, d.contact.includemargin, d.contact.friction, d.contact.solref, d.contact.solreffriction, d.contact.solimp, d.contact.dim, d.contact.geom, d.contact.flex, d.contact.vert, d.contact.efc_address, d.contact.worldid, d.contact.type, d.contact.geomcollisionid, ], ) wp.launch( reset_nworld, dim=d.nworld, inputs=[m.nq, m.nv, m.nu, m.na, m.neq, m.nsensordata, m.qpos0, m.eq_active0, d.nworld, reset_input], outputs=[ d.solver_niter, d.ne, d.nf, d.nl, d.nefc, d.time, d.energy, d.qpos, d.qvel, d.act, d.qacc_warmstart, d.ctrl, d.qfrc_applied, d.eq_active, d.qacc, d.act_dot, d.sensordata, d.nacon, ], ) ``` -------------------------------- ### Simple MuJoCo Control Callback Source: https://mujoco.readthedocs.io/en/stable/_sources/programming/simulation.rst.txt A basic example of a control callback function for MuJoCo. This specific example applies damping to each degree of freedom (DOF) if the number of controls matches the number of DOFs. ```C void mycontroller(const mjModel* m, mjData* d) { if (m->nu == m->nv) mju_scl(d->ctrl, d->qvel, -0.1, m->nv); } ``` -------------------------------- ### Run MuJoCo Simulation with USD Support Source: https://mujoco.readthedocs.io/en/stable/OpenUSD/building.html Execute the `simulate` program after building MuJoCo with USD support enabled. This allows for dragging and dropping USD files into the simulation. ```bash simulate ``` -------------------------------- ### Record Sample Command Line Usage Source: https://mujoco.readthedocs.io/en/stable/programming/samples.html This is the basic command structure for the record sample. It requires the model file, duration, frames per second, and output RGB file name. An optional argument can be used to add depth information. ```bash record modelfile duration fps rgbfile [adddepth] ``` -------------------------------- ### MJCF Default Settings Example Source: https://mujoco.readthedocs.io/en/stable/_sources/modeling.rst.txt Demonstrates the use of nested default classes to set attribute values for geoms within an MJCF model. This example illustrates how default settings propagate and can be overridden. ```xml ``` -------------------------------- ### Using MjVfs with Context Manager Source: https://mujoco.readthedocs.io/en/stable/python.html Demonstrates loading assets from memory using the MjVfs context manager. Ensure the same VFS is used for parsing and compiling. ```python import mujoco with mujoco.MjVfs() as vfs: vfs["model.xml"] = b"" spec = mujoco.MjSpec.from_string("model.xml", vfs=vfs) spec.compile(vfs=vfs) ```