diff --git a/agent_context/MAP.yaml b/agent_context/MAP.yaml index 55fa192eb..b4405c290 100644 --- a/agent_context/MAP.yaml +++ b/agent_context/MAP.yaml @@ -10,7 +10,7 @@ topics: title: Simulation System aliases: [simulation system, simulation manager, Newton physics backend, motion module, sim motion, camera attachment, 运动能力模块, 仿真系统, 仿真管理器] keywords: [SimulationManager, SimulationManagerCfg, RenderCfg, DenoisingCfg, DenoisingMode, DLSSCfg, - NRDCfg, DLSS, NRD, frame_time_delta_ms, explicit physics stepping, simulation_time, arena, DexSim, LightCfg, LightBatch, 灯光批次, PhysicsBackendCfg, + NRDCfg, DLSS, NRD, frame_time_delta_ms, explicit physics stepping, simulation_time, arena, DexSim, UsdImportCfg, UsdImportResult, root_prim_path, LightCfg, LightBatch, 灯光批次, PhysicsBackendCfg, DefaultPhysicsCfg, NewtonPhysicsCfg, VisualObject, VisualObjectCfg, VisualMaterial, VisualMaterialCfg, VisualMaterialInst, preview-material, 材质预览, UsdSourceCfg, source_prim_path, add_visual_object, 纯渲染对象, DexUniSolverCfg, DexUni, runtime control, deformable, particle set, UsdSourceSnapshot, read_usd_source, LinkMesh, PhysicalCollisionGeometry, capture_physical_collision_geometry, diff --git a/agent_context/topics/simulation-system/deformables.md b/agent_context/topics/simulation-system/deformables.md index b6c7fc026..e7d35e0c1 100644 --- a/agent_context/topics/simulation-system/deformables.md +++ b/agent_context/topics/simulation-system/deformables.md @@ -17,6 +17,12 @@ accept the default DexUni solver or an explicit supported particle solver post-finalization additions. Default soft/cloth compatibility is absent. Future backend support belongs at dispatch, not inside a monolithic config. +`UsdImportCfg` whole-scene loading and a deformable config's optional `source` +bind authored soft-body/cloth descriptors through these same facades. Source +physics and simulation/render topology are retained; the source route accepts +identity, pose and particle flag/radius overrides rather than regenerating a +mesh with the procedural meshing defaults. + `spawn/descriptors.py` translates volume/surface configs to typed `SoftBodyDesc` and `ClothDesc`; volume meshing uses `SoftBodyMeshingDesc`. Runtime mutation uses `Scene.create_particle_set_batch()`, not renderer buffers or legacy native diff --git a/agent_context/topics/simulation-system/physics-configuration.md b/agent_context/topics/simulation-system/physics-configuration.md index 9f539aff3..cb8986c84 100644 --- a/agent_context/topics/simulation-system/physics-configuration.md +++ b/agent_context/topics/simulation-system/physics-configuration.md @@ -73,10 +73,26 @@ MuJoCo force reports are unavailable. See `physics/` and `"overlay"` applies non-`None` config fields after source translation. The same policy covers USD rigid objects and USD/URDF articulations. Generic rigid objects/articulations preserve by default; Robot configs overlay their authored -drives. Preserve-mode articulation configs warn about ignored overlay fields. +drives. Preserve mode keeps the source actor and scale even when saved config +fields contain legacy defaults; explicit actor/scale changes require overlay. +Preserve-mode articulation configs warn about ignored overlay fields. Root import intent is handled separately in [articulation adapters](articulation-adapters.md). +Unset USD actor type, scale, root flags and placement retain parsed source +values. An explicit singleton `source_pose_mode` replaces, preserves or offsets +the source transform. Singleton translation resolves a runtime-owned config +copy, preserving caller placement intent for repeated imports and Gym +replacement comparisons. Returned facade configs store resolved absolute poses +in `config` mode, so copying them for replacement retains source offsets and +scene placement without applying them again. Sparse pose keys preserve explicit +zero values; only omitted pose fields retain source placement in `auto` mode. +Non-USD rigid and URDF articulation imports keep their +dynamic/unit-scale and fixed-root defaults respectively. Whole-scene +`add_usd(UsdImportCfg(...))` applies sparse dictionary fields before Spawn +declaration. Source subtree and variants belong to its `source`; namespace and +scene placement belong to the import recipe. + `RigidBodyPhysicsCfg` is the single grouped schema. `mass_props`, `rigid_props`, `collision_props` and `material_props` each own one physical concept; concrete subclasses/local backend discriminators carry native fields. diff --git a/agent_context/topics/simulation-system/simulation-system.md b/agent_context/topics/simulation-system/simulation-system.md index 77588da5e..488f0b68b 100644 --- a/agent_context/topics/simulation-system/simulation-system.md +++ b/agent_context/topics/simulation-system/simulation-system.md @@ -7,6 +7,7 @@ | Public simulation facade | `embodichain/lab/sim/__init__.py` | | World, registries, readiness and stepping | `embodichain/lab/sim/sim_manager.py` → `SimulationManager`, `SimulationManagerCfg` | | Declaration, source resolution and binding | `embodichain/lab/sim/spawn/scene.py`, `spawn/source.py`, `spawn/descriptors.py` | +| USD import recipes, preflight and source-path results | `cfg/usd.py`, `spawn/usd_import.py`, `spawn/usd_result.py` | | Fresh static USD reads and owned authored link meshes | `embodichain/lab/sim/spawn/source_geometry.py` | | Manager-level backend hooks and capabilities | `embodichain/lab/sim/physics/` | | Object-level Scene batch adapters | `embodichain/lab/sim/objects/backends/scene.py`, `newton.py` | @@ -31,15 +32,26 @@ that same object in place. UIDs identify resources in the manager registry. `VisualObject` owns render-only root poses, visibility and material assignments, with no rigid-body buffers or collision API. Its config lives in `cfg/visual_object.py`; mesh files use `MeshCfg.fpath`, as for rigid objects. -`cfg/source.py:UsdSourceCfg` owns the source file and exact `source_prim_path`; +`cfg/source.py:UsdSourceCfg` owns the source file, exact singleton +`source_prim_path` and optional parser subtree/variants; visual, rigid and articulation configs accept it through `source`, exclusively with their existing shape/file input. `ObjectBaseCfg` keeps runtime identity and initial pose independent of file formats. `add_visual_object()` compiles mesh/primitive appearance or -selects a USD object's appearance. Whole-scene `add_usd()` -preserves physical types and wraps only objects without physics and colliders +selects a USD object's appearance. Whole-scene `add_usd(UsdImportCfg(...))` +owns namespace, scene placement and sparse per-asset overrides keyed by source +prim paths. Single-asset placement belongs to `source_pose_mode` on the asset +configuration. Both routes share the fresh DexSim source parser and validate +before native declaration. `UsdImportResult` maps source paths to facades and +records logical UIDs for constraints and native-only resources. Unique sources +retain prim-path keys; multiple resources from one prim receive ordinal keys, +with `resource_source_paths` retaining the original prim identity. It remaps +standalone constraint endpoints after UID changes, preserves physical types, +and wraps only objects without physics and colliders as visuals. Conflicting visual UIDs receive the scene-name prefix while returned keys preserve source prim paths. Other import UID conflicts fail before declaration. -Imported facades retain their source address in `cfg.source`. This metadata +Volume and surface particle sets bind through the existing deformable facades; +they require Newton/CUDA and retain source topology and physics. Imported +facades retain their source address in `cfg.source`. This metadata does not request a second spawn or bind an unrelated existing scene entity. Visuals retain facade-owned pose/visibility/material-assignment state across native topology rebuilds, with separate reset baselines. They use the same prepare, diff --git a/docs/source/api_reference/embodichain/embodichain.lab.sim.cfg.rst b/docs/source/api_reference/embodichain/embodichain.lab.sim.cfg.rst index 5b71f8a0e..440f315ec 100644 --- a/docs/source/api_reference/embodichain/embodichain.lab.sim.cfg.rst +++ b/docs/source/api_reference/embodichain/embodichain.lab.sim.cfg.rst @@ -70,6 +70,7 @@ UV seams and render detail. NewtonJointDrivePropertiesCfg ObjectBaseCfg UsdSourceCfg + UsdImportCfg LightCfg VisualObjectCfg RigidObjectCfg @@ -107,6 +108,42 @@ existing ``shape``/``fpath`` input. Ordinary mesh files continue to use of the requested type; ambiguous sources fail instead of selecting the first object. Whole-scene imports preserve this source address on their facades. +USD import recipes +------------------ + +``SimulationManager.add_usd(UsdImportCfg(...))`` declares a complete scene +selection. ``source.root_prim_path`` selects a source subtree and ``variants`` +selects source variants. The import recipe separately owns runtime namespace, +the optional left-multiplied scene pose and overrides keyed by unchanged source +prim paths. Unset source properties are retained. Source and override validation +precedes native declaration; returned facades bind in place at ``prepare()``. + +.. code-block:: python + + from embodichain.lab.sim.cfg import UsdImportCfg, UsdSourceCfg + + imported = sim.add_usd( + UsdImportCfg( + name="workcell", + source=UsdSourceCfg( + file_path="workcell.usda", + root_prim_path="/World/Cell", + ), + namespace="cell_1", + ) + ) + sim.prepare() + robot = imported["/World/Cell/Robot"] + +.. autoclass:: embodichain.lab.sim.cfg.usd.UsdImportCfg + :members: + +Single-asset configurations retain their exact ``source_prim_path`` selector. +Their ``source_pose_mode`` chooses automatic, replacement, preservation or +offset placement. Legacy source-option spellings remain accepted by the +compatibility adapter. New scene recipes keep namespace and placement on +``UsdImportCfg``. + Deformable physics and meshing ----------------------------- diff --git a/docs/source/api_reference/public_api.rst b/docs/source/api_reference/public_api.rst index 58d68d14e..e09b87b2b 100644 --- a/docs/source/api_reference/public_api.rst +++ b/docs/source/api_reference/public_api.rst @@ -2697,6 +2697,7 @@ embodichain.lab.sim VisualMaterialInst ReuseSegmentState BatchEntity + UsdImportResult SimulationManager SimulationManagerCfg SIM_CACHE_DIR @@ -3753,6 +3754,23 @@ embodichain.lab.sim.spawn.usd rigid_desc_from_usd visual_desc_from_usd +embodichain.lab.sim.spawn.usd_result +------------------------------------- + +.. currentmodule:: embodichain.lab.sim.spawn.usd_result + +USD import results retain stable source keys for declared facades and logical +resource UIDs. A unique source keeps its prim path as its key. If one prim emits +several resources, keys append ``#0``, ``#1``, and so on in parser order; +``resource_source_paths`` maps each key back to its exact source prim path. +The UID, type and source-path maps use the same keys, independently of namespace +and runtime UID changes. Results share the manager's ``prepare()`` lifecycle and +do not own another object registry or native-resource lifetime. + +.. autosummary:: + + UsdImportResult + embodichain.lab.sim.utility.dynamic_pybind ---------------------------------------- diff --git a/embodichain/gen_sim/scene_engine/pipeline/utils/usd_scene.py b/embodichain/gen_sim/scene_engine/pipeline/utils/usd_scene.py index 872b5f277..827370ca7 100644 --- a/embodichain/gen_sim/scene_engine/pipeline/utils/usd_scene.py +++ b/embodichain/gen_sim/scene_engine/pipeline/utils/usd_scene.py @@ -233,7 +233,11 @@ def load_into(cls, sim: object, stage_path: str | Path) -> "UsdSceneBinding": """Import a schema-v2 USD stage and bind every indexed entity.""" path = Path(stage_path).expanduser().resolve() index = UsdSceneIndex.load(path, require_schema=True) - assets = sim.add_usd(name=path.stem, file_path=str(path)) + from embodichain.lab.sim.cfg import UsdImportCfg, UsdSourceCfg + + assets = sim.add_usd( + UsdImportCfg(name=path.stem, source=UsdSourceCfg(file_path=str(path))) + ) bindings: list[UsdEntityBinding] = [] for desc in index.entities: runtime = assets.get(desc.prim_path) diff --git a/embodichain/lab/gym/envs/embodied_env.py b/embodichain/lab/gym/envs/embodied_env.py index 4ea89db80..1235c9cf7 100644 --- a/embodichain/lab/gym/envs/embodied_env.py +++ b/embodichain/lab/gym/envs/embodied_env.py @@ -3116,27 +3116,32 @@ def _setup_lights(self) -> None: def _setup_background(self) -> None: """Setup the static rigid objects in the environment.""" - for cfg in self.cfg.visual_object: - self.sim.add_visual_object(cfg) - for cfg in self.cfg.background: + + def validate_resolved(cfg: RigidObjectCfg) -> None: if cfg.body_type == "dynamic": logger.log_error( - f"Background object must be kinematic or static rigid object." + "Background object must be kinematic or static rigid object." ) - self.sim.add_rigid_object(cfg=cfg) + + for cfg in self.cfg.visual_object: + self.sim.add_visual_object(cfg) + for cfg in self.cfg.background: + self.sim.add_rigid_object(cfg=cfg, validate_resolved=validate_resolved) def _setup_interactive_objects(self) -> None: """Setup the interactive objects in the environment.""" + def validate_resolved(cfg: RigidObjectCfg) -> None: + if cfg.body_type != "dynamic": + logger.log_error( + "Interactive rigid object must be dynamic rigid object." + ) + for cfg in self.cfg.articulation: self.sim.add_articulation(cfg=cfg) for cfg in self.cfg.rigid_object: - if cfg.body_type != "dynamic": - logger.log_error( - f"Interactive rigid object must be dynamic rigid object." - ) - self.sim.add_rigid_object(cfg=cfg) + self.sim.add_rigid_object(cfg=cfg, validate_resolved=validate_resolved) for cfg in self.cfg.rigid_object_group: self.sim.add_rigid_object_group(cfg=cfg) diff --git a/embodichain/lab/sim/__init__.py b/embodichain/lab/sim/__init__.py index 2432be884..1aa9ffa7e 100644 --- a/embodichain/lab/sim/__init__.py +++ b/embodichain/lab/sim/__init__.py @@ -29,6 +29,7 @@ ) from .cfg import DenoisingCfg, DenoisingMode, DLSSCfg, NRDCfg from .common import BatchEntity +from .spawn.usd_result import UsdImportResult from .profiler import Profiler, ProfilerCfg from .sim_manager import * @@ -39,6 +40,7 @@ "VisualMaterialInst", "ReuseSegmentState", "BatchEntity", + "UsdImportResult", "Profiler", "ProfilerCfg", "SimulationManager", diff --git a/embodichain/lab/sim/cfg/__init__.py b/embodichain/lab/sim/cfg/__init__.py index 375715916..c790a9b80 100644 --- a/embodichain/lab/sim/cfg/__init__.py +++ b/embodichain/lab/sim/cfg/__init__.py @@ -41,6 +41,7 @@ from .asset import AssetPhysicsMode, ObjectBaseCfg, _resolve_asset_physics_mode from .fluid import FluidObjectCfg, FluidSpawnCfg, FluidRenderCfg from .source import UsdSourceCfg +from .usd import UsdImportCfg from .deformable import ( SurfaceElementPropertiesCfg, VolumeDeformableMeshingCfg, @@ -125,6 +126,7 @@ "RigidBodyPhysicsCfg", "ObjectBaseCfg", "UsdSourceCfg", + "UsdImportCfg", "LightCfg", "RigidObjectCfg", "VisualObjectCfg", diff --git a/embodichain/lab/sim/cfg/articulation.py b/embodichain/lab/sim/cfg/articulation.py index 19cba5b71..234d916cf 100644 --- a/embodichain/lab/sim/cfg/articulation.py +++ b/embodichain/lab/sim/cfg/articulation.py @@ -76,18 +76,18 @@ class ArticulationRootPropertiesCfg: ``fixed_base`` and ``self_collision_enabled`` are consumed by both backends. ``sleep_threshold`` and the solver-iteration fields are supported - only by the Default backend and are ignored by Newton. By default, the - articulation root is fixed and self-collision is disabled. Explicit - ``None`` values preserve the source value or backend/import default. + only by the Default backend and are ignored by Newton. Unset values + preserve USD intent; URDF and procedural imports resolve to a fixed root + without self-collision. """ - fixed_base: bool | None = True + fixed_base: bool | None = None """Whether the articulation root is rigidly fixed to the world frame. Set to ``None`` to preserve the source value or backend/import default. """ - self_collision_enabled: bool | None = False + self_collision_enabled: bool | None = None """Whether non-filtered link pairs in the articulation may self-collide. Newton may still apply source-authored or Spawn-owned filtering to adjacent @@ -445,9 +445,17 @@ class ArticulationCfg(ObjectBaseCfg): source: UsdSourceCfg | None = field(default=None, kw_only=True) """USD source asset; mutually exclusive with :attr:`fpath`.""" - body_scale: tuple | list = (1.0, 1.0, 1.0) + body_scale: tuple | list | None = None """Scale of the articulation in the simulation world frame.""" + def __post_init__(self) -> None: + path = self.source.file_path if self.source is not None else self.fpath + if path is None or not str(path).lower().endswith( + (".usd", ".usda", ".usdc", ".usdz") + ): + if self.body_scale is None: + self.body_scale = (1.0, 1.0, 1.0) + compute_uv: bool = False """Whether to compute the UV mapping for the articulation link. @@ -482,9 +490,8 @@ class ArticulationCfg(ObjectBaseCfg): Fixed-base and self-collision intent is portable. Root sleep and solver iterations are Default-only fields and are ignored by Newton. The portable - fields default to a fixed base with self-collision disabled. Set either - field to ``None`` to preserve an authored USD/backend value; URDF imports - then use the established fixed-base, self-collision-off defaults. + fields default to ``None`` so USD imports retain their authored values. + URDF imports retain the fixed-base, self-collision-off defaults. """ joint_drive_props: JointDrivePropertiesCfg | None = None @@ -573,9 +580,23 @@ def from_dict( else: from scipy.spatial.transform import Rotation as R + cfg.init_local_pose = np.asarray(cfg.init_local_pose) cfg.init_pos = tuple(cfg.init_local_pose[:3, 3]) cfg.init_rot = tuple( R.from_matrix(cfg.init_local_pose[:3, :3]).as_euler("xyz", degrees=True) ) + path = cfg.source.file_path if cfg.source is not None else cfg.fpath + if path is not None and str(path).lower().endswith( + (".usd", ".usda", ".usdc", ".usdz") + ): + if "body_scale" not in init_dict: + cfg.body_scale = None + if ( + "init_local_pose" in init_dict and init_dict["init_local_pose"] is None + ) or not {"init_pos", "init_rot", "init_local_pose"}.intersection( + init_dict + ): + cfg.init_local_pose = None + return cfg diff --git a/embodichain/lab/sim/cfg/asset.py b/embodichain/lab/sim/cfg/asset.py index 4fec8c374..0c9ed6cc1 100644 --- a/embodichain/lab/sim/cfg/asset.py +++ b/embodichain/lab/sim/cfg/asset.py @@ -19,6 +19,7 @@ from __future__ import annotations from collections.abc import Mapping +from dataclasses import field from typing import Dict, Literal import numpy as np @@ -59,6 +60,15 @@ class ObjectBaseCfg: init_local_pose: np.ndarray | None = None """4x4 transformation matrix of the root in local frame. If specified, it will override init_pos and init_rot.""" + source_pose_mode: Literal["auto", "config", "preserve", "offset"] = field( + default="auto", kw_only=True + ) + """USD input placement: retain an unset pose, replace, preserve, or offset it. + + Imported facades use ``"config"`` with their resolved ``init_local_pose`` + so reusing the returned configuration preserves its effective placement. + """ + @classmethod def from_dict(cls, init_dict: Dict[str, str | float | tuple]) -> ObjectBaseCfg: """Initialize the configuration from a dictionary.""" @@ -109,4 +119,26 @@ def from_dict(cls, init_dict: Dict[str, str | float | tuple]) -> ObjectBaseCfg: cfg.init_pos = tuple(T[:3, 3]) cfg.init_rot = tuple(R.from_matrix(T[:3, :3]).as_euler("xyz", degrees=True)) + source = getattr(cfg, "source", None) + path = ( + getattr(source, "file_path", None) + if source is not None + else getattr( + getattr(cfg, "shape", None), "fpath", getattr(cfg, "fpath", None) + ) + ) + if ( + path is not None + and str(path).lower().endswith((".usd", ".usda", ".usdc", ".usdz")) + and ( + ( + "init_local_pose" in init_dict + and init_dict["init_local_pose"] is None + ) + or not {"init_pos", "init_rot", "init_local_pose"}.intersection( + init_dict + ) + ) + ): + cfg.init_local_pose = None return cfg diff --git a/embodichain/lab/sim/cfg/deformable.py b/embodichain/lab/sim/cfg/deformable.py index 13af9639e..1b3ea0c41 100644 --- a/embodichain/lab/sim/cfg/deformable.py +++ b/embodichain/lab/sim/cfg/deformable.py @@ -19,7 +19,7 @@ from __future__ import annotations from collections.abc import Mapping -from dataclasses import MISSING +from dataclasses import MISSING, field from typing import Any from typing import Literal, Sequence @@ -29,6 +29,7 @@ from ..shapes import MeshCfg from .asset import ObjectBaseCfg +from .source import UsdSourceCfg, _usd_source_from_value __all__: list[str] = [] @@ -217,6 +218,9 @@ class DeformableObjectCfg(ObjectBaseCfg): shape: MeshCfg = MeshCfg() """Render and source-mesh configuration.""" + source: UsdSourceCfg | None = field(default=None, kw_only=True) + """Optional authored USD particle-set source; source physics is retained.""" + particle_radius: float | None = None """Newton particle radius; ``None`` uses the active solver default.""" @@ -235,6 +239,7 @@ class DeformableObjectCfg(ObjectBaseCfg): """Whether Newton reports source-mesh quality validation warnings.""" def __post_init__(self) -> None: + self.source = _usd_source_from_value(self.source) if isinstance(self.shape, Mapping): self.shape = _mesh_cfg_from_dict(self.shape) visual_shape = getattr(self, "visual_shape", None) @@ -261,6 +266,11 @@ def from_dict(cls, init_dict: Mapping[str, Any]) -> DeformableObjectCfg: ) cfg.init_pos, cfg.init_rot = pose.init_pos, pose.init_rot cfg.init_local_pose = pose.init_local_pose + if cfg.source is not None and ( + ("init_local_pose" in init_dict and init_dict["init_local_pose"] is None) + or not {"init_pos", "init_rot", "init_local_pose"}.intersection(init_dict) + ): + cfg.init_local_pose = None return cfg diff --git a/embodichain/lab/sim/cfg/rigid_object.py b/embodichain/lab/sim/cfg/rigid_object.py index 4ea774d10..7101a1306 100644 --- a/embodichain/lab/sim/cfg/rigid_object.py +++ b/embodichain/lab/sim/cfg/rigid_object.py @@ -56,10 +56,16 @@ class RigidObjectCfg(ObjectBaseCfg): :class:`RigidBodyPhysicsCfg` groups portable and backend-native intent. """ - body_type: Literal["dynamic", "kinematic", "static"] = "dynamic" + body_type: Literal["dynamic", "kinematic", "static"] | None = None + """Actor type for procedural bodies or explicit USD ``overlay`` mode. - body_scale: tuple | list = (1.0, 1.0, 1.0) - """Scale of the rigid body in the simulation world frame.""" + USD ``preserve`` mode always retains the source actor, including when + loading older configurations that serialized a default actor type.""" + + body_scale: tuple | list | None = None + """Geometry scale for procedural bodies or USD ``overlay`` mode. + + USD ``preserve`` mode retains its source scale.""" asset_physics_mode: AssetPhysicsMode = "preserve" """How a file-backed asset's physical properties are handled. @@ -69,6 +75,22 @@ class RigidObjectCfg(ObjectBaseCfg): use config. """ + def __post_init__(self) -> None: + self._resolve_procedural_defaults() + + def _resolve_procedural_defaults(self) -> None: + """Resolve defaults only after ordinary geometry is assembled.""" + if self.shape is None or self.source is not None: + return + path = getattr(self.shape, "fpath", None) + if path is None or not str(path).lower().endswith( + (".usd", ".usda", ".usdc", ".usdz") + ): + if self.body_type is None: + self.body_type = "dynamic" + if self.body_scale is None: + self.body_scale = (1.0, 1.0, 1.0) + def resolve_asset_physics_mode(self) -> AssetPhysicsMode: """Return the effective file-backed physics policy.""" return _resolve_asset_physics_mode(self.asset_physics_mode) @@ -106,7 +128,23 @@ def from_dict(cls, init_dict: Dict[str, Any]) -> RigidObjectCfg: DeprecationWarning, stacklevel=2, ) - return super().from_dict(data) + cfg = super().from_dict(data) + path = ( + cfg.source.file_path + if cfg.source is not None + else getattr(cfg.shape, "fpath", None) + ) + if path is not None and str(path).lower().endswith( + (".usd", ".usda", ".usdc", ".usdz") + ): + if "body_type" not in data: + cfg.body_type = None + if "body_scale" not in data: + cfg.body_scale = None + if not {"init_pos", "init_rot", "init_local_pose"}.intersection(data): + cfg.init_local_pose = None + cfg._resolve_procedural_defaults() + return cfg def to_dexsim_body_type(self) -> ActorType: """Convert the body type to dexsim ActorType.""" diff --git a/embodichain/lab/sim/cfg/robot.py b/embodichain/lab/sim/cfg/robot.py index 77bd28743..69e594bad 100644 --- a/embodichain/lab/sim/cfg/robot.py +++ b/embodichain/lab/sim/cfg/robot.py @@ -143,10 +143,17 @@ def from_dict(cls, init_dict: Dict[str, str | float | tuple]) -> RobotCfg: solver_module = importlib.import_module("embodichain.lab.sim.motion.solvers") - cfg = cls() # Create a new instance of the class (cls) + file_fields = {} + if "source" in init_dict: + file_fields["source"] = _usd_source_from_value(init_dict["source"]) + if "fpath" in init_dict: + path = init_dict["fpath"] + file_fields["fpath"] = None if path is None else _get_data_path(path) + # Resolve source-dependent defaults with the actual file owner present. + cfg = cls(**file_fields) for key, value in init_dict.items(): - if key == "source": - cfg.source = _usd_source_from_value(value) + if key in file_fields: + continue elif key == "link_attrs" and isinstance(value, dict): cfg.link_attrs = link_attrs_from_dict(value) elif key == "attrs" and isinstance(value, Mapping): @@ -187,8 +194,6 @@ def from_dict(cls, init_dict: Dict[str, str | float | tuple]) -> RobotCfg: for part, part_cfg in value.items() }, ) - elif key == "fpath": - setattr(cfg, key, None if value is None else _get_data_path(value)) elif isinstance(attr, JointDrivePropertiesCfg) and isinstance( value, dict ): diff --git a/embodichain/lab/sim/cfg/source.py b/embodichain/lab/sim/cfg/source.py index 5955b2ad4..cc683b372 100644 --- a/embodichain/lab/sim/cfg/source.py +++ b/embodichain/lab/sim/cfg/source.py @@ -20,6 +20,7 @@ from collections.abc import Mapping from dataclasses import MISSING +from typing import Any, Literal from embodichain.utils import configclass @@ -45,6 +46,21 @@ class UsdSourceCfg: asset type. This is not a destination path, regex or parent/link binding. """ + root_prim_path: str | None = None + """Absolute subtree to parse; omission uses the source default prim/stage.""" + + prim_path: str | None = None + """Compatibility spelling of :attr:`root_prim_path`.""" + + variants: dict[str, dict[str, str]] | None = None + """Variant selections keyed by absolute source prim path.""" + + namespace: str | None = None + """Legacy singleton namespace; scene namespace belongs to UsdImportCfg.""" + + pose_mode: Literal["auto", "config", "preserve", "offset"] = "auto" + """Legacy singleton placement; prefer the containing asset's source_pose_mode.""" + @classmethod def from_dict(cls, data: Mapping[str, object]) -> UsdSourceCfg: """Decode a source mapping, rejecting unknown source options. @@ -55,11 +71,98 @@ def from_dict(cls, data: Mapping[str, object]) -> UsdSourceCfg: Returns: Source configuration; call ``validate()`` after assembly. """ - unknown = set(data) - {"file_path", "source_prim_path"} + unknown = set(data) - { + "file_path", + "source_prim_path", + "root_prim_path", + "prim_path", + "variants", + "namespace", + "pose_mode", + } if unknown: raise ValueError(f"Unknown UsdSourceCfg fields: {sorted(unknown)}.") return cls(**data) + def parse_kwargs(self) -> dict[str, Any]: + """Return source selection options accepted by DexSim. + + Returns: + Configured parser options. + """ + if self.pose_mode not in {"auto", "config", "preserve", "offset"}: + raise ValueError(f"Unsupported USD pose_mode {self.pose_mode!r}.") + if self.root_prim_path is not None and self.prim_path is not None: + raise ValueError("Specify root_prim_path or legacy prim_path, not both.") + root = ( + self.root_prim_path if self.root_prim_path is not None else self.prim_path + ) + if root is not None: + _validate_prim_path(root, allow_root=True, field_name="root_prim_path") + if self.namespace is not None and ( + not isinstance(self.namespace, str) + or not self.namespace + or "/" in self.namespace + ): + raise ValueError("USD namespace must be non-empty and cannot contain '/'.") + if self.variants is not None: + if not isinstance(self.variants, Mapping): + raise ValueError( + "USD variants require absolute prim paths and mappings." + ) + for path, choices in self.variants.items(): + if ( + not isinstance(path, str) + or not path.startswith("/") + or not isinstance(choices, Mapping) + ): + raise ValueError( + "USD variants require absolute prim paths and mappings." + ) + if any( + not isinstance(name, str) or not isinstance(choice, str) + for name, choice in choices.items() + ): + raise ValueError( + "USD variant-set names and choices must be strings." + ) + options = { + name: getattr(self, name) + for name in ("variants", "namespace") + if getattr(self, name) is not None + } + if root is not None: + options["prim_path"] = root + return options + + def validate_source(self) -> None: + """Validate one fully assembled source without opening its stage.""" + self.validate() + path = self.file_path + if not isinstance(path, str) or not path.strip(): + raise ValueError("UsdSourceCfg.file_path must be a non-empty string.") + if not path.lower().endswith((".usd", ".usda", ".usdc", ".usdz")): + raise ValueError("UsdSourceCfg.file_path requires a USD source file.") + if self.source_prim_path is not None: + _validate_prim_path( + self.source_prim_path, allow_root=False, field_name="source_prim_path" + ) + self.parse_kwargs() + + +def _validate_prim_path(value: object, *, allow_root: bool, field_name: str) -> None: + from pxr import Sdf + + if not isinstance(value, str) or not Sdf.Path.IsValidPathString(value): + raise ValueError(f"{field_name} must be an absolute USD prim path.") + path = Sdf.Path(value) + if ( + not path.IsAbsolutePath() + or path.ContainsPrimVariantSelection() + or not (path.IsPrimPath() or (allow_root and path == Sdf.Path.absoluteRootPath)) + ): + raise ValueError(f"{field_name} must be an absolute USD prim path.") + def _usd_source_from_value(value: object) -> UsdSourceCfg | None: if value is None or isinstance(value, UsdSourceCfg): @@ -94,25 +197,8 @@ def _asset_file_path(cfg: object) -> str | None: raise TypeError("source must be a UsdSourceCfg.") if shape is not None or legacy_path is not None: raise ValueError("source cannot be combined with shape or fpath.") - source.validate() + source.validate_source() path = source.file_path - if not isinstance(path, str) or not path.strip(): - raise ValueError("UsdSourceCfg.file_path must be a non-empty string.") - if not path.lower().endswith((".usd", ".usda", ".usdc", ".usdz")): - raise ValueError("UsdSourceCfg.file_path requires a USD source file.") - selector = source.source_prim_path - if selector is not None: - from pxr import Sdf - - if not isinstance(selector, str) or not Sdf.Path.IsValidPathString(selector): - raise ValueError("source_prim_path must be an absolute USD prim path.") - prim_path = Sdf.Path(selector) - if ( - not prim_path.IsAbsolutePath() - or not prim_path.IsPrimPath() - or prim_path.ContainsPrimVariantSelection() - ): - raise ValueError("source_prim_path must be an absolute USD prim path.") return path diff --git a/embodichain/lab/sim/cfg/usd.py b/embodichain/lab/sim/cfg/usd.py new file mode 100644 index 000000000..ed284016b --- /dev/null +++ b/embodichain/lab/sim/cfg/usd.py @@ -0,0 +1,290 @@ +# ---------------------------------------------------------------------------- +# Copyright (c) 2021-2026 DexForce Technology Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------- + +"""Configuration for a complete USD import into a simulation manager.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import MISSING, field +from typing import TYPE_CHECKING, Any + +import numpy as np + +from embodichain.utils import configclass +from .source import UsdSourceCfg + +if TYPE_CHECKING: + from .articulation import ArticulationCfg + from .deformable import DeformableObjectCfg + from .rigid_object import RigidObjectCfg + from .robot import RobotCfg + from .visual_object import VisualObjectCfg + +__all__ = ["UsdImportCfg"] + + +@configclass +class UsdImportCfg: + """Describe one source selection, placement and set of asset overrides. + + Source prim paths identify override targets and returned assets. Runtime + names are assigned independently through ``namespace`` and per-asset UIDs. + Replication, backend and device are owned by the simulation manager. + """ + + name: str = MISSING + """Import label, also used to disambiguate conflicting visual names.""" + + source: UsdSourceCfg = MISSING + """USD source file, optional subtree and variant selections.""" + + namespace: str | None = None + """Prefix passed to DexSim for imported entity and material names.""" + + pose: np.ndarray | None = None + """Finite 4x4 scene transform in meters/Z-up, left-multiplied onto the source.""" + + asset_cfgs: dict[ + str, + RigidObjectCfg + | ArticulationCfg + | DeformableObjectCfg + | VisualObjectCfg + | dict[str, Any], + ] = field(default_factory=dict) + """Sparse overrides or typed asset configurations keyed by source prim path. + + In sparse mappings with ``auto`` placement, explicit ``init_pos`` or + ``init_rot`` keys select the configured pose, including zero values. + Omitted pose fields retain source placement. + """ + + robot_cfgs: dict[str, RobotCfg] = field(default_factory=dict) + """Robot metadata bindings; source physics and placement are preserved.""" + + def __post_init__(self) -> None: + if isinstance(self.source, Mapping): + self.source = UsdSourceCfg.from_dict(self.source) + if isinstance(self.robot_cfgs, Mapping): + from .robot import RobotCfg + + self.robot_cfgs = { + path: RobotCfg.from_dict(value) if isinstance(value, Mapping) else value + for path, value in self.robot_cfgs.items() + } + if isinstance(self.asset_cfgs, Mapping): + normalized_assets = dict(self.asset_cfgs) + for path, value in self.asset_cfgs.items(): + if isinstance(value, Mapping) and "class_type" in value: + if set(value) != {"class_type", "config"}: + raise ValueError( + "Serialized typed USD overrides require class_type and config." + ) + config_type = _asset_config_types().get(value["class_type"]) + if config_type is None: + raise ValueError( + f"Unsupported USD override class_type {value['class_type']!r}." + ) + decoded = config_type.from_dict(value["config"]) + if ( + "init_local_pose" in value["config"] + and value["config"]["init_local_pose"] is None + ): + decoded.init_local_pose = None + normalized_assets[path] = decoded + self.asset_cfgs = normalized_assets + + def to_dict(self) -> dict[str, Any]: + """Serialize the recipe while retaining typed override semantics. + + Returns: + Recipe fields with tagged typed overrides and unchanged sparse mappings. + """ + from embodichain.utils.configclass import class_to_dict + + data = class_to_dict(self) + data["robot_cfgs"] = { + path: value.to_dict() for path, value in self.robot_cfgs.items() + } + types = _asset_config_types() + data["asset_cfgs"] = {} + for path, value in self.asset_cfgs.items(): + if isinstance(value, Mapping): + data["asset_cfgs"][path] = class_to_dict(dict(value)) + elif ( + type(value).__name__ in types + and type(value) is types[type(value).__name__] + ): + data["asset_cfgs"][path] = { + "class_type": type(value).__name__, + "config": value.to_dict(), + } + else: + raise TypeError( + f"Cannot serialize USD override type {type(value).__name__}." + ) + return data + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> UsdImportCfg: + """Decode a portable import recipe without creating native resources. + + Args: + data: Import fields, including a source mapping and optional robot metadata. + + Returns: + Import configuration; ``validate_import()`` checks the assembled recipe. + """ + unknown = set(data) - { + "name", + "source", + "namespace", + "pose", + "asset_cfgs", + "robot_cfgs", + } + if unknown: + raise ValueError(f"Unknown UsdImportCfg fields: {sorted(unknown)}.") + values = dict(data) + return cls(**values) + + def validate_import(self) -> None: + """Validate the assembled recipe before reading or declaring its source.""" + from .source import _validate_prim_path + + self.validate() + if not isinstance(self.name, str) or not self.name.strip(): + raise ValueError("USD import name must be a non-empty string.") + if not isinstance(self.source, UsdSourceCfg): + raise TypeError("USD import source must be a UsdSourceCfg.") + self.source.validate_source() + if self.source.source_prim_path is not None: + raise ValueError( + "Scene imports select a subtree with source.root_prim_path; source_prim_path is an exact singleton selector." + ) + if self.source.namespace is not None or self.source.pose_mode != "auto": + raise ValueError( + "Scene namespace and placement belong to UsdImportCfg, not its source." + ) + if self.namespace is not None and ( + not isinstance(self.namespace, str) + or not self.namespace + or "/" in self.namespace + ): + raise ValueError("USD namespace must be non-empty and cannot contain '/'.") + if self.pose is not None: + pose = np.asarray(self.pose, dtype=np.float32) + if pose.shape != (4, 4) or not np.isfinite(pose).all(): + raise ValueError("USD scene pose must be a finite (4, 4) transform.") + if not np.allclose(pose[3], (0, 0, 0, 1)): + raise ValueError("USD scene pose must be an affine transform.") + rotation = pose[:3, :3] + if not np.allclose( + rotation.T @ rotation, np.eye(3), atol=1e-5 + ) or not np.isclose(np.linalg.det(rotation), 1.0, atol=1e-5): + raise ValueError( + "USD scene pose must contain a rigid rotation without scale." + ) + for label, mapping in ( + ("asset_cfgs", self.asset_cfgs), + ("robot_cfgs", self.robot_cfgs), + ): + if not isinstance(mapping, Mapping): + raise TypeError( + f"{label} must map source prim paths to configurations." + ) + for path in mapping: + _validate_prim_path( + path, allow_root=False, field_name=f"{label} target" + ) + overlap = self.robot_cfgs.keys() & self.asset_cfgs.keys() + if overlap: + raise ValueError(f"Duplicate USD configuration targets: {sorted(overlap)}.") + + +def _asset_config_types() -> dict[str, type]: + from .articulation import ArticulationCfg + from .deformable import VolumeDeformableObjectCfg, SurfaceDeformableObjectCfg + from .rigid_object import RigidObjectCfg + from .robot import RobotCfg + from .visual_object import VisualObjectCfg + + return { + config_type.__name__: config_type + for config_type in ( + ArticulationCfg, + RigidObjectCfg, + RobotCfg, + VisualObjectCfg, + VolumeDeformableObjectCfg, + SurfaceDeformableObjectCfg, + ) + } + + +def _normalize_usd_import( + cfg: UsdImportCfg | str | None, + *, + file_path: str | None, + name: str | None, + pose: np.ndarray | None, + robot_cfgs: dict | None, + usd: UsdSourceCfg | None, + asset_cfgs: dict | None, +) -> UsdImportCfg: + from copy import deepcopy + import warnings + + if isinstance(cfg, UsdImportCfg): + if any( + value is not None + for value in (file_path, name, pose, robot_cfgs, usd, asset_cfgs) + ): + raise ValueError( + "UsdImportCfg cannot be combined with legacy add_usd arguments." + ) + return deepcopy(cfg) + if cfg is not None and not isinstance(cfg, str): + raise TypeError("add_usd() requires a UsdImportCfg.") + if cfg is not None and name is not None: + raise ValueError("Specify the legacy USD import name once.") + label = cfg if cfg is not None else name + if label is None or file_path is None: + raise TypeError( + "add_usd() requires UsdImportCfg(name=..., source=UsdSourceCfg(file_path=...))." + ) + warnings.warn( + "add_usd(name, file_path, ...) is deprecated; pass UsdImportCfg instead.", + DeprecationWarning, + stacklevel=3, + ) + source = deepcopy(usd) if usd is not None else UsdSourceCfg(file_path=file_path) + if not isinstance(source, UsdSourceCfg): + raise TypeError("usd must be a UsdSourceCfg.") + if isinstance(source.file_path, str) and source.file_path != file_path: + raise ValueError("add_usd() file_path and usd.file_path must match.") + source.file_path = file_path + namespace = source.namespace + source.namespace = None + return UsdImportCfg( + name=label, + source=source, + namespace=namespace, + pose=pose, + robot_cfgs=robot_cfgs or {}, + asset_cfgs=asset_cfgs or {}, + ) diff --git a/embodichain/lab/sim/cfg/visual_object.py b/embodichain/lab/sim/cfg/visual_object.py index d2a85b666..2d016c7cb 100644 --- a/embodichain/lab/sim/cfg/visual_object.py +++ b/embodichain/lab/sim/cfg/visual_object.py @@ -19,6 +19,7 @@ from __future__ import annotations from dataclasses import field +from typing import Literal # Resolve inherited ObjectBaseCfg annotations in runtime type inspection. import numpy as np @@ -49,8 +50,46 @@ class VisualObjectCfg(ObjectBaseCfg): source: UsdSourceCfg | None = field(default=None, kw_only=True) """USD source asset; mutually exclusive with :attr:`shape`.""" - body_scale: tuple[float, float, float] = (1.0, 1.0, 1.0) + body_scale: tuple[float, float, float] | None = None """Scale applied to the visual geometry, independently of its root pose.""" visible: bool = True """Initial visibility restored by reset.""" + + def __post_init__(self) -> None: + if self.shape is None and self.source is None: + return + path = ( + self.source.file_path + if self.source is not None + else getattr(self.shape, "fpath", None) + ) + if path is None or not str(path).lower().endswith( + (".usd", ".usda", ".usdc", ".usdz") + ): + if self.body_scale is None: + self.body_scale = (1.0, 1.0, 1.0) + + @classmethod + def from_dict(cls, init_dict: dict) -> VisualObjectCfg: + """Decode a visual configuration, retaining omitted USD scale. + + Args: + init_dict: Asset configuration fields. + + Returns: + Visual configuration with procedural or source defaults. + """ + cfg = super().from_dict(init_dict) + path = ( + cfg.source.file_path + if cfg.source is not None + else getattr(cfg.shape, "fpath", None) + ) + if ( + path is not None + and str(path).lower().endswith((".usd", ".usda", ".usdc", ".usdz")) + and "body_scale" not in init_dict + ): + cfg.body_scale = None + return cfg diff --git a/embodichain/lab/sim/sim_manager.py b/embodichain/lab/sim/sim_manager.py index 71b5ed686..215c6ebb6 100644 --- a/embodichain/lab/sim/sim_manager.py +++ b/embodichain/lab/sim/sim_manager.py @@ -112,6 +112,7 @@ def _is_usd_path(path: object | None) -> bool: RigidObjectCfg, VisualObjectCfg, UsdSourceCfg, + UsdImportCfg, DeformableObjectCfg, SurfaceDeformableObjectCfg, VolumeDeformableObjectCfg, @@ -137,6 +138,7 @@ def _is_usd_path(path: object | None) -> bool: rigid_desc_from_usd, visual_desc_from_usd, ) +from embodichain.lab.sim.spawn.usd_result import UsdImportResult from embodichain.lab.sim.spawn.scene import SpawnScene from embodichain.lab.sim import VisualMaterial, VisualMaterialCfg from embodichain.lab.sim.material import _material_desc_from_cfg @@ -2648,206 +2650,94 @@ def get_light_uid_list(self) -> List[str]: def add_usd( self, - name: str, - file_path: str, + cfg: UsdImportCfg | str | None = None, + file_path: str | None = None, *, + name: str | None = None, pose: np.ndarray | None = None, robot_cfgs: dict[str, RobotCfg] | None = None, - ) -> dict[str, VisualObject | RigidObject | Articulation | Robot]: - """Declare the supported entities in a USD scene. - - The returned facades are keyed by their USD prim paths. They remain in - declared state until :meth:`prepare` finalizes the shared Spawn scene, - then bind in place to the resulting DexSim handles. - - Objects without physics or collision geometry become VisualObjects. - Conflicting render-only names receive a ``name_`` prefix; dictionary - keys retain their original USD prim paths. Other UID conflicts fail - before native declarations. + usd: UsdSourceCfg | None = None, + asset_cfgs: ( + dict[str, RigidObjectCfg | ArticulationCfg | dict[str, Any]] | None + ) = None, + ) -> ( + UsdImportResult + | dict[ + str, VisualObject | RigidObject | Articulation | Robot | DeformableObject + ] + ): + """Declare a USD import through a validated configuration recipe. - USD does not identify which articulations should expose EmbodiChain's - robot interface. Pass those explicitly through ``robot_cfgs``; all - other articulation descriptions become :class:`Articulation` objects. + The returned mapping uses source resource keys; unique sources retain + their prim paths. See :class:`UsdImportResult` for derived resource keys. + Facades bind in place at ``prepare()``. Source selection, overrides and supported facade + types are checked before native declaration. Backend materialization is + validated at ``prepare()``; + native creation failures do not promise rollback. Args: - name: Name passed to DexSim's USD scene parser. - file_path: USD, USDA, USDC, or USDZ file path. - pose: Optional scene-root transform. - robot_cfgs: Robot configurations keyed by USD prim path. These - provide robot-side metadata while physics remains authored by - the USD scene. + cfg: Complete USD import recipe. A string retains the legacy name argument. + file_path: Legacy source path; use ``cfg.source.file_path``. + name: Legacy keyword spelling of the import name. + pose: Legacy scene transform; use ``cfg.pose``. + robot_cfgs: Legacy robot metadata; use ``cfg.robot_cfgs``. + usd: Legacy source options; use ``cfg.source`` and ``cfg.namespace``. + asset_cfgs: Legacy per-asset overrides; use ``cfg.asset_cfgs``. Returns: - Supported EmbodiChain facades keyed by USD prim path. - - Raises: - RuntimeError: If called after the Spawn scene was finalized. + Source-path mapping of declared facades and imported resource UIDs. + Legacy argument forms retain the mutable asset dictionary result. """ + from .cfg.usd import _normalize_usd_import + from .spawn.usd_import import _compile_usd_import + if self.spawn_result is not None: raise RuntimeError( "add_usd() must be called before SimulationManager.prepare()." ) - - from dexsim.spawn import ArticulationDesc, MeshObjectDesc - - from dexsim.kit.usd import parse_usd - - source = parse_usd(file_path, root_name=name) - occupied = set(self.asset_uids) - for descriptor in ( - *getattr(self._spawn_scene.builder, "mesh_objects", ()), - *getattr(self._spawn_scene.builder, "scene_entities", ()), - ): - occupied.add(descriptor.name) - # Exported scenes can contain a visual ground named like our global - # physical ground. Keep both and retain the original USD path as the key. - for descriptor in source.mesh_objects: - if ( - descriptor.name in occupied - and descriptor.physics is None - and not descriptor.collisions - ): - descriptor.name = f"{name}_{descriptor.name}" - for collection in ( - "mesh_objects", - "articulations", - "particle_sets", - "cameras", - "lights", - "cables", - "records", - ): - for descriptor in getattr(source, collection, ()): - if descriptor.name in occupied: - raise ValueError( - f"USD asset UID already exists: {descriptor.name!r}." - ) - occupied.add(descriptor.name) - if pose is not None and hasattr(descriptor, "pose"): - descriptor.pose = ( - np.asarray(pose, dtype=np.float32).reshape(4, 4) - @ descriptor.pose - ) - source.materials = self._spawn_scene._resolve_materials(source.materials) - descriptors = self._spawn_scene.builder.add_scene(source, per_env=True) - assets: dict[str, VisualObject | RigidObject | Articulation | Robot] = {} - robot_cfgs = robot_cfgs or {} - - for descriptor in descriptors: - source_path = ( - descriptor.usd.prim_path - if descriptor.usd is not None and descriptor.usd.prim_path - else descriptor.name - ) - - if type(descriptor) is MeshObjectDesc: - if descriptor.physics is None and not descriptor.collisions: - cfg = VisualObjectCfg( - uid=descriptor.name, - source=UsdSourceCfg( - file_path=file_path, - source_prim_path=( - descriptor.usd.prim_path - if descriptor.usd is not None - else None - ), - ), - init_local_pose=descriptor.pose.copy(), - body_scale=tuple( - float(value) for value in descriptor.body_scale - ), - ) - facade = VisualObject(cfg=cfg, device=self.device) - self._spawn_scene.track( - "visual_object", descriptor.name, descriptor, facade=facade - ) - self._visual_objects[descriptor.name] = facade - assets[source_path] = facade - continue - body_type = "static" - if descriptor.physics is not None: - body_type = { - ActorType.DYNAMIC: "dynamic", - ActorType.KINEMATIC: "kinematic", - ActorType.STATIC: "static", - }[descriptor.physics.actor_type] - cfg = RigidObjectCfg( - uid=descriptor.name, - source=UsdSourceCfg( - file_path=file_path, - source_prim_path=( - descriptor.usd.prim_path - if descriptor.usd is not None - else None - ), - ), - init_local_pose=descriptor.pose.copy(), - body_type=body_type, - body_scale=tuple(float(value) for value in descriptor.body_scale), - asset_physics_mode="preserve", - ) - facade = RigidObject( - cfg=cfg, - device=self.device, - ) - - self._spawn_scene.track( - "rigid_object", - descriptor.name, - descriptor, - facade=facade, - ) - self._rigid_objects[descriptor.name] = facade - assets[source_path] = facade - continue - - if isinstance(descriptor, ArticulationDesc): - robot_cfg = robot_cfgs.get(source_path) - facade_type: type[Articulation] = ( - Robot if robot_cfg is not None else Articulation - ) - cfg = ( - deepcopy(robot_cfg) - if robot_cfg is not None - else ArticulationCfg(uid=descriptor.name) - ) - cfg.uid = descriptor.name - cfg.fpath = None - cfg.source = UsdSourceCfg( - file_path=file_path, - source_prim_path=( - descriptor.usd.prim_path if descriptor.usd is not None else None - ), - ) - cfg.init_local_pose = descriptor.pose.copy() - cfg.asset_physics_mode = "preserve" - if robot_cfg is None: - cfg.root_props = ArticulationRootPropertiesCfg() - else: - cfg.root_props = cfg.root_props.copy() - cfg.root_props.fixed_base = bool(descriptor.fixed_base) - cfg.root_props.self_collision_enabled = descriptor.enable_self_collision - cfg.body_scale = tuple(float(value) for value in descriptor.body_scale) - cfg.build_pk_chain = False - facade = facade_type( - cfg=cfg, - device=self.device, - ) - - self._spawn_scene.track( - "articulation", - descriptor.name, - descriptor, - facade=facade, - ) - registry = ( - self._robots if robot_cfg is not None else self._articulations - ) - registry[descriptor.name] = facade - assets[source_path] = facade - + legacy_result = not isinstance(cfg, UsdImportCfg) + recipe = _normalize_usd_import( + cfg, + file_path=file_path, + name=name, + pose=pose, + robot_cfgs=robot_cfgs, + usd=usd, + asset_cfgs=asset_cfgs, + ) + plan = _compile_usd_import(self, recipe) + plan.source.materials = self._spawn_scene._resolve_materials( + plan.source.materials + ) + added = self._spawn_scene.builder.add_scene(plan.source, per_env=True) + added_by_name = {item.name: item for item in added} + assets = {} + for source_path, kind, descriptor, facade in plan.declarations: + self._spawn_scene.track( + kind, descriptor.name, added_by_name[descriptor.name], facade=facade + ) + registry = { + "visual_object": self._visual_objects, + "rigid_object": self._rigid_objects, + "articulation": ( + self._robots if isinstance(facade, Robot) else self._articulations + ), + "soft_object": self._deformable_objects, + "cloth_object": self._deformable_objects, + }[kind] + registry[descriptor.name] = facade + assets[source_path] = facade + for sensor_cfg in plan.mounted_sensors: + self.add_sensor(sensor_cfg) self.notify_visualization_topology_changed() - return assets + result = UsdImportResult( + assets, + resource_uids=plan.resource_uids, + resource_types=plan.resource_types, + constraint_uids=plan.constraint_uids, + resource_source_paths=plan.resource_source_paths, + ) + return dict(result) if legacy_result else result def add_visual_object(self, cfg: VisualObjectCfg) -> VisualObject: """Declare a render-only mesh or primitive, without physics or colliders. @@ -2859,6 +2749,7 @@ def add_visual_object(self, cfg: VisualObjectCfg) -> VisualObject: Returns: The declared facade, bound after ``prepare()``. """ + cfg = deepcopy(cfg) if cfg.uid is None or cfg.uid in self.asset_uids: raise ValueError("Visual object requires a unique, nonempty UID.") path = _asset_file_path(cfg) @@ -2900,16 +2791,22 @@ def get_visual_object_uid_list(self) -> list[str]: def add_rigid_object( self, cfg: RigidObjectCfg, + *, + validate_resolved: Callable[[RigidObjectCfg], None] | None = None, ) -> RigidObject: """Add a rigid object to the scene. Args: cfg (RigidObjectCfg): Configuration for the rigid object. + validate_resolved: Optional check of the source-resolved config, + run before declaring the object in Spawn. Returns: RigidObject: The added rigid object instance handle. """ - return self._declare_rigid_object(cfg, replace=False) + return self._declare_rigid_object( + cfg, replace=False, validate_resolved=validate_resolved + ) def replace_rigid_object(self, cfg: RigidObjectCfg) -> RigidObject: """Replace a rigid object with the same UID in one preparation. @@ -2959,15 +2856,25 @@ def replace_rigid_objects( return self._declare_rigid_objects(cfgs, replace=True) def _declare_rigid_object( - self, cfg: RigidObjectCfg, *, replace: bool + self, + cfg: RigidObjectCfg, + *, + replace: bool, + validate_resolved: Callable[[RigidObjectCfg], None] | None = None, ) -> RigidObject: - return self._declare_rigid_objects([cfg], replace=replace)[0] + return self._declare_rigid_objects( + [cfg], replace=replace, validate_resolved=validate_resolved + )[0] def _declare_rigid_objects( - self, cfgs: Sequence[RigidObjectCfg], *, replace: bool + self, + cfgs: Sequence[RigidObjectCfg], + *, + replace: bool, + validate_resolved: Callable[[RigidObjectCfg], None] | None = None, ) -> list[RigidObject]: """Translate the complete batch before changing the scene.""" - cfgs = list(cfgs) + cfgs = [deepcopy(cfg) for cfg in cfgs] if not cfgs: return [] seen: set[str] = set() @@ -2998,6 +2905,8 @@ def _declare_rigid_objects( per_env=True, newton_solver_type=self._active_newton_solver_type, ) + if validate_resolved is not None: + validate_resolved(cfg) rigid_obj = RigidObject(cfg=cfg, device=self.device) declarations.append((cfg.uid, descriptor, materials, rigid_obj)) @@ -3178,6 +3087,7 @@ def add_deformable_object(self, cfg: DeformableObjectCfg) -> DeformableObject: the requested deformable type. ValueError: If the discriminator or UID is invalid. """ + cfg = deepcopy(cfg) deformable_type = cfg.deformable_type if deformable_type == "volume": supported = self.physics.supports_volume_deformables @@ -3242,7 +3152,12 @@ def add_deformable_object(self, cfg: DeformableObjectCfg) -> DeformableObject: f"A {deformable_type} deformable requires " f"{config_cls.__name__}, got {type(cfg).__name__}." ) - descriptor, materials = descriptor_factory(cfg, per_env=True) + if cfg.source is not None: + from .spawn.usd import _deformable_desc_from_usd + + descriptor, materials = _deformable_desc_from_usd(cfg) + else: + descriptor, materials = descriptor_factory(cfg, per_env=True) self._spawn_scene.builder.materials.update( self._spawn_scene._resolve_materials(materials) ) @@ -3809,6 +3724,7 @@ def _declare_spawn_articulation( backend materializes it. Runtime Batch data is created at the shared prepare boundary. """ + cfg = deepcopy(cfg) if _is_usd_path(_asset_file_path(cfg)): descriptor, materials = articulation_desc_from_usd( cfg, @@ -3827,6 +3743,8 @@ def _declare_spawn_articulation( if cfg.uid is None: cfg.uid = descriptor.name + cfg.root_props.fixed_base = bool(descriptor.fixed_base) + cfg.root_props.self_collision_enabled = descriptor.enable_self_collision facade = facade_type( cfg=cfg, device=self.device, diff --git a/embodichain/lab/sim/spawn/descriptors.py b/embodichain/lab/sim/spawn/descriptors.py index f6d1a4565..e710f5d96 100644 --- a/embodichain/lab/sim/spawn/descriptors.py +++ b/embodichain/lab/sim/spawn/descriptors.py @@ -318,6 +318,8 @@ def visual_desc_from_cfg( raise NotImplementedError( "Visual objects support MeshCfg, CubeCfg and SphereCfg." ) + if cfg.body_scale is None: + cfg.body_scale = (1.0, 1.0, 1.0) scale = _vector3(cfg.body_scale, field_name="body_scale") material_ref, material_entry = _compile_visual_material(uid, shape.visual_material) return ObjectDesc( @@ -351,6 +353,11 @@ def rigid_desc_from_cfg( "select one rigid object." ) + if cfg.body_type is None: + cfg.body_type = "dynamic" + if cfg.body_scale is None: + cfg.body_scale = (1.0, 1.0, 1.0) + physics = _with_procedural_collision_defaults( _resolve_rigid_physics( cfg.attrs, @@ -811,6 +818,8 @@ def articulation_desc_from_cfg( "USD files describe typed scenes; use articulation_desc_from_usd() " "to select one articulation." ) + if cfg.body_scale is None: + cfg.body_scale = (1.0, 1.0, 1.0) if cfg.resolve_asset_physics_mode() == "overlay": _validate_articulation_rigid_physics( cfg, @@ -2006,7 +2015,7 @@ def _articulation_uid(value: str | None, path: str | None) -> str: def _is_usd_path(path: object) -> bool: - return str(path).lower().endswith((".usd", ".usda", ".usdc")) + return str(path).lower().endswith((".usd", ".usda", ".usdc", ".usdz")) def _is_missing(value: object) -> bool: diff --git a/embodichain/lab/sim/spawn/scene.py b/embodichain/lab/sim/spawn/scene.py index 8b9904a92..0ffbd5c7f 100644 --- a/embodichain/lab/sim/spawn/scene.py +++ b/embodichain/lab/sim/spawn/scene.py @@ -20,7 +20,7 @@ from collections.abc import Iterator from contextlib import contextmanager -from dataclasses import dataclass +from dataclasses import dataclass, fields, replace from typing import Any, Callable, Literal from ._usd_assets import _UsdTextureFiles @@ -116,9 +116,38 @@ def _resolve_materials(self, materials: dict[str, Any]) -> dict[str, Any]: # Native Spawn's simplified MaterialDesc path cannot express these # definitions. Bind the exact loaded child directly on each RenderDesc. # NoRender retains only metadata and never invokes a native loader. - return {uid: desc for uid, desc in resolved.items() if uid not in resources} + native = {uid: desc for uid, desc in resolved.items() if uid not in resources} + if ( + getattr(getattr(self, "_material_resources", None), "renderer", None) + == "no-render" + ): + # NoRender has no texture or alpha-mode consumer. Retain authored + # recipes for metadata/identity while avoiding rendering-only + # resource creation and setters in its native adapter input. + from dexsim.spawn import MaterialDesc + + if not hasattr(self, "_no_render_material_definitions"): + self._no_render_material_definitions = {} + for uid, desc in native.items(): + if isinstance(desc, MaterialDesc): + self._no_render_material_definitions[uid] = desc + omitted = { + item.name: None + for item in fields(desc) + if item.name.endswith("_map") + } + omitted.update( + alpha_mode=None, + unlit=None, + depth_write=None, + transmission_bounce_limit=None, + ) + native[uid] = replace(desc, **omitted) + return native def _material_definition(self, uid: str) -> Any | None: + if uid in getattr(self, "_no_render_material_definitions", {}): + return self._no_render_material_definitions[uid] return getattr(self, "_resource_material_definitions", {}).get( uid, self.builder.materials.get(uid) ) @@ -453,6 +482,7 @@ def close(self) -> None: self.builder.result = None self._assets.clear() self._usd_texture_files.close() + getattr(self, "_no_render_material_definitions", {}).clear() if hasattr(self, "_material_resources"): self._material_resources.close() self._resource_material_definitions.clear() diff --git a/embodichain/lab/sim/spawn/usd.py b/embodichain/lab/sim/spawn/usd.py index f00b7dcd7..71a60ad39 100644 --- a/embodichain/lab/sim/spawn/usd.py +++ b/embodichain/lab/sim/spawn/usd.py @@ -17,11 +17,10 @@ from __future__ import annotations -from ._usd_assets import _parse_singleton - import os from dataclasses import fields, replace from typing import TypeVar +import numpy as np from dexsim.spawn import ( ArticulationDesc, @@ -33,7 +32,14 @@ ) from dexsim.types import ActorType -from embodichain.lab.sim.cfg import ArticulationCfg, RigidObjectCfg, VisualObjectCfg +from embodichain.lab.sim.cfg import ( + ArticulationCfg, + ObjectBaseCfg, + RigidObjectCfg, + VisualObjectCfg, + UsdSourceCfg, + DeformableObjectCfg, +) from embodichain.lab.sim.cfg.source import _asset_file_path, _source_prim_path from embodichain.lab.sim.spawn.descriptors import ( _apply_newton_gap_default, @@ -44,6 +50,7 @@ _articulation_root_values, _articulation_gravity_compensation, _pose_from_cfg, + _particle_flags_from_cfg, _required_uid, _resolve_rigid_physics, _validate_articulation_rigid_physics, @@ -55,6 +62,111 @@ _PropertyCfgT = TypeVar("_PropertyCfgT") +def _require_usd_import_contract() -> None: + """Reject DexSim wheels without source selection and scene constraints.""" + import inspect + from dexsim.kit.usd import parse_stage + from dexsim.spawn import SceneDesc + + if ( + "prim_path" not in inspect.signature(parse_stage).parameters + or "constraints" not in SceneDesc.__dataclass_fields__ + ): + raise RuntimeError( + "USD loading requires a compatible DexSim build with source selection " + "and standalone constraint support." + ) + + +def _source_pose( + cfg: RigidObjectCfg | ArticulationCfg | DeformableObjectCfg | VisualObjectCfg, + source_pose: np.ndarray, +) -> np.ndarray: + source = cfg.source + mode = cfg.source_pose_mode + if source is not None and source.pose_mode != "auto": + if mode != "auto" and mode != source.pose_mode: + raise ValueError( + "Conflicting source_pose_mode and legacy source.pose_mode." + ) + mode = source.pose_mode + if mode not in {"auto", "config", "preserve", "offset"}: + raise ValueError(f"Unsupported source_pose_mode {mode!r}.") + configured = _pose_from_cfg(cfg) + if mode == "preserve": + return source_pose.copy() + if mode == "offset": + return configured @ source_pose + if mode == "auto" and cfg.init_local_pose is None: + if not np.any(np.asarray(cfg.init_pos)) and not np.any( + np.asarray(cfg.init_rot) + ): + return source_pose.copy() + return configured + + +def _set_resolved_usd_pose(cfg: ObjectBaseCfg, pose: np.ndarray) -> None: + """Keep a resolved runtime config reusable as an absolute placement. + + Import callers retain their original intent in their own config. The + returned facade config represents the effective placement, including any + scene transform, so reimporting it must not apply source placement again. + """ + cfg.init_local_pose = pose.copy() + cfg.source_pose_mode = "config" + source = getattr(cfg, "source", None) + if source is not None: + source.pose_mode = "auto" + + +def _deformable_desc_from_usd(cfg: DeformableObjectCfg): + if cfg.source is None: + raise ValueError("USD deformables require a source configuration.") + cfg.source.validate_source() + scene, descriptor = _parse_singleton( + cfg.source.file_path, "particle_sets", "deformable", source=cfg.source + ) + _configure_deformable_usd(cfg, descriptor) + return descriptor, scene.materials + + +def _configure_deformable_usd(cfg: DeformableObjectCfg, descriptor) -> None: + from dexsim.spawn import SoftBodyDesc, ClothDesc + + expected = SoftBodyDesc if cfg.deformable_type == "volume" else ClothDesc + if not isinstance(descriptor, expected): + raise ValueError(f"USD source is not a {cfg.deformable_type} deformable.") + if cfg.attrs.to_dict() != type(cfg.attrs)().to_dict(): + raise ValueError( + "USD deformable physics is source-owned; physical config overrides are not supported." + ) + meshing = getattr(cfg, "meshing", None) + if meshing is not None and meshing.to_dict() != type(meshing)().to_dict(): + raise ValueError( + "USD deformable simulation topology is source-owned; meshing overrides are not supported." + ) + if getattr(cfg, "visual_shape", None) is not None: + raise ValueError("USD deformable source already owns its visual mesh.") + if ( + getattr(cfg.shape, "fpath", None) is not None + or getattr(cfg.shape, "vertices", None) is not None + ): + raise ValueError( + "USD deformable source cannot be combined with configured mesh geometry." + ) + descriptor.name = _required_uid(cfg.uid, "Deformable") + descriptor.pose = _source_pose(cfg, descriptor.pose) + _set_resolved_usd_pose(cfg, descriptor.pose) + if cfg.validate_mesh: + descriptor.validate_mesh = True + if cfg.particle_radius is not None: + if not np.isfinite(cfg.particle_radius) or cfg.particle_radius <= 0: + raise ValueError("particle_radius must be finite and positive.") + descriptor.particle_radius = cfg.particle_radius + if cfg.particle_flags is not None: + descriptor.particle_flags = _particle_flags_from_cfg(cfg.particle_flags) + + def _overlay_optional_properties( source: _PropertyCfgT | None, configured: _PropertyCfgT | None, @@ -126,15 +238,17 @@ def visual_desc_from_usd( _asset_file_path(cfg), "mesh_objects", "visual object", - prim_path=_source_prim_path(cfg), + source=cfg.source, ) desc.name = _required_uid(cfg.uid, "Visual object") - desc.pose = _pose_from_cfg(cfg) + desc.pose = _source_pose(cfg, desc.pose) + _set_resolved_usd_pose(cfg, desc.pose) desc.per_env = per_env desc.physics = None desc.collisions = [] - scale = _vector3(cfg.body_scale, field_name="body_scale") - desc.body_scale = scale + if cfg.body_scale is not None: + desc.body_scale = _vector3(cfg.body_scale, field_name="body_scale") + cfg.body_scale = tuple(float(value) for value in desc.body_scale) materials = _namespace_materials(desc.renders, scene.materials, desc.name) material_ref, material_entry = _compile_visual_material( desc.name, getattr(cfg.shape, "visual_material", None) @@ -157,11 +271,29 @@ def rigid_desc_from_usd( uid = _required_uid(cfg.uid, "Rigid object") path = _asset_file_path(cfg) scene, desc = _parse_singleton( - path, "mesh_objects", "rigid object", prim_path=_source_prim_path(cfg) + path, "mesh_objects", "rigid object", source=cfg.source + ) + + return _configure_rigid_usd( + cfg, scene, desc, per_env=per_env, newton_solver_type=newton_solver_type ) + +def _configure_rigid_usd( + cfg: RigidObjectCfg, + scene, + desc: ObjectDesc, + *, + per_env: bool = True, + newton_solver_type: str | None = None, +) -> tuple[ObjectDesc, dict[str, MaterialDesc]]: + """Apply a rigid configuration to an already parsed USD descriptor.""" + uid = _required_uid(cfg.uid, "Rigid object") + path = _asset_file_path(cfg) + desc.name = uid - desc.pose = _pose_from_cfg(cfg) + desc.pose = _source_pose(cfg, desc.pose) + _set_resolved_usd_pose(cfg, desc.pose) desc.per_env = per_env materials = _namespace_materials(desc.renders, scene.materials, uid) @@ -181,13 +313,26 @@ def rigid_desc_from_usd( cfg.attrs, newton_solver_type=newton_solver_type, ) - configured_body = _compile_rigid_physics(physics, cfg.body_type) + actor_type = cfg.body_type + if actor_type is None: + if desc.physics is None: + actor_type = "static" + else: + actor_type = { + ActorType.DYNAMIC: "dynamic", + ActorType.KINEMATIC: "kinematic", + ActorType.STATIC: "static", + }[desc.physics.actor_type] + configured_body = _compile_rigid_physics(physics, actor_type) desc.physics = _overlay_rigid_body_properties( desc.physics, configured_body, recompute_inertia=bool(physics.recompute_inertia), ) - desc.body_scale = _vector3(cfg.body_scale, field_name="body_scale") + if cfg.body_scale is not None: + desc.body_scale = _vector3(cfg.body_scale, field_name="body_scale") + cfg.body_type = actor_type + cfg.body_scale = tuple(float(value) for value in desc.body_scale) for collision in desc.collisions: _overlay_collision_properties( collision, @@ -222,7 +367,6 @@ def articulation_desc_from_usd( newton_solver_type: str | None = None, ) -> tuple[ArticulationDesc, dict[str, MaterialDesc]]: """Select an articulation by exact prim path, or require a singleton stage.""" - compensation = _articulation_gravity_compensation(cfg, newton_solver_type) preserve_asset_physics = cfg.resolve_asset_physics_mode() == "preserve" if not preserve_asset_physics: _validate_articulation_rigid_physics( @@ -232,23 +376,48 @@ def articulation_desc_from_usd( configured_path = _asset_file_path(cfg) path = source_path or configured_path scene, desc = _parse_singleton( - path, "articulations", "articulation", prim_path=_source_prim_path(cfg) + path, "articulations", "articulation", source=cfg.source + ) + return _configure_articulation_usd( + cfg, + scene, + desc, + per_env=per_env, + source_path=path, + newton_solver_type=newton_solver_type, ) + + +def _configure_articulation_usd( + cfg: ArticulationCfg, + scene, + desc: ArticulationDesc, + *, + per_env: bool = True, + source_path: str | None = None, + newton_solver_type: str | None = None, +) -> tuple[ArticulationDesc, dict[str, MaterialDesc]]: + """Apply an articulation configuration to an already parsed USD descriptor.""" + compensation = _articulation_gravity_compensation(cfg, newton_solver_type) + preserve_asset_physics = cfg.resolve_asset_physics_mode() == "preserve" + if not preserve_asset_physics: + _validate_articulation_rigid_physics(cfg, newton_solver_type=newton_solver_type) + path = source_path or _asset_file_path(cfg) uid = _required_uid( cfg.uid or os.path.splitext(os.path.basename(str(path)))[0], "Articulation", ) cfg.uid = uid desc.name = uid - desc.pose = _pose_from_cfg(cfg) + desc.pose = _source_pose(cfg, desc.pose) + _set_resolved_usd_pose(cfg, desc.pose) desc.per_env = per_env renders = [visual for link in desc.links for visual in link.visuals] materials = _namespace_materials(renders, scene.materials, uid) - if preserve_asset_physics: - cfg.body_scale = tuple(float(value) for value in desc.body_scale) - else: + if not preserve_asset_physics and cfg.body_scale is not None: desc.body_scale = _vector3(cfg.body_scale, field_name="body_scale") + cfg.body_scale = tuple(float(value) for value in desc.body_scale) desc.fixed_base, desc.enable_self_collision = _articulation_root_values( cfg, fixed_base_default=bool(desc.fixed_base), @@ -259,6 +428,64 @@ def articulation_desc_from_usd( return desc, materials +def _parse_singleton(path: object, collection: str, label: str, *, source=None): + if path is None: + raise ValueError(f"A USD path is required for the {label}.") + + scene = _parse_usd_source( + source or UsdSourceCfg(file_path=str(path)), source_path=str(path) + ) + candidates = getattr(scene, collection) + prim_path = None if source is None else source.source_prim_path + if prim_path is not None: + candidates = [ + item + for item in candidates + if item.usd is not None and item.usd.prim_path == prim_path + ] + if len(candidates) != 1: + found = [ + (item.name, None if item.usd is None else item.usd.prim_path) + for item in candidates + ] + selection = "" if prim_path is None else f" at prim path {prim_path!r}" + raise ValueError( + f"Expected exactly one {label} in USD file {path!r}{selection}, found " + f"{len(candidates)}: {found}." + ) + selected = candidates[0] + if label != "visual object": + for constraint in scene.constraints: + if any( + endpoint is not None and endpoint.partition("/")[0] == selected.name + for endpoint in (constraint.body0, constraint.body1) + ): + raise ValueError( + "A selected USD asset with standalone constraints requires SimulationManager.add_usd()." + ) + return scene, selected + + +def _parse_usd_source( + source: UsdSourceCfg, + *, + name: str | None = None, + namespace: str | None = None, + source_path: str | None = None, +): + """Read one fresh DexSim scene for singleton and whole-scene imports.""" + from dexsim.kit.usd import parse_usd + + _require_usd_import_contract() + source.validate_source() + options = source.parse_kwargs() + if name is not None: + options["root_name"] = name + if namespace is not None: + options["namespace"] = namespace + return parse_usd(source_path or source.file_path, **options) + + def _namespace_materials( renders: list[RenderDesc], materials: dict[str, MaterialDesc], diff --git a/embodichain/lab/sim/spawn/usd_import.py b/embodichain/lab/sim/spawn/usd_import.py new file mode 100644 index 000000000..4256a1fa8 --- /dev/null +++ b/embodichain/lab/sim/spawn/usd_import.py @@ -0,0 +1,537 @@ +# ---------------------------------------------------------------------------- +# Copyright (c) 2021-2026 DexForce Technology Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------- + +"""Compile a USD import completely before native scene declaration.""" + +from __future__ import annotations + +from collections import Counter +from copy import deepcopy +from dataclasses import dataclass, fields +from typing import TYPE_CHECKING, Any + +import numpy as np + +from dexsim.spawn import ( + ArticulationDesc, + ConstraintDesc, + MeshObjectDesc, + SoftBodyDesc, + ClothDesc, +) + +from embodichain.lab.sim.cfg import ( + ArticulationCfg, + ArticulationRootPropertiesCfg, + RigidObjectCfg, + RobotCfg, + VisualObjectCfg, + UsdSourceCfg, + UsdImportCfg, + VolumeDeformableObjectCfg, + SurfaceDeformableObjectCfg, +) +from embodichain.lab.sim.objects import ( + Articulation, + RigidObject, + Robot, + VisualObject, + VolumeDeformableObject, + SurfaceDeformableObject, +) +from embodichain.lab.sim.sensors import Camera, CameraCfg, StereoCamera, StereoCameraCfg +from .descriptors import _pose_from_cfg, configure_articulation_desc +from .usd import ( + _configure_articulation_usd, + _configure_rigid_usd, + _parse_usd_source, + _source_pose, + _set_resolved_usd_pose, +) + +if TYPE_CHECKING: + from embodichain.lab.sim.sim_manager import SimulationManager + +__all__: list[str] = [] + + +@dataclass +class _UsdImportPlan: + source: Any + declarations: list[tuple[str, str, Any, Any]] + mounted_sensors: list[Any] + resource_uids: dict[str, str] + resource_types: dict[str, str] + constraint_uids: dict[str, str] + resource_source_paths: dict[str, str] + + +def _source_path(descriptor: Any) -> str: + usd = getattr(descriptor, "usd", None) + return usd.prim_path if usd is not None and usd.prim_path else descriptor.name + + +def _compile_usd_import( + manager: SimulationManager, recipe: UsdImportCfg +) -> _UsdImportPlan: + recipe.validate_import() + file_path = recipe.source.file_path + source = _parse_usd_source( + recipe.source, name=recipe.name, namespace=recipe.namespace + ) + if source.gaussian_splats: + raise NotImplementedError( + "USD Gaussian-splat imports are not supported by the EmbodiChain USD entry point." + ) + unsupported_particles = [ + type(item).__name__ + for item in source.particle_sets + if not isinstance(item, (SoftBodyDesc, ClothDesc)) + ] + if unsupported_particles: + raise NotImplementedError( + f"Unsupported USD particle-set types: {unsupported_particles}." + ) + resources = list(source.iter_entities()) + source_paths_by_id = {id(item): _source_path(item) for item in resources} + counts = Counter(source_paths_by_id.values()) + occurrences: Counter[str] = Counter() + resource_keys = {} + for item in resources: + path = source_paths_by_id[id(item)] + resource_keys[id(item)] = ( + path if counts[path] == 1 else f"{path}#{occurrences[path]}" + ) + occurrences[path] += 1 + descriptors = [item for item in resources if not isinstance(item, ConstraintDesc)] + robot_cfgs = recipe.robot_cfgs + asset_cfgs = recipe.asset_cfgs + source_paths = { + ( + item.usd.prim_path + if item.usd is not None and item.usd.prim_path + else item.name + ) + for item in (*source.mesh_objects, *source.articulations, *source.particle_sets) + } + overlap = robot_cfgs.keys() & asset_cfgs.keys() + missing = (robot_cfgs.keys() | asset_cfgs.keys()) - source_paths + if overlap or missing: + raise ValueError( + f"Invalid USD configuration targets; duplicate={sorted(overlap)}, missing={sorted(missing)}." + ) + root_pose = ( + None if recipe.pose is None else np.asarray(recipe.pose, dtype=np.float32) + ) + if root_pose is not None and ( + root_pose.shape != (4, 4) or not np.isfinite(root_pose).all() + ): + raise ValueError("USD scene pose must be a finite (4, 4) transform.") + + occupied = set(manager.asset_uids) + for collection in ( + "mesh_objects", + "articulations", + "particle_sets", + "constraints", + "cameras", + "lights", + "records", + "cables", + "scene_entities", + ): + for item in getattr(manager._spawn_scene.builder, collection, ()): + occupied.add(item.name) + declarations = [] + mounted_sensors = [] + sensor_uids = set(manager._sensors) + renamed = {} + rigid_renames = {} + for descriptor in descriptors: + original_name = descriptor.name + source_path = ( + descriptor.usd.prim_path + if descriptor.usd is not None and descriptor.usd.prim_path + else descriptor.name + ) + configured = asset_cfgs.get(source_path) + legacy_robot = robot_cfgs.get(source_path) + is_articulation = isinstance(descriptor, ArticulationDesc) + is_soft = isinstance(descriptor, SoftBodyDesc) + is_cloth = isinstance(descriptor, ClothDesc) + is_deformable = is_soft or is_cloth + if is_deformable and ( + manager.physics.name != "newton" or manager.device.type != "cuda" + ): + raise NotImplementedError( + "USD soft bodies and cloth require the Newton backend on CUDA." + ) + if is_deformable and manager._active_newton_solver_type not in ( + None, + "dexuni", + "xpbd", + "semi_implicit", + "vbd", + ): + raise NotImplementedError( + "The active Newton solver does not support USD soft bodies or cloth." + ) + if is_deformable and manager.sim_config.physics_cfg.requires_grad: + raise NotImplementedError( + "USD deformable facades do not support Newton gradient mode." + ) + if legacy_robot is not None and not is_articulation: + raise ValueError( + f"USD robot target must be an articulation: {source_path}." + ) + selected_path = ( + descriptor.usd.prim_path + if descriptor.usd is not None and descriptor.usd.prim_path + else None + ) + is_visual = ( + type(descriptor) is MeshObjectDesc + and descriptor.physics is None + and not descriptor.collisions + ) + if configured is not None and not isinstance( + descriptor, (MeshObjectDesc, ArticulationDesc, SoftBodyDesc, ClothDesc) + ): + raise ValueError( + f"USD configuration type does not match source entity {source_path}." + ) + if isinstance(configured, dict): + data = deepcopy(configured) + source_options = data.pop("source", None) + if source_options is not None: + if not isinstance(source_options, dict) or set(source_options) != { + "pose_mode" + }: + raise ValueError( + f"Per-asset source selection is not supported: {source_path}." + ) + if "shape" in data or "fpath" in data: + raise ValueError( + f"USD source selection belongs to add_usd(), not asset_cfgs: {source_path}." + ) + config_type = ( + VolumeDeformableObjectCfg + if is_soft + else ( + SurfaceDeformableObjectCfg + if is_cloth + else ( + ArticulationCfg + if is_articulation + else VisualObjectCfg if is_visual else RigidObjectCfg + ) + ) + ) + if is_deformable and set(data) - { + "uid", + "init_pos", + "init_rot", + "init_local_pose", + "source_pose_mode", + "particle_flags", + "particle_radius", + }: + raise ValueError( + "USD deformable overrides currently support identity, placement and particle flags/radius; physical properties stay authored by the source." + ) + unknown = data.keys() - {item.name for item in fields(config_type)} + if unknown: + raise ValueError( + f"Unknown USD override fields at {source_path}: {sorted(unknown)}." + ) + cfg = config_type.from_dict(data) + if data.get("init_local_pose") is None: + cfg.init_local_pose = None + if {"init_pos", "init_rot"}.intersection(data): + cfg.init_local_pose = _pose_from_cfg(cfg) + if not is_deformable and "body_scale" not in data: + cfg.body_scale = None + if ( + not is_articulation + and not is_deformable + and not is_visual + and "body_type" not in data + ): + cfg.body_type = None + pose_mode = ( + "auto" if source_options is None else source_options["pose_mode"] + ) + elif configured is not None: + expected_type = ( + VolumeDeformableObjectCfg + if is_soft + else ( + SurfaceDeformableObjectCfg + if is_cloth + else ( + ArticulationCfg + if is_articulation + else VisualObjectCfg if is_visual else RigidObjectCfg + ) + ) + ) + if not isinstance(configured, expected_type): + raise ValueError( + f"USD configuration type does not match source entity {source_path}." + ) + cfg = deepcopy(configured) + if (is_articulation and cfg.fpath is not None) or ( + not is_articulation and not is_deformable and cfg.shape is not None + ): + raise ValueError( + f"Per-asset source selection is not supported: {source_path}." + ) + if cfg.source is not None and ( + isinstance(cfg.source.file_path, str) + or cfg.source.source_prim_path is not None + or cfg.source.prim_path is not None + or cfg.source.root_prim_path is not None + or cfg.source.variants is not None + or cfg.source.namespace is not None + ): + raise ValueError( + f"Per-asset source selection is not supported: {source_path}." + ) + pose_mode = "auto" if cfg.source is None else cfg.source.pose_mode + elif legacy_robot is not None: + cfg = deepcopy(legacy_robot) + cfg.uid = descriptor.name + cfg.asset_physics_mode = "preserve" + cfg.init_local_pose = None + cfg.root_props.fixed_base = descriptor.fixed_base + cfg.root_props.self_collision_enabled = descriptor.enable_self_collision + pose_mode = "preserve" + elif is_articulation: + cfg = ArticulationCfg(build_pk_chain=False) + cfg.init_local_pose = None + cfg.body_scale = None + pose_mode = "preserve" + elif is_deformable: + cfg = ( + VolumeDeformableObjectCfg() if is_soft else SurfaceDeformableObjectCfg() + ) + pose_mode = "preserve" + elif is_visual: + cfg = VisualObjectCfg() + cfg.body_scale = tuple(float(value) for value in descriptor.body_scale) + pose_mode = "preserve" + elif type(descriptor) is MeshObjectDesc: + cfg = RigidObjectCfg() + cfg.init_local_pose = None + cfg.body_type = None + cfg.body_scale = None + pose_mode = "preserve" + else: + if descriptor.name in occupied: + raise ValueError(f"USD asset UID already exists: {descriptor.name!r}.") + occupied.add(descriptor.name) + if root_pose is not None and hasattr(descriptor, "pose"): + descriptor.pose = root_pose @ descriptor.pose + continue + + uid = cfg.uid or descriptor.name + if is_visual and uid in occupied: + uid = f"{recipe.name}_{uid}" + if uid in occupied: + raise ValueError(f"USD asset UID already exists: {uid!r}.") + occupied.add(uid) + cfg.uid = uid + cfg.source = deepcopy(recipe.source) + cfg.source.source_prim_path = selected_path + if cfg.source_pose_mode == "auto": + cfg.source_pose_mode = pose_mode + if is_deformable: + from .usd import _configure_deformable_usd + + _configure_deformable_usd(cfg, descriptor) + kind = "soft_object" if is_soft else "cloth_object" + facade_type = VolumeDeformableObject if is_soft else SurfaceDeformableObject + materials = {} + elif is_articulation: + cfg.fpath = None + cfg.source.parse_kwargs() + if configured is None and legacy_robot is None: + cfg.root_props = ArticulationRootPropertiesCfg() + descriptor, materials = _configure_articulation_usd( + cfg, + source, + descriptor, + source_path=file_path, + newton_solver_type=manager._active_newton_solver_type, + ) + configure_articulation_desc( + descriptor, cfg, newton_solver_type=manager._active_newton_solver_type + ) + kind = "articulation" + facade_type = Robot if isinstance(cfg, RobotCfg) else Articulation + cfg.root_props.fixed_base = bool(descriptor.fixed_base) + cfg.root_props.self_collision_enabled = descriptor.enable_self_collision + elif is_visual: + descriptor.name = uid + descriptor.pose = _source_pose(cfg, descriptor.pose) + if cfg.body_scale is not None: + from .descriptors import _vector3 + + descriptor.body_scale = _vector3( + cfg.body_scale, field_name="body_scale" + ) + cfg.body_scale = tuple(float(value) for value in descriptor.body_scale) + kind = "visual_object" + facade_type = VisualObject + materials = {} + else: + cfg.shape = None + cfg.source.parse_kwargs() + if ( + descriptor.physics is None + and cfg.resolve_asset_physics_mode() == "preserve" + ): + descriptor.name = uid + descriptor.pose = _source_pose(cfg, descriptor.pose) + cfg.body_type = "static" + cfg.body_scale = tuple(float(value) for value in descriptor.body_scale) + materials = {} + else: + descriptor, materials = _configure_rigid_usd( + cfg, + source, + descriptor, + newton_solver_type=manager._active_newton_solver_type, + ) + kind = "rigid_object" + facade_type = RigidObject + if root_pose is not None: + descriptor.pose = root_pose @ descriptor.pose + _set_resolved_usd_pose(cfg, descriptor.pose) + source.materials.update(materials) + if isinstance(cfg, RobotCfg) and cfg.enable_sensor: + for sensor_cfg in cfg.sensors: + if not isinstance(sensor_cfg, CameraCfg): + raise TypeError("RobotCfg.sensors supports mounted cameras only.") + sensor_factory = manager.SUPPORTED_SENSOR_TYPES.get( + sensor_cfg.sensor_type + ) + if not isinstance(sensor_factory, type) or not issubclass( + sensor_factory, Camera + ): + raise ValueError( + f"Unsupported mounted camera type {sensor_cfg.sensor_type!r}." + ) + if issubclass(sensor_factory, StereoCamera) and not isinstance( + sensor_cfg, StereoCameraCfg + ): + raise TypeError( + "StereoCamera requires a StereoCameraCfg configuration." + ) + manager._require_native_renderer("Mounted cameras") + if not isinstance(sensor_cfg.uid, str) or not sensor_cfg.uid.strip(): + raise ValueError("Mounted sensors require a non-empty uid.") + if sensor_cfg.uid in sensor_uids: + raise ValueError(f"Sensor {sensor_cfg.uid!r} already exists.") + sensor_uids.add(sensor_cfg.uid) + parent = sensor_cfg.extrinsics.parent + if not isinstance(parent, str) or not parent.strip(): + raise ValueError("Mounted sensors require a parent link.") + link_name = parent.removeprefix(f"{uid}/") + if not link_name or "/" in link_name: + raise ValueError( + f"Mounted sensor {sensor_cfg.uid!r} must refer to a local link on robot {uid!r}." + ) + if link_name not in {link.name for link in descriptor.links}: + raise ValueError( + f"Mounted sensor {sensor_cfg.uid!r} refers to unknown link {link_name!r} on robot {uid!r}." + ) + bound_cfg = deepcopy(sensor_cfg) + bound_cfg.extrinsics.parent = f"{uid}/{link_name}" + mounted_sensors.append(bound_cfg) + facade = facade_type(cfg=cfg, device=manager.device) + declarations.append((resource_keys[id(descriptor)], kind, descriptor, facade)) + renamed[original_name] = descriptor.name + if isinstance(descriptor, MeshObjectDesc) and descriptor.physics is not None: + rigid_renames[original_name] = descriptor.name + + for sensor_cfg in mounted_sensors: + if sensor_cfg.uid in occupied: + raise ValueError( + f"Mounted sensor UID {sensor_cfg.uid!r} already exists in the scene." + ) + + def renamed_endpoint(endpoint: str) -> str: + owner, separator, suffix = endpoint.partition("/") + return renamed.get(owner, owner) + separator + suffix + + for constraint in source.constraints: + if constraint.body0 is not None: + constraint.body0 = renamed_endpoint(constraint.body0) + elif root_pose is not None: + constraint.origin_pose = root_pose @ constraint.origin_pose + if constraint.body1 is not None: + constraint.body1 = renamed_endpoint(constraint.body1) + elif root_pose is not None: + constraint.target_pose = root_pose @ constraint.target_pose + if source.newton is not None: + if source.newton.body_order is not None: + source.newton.body_order = [ + rigid_renames.get(name, name) for name in source.newton.body_order + ] + for equality in source.newton.equalities: + if equality.equality_type == 1: + equality.object1 = rigid_renames.get(equality.object1, equality.object1) + equality.object2 = rigid_renames.get(equality.object2, equality.object2) + source.rigid_collision_filter_pairs = [ + (renamed_endpoint(first), renamed_endpoint(second)) + for first, second in source.rigid_collision_filter_pairs + ] + + resource_uids = {resource_keys[id(item)]: item.name for item in resources} + resource_source_paths = { + resource_keys[id(item)]: source_paths_by_id[id(item)] for item in resources + } + public_kinds = { + "soft_object": "volume_deformable", + "cloth_object": "surface_deformable", + } + resource_types = { + path: "robot" if isinstance(facade, Robot) else public_kinds.get(kind, kind) + for path, kind, _, facade in declarations + } + for collection, kind in ( + ("cameras", "camera"), + ("lights", "light"), + ("records", "record"), + ("cables", "cable"), + ("constraints", "constraint"), + ): + resource_types.update( + {resource_keys[id(item)]: kind for item in getattr(source, collection)} + ) + constraint_uids = { + resource_keys[id(item)]: item.name for item in source.constraints + } + return _UsdImportPlan( + source, + declarations, + mounted_sensors, + resource_uids, + resource_types, + constraint_uids, + resource_source_paths, + ) diff --git a/embodichain/lab/sim/spawn/usd_result.py b/embodichain/lab/sim/spawn/usd_result.py new file mode 100644 index 000000000..dd562cb59 --- /dev/null +++ b/embodichain/lab/sim/spawn/usd_result.py @@ -0,0 +1,93 @@ +# ---------------------------------------------------------------------------- +# Copyright (c) 2021-2026 DexForce Technology Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------- + +"""Stable source-path mappings for a declared USD import.""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from types import MappingProxyType +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from embodichain.lab.sim.objects import ( + Articulation, + DeformableObject, + RigidObject, + Robot, + VisualObject, + ) + +__all__ = ["UsdImportResult"] + + +class UsdImportResult( + Mapping[str, "VisualObject | RigidObject | Articulation | Robot | DeformableObject"] +): + """Map source resource keys to stable, declared EmbodiChain facades. + + Facades bind in place at ``SimulationManager.prepare()``. Resource maps + include native-only scene resources and constraints; their values are + logical Spawn UIDs, not native handles or builder indices. A unique source + keeps its prim path as the resource key. When a source prim produces several + resources, each uses ``#`` in parser order, starting at + zero. Keys are independent of namespace and runtime UID changes; + :attr:`resource_source_paths` retains the exact prim path for every key. + """ + + def __init__( + self, + assets: Mapping[ + str, VisualObject | RigidObject | Articulation | Robot | DeformableObject + ], + *, + resource_uids: Mapping[str, str], + resource_types: Mapping[str, str], + constraint_uids: Mapping[str, str], + resource_source_paths: Mapping[str, str] | None = None, + ) -> None: + """Capture mappings for one successful declaration. + + Args: + assets: Source resource keys mapped to stable EmbodiChain facades. + resource_uids: Source resource keys mapped to logical Spawn identifiers. + resource_types: Logical scene resource kinds for the same resource keys. + constraint_uids: Source constraint resource keys mapped to identifiers. + resource_source_paths: Resource keys mapped to their exact source prim + paths. Defaults to identity mapping for singleton resources. + """ + self._assets = MappingProxyType(dict(assets)) + self.resource_source_paths: Mapping[str, str] = MappingProxyType( + dict(resource_source_paths) + if resource_source_paths is not None + else {key: key for key in resource_uids} + ) + self.resource_uids: Mapping[str, str] = MappingProxyType(dict(resource_uids)) + self.resource_types: Mapping[str, str] = MappingProxyType(dict(resource_types)) + self.constraint_uids: Mapping[str, str] = MappingProxyType( + dict(constraint_uids) + ) + + def __getitem__( + self, source_path: str + ) -> VisualObject | RigidObject | Articulation | Robot | DeformableObject: + return self._assets[source_path] + + def __iter__(self) -> Iterator[str]: + return iter(self._assets) + + def __len__(self) -> int: + return len(self._assets) diff --git a/embodichain/lab/sim/utility/sim_utils.py b/embodichain/lab/sim/utility/sim_utils.py index 0ed7b5a9f..4a3dbf0cc 100644 --- a/embodichain/lab/sim/utility/sim_utils.py +++ b/embodichain/lab/sim/utility/sim_utils.py @@ -686,7 +686,6 @@ def spawn_rigid_object_entities( if clone_options is None: clone_options = default_rigid_object_clone_options() - body_type = cfg.to_dexsim_body_type() is_newton_backend = _is_newton_backend_active() if is_newton_backend: raise TypeError( @@ -709,7 +708,7 @@ def spawn_rigid_object_entities( source_env, cfg, cache_dir=cache_dir, - body_type=body_type, + body_type=cfg.to_dexsim_body_type(), is_newton_backend=is_newton_backend, ) prototype.set_name(prototype_name) @@ -721,7 +720,7 @@ def spawn_rigid_object_entities( _configure_primitive_rigidbody( prototype, cfg, - body_type, + cfg.to_dexsim_body_type(), is_newton_backend=is_newton_backend, shape_type=RigidBodyShape.BOX, ) @@ -731,7 +730,7 @@ def spawn_rigid_object_entities( _configure_primitive_rigidbody( prototype, cfg, - body_type, + cfg.to_dexsim_body_type(), is_newton_backend=is_newton_backend, shape_type=RigidBodyShape.SPHERE, ) diff --git a/examples/sim/atomic_skill/open_door.py b/examples/sim/atomic_skill/open_door.py index a5b25f238..5c4d9b32f 100644 --- a/examples/sim/atomic_skill/open_door.py +++ b/examples/sim/atomic_skill/open_door.py @@ -36,6 +36,7 @@ ) from embodichain.lab.sim.cfg import ( ArticulationCfg, + ArticulationRootPropertiesCfg, JointDrivePropertiesCfg, RigidBodyPhysicsCfg, ) @@ -94,6 +95,7 @@ def create_microwave(sim: SimulationManager) -> Articulation: uid="microwave", fpath=get_data_path(MICROWAVE_ASSET), asset_physics_mode="overlay", + root_props=ArticulationRootPropertiesCfg(fixed_base=True), init_pos=MICROWAVE_POSITION, init_rot=MICROWAVE_ORIENTATION, joint_drive_props=JointDrivePropertiesCfg(drive_type="none"), diff --git a/examples/sim/atomic_skill/press.py b/examples/sim/atomic_skill/press.py index abbba47a0..358676df3 100644 --- a/examples/sim/atomic_skill/press.py +++ b/examples/sim/atomic_skill/press.py @@ -35,6 +35,7 @@ ) from embodichain.lab.sim.cfg import ( ArticulationCfg, + ArticulationRootPropertiesCfg, JointDrivePropertiesCfg, RigidObjectCfg, ) @@ -99,6 +100,7 @@ def create_microwave(sim) -> Articulation: uid="microwave", fpath=get_data_path(MICROWAVE_ASSET), asset_physics_mode="overlay", + root_props=ArticulationRootPropertiesCfg(fixed_base=True), init_pos=MICROWAVE_POSITION, init_qpos=(0, 0, 0, 0), init_rot=MICROWAVE_ORIENTATION, diff --git a/examples/sim/atomic_skill/slide.py b/examples/sim/atomic_skill/slide.py index f385c7be3..45280d4bd 100644 --- a/examples/sim/atomic_skill/slide.py +++ b/examples/sim/atomic_skill/slide.py @@ -38,6 +38,7 @@ ) from embodichain.lab.sim.cfg import ( ArticulationCfg, + ArticulationRootPropertiesCfg, JointDrivePropertiesCfg, ) from embodichain.lab.sim.objects import Articulation @@ -90,6 +91,7 @@ def create_drawer( uid="drawer", fpath=get_data_path(DRAWER_ASSET), asset_physics_mode="overlay", + root_props=ArticulationRootPropertiesCfg(fixed_base=True), init_pos=DRAWER_POSITION, init_rot=DRAWER_ORIENTATION, init_qpos=(0.0,), diff --git a/examples/sim/atomic_skill/twist.py b/examples/sim/atomic_skill/twist.py index e3f19930b..2f9eaad1d 100644 --- a/examples/sim/atomic_skill/twist.py +++ b/examples/sim/atomic_skill/twist.py @@ -36,6 +36,7 @@ ) from embodichain.lab.sim.cfg import ( ArticulationCfg, + ArticulationRootPropertiesCfg, JointDrivePropertiesCfg, RigidObjectCfg, ) @@ -92,6 +93,7 @@ def create_microwave(sim) -> Articulation: uid="microwave", fpath=get_data_path(MICROWAVE_ASSET), asset_physics_mode="overlay", + root_props=ArticulationRootPropertiesCfg(fixed_base=True), init_pos=MICROWAVE_POSITION, init_rot=MICROWAVE_ORIENTATION, joint_drive_props=JointDrivePropertiesCfg( diff --git a/scripts/tutorials/sim/import_usd.py b/scripts/tutorials/sim/import_usd.py index 50563f09f..407874147 100644 --- a/scripts/tutorials/sim/import_usd.py +++ b/scripts/tutorials/sim/import_usd.py @@ -16,8 +16,8 @@ """ This script demonstrates how to import USD files into the scene. -Currently, it supports importing USD files as rigid objects or articulations. -Multiple arenas are not supported when importing USD files. +Scene imports retain source-authored entity types and replicate through the +simulation manager's arena configuration. """ from __future__ import annotations @@ -41,6 +41,8 @@ def build_parser() -> argparse.ArgumentParser: _cli_args = build_parser().parse_args() +import numpy as np + from embodichain.lab.sim import SimulationManager, SimulationManagerCfg from embodichain.lab.visualization import visualization_cfg_from_args from embodichain.lab.sim.cfg import ( @@ -48,9 +50,11 @@ def build_parser() -> argparse.ArgumentParser: RenderCfg, RigidBodyMaterialCfg, RigidBodyPhysicsCfg, + UsdImportCfg, + UsdSourceCfg, physics_cfg_for_backend, ) -from embodichain.lab.sim.shapes import CubeCfg, MeshCfg +from embodichain.lab.sim.shapes import CubeCfg from embodichain.lab.sim.objects import ( RigidObject, RigidObjectCfg, @@ -106,13 +110,14 @@ def main(args: argparse.Namespace | None = None) -> None: sugar_box_path = get_data_path("SugarBox/sugar_box_usd/sugar_box.usda") print(f"Loading USD file from: {sugar_box_path}") - sugar_box: RigidObject = sim.add_rigid_object( - cfg=RigidObjectCfg( - uid="sugar_box", - shape=MeshCfg(fpath=sugar_box_path), - body_type="dynamic", - init_pos=[0.2, 0.2, 1.0], - asset_physics_mode="preserve", + scene_pose = np.eye(4, dtype=np.float32) + scene_pose[:3, 3] = (0.2, 0.2, 1.0) + sugar_box = sim.add_usd( + UsdImportCfg( + name="sugar_box", + source=UsdSourceCfg(file_path=sugar_box_path), + namespace="sugar_box", + pose=scene_pose, ) ) diff --git a/scripts/validation/accept_usd_import.py b/scripts/validation/accept_usd_import.py new file mode 100644 index 000000000..dd7b09a75 --- /dev/null +++ b/scripts/validation/accept_usd_import.py @@ -0,0 +1,461 @@ +# ---------------------------------------------------------------------------- +# Copyright (c) 2021-2026 DexForce Technology Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------- + +"""Run isolated, reproducible native acceptance of USD import recipes. + +A JSON manifest contains a list of cases with ``id`` and ``file_path``. Optional +fields are ``category``, ``render``, ``num_envs`` and ``steps``. Results retain +source hashes, runtime versions, per-stage outcomes and logs. Every case runs +in its own process so native resource lifetimes cannot mask another case. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path, PureWindowsPath +import subprocess +import sys +import time +import traceback +from typing import Any + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _accept_case(case: dict[str, Any], output: Path) -> dict[str, Any]: + import importlib.metadata + import numpy as np + import torch + from pxr import Usd, UsdGeom + from embodichain.lab.sim import SimulationManager, SimulationManagerCfg + from embodichain.lab.sim.cfg import ( + DefaultPhysicsCfg, + NewtonPhysicsCfg, + RenderCfg, + DenoisingCfg, + UsdImportCfg, + UsdSourceCfg, + LightCfg, + VolumeDeformableObjectCfg, + SurfaceDeformableObjectCfg, + RigidObjectCfg, + VisualObjectCfg, + ArticulationCfg, + ) + from embodichain.lab.sim.sensors import CameraCfg + from embodichain.lab.sim.spawn.usd import _parse_usd_source + from embodichain.lab.sim.spawn import usd_import + import dexsim + + path = Path(case["file_path"]).expanduser().resolve() + record: dict[str, Any] = { + "id": case["id"], + "category": case.get("category"), + "file_path": str(path), + "source_url": case.get("source_url"), + "sha256": _sha256(path), + "stages": {}, + "python": sys.executable, + "dexsim": importlib.metadata.version("dexsim_engine"), + "dexsim_module": dexsim.__file__, + "acceptance_script_sha256": _sha256(Path(__file__)), + } + record["loader_sources_sha256"] = { + module_name: _sha256(Path(sys.modules[module_name].__file__)) + for module_name in ( + "embodichain.lab.sim.sim_manager", + "embodichain.lab.sim.cfg.usd", + "embodichain.lab.sim.cfg.source", + "embodichain.lab.sim.cfg.asset", + "embodichain.lab.sim.cfg.visual_object", + "embodichain.lab.sim.cfg.deformable", + "embodichain.lab.sim.cfg.physics", + "embodichain.lab.sim.spawn.usd", + "embodichain.lab.sim.spawn.usd_import", + "embodichain.lab.sim.spawn.usd_result", + "embodichain.lab.sim.spawn.scene", + ) + } + try: + record["embodichain_commit"] = subprocess.check_output( + ["git", "rev-parse", "HEAD"], + cwd=Path(__file__).resolve().parents[2], + text=True, + ).strip() + except subprocess.CalledProcessError: + record["embodichain_commit"] = "unknown" + sim = None + imported = camera = asset = None + stage_name = "parse" + started = time.monotonic() + try: + source_cfg = UsdSourceCfg( + file_path=str(path), root_prim_path=case.get("root_prim_path") + ) + raw = _parse_usd_source(source_cfg) + entities = list(raw.iter_entities()) + types: dict[str, int] = {} + for item in entities: + types[type(item).__name__] = types.get(type(item).__name__, 0) + 1 + record["descriptors"] = types + if raw.gaussian_splats: + raise ValueError("Manifest includes excluded 3DGS content.") + if not entities: + raise ValueError("Source contains no importable scene entities.") + record["stages"][stage_name] = "passed" + stage_name = "initialize" + newton = ( + bool(raw.particle_sets or raw.cables) or case.get("physics") == "newton" + ) + device = "cuda:0" if newton else "cpu" + physics = ( + NewtonPhysicsCfg(device=device, use_cuda_graph=False, collision_cfg=None) + if newton + else DefaultPhysicsCfg(device=device) + ) + render = case.get("render", False) + if ( + render + and sys.platform == "linux" + and not any( + os.environ.get(key) + for key in ("DISPLAY", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER") + ) + ): + raise RuntimeError( + "Native offscreen rendering requires a configured display or SDL video driver." + ) + sim = SimulationManager( + SimulationManagerCfg( + headless=True, + device=device, + physics_cfg=physics, + num_envs=case.get("num_envs", 1), + scene_node_capacity=max(512, len(entities) * 24), + render_cfg=RenderCfg( + renderer="hybrid" if render else "no-render", + denoising=DenoisingCfg(window="off", offscreen="off"), + ), + ) + ) + record["physics"] = "newton" if newton else "default" + record["device"] = device + record["num_envs"] = sim.num_envs + record["stages"][stage_name] = "passed" + stage_name = "declare" + entry_point = case.get("entry_point", "scene") + if entry_point == "scene": + imported = sim.add_usd(UsdImportCfg(name=case["id"], source=source_cfg)) + if len(imported.resource_uids) != len(entities): + raise AssertionError( + "An imported entity was lost or a source path is duplicated." + ) + expected_assets = ( + len(raw.mesh_objects) + len(raw.articulations) + len(raw.particle_sets) + ) + record["resources"] = dict(imported.resource_uids) + record["resource_source_paths"] = dict(imported.resource_source_paths) + record["constraints"] = dict(imported.constraint_uids) + else: + config_type, add, collection = { + "volume": ( + VolumeDeformableObjectCfg, + sim.add_deformable_object, + raw.particle_sets, + ), + "surface": ( + SurfaceDeformableObjectCfg, + sim.add_deformable_object, + raw.particle_sets, + ), + "rigid": (RigidObjectCfg, sim.add_rigid_object, raw.mesh_objects), + "visual": (VisualObjectCfg, sim.add_visual_object, raw.mesh_objects), + "articulation": ( + ArticulationCfg, + sim.add_articulation, + raw.articulations, + ), + }[entry_point] + if len(collection) != 1: + raise ValueError("Typed acceptance requires a singleton source.") + selected = collection[0].usd.prim_path + source_cfg.source_prim_path = selected + asset_cfg = config_type(uid="typed_asset", source=source_cfg) + if entry_point == "articulation": + asset_cfg.build_pk_chain = False + asset = add(asset_cfg) + imported = {selected: asset} + expected_assets = 1 + record["resources"] = {selected: asset.uid} + record["constraints"] = {} + record["entry_point"] = entry_point + if len(imported) != expected_assets: + raise AssertionError( + f"Expected {expected_assets} EmbodiChain assets, got {len(imported)}." + ) + record["assets"] = { + key: {"uid": value.uid, "type": type(value).__name__} + for key, value in imported.items() + } + if render: + stage = Usd.Stage.Open(str(path)) + box = ( + UsdGeom.BBoxCache( + Usd.TimeCode.Default(), + [ + UsdGeom.Tokens.default_, + UsdGeom.Tokens.render, + UsdGeom.Tokens.proxy, + UsdGeom.Tokens.guide, + ], + False, + True, + ) + .ComputeWorldBound(stage.GetPseudoRoot()) + .ComputeAlignedRange() + ) + lo, hi = np.array(box.GetMin()), np.array(box.GetMax()) + lo, hi = lo * UsdGeom.GetStageMetersPerUnit( + stage + ), hi * UsdGeom.GetStageMetersPerUnit(stage) + center = (lo + hi) * 0.5 + if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y: + center = np.array((center[0], -center[2], center[1])) + radius = float(np.linalg.norm(hi - lo) * 0.5) + if box.IsEmpty() or not np.isfinite(radius) or radius < 0.01: + center, radius = np.zeros(3), 1.0 + eye = center + np.array((1.25, -1.65, 1.05)) * radius + camera = sim.add_sensor( + CameraCfg( + uid="acceptance_camera", + width=320, + height=240, + near=min(0.005, max(0.0001, radius * 0.001)), + far=max(100.0, radius * 30), + intrinsics=(280.0, 280.0, 160.0, 120.0), + extrinsics=CameraCfg.ExtrinsicsCfg( + eye=tuple(eye), target=tuple(center), up=(0, 0, 1) + ), + ) + ) + sim.add_light( + LightCfg(uid="acceptance_light", light_type="direction", intensity=8.0) + ) + record["camera"] = {"eye": eye.tolist(), "target": center.tolist()} + record["stages"][stage_name] = "passed" + stage_name = "prepare" + sim.prepare() + for key, asset in imported.items(): + if type(asset).__name__ != "VisualObject" or render: + if not asset.is_spawn_bound: + raise AssertionError(f"Facade {key} did not bind.") + if asset.num_instances != sim.num_envs: + raise AssertionError(f"Facade {key} lost replication.") + record["stages"][stage_name] = "passed" + + def check_state() -> None: + for asset in imported.values(): + if not asset.is_spawn_bound: + continue + if type(asset).__name__ in ( + "VolumeDeformableObject", + "SurfaceDeformableObject", + ): + value = asset.data.nodal_pos_w + if value.numel() == 0: + raise AssertionError( + f"Deformable {asset.uid} has no simulation nodes." + ) + elif type(asset).__name__ in ("Articulation", "Robot"): + value = asset.get_qpos() + else: + value = asset.get_local_pose() + if not torch.isfinite(value).all(): + raise AssertionError(f"Nonfinite state in {asset.uid}.") + record.setdefault("state_shapes", {})[asset.uid] = list(value.shape) + + check_state() + if render: + stage_name = "render" + sim.set_ground_plane_visibility(False) + sim.sync_render_state() + for _ in range(8): + camera.update() + pixels = camera.get_data()["color"][0, :, :, :3].cpu().numpy() + from PIL import Image + + Image.fromarray(pixels).save(output / "overview.png") + record["image"] = { + "path": "overview.png", + "std": float(pixels.std()), + "sha256": _sha256(output / "overview.png"), + } + if pixels.std() < 0.5: + raise AssertionError("Offscreen image is uniform.") + record["stages"][stage_name] = "passed" + stage_name = "step" + start_time = sim.simulation_time + for _ in range(case.get("steps", 3)): + sim.update() + check_state() + if sim.simulation_time <= start_time: + raise AssertionError("Physics time did not advance.") + record["simulation_time"] = sim.simulation_time + record["stages"][stage_name] = "passed" + stage_name = "reset" + sim.reset_objects_state() + check_state() + record["stages"][stage_name] = "passed" + record["status"] = "passed" + except Exception as error: + record["status"] = "failed" + record["stages"][stage_name] = "failed" + record["error"] = f"{type(error).__name__}: {error}" + record["traceback"] = traceback.format_exc() + finally: + if sim is not None: + try: + sim.destroy(exit_process=False) + imported = camera = asset = None + SimulationManager.flush_cleanup_queue() + except Exception as error: + record["teardown_error"] = f"{type(error).__name__}: {error}" + record["status"] = "failed" + record["entry_unchanged"] = _sha256(path) == record["sha256"] + record["seconds"] = time.monotonic() - started + return record + + +def _validate_output_files(directory: Path) -> None: + """Reject existing artifact symlinks before any output is changed.""" + for name in ( + "case.json", + "runtime.log", + "result.json", + "results.json", + "overview.png", + ): + if (directory / name).is_symlink(): + raise ValueError( + f"Acceptance output cannot be a symlink: {directory / name}" + ) + + +def _case_directory(output: Path, case_id: object) -> Path: + """Resolve a manifest case strictly inside its authorized output root.""" + if ( + not isinstance(case_id, str) + or not case_id.strip() + or case_id in {".", ".."} + or any(char in case_id for char in ("/", "\\", "\0")) + or PureWindowsPath(case_id).drive + ): + raise ValueError( + f"Acceptance case id must be a safe single path component: {case_id!r}" + ) + directory = output / case_id + if directory.is_symlink() or not directory.resolve().is_relative_to(output): + raise ValueError( + f"Acceptance case directory escapes its output root: {case_id!r}" + ) + _validate_output_files(directory) + return directory + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest", type=Path) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--case", type=Path) + parser.add_argument("--timeout", type=int, default=240) + args = parser.parse_args() + args.output = args.output.expanduser().resolve() + _validate_output_files(args.output) + args.output.mkdir(parents=True, exist_ok=True) + if args.case: + record = _accept_case(json.loads(args.case.read_text()), args.output) + (args.output / "result.json").write_text(json.dumps(record, indent=2)) + print( + json.dumps( + { + "id": record["id"], + "status": record["status"], + "error": record.get("error"), + } + ) + ) + return + cases = json.loads(args.manifest.read_text()) + results = [] + directories = [_case_directory(args.output, case["id"]) for case in cases] + if len(set(directories)) != len(directories): + raise ValueError("Duplicate acceptance case IDs would overwrite case evidence.") + for case, directory in zip(cases, directories): + directory.mkdir(exist_ok=True) + job = directory / "case.json" + job.write_text(json.dumps(case, indent=2)) + (directory / "result.json").unlink(missing_ok=True) + try: + with (directory / "runtime.log").open("w") as log: + process = subprocess.run( + [ + sys.executable, + __file__, + "--case", + str(job), + "--output", + str(directory), + ], + stdout=log, + stderr=subprocess.STDOUT, + timeout=args.timeout, + ) + if (directory / "result.json").exists(): + result = json.loads((directory / "result.json").read_text()) + if process.returncode: + result["status"] = "failed" + result["process_exit"] = process.returncode + else: + result = { + **case, + "status": "failed", + "process_exit": process.returncode, + "error": "Native process exited without a result; see runtime.log.", + } + except subprocess.TimeoutExpired: + result = { + **case, + "status": "failed", + "error": "Native acceptance timed out.", + } + results.append(result) + (args.output / "results.json").write_text(json.dumps(results, indent=2)) + print(case["id"], result["status"], result.get("error", ""), flush=True) + print( + f"{sum(x['status']=='passed' for x in results)}/{len(results)} passed", + flush=True, + ) + if any(item["status"] != "passed" for item in results): + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/scripts/validation/usd_import_acceptance_20261107.json b/scripts/validation/usd_import_acceptance_20261107.json new file mode 100644 index 000000000..14588fbf7 --- /dev/null +++ b/scripts/validation/usd_import_acceptance_20261107.json @@ -0,0 +1,1691 @@ +{ + "schema_version": 1, + "date": "2026-11-07", + "runtime": { + "dexsim": "0.6.0+c3e92584a3dc31479ad07cb1a3551965077109e6", + "python": "3.11", + "gpu": "NVIDIA GeForce RTX 5090" + }, + "scope": "USD import, facade binding, finite simulation state, stepping and reset; selected native offscreen views. This is not SimReady profile certification or a material-fidelity comparison.", + "excluded": [ + "3DGS assets and composites containing 3DGS", + "Derived inputs and three six-type composites without available original packages, deferred at user request" + ], + "primary_summary": { + "input_cases": 54, + "unique_entry_sha256": 54, + "passed": 43, + "compatibility_failures": 11, + "existing_entry_points": 10, + "existing_entry_points_passed": 10 + }, + "primary_cases": [ + { + "id": "catalog-004_sugar_box_xmh-931cdab0", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-004_sugar_box_xmh-931cdab0", + "entry_sha256": "3d02b5b599a348f9b1928898c1620e0b852f8f5c2f3970ada6b54143bedfb6c9", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-006_mustard_bottle-19c63ac2", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-006_mustard_bottle-19c63ac2", + "entry_sha256": "26b7b4e781e3b5d9b6da86d0c27459fd05ee27960f15350214e3c5bbfeb55841", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "VisualObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-S18-17-55f1445e", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-S18-17-55f1445e", + "entry_sha256": "4f6d30329e32d9db657daf6bb4b6a928ef3c7680d3556a35f455cbe04b2293c3", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-bowl-7cc39faa", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-bowl-7cc39faa", + "entry_sha256": "2497510111f01b8b9c78842314e8ef72b0bb99571b564715b676e7c2d4022507", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-cartpole-01890707", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-cartpole-01890707", + "entry_sha256": "b7020b3fb990ec4967ec7241aeb98965becc63586056d8f2492d6e83923a604f", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-cartpole-cf0ebdc7", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-cartpole-cf0ebdc7", + "entry_sha256": "5340c9aad17d919f9e0f6d029081b215ed330a8835563fc2efbb906087775be2", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-cartpole-abebab1b", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-cartpole-abebab1b", + "entry_sha256": "3a2def48a5f72a052a4dce405f40cdf2212fcfd25add1b861809810241418832", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-crx3ia-4a934f88", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-crx3ia-4a934f88", + "entry_sha256": "5e1c0ac4d9587c443d0a8e9a9c73abfcde93fa50e67f79369e89205c756af159", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-hammer-85866117", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-hammer-85866117", + "entry_sha256": "16009997ab028c37b59c163a33b3e6801de401c3c8b7a5f75d0baf6be536d464", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-mug-b3477d58", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-mug-b3477d58", + "entry_sha256": "4377cb915f96fff1b6973556973dc4d9d5a557859f3d4e8c44700d52cc4dc54d", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-pallet-e9b04578", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-pallet-e9b04578", + "entry_sha256": "a8634b983da91f7b830258fc415485bcb276e4b1c910181dcaa5bdf4beca5313", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-volume_deformable_multi-f30a52fe", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-volume_deformable_multi-f30a52fe", + "entry_sha256": "7a2945afc7dead50e39f2f080fdf4927ee45b4a2c75055c9f4fddcf0e9f30406", + "status": "failed", + "backend": "newton", + "replicas": 1, + "descriptor_counts": { + "SoftBodyDesc": 2 + }, + "facade_counts": { + "VolumeDeformableObject": 2 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "failed" + }, + "error": "NotImplementedError: USD deformable /World/DeformableBody_0: Newton cannot preserve PhysX settings ['dynamic_friction', 'elasticity_damping']; choose the default backend or explicitly replace those settings on the parsed descriptor.", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "catalog-volume_deformable_simple-52ec3881", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: catalog-volume_deformable_simple-52ec3881", + "entry_sha256": "7af4f5bdbe52381a780f48987d41d8c4f2c7b89c1e618ac192bea4d5221348dc", + "status": "failed", + "backend": "newton", + "replicas": 1, + "descriptor_counts": { + "SoftBodyDesc": 1 + }, + "facade_counts": { + "VolumeDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "failed" + }, + "error": "NotImplementedError: USD deformable /World/DeformableBody: Newton cannot preserve PhysX settings ['dynamic_friction', 'elasticity_damping']; choose the default backend or explicitly replace those settings on the parsed descriptor.", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-usd_soft_body_duck_v1", + "category": "soft", + "source_reference": "Schema v1 document asset: doc-usd_soft_body_duck_v1", + "entry_sha256": "d69c3e0b4ce3cab467086e69af4848edfb48ebf74f401ebf05f5c5f3b8dbc938", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "SoftBodyDesc": 1 + }, + "facade_counts": { + "VolumeDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-usd_soft_body_isaac_duck_v1", + "category": "soft", + "source_reference": "Schema v1 document asset: doc-usd_soft_body_isaac_duck_v1", + "entry_sha256": "39c2ae2e858405e0ba4e687212ff595e6d46820a0779afe7d40be55db3aef8d2", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "SoftBodyDesc": 1 + }, + "facade_counts": { + "VolumeDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-usd_soft_body_cow_v1", + "category": "soft", + "source_reference": "Schema v1 document asset: doc-usd_soft_body_cow_v1", + "entry_sha256": "e5c462b0bbf098edd96a0f6f0fd34b54296bfaa50011dad3d54971857b7e3a9d", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "SoftBodyDesc": 1 + }, + "facade_counts": { + "VolumeDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-usd_cloth_curtain_v1", + "category": "cloth", + "source_reference": "Schema v1 document asset: doc-usd_cloth_curtain_v1", + "entry_sha256": "042f0379334fc162aa1bc1a1f6352c98a4cd32bf35911c44c91e6016e35dd12f", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "ClothDesc": 1 + }, + "facade_counts": { + "SurfaceDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-usd_cloth_shirt_v1", + "category": "cloth", + "source_reference": "Schema v1 document asset: doc-usd_cloth_shirt_v1", + "entry_sha256": "2cb245f382d3d256d11b1a068adae082025f736ff5022387cd2e3f794b7889ad", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "ClothDesc": 1 + }, + "facade_counts": { + "SurfaceDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-pipette_usd", + "category": "articulation", + "source_reference": "Schema v1 document asset: doc-pipette_usd", + "entry_sha256": "9486b8d29aefb6b635a9f654811488dc6c1361c1a845ec69f7bd696bc9107d29", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-GLB_Reference_Box", + "category": "rigid", + "source_reference": "Schema v1 document asset: doc-GLB_Reference_Box", + "entry_sha256": "c8b1070aaa25ce390fca197ca682b0a40795df5ba732c8c3b2c8fdc7d2822ab3", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-clean_lab", + "category": "scene_mesh", + "source_reference": "Schema v1 document asset: doc-clean_lab", + "entry_sha256": "906bf9c093941e3bca2b6db4dbcc5fa3e1eb3bcae8d3eb6231ea7848e299b207", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 2 + }, + "facade_counts": { + "VisualObject": 1, + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "render": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": true + }, + { + "id": "doc-demo_studio", + "category": "scene_mesh", + "source_reference": "Schema v1 document asset: doc-demo_studio", + "entry_sha256": "6471aeaf3d64c8aaba2430162e0d209a9d576590b697c4a8f354b78a5857c547", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 2 + }, + "facade_counts": { + "VisualObject": 1, + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-industrial_workshop", + "category": "scene_mesh", + "source_reference": "Schema v1 document asset: doc-industrial_workshop", + "entry_sha256": "87dab3b3260c1ad28677f8d4c11877591477a217eb8a8f1ed68d128e59d937bd", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 2 + }, + "facade_counts": { + "VisualObject": 1, + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-wood_lab", + "category": "scene_mesh", + "source_reference": "Schema v1 document asset: doc-wood_lab", + "entry_sha256": "e14446ab360089170ba75ad6046d30008532444f18ee153547801502ac527fe7", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 2 + }, + "facade_counts": { + "VisualObject": 1, + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-robot_workbench_usd", + "category": "scene_mesh", + "source_reference": "Schema v1 document asset: doc-robot_workbench_usd", + "entry_sha256": "31be69f5e42e4e735131ec32b8fa743b9ff72be2df19f64a5dbfd41278408c25", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 24, + "ArticulationDesc": 1 + }, + "facade_counts": { + "RigidObject": 24, + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "render": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": true + }, + { + "id": "doc-hf-food_beverage_beerBottle_a01", + "category": "single", + "source_reference": "https://huggingface.co/datasets/nvidia/simready-assets/resolve/653d91e182011f357cf1644013cc94ddf194d349/food_beverage_beerBottle_a01/simready_usd/sm_food_beverage_beerBottle_a01_01.usd", + "entry_sha256": "430e7a24b91c32b3c268013289fd49676e591d97d959c725a4438b9697f4dffd", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "render": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": true + }, + { + "id": "doc-hf-food_produce_banana_a01", + "category": "single", + "source_reference": "https://huggingface.co/datasets/nvidia/simready-assets/resolve/653d91e182011f357cf1644013cc94ddf194d349/food_produce_banana_a01/simready_usd/sm_food_produce_banana_a01_01.usd", + "entry_sha256": "5f6e7f4f0c3841a62b442002d4b56009849e5faa69e3ec910dec89e7b9a82cad", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "render": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": true + }, + { + "id": "doc-hf-cleaning_sponge_c01", + "category": "single", + "source_reference": "https://huggingface.co/datasets/nvidia/simready-assets/resolve/653d91e182011f357cf1644013cc94ddf194d349/cleaning_sponge_c01/simready_usd/sm_cleaning_sponge_c01_01.usd", + "entry_sha256": "df5595bc0a88790f2a351d6cf28e0f125a6cd5a24ab29a03b347b337855f6590", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "render": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": true + }, + { + "id": "doc-hf-Robotiq_2F_140", + "category": "articulation", + "source_reference": "https://huggingface.co/datasets/Robotiq-Official/simready-assets/resolve/c7fa7615a353ebac03990208cbc2aa57426f4c48/Robotiq_2F_140/simready_usd/Robotiq_2F_140.usda", + "entry_sha256": "202d17a0ea8c842cbdcbe6cda2d3dced765f2bb7f963f589bc2da80af33519d6", + "status": "failed", + "descriptor_counts": {}, + "facade_counts": {}, + "stages": { + "parse": "failed" + }, + "error": "ValueError: Articulation /Robotiq_2F_140/Robotiq_2F_140 has duplicate joint name 'FixedJoint' at /Robotiq_2F_140/Robotiq_2F_140/left_outer_finger/FixedJoint and /Robotiq_2F_140/Robotiq_2F_140/right_outer_finger/FixedJoint.", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-hf-g2_omnipicker", + "category": "articulation", + "source_reference": "https://huggingface.co/datasets/agibot-assets/simready-assets/resolve/b0628c2800bb1d64559489d6b2b8643b0d502fcc/g2_omnipicker/simready_usd/g2_omnipicker.usda", + "entry_sha256": "fe2da149412ca73dc740b5ca13c495c3c3b9e43e9d7e26b41dba8155e1b90480", + "status": "failed", + "descriptor_counts": {}, + "facade_counts": {}, + "stages": { + "parse": "failed" + }, + "error": "ValueError: Mimic joint /g2_omnipicker/Physics/idx41_gripper_l_outer_joint1 has invalid axis 'angular'.", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-hf-g2_swiftpicker", + "category": "articulation", + "source_reference": "https://huggingface.co/datasets/agibot-assets/simready-assets/resolve/b0628c2800bb1d64559489d6b2b8643b0d502fcc/g2_swiftpicker/simready_usd/g2_swiftpicker.usda", + "entry_sha256": "4d3a9ef0554b19ede941e6c2e0b760c1644f86b9d1d5932e04caec8fb04d694f", + "status": "failed", + "descriptor_counts": {}, + "facade_counts": {}, + "stages": { + "parse": "failed" + }, + "error": "ValueError: Mimic joint /g2_swiftpicker/Physics/idx32_gripper_l_outer_joint1 has invalid axis 'angular'.", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "doc-hf-franka_hand", + "category": "articulation", + "source_reference": "https://huggingface.co/datasets/frankarobotics/simready-assets/resolve/89b84c2e10b49f2ed5b056e08164ece2cfe0fb94/franka_hand/simready_usd/franka_hand.usda", + "entry_sha256": "d7654a0ef9a8c1dede4007b216ce8d48f531ca9cb593e43a0e753e3f1d3e779f", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-UnitreeH1_2Locomotion-usda", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: UnitreeH1_2Locomotion", + "entry_sha256": "b0b1c29be546bc30e6a67f4733b4244735daa351ccac689767d5a0d359c25491", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-UnitreeGo2Locomotion-usda", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: UnitreeGo2Locomotion", + "entry_sha256": "a2e8e15cd1d7a79a38e4b3897f3736fc95d3c2d91ca5fec7895404cc5052f4a5", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-RubiksCube-usdc", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: RubiksCube", + "entry_sha256": "94ed00151c9401ae1fbd1337a13e36e49c3cd2a3fa996e693355d657be34f6ee", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-UnitreeH1Usd-usda", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: UnitreeH1Usd", + "entry_sha256": "094e30cb012f63fe20d97613eab3825c77a49001fa2fe6158d9d63f2cd50227c", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-UnitreeH1Usd-usd", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: UnitreeH1Usd", + "entry_sha256": "65e7f372b0a60d1d794b37765970ca622796d3891fa9933364120b7573bdd935", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-DrawerUSD-usdc", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: DrawerUSD", + "entry_sha256": "695d4bee9b2f4cb47d81fc1d3f1122069b99dc450d23854ad645564d98c4ddae", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-SugarBox-usda", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: SugarBox", + "entry_sha256": "31d0acd23494d7f64d5c4f09250e0baed8155a34484a1f5c84520d5c9cc1a0a8", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-ANYmalCLocomotion-usda", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: ANYmalCLocomotion", + "entry_sha256": "afd0b2de8a3c57c04efeb39977e54ac89d2f4e3674215222f591c0ed4cf7403b", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-UnitreeG1Locomotion-usda", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: UnitreeG1Locomotion", + "entry_sha256": "f25703374def6a56310c8b26691fae55f9a9dddb4bc513bee3eb4c2ecdeeea8b", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "existing-UnitreeGo1Locomotion-usda", + "category": "embodichain-existing", + "source_reference": "EmbodiChain data registry: UnitreeGo1Locomotion", + "entry_sha256": "e02ea2e678e442c5b77b182b35cc421c5c2439778eb2f8aa37852ed34be65936", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-teddy_bear", + "category": "soft", + "source_reference": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.1/Isaac/IsaacLab/Objects/Teddy_Bear/teddy_bear.usd", + "entry_sha256": "f3bcbce2b70a4d43f42152bf68f6cb5883c70ee2310f2aec54cf380c728f2d2a", + "status": "failed", + "descriptor_counts": {}, + "facade_counts": {}, + "stages": { + "parse": "failed" + }, + "error": "ValueError: /Bear/geometry/bear: duplicate tetrahedron", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-tube", + "category": "soft", + "source_reference": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.1/Isaac/Props/DeformableTube/tube.usd", + "entry_sha256": "c834b872fb7af0ee465dbf9c527432ea71ab2a0702a13af00680500480b859d5", + "status": "failed", + "descriptor_counts": {}, + "facade_counts": {}, + "stages": { + "parse": "failed" + }, + "error": "ValueError: /Tube/mesh: non-manifold tetrahedral face", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-cloth", + "category": "cloth", + "source_reference": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/Healthcare/0.7.0/724f82e/Props/Lightwheel/Assets/DeformableCloth/cloth.usd", + "entry_sha256": "8801537d35de5008675efcfc7c3a17b7578b1c1edd69cc1ff7fa0715ad54d490", + "status": "failed", + "descriptor_counts": {}, + "facade_counts": {}, + "stages": { + "parse": "failed" + }, + "error": "NotImplementedError: USD prim /Tablecloth/Cloth_fold07/Visuals/Cloth_fold06 uses unsupported schemas ['PhysxSurfaceDeformableBodyAPI']; deformable import is deferred.", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-surface_deformable_material", + "category": "cloth", + "source_reference": "https://raw.githubusercontent.com/NVIDIA-Omniverse/PhysX/b97365c6ddb32fda8469bc788ec18024862b0368/ovphysx/tests/data/surface_deformable_material.usda", + "entry_sha256": "1ee42ec83d95e97b7c27e9dbe143847767f25c77664ec7ae7e1b0156f90c25ae", + "status": "failed", + "backend": "newton", + "replicas": 1, + "descriptor_counts": { + "ClothDesc": 1 + }, + "facade_counts": { + "SurfaceDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "failed" + }, + "error": "NotImplementedError: USD deformable /World/DeformableBody: Newton cannot preserve PhysX settings ['dynamic_friction', 'elasticity_damping', 'bending_damping']; choose the default backend or explicitly replace those settings on the parsed descriptor.", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-deformables_mixed", + "category": "cloth", + "source_reference": "https://raw.githubusercontent.com/newton-physics/newton/1c0e1383f07835781ddff660ae86938f12c90b3f/newton/tests/assets/deformables_mixed.usda", + "entry_sha256": "dbef29649fd10713081d7541ede760772936d603e56f277f14819c3feaf3c1b8", + "status": "passed", + "backend": "newton", + "replicas": 1, + "descriptor_counts": { + "ClothDesc": 1, + "SoftBodyDesc": 2, + "CableDesc": 2 + }, + "facade_counts": { + "SurfaceDeformableObject": 1, + "VolumeDeformableObject": 2 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-deformables_envs_128", + "category": "soft", + "source_reference": "https://raw.githubusercontent.com/NVIDIA-Omniverse/PhysX/b97365c6ddb32fda8469bc788ec18024862b0368/ovphysx/tests/benchmarks/data/deformables_envs_128.usda", + "entry_sha256": "93af98e1f6f99856574cc7e0d5fc3fa123c9f627651d062830fdb62abeaba295", + "status": "failed", + "backend": "newton", + "replicas": 1, + "descriptor_counts": { + "SoftBodyDesc": 128, + "ClothDesc": 128 + }, + "facade_counts": { + "VolumeDeformableObject": 128, + "SurfaceDeformableObject": 128 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "failed" + }, + "error": "NotImplementedError: USD deformable /World/envs/env_0/Volume: Newton cannot preserve PhysX settings ['dynamic_friction', 'elasticity_damping']; choose the default backend or explicitly replace those settings on the parsed descriptor.", + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-default_environment", + "category": "scene_mesh", + "source_reference": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Environments/Grid/default_environment.usd", + "entry_sha256": "086584c39cb37fe460f20e6e1de64f3dcdd4115b28acbf60250bc8665d0d4147", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 2 + }, + "facade_counts": { + "RigidObject": 1, + "VisualObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "render": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": true + }, + { + "id": "official-jetracer_track_solid", + "category": "scene_mesh", + "source_reference": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Environments/Jetracer/jetracer_track_solid.usd", + "entry_sha256": "f2e85c9a0e3e505c048ceb9ef4bc23142b8cfb4077f29813b7bb0c35f936904c", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 4 + }, + "facade_counts": { + "VisualObject": 4 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "render": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": true + }, + { + "id": "official-Female_T_Shirt", + "category": "cloth", + "source_reference": "https://raw.githubusercontent.com/newton-physics/newton-assets/0deda9b1a68d1c202a6115a78ce0ff61ac861e00/style3d/garments/Female_T_Shirt.usd", + "entry_sha256": "301d2e85049be96b2e84a55a094a6da9d4a7c2ef31ad6fc0372bbf9d0673b82e", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "VisualObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-Women_Skirt", + "category": "cloth", + "source_reference": "https://raw.githubusercontent.com/newton-physics/newton-assets/0deda9b1a68d1c202a6115a78ce0ff61ac861e00/style3d/garments/Women_Skirt.usd", + "entry_sha256": "c3ba8dcf96e3f75f7d8f89a2227ce0a267f30f33e096749e078a1e5f371adeec", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "VisualObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-Women_Sweatshirt", + "category": "cloth", + "source_reference": "https://raw.githubusercontent.com/newton-physics/newton-assets/0deda9b1a68d1c202a6115a78ce0ff61ac861e00/style3d/garments/Women_Sweatshirt.usd", + "entry_sha256": "c0fbcbf8f5db0b58ce50830a41d76df9f04796c4edb545e18174f40b2ad32174", + "status": "passed", + "backend": "default", + "replicas": 1, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "VisualObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "official-model", + "category": "single", + "source_reference": "https://raw.githubusercontent.com/newton-physics/newton-assets/0deda9b1a68d1c202a6115a78ce0ff61ac861e00/manipulation_objects/rubber_duck/model.usda", + "entry_sha256": "13a6c07c43926833e574bb695fac51c7f5727c5a1214cfb041e79bccffbff4c0", + "status": "failed", + "descriptor_counts": {}, + "facade_counts": {}, + "stages": { + "parse": "failed" + }, + "error": "TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'", + "source_entry_unchanged": true, + "offscreen_image": false + } + ], + "typed_entry_points": [ + { + "id": "typed-articulation", + "category": "document-catalog", + "source_reference": "Schema v1 document asset: typed-articulation", + "entry_sha256": "b7020b3fb990ec4967ec7241aeb98965becc63586056d8f2492d6e83923a604f", + "status": "passed", + "backend": "default", + "replicas": 2, + "descriptor_counts": { + "ArticulationDesc": 1 + }, + "facade_counts": { + "Articulation": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "typed-volume", + "category": "soft", + "source_reference": "Schema v1 document asset: typed-volume", + "entry_sha256": "e5c462b0bbf098edd96a0f6f0fd34b54296bfaa50011dad3d54971857b7e3a9d", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "SoftBodyDesc": 1 + }, + "facade_counts": { + "VolumeDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "typed-surface", + "category": "cloth", + "source_reference": "Schema v1 document asset: typed-surface", + "entry_sha256": "042f0379334fc162aa1bc1a1f6352c98a4cd32bf35911c44c91e6016e35dd12f", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "ClothDesc": 1 + }, + "facade_counts": { + "SurfaceDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "typed-rigid", + "category": "rigid", + "source_reference": "Schema v1 document asset: typed-rigid", + "entry_sha256": "c8b1070aaa25ce390fca197ca682b0a40795df5ba732c8c3b2c8fdc7d2822ab3", + "status": "passed", + "backend": "default", + "replicas": 2, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "RigidObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false + }, + { + "id": "typed-visual", + "category": "rigid", + "source_reference": "Schema v1 document asset: typed-visual", + "entry_sha256": "c8b1070aaa25ce390fca197ca682b0a40795df5ba732c8c3b2c8fdc7d2822ab3", + "status": "passed", + "backend": "default", + "replicas": 2, + "descriptor_counts": { + "MeshObjectDesc": 1 + }, + "facade_counts": { + "VisualObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "render": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": true + } + ], + "nonempty_particle_state_verification": [ + { + "id": "doc-usd_soft_body_duck_v1", + "category": "soft", + "source_reference": "Schema v1 document asset: doc-usd_soft_body_duck_v1", + "entry_sha256": "d69c3e0b4ce3cab467086e69af4848edfb48ebf74f401ebf05f5c5f3b8dbc938", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "SoftBodyDesc": 1 + }, + "facade_counts": { + "VolumeDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false, + "state_shapes": { + "Duck": [ + 2, + 2734, + 3 + ] + } + }, + { + "id": "doc-usd_soft_body_isaac_duck_v1", + "category": "soft", + "source_reference": "Schema v1 document asset: doc-usd_soft_body_isaac_duck_v1", + "entry_sha256": "39c2ae2e858405e0ba4e687212ff595e6d46820a0779afe7d40be55db3aef8d2", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "SoftBodyDesc": 1 + }, + "facade_counts": { + "VolumeDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false, + "state_shapes": { + "Duck": [ + 2, + 2734, + 3 + ] + } + }, + { + "id": "doc-usd_soft_body_cow_v1", + "category": "soft", + "source_reference": "Schema v1 document asset: doc-usd_soft_body_cow_v1", + "entry_sha256": "e5c462b0bbf098edd96a0f6f0fd34b54296bfaa50011dad3d54971857b7e3a9d", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "SoftBodyDesc": 1 + }, + "facade_counts": { + "VolumeDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false, + "state_shapes": { + "Cow": [ + 2, + 917, + 3 + ] + } + }, + { + "id": "doc-usd_cloth_curtain_v1", + "category": "cloth", + "source_reference": "Schema v1 document asset: doc-usd_cloth_curtain_v1", + "entry_sha256": "042f0379334fc162aa1bc1a1f6352c98a4cd32bf35911c44c91e6016e35dd12f", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "ClothDesc": 1 + }, + "facade_counts": { + "SurfaceDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false, + "state_shapes": { + "Cloth": [ + 2, + 2500, + 3 + ] + } + }, + { + "id": "doc-usd_cloth_shirt_v1", + "category": "cloth", + "source_reference": "Schema v1 document asset: doc-usd_cloth_shirt_v1", + "entry_sha256": "2cb245f382d3d256d11b1a068adae082025f736ff5022387cd2e3f794b7889ad", + "status": "passed", + "backend": "newton", + "replicas": 2, + "descriptor_counts": { + "ClothDesc": 1 + }, + "facade_counts": { + "SurfaceDeformableObject": 1 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false, + "state_shapes": { + "Cloth": [ + 2, + 6436, + 3 + ] + } + }, + { + "id": "official-deformables_mixed", + "category": "cloth", + "source_reference": "https://raw.githubusercontent.com/newton-physics/newton/1c0e1383f07835781ddff660ae86938f12c90b3f/newton/tests/assets/deformables_mixed.usda", + "entry_sha256": "dbef29649fd10713081d7541ede760772936d603e56f277f14819c3feaf3c1b8", + "status": "passed", + "backend": "newton", + "replicas": 1, + "descriptor_counts": { + "ClothDesc": 1, + "SoftBodyDesc": 2, + "CableDesc": 2 + }, + "facade_counts": { + "SurfaceDeformableObject": 1, + "VolumeDeformableObject": 2 + }, + "stages": { + "parse": "passed", + "initialize": "passed", + "declare": "passed", + "prepare": "passed", + "step": "passed", + "reset": "passed" + }, + "source_entry_unchanged": true, + "offscreen_image": false, + "state_shapes": { + "Cloth": [ + 1, + 4, + 3 + ], + "SoftA": [ + 1, + 4, + 3 + ], + "SoftB": [ + 1, + 4, + 3 + ] + } + } + ], + "checks": { + "focused_behavioral_tests": { + "passed": 344 + }, + "gen_sim_usd_tests": { + "passed": 11 + }, + "agent_context_tests": { + "passed": 42 + }, + "api_checker_tests": { + "passed": 11 + }, + "broad_configuration_tests": { + "passed": 179, + "failed": 1, + "remaining_failure": "test_backend_property_groups_track_dexsim_spawn_descriptors: main schema does not expose all DexSim 0.6 collision fields; tracked by the shared 0.6 migration." + }, + "api_documentation": { + "documented": 4335, + "exports": 4335 + }, + "sphinx_dummy": { + "status": "passed", + "project_warnings": 852 + }, + "formatting": "black==26.10.1", + "scalar_particle_flags": { + "passed": 2 + } + }, + "source_notes": [ + "Original garment inputs without authored cloth physics remain visual assets; they are not counted as physical cloth acceptance.", + "The compatibility failures retain the current parser/backend errors without modifying source assets." + ], + "implementation_reference_commit": "a80e8861b5136b56e95bb7361af1622207b1cab9", + "validation_provenance": "Primary results were collected from the implementation worktree. The nonempty-particle rerun records commit and module hashes in the full evidence bundle." +} diff --git a/tests/gen_sim/scene_engine/test_scene_core_and_export.py b/tests/gen_sim/scene_engine/test_scene_core_and_export.py index f3279abe7..767cdf7fc 100644 --- a/tests/gen_sim/scene_engine/test_scene_core_and_export.py +++ b/tests/gen_sim/scene_engine/test_scene_core_and_export.py @@ -696,8 +696,8 @@ class _DirectUsdSim: def __init__(self) -> None: self.calls: list[dict[str, str]] = [] - def add_usd(self, **kwargs: str) -> dict[str, object]: - self.calls.append(kwargs) + def add_usd(self, cfg) -> dict[str, object]: + self.calls.append({"name": cfg.name, "file_path": cfg.source.file_path}) return {"/World/Scene/Entities/drawer": drawer} def prepare(self) -> None: diff --git a/tests/gen_sim/scene_engine/test_scene_usd_integration.py b/tests/gen_sim/scene_engine/test_scene_usd_integration.py index 95e604c3c..9b1977808 100644 --- a/tests/gen_sim/scene_engine/test_scene_usd_integration.py +++ b/tests/gen_sim/scene_engine/test_scene_usd_integration.py @@ -115,7 +115,13 @@ def test_exported_usd_texture_matches_native_gltf( texture_files = [] reference = exported = camera = item = None try: - imported = sim.add_usd("whole_scene", str(usd_path)) + from embodichain.lab.sim.cfg import UsdImportCfg + + imported = sim.add_usd( + UsdImportCfg( + name="whole_scene", source=UsdSourceCfg(file_path=str(usd_path)) + ) + ) reference = sim.add_visual_object( VisualObjectCfg( uid="gltf_reference", @@ -181,7 +187,7 @@ def test_exported_usd_texture_matches_native_gltf( assert np.abs(actual - expected)[foreground].mean() < 4.0 finally: sim.destroy(exit_process=False) - imported.clear() + imported = None reference = exported = camera = item = None SimulationManager.flush_cleanup_queue() assert all(not path.exists() for path in texture_files) diff --git a/tests/gym/envs/test_usd_actor_roles.py b/tests/gym/envs/test_usd_actor_roles.py new file mode 100644 index 000000000..b1e718497 --- /dev/null +++ b/tests/gym/envs/test_usd_actor_roles.py @@ -0,0 +1,106 @@ +# ---------------------------------------------------------------------------- +# Copyright (c) 2021-2026 DexForce Technology Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------- + +"""Gym classifies authored USD actors after source resolution.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from embodichain.lab.gym.envs.embodied_env import EmbodiedEnv +from embodichain.lab.sim.cfg import RigidObjectCfg, UsdSourceCfg + +pytestmark = pytest.mark.no_sim + + +@pytest.mark.parametrize( + "role,resolved_type,valid", + [ + ("interactive", "dynamic", True), + ("interactive", "kinematic", False), + ("background", "kinematic", True), + ("background", "dynamic", False), + ], +) +def test_role_uses_resolved_usd_actor(role, resolved_type, valid): + cfg = RigidObjectCfg(uid="usd", source=UsdSourceCfg(file_path="scene.usda")) + assert cfg.body_type is None + registered = [] + + def declare(*, cfg, validate_resolved): + cfg.body_type = resolved_type + validate_resolved(cfg) + registered.append(cfg) + + env = SimpleNamespace( + cfg=SimpleNamespace( + background=[cfg], + rigid_object=[cfg], + articulation=[], + visual_object=[], + rigid_object_group=[], + ), + sim=SimpleNamespace(add_rigid_object=declare), + ) + if role == "interactive": + setup = EmbodiedEnv._setup_interactive_objects + else: + setup = EmbodiedEnv._setup_background + if valid: + setup(env) + assert registered == [cfg] + else: + with pytest.raises(RuntimeError, match="rigid object"): + setup(env) + assert registered == [] + + +def test_resolved_role_failure_does_not_declare_a_rigid_object(monkeypatch): + import torch + from embodichain.lab.sim.sim_manager import SimulationManager + from embodichain.lab.sim.spawn.scene import SpawnScene + + cfg = RigidObjectCfg(uid="usd", source=UsdSourceCfg(file_path="scene.usda")) + sim = object.__new__(SimulationManager) + sim.device = torch.device("cpu") + sim.physics = SimpleNamespace(name="default") + sim._rigid_objects = {} + scene = object.__new__(SpawnScene) + scene.builder = SimpleNamespace(is_finalized=False, result=None) + scene.declare = Mock() + sim._spawn_scene = scene + sim.notify_visualization_topology_changed = Mock() + + def resolve(cfg, **kwargs): + cfg.body_type = "kinematic" + return object(), {} + + resolver = Mock(side_effect=resolve) + monkeypatch.setattr("embodichain.lab.sim.sim_manager.rigid_desc_from_usd", resolver) + + def require_dynamic(resolved): + if resolved.body_type != "dynamic": + raise ValueError("expected dynamic actor") + + with pytest.raises(ValueError, match="dynamic"): + sim.add_rigid_object(cfg, validate_resolved=require_dynamic) + assert sim._rigid_objects == {} + scene.declare.assert_not_called() + sim.notify_visualization_topology_changed.assert_not_called() + resolver.assert_called_once() diff --git a/tests/scripts/validation/test_accept_usd_import.py b/tests/scripts/validation/test_accept_usd_import.py new file mode 100644 index 000000000..d895aa752 --- /dev/null +++ b/tests/scripts/validation/test_accept_usd_import.py @@ -0,0 +1,173 @@ +# ---------------------------------------------------------------------------- +# Copyright (c) 2021-2026 DexForce Technology Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------- + +"""Regression coverage for isolated USD acceptance result handling.""" + +from __future__ import annotations + +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from scripts.validation import accept_usd_import as acceptance + + +@pytest.mark.parametrize("writes_result", [False, True]) +def test_rerun_requires_a_result_from_the_current_child( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, writes_result: bool +) -> None: + output = tmp_path / "output" + case_dir = output / "example" + case_dir.mkdir(parents=True) + result_path = case_dir / "result.json" + result_path.write_text( + json.dumps({"id": "example", "status": "passed", "previous_run": True}) + ) + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps([{"id": "example", "file_path": "source.usda"}])) + monkeypatch.setattr( + acceptance.sys, + "argv", + ["accept_usd_import", "--manifest", str(manifest), "--output", str(output)], + ) + + def run_child(*args, **kwargs): + if writes_result: + result_path.write_text(json.dumps({"id": "example", "status": "passed"})) + return SimpleNamespace(returncode=0) + + monkeypatch.setattr(acceptance.subprocess, "run", run_child) + if writes_result: + acceptance.main() + else: + with pytest.raises(SystemExit, match="1"): + acceptance.main() + result = json.loads((output / "results.json").read_text())[0] + assert "previous_run" not in result + if writes_result: + assert result["status"] == "passed" + else: + assert result["status"] == "failed" + assert "without a result" in result["error"] + + +@pytest.mark.parametrize( + "case_id", ["../outside", "..\\outside", "/outside", "C:outside", "..", "", None] +) +def test_manifest_rejects_unsafe_case_ids_before_writing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case_id: object +) -> None: + from unittest.mock import Mock + + output = tmp_path / "output" + outside = tmp_path / "outside" + outside.mkdir() + sentinel = outside / "result.json" + sentinel.write_text("keep") + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps([{"id": case_id, "file_path": "source.usda"}])) + monkeypatch.setattr( + acceptance.sys, + "argv", + ["accept_usd_import", "--manifest", str(manifest), "--output", str(output)], + ) + child = Mock() + monkeypatch.setattr(acceptance.subprocess, "run", child) + with pytest.raises(ValueError, match="single path component"): + acceptance.main() + child.assert_not_called() + assert sentinel.read_text() == "keep" + assert not (outside / "case.json").exists() + + +@pytest.mark.parametrize( + "target", + [ + "directory", + "case.json", + "runtime.log", + "result.json", + "overview.png", + "results.json", + ], +) +def test_acceptance_rejects_output_symlinks_without_touching_external_files( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, target: str +) -> None: + from unittest.mock import Mock + + output = tmp_path / "output" + case_dir = output / "example" + outside = tmp_path / "outside" + outside.mkdir() + external = outside / "result.json" + external.write_text("keep") + if target == "directory": + output.mkdir() + case_dir.symlink_to(outside, target_is_directory=True) + else: + case_dir.mkdir(parents=True) + destination = output / target if target == "results.json" else case_dir / target + destination.symlink_to(external) + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps([{"id": "example", "file_path": "source.usda"}])) + monkeypatch.setattr( + acceptance.sys, + "argv", + ["accept_usd_import", "--manifest", str(manifest), "--output", str(output)], + ) + child = Mock() + monkeypatch.setattr(acceptance.subprocess, "run", child) + with pytest.raises(ValueError, match="symlink|escapes"): + acceptance.main() + child.assert_not_called() + assert external.read_text() == "keep" + assert not (outside / "case.json").exists() + + +def test_duplicate_manifest_ids_are_rejected_before_any_child_or_case_write( + tmp_path, monkeypatch +): + from unittest.mock import Mock + + output = tmp_path / "output" + case_dir = output / "same" + case_dir.mkdir(parents=True) + sentinel = case_dir / "runtime.log" + sentinel.write_text("keep previous evidence") + manifest = tmp_path / "manifest.json" + manifest.write_text( + json.dumps( + [ + {"id": "same", "file_path": "first.usda"}, + {"id": "same", "file_path": "second.usda"}, + ] + ) + ) + monkeypatch.setattr( + acceptance.sys, + "argv", + ["accept_usd_import", "--manifest", str(manifest), "--output", str(output)], + ) + child = Mock(return_value=SimpleNamespace(returncode=0)) + monkeypatch.setattr(acceptance.subprocess, "run", child) + with pytest.raises(ValueError, match="Duplicate acceptance case"): + acceptance.main() + child.assert_not_called() + assert sentinel.read_text() == "keep previous evidence" + assert not (case_dir / "case.json").exists() diff --git a/tests/sim/objects/test_usd.py b/tests/sim/objects/test_usd.py index 6da0e5825..206b48580 100644 --- a/tests/sim/objects/test_usd.py +++ b/tests/sim/objects/test_usd.py @@ -18,6 +18,8 @@ import math from pathlib import Path +from copy import deepcopy +from types import SimpleNamespace import pytest import torch @@ -314,6 +316,166 @@ def setup_method(self): self.setup_simulation("cuda") +def _write_placed_usd(path: Path, kind: str) -> None: + from pxr import Usd, UsdGeom, UsdPhysics + + stage = Usd.Stage.CreateNew(str(path)) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + root = UsdGeom.Xform.Define(stage, "/Asset") + stage.SetDefaultPrim(root.GetPrim()) + root.AddTranslateOp().Set((2.0, -1.0, 3.0)) + root.AddRotateZOp().Set(35.0) + if kind == "articulation": + UsdPhysics.ArticulationRootAPI.Apply(root.GetPrim()) + bodies = [ + UsdGeom.Xform.Define(stage, "/Asset/base"), + UsdGeom.Xform.Define(stage, "/Asset/tip"), + ] + joint = UsdPhysics.RevoluteJoint.Define(stage, "/Asset/joint") + joint.CreateBody0Rel().SetTargets(["/Asset/base"]) + joint.CreateBody1Rel().SetTargets(["/Asset/tip"]) + joint.CreateAxisAttr("X") + else: + bodies = [root] + for body in bodies: + UsdPhysics.RigidBodyAPI.Apply(body.GetPrim()) + UsdPhysics.MassAPI.Apply(body.GetPrim()).CreateMassAttr(1.0) + cube = UsdGeom.Cube.Define(stage, str(body.GetPath()) + "/mesh") + cube.CreateSizeAttr(0.1) + UsdPhysics.CollisionAPI.Apply(cube.GetPrim()) + stage.GetRootLayer().Save() + + +@pytest.mark.parametrize("kind", ["rigid", "articulation"]) +@pytest.mark.parametrize("pose_mode", ["auto", "offset"]) +def test_singleton_authored_pose_survives_binding_and_reset( + tmp_path: Path, kind: str, pose_mode: str +) -> None: + """Source placement is the native binding and reset baseline.""" + from embodichain.lab.sim.cfg import UsdSourceCfg + + path = tmp_path / "placed.usda" + _write_placed_usd(path, kind) + angle = math.radians(35.0) + expected = torch.tensor( + [ + [math.cos(angle), -math.sin(angle), 0, 2], + [math.sin(angle), math.cos(angle), 0, -1], + [0, 0, 1, 3], + [0, 0, 0, 1], + ], + dtype=torch.float32, + ).unsqueeze(0) + sim = SimulationManager( + SimulationManagerCfg( + headless=True, + device="cpu", + num_envs=1, + ) + ) + asset = None + try: + source = UsdSourceCfg(file_path=str(path)) + config_type = RigidObjectCfg if kind == "rigid" else ArticulationCfg + offset = 1.0 if pose_mode == "offset" else 0.0 + cfg = config_type( + uid="placed", + source=source, + source_pose_mode=pose_mode, + init_pos=(offset, 0, 0), + ) + current = SimpleNamespace( + num_envs=1, + rigid_object=[cfg], + background=[], + sim_cfg=sim.sim_config, + task_program=SimpleNamespace(program_id="test"), + target_control_frequency=10, + ) + selected = deepcopy(current) + expected[:, 0, 3] += offset + if kind == "rigid": + asset = sim.add_rigid_object(cfg) + else: + asset = sim.add_articulation(cfg) + sim.prepare() + assert cfg.init_local_pose is None + if kind == "rigid": + from embodichain.lab.gym.envs._asset_replacement import _check_environment + + _check_environment(current, selected, set()) + torch.testing.assert_close(asset.get_local_pose(to_matrix=True), expected) + moved = expected.clone() + moved[:, 0, 3] += 1 + asset.set_local_pose(moved) + asset.reset() + torch.testing.assert_close(asset.get_local_pose(to_matrix=True), expected) + if kind == "rigid": + asset = sim.replace_rigid_object(cfg) + torch.testing.assert_close(asset.get_local_pose(to_matrix=True), expected) + assert cfg.init_local_pose is None + _check_environment(current, selected, set()) + asset = sim.replace_rigid_object(asset.cfg.copy()) + torch.testing.assert_close(asset.get_local_pose(to_matrix=True), expected) + asset.reset() + torch.testing.assert_close(asset.get_local_pose(to_matrix=True), expected) + finally: + sim.destroy(exit_process=False) + asset = None + SimulationManager.flush_cleanup_queue() + + +@pytest.mark.parametrize("legacy", [False, True]) +def test_scene_import_returned_cfg_keeps_scene_placement_on_replacement( + tmp_path: Path, legacy: bool +) -> None: + import numpy as np + from embodichain.lab.sim.cfg import UsdImportCfg, UsdSourceCfg + + path = tmp_path / "scene.usda" + _write_placed_usd(path, "rigid") + scene_pose = np.eye(4, dtype=np.float32) + scene_pose[0, 3] = 1 + expected = torch.eye(4, dtype=torch.float32).unsqueeze(0) + angle = math.radians(35) + expected[0, :3, :3] = torch.tensor( + [ + [math.cos(angle), -math.sin(angle), 0], + [math.sin(angle), math.cos(angle), 0], + [0, 0, 1], + ] + ) + expected[0, :3, 3] = torch.tensor([3, -1, 3]) + sim = SimulationManager( + SimulationManagerCfg(headless=True, device="cpu", num_envs=1) + ) + imported = asset = None + try: + if legacy: + imported = sim.add_usd("scene", str(path), pose=scene_pose) + else: + imported = sim.add_usd( + UsdImportCfg( + name="scene", + source=UsdSourceCfg(file_path=str(path)), + pose=scene_pose, + ) + ) + asset = imported["/Asset"] + sim.prepare() + torch.testing.assert_close(asset.get_local_pose(to_matrix=True), expected) + for _ in range(2): + asset = sim.replace_rigid_object(asset.cfg.copy()) + torch.testing.assert_close(asset.get_local_pose(to_matrix=True), expected) + asset.reset() + torch.testing.assert_close(asset.get_local_pose(to_matrix=True), expected) + finally: + sim.destroy(exit_process=False) + imported = asset = None + SimulationManager.flush_cleanup_queue() + + if __name__ == "__main__": test = TestUsdCPU() test.setup_method() diff --git a/tests/sim/objects/test_visual_object.py b/tests/sim/objects/test_visual_object.py index 8cdbd9a2e..7bb397b2c 100644 --- a/tests/sim/objects/test_visual_object.py +++ b/tests/sim/objects/test_visual_object.py @@ -300,6 +300,7 @@ def test_add_usd_classifies_visuals_without_promoting_collision_only_objects(tmp manager.notify_visualization_topology_changed = MagicMock() with patch("dexsim.kit.usd.parse_usd", return_value=source): assets = manager.add_usd("scene", str(path)) + assert isinstance(assets, dict) assert isinstance(assets["/World/Visual"], VisualObject) assert isinstance(assets["/World/Physical"], RigidObject) assert manager.get_asset("scene_default_plane") is assets["/World/Visual"] diff --git a/tests/sim/spawn/test_descriptors.py b/tests/sim/spawn/test_descriptors.py index 65118a6ac..d44b4b9de 100644 --- a/tests/sim/spawn/test_descriptors.py +++ b/tests/sim/spawn/test_descriptors.py @@ -87,6 +87,13 @@ pytestmark = pytest.mark.no_sim + +def test_packaged_usd_requires_typed_source_translation() -> None: + cfg = RigidObjectCfg(uid="packaged", shape=MeshCfg(fpath="source.usdz")) + with pytest.raises(NotImplementedError, match="typed scenes"): + rigid_desc_from_cfg(cfg) + + RESTITUTION = 0.25 DEFORMABLE_MESH_PATH = "/assets/deformable.obj" @@ -805,7 +812,7 @@ def test_grouped_rigid_physics_overlays_usd_without_erasing_source( ) scene = SimpleNamespace(materials={}) - def parse_singleton(path, collection, label, *, prim_path=None): + def parse_singleton(path, collection, label, **kwargs): return scene, source monkeypatch.setattr( @@ -850,7 +857,7 @@ def test_rigid_usd_can_recompute_source_inertia( ) monkeypatch.setattr( "embodichain.lab.sim.spawn.usd._parse_singleton", - lambda path, collection, label, *, prim_path=None: ( + lambda path, collection, label, **kwargs: ( SimpleNamespace(materials={}), source, ), @@ -886,7 +893,7 @@ def test_rigid_usd_preserves_asset_physics_by_default( ) monkeypatch.setattr( "embodichain.lab.sim.spawn.usd._parse_singleton", - lambda path, collection, label, *, prim_path=None: ( + lambda path, collection, label, **kwargs: ( SimpleNamespace(materials={}), source, ), @@ -894,8 +901,6 @@ def test_rigid_usd_preserves_asset_physics_by_default( cfg = RigidObjectCfg( uid="cube", shape=MeshCfg(fpath="cube.usd"), - body_type="static", - body_scale=(1.0, 1.0, 1.0), attrs=RigidBodyPhysicsCfg(mass_props=MassPropertiesCfg(mass=1.0)), ) @@ -1410,11 +1415,19 @@ def test_articulation_root_properties_compile_to_common_descriptor() -> None: assert descriptor.enable_self_collision is True -def test_articulation_root_defaults_are_resolved_at_import_boundary() -> None: - descriptor = articulation_desc_from_cfg( - ArticulationCfg(uid="robot", fpath="robot.urdf") - ) - +@pytest.mark.parametrize("cfg_type", [ArticulationCfg, RobotCfg]) +@pytest.mark.parametrize("scale", [None, (2.0, 3.0, 4.0)]) +def test_articulation_root_defaults_are_resolved_at_import_boundary( + cfg_type, scale +) -> None: + cfg = cfg_type(uid="robot") + # Catalog presets can assemble a URDF after nullable source defaults were decoded. + cfg.fpath = "robot.urdf" + cfg.body_scale = scale + descriptor = articulation_desc_from_cfg(cfg) + expected_scale = (1.0, 1.0, 1.0) if scale is None else scale + np.testing.assert_array_equal(descriptor.body_scale, expected_scale) + assert cfg.body_scale == expected_scale assert descriptor.fixed_base is True assert descriptor.urdf_fix_root_link is True assert descriptor.enable_self_collision is False @@ -1446,7 +1459,7 @@ def test_explicit_root_properties_override_usd_in_preserve_mode() -> None: assert descriptor.enable_self_collision is False -def test_default_root_properties_override_usd_values() -> None: +def test_default_root_properties_preserve_usd_values() -> None: source = ArticulationDesc( name="source", fixed_base=False, @@ -1464,8 +1477,8 @@ def test_default_root_properties_override_usd_values() -> None: ): descriptor, _ = articulation_desc_from_usd(cfg) - assert descriptor.fixed_base is True - assert descriptor.enable_self_collision is False + assert descriptor.fixed_base is False + assert descriptor.enable_self_collision is True def test_explicit_none_root_properties_preserve_usd_values() -> None: diff --git a/tests/sim/spawn/test_scene.py b/tests/sim/spawn/test_scene.py index e57846437..5cfadc1e9 100644 --- a/tests/sim/spawn/test_scene.py +++ b/tests/sim/spawn/test_scene.py @@ -50,6 +50,29 @@ def test_material_resolution_rejects_conflicting_explicit_definitions(): assert scene.builder.materials["shared"] is original +def test_no_render_preserves_authored_alpha_recipe_without_native_alpha_write(): + scene = object.__new__(SpawnScene) + scene.builder = SimpleNamespace(materials={}) + scene._usd_texture_files = SimpleNamespace(resolve=lambda materials: materials) + scene._material_resources = SimpleNamespace(renderer="no-render") + original = MaterialDesc( + name="glass", alpha_mode="BLEND", base_color_map="authored.png" + ) + + native = scene._resolve_materials({"glass": original}) + + assert native["glass"].alpha_mode is None + assert native["glass"].base_color_map is None + assert original.alpha_mode == "BLEND" + assert original.base_color_map == "authored.png" + scene.builder.materials.update(native) + assert scene._material_definition("glass") is original + with pytest.raises(ValueError, match="Conflicting visual material"): + scene._resolve_materials( + {"glass": MaterialDesc(name="glass", alpha_mode="MASK")} + ) + + def _make_scene(handles: dict[str, object]) -> SpawnScene: scene = object.__new__(SpawnScene) scene._num_envs = 1 diff --git a/tests/sim/spawn/test_usd_scene_overrides.py b/tests/sim/spawn/test_usd_scene_overrides.py new file mode 100644 index 000000000..6b488add0 --- /dev/null +++ b/tests/sim/spawn/test_usd_scene_overrides.py @@ -0,0 +1,723 @@ +# ---------------------------------------------------------------------------- +# Copyright (c) 2021-2026 DexForce Technology Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------- + +"""Whole-scene USD overrides are validated before native declaration.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock + +import numpy as np +import pytest +import torch +from pxr import Sdf, Usd, UsdGeom, UsdPhysics + +from dexsim.spawn import ( + MeshObjectDesc, + ConstraintDesc, + RigidBodyPhysicsDesc, + UsdSourceDesc, + SceneDesc, + SoftBodyDesc, + ClothDesc, + GeometryDesc, + ArticulationDesc, + LinkDesc, +) +from dexsim.types import ActorType + +from embodichain.lab.sim.sim_manager import SimulationManager +from embodichain.lab.sim.spawn.scene import SpawnScene +from embodichain.lab.sim.cfg import UsdImportCfg, UsdSourceCfg + +pytestmark = pytest.mark.no_sim + + +def _manager(): + manager = object.__new__(SimulationManager) + manager.device = torch.device("cpu") + manager.physics = SimpleNamespace(name="default") + manager.sim_config = SimpleNamespace(render_cfg=SimpleNamespace(renderer="hybrid")) + for name in ( + "_lights", + "_sensors", + "_robots", + "_visual_objects", + "_rigid_objects", + "_rigid_object_groups", + "_deformable_objects", + "_fluid_objects", + "_articulations", + ): + setattr(manager, name, {}) + manager.add_sensor = MagicMock() + scene = object.__new__(SpawnScene) + scene._assets = {} + scene._num_envs = 1 + scene.builder = MagicMock(is_finalized=False, result=None) + scene.builder.add_scene.side_effect = lambda source, **kwargs: list( + source.iter_entities() + ) + scene._resolve_materials = lambda materials: materials + scene.track = MagicMock() + manager._spawn_scene = scene + manager.notify_visualization_topology_changed = MagicMock() + return manager + + +def _source(): + base = MeshObjectDesc( + name="base", + usd=UsdSourceDesc(prim_path="/World/base"), + physics=RigidBodyPhysicsDesc(actor_type=ActorType.KINEMATIC), + ) + base.pose[0, 3] = 2 + child = MeshObjectDesc( + name="child", + usd=UsdSourceDesc(prim_path="/World/child"), + physics=RigidBodyPhysicsDesc(actor_type=ActorType.DYNAMIC), + ) + constraint = ConstraintDesc(name="joint", body0="base", body1="child") + scene = SceneDesc( + mesh_objects=[base, child], + articulations=[], + constraints=[constraint], + materials={}, + rigid_collision_filter_pairs=[("base", "child")], + ) + return scene + + +def test_sparse_override_keeps_actor_and_pose_and_remaps_constraint(monkeypatch): + import dexsim.kit.usd + + source = _source() + monkeypatch.setattr(dexsim.kit.usd, "parse_usd", lambda *args, **kwargs: source) + manager = _manager() + + assets = manager.add_usd( + UsdImportCfg( + name="room", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={ + "/World/base": { + "asset_physics_mode": "overlay", + "attrs": {"mass_props": {"mass": 5}}, + }, + "/World/child": {"uid": "door"}, + }, + ) + ) + + assert set(assets) == {"/World/base", "/World/child"} + assert assets["/World/base"].cfg.body_type == "kinematic" + assert assets["/World/base"].cfg.init_local_pose[0, 3] == 2 + assert source.mesh_objects[0].physics.mass == 5 + assert assets["/World/child"].uid == "door" + assert source.constraints[0].body0 == "base" + assert source.constraints[0].body1 == "door" + assert source.rigid_collision_filter_pairs == [("base", "door")] + manager._spawn_scene.builder.add_scene.assert_called_once() + + +def test_unknown_override_target_is_rejected_before_declaration(monkeypatch): + import dexsim.kit.usd + + source = _source() + monkeypatch.setattr(dexsim.kit.usd, "parse_usd", lambda *args, **kwargs: source) + manager = _manager() + + with pytest.raises(ValueError, match="missing"): + manager.add_usd( + UsdImportCfg( + name="room", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={"/World/missing": {}}, + ) + ) + manager._spawn_scene.builder.add_scene.assert_not_called() + + +def test_dexsim_scene_parser_keeps_standalone_constraint_after_uid_override(tmp_path): + path = tmp_path / "joint.usda" + stage = Usd.Stage.CreateNew(str(path)) + root = UsdGeom.Xform.Define(stage, "/World") + stage.SetDefaultPrim(root.GetPrim()) + for name in ("base", "child"): + body = UsdGeom.Xform.Define(stage, f"/World/{name}") + UsdPhysics.RigidBodyAPI.Apply(body.GetPrim()) + cube = UsdGeom.Cube.Define(stage, f"/World/{name}/mesh") + UsdPhysics.CollisionAPI.Apply(cube.GetPrim()) + joint = UsdPhysics.FixedJoint.Define(stage, "/World/joint") + joint.CreateBody0Rel().SetTargets(["/World/base"]) + joint.CreateBody1Rel().SetTargets(["/World/child"]) + stage.GetRootLayer().Save() + + manager = _manager() + imported = manager.add_usd( + UsdImportCfg( + name="room", + source=UsdSourceCfg(file_path=str(path)), + asset_cfgs={"/World/child": {"uid": "door"}}, + ) + ) + from embodichain.lab.sim import UsdImportResult + + assert isinstance(imported, UsdImportResult) + + scene = manager._spawn_scene.builder.add_scene.call_args.args[0] + assert len(scene.constraints) == 1 + assert scene.constraints[0].body0 == "base" + assert scene.constraints[0].body1 == "door" + assert imported.constraint_uids["/World/joint"] == "joint" + assert imported.resource_uids["/World/child"] == "door" + assert imported.resource_types["/World/joint"] == "constraint" + assert imported.resource_types["/World/child"] == "rigid_object" + + +@pytest.mark.parametrize( + "descriptor_type,facade_name", + [(SoftBodyDesc, "VolumeDeformableObject"), (ClothDesc, "SurfaceDeformableObject")], +) +def test_particle_import_registers_existing_facade_and_preserves_authored_physics( + monkeypatch, descriptor_type, facade_name +): + import dexsim.kit.usd + + points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32) + descriptor = descriptor_type( + name="authored", + mesh=GeometryDesc.mesh( + vertices=points, triangles=np.array([[0, 1, 2]], dtype=np.int32) + ), + positions=points, + usd=UsdSourceDesc(prim_path="/World/Soft"), + ) + descriptor.physics.density = 321.0 + source = SceneDesc(particle_sets=[descriptor]) + monkeypatch.setattr(dexsim.kit.usd, "parse_usd", lambda *args, **kwargs: source) + manager = _manager() + manager.device = torch.device("cuda:0") + manager.physics = SimpleNamespace(name="newton", solver_type="dexuni") + manager.sim_config = SimpleNamespace( + physics_cfg=SimpleNamespace(requires_grad=False) + ) + + result = manager.add_usd( + UsdImportCfg( + name="test", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={"/World/Soft": {"uid": "renamed", "particle_flags": 0}}, + ) + ) + + asset = result["/World/Soft"] + assert type(asset).__name__ == facade_name + assert manager._deformable_objects["renamed"] is asset + assert asset.cfg.source.source_prim_path == "/World/Soft" + assert descriptor.physics.density == 321.0 + assert descriptor.particle_flags == 0 + assert isinstance(descriptor.particle_flags, int) + np.testing.assert_array_equal(descriptor.positions, points) + + +def test_import_recipe_selects_subtree_and_namespaces_runtime_identity(tmp_path): + path = tmp_path / "two_cells.usda" + stage = Usd.Stage.CreateNew(str(path)) + for side in ("Left", "Right"): + body = UsdGeom.Xform.Define(stage, f"/World/{side}/Body") + UsdPhysics.RigidBodyAPI.Apply(body.GetPrim()) + mesh = UsdGeom.Cube.Define(stage, f"/World/{side}/Body/mesh") + UsdPhysics.CollisionAPI.Apply(mesh.GetPrim()) + stage.GetRootLayer().Save() + original = path.read_bytes() + manager = _manager() + + first = manager.add_usd( + UsdImportCfg( + name="left", + source=UsdSourceCfg(file_path=str(path), root_prim_path="/World/Left"), + namespace="a", + ) + ) + second = manager.add_usd( + UsdImportCfg( + name="right", + source=UsdSourceCfg(file_path=str(path), root_prim_path="/World/Right"), + namespace="b", + ) + ) + + assert list(first) == ["/World/Left/Body"] + assert list(second) == ["/World/Right/Body"] + assert first["/World/Left/Body"].uid == "a::Body" + assert second["/World/Right/Body"].uid == "b::Body" + assert path.read_bytes() == original + with pytest.raises(ValueError, match="already exists"): + manager.add_usd( + UsdImportCfg( + name="duplicate", + source=UsdSourceCfg(file_path=str(path), root_prim_path="/World/Left"), + namespace="a", + ) + ) + assert manager._spawn_scene.builder.add_scene.call_count == 2 + + +@pytest.mark.parametrize( + "parent,sensor_uid,renderer,sensor_type,valid", + [ + ("base", "wrist", "hybrid", "Camera", True), + ("missing", "wrist", "hybrid", "Camera", False), + ("base", "Robot", "hybrid", "Camera", False), + ("base", "wrist", "no-render", "Camera", False), + ("base", "wrist", "hybrid", "Unsupported", False), + ("base", "wrist", "hybrid", "ContactSensor", False), + ("base", "wrist", "hybrid", "StereoCamera", False), + ], +) +def test_robot_metadata_preserves_source_identity_and_preflights_sensor_binding( + monkeypatch, parent, sensor_uid, renderer, sensor_type, valid +): + import dexsim.kit.usd + from embodichain.lab.sim.cfg import RobotCfg, ArticulationRootPropertiesCfg + from embodichain.lab.sim.sensors import CameraCfg + + descriptor = ArticulationDesc( + name="Robot", + links=[ + LinkDesc(name="base", parent_name=None, pose=np.eye(4, dtype=np.float32)) + ], + fixed_base=False, + usd=UsdSourceDesc(prim_path="/Robot"), + ) + descriptor.pose[0, 3] = 2 + monkeypatch.setattr( + dexsim.kit.usd, + "parse_usd", + lambda *args, **kwargs: SceneDesc(articulations=[descriptor]), + ) + metadata = RobotCfg( + uid="metadata_uid", + init_pos=(9, 0, 0), + root_props=ArticulationRootPropertiesCfg( + fixed_base=True, + sleep_threshold=0.123, + min_position_iters=16, + min_velocity_iters=4, + ), + build_pk_chain=False, + enable_sensor=True, + sensors=[ + CameraCfg( + uid=sensor_uid, + sensor_type=sensor_type, + extrinsics=CameraCfg.ExtrinsicsCfg(parent=parent), + ) + ], + joint_drive_props=None, + ) + recipe = UsdImportCfg( + name="test", + source=UsdSourceCfg(file_path="scene.usda"), + robot_cfgs={"/Robot": metadata}, + ) + manager = _manager() + + manager.sim_config.render_cfg.renderer = renderer + if valid: + result = manager.add_usd(recipe) + assert result["/Robot"].uid == "Robot" + assert result["/Robot"].cfg.init_local_pose[0, 3] == 2 + assert result["/Robot"].cfg.root_props.fixed_base is False + root_props = result["/Robot"].cfg.root_props + assert ( + root_props.sleep_threshold, + root_props.min_position_iters, + root_props.min_velocity_iters, + ) == (0.123, 16, 4) + assert manager.add_sensor.call_args.args[0].extrinsics.parent == "Robot/base" + assert metadata.uid == "metadata_uid" + assert metadata.sensors[0].extrinsics.parent == "base" + else: + with pytest.raises( + (ValueError, RuntimeError, TypeError), + match="unknown link|already exists|requires a native renderer|Unsupported mounted|StereoCamera requires", + ): + manager.add_usd(recipe) + manager._spawn_scene.builder.add_scene.assert_not_called() + manager.add_sensor.assert_not_called() + assert manager._robots == {} + if renderer == "no-render" or sensor_type != "Camera": + recipe.robot_cfgs["/Robot"].enable_sensor = False + result = manager.add_usd(recipe) + assert manager._robots == {"Robot": result["/Robot"]} + manager.add_sensor.assert_not_called() + + +@pytest.mark.parametrize("typed", [False, True]) +def test_static_collider_overrides_keep_identity_pose_and_relationships( + monkeypatch, typed +): + import dexsim.kit.usd + from dexsim.spawn import CollisionDesc, ConstraintDesc + from embodichain.lab.sim.cfg import RigidObjectCfg + + descriptor = MeshObjectDesc( + name="wall", collisions=[CollisionDesc()], usd=UsdSourceDesc(prim_path="/Wall") + ) + descriptor.body_scale = np.array([2, 3, 4], dtype=np.float32) + descriptor.pose[0, 3] = 2 + constraint = ConstraintDesc(name="anchor", body0="wall", body1=None) + source = SceneDesc(mesh_objects=[descriptor], constraints=[constraint]) + monkeypatch.setattr(dexsim.kit.usd, "parse_usd", lambda *args, **kwargs: source) + override = { + "uid": "renamed", + "init_pos": (1, 0, 0), + "source_pose_mode": "offset", + "body_type": "dynamic", + "body_scale": (1, 1, 1), + } + manager = _manager() + result = manager.add_usd( + UsdImportCfg( + name="room", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={ + "/Wall": (RigidObjectCfg.from_dict(override) if typed else override) + }, + ) + ) + assert descriptor.name == result["/Wall"].uid == "renamed" + assert manager._rigid_objects == {"renamed": result["/Wall"]} + assert result.resource_uids["/Wall"] == "renamed" + assert constraint.body0 == "renamed" + assert descriptor.pose[0, 3] == result["/Wall"].cfg.init_local_pose[0, 3] == 3 + assert descriptor.physics is None + assert result["/Wall"].cfg.body_type == "static" + np.testing.assert_array_equal(result["/Wall"].cfg.body_scale, [2, 3, 4]) + + +@pytest.mark.parametrize("representation", ["sparse", "typed", "serialized"]) +def test_identity_override_preserves_source_actor_and_nonunit_scale( + monkeypatch, representation +): + import dexsim.kit.usd + from embodichain.lab.sim.cfg import RigidObjectCfg + + descriptor = MeshObjectDesc( + name="body", + usd=UsdSourceDesc(prim_path="/Body"), + physics=RigidBodyPhysicsDesc(actor_type=ActorType.KINEMATIC), + body_scale=np.array([2, 3, 4], dtype=np.float32), + ) + monkeypatch.setattr( + dexsim.kit.usd, + "parse_usd", + lambda *args, **kwargs: SceneDesc(mesh_objects=[descriptor]), + ) + override = ( + {"uid": "renamed"} + if representation == "sparse" + else RigidObjectCfg(uid="renamed", body_type=None) + ) + recipe = UsdImportCfg( + name="scene", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={"/Body": override}, + ) + if representation == "serialized": + recipe = UsdImportCfg.from_dict(recipe.to_dict()) + result = _manager().add_usd(recipe) + assert result["/Body"].cfg.body_type == "kinematic" + np.testing.assert_array_equal(result["/Body"].cfg.body_scale, [2, 3, 4]) + assert descriptor.physics.actor_type == ActorType.KINEMATIC + + +@pytest.mark.parametrize("typed", [False, True]) +@pytest.mark.parametrize("explicit_matrix", [False, True]) +def test_scene_override_rotation_matches_intrinsic_xyz( + monkeypatch, typed, explicit_matrix +): + import dexsim.kit.usd + from scipy.spatial.transform import Rotation + from embodichain.lab.sim.cfg import RigidObjectCfg + + descriptor = MeshObjectDesc( + name="body", + usd=UsdSourceDesc(prim_path="/Body"), + physics=RigidBodyPhysicsDesc(actor_type=ActorType.DYNAMIC), + ) + monkeypatch.setattr( + dexsim.kit.usd, + "parse_usd", + lambda *args, **kwargs: SceneDesc(mesh_objects=[descriptor]), + ) + fields = {"init_rot": (30, 40, 50)} + expected = np.eye(4) + expected[:3, :3] = Rotation.from_euler( + "XYZ", (30, 40, 50), degrees=True + ).as_matrix() + if explicit_matrix: + expected[:3, :3] = Rotation.from_euler("Z", 17, degrees=True).as_matrix() + expected[:3, 3] = (1, 2, 3) + fields["init_local_pose"] = expected.tolist() + override = RigidObjectCfg(**fields) if typed else fields + result = _manager().add_usd( + UsdImportCfg( + name="scene", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={"/Body": override}, + ) + ) + np.testing.assert_allclose(result["/Body"].cfg.init_local_pose, expected, atol=1e-6) + + +def test_rigid_uid_override_remaps_newton_body_references_only(monkeypatch): + import dexsim.kit.usd + from dexsim.spawn import NewtonSceneDesc, NewtonEqualityDesc + from collections import Counter + from dexsim.spawn.adapters.newton_mujoco_scene import _validate_mujoco_references + + source = SceneDesc( + mesh_objects=[ + MeshObjectDesc( + name=name, + usd=UsdSourceDesc(prim_path="/" + name), + physics=RigidBodyPhysicsDesc(actor_type=ActorType.DYNAMIC), + ) + for name in ["A", "B"] + ], + newton=NewtonSceneDesc( + body_order=["A", "B", "link"], + equalities=[ + NewtonEqualityDesc( + name="weld", equality_type=1, object1="A", object2="B", data=() + ), + NewtonEqualityDesc( + name="joint", equality_type=2, object1="A", object2="B", data=() + ), + ], + ), + ) + monkeypatch.setattr(dexsim.kit.usd, "parse_usd", lambda *args, **kwargs: source) + result = _manager().add_usd( + UsdImportCfg( + name="scene", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={"/A": {"uid": "new_A"}}, + ) + ) + assert result["/A"].uid == "new_A" + assert source.newton.body_order == ["new_A", "B", "link"] + assert ( + source.newton.equalities[0].object1, + source.newton.equalities[0].object2, + ) == ("new_A", "B") + assert ( + source.newton.equalities[1].object1, + source.newton.equalities[1].object2, + ) == ("A", "B") + _validate_mujoco_references( + source.newton, + Counter({"new_A": 1, "B": 1}), + Counter({"A": 1, "B": 1}), + Counter(), + ) + + +def test_visual_rename_does_not_rewrite_newton_articulation_body_names(monkeypatch): + import dexsim.kit.usd + from dexsim.spawn import NewtonSceneDesc, NewtonEqualityDesc + + visual = MeshObjectDesc(name="A", usd=UsdSourceDesc(prim_path="/Visual")) + robot = ArticulationDesc( + name="Robot", + links=[ + LinkDesc( + name="A", + parent_name=None, + pose=np.eye(4, dtype=np.float32), + rigid_body=RigidBodyPhysicsDesc(actor_type=ActorType.DYNAMIC), + ) + ], + usd=UsdSourceDesc(prim_path="/Robot"), + ) + source = SceneDesc( + mesh_objects=[visual], + articulations=[robot], + newton=NewtonSceneDesc( + body_order=["A"], + equalities=[ + NewtonEqualityDesc( + name="weld", equality_type=1, object1="A", object2=None, data=() + ) + ], + ), + ) + monkeypatch.setattr(dexsim.kit.usd, "parse_usd", lambda *args, **kwargs: source) + result = _manager().add_usd( + UsdImportCfg( + name="scene", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={"/Visual": {"uid": "new_visual"}}, + ) + ) + assert result["/Visual"].uid == "new_visual" + assert robot.links[0].name == "A" + assert source.newton.body_order == ["A"] + assert source.newton.equalities[0].object1 == "A" + + +@pytest.mark.parametrize( + "override,preserve_source", + [ + ({}, True), + ({"init_pos": (0, 0, 0)}, False), + ({"init_rot": (0, 0, 0)}, False), + ({"init_local_pose": np.eye(4)}, False), + ({"source_pose_mode": "config"}, False), + ({"source_pose_mode": "preserve", "init_pos": (0, 0, 0)}, True), + ], + ids=[ + "omitted", + "zero-position", + "zero-rotation", + "identity-matrix", + "config-mode", + "preserve-mode", + ], +) +def test_sparse_override_preserves_explicit_zero_placement( + monkeypatch, override, preserve_source +): + import dexsim.kit.usd + from scipy.spatial.transform import Rotation + + authored = np.eye(4, dtype=np.float32) + authored[:3, :3] = Rotation.from_euler("Z", 17, degrees=True).as_matrix() + authored[0, 3] = 2 + descriptor = MeshObjectDesc( + name="body", + pose=authored.copy(), + usd=UsdSourceDesc(prim_path="/Body"), + physics=RigidBodyPhysicsDesc(actor_type=ActorType.DYNAMIC), + ) + monkeypatch.setattr( + dexsim.kit.usd, + "parse_usd", + lambda *args, **kwargs: SceneDesc(mesh_objects=[descriptor]), + ) + result = _manager().add_usd( + UsdImportCfg( + name="scene", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={"/Body": override}, + ) + ) + expected = authored if preserve_source else np.eye(4) + np.testing.assert_allclose(result["/Body"].cfg.init_local_pose, expected, atol=1e-6) + + +@pytest.mark.parametrize("curve_count", [1, 2]) +def test_curve_prim_resources_keep_all_uids_and_stable_source_keys( + tmp_path, curve_count +): + path = tmp_path / "cables.usda" + stage = Usd.Stage.CreateNew(str(path)) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + root = UsdGeom.Xform.Define(stage, "/World") + stage.SetDefaultPrim(root.GetPrim()) + curves = UsdGeom.BasisCurves.Define(stage, "/World/Cable") + curves.CreateTypeAttr("linear") + curves.CreateWrapAttr("nonperiodic") + curves.CreateCurveVertexCountsAttr([2] * curve_count) + curves.CreatePointsAttr( + [ + (0, i, 1) if end == 0 else (1, i, 1) + for i in range(curve_count) + for end in (0, 1) + ] + ) + curves.GetPrim().SetMetadata( + "apiSchemas", + Sdf.TokenListOp.Create(prependedItems=["PhysicsCurvesDeformableSimAPI"]), + ) + stage.GetRootLayer().Save() + expected_keys = ( + ["/World/Cable"] + if curve_count == 1 + else [f"/World/Cable#{i}" for i in range(curve_count)] + ) + for namespace in (None, "copy"): + manager = _manager() + result = manager.add_usd( + UsdImportCfg( + name="scene", + source=UsdSourceCfg(file_path=str(path)), + namespace=namespace, + ) + ) + declared = manager._spawn_scene.builder.add_scene.call_args.args[0].cables + assert len(declared) == curve_count + assert list(result.resource_uids) == expected_keys + assert list(result.resource_uids.values()) == [cable.name for cable in declared] + assert dict(result.resource_types) == {key: "cable" for key in expected_keys} + assert dict(result.resource_source_paths) == { + key: "/World/Cable" for key in expected_keys + } + assert len(result) == 0 + with pytest.raises(TypeError): + result.resource_source_paths[expected_keys[0]] = "/Other" + + +def test_portable_sparse_articulation_pose_matrix_is_decoded(monkeypatch): + import json + import dexsim.kit.usd + from scipy.spatial.transform import Rotation + + descriptor = ArticulationDesc( + name="robot", + links=[LinkDesc(name="base", parent_name=None, pose=np.eye(4))], + usd=UsdSourceDesc(prim_path="/Robot"), + ) + monkeypatch.setattr( + dexsim.kit.usd, + "parse_usd", + lambda *args, **kwargs: SceneDesc(articulations=[descriptor]), + ) + expected = np.eye(4) + expected[:3, :3] = Rotation.from_euler( + "XYZ", (20, 30, 40), degrees=True + ).as_matrix() + expected[:3, 3] = (1, 2, 3) + recipe = UsdImportCfg.from_dict( + json.loads( + json.dumps( + { + "name": "scene", + "source": {"file_path": "robot.usda"}, + "asset_cfgs": {"/Robot": {"init_local_pose": expected.tolist()}}, + } + ) + ) + ) + result = _manager().add_usd(recipe) + np.testing.assert_allclose( + result["/Robot"].cfg.init_local_pose, expected, atol=1e-6 + ) diff --git a/tests/sim/test_cfg.py b/tests/sim/test_cfg.py index f06bf60e0..400d6a119 100644 --- a/tests/sim/test_cfg.py +++ b/tests/sim/test_cfg.py @@ -108,8 +108,8 @@ def test_articulation_cfg_uses_grouped_physics_fields_only() -> None: "joint_props", }.isdisjoint(field_names) assert root_props == ArticulationRootPropertiesCfg() - assert root_props.fixed_base is True - assert root_props.self_collision_enabled is False + assert root_props.fixed_base is None + assert root_props.self_collision_enabled is None @pytest.mark.parametrize( @@ -1009,7 +1009,7 @@ def test_backend_joint_and_articulation_configs_round_trip() -> None: assert isinstance(restored_drive, NewtonJointDrivePropertiesCfg) assert root.to_dict() == { "fixed_base": False, - "self_collision_enabled": False, + "self_collision_enabled": None, "sleep_threshold": None, "min_position_iters": None, "min_velocity_iters": None, diff --git a/tests/sim/test_source_cfg.py b/tests/sim/test_source_cfg.py index 05dbd67f9..e8f91b1ca 100644 --- a/tests/sim/test_source_cfg.py +++ b/tests/sim/test_source_cfg.py @@ -18,6 +18,8 @@ from pathlib import Path +import numpy as np + import pytest from pxr import Sdf, Usd, UsdGeom, UsdPhysics @@ -27,13 +29,82 @@ RigidObjectCfg, RobotCfg, UsdSourceCfg, + UsdImportCfg, VisualObjectCfg, + VolumeDeformableObjectCfg, + SurfaceDeformableObjectCfg, ) from embodichain.lab.sim.cfg.source import _asset_file_path from embodichain.lab.sim.shapes import CubeCfg, MeshCfg from embodichain.lab.sim.spawn.usd import rigid_desc_from_usd, visual_desc_from_usd ASSET_CONFIGS = (VisualObjectCfg, RigidObjectCfg, ArticulationCfg, RobotCfg) +pytestmark = pytest.mark.no_sim + + +def test_import_recipe_round_trip_keeps_source_selection_and_sparse_overrides(): + data = { + "name": "cell", + "source": { + "file_path": "cell.usda", + "root_prim_path": "/World/Cell", + "variants": {"/World/Cell": {"tool": "gripper"}}, + }, + "namespace": "cell_1", + "asset_cfgs": {"/World/Cell/Box": {"uid": "payload"}}, + } + cfg = UsdImportCfg.from_dict(data) + cfg.validate_import() + restored = UsdImportCfg.from_dict(cfg.to_dict()) + restored.validate_import() + assert restored.source.parse_kwargs() == { + "prim_path": "/World/Cell", + "variants": {"/World/Cell": {"tool": "gripper"}}, + } + assert restored.asset_cfgs == data["asset_cfgs"] + assert restored.namespace == "cell_1" + + +def test_import_recipe_round_trip_retains_typed_robot_override(): + cfg = UsdImportCfg( + name="scene", + source=UsdSourceCfg(file_path="scene.usda"), + asset_cfgs={ + "/Robot": RobotCfg( + uid="robot", control_parts={"arm": ["joint"]}, build_pk_chain=False + ) + }, + ) + + restored = UsdImportCfg.from_dict(cfg.to_dict()) + + assert isinstance(restored.asset_cfgs["/Robot"], RobotCfg) + assert restored.asset_cfgs["/Robot"].control_parts == {"arm": ["joint"]} + assert restored.asset_cfgs["/Robot"].init_local_pose is None + assert ( + restored.asset_cfgs["/Robot"].asset_physics_mode + == cfg.asset_cfgs["/Robot"].asset_physics_mode + ) + + +@pytest.mark.parametrize( + "source", + [ + UsdSourceCfg(file_path="scene.usda", source_prim_path="/World/Cup"), + UsdSourceCfg(file_path="scene.usda", pose_mode="offset"), + UsdSourceCfg(file_path="scene.usda", namespace="misplaced"), + ], +) +def test_scene_recipe_rejects_singleton_or_import_options_in_source(source): + with pytest.raises(ValueError, match="source|namespace|placement"): + UsdImportCfg(name="scene", source=source).validate_import() + + +def test_source_root_and_legacy_subtree_cannot_disagree(): + with pytest.raises(ValueError, match="root_prim_path"): + UsdSourceCfg( + file_path="scene.usda", root_prim_path="/A", prim_path="/B" + ).validate_source() @pytest.mark.parametrize("cfg_type", ASSET_CONFIGS) @@ -47,8 +118,11 @@ def test_source_configuration_round_trip(cfg_type): assert isinstance(cfg.source, UsdSourceCfg) assert _asset_file_path(cfg) == "scene.usda" restored = cfg_type.from_dict(cfg.to_dict()) - assert restored.source.to_dict() == data["source"] + assert restored.source.file_path == data["source"]["file_path"] + assert restored.source.source_prim_path == data["source"]["source_prim_path"] + assert restored.source.pose_mode == "auto" assert restored.uid == "runtime_instance" + assert restored.init_local_pose is None assert not hasattr(cfg, "prim_path") assert not hasattr(ObjectBaseCfg(), "source") @@ -104,7 +178,48 @@ def test_top_level_selectors_have_an_actionable_error(cfg_type, old_field): def test_source_rejects_unknown_options(): with pytest.raises(ValueError, match="Unknown UsdSourceCfg fields"): - UsdSourceCfg.from_dict({"file_path": "scene.usda", "prim_path": "/World/Cup"}) + UsdSourceCfg.from_dict({"file_path": "scene.usda", "unknown": "/World/Cup"}) + + +def test_source_options_keep_exact_entity_selection_separate_from_stage_selection(): + source = UsdSourceCfg( + file_path="scene.usda", + source_prim_path="/World/Cup", + prim_path="/World", + variants={"/World": {"size": "large"}}, + namespace="room", + pose_mode="offset", + ) + assert source.parse_kwargs() == { + "prim_path": "/World", + "variants": {"/World": {"size": "large"}}, + "namespace": "room", + } + assert source.source_prim_path == "/World/Cup" + + +@pytest.mark.parametrize("placement_owner", ["asset", "legacy_source"]) +def test_usd_pose_mode_preserves_or_offsets_authored_transform(placement_owner): + import numpy as np + from embodichain.lab.sim.spawn.usd import _source_pose + + authored = np.eye(4, dtype=np.float32) + authored[0, 3] = 2 + cfg = RigidObjectCfg( + uid="cup", + source=UsdSourceCfg(file_path="scene.usda"), + init_pos=(1, 0, 0), + ) + if placement_owner == "asset": + cfg.source_pose_mode = "offset" + else: + cfg.source.pose_mode = "offset" + assert _source_pose(cfg, authored)[0, 3] == 3 + if placement_owner == "asset": + cfg.source_pose_mode = "preserve" + else: + cfg.source.pose_mode = "preserve" + assert _source_pose(cfg, authored)[0, 3] == 2 def _cups(tmp_path: Path, names: tuple[str, ...]) -> Path: @@ -132,6 +247,38 @@ def test_source_exact_path_distinguishes_repeated_leaf_names(tmp_path): assert rigid.physics is not None +def test_visual_source_defaults_preserve_authored_pose_and_scale(tmp_path): + import numpy as np + from itertools import product + + path = _cups(tmp_path, ("Only",)) + stage = Usd.Stage.Open(str(path)) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + body = UsdGeom.Xform(stage.GetPrimAtPath("/World/Only")) + body.AddTranslateOp().Set((2.0, 0.0, 0.0)) + body.AddScaleOp().Set((2.0, 2.0, 2.0)) + stage.GetRootLayer().Save() + cfg = VisualObjectCfg.from_dict( + { + "uid": "appearance", + "source": {"file_path": str(path), "root_prim_path": "/World/Only"}, + } + ) + + descriptor, _ = visual_desc_from_usd(cfg) + + np.testing.assert_allclose(descriptor.pose[:3, 3], (2.0, 0.0, 0.0)) + visual = descriptor.renders[0] + corners = np.array(list(product((-0.5, 0.5), repeat=3))) * np.asarray(visual.size) + transform = ( + descriptor.pose @ np.diag([*descriptor.body_scale, 1]) @ visual.local_transform + ) + world = corners @ transform[:3, :3].T + transform[:3, 3] + np.testing.assert_allclose(world.min(axis=0), (0.0, -2.0, -2.0), atol=1e-6) + np.testing.assert_allclose(world.max(axis=0), (4.0, 2.0, 2.0), atol=1e-6) + assert descriptor.physics is None + + def test_source_omitted_selector_requires_one_candidate(tmp_path): path = _cups(tmp_path, ("Only",)) descriptor, _ = visual_desc_from_usd( @@ -155,3 +302,258 @@ def test_legacy_mesh_file_input_remains_available(tmp_path): ) assert descriptor.name == "legacy" assert descriptor.physics is not None + + +@pytest.mark.parametrize( + "cfg_type,explicit_pose", + [ + (cfg_type, True) + for cfg_type in ( + *ASSET_CONFIGS, + VolumeDeformableObjectCfg, + SurfaceDeformableObjectCfg, + ) + ] + + [(VolumeDeformableObjectCfg, False), (SurfaceDeformableObjectCfg, False)], +) +def test_singleton_usd_round_trip_preserves_pose_intent(cfg_type, explicit_pose): + pose = np.eye(4) + pose[:3, 3] = (2.0, -1.0, 3.0) + cfg = cfg_type( + uid="asset", + source=UsdSourceCfg(file_path="scene.usda"), + init_local_pose=pose if explicit_pose else None, + ) + restored = cfg_type.from_dict(cfg.to_dict()) + if explicit_pose: + np.testing.assert_allclose(restored.init_local_pose, pose) + else: + assert restored.init_local_pose is None + + +@pytest.mark.parametrize( + "kind", ["visual", "rigid", "articulation", "volume", "surface"] +) +def test_singleton_translation_captures_resolved_reset_pose(monkeypatch, kind): + import embodichain.lab.sim.spawn.usd as adapter + from dexsim.spawn import ( + ArticulationDesc, + MeshObjectDesc, + SoftBodyDesc, + ClothDesc, + RigidBodyPhysicsDesc, + SceneDesc, + GeometryDesc, + ) + from dexsim.types import ActorType + + config_type, descriptor_type, translate, collection = { + "visual": ( + VisualObjectCfg, + MeshObjectDesc, + adapter.visual_desc_from_usd, + "mesh_objects", + ), + "rigid": ( + RigidObjectCfg, + MeshObjectDesc, + adapter.rigid_desc_from_usd, + "mesh_objects", + ), + "articulation": ( + ArticulationCfg, + ArticulationDesc, + adapter.articulation_desc_from_usd, + "articulations", + ), + "volume": ( + VolumeDeformableObjectCfg, + SoftBodyDesc, + adapter._deformable_desc_from_usd, + "particle_sets", + ), + "surface": ( + SurfaceDeformableObjectCfg, + ClothDesc, + adapter._deformable_desc_from_usd, + "particle_sets", + ), + }[kind] + if kind in ("volume", "surface"): + mesh = GeometryDesc.mesh( + vertices=np.array( + [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32 + ), + triangles=np.array([[0, 1, 2]], dtype=np.int32), + ) + descriptor = descriptor_type(name="authored", mesh=mesh) + else: + descriptor = descriptor_type(name="authored") + descriptor.pose[:3, :3] = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]]) + descriptor.pose[:3, 3] = (2, -1, 3) + if kind == "rigid": + descriptor.physics = RigidBodyPhysicsDesc(actor_type=ActorType.DYNAMIC) + scene = SceneDesc(**{collection: [descriptor]}) + monkeypatch.setattr( + adapter, "_parse_singleton", lambda *args, **kwargs: (scene, descriptor) + ) + cfg = config_type( + uid="runtime", + source=UsdSourceCfg( + file_path="scene.usda", + pose_mode="offset" if kind in ("volume", "surface") else "auto", + ), + source_pose_mode="auto" if kind in ("volume", "surface") else "offset", + init_pos=(1, 2, -1), + ) + authored = descriptor.pose.copy() + expected = authored.copy() + expected[:3, 3] += (1, 2, -1) + resolved, _ = translate(cfg) + np.testing.assert_allclose(resolved.pose, expected) + np.testing.assert_allclose(cfg.init_local_pose, expected) + resolved.pose[0, 3] += 10 + np.testing.assert_allclose(cfg.init_local_pose, expected) + + descriptor.pose = authored.copy() + reused, _ = translate(cfg.copy()) + np.testing.assert_allclose(reused.pose, expected) + + +def test_source_placement_option_keeps_legacy_positional_shape(): + mesh = MeshCfg(fpath="box.obj") + cfg = RigidObjectCfg( + "box", (0, 0, 0), (0, 0, 0), None, mesh, source_pose_mode="offset" + ) + assert isinstance(cfg.shape, MeshCfg) + assert cfg.shape.fpath == "box.obj" + assert cfg.source_pose_mode == "offset" + + +@pytest.mark.parametrize( + "mode,expected_actor", [("preserve", "KINEMATIC"), ("overlay", "DYNAMIC")] +) +def test_legacy_saved_rigid_config_retains_preserve_actor( + tmp_path, mode, expected_actor +): + import json + from dexsim.types import ActorType + + path = _cups(tmp_path, ("Body",)) + stage = Usd.Stage.Open(str(path)) + body = stage.GetPrimAtPath("/World/Body") + UsdPhysics.RigidBodyAPI(body).CreateKinematicEnabledAttr(True) + stage.GetRootLayer().Save() + # Previous versions serialized dynamic even when the user selected no actor. + saved = tmp_path / "legacy.json" + saved.write_text( + json.dumps( + { + "uid": "body", + "shape": {"shape_type": "Mesh", "fpath": str(path)}, + "body_type": "dynamic", + "body_scale": [1, 1, 1], + "asset_physics_mode": mode, + "init_pos": [0, 0, 0], + "init_rot": [0, 0, 0], + "init_local_pose": None, + } + ) + ) + cfg = RigidObjectCfg.from_dict(json.loads(saved.read_text())) + descriptor, _ = rigid_desc_from_usd(cfg) + assert descriptor.physics.actor_type == getattr(ActorType, expected_actor) + + +def test_singleton_constraint_checks_follow_the_selected_asset(tmp_path): + path = _cups(tmp_path, ("A", "B", "C")) + stage = Usd.Stage.Open(str(path)) + joint = UsdPhysics.FixedJoint.Define(stage, "/World/joint") + joint.CreateBody0Rel().SetTargets(["/World/A"]) + joint.CreateBody1Rel().SetTargets(["/World/B"]) + stage.GetRootLayer().Save() + independent, _ = rigid_desc_from_usd( + RigidObjectCfg( + uid="free", + source=UsdSourceCfg(file_path=str(path), source_prim_path="/World/C"), + ) + ) + assert independent.usd.prim_path == "/World/C" + with pytest.raises(ValueError, match="standalone constraints"): + rigid_desc_from_usd( + RigidObjectCfg( + uid="coupled", + source=UsdSourceCfg(file_path=str(path), source_prim_path="/World/A"), + ) + ) + visual, _ = visual_desc_from_usd( + VisualObjectCfg( + uid="appearance", + source=UsdSourceCfg(file_path=str(path), source_prim_path="/World/B"), + ) + ) + assert visual.physics is None + assert visual.collisions == [] + + +@pytest.mark.parametrize("source_field", ["source", "fpath"]) +@pytest.mark.parametrize("configured_scale", [None, (2.0, 3.0, 4.0)]) +def test_robot_source_scale_survives_portable_round_trip( + tmp_path, monkeypatch, source_field, configured_scale +): + import json + from copy import deepcopy + from dexsim.spawn import ArticulationDesc, SceneDesc + import embodichain.lab.sim.spawn.usd as adapter + + path = tmp_path / "robot.usda" + path.touch() + file_fields = ( + {"source": UsdSourceCfg(file_path=str(path))} + if source_field == "source" + else {"fpath": str(path)} + ) + original = RobotCfg(uid="robot", body_scale=configured_scale, **file_fields) + serialized = json.loads(json.dumps(original.to_dict())) + restored = RobotCfg.from_dict(serialized) + if configured_scale is None: + assert restored.body_scale is None + else: + np.testing.assert_allclose(restored.body_scale, configured_scale) + authored = ArticulationDesc(name="authored", body_scale=np.array([1.5, 1.5, 1.5])) + monkeypatch.setattr( + adapter, + "_parse_singleton", + lambda *args, **kwargs: (SceneDesc(), deepcopy(authored)), + ) + for cfg in (original, restored): + descriptor, _ = adapter.articulation_desc_from_usd(cfg) + np.testing.assert_allclose( + descriptor.body_scale, + [1.5] * 3 if configured_scale is None else configured_scale, + ) + + +def test_robot_decode_retains_preset_scale_and_urdf_defaults(tmp_path): + from embodichain.utils import configclass + + @configclass + class ScaledRobotCfg(RobotCfg): + body_scale: tuple = (2.0, 3.0, 4.0) + + cfg = ScaledRobotCfg.from_dict({"source": {"file_path": "robot.usda"}}) + assert cfg.body_scale == (2.0, 3.0, 4.0) + path = tmp_path / "robot.urdf" + path.touch() + assert RobotCfg.from_dict({"fpath": str(path)}).body_scale == (1.0, 1.0, 1.0) + + +def test_locomotion_preset_keeps_source_scale_unset_after_decode(tmp_path): + from embodichain.robot_registry import resolve_robot_cfg + + path = tmp_path / "g1.usda" + path.touch() + cfg = resolve_robot_cfg("UnitreeG1", {"source": {"file_path": str(path)}}) + assert cfg.source.file_path == str(path) + assert cfg.fpath is None + assert cfg.body_scale is None diff --git a/tests/sim/utility/test_sim_utils.py b/tests/sim/utility/test_sim_utils.py index cc7cb83a3..f977ffbe3 100644 --- a/tests/sim/utility/test_sim_utils.py +++ b/tests/sim/utility/test_sim_utils.py @@ -38,11 +38,17 @@ def set_name(self, name: str) -> None: class _FakeArena: def __init__(self) -> None: self.acd_kwargs: dict[str, object] | None = None + self.usd_path: str | None = None def load_actor_with_acd(self, _fpath: str, **kwargs: object) -> _FakeMeshObject: self.acd_kwargs = kwargs return _FakeMeshObject() + def import_from_usd_file(self, fpath: str, *, return_object: bool): + assert return_object + self.usd_path = fpath + return {"/Body": _FakeMeshObject()} + @pytest.fixture(autouse=True) def default_backend(monkeypatch: pytest.MonkeyPatch) -> None: @@ -80,3 +86,45 @@ def test_mesh_collision_acd_method_is_forwarded_to_dexsim() -> None: assert arena.acd_kwargs is not None assert arena.acd_kwargs["method"] == "vhacd" + + +def test_decoded_ordinary_mesh_defaults_work_with_legacy_loader() -> None: + from dexsim.types import ActorType + + cfg = RigidObjectCfg.from_dict( + { + "uid": "mesh", + "shape": { + "shape_type": "Mesh", + "fpath": _MESH_PATH, + "collision": { + "approximation": "convex_decomposition", + "max_hulls": _CONVEX_HULL_COUNT, + }, + }, + } + ) + arena = _FakeArena() + objects = load_mesh_objects_from_cfg(cfg, [arena]) + assert objects[0].name == "mesh_0" + assert cfg.to_dexsim_body_type() == ActorType.DYNAMIC + assert cfg.body_scale == (1.0, 1.0, 1.0) + + +@pytest.mark.parametrize("decoded", [False, True]) +def test_legacy_usd_mesh_import_does_not_require_configured_actor(monkeypatch, decoded): + path = "mesh.usda" + cfg = ( + RigidObjectCfg.from_dict( + {"uid": "mesh", "shape": {"shape_type": "Mesh", "fpath": path}} + ) + if decoded + else RigidObjectCfg(uid="mesh", shape=MeshCfg(fpath=path)) + ) + monkeypatch.setattr(sim_utils, "MeshObject", _FakeMeshObject) + arena = _FakeArena() + objects = load_mesh_objects_from_cfg(cfg, [arena]) + assert objects[0].name == "mesh_0" + assert arena.usd_path == path + assert arena.acd_kwargs is None + assert cfg.body_type is None