joint_view/
joint_view.rs

1//! Example of using views.
2//! The example shows how to obtain a [`MjJointInfo`] struct that can be used
3//! to create a (temporary) [`MjJointView`] to corresponding fields in [`MjData`].
4use std::time::Duration;
5
6use mujoco_rs::viewer::MjViewer;
7use mujoco_rs::prelude::*;
8
9
10const EXAMPLE_MODEL: &str = "
11<mujoco>
12  <worldbody>
13    <light ambient=\"0.2 0.2 0.2\"/>
14    <body name=\"ball\">
15        <geom name=\"green_sphere\" pos=\".2 .2 .2\" size=\".1\" rgba=\"0 1 0 1\" solref=\"0.004 1.0\"/>
16        <joint name=\"ball_joint\" type=\"free\"/>
17    </body>
18
19    <geom name=\"floor1\" type=\"plane\" size=\"10 10 1\" euler=\"15 4 0\" solref=\"0.004 1.0\"/>
20    <geom name=\"floor2\" type=\"plane\" pos=\"15 -20 0\" size=\"10 10 1\" euler=\"-15 -4 0\" solref=\"0.004 1.0\"/>
21
22  </worldbody>
23</mujoco>
24";
25
26fn main() {
27    /* Load the model and create data */
28    let model = MjModel::from_xml_string(EXAMPLE_MODEL).expect("could not load the model");
29    let mut data = model.make_data();  // or MjData::new(&model);
30
31    /* Launch a passive Rust-native viewer */
32    let mut viewer = MjViewer::launch_passive(&model, 0)
33        .expect("could not launch the viewer");
34
35    /* Create the joint info */
36    let ball_info = data.joint("ball_joint").unwrap();
37    while viewer.running() {
38        /* Step the simulation and sync the viewer */
39        viewer.sync(&mut data);
40        data.step();
41
42        /* Obtain the view and access first three variables of `qpos` (x, y, z) */
43        let xyz = &ball_info.view(&data).qpos[..3];
44        println!("The ball's position is: {xyz:.2?}");
45
46        std::thread::sleep(Duration::from_secs_f64(0.002));
47    }
48}