Add from_xml_string to MuJoCo WASM bindings.

This change introduces new functions to load an `mjModel` from an XML string. Two overloads are provided: one that creates a temporary VFS and one that uses a MjVFS arg.

Also updated other places where `from_xml_string` should be used: demos, readme, etc.

PiperOrigin-RevId: 882581762
Change-Id: I8428196f8f56ae9630fcd4f0bb6763cdc1c43da0
This commit is contained in:
Google DeepMind
2026-03-12 07:35:08 -07:00
committed by Copybara-Service
parent df0bc58578
commit b294d15558
7 changed files with 159 additions and 28 deletions
+52
View File
@@ -2603,4 +2603,56 @@ describe('MuJoCo WASM Bindings', () => {
}
});
it('should load a model from an XML string', () => {
let model: MjModel|null = null;
try {
model = mujoco.from_xml_string(TEST_XML);
assertExists(model);
expect(model.nbody).toBe(5);
expect(model.ngeom).toBe(3);
} finally {
model?.delete();
}
});
it('should load a model from an XML string with VFS', () => {
const xml = `
<mujoco>
<asset>
<mesh file="cube.obj"/>
</asset>
<worldbody>
<geom type="mesh" mesh="cube"/>
</worldbody>
</mujoco>`;
const cube1 = `
v -1 -1 1
v 1 -1 1
v -1 1 1
v 1 1 1
v -1 1 -1
v 1 1 -1
v -1 -1 -1
v 1 -1 -1`;
let model: MjModel|null = null;
let vfs: MjVFS|null = null;
try {
vfs = new mujoco.MjVFS();
vfs.addBuffer('cube.obj', new TextEncoder().encode(cube1));
assertExists(vfs);
model = mujoco.from_xml_string(xml, vfs);
assertExists(model);
expect(model.nmesh).toBe(1);
const meshId =
mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_MESH.value, 'cube');
expect(meshId).toBeGreaterThanOrEqual(0);
} finally {
model?.delete();
vfs?.delete();
}
});
});
+1 -6
View File
@@ -20,9 +20,6 @@ declare function loadMujoco(): Promise<MainModule>;
async function main() {
const mujoco: MainModule = await loadMujoco();
(mujoco as any).FS.mkdir('/working');
(mujoco as any).FS.mount((mujoco as any).MEMFS, {root: '.'}, '/working');
const xmlContent = `
<mujoco model="Box falling">
<option viscosity="1"/>
@@ -37,13 +34,12 @@ async function main() {
</worldbody>
</mujoco>`;
(mujoco as any).FS.writeFile('/working/hello.xml', xmlContent);
let model: MjModel|undefined;
let data: MjData|undefined;
try {
console.log('Hello world!: Loading model');
model = mujoco.MjModel.mj_loadXML('/working/hello.xml');
model = mujoco.MjModel.from_xml_string(xmlContent);
if (!model) {
throw new Error('Failed to load model');
}
@@ -57,7 +53,6 @@ async function main() {
} finally {
model?.delete();
data?.delete();
(mujoco as any).FS.unmount('/working');
}
}