Add mujoco.MjSpec.to_zip()

PiperOrigin-RevId: 719003836
Change-Id: I310ac96b0080b3313c325cee76d3bf7f81fa9df0
This commit is contained in:
Alessio Quaglino
2025-01-23 14:00:07 -08:00
committed by Copybara-Service
parent 3d174a4034
commit 2546fcefa0
2 changed files with 27 additions and 0 deletions
+24
View File
@@ -19,7 +19,9 @@ import ctypes.util
import os import os
import platform import platform
import subprocess import subprocess
from typing import Union, IO
import warnings import warnings
import zipfile
# Extend the path to enable multiple directories to contribute to the same # Extend the path to enable multiple directories to contribute to the same
# package. Without this line, the `mujoco-mjx` package would not be able to # package. Without this line, the `mujoco-mjx` package would not be able to
@@ -53,10 +55,32 @@ from mujoco._errors import *
from mujoco._functions import * from mujoco._functions import *
from mujoco._render import * from mujoco._render import *
from mujoco._specs import * from mujoco._specs import *
from mujoco._specs import MjSpec
from mujoco._structs import * from mujoco._structs import *
from mujoco.gl_context import * from mujoco.gl_context import *
from mujoco.renderer import Renderer from mujoco.renderer import Renderer
def to_zip(spec: MjSpec, file: Union[str, IO[bytes]]) -> None:
"""Converts a spec to a zip file.
Args:
spec: The mjSpec to save to a file.
file: The path to the file to save to or the file object to write to.
"""
files_to_zip = spec.assets
files_to_zip[spec.modelname + '.xml'] = spec.to_xml()
if isinstance(file, str):
directory = os.path.dirname(file)
os.makedirs(directory, exist_ok=True)
file = open(file, 'wb')
with zipfile.ZipFile(file, 'w') as zip_file:
for filename, contents in files_to_zip.items():
zip_info = zipfile.ZipInfo(os.path.join(spec.modelname, filename))
zip_file.writestr(zip_info, contents)
MjSpec.to_zip = to_zip
HEADERS_DIR = os.path.join(os.path.dirname(__file__), 'include/mujoco') HEADERS_DIR = os.path.join(os.path.dirname(__file__), 'include/mujoco')
PLUGINS_DIR = os.path.join(os.path.dirname(__file__), 'plugin') PLUGINS_DIR = os.path.join(os.path.dirname(__file__), 'plugin')
+3
View File
@@ -15,7 +15,9 @@
"""Tests for mjSpec bindings.""" """Tests for mjSpec bindings."""
import inspect import inspect
import os
import textwrap import textwrap
import zipfile
from absl.testing import absltest from absl.testing import absltest
from etils import epath from etils import epath
@@ -735,6 +737,7 @@ class SpecsTest(absltest.TestCase):
v -1 -1 -1 v -1 -1 -1
v 1 -1 -1""" v 1 -1 -1"""
spec = mujoco.MjSpec() spec = mujoco.MjSpec()
spec.modelname = 'test'
mesh = spec.add_mesh() mesh = spec.add_mesh()
mesh.name = 'cube' mesh.name = 'cube'
mesh.file = 'cube.obj' mesh.file = 'cube.obj'