diff --git a/docs/source/api/lab/isaaclab.sim.spawners.rst b/docs/source/api/lab/isaaclab.sim.spawners.rst index d42fa13e524e..ce82c003e8e5 100644 --- a/docs/source/api/lab/isaaclab.sim.spawners.rst +++ b/docs/source/api/lab/isaaclab.sim.spawners.rst @@ -267,6 +267,9 @@ Materials MdlFileCfg GlassMdlCfg PhysicsMaterialCfg + RigidBodyMaterialBaseCfg + RigidBodyMaterialFragment + UsdPhysicsRigidBodyMaterialCfg RigidBodyMaterialCfg DeformableBodyMaterialBaseCfg SurfaceDeformableBodyMaterialBaseCfg @@ -303,8 +306,27 @@ Physical Materials :members: :exclude-members: __init__, func +.. autofunction:: spawn_physics_material + .. autofunction:: spawn_rigid_body_material +.. autoclass:: RigidBodyMaterialBaseCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autofunction:: spawn_rigid_body_material_from_fragments + +.. autoclass:: RigidBodyMaterialFragment + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: UsdPhysicsRigidBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + .. autoclass:: RigidBodyMaterialCfg :members: :exclude-members: __init__, func diff --git a/docs/source/api/lab_newton/isaaclab_newton.sim.spawners.rst b/docs/source/api/lab_newton/isaaclab_newton.sim.spawners.rst index f42cef3d8167..2db0a1622814 100644 --- a/docs/source/api/lab_newton/isaaclab_newton.sim.spawners.rst +++ b/docs/source/api/lab_newton/isaaclab_newton.sim.spawners.rst @@ -7,10 +7,19 @@ isaaclab_newton.sim.spawners .. autosummary:: + NewtonMaterialCfg NewtonDeformableBodyMaterialCfg NewtonDeformableMaterialCfg NewtonSurfaceDeformableBodyMaterialCfg +Rigid Materials +--------------- + +.. autoclass:: NewtonMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + Deformable Materials -------------------- diff --git a/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst b/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst index 7a2ace2a33ff..3e2355d141e2 100644 --- a/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst +++ b/docs/source/api/lab_physx/isaaclab_physx.sim.spawners.rst @@ -7,12 +7,27 @@ isaaclab_physx.sim.spawners .. autosummary:: + PhysxRigidBodyMaterialCfg + PhysxMaterialCfg PhysxDeformableBodyMaterialCfg PhysxSurfaceDeformableBodyMaterialCfg PhysXDeformableMaterialCfg DeformableBodyMaterialCfg SurfaceDeformableBodyMaterialCfg +Rigid Materials +--------------- + +.. autoclass:: PhysxRigidBodyMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autoclass:: PhysxMaterialCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + Deformable Materials -------------------- diff --git a/source/isaaclab/changelog.d/vidurv-schema-frag-materials.minor.rst b/source/isaaclab/changelog.d/vidurv-schema-frag-materials.minor.rst new file mode 100644 index 000000000000..1cfe675cb0b3 --- /dev/null +++ b/source/isaaclab/changelog.d/vidurv-schema-frag-materials.minor.rst @@ -0,0 +1,45 @@ +Added +^^^^^ + +* Added the rigid-body physics-material "fragment" classes + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment` (marker base) and + :class:`~isaaclab.sim.spawners.materials.UsdPhysicsRigidBodyMaterialCfg` (solver-common + ``physics:*`` friction/restitution/density), plus the family writer + :func:`~isaaclab.sim.spawners.materials.spawn_rigid_body_material_from_fragments` and the slot + dispatcher :func:`~isaaclab.sim.spawners.materials.spawn_physics_material`. Relevant + ``physics_material`` slots now accept a single fragment or list alongside their legacy cfg form. + Legacy material cfgs are current-stage-only: the dispatcher raises ``ValueError`` for an explicit + non-current stage, while fragment-based materials support explicit-stage authoring. + +* Added :attr:`~isaaclab.sim.spawners.materials.UsdPhysicsRigidBodyMaterialCfg.density` (writes + ``physics:density``), completing the fragment's coverage of ``UsdPhysics.MaterialAPI``. +* Added :attr:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg.density`, so the legacy + rigid material base authors every attribute the fragment authors. + +Changed +^^^^^^^ + +* Narrowed :attr:`~isaaclab.sim.spawners.ShapeCfg.physics_material` from the broad + :class:`~isaaclab.sim.spawners.materials.PhysicsMaterialCfg` to the rigid material base, a single + rigid-material fragment, or a list of fragments. +* Extended the already rigid-only :attr:`~isaaclab.sim.spawners.GroundPlaneCfg.physics_material` + and :attr:`~isaaclab.terrains.TerrainImporterCfg.physics_material` slots from the legacy + :class:`~isaaclab_physx.sim.spawners.materials.RigidBodyMaterialCfg` type to + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg`, a single + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment`, or a list of fragments. + Deformable materials remain accepted where deformables can spawn + (:class:`~isaaclab.sim.spawners.FileCfg` and :class:`~isaaclab.sim.spawners.MeshCfg`). +* Changed the generated-terrain material path to use + :func:`~isaaclab.sim.spawners.materials.spawn_physics_material`, enabling fragment lists there. + +Fixed +^^^^^ + +* Fixed mesh spawners rejecting valid rigid physics materials: the rigid-material check compared + against the deprecated leaf class, so canonical + :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg` and + :class:`~isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg` instances raised + ``ValueError`` on rigid meshes. The check now accepts any + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg`. +* Fixed malformed fragment inputs reaching an opaque legacy ``func`` call. Direct and dispatched + fragment calls now reject empty, mixed, and non-fragment inputs before creating a material prim. diff --git a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py index d9f789b666f3..80b9f940e417 100644 --- a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py +++ b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py @@ -16,6 +16,7 @@ from isaaclab.sim import converters, schemas from isaaclab.sim.spawners.materials import SurfaceDeformableBodyMaterialBaseCfg +from isaaclab.sim.spawners.materials.physics_materials import spawn_physics_material from isaaclab.sim.utils import ( add_labels, bind_physics_material, @@ -211,7 +212,7 @@ def spawn_ground_plane( # Create physics material if cfg.physics_material is not None: - cfg.physics_material.func(f"{prim_path}/physicsMaterial", cfg.physics_material) + spawn_physics_material(f"{prim_path}/physicsMaterial", cfg.physics_material, stage=stage) # Apply physics material to ground plane collision_prim = get_first_matching_child_prim( prim_path, @@ -478,8 +479,8 @@ def _spawn_from_usd_file( material_path = f"{prim_path}/{cfg.physics_material_path}" else: material_path = cfg.physics_material_path - # create material - cfg.physics_material.func(material_path, cfg.physics_material) + # create material (accepts a legacy material cfg or rigid-body fragment(s)) + spawn_physics_material(material_path, cfg.physics_material, stage=stage) # apply material bind_physics_material(prim_path, material_path, stage=stage) diff --git a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files_cfg.py b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files_cfg.py index ea2cfe9b6c9f..1c9c26e02525 100644 --- a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files_cfg.py @@ -106,9 +106,18 @@ class FileCfg(RigidObjectSpawnerCfg, DeformableObjectSpawnerCfg): This parameter is ignored if `physics_material` is not None. """ - physics_material: materials.PhysicsMaterialCfg | None = None + physics_material: ( + materials.PhysicsMaterialCfg + | materials.RigidBodyMaterialFragment + | list[materials.RigidBodyMaterialFragment] + | None + ) = None """Physics material properties. + Accepts either a legacy material cfg, a single + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment`, or a list of such + single-namespace fragments. + Note: If None, then no custom physics material will be added. """ @@ -259,5 +268,15 @@ class GroundPlaneCfg(SpawnerCfg): size: tuple[float, float] = (100.0, 100.0) """The size of the ground plane. Defaults to 100 m x 100 m.""" - physics_material: materials.RigidBodyMaterialCfg = materials.RigidBodyMaterialCfg() - """Physics material properties. Defaults to the default rigid body material.""" + physics_material: ( + materials.RigidBodyMaterialBaseCfg + | materials.RigidBodyMaterialFragment + | list[materials.RigidBodyMaterialFragment] + ) = materials.RigidBodyMaterialCfg() + """Physics material properties. Defaults to the default rigid body material. + + The ground plane only spawns a collision plane, so this only accepts rigid-body materials: a + legacy :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg`, a single + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment`, or a list of such + single-namespace fragments. + """ diff --git a/source/isaaclab/isaaclab/sim/spawners/materials/__init__.pyi b/source/isaaclab/isaaclab/sim/spawners/materials/__init__.pyi index 7ce7815955c2..305c980d2312 100644 --- a/source/isaaclab/isaaclab/sim/spawners/materials/__init__.pyi +++ b/source/isaaclab/isaaclab/sim/spawners/materials/__init__.pyi @@ -5,9 +5,13 @@ __all__ = [ "spawn_rigid_body_material", + "spawn_rigid_body_material_from_fragments", + "spawn_physics_material", "spawn_deformable_body_material", "PhysicsMaterialCfg", "RigidBodyMaterialBaseCfg", + "RigidBodyMaterialFragment", + "UsdPhysicsRigidBodyMaterialCfg", "DeformableBodyMaterialBaseCfg", "DeformableBodyMaterialCfg", "SurfaceDeformableBodyMaterialBaseCfg", @@ -20,10 +24,17 @@ __all__ = [ "VisualMaterialCfg", ] -from .physics_materials import spawn_rigid_body_material, spawn_deformable_body_material +from .physics_materials import ( + spawn_deformable_body_material, + spawn_physics_material, + spawn_rigid_body_material, + spawn_rigid_body_material_from_fragments, +) from .physics_materials_cfg import ( PhysicsMaterialCfg, RigidBodyMaterialBaseCfg, + RigidBodyMaterialFragment, + UsdPhysicsRigidBodyMaterialCfg, DeformableBodyMaterialBaseCfg, DeformableBodyMaterialCfg, SurfaceDeformableBodyMaterialBaseCfg, diff --git a/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials.py b/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials.py index 8c12bee9442d..51f19226bb1e 100644 --- a/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials.py +++ b/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials.py @@ -12,10 +12,138 @@ from isaaclab.sim.schemas.schemas import _apply_namespaced_schemas from isaaclab.sim.utils import clone from isaaclab.sim.utils.stage import get_current_stage +from isaaclab.utils.string import string_to_callable from . import physics_materials_cfg +def spawn_rigid_body_material_from_fragments( + prim_path: str, + fragments: physics_materials_cfg.RigidBodyMaterialFragment + | list[physics_materials_cfg.RigidBodyMaterialFragment] + | tuple[physics_materials_cfg.RigidBodyMaterialFragment, ...], + stage: Usd.Stage | None = None, +) -> Usd.Prim: + """Spawn a rigid-body physics material from one or more single-namespace fragments. + + Creates (or reuses) the ``UsdShade.Material`` prim at ``prim_path``, applies the standard + ``UsdPhysics.MaterialAPI`` anchor, then dispatches each fragment via its + :attr:`~isaaclab.sim.schemas.SchemaFragment.func` to author its namespace onto the material prim. + Backend fragments carry backend-specific namespaces (e.g. PhysX ``physxMaterial:*``) without core + importing a backend. + + .. note:: + Unlike the ``@clone``-decorated :func:`spawn_rigid_body_material`, this writer expects a + concrete ``prim_path`` and does not resolve regex prim-path patterns. Physics materials are + spawned at a single derived path by :func:`spawn_physics_material` and the spawner internals, + so regex resolution does not apply here. + + Args: + prim_path: The prim path to spawn the material at. + fragments: A single :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment`, + or a list/tuple of them. + stage: The stage to spawn on. Defaults to None, in which case the current stage is used. + + Returns: + The spawned rigid body material prim. + + Raises: + ValueError: When ``fragments`` is empty. + ValueError: When a prim already exists at the path and is not a material. + TypeError: When an item is not a rigid-body material fragment. + """ + if not isinstance(fragments, (list, tuple)): + fragments = [fragments] + else: + fragments = list(fragments) + if not fragments: + raise ValueError(f"Cannot spawn a physics material at '{prim_path}' from an empty fragment collection.") + invalid_types = [ + type(fragment).__name__ + for fragment in fragments + if not isinstance(fragment, physics_materials_cfg.RigidBodyMaterialFragment) + ] + if invalid_types: + raise TypeError( + "A physics-material fragment collection must contain only RigidBodyMaterialFragment instances; got" + f" {invalid_types}." + ) + if stage is None: + stage = get_current_stage() + + # create the material prim if none exists yet + if not stage.GetPrimAtPath(prim_path).IsValid(): + UsdShade.Material.Define(stage, prim_path) + prim = stage.GetPrimAtPath(prim_path) + if not prim.IsA(UsdShade.Material): + raise ValueError(f"A prim already exists at path: '{prim_path}' but is not a material.") + + # apply the standard UsdPhysics MaterialAPI anchor (the defining schema for a physics material) + if not UsdPhysics.MaterialAPI(prim): + UsdPhysics.MaterialAPI.Apply(prim) + + # dispatch each fragment's applier (writes its single namespace onto the material prim) + for cfg in fragments: + func = cfg.func if callable(cfg.func) else string_to_callable(cfg.func) + func(cfg, prim_path, stage) + return prim + + +def spawn_physics_material( + prim_path: str, + material: physics_materials_cfg.PhysicsMaterialCfg + | physics_materials_cfg.RigidBodyMaterialFragment + | list[physics_materials_cfg.RigidBodyMaterialFragment] + | tuple[physics_materials_cfg.RigidBodyMaterialFragment, ...], + stage: Usd.Stage | None = None, +) -> Usd.Prim: + """Spawn a physics material from a spawner ``physics_material`` slot value. + + Dispatches the two accepted slot forms: a single rigid-body fragment or list/tuple is spawned via + :func:`spawn_rigid_body_material_from_fragments`; otherwise the value is a legacy material cfg and is + spawned via its own :attr:`func`. Lets spawners accept both the fragment and the legacy interface + from one call site. + + Args: + prim_path: The prim path to spawn the material at. + material: A :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment` (or list/tuple + of them), or a legacy material cfg carrying a :attr:`func`. + stage: The stage to spawn on. Defaults to None, in which case the current stage is used. A + legacy material cfg only supports the current stage (or None); passing a different + stage raises. + Returns: + The spawned material prim. + + Raises: + ValueError: When ``material`` is an empty fragment collection. + ValueError: When ``material`` is a legacy material cfg and ``stage`` is neither ``None`` + nor the current stage. + TypeError: When ``material`` is a fragment collection containing anything other than + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment` instances. + TypeError: When ``material`` is neither a physics-material cfg nor a rigid-body fragment. + """ + # The family writer owns fragment validation so direct and dispatched calls have one contract. + if isinstance(material, (list, tuple, physics_materials_cfg.RigidBodyMaterialFragment)): + return spawn_rigid_body_material_from_fragments(prim_path, material, stage) + if not isinstance(material, physics_materials_cfg.PhysicsMaterialCfg): + raise TypeError( + "A physics material must be a PhysicsMaterialCfg or rigid-body material fragment; got" + f" '{type(material).__name__}'." + ) + # legacy single-cfg path (rigid or deformable material cfg with its own spawner ``func``). + # Legacy material funcs take only ``(prim_path, cfg)`` and resolve the stage internally via + # ``get_current_stage()`` (their path matching is also current-stage-bound), so an explicit + # different stage cannot be honored on this path -- reject it loudly rather than authoring on + # the wrong stage. The fragment path above supports explicit stages. + if stage is not None and stage != get_current_stage(): + raise ValueError( + f"Legacy material cfg '{type(material).__name__}' can only be spawned on the current" + " stage. Pass the current stage (or None), or use the fragment-based API for" + " explicit-stage authoring." + ) + return material.func(prim_path, material) + + @clone def spawn_rigid_body_material(prim_path: str, cfg: physics_materials_cfg.RigidBodyMaterialBaseCfg) -> Usd.Prim: """Create material with rigid-body physics properties. @@ -26,10 +154,10 @@ def spawn_rigid_body_material(prim_path: str, cfg: physics_materials_cfg.RigidBo PxMaterial `_. The writer is metadata-driven: it always applies the standard ``UsdPhysics.MaterialAPI`` and - writes the friction/restitution fields, then reads ``_usd_applied_schema``, ``_usd_namespace``, - and ``_usd_attr_name_map`` from the cfg to author solver-specific attributes. The applied - schema (e.g. ``PhysxMaterialAPI``) is added only when at least one solver-specific field has a - non-``None`` value at the instance level. + writes the friction/restitution/density fields, then reads ``_usd_applied_schema``, + ``_usd_namespace``, and ``_usd_attr_name_map`` from the cfg to author solver-specific attributes. + The applied schema (e.g. ``PhysxMaterialAPI``) is added only when at least one solver-specific + field has a non-``None`` value at the instance level. .. note:: This function is decorated with :func:`clone` that resolves prim path into list of paths diff --git a/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py b/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py index 5c88731cf8d5..6dbe000e773f 100644 --- a/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py @@ -9,6 +9,7 @@ from dataclasses import MISSING from typing import ClassVar +from isaaclab.sim.schemas.schemas_cfg import SchemaFragment from isaaclab.utils.configclass import configclass # Names that moved out of this submodule into ``isaaclab_physx.sim.spawners.materials.physics_materials_cfg``. @@ -60,9 +61,10 @@ class PhysicsMaterialCfg: class RigidBodyMaterialBaseCfg(PhysicsMaterialCfg): """Solver-common physics-material parameters for rigid bodies. - Contains the friction and restitution fields from the `UsdPhysics.MaterialAPI`_ that are common - across all simulation backends. For PhysX-only material properties (compliant-contact spring, - combine modes), use :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg`. + Contains the friction, restitution, and density fields from the `UsdPhysics.MaterialAPI`_ that + are common across all simulation backends. For properties in the ``physxMaterial`` namespace + (compliant-contact spring and combine modes), use + :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg`. See :meth:`spawn_rigid_body_material` for more information. @@ -88,6 +90,60 @@ class RigidBodyMaterialBaseCfg(PhysicsMaterialCfg): restitution: float = 0.0 """The restitution coefficient. Defaults to 0.0.""" + density: float | None = None + """The material density [kg/m^3]. Defaults to None, in which case it is not authored. + + Writes ``physics:density``. It is a fallback for collision shapes bound to this material; + explicitly authored rigid-body mass or density takes precedence. + """ + + +@configclass +class RigidBodyMaterialFragment(SchemaFragment): + """Marker base for rigid-body physics-material fragments; types the ``physics_material`` slot. + + A rigid-body physics material is a single ``UsdShade.Material`` prim that carries one or more + physics-material schemas. The fragments author single namespaces onto that prim: the + solver-common ``physics:*`` friction/restitution/density + (:class:`UsdPhysicsRigidBodyMaterialCfg`) and any backend-specific namespace (e.g. PhysX + ``physxMaterial:*`` via :class:`~isaaclab_physx.sim.spawners.materials.PhysxMaterialCfg`). + The defining ``UsdPhysics.MaterialAPI`` anchor is applied by the family writer + (:func:`~isaaclab.sim.spawners.materials.spawn_rigid_body_material_from_fragments`). + """ + + pass + + +@configclass +class UsdPhysicsRigidBodyMaterialCfg(RigidBodyMaterialFragment): + """``physics:*`` rigid-body material attributes from `UsdPhysics.MaterialAPI`_. + + The ``UsdPhysics.MaterialAPI`` schema is applied as the implicit anchor by the rigid-body material + family writer, so this fragment owns no applied schema of its own. ``None`` fields are left + unchanged on the material prim. + + .. _UsdPhysics.MaterialAPI: https://openusd.org/dev/api/class_usd_physics_material_a_p_i.html + """ + + _usd_namespace: ClassVar[str | None] = "physics" + _usd_applied_schema: ClassVar[str | None] = None # MaterialAPI applied by the family writer + + static_friction: float | None = None + """The static friction coefficient. Writes ``physics:staticFriction``.""" + + dynamic_friction: float | None = None + """The dynamic friction coefficient. Writes ``physics:dynamicFriction``.""" + + restitution: float | None = None + """The restitution coefficient. Writes ``physics:restitution``.""" + + density: float | None = None + """The material density [kg/m^3]. Writes ``physics:density``. + + Participates in mass computation via material binding when no explicit rigid-body mass or + density takes precedence. + """ + @configclass class DeformableBodyMaterialBaseCfg(PhysicsMaterialCfg): diff --git a/source/isaaclab/isaaclab/sim/spawners/meshes/meshes.py b/source/isaaclab/isaaclab/sim/spawners/meshes/meshes.py index bf0df38db129..f46d06c68560 100644 --- a/source/isaaclab/isaaclab/sim/spawners/meshes/meshes.py +++ b/source/isaaclab/isaaclab/sim/spawners/meshes/meshes.py @@ -16,7 +16,13 @@ from isaaclab.sim import schemas from isaaclab.sim.utils import bind_physics_material, bind_visual_material, clone, create_prim, get_current_stage -from ..materials import DeformableBodyMaterialBaseCfg, RigidBodyMaterialCfg, SurfaceDeformableBodyMaterialBaseCfg +from ..materials import ( + DeformableBodyMaterialBaseCfg, + RigidBodyMaterialBaseCfg, + RigidBodyMaterialFragment, + SurfaceDeformableBodyMaterialBaseCfg, +) +from ..materials.physics_materials import spawn_physics_material if TYPE_CHECKING: from . import meshes_cfg @@ -367,7 +373,15 @@ def _spawn_mesh_geom_from_mesh( if not isinstance(cfg.physics_material, DeformableBodyMaterialBaseCfg): raise ValueError("Deformable properties require a deformable physics material.") if cfg.rigid_props is not None and cfg.physics_material is not None: - if not isinstance(cfg.physics_material, RigidBodyMaterialCfg): + # accept anything spawn_physics_material accepts for the rigid case: a legacy rigid-body + # material cfg, a single fragment, or a list/tuple of fragments + physics_material_frags = ( + cfg.physics_material if isinstance(cfg.physics_material, (list, tuple)) else [cfg.physics_material] + ) + is_rigid_material = isinstance(cfg.physics_material, RigidBodyMaterialBaseCfg) or all( + isinstance(frag, RigidBodyMaterialFragment) for frag in physics_material_frags + ) + if not is_rigid_material: raise ValueError("Rigid properties require a rigid physics material.") # create all the paths we need for clarity @@ -439,8 +453,8 @@ def _spawn_mesh_geom_from_mesh( material_path = f"{geom_prim_path}/{cfg.physics_material_path}" else: material_path = cfg.physics_material_path - # create material - cfg.physics_material.func(material_path, cfg.physics_material) + # create material (accepts a legacy material cfg or rigid-body fragment(s)) + spawn_physics_material(material_path, cfg.physics_material, stage=stage) # apply material bind_physics_material(prim_path, material_path, stage=stage) diff --git a/source/isaaclab/isaaclab/sim/spawners/meshes/meshes_cfg.py b/source/isaaclab/isaaclab/sim/spawners/meshes/meshes_cfg.py index c6eb26507d3a..aafd4d3cd7e0 100644 --- a/source/isaaclab/isaaclab/sim/spawners/meshes/meshes_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/meshes/meshes_cfg.py @@ -57,9 +57,18 @@ class MeshCfg(RigidObjectSpawnerCfg, DeformableObjectSpawnerCfg): This parameter is ignored if `physics_material` is not None. """ - physics_material: materials.PhysicsMaterialCfg | None = None + physics_material: ( + materials.PhysicsMaterialCfg + | materials.RigidBodyMaterialFragment + | list[materials.RigidBodyMaterialFragment] + | None + ) = None """Physics material properties. + Accepts either a legacy material cfg, a single + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment`, or a list of such + single-namespace fragments. + Note: If None, then no physics material will be added. """ diff --git a/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py b/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py index 2d1b721e9567..2b8177423a88 100644 --- a/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py +++ b/source/isaaclab/isaaclab/sim/spawners/shapes/shapes.py @@ -10,6 +10,7 @@ from pxr import Usd from isaaclab.sim import schemas +from isaaclab.sim.spawners.materials.physics_materials import spawn_physics_material from isaaclab.sim.utils import bind_physics_material, bind_visual_material, clone, create_prim, get_current_stage if TYPE_CHECKING: @@ -316,8 +317,8 @@ def _spawn_geom_from_prim_type( material_path = f"{geom_prim_path}/{cfg.physics_material_path}" else: material_path = cfg.physics_material_path - # create material - cfg.physics_material.func(material_path, cfg.physics_material) + # create material (accepts a legacy material cfg or rigid-body fragment(s)) + spawn_physics_material(material_path, cfg.physics_material, stage=stage) # apply material bind_physics_material(mesh_prim_path, material_path, stage=stage) diff --git a/source/isaaclab/isaaclab/sim/spawners/shapes/shapes_cfg.py b/source/isaaclab/isaaclab/sim/spawners/shapes/shapes_cfg.py index b111bdbb2bf3..04d0bc42a764 100644 --- a/source/isaaclab/isaaclab/sim/spawners/shapes/shapes_cfg.py +++ b/source/isaaclab/isaaclab/sim/spawners/shapes/shapes_cfg.py @@ -37,9 +37,18 @@ class ShapeCfg(RigidObjectSpawnerCfg): If the path is relative, then it will be relative to the prim's path. This parameter is ignored if `physics_material` is not None. """ - physics_material: materials.PhysicsMaterialCfg | None = None + physics_material: ( + materials.RigidBodyMaterialBaseCfg + | materials.RigidBodyMaterialFragment + | list[materials.RigidBodyMaterialFragment] + | None + ) = None """Physics material properties. + Since shapes are rigid-only spawners, this slot accepts the rigid material base class or + rigid-material fragments (single-namespace :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment` + instances or lists thereof). + Note: If None, then no physics material will be added. """ diff --git a/source/isaaclab/isaaclab/terrains/terrain_importer_cfg.py b/source/isaaclab/isaaclab/terrains/terrain_importer_cfg.py index db34c9a17195..d457c1606c83 100644 --- a/source/isaaclab/isaaclab/terrains/terrain_importer_cfg.py +++ b/source/isaaclab/isaaclab/terrains/terrain_importer_cfg.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Literal import isaaclab.sim as sim_utils +from isaaclab.sim.spawners import materials from isaaclab.utils.configclass import configclass if TYPE_CHECKING: @@ -87,13 +88,20 @@ class TerrainImporterCfg: to the grid color of the imported ground plane. """ - physics_material: sim_utils.RigidBodyMaterialCfg = sim_utils.RigidBodyMaterialCfg() + physics_material: ( + materials.RigidBodyMaterialBaseCfg + | materials.RigidBodyMaterialFragment + | list[materials.RigidBodyMaterialFragment] + ) = materials.RigidBodyMaterialCfg() """The physics material of the terrain. Defaults to a default physics material. The material is created at the path: ``{prim_path}/physicsMaterial``. .. note:: This parameter is used only when the ``terrain_type`` is "generator" or "plane". + + Accepts a legacy rigid material cfg, a single rigid-material fragment, or a list of + rigid-material fragments. """ max_init_terrain_level: int | None = None diff --git a/source/isaaclab/isaaclab/terrains/utils.py b/source/isaaclab/isaaclab/terrains/utils.py index 739f80940021..68498cfde402 100644 --- a/source/isaaclab/isaaclab/terrains/utils.py +++ b/source/isaaclab/isaaclab/terrains/utils.py @@ -14,6 +14,7 @@ from pxr import UsdGeom import isaaclab.sim as sim_utils +from isaaclab.sim.spawners.materials import spawn_physics_material from isaaclab.utils.warp import raycast_mesh @@ -80,7 +81,8 @@ def create_prim_from_mesh(prim_path: str, mesh: trimesh.Trimesh, **kwargs): translation: The translation of the terrain. Defaults to None. orientation: The orientation of the terrain. Defaults to None. visual_material: The visual material to apply. Defaults to None. - physics_material: The physics material to apply. Defaults to None. + physics_material: The physics material to apply. Defaults to None. Accepts a legacy rigid + material cfg, a single rigid-material fragment, or a list of fragments. """ # create parent prim sim_utils.create_prim(prim_path, "Xform") @@ -122,10 +124,9 @@ def create_prim_from_mesh(prim_path: str, mesh: trimesh.Trimesh, **kwargs): visual_material_cfg.func(f"{prim_path}/visualMaterial", visual_material_cfg) sim_utils.bind_visual_material(prim.GetPrimPath(), f"{prim_path}/visualMaterial") # create physics material - if kwargs.get("physics_material") is not None: - physics_material_cfg: sim_utils.RigidBodyMaterialCfg = kwargs.get("physics_material") - # spawn the material - physics_material_cfg.func(f"{prim_path}/physicsMaterial", physics_material_cfg) + physics_material = kwargs.get("physics_material") + if physics_material is not None: + spawn_physics_material(f"{prim_path}/physicsMaterial", physics_material) sim_utils.bind_physics_material(prim.GetPrimPath(), f"{prim_path}/physicsMaterial") diff --git a/source/isaaclab/test/sim/test_material_fragments.py b/source/isaaclab/test/sim/test_material_fragments.py new file mode 100644 index 000000000000..8caf9a99fd92 --- /dev/null +++ b/source/isaaclab/test/sim/test_material_fragments.py @@ -0,0 +1,523 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True).app + +"""Rest everything follows.""" + +import pytest + +from pxr import UsdPhysics, UsdShade + +import isaaclab.sim as sim_utils +from isaaclab.sim import SimulationCfg, SimulationContext + +# ------------------------------------------------------------------------------------- +# RigidBodyMaterialFragment marker + metadata +# ------------------------------------------------------------------------------------- + + +def test_rigid_body_material_fragment_metadata_defaults(): + from isaaclab.sim.schemas import SchemaFragment + from isaaclab.sim.spawners.materials.physics_materials_cfg import ( + RigidBodyMaterialFragment, + UsdPhysicsRigidBodyMaterialCfg, + ) + + cfg = UsdPhysicsRigidBodyMaterialCfg(static_friction=0.7) + assert isinstance(cfg, RigidBodyMaterialFragment) and isinstance(cfg, SchemaFragment) + assert type(cfg)._usd_namespace == "physics" + assert type(cfg)._usd_applied_schema is None # MaterialAPI applied by the family writer + assert cfg.func == "isaaclab.sim.schemas:apply_namespaced" + assert cfg.static_friction == 0.7 and cfg.dynamic_friction is None + + +def test_physx_material_fragment_metadata_defaults(): + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import PhysxMaterialCfg + + from isaaclab.sim.spawners.materials.physics_materials_cfg import RigidBodyMaterialFragment + + cfg = PhysxMaterialCfg(compliant_contact_stiffness=100.0) + assert isinstance(cfg, RigidBodyMaterialFragment) + assert type(cfg)._usd_namespace == "physxMaterial" + assert type(cfg)._usd_applied_schema == "PhysxMaterialAPI" + assert cfg.func == "isaaclab.sim.schemas:apply_namespaced" + + +# ------------------------------------------------------------------------------------- +# spawn_rigid_body_material_from_fragments: spawn prim + anchor + multi-namespace compose +# ------------------------------------------------------------------------------------- + + +def test_spawn_rigid_body_material_from_fragments_composes_namespaces(): + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import PhysxMaterialCfg + + from isaaclab.sim.spawners.materials.physics_materials import spawn_rigid_body_material_from_fragments + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + prim = spawn_rigid_body_material_from_fragments( + "/World/Mat", + [ + UsdPhysicsRigidBodyMaterialCfg(static_friction=0.7, dynamic_friction=0.6, restitution=0.1), + PhysxMaterialCfg(compliant_contact_stiffness=100.0, friction_combine_mode="max"), + ], + stage, + ) + assert prim.IsA(UsdShade.Material) + assert bool(UsdPhysics.MaterialAPI(prim)) # neutral anchor applied by the writer + assert prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.7) + assert prim.GetAttribute("physics:dynamicFriction").Get() == pytest.approx(0.6) + assert prim.GetAttribute("physics:restitution").Get() == pytest.approx(0.1) + # the PhysX fragment applied its own schema and namespace + assert "PhysxMaterialAPI" in prim.GetAppliedSchemas() + assert prim.GetAttribute("physxMaterial:compliantContactStiffness").Get() == pytest.approx(100.0) + assert prim.GetAttribute("physxMaterial:frictionCombineMode").Get() == "max" + + +def test_spawn_rigid_body_material_from_fragments_accepts_single_fragment(): + from isaaclab.sim.spawners.materials.physics_materials import spawn_rigid_body_material_from_fragments + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + prim = spawn_rigid_body_material_from_fragments( + "/World/Mat2", UsdPhysicsRigidBodyMaterialCfg(static_friction=0.3), stage + ) + assert prim.IsA(UsdShade.Material) + assert bool(UsdPhysics.MaterialAPI(prim)) + assert prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.3) + + +def test_spawn_physics_material_dispatches_fragments_and_legacy(): + """The shared dispatcher handles both a rigid-body fragment collection and a legacy material + cfg carrying its own ``func``.""" + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import PhysxRigidBodyMaterialCfg + + from isaaclab.sim.spawners.materials.physics_materials import spawn_physics_material + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + + # tuple form is accepted by the low-level dispatcher alongside the list form used by cfg slots + frag_prim = spawn_physics_material("/World/MaterialA", (UsdPhysicsRigidBodyMaterialCfg(static_friction=0.4),)) + assert bool(UsdPhysics.MaterialAPI(frag_prim)) + assert frag_prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.4) + + # legacy single-cfg form (RigidBodyMaterialBaseCfg subclass with its own spawner func) + legacy_prim = spawn_physics_material("/World/MaterialB", PhysxRigidBodyMaterialCfg(static_friction=0.9)) + assert bool(UsdPhysics.MaterialAPI(legacy_prim)) + assert legacy_prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.9) + + +def test_spawn_physics_material_rejects_non_current_stage_for_legacy(): + """The legacy path is current-stage-bound; an explicit different stage raises instead of + silently authoring on the current stage. Passing the current stage explicitly stays valid + (the in-tree spawners do so unconditionally).""" + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import PhysxRigidBodyMaterialCfg + + from pxr import Usd + + from isaaclab.sim.spawners.materials import spawn_physics_material + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + other = Usd.Stage.CreateInMemory() + with pytest.raises(ValueError, match="current stage"): + spawn_physics_material("/World/MatOther", PhysxRigidBodyMaterialCfg(), stage=other) + # nothing leaked onto the current stage + assert not sim_utils.get_current_stage().GetPrimAtPath("/World/MatOther").IsValid() + # explicit current stage remains supported + prim = spawn_physics_material("/World/MatCurrent", PhysxRigidBodyMaterialCfg(), stage=sim_utils.get_current_stage()) + assert prim.IsValid() + + +def test_fragment_writer_validates_inputs_before_authoring(): + """Direct and dispatched fragment calls share one validation contract and do not leave prims.""" + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import PhysxRigidBodyMaterialCfg + + from isaaclab.sim.spawners.materials.physics_materials import ( + spawn_physics_material, + spawn_rigid_body_material_from_fragments, + ) + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + + with pytest.raises(ValueError): + spawn_rigid_body_material_from_fragments("/World/MatEmpty", [], stage) + # a list mixing a fragment with a legacy cfg is not a valid fragment list + with pytest.raises(TypeError): + spawn_physics_material( + "/World/MatMixed", + [UsdPhysicsRigidBodyMaterialCfg(static_friction=0.4), PhysxRigidBodyMaterialCfg(static_friction=0.9)], + ) + with pytest.raises(TypeError): + spawn_rigid_body_material_from_fragments("/World/MatLegacy", PhysxRigidBodyMaterialCfg(), stage) + with pytest.raises(TypeError): + spawn_physics_material("/World/MatInvalid", object()) + for path in ("MatEmpty", "MatMixed", "MatLegacy", "MatInvalid"): + assert not stage.GetPrimAtPath(f"/World/{path}").IsValid() + + +def test_spawn_rigid_body_material_from_fragments_leaves_none_fields_unwritten(): + from isaaclab.sim.spawners.materials.physics_materials import spawn_rigid_body_material_from_fragments + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + prim = spawn_rigid_body_material_from_fragments( + "/World/Mat3", [UsdPhysicsRigidBodyMaterialCfg(static_friction=0.5)], stage + ) + # only the authored field is written; None fields are left unauthored (partial update) + assert prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.5) + assert not prim.GetAttribute("physics:dynamicFriction").HasAuthoredValue() + + +# ------------------------------------------------------------------------------------- +# UsdPhysicsRigidBodyMaterialCfg: density round-trip + physics:* schema parity +# ------------------------------------------------------------------------------------- + + +def test_usd_physics_rigid_body_material_density_round_trips(): + """``physics:density`` participates in mass computation via material binding; it must author + the same as the other ``UsdPhysics.MaterialAPI`` friction/restitution fields.""" + from isaaclab.sim.spawners.materials.physics_materials import spawn_rigid_body_material_from_fragments + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + prim = spawn_rigid_body_material_from_fragments( + "/World/MatDensity", [UsdPhysicsRigidBodyMaterialCfg(density=1200.0)], stage + ) + assert prim.GetAttribute("physics:density").Get() == pytest.approx(1200.0) + + +def test_usd_physics_rigid_body_material_fragment_matches_material_api_schema(): + """Schema-parity guard: the set of ``physics:*`` attrs the neutral fragment can author must + equal the attribute set on ``UsdPhysics.MaterialAPI`` (4 attrs: static/dynamic friction, + restitution, density). Catches drift if the schema gains/loses an attribute.""" + import dataclasses + + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + from isaaclab.utils.string import to_camel_case + + fragment_fields = {f.name for f in dataclasses.fields(UsdPhysicsRigidBodyMaterialCfg) if f.name != "func"} + schema_attr_names = {name.split(":", 1)[1] for name in UsdPhysics.MaterialAPI.GetSchemaAttributeNames()} + fragment_attr_names = {to_camel_case(name, "cC") for name in fragment_fields} + assert fragment_attr_names == schema_attr_names + + +# ------------------------------------------------------------------------------------- +# PhysxMaterialCfg: damping-combine-mode + compliant-contact-acceleration-spring +# ------------------------------------------------------------------------------------- + + +def test_physx_material_fragment_authors_damping_combine_mode_and_acceleration_spring(): + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import PhysxMaterialCfg + + from isaaclab.sim.spawners.materials.physics_materials import spawn_rigid_body_material_from_fragments + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + prim = spawn_rigid_body_material_from_fragments( + "/World/MatPhysxExtra", + [PhysxMaterialCfg(damping_combine_mode="min", compliant_contact_acceleration_spring=True)], + stage, + ) + assert "PhysxMaterialAPI" in prim.GetAppliedSchemas() + assert prim.GetAttribute("physxMaterial:dampingCombineMode").Get() == "min" + assert prim.GetAttribute("physxMaterial:compliantContactAccelerationSpring").Get() is True + + +# ------------------------------------------------------------------------------------- +# Finding 4: mesh spawner must accept a fragment list for a rigid physics_material +# ------------------------------------------------------------------------------------- + + +def test_spawn_mesh_with_rigid_props_accepts_fragment_list_physics_material(): + """Regression test: the rigid-vs-deformable material guard in the mesh spawner used to reject + a fragment / fragment-list ``physics_material`` outright. A rigid-body fragment list must spawn + and bind successfully.""" + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + from isaaclab.sim.spawners.meshes.meshes_cfg import MeshCuboidCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + cfg = MeshCuboidCfg( + size=(1.0, 1.0, 1.0), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=[UsdPhysicsRigidBodyMaterialCfg(static_friction=0.65, dynamic_friction=0.55)], + ) + prim = cfg.func("/World/MeshCubeFrag", cfg, stage=stage) + assert prim.IsValid() + material_prim = stage.GetPrimAtPath("/World/MeshCubeFrag/geometry/material") + assert material_prim.IsValid() + assert bool(UsdPhysics.MaterialAPI(material_prim)) + assert material_prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.65) + # material binding: the mesh prim carries a physics-purpose material binding + binding_api = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/MeshCubeFrag/geometry/mesh")) + bound_material, _ = binding_api.ComputeBoundMaterial(materialPurpose="physics") + assert bound_material.GetPath() == material_prim.GetPath() + + +# ------------------------------------------------------------------------------------- +# Finding 5: ground-plane spawner must accept a fragment-list physics_material +# ------------------------------------------------------------------------------------- + + +def test_spawn_ground_plane_accepts_fragment_list_physics_material(): + from isaaclab.sim.spawners.from_files.from_files_cfg import GroundPlaneCfg + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + cfg = GroundPlaneCfg(physics_material=[UsdPhysicsRigidBodyMaterialCfg(static_friction=0.42)]) + prim = cfg.func("/World/groundPlane", cfg) + assert prim.IsValid() + material_prim = stage.GetPrimAtPath("/World/groundPlane/physicsMaterial") + assert material_prim.IsValid() + assert bool(UsdPhysics.MaterialAPI(material_prim)) + assert material_prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.42) + # the collision (Plane) prim under the ground plane must bind to the spawned material + from isaaclab.sim.utils import get_first_matching_child_prim + + collision_prim = get_first_matching_child_prim( + "/World/groundPlane", predicate=lambda _prim: _prim.GetTypeName() == "Plane", stage=stage + ) + assert collision_prim is not None + binding_api = UsdShade.MaterialBindingAPI(collision_prim) + bound_material, _ = binding_api.ComputeBoundMaterial(materialPurpose="physics") + assert bound_material.GetPath() == material_prim.GetPath() + + +# ------------------------------------------------------------------------------------- +# Regression: the mesh spawner's rigid-material guard must also accept legacy (non-fragment) +# rigid-body material cfgs, not just the deprecated ``RigidBodyMaterialCfg`` alias. +# ------------------------------------------------------------------------------------- + + +def test_spawn_mesh_with_rigid_props_accepts_legacy_physx_rigid_body_material(): + """Regression test: the mesh guard used to check ``isinstance(cfg.physics_material, + RigidBodyMaterialCfg)`` -- the deprecated PhysX leaf alias -- which rejected the canonical + legacy :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg` even though + :func:`~isaaclab.sim.spawners.materials.spawn_physics_material` accepts it.""" + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import PhysxRigidBodyMaterialCfg + + from isaaclab.sim.spawners.meshes.meshes_cfg import MeshCuboidCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + cfg = MeshCuboidCfg( + size=(1.0, 1.0, 1.0), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=PhysxRigidBodyMaterialCfg(static_friction=0.65, dynamic_friction=0.55), + ) + prim = cfg.func("/World/MeshCubeLegacyPhysx", cfg, stage=stage) + assert prim.IsValid() + material_prim = stage.GetPrimAtPath("/World/MeshCubeLegacyPhysx/geometry/material") + assert material_prim.IsValid() + assert bool(UsdPhysics.MaterialAPI(material_prim)) + assert material_prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.65) + binding_api = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/MeshCubeLegacyPhysx/geometry/mesh")) + bound_material, _ = binding_api.ComputeBoundMaterial(materialPurpose="physics") + assert bound_material.GetPath() == material_prim.GetPath() + + +def test_spawn_mesh_with_rigid_props_accepts_legacy_newton_material(): + """Same regression as above for Newton's legacy rigid-body material cfg, which also derives + from :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg` (not the deprecated + PhysX ``RigidBodyMaterialCfg`` alias) and must not be rejected by the mesh guard.""" + from isaaclab_newton.sim.schemas import NewtonMaterialPropertiesCfg + + from isaaclab.sim.spawners.meshes.meshes_cfg import MeshCuboidCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + stage = sim_utils.get_current_stage() + cfg = MeshCuboidCfg( + size=(1.0, 1.0, 1.0), + rigid_props=sim_utils.RigidBodyPropertiesCfg(), + collision_props=sim_utils.CollisionPropertiesCfg(), + physics_material=NewtonMaterialPropertiesCfg(torsional_friction=0.3, rolling_friction=0.001), + ) + prim = cfg.func("/World/MeshCubeLegacyNewton", cfg, stage=stage) + assert prim.IsValid() + material_prim = stage.GetPrimAtPath("/World/MeshCubeLegacyNewton/geometry/material") + assert material_prim.IsValid() + assert bool(UsdPhysics.MaterialAPI(material_prim)) + assert material_prim.GetAttribute("newton:torsionalFriction").Get() == pytest.approx(0.3) + assert material_prim.GetAttribute("newton:rollingFriction").Get() == pytest.approx(0.001) + binding_api = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/MeshCubeLegacyNewton/geometry/mesh")) + bound_material, _ = binding_api.ComputeBoundMaterial(materialPurpose="physics") + assert bound_material.GetPath() == material_prim.GetPath() + + +# ------------------------------------------------------------------------------------- +# PhysxRigidBodyMaterialCfg (legacy): damping-combine-mode + compliant-contact-acceleration-spring +# ------------------------------------------------------------------------------------- + + +def test_legacy_physx_rigid_body_material_authors_damping_combine_mode_and_acceleration_spring(): + """The legacy :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg` must + author the same two ``physxMaterial:*`` attributes as the + :class:`~isaaclab_physx.sim.spawners.materials.PhysxMaterialCfg` fragment, since the legacy + spawner is metadata-driven off the same ``physxMaterial`` namespace.""" + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import PhysxRigidBodyMaterialCfg + + from isaaclab.sim.spawners.materials import spawn_rigid_body_material + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + cfg = PhysxRigidBodyMaterialCfg(damping_combine_mode="min", compliant_contact_acceleration_spring=True) + prim = spawn_rigid_body_material("/World/MatLegacyPhysxExtra", cfg) + assert "PhysxMaterialAPI" in prim.GetAppliedSchemas() + assert prim.GetAttribute("physxMaterial:dampingCombineMode").Get() == "min" + assert prim.GetAttribute("physxMaterial:compliantContactAccelerationSpring").Get() is True + + +# ------------------------------------------------------------------------------------- +# Generated-terrain routing: create_prim_from_mesh must accept a fragment-list physics_material +# ------------------------------------------------------------------------------------- + + +def test_create_prim_from_mesh_accepts_fragment_list(): + """Generated terrain routes its material through the dispatcher, so a fragment list works + end-to-end instead of crashing on the legacy-only spawn path.""" + import trimesh + from isaaclab_newton.sim.spawners.materials.physics_materials_cfg import NewtonMaterialCfg + + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + from isaaclab.terrains.utils import create_prim_from_mesh + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + mesh = trimesh.creation.box(extents=(1.0, 1.0, 0.2)) + create_prim_from_mesh( + "/World/terrainFrag", + mesh, + physics_material=[UsdPhysicsRigidBodyMaterialCfg(static_friction=0.9), NewtonMaterialCfg(rolling_friction=0.1)], + ) + stage = sim_utils.get_current_stage() + mat = stage.GetPrimAtPath("/World/terrainFrag/physicsMaterial") + assert mat.IsValid() + assert mat.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.9) + assert mat.GetAttribute("newton:rollingFriction").Get() == pytest.approx(0.1) + + +def test_legacy_base_cfg_authors_density(): + """The legacy rigid material base authors ``physics:density``, matching the USD fragment. + + ``UsdPhysics.MaterialAPI`` defines four properties; explicitly set values must be available + through both interfaces, including material density read by Newton's importer. + """ + from isaaclab.sim.spawners.materials import spawn_rigid_body_material + from isaaclab.sim.spawners.materials.physics_materials_cfg import RigidBodyMaterialBaseCfg + + sim_utils.create_new_stage() + SimulationContext(SimulationCfg(dt=0.01)) + prim = spawn_rigid_body_material("/World/LegacyDensity", RigidBodyMaterialBaseCfg(density=800.0)) + assert prim.GetAttribute("physics:density").Get() == pytest.approx(800.0) + # None default -> unauthored (backward compatible) + prim2 = spawn_rigid_body_material("/World/LegacyDensityNone", RigidBodyMaterialBaseCfg()) + assert not prim2.GetAttribute("physics:density").HasAuthoredValue() + + +def test_public_default_material_types_remain_backward_compatible(): + """Fragment support must not silently replace the released default config objects.""" + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import RigidBodyMaterialCfg + + from isaaclab.sim.spawners.from_files.from_files_cfg import GroundPlaneCfg + from isaaclab.terrains.terrain_importer_cfg import TerrainImporterCfg + + defaults = ( + SimulationCfg().physics_material, + GroundPlaneCfg().physics_material, + TerrainImporterCfg(prim_path="/World/terrain").physics_material, + ) + assert all(type(material) is RigidBodyMaterialCfg for material in defaults) + + +def test_physx_fragment_and_legacy_cfg_match_material_api_schema(): + """Both PhysX interfaces cover the properties declared by ``PhysxMaterialAPI``.""" + import dataclasses + + from isaaclab_physx.sim.spawners.materials.physics_materials_cfg import ( + PhysxMaterialCfg, + PhysxRigidBodyMaterialCfg, + ) + + from pxr import PhysxSchema + + from isaaclab.sim.spawners.materials.physics_materials_cfg import RigidBodyMaterialBaseCfg + from isaaclab.utils.string import to_camel_case + + def fields(cls): + return {f.name for f in dataclasses.fields(cls) if f.name != "func"} + + base = fields(RigidBodyMaterialBaseCfg) + schema_attrs = {name.split(":", 1)[1] for name in PhysxSchema.PhysxMaterialAPI.GetSchemaAttributeNames()} + fragment_attrs = {to_camel_case(name, "cC") for name in fields(PhysxMaterialCfg)} + legacy_attrs = {to_camel_case(name, "cC") for name in fields(PhysxRigidBodyMaterialCfg) - base} + assert fragment_attrs == schema_attrs + assert legacy_attrs == schema_attrs + + +# ------------------------------------------------------------------------------------- +# Slot-typing contract +# ------------------------------------------------------------------------------------- + + +def test_material_slot_unions_match_spawner_kind(): + """Structural slot typing: rigid-only spawner slots admit the rigid base + fragments and + exclude the deformable-admitting root; mixed spawners keep the broad root. New slots added + to this list keep the contract enforced.""" + import sys + import typing + + from isaaclab.sim.spawners.from_files.from_files_cfg import FileCfg, GroundPlaneCfg + from isaaclab.sim.spawners.materials import physics_materials_cfg as mats + from isaaclab.sim.spawners.meshes.meshes_cfg import MeshCfg + from isaaclab.sim.spawners.shapes.shapes_cfg import ShapeCfg + from isaaclab.terrains.terrain_importer_cfg import TerrainImporterCfg + + def union_args(cls): + # typing.get_type_hints(cls) resolves annotations across the whole MRO, including the + # inherited ``func: Callable[..., Usd.Prim]`` from ``SpawnerCfg``, whose ``Usd`` import is + # TYPE_CHECKING-only and unresolvable at runtime. Evaluate the ``physics_material`` + # annotation directly against its declaring class's module globals instead -- each class + # in this list declares the field itself, so this never needs the base class's namespace. + annotation = cls.__dict__["__annotations__"]["physics_material"] + resolved = eval(annotation, vars(sys.modules[cls.__module__])) + return set(typing.get_args(resolved)) + + for cls in (ShapeCfg, GroundPlaneCfg, TerrainImporterCfg): + args = union_args(cls) + assert mats.RigidBodyMaterialBaseCfg in args, f"{cls.__name__} must admit the rigid base" + assert mats.RigidBodyMaterialFragment in args, f"{cls.__name__} must admit fragments" + assert mats.PhysicsMaterialCfg not in args, f"{cls.__name__} is rigid-only" + for cls in (FileCfg, MeshCfg): + args = union_args(cls) + assert mats.PhysicsMaterialCfg in args, f"{cls.__name__} spawns deformables too" + assert mats.RigidBodyMaterialFragment in args diff --git a/source/isaaclab_newton/changelog.d/vidurv-schema-frag-materials.minor.rst b/source/isaaclab_newton/changelog.d/vidurv-schema-frag-materials.minor.rst new file mode 100644 index 000000000000..977d1590eca7 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/vidurv-schema-frag-materials.minor.rst @@ -0,0 +1,21 @@ +Added +^^^^^ + +* Added :class:`~isaaclab_newton.sim.spawners.materials.NewtonMaterialCfg`, a single-namespace + ``newton`` rigid-body physics-material fragment (torsional and rolling friction) backing + ``NewtonMaterialAPI``. Composes with other rigid-body material fragments (e.g. + :class:`~isaaclab.sim.spawners.materials.UsdPhysicsRigidBodyMaterialCfg`) in a fragment list. +* Added :attr:`~isaaclab_newton.sim.spawners.materials.NewtonMaterialCfg.contact_stiffness`, + :attr:`~isaaclab_newton.sim.spawners.materials.NewtonMaterialCfg.contact_damping`, + :attr:`~isaaclab_newton.sim.spawners.materials.NewtonMaterialCfg.contact_friction_gain`, and + :attr:`~isaaclab_newton.sim.spawners.materials.NewtonMaterialCfg.contact_adhesion` (writing + ``newton:contactStiffness``, ``newton:contactDamping``, ``newton:contactFrictionGain``, and + ``newton:contactAdhesion``), matching the per-material contact attributes Newton's USD schema + resolver reads in place of the deprecated per-shape ``ke``/``kd``/``kf``/``ka`` parameters. +* Added the contact attributes + (:attr:`~isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg.contact_stiffness`, + :attr:`~isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg.contact_damping`, + :attr:`~isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg.contact_friction_gain`, and + :attr:`~isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg.contact_adhesion`) to + :class:`~isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg`, matching + :class:`~isaaclab_newton.sim.spawners.materials.NewtonMaterialCfg`. diff --git a/source/isaaclab_newton/isaaclab_newton/sim/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/sim/__init__.pyi index 27677fbd6dbf..1e684304e810 100644 --- a/source/isaaclab_newton/isaaclab_newton/sim/__init__.pyi +++ b/source/isaaclab_newton/isaaclab_newton/sim/__init__.pyi @@ -7,6 +7,7 @@ __all__ = [ "NewtonDeformableBodyPropertiesCfg", "NewtonDeformableBodyMaterialCfg", "NewtonDeformableMaterialCfg", + "NewtonMaterialCfg", "NewtonSurfaceDeformableBodyMaterialCfg", "MPMGridCfg", "MPMParticleMaterialCfg", @@ -22,6 +23,7 @@ from .schemas import NewtonDeformableBodyPropertiesCfg from .spawners.materials import ( NewtonDeformableBodyMaterialCfg, NewtonDeformableMaterialCfg, + NewtonMaterialCfg, NewtonSurfaceDeformableBodyMaterialCfg, ) from .spawners.mpm import MPMGridCfg, MPMParticleMaterialCfg, MPMParticleSpawnerCfg, MPMPointsCfg diff --git a/source/isaaclab_newton/isaaclab_newton/sim/schemas/schemas_cfg.py b/source/isaaclab_newton/isaaclab_newton/sim/schemas/schemas_cfg.py index 05d63921efde..86485af3aa7f 100644 --- a/source/isaaclab_newton/isaaclab_newton/sim/schemas/schemas_cfg.py +++ b/source/isaaclab_newton/isaaclab_newton/sim/schemas/schemas_cfg.py @@ -501,6 +501,35 @@ class NewtonMaterialPropertiesCfg(RigidBodyMaterialBaseCfg): Range: [0, inf). """ + contact_stiffness: float | None = None + """Contact normal-force stiffness [N/m]. + + Writes ``newton:contactStiffness``. Replaces the deprecated per-shape ``ke`` contact parameter; + used by the SemiImplicit, Featherstone, MuJoCo, and VBD solvers. + """ + + contact_damping: float | None = None + """Contact normal-force damping coefficient [N·s/m]. + + Writes ``newton:contactDamping``. Replaces the deprecated per-shape ``kd`` contact parameter; + used by the SemiImplicit, Featherstone, MuJoCo, and VBD solvers. + """ + + contact_friction_gain: float | None = None + """Friction-force stiffness gain used by the tangential (friction) contact response [N·s/m]. + + Writes ``newton:contactFrictionGain``. Replaces the deprecated per-shape ``kf`` contact + parameter; used by the SemiImplicit and Featherstone solvers. + """ + + contact_adhesion: float | None = None + """Contact adhesion distance: shapes closer than this threshold experience an attractive + (adhesive) force [m]. + + Writes ``newton:contactAdhesion``. Replaces the deprecated per-shape ``ka`` contact parameter; + used by the SemiImplicit and Featherstone solvers. + """ + @configclass class MujocoFixedTendonCfg(FixedTendonFragment): diff --git a/source/isaaclab_newton/isaaclab_newton/sim/spawners/materials/__init__.pyi b/source/isaaclab_newton/isaaclab_newton/sim/spawners/materials/__init__.pyi index c3f13216f781..5ee626b240bd 100644 --- a/source/isaaclab_newton/isaaclab_newton/sim/spawners/materials/__init__.pyi +++ b/source/isaaclab_newton/isaaclab_newton/sim/spawners/materials/__init__.pyi @@ -7,6 +7,7 @@ __all__ = [ "spawn_deformable_body_material", "NewtonDeformableBodyMaterialCfg", "NewtonDeformableMaterialCfg", + "NewtonMaterialCfg", "NewtonSurfaceDeformableBodyMaterialCfg", ] @@ -14,5 +15,6 @@ from .physics_materials import spawn_deformable_body_material from .physics_materials_cfg import ( NewtonDeformableBodyMaterialCfg, NewtonDeformableMaterialCfg, + NewtonMaterialCfg, NewtonSurfaceDeformableBodyMaterialCfg, ) diff --git a/source/isaaclab_newton/isaaclab_newton/sim/spawners/materials/physics_materials_cfg.py b/source/isaaclab_newton/isaaclab_newton/sim/spawners/materials/physics_materials_cfg.py index f7b63a8701c6..e0027a815530 100644 --- a/source/isaaclab_newton/isaaclab_newton/sim/spawners/materials/physics_materials_cfg.py +++ b/source/isaaclab_newton/isaaclab_newton/sim/spawners/materials/physics_materials_cfg.py @@ -10,6 +10,7 @@ from isaaclab.sim.spawners.materials.physics_materials_cfg import ( DeformableBodyMaterialBaseCfg, + RigidBodyMaterialFragment, SurfaceDeformableBodyMaterialBaseCfg, ) from isaaclab.utils.configclass import configclass @@ -77,3 +78,73 @@ class NewtonSurfaceDeformableBodyMaterialCfg(SurfaceDeformableBodyMaterialBaseCf edge_kd: float = 1e-2 """Bending damping [N*m*s]. Used by Newton backend for cloth meshes.""" + + +@configclass +class NewtonMaterialCfg(RigidBodyMaterialFragment): + """``newton:*`` rigid-body material attributes read by Newton's USD material schema resolver. + + Single-namespace fragment (see + :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment`) for the Newton-only + friction knobs (torsional and rolling friction) and the per-material contact model (contact + stiffness/damping, friction gain, adhesion) that replaces the deprecated per-shape + ``ke``/``kd``/``kf``/``ka`` parameters. The ``NewtonMaterialAPI`` schema is applied (and the + ``newton:*`` attributes authored) by the generic :func:`~isaaclab.sim.schemas.apply_namespaced` + writer. ``None`` fields are left unchanged. + + .. note:: + The generated ``NewtonMaterialAPI`` USD schema currently only declares the two friction + attributes; the four contact attributes are still authored as raw ``newton:*`` USD + attributes and are read directly by Newton's schema resolver. + + Composes with other rigid-body material fragments (e.g. + :class:`~isaaclab.sim.spawners.materials.UsdPhysicsRigidBodyMaterialCfg`) in the same fragment + list passed to + :func:`~isaaclab.sim.spawners.materials.spawn_rigid_body_material_from_fragments`. For the + legacy (non-fragment) equivalent, see + :class:`~isaaclab_newton.sim.schemas.NewtonMaterialPropertiesCfg`. + """ + + _usd_namespace: ClassVar[str | None] = "newton" + _usd_applied_schema: ClassVar[str | None] = "NewtonMaterialAPI" + + torsional_friction: float | None = None + """Torsional friction coefficient (resistance to spinning at a contact point) [dimensionless]. + + Writes ``newton:torsionalFriction``. Range: [0, inf). + """ + + rolling_friction: float | None = None + """Rolling friction coefficient (resistance to rolling motion) [dimensionless]. + + Writes ``newton:rollingFriction``. Range: [0, inf). + """ + + contact_stiffness: float | None = None + """Contact normal-force stiffness [N/m]. + + Writes ``newton:contactStiffness``. Replaces the deprecated per-shape ``ke`` contact parameter; + used by the SemiImplicit, Featherstone, MuJoCo, and VBD solvers. + """ + + contact_damping: float | None = None + """Contact normal-force damping coefficient [N·s/m]. + + Writes ``newton:contactDamping``. Replaces the deprecated per-shape ``kd`` contact parameter; + used by the SemiImplicit, Featherstone, MuJoCo, and VBD solvers. + """ + + contact_friction_gain: float | None = None + """Friction-force stiffness gain used by the tangential (friction) contact response [N·s/m]. + + Writes ``newton:contactFrictionGain``. Replaces the deprecated per-shape ``kf`` contact + parameter; used by the SemiImplicit and Featherstone solvers. + """ + + contact_adhesion: float | None = None + """Contact adhesion distance: shapes closer than this threshold experience an attractive + (adhesive) force [m]. + + Writes ``newton:contactAdhesion``. Replaces the deprecated per-shape ``ka`` contact parameter; + used by the SemiImplicit and Featherstone solvers. + """ diff --git a/source/isaaclab_newton/test/sim/test_newton_schemas.py b/source/isaaclab_newton/test/sim/test_newton_schemas.py index 1774792d3d03..0f78c8e39507 100644 --- a/source/isaaclab_newton/test/sim/test_newton_schemas.py +++ b/source/isaaclab_newton/test/sim/test_newton_schemas.py @@ -164,6 +164,72 @@ def test_newton_material_no_schema_when_none(setup_sim): assert "NewtonMaterialAPI" not in prim.GetAppliedSchemas() +@pytest.mark.isaacsim_ci +def test_newton_material_fragment_composes_with_usd_physics_fragment(setup_sim): + """NewtonMaterialCfg is a rigid-body material fragment (backend symmetry with the PhysX + fragment): it must compose in a fragment list with UsdPhysicsRigidBodyMaterialCfg and author + both the ``newton:*`` and solver-common ``physics:*`` namespaces on the same material prim.""" + from isaaclab_newton.sim.spawners.materials import NewtonMaterialCfg + + from isaaclab.sim.spawners.materials.physics_materials import spawn_rigid_body_material_from_fragments + from isaaclab.sim.spawners.materials.physics_materials_cfg import UsdPhysicsRigidBodyMaterialCfg + + prim = spawn_rigid_body_material_from_fragments( + "/World/newton_mat_frag", + [ + UsdPhysicsRigidBodyMaterialCfg(static_friction=0.6, dynamic_friction=0.5), + NewtonMaterialCfg(torsional_friction=0.3, rolling_friction=0.001), + ], + ) + assert bool(UsdPhysics.MaterialAPI(prim)) + assert prim.GetAttribute("physics:staticFriction").Get() == pytest.approx(0.6) + assert prim.GetAttribute("physics:dynamicFriction").Get() == pytest.approx(0.5) + assert "NewtonMaterialAPI" in prim.GetAppliedSchemas() + assert prim.GetAttribute("newton:torsionalFriction").Get() == pytest.approx(0.3) + assert prim.GetAttribute("newton:rollingFriction").Get() == pytest.approx(0.001) + + +@pytest.mark.isaacsim_ci +def test_newton_material_fragment_authors_all_six_newton_attrs(setup_sim): + """Regression test: Newton's USD material schema resolver (``SchemaResolverNewton``) reads six + ``newton:*`` material attributes -- the two friction knobs plus four contact-model attributes + (``contactStiffness``/``contactDamping``/``contactFrictionGain``/``contactAdhesion``) that + replace the deprecated per-shape ``ke``/``kd``/``kf``/``ka`` parameters. All six must round-trip + through :class:`~isaaclab_newton.sim.spawners.materials.NewtonMaterialCfg`, even though the + generated ``NewtonMaterialAPI`` schema currently only declares the two friction attributes.""" + from isaaclab_newton.sim.spawners.materials import NewtonMaterialCfg + from newton._src.usd.schema_resolver import PrimType + from newton._src.usd.schemas import SchemaResolverNewton + + from isaaclab.sim.spawners.materials import spawn_rigid_body_material_from_fragments + + prim = spawn_rigid_body_material_from_fragments( + "/World/newton_mat_contact", + NewtonMaterialCfg( + torsional_friction=0.3, + rolling_friction=0.001, + contact_stiffness=2500.0, + contact_damping=100.0, + contact_friction_gain=1000.0, + contact_adhesion=0.01, + ), + ) + expected = { + "mu_torsional": 0.3, + "mu_rolling": 0.001, + "ke": 2500.0, + "kd": 100.0, + "kf": 1000.0, + "ka": 0.01, + } + + assert "NewtonMaterialAPI" in prim.GetAppliedSchemas() + resolver = SchemaResolverNewton() + assert set(resolver.mapping[PrimType.MATERIAL]) == set(expected) + for key, value in expected.items(): + assert resolver.get_value(prim, PrimType.MATERIAL, key) == pytest.approx(value) + + # --------------------------------------------------------------------------- # Newton articulation root # --------------------------------------------------------------------------- @@ -347,3 +413,16 @@ def test_newton_mesh_collision_mixed_namespace_write(setup_sim): applied = prim.GetAppliedSchemas() assert "NewtonCollisionAPI" in applied assert "NewtonMeshCollisionAPI" in applied + + +@pytest.mark.isaacsim_ci +def test_newton_legacy_cfg_authors_contact_attrs(setup_sim): + """The legacy Newton material cfg authors all newton:* attributes the fragment authors.""" + mat_cfg = NewtonMaterialPropertiesCfg( + contact_stiffness=1.0e4, contact_damping=250.0, contact_friction_gain=40.0, contact_adhesion=0.02 + ) + prim = spawn_rigid_body_material("/World/newton_mat_contact", mat_cfg) + assert prim.GetAttribute("newton:contactStiffness").Get() == pytest.approx(1.0e4) + assert prim.GetAttribute("newton:contactDamping").Get() == pytest.approx(250.0) + assert prim.GetAttribute("newton:contactFrictionGain").Get() == pytest.approx(40.0) + assert prim.GetAttribute("newton:contactAdhesion").Get() == pytest.approx(0.02) diff --git a/source/isaaclab_physx/changelog.d/vidurv-schema-frag-materials.minor.rst b/source/isaaclab_physx/changelog.d/vidurv-schema-frag-materials.minor.rst new file mode 100644 index 000000000000..b580d3ad6316 --- /dev/null +++ b/source/isaaclab_physx/changelog.d/vidurv-schema-frag-materials.minor.rst @@ -0,0 +1,12 @@ +Added +^^^^^ + +* Added :class:`~isaaclab_physx.sim.spawners.materials.PhysxMaterialCfg`, a single-namespace + ``physxMaterial`` rigid-body physics-material fragment (compliant-contact spring stiffness/damping + and the friction/restitution combine-mode tokens) backing ``PhysxMaterialAPI``. +* Added :attr:`~isaaclab_physx.sim.spawners.materials.PhysxMaterialCfg.damping_combine_mode` (writes + ``physxMaterial:dampingCombineMode``) and + :attr:`~isaaclab_physx.sim.spawners.materials.PhysxMaterialCfg.compliant_contact_acceleration_spring` + (writes ``physxMaterial:compliantContactAccelerationSpring``), completing the fragment's coverage + of ``PhysxMaterialAPI``. Also added the same two fields to the legacy + :class:`~isaaclab_physx.sim.spawners.materials.PhysxRigidBodyMaterialCfg`. diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.pyi b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.pyi index 315458ea5d24..7a018a14ecd6 100644 --- a/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.pyi +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/__init__.pyi @@ -7,6 +7,7 @@ __all__ = [ "DeformableBodyMaterialCfg", "PhysXDeformableMaterialCfg", "PhysxDeformableBodyMaterialCfg", + "PhysxMaterialCfg", "PhysxRigidBodyMaterialCfg", "PhysxSurfaceDeformableBodyMaterialCfg", "RigidBodyMaterialCfg", @@ -17,6 +18,7 @@ from .physics_materials_cfg import ( DeformableBodyMaterialCfg, PhysXDeformableMaterialCfg, PhysxDeformableBodyMaterialCfg, + PhysxMaterialCfg, PhysxRigidBodyMaterialCfg, PhysxSurfaceDeformableBodyMaterialCfg, RigidBodyMaterialCfg, diff --git a/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials_cfg.py b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials_cfg.py index 345fadc88704..3560bc12bb3b 100644 --- a/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials_cfg.py +++ b/source/isaaclab_physx/isaaclab_physx/sim/spawners/materials/physics_materials_cfg.py @@ -12,6 +12,7 @@ from isaaclab.sim.spawners.materials.physics_materials_cfg import ( DeformableBodyMaterialBaseCfg, RigidBodyMaterialBaseCfg, + RigidBodyMaterialFragment, SurfaceDeformableBodyMaterialBaseCfg, ) from isaaclab.utils.configclass import configclass @@ -154,12 +155,13 @@ class PhysxRigidBodyMaterialCfg(RigidBodyMaterialBaseCfg): Extends :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialBaseCfg` with the `PhysxMaterialAPI`_ schema fields: compliant-contact spring (stiffness/damping) and the - friction/restitution combine-mode tokens. None of these fields have a Newton consumer - today; they are PhysX-engine-only knobs. + friction/restitution combine-mode tokens. Newton's USD importer also recognizes stiffness and + damping as fallback contact parameters; the acceleration-spring flag and combine modes are + PhysX-only. See :meth:`~isaaclab.sim.spawners.materials.spawn_rigid_body_material` for more information. - .. _PhysxMaterialAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/104.2/class_physx_schema_physx_material_a_p_i.html + .. _PhysxMaterialAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/latest/class_physx_schema_physx_material_a_p_i.html """ # -- Class metadata (not dataclass fields) -- @@ -172,14 +174,23 @@ class PhysxRigidBodyMaterialCfg(RigidBodyMaterialBaseCfg): """Spring stiffness for a compliant contact model using implicit springs. A higher stiffness results in behavior closer to a rigid contact. The compliant contact model - is only enabled if the stiffness is larger than 0. PhysX-only; not consumed by Newton. + is only enabled if the stiffness is larger than 0. Newton's USD importer also recognizes this + attribute as a fallback contact-stiffness value. """ compliant_contact_damping: float | None = None """Damping coefficient for a compliant contact model using implicit springs. Irrelevant if compliant contacts are disabled when :attr:`compliant_contact_stiffness` is set - to zero and rigid contacts are active. PhysX-only; not consumed by Newton. + to zero and rigid contacts are active. Newton's USD importer also recognizes this attribute as + a fallback contact-damping value. + """ + + compliant_contact_acceleration_spring: bool | None = None + """Whether the compliant contact spring is formulated in acceleration (rather than force) units. + + Only relevant when compliant contacts are enabled (:attr:`compliant_contact_stiffness` is + non-zero). PhysX-only; not consumed by Newton. """ friction_combine_mode: Literal["average", "min", "multiply", "max"] | None = None @@ -202,6 +213,73 @@ class PhysxRigidBodyMaterialCfg(RigidBodyMaterialBaseCfg): `__. """ + damping_combine_mode: Literal["average", "min", "multiply", "max"] | None = None + """Determines the way the (compliant-contact) damping coefficient is combined during collisions. + + .. attention:: + + When two physics materials with different combine modes collide, the combine mode with + the higher priority will be used. The priority order is provided `here + `__. + """ + + +@configclass +class PhysxMaterialCfg(RigidBodyMaterialFragment): + """``physxMaterial:*`` rigid-body material attributes from `PhysxMaterialAPI`_. + + Single-namespace fragment (see :class:`~isaaclab.sim.spawners.materials.RigidBodyMaterialFragment`) + for the PhysX material namespace: compliant-contact spring (stiffness/damping), which Newton's + USD importer can read as fallback contact parameters, plus PhysX-only acceleration-spring and + combine-mode knobs. The ``PhysxMaterialAPI`` schema is applied (and the ``physxMaterial:*`` + attributes authored) by the generic :func:`~isaaclab.sim.schemas.apply_namespaced` writer. + ``None`` fields are left unchanged. + + .. _PhysxMaterialAPI: https://docs.omniverse.nvidia.com/kit/docs/omni_usd_schema_physics/latest/class_physx_schema_physx_material_a_p_i.html + """ + + _usd_namespace: ClassVar[str | None] = "physxMaterial" + _usd_applied_schema: ClassVar[str | None] = "PhysxMaterialAPI" + + compliant_contact_stiffness: float | None = None + """Spring stiffness for a compliant contact model using implicit springs. + + A higher stiffness results in behavior closer to a rigid contact. The compliant contact model is + only enabled if the stiffness is larger than 0. Writes ``physxMaterial:compliantContactStiffness``. + """ + + compliant_contact_damping: float | None = None + """Damping coefficient for a compliant contact model using implicit springs. + + Irrelevant if compliant contacts are disabled (``compliant_contact_stiffness`` is zero). Writes + ``physxMaterial:compliantContactDamping``. + """ + + compliant_contact_acceleration_spring: bool | None = None + """Whether the compliant contact spring is formulated in acceleration (rather than force) units. + + Writes ``physxMaterial:compliantContactAccelerationSpring``. Only relevant when compliant + contacts are enabled (:attr:`compliant_contact_stiffness` is non-zero). + """ + + friction_combine_mode: Literal["average", "min", "multiply", "max"] | None = None + """How friction is combined during collisions. Writes ``physxMaterial:frictionCombineMode``.""" + + restitution_combine_mode: Literal["average", "min", "multiply", "max"] | None = None + """How restitution is combined during collisions. Writes ``physxMaterial:restitutionCombineMode``.""" + + damping_combine_mode: Literal["average", "min", "multiply", "max"] | None = None + """How the (compliant-contact) damping coefficient is combined during collisions. + + Writes ``physxMaterial:dampingCombineMode``. + + .. attention:: + + When two physics materials with different combine modes collide, the combine mode with + the higher priority will be used. The priority order is provided `here + `__. + """ + @configclass class RigidBodyMaterialCfg(PhysxRigidBodyMaterialCfg):