diff --git a/docs/source/api/lab_ov/isaaclab_ov.cloner.rst b/docs/source/api/lab_ov/isaaclab_ov.cloner.rst index 6d4467bb9b19..4fbb3a3bfb69 100644 --- a/docs/source/api/lab_ov/isaaclab_ov.cloner.rst +++ b/docs/source/api/lab_ov/isaaclab_ov.cloner.rst @@ -62,7 +62,7 @@ Shared mode uses early physics attachment without an additional flag: Populate original worlds and required render sources, then seal ordinal 1. Attach OVPhysX and wait. Execute native physics clones and wait before warmup. - Initialize asset and contact bindings, then acquire scene-data bindings. + Initialize assets, contacts and joint-wrench bindings, then acquire scene-data bindings. Clone remaining render prims, place environments, and seal rendering-only ordinal 2. Publish PHYSICS_READY for startup callbacks and camera preparation, then attach OVRTX during renderer preparation and continue normal rendering. @@ -102,15 +102,15 @@ Shared mode uses early physics attachment without an additional flag: Execute native physics clones Wait for completion Run physics warmup - Initialize asset and contact bindings - binding_init_event - Acquire scene-data bindings - Clone remaining render prims and place environments + Initialize physics consumers + Acquire scene-data bindings + Clone remaining render prims + Apply environment placement Seal ordinal 2 (rendering-only) Publish PHYSICS_READY - Startup callbacks and camera preparation can proceed - Attach OVRTX during renderer preparation - Continue normal rendering + Native physics queries and control writes are safe + Initialize cameras and renderer + Physics consumers already initialized @@ -119,25 +119,28 @@ Shared mode uses early physics attachment without an additional flag: #. Populate complete original worlds and required render sources in the shared OVStage, then seal ordinal 1. #. Attach OVPhysX to ordinal 1 and wait for attachment to complete. #. Execute native physics clones, wait for completion, and run physics warmup. - #. Initialize asset and contact bindings, then acquire scene-data bindings. + #. Initialize physics assets, contact sensors, and joint-wrench sensors, then acquire scene-data bindings. #. Clone the remaining render prims into the shared OVStage, apply environment placement, and seal ordinal 2. - #. Publish ``PHYSICS_READY``, allowing startup gravity callbacks and camera preparation to use the completed stage. - #. Attach OVRTX to the shared stage during renderer preparation and continue normal rendering. + #. Publish ``PHYSICS_READY`` for startup callbacks, ordinary sensors, and renderer preparation. + Startup gravity callbacks and camera preparation use the completed stage. + #. Continue normal rendering after OVRTX attaches during renderer preparation. CPU simulations populate all physics worlds before OVPhysX attachment and skip native physics cloning. Deferred render copies still populate any missing render-only prims at ordinal 2. -Sensors select their initialization phase through the -:attr:`~isaaclab.sensors.SensorBase.initialize_event` attribute. Ordinary sensors use ``PHYSICS_READY``; -OVPhysX contact sensors use the manager's earlier :attr:`~isaaclab.physics.PhysicsManager.binding_init_event`. -The earlier phase runs only when OVPhysX borrows a shared stage. Without a shared stage, asset and -contact initialization callbacks run together with ``PHYSICS_READY`` callbacks in priority order, -including on resets and forced reinitialization. - -``MODEL_INIT`` is a construction hook and may run before native handles exist. In OVPhysX it -runs during initial warmup and rebuilds. Binding callbacks also run on ordinary non-soft resets, -allowing late-created assets and contact sensors to initialize without replaying construction -callbacks. The two phases therefore remain separate even though they are adjacent during startup. +On borrowed/shared physics stages, OVPhysX directly prepares registered assets, contact sensors, +and joint-wrench sensors after native warmup and before deferred render copies. This internal +runtime preparation completes before public ``PHYSICS_READY`` callbacks run. Applications continue +to use ``PhysicsEvent.PHYSICS_READY`` with their existing callback priorities. Cameras and ordinary +sensors retain their existing readiness subscriptions. Owned stages retain their original callback +ordering. +Direct planned paths keep native binding acquisition efficient, including late-created consumers on +subsequent non-soft resets. The reserved render-copy ordinal is sealed before public callbacks run, +so initialization and control writes cannot consume it. + +``MODEL_INIT`` remains a construction hook and may run before native handles exist. In OVPhysX it +runs during initial warmup and rebuilds. Ordinary non-soft resets dispatch ``PHYSICS_READY`` again, +allowing late-created consumers to initialize without replaying construction callbacks. Later physics edits consume their exact update ordinals and exclude the render-copy ordinal 2. A failed render copy requires a stage rebuild before retry. A forced reset releases bindings before diff --git a/source/isaaclab/changelog.d/standard-physics-readiness.removed.rst b/source/isaaclab/changelog.d/standard-physics-readiness.removed.rst new file mode 100644 index 000000000000..173864160978 --- /dev/null +++ b/source/isaaclab/changelog.d/standard-physics-readiness.removed.rst @@ -0,0 +1,2 @@ +* Removed the unreleased internal binding-event plumbing from asset and sensor initialization. + Public ``PhysicsEvent.PHYSICS_READY`` subscriptions and callback priorities remained unchanged. diff --git a/source/isaaclab/isaaclab/assets/asset_base.py b/source/isaaclab/isaaclab/assets/asset_base.py index 151a344fef0c..cd7be0a464d8 100644 --- a/source/isaaclab/isaaclab/assets/asset_base.py +++ b/source/isaaclab/isaaclab/assets/asset_base.py @@ -67,7 +67,7 @@ class AssetBase(Asset, ABC): Unlike backend-specific interfaces (e.g. Isaac Sim PhysX) where one usually needs to call initialize explicitly, the asset class automatically initializes and invalidates physics handles when the simulation is ready or stopped. This is done by registering callbacks - for the backend's binding-initialization event (by default :attr:`PhysicsEvent.PHYSICS_READY`) + for physics initialization (by default :attr:`PhysicsEvent.PHYSICS_READY`) and :attr:`PhysicsEvent.STOP`. Additionally, the class registers a callback for debug visualization of the asset if a debug visualization @@ -371,14 +371,15 @@ def _register_callbacks(self): def _invoke(callback_name, event): getattr(obj_ref, callback_name)(event) - # Acquire native bindings in the backend's initialization phase, before public readiness if needed. + # Acquire native physics resources once the runtime is ready. self._initialize_handle = physics_mgr.register_callback( lambda payload: PhysicsManager.safe_callback_invoke( _invoke, "_initialize_callback", payload, backend_manager=physics_mgr ), - physics_mgr.binding_init_event, + PhysicsEvent.PHYSICS_READY, order=10, ) + physics_mgr._register_physics_consumer(self) self._invalidate_initialize_handle = physics_mgr.register_callback( lambda payload: PhysicsManager.safe_callback_invoke( _invoke, "_invalidate_initialize_callback", payload, backend_manager=physics_mgr @@ -402,8 +403,8 @@ def _initialize_callback(self, event): """Initializes the scene elements. .. note:: - The backend dispatches this callback once native physics handles are valid, no later - than :attr:`PhysicsEvent.PHYSICS_READY`. + Native physics handles must be valid. Backends may prepare this consumer + directly before publishing :attr:`PhysicsEvent.PHYSICS_READY`. """ if not self._is_initialized: self._backend = self._backend_manager.get_backend() diff --git a/source/isaaclab/isaaclab/physics/physics_manager.py b/source/isaaclab/isaaclab/physics/physics_manager.py index b1614511826a..b5459a9d15f5 100644 --- a/source/isaaclab/isaaclab/physics/physics_manager.py +++ b/source/isaaclab/isaaclab/physics/physics_manager.py @@ -44,13 +44,14 @@ class PhysicsEvent(Enum): """Physics model is being constructed. Fired during scene building, before simulation can run. Use this to register physics representations (rigid bodies, joints, constraints) with the solver. - Native handles need not be available yet; this event does not imply binding readiness. + Native handles need not be available yet; this event does not imply runtime readiness. """ PHYSICS_READY = "physics_ready" """Physics is initialized and queryable. Fired after all physics data structures are created and the simulation is - ready to step. Assets can now read initial state (positions, velocities). + ready to step. Native handles and state buffers are available to callbacks, which + initialize consumers in callback priority order. """ STOP = "stop" @@ -150,18 +151,6 @@ class PhysicsManager(metaclass=_PhysicsManagerMeta): backend_name: ClassVar[str] """Backend implementation key used by asset and sensor factories.""" - binding_init_event: Enum = PhysicsEvent.PHYSICS_READY - """Lifecycle event on which assets and contact sensors acquire native physics bindings. - - Backends may select an earlier event, dispatched after native handles are valid and before - public readiness. The manager dispatches the selected event on non-soft resets; consumers use - it to register initialization callbacks without depending on backend-specific event names. - When early binding is unnecessary, backends may combine this phase with - :attr:`PhysicsEvent.PHYSICS_READY` in callback priority order. - Construction callbacks on :attr:`PhysicsEvent.MODEL_INIT` need not run on every reset, - so they cannot replace this binding-readiness contract for late-created consumers. - """ - def __init__(self, cfg: PhysicsCfg): """Store the physics configuration this manager runs. @@ -354,6 +343,14 @@ def _relocate_articulation_root( ) return new_root + def _register_physics_consumer(self, consumer: Any) -> None: + """Allow a backend to prepare an asset or physics sensor before public readiness. + + Consumers retain their normal readiness subscriptions. Backends that need early + native binding acquisition can initialize them directly during runtime construction. + The default leaves initialization to the normal callback priority order. + """ + def register_callback( self, callback: Callable[[Any], None], @@ -417,16 +414,7 @@ def dispatch_event(self, event: PhysicsEvent, payload: Any = None) -> None: event: The event to dispatch. payload: Optional data to pass to callbacks. """ - self._dispatch_events((event,), payload) - - def _dispatch_events(self, events: tuple[Enum, ...], payload: Any = None) -> None: - """Dispatch subscribers to the selected events together in callback priority order. - - Args: - events: Lifecycle phases whose subscribers should run in one ordered pass. - payload: Optional data to pass to callbacks. - """ - matching = [(cid, cb, order) for cid, (ev, cb, order, name, sub) in self._callbacks.items() if ev in events] + matching = [(cid, cb, order) for cid, (ev, cb, order, name, sub) in self._callbacks.items() if ev == event] matching.sort(key=lambda x: x[2]) for _, callback, _ in matching: diff --git a/source/isaaclab/isaaclab/sensors/sensor_base.py b/source/isaaclab/isaaclab/sensors/sensor_base.py index d81e7e27e5ef..f6e0baeb42ed 100644 --- a/source/isaaclab/isaaclab/sensors/sensor_base.py +++ b/source/isaaclab/isaaclab/sensors/sensor_base.py @@ -17,7 +17,6 @@ import weakref from abc import ABC, abstractmethod from collections.abc import Callable, Sequence -from enum import Enum from typing import TYPE_CHECKING, Any import warp as wp @@ -56,14 +55,6 @@ class SensorBase(ABC): they must not repeat reset-readiness checks or introduce class-level reset policies. """ - initialize_event: Enum = PhysicsEvent.PHYSICS_READY - """Lifecycle event on which this sensor acquires its native resources. - - Backend sensor implementations may select an earlier event when their native resources are - valid. Physics-binding consumers can use :attr:`~isaaclab.physics.PhysicsManager.binding_init_event` - from their backend manager. The event is selected when initialization callbacks are registered. - """ - def __init__(self, cfg: SensorBaseCfg): """Initialize the sensor class. @@ -365,12 +356,12 @@ def _register_callbacks(self): def _invoke(callback_name, event): getattr(obj_ref, callback_name)(event) - # Physics-only sensors may bind before render consumers and public readiness. + # Acquire native sensor resources once the runtime is ready. self._initialize_handle = physics_mgr.register_callback( lambda payload: PhysicsManager.safe_callback_invoke( _invoke, "_initialize_callback", payload, backend_manager=physics_mgr ), - self.initialize_event, + PhysicsEvent.PHYSICS_READY, order=10, ) self._invalidate_initialize_handle = physics_mgr.register_callback( @@ -397,9 +388,9 @@ def _initialize_callback(self, event): """Initializes the scene elements. .. note:: - The backend dispatches this callback once this sensor's native resources are valid. - Sensors initialize on :attr:`PhysicsEvent.PHYSICS_READY` unless their backend selects - an earlier binding phase. + The backend invokes this callback once this sensor's native resources are valid. + Ordinary sensors initialize on :attr:`PhysicsEvent.PHYSICS_READY`; a backend + may prepare its native physics sensors before publishing that event. """ if not self._is_initialized: self._initialize_impl() diff --git a/source/isaaclab_ov/changelog.d/early-joint-wrench-bindings.fixed.rst b/source/isaaclab_ov/changelog.d/early-joint-wrench-bindings.fixed.rst new file mode 100644 index 000000000000..2ae5ed0fcff6 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/early-joint-wrench-bindings.fixed.rst @@ -0,0 +1,2 @@ +* Reduced shared-OVStage joint-wrench initialization work by resolving native articulation + selections from clone-plan paths. diff --git a/source/isaaclab_ov/changelog.d/standard-physics-readiness.changed.rst b/source/isaaclab_ov/changelog.d/standard-physics-readiness.changed.rst new file mode 100644 index 000000000000..80530a0e6348 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/standard-physics-readiness.changed.rst @@ -0,0 +1,3 @@ +* Replaced the unreleased internal binding event with direct physics-consumer preparation on + borrowed stages, preserving initialization before render copies and public readiness callbacks. + Owned-stage callback ordering remained unchanged. diff --git a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py index db79ce49bc00..e51e21b20a8e 100644 --- a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py +++ b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py @@ -18,9 +18,9 @@ import math import os import stat +import weakref from collections.abc import Iterator, Sequence from contextlib import contextmanager -from enum import Enum from typing import TYPE_CHECKING, Any import numpy as np @@ -411,16 +411,6 @@ def close(self) -> None: self.stage = None -class _OvPhysxEvent(Enum): - """Internal binding phase after native cloning and before render expansion. - - It also initializes late consumers on ordinary resets, independently of MODEL_INIT's - construction callbacks, which run only during warmup or rebuild. - """ - - BINDINGS_READY = "ovphysx_bindings_ready" - - class OvPhysxManager(PhysicsManager): """Manages an ovphysx-backed physics simulation lifecycle. @@ -433,6 +423,7 @@ class OvPhysxManager(PhysicsManager): def __init__(self, cfg: OvPhysxCfg): super().__init__(cfg) + self._physics_consumers: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() self._cfg: OvPhysxCfg = cfg self.backend: OvPhysxBackend | None = None """Native resource borrowed from the context registry after warmup.""" @@ -452,24 +443,6 @@ def __init__(self, cfg: OvPhysxCfg): backend_name = "ovphysx" clone_context_type = OvPhysxReplicateContext - binding_init_event = _OvPhysxEvent.BINDINGS_READY - """Binding phase before render cloning and public readiness when a shared stage is borrowed. - - Otherwise, its subscribers run with PHYSICS_READY subscribers in callback priority order. - """ - - def dispatch_event(self, event: PhysicsEvent, payload: Any = None) -> None: - """Resolve binding readiness using the stage ownership selected after callback registration. - - Args: - event: Lifecycle event to dispatch. - payload: Optional data to pass to callbacks. - """ - if event == PhysicsEvent.PHYSICS_READY and (self.backend is None or self.backend.owns_scene): - self._dispatch_events((self.binding_init_event, event), payload) - else: - super().dispatch_event(event, payload) - def get_dt(self) -> float: """Get the physics timestep. Alias for get_physics_dt().""" return self.get_physics_dt() @@ -564,6 +537,22 @@ def initialize(self, sim_context: SimulationContext) -> None: self._scene_data_backend = OvPhysxSceneDataBackend(self) self.kinematics_dirty = False + def _register_physics_consumer(self, consumer: Any) -> None: + """Track native consumers in registration order without retaining their lifetime.""" + self._physics_consumers[consumer._initialize_handle.id] = consumer + + def _initialize_physics_consumers(self) -> None: + """Prepare borrowed-stage consumers before render copies and public readiness. + + Normal readiness subscriptions remain installed for owned stages. Initialization + is idempotent, so their later invocation on borrowed stages does no further work. + Looking up the live subscription also honors explicit callback deregistration. + """ + for callback_id in list(self._physics_consumers): + registration = self._callbacks.get(callback_id) + if registration is not None: + registration[1]({}) + def reset(self, soft: bool = False) -> None: """Reset physics simulation. @@ -583,8 +572,7 @@ def reset(self, soft: bool = False) -> None: self.dispatch_event(PhysicsEvent.STOP, payload={}) self._warmup_and_load() elif not self.backend.owns_scene: - # Consumers added since the previous reset still need their binding callback. - self.dispatch_event(self.binding_init_event, payload={}) + self._initialize_physics_consumers() self.dispatch_event(PhysicsEvent.PHYSICS_READY, payload={}) self.kinematics_dirty = True self._scene_data_backend.transforms_timestamp += 1 @@ -810,7 +798,7 @@ def _warmup_and_load(self) -> None: self.dispatch_event(PhysicsEvent.MODEL_INIT, payload={}) if not self.backend.owns_scene: - self.dispatch_event(self.binding_init_event, payload={}) + self._initialize_physics_consumers() if shared_scene is not None and shared_scene.render_copies_pending: # Acquire publication bindings while the stage still contains only originals. # Complete the reserved ordinal before public callbacks can author gravity or cameras. diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py index ce117ef7a141..bc11bfc52524 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py @@ -12,7 +12,6 @@ import logging import re from collections.abc import Sequence -from enum import Enum from fnmatch import fnmatchcase from typing import TYPE_CHECKING, Any @@ -132,11 +131,6 @@ def num_instances(self) -> int | None: return None return self._contact_binding.sensor_count - @property - def initialize_event(self) -> Enum: - """Manager-selected binding event, before the remaining shared-stage render prims are cloned.""" - return self._backend_manager.binding_init_event - @property def data(self) -> ContactSensorData: self._update_outdated_buffers() @@ -184,6 +178,11 @@ def pose_binding(self) -> Any: Implementation. """ + def _register_callbacks(self): + """Register native physics preparation without exposing another lifecycle event.""" + super()._register_callbacks() + self._backend_manager._register_physics_consumer(self) + def _initialize_impl(self) -> None: super()._initialize_impl() diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py index c8d13d205e1c..fb7596acf5fd 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py @@ -21,7 +21,7 @@ from isaaclab.utils.warp import memory as memory_kernels import isaaclab_ov.tensor_types as TT -from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView +from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView, expand_env_pattern from .joint_wrench_sensor_data import JointWrenchSensorData @@ -52,6 +52,11 @@ class JointWrenchSensor(BaseJointWrenchSensor): __backend_name__: str = "ovphysx" """The name of the backend for the joint wrench sensor.""" + def _register_callbacks(self): + """Register native physics preparation without exposing another lifecycle event.""" + super()._register_callbacks() + self._backend_manager._register_physics_consumer(self) + def __init__(self, cfg: JointWrenchSensorCfg): """Initialize the OVPhysX joint-wrench sensor. @@ -119,7 +124,7 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None """ def _initialize_impl(self) -> None: - """PHYSICS_READY callback: builds the tensor binding and allocates buffers.""" + """Build the tensor binding and buffers once native physics is ready.""" super()._initialize_impl() physx_instance = self._backend_manager.get_physx_instance() @@ -132,7 +137,8 @@ def _initialize_impl(self) -> None: pattern = re.sub(r"\{ENV_REGEX_NS\}", "*", root_prim_path_expr) pattern = path_expr_to_glob(pattern) - self._root_view = OvPhysxView(physx_instance, pattern=pattern, device=self._device) + paths = expand_env_pattern(pattern, self._sim.get_clone_plan()) + self._root_view = OvPhysxView(physx_instance, prim_paths=paths, device=self._device) self._wrench_binding = self._root_view.binding_for(TT.LINK_INCOMING_JOINT_FORCE) if self._wrench_binding.body_count == 0 or self._wrench_binding.count == 0: raise RuntimeError(f"Joint wrench sensor matched zero bodies at '{self.cfg.prim_path}'.") diff --git a/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py b/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py index 71c218252237..aa38d8f8ca83 100644 --- a/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py +++ b/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py @@ -764,13 +764,18 @@ def test_shared_stage_rejects_joint_only_native_recipe(): @pytest.mark.kitless @pytest.mark.integration -@pytest.mark.skipif(not _CPU_DEVICES, reason="Requires a selected CPU test device") -@pytest.mark.parametrize("shared", [False, True]) -def test_binding_readiness_preserves_priorities_across_resets(monkeypatch, shared): - """Binding callbacks preserve priority and initialize late consumers without replaying construction.""" +@pytest.mark.parametrize( + "device,shared", + [(device, shared) for device in _CPU_DEVICES for shared in (False, True)] + + [(device, True) for device in _CUDA_DEVICES], +) +def test_physics_readiness_preserves_priorities_and_stage_writes_across_resets(monkeypatch, device, shared): + """Shared consumers precede public readiness; owned priorities and ordinal safety stay intact.""" + import warp as wp from isaaclab_ov.assets import RigidObject from isaaclab_ov.physics import OvPhysxCfg from isaaclab_ov.stage import OvstageBackendCfg + from ovphysx.types import TensorType import isaaclab.sim as sim_utils from isaaclab.assets import RigidObjectCfg @@ -779,7 +784,7 @@ def test_binding_readiness_preserves_priorities_across_resets(monkeypatch, share # A flag without a shared renderer must not change headless callback ordering. monkeypatch.setenv("ISAAC_LAB_SHARE_OVSTAGE", "1") - cfg = SimulationCfg(physics=OvPhysxCfg(), device=_CPU_DEVICES[0], gravity=(0.0, 0.0, 0.0)) + cfg = SimulationCfg(physics=OvPhysxCfg(), device=device, gravity=(0.0, 0.0, 0.0)) with build_simulation_context(sim_cfg=cfg) as sim: consumers = [ RigidObject( @@ -795,10 +800,27 @@ def test_binding_readiness_preserves_priorities_across_resets(monkeypatch, share ] events = [] manager = sim.backend_manager + + def runtime_ready(_): + events.append(("ready_first", tuple(asset.is_initialized for asset in consumers))) + # Native buffers are queryable independently of wrapper initialization order. + with manager.get_physx_instance().create_tensor_binding( + prim_paths=["/World/Cube"], tensor_type=TensorType.RIGID_BODY_POSE + ) as binding: + assert binding.count == 1 + poses = wp.zeros(tuple(binding.shape), dtype=wp.float32, device=cfg.device) + binding.read(poses) + assert wp.to_torch(poses).isfinite().all() + if shared: + assert not manager.backend.scene.render_copies_pending + # A public callback may author a control ordinal immediately. Deferred render + # copies must already be sealed, including after a forced runtime rebuild. + manager.set_gravity((0.0, 0.0, -3.72)) + assert manager.get_gravity() == pytest.approx((0.0, 0.0, -3.72)) + + manager.register_callback(runtime_ready, PhysicsEvent.PHYSICS_READY, order=-1000) for name, event, order in [ ("model_init", PhysicsEvent.MODEL_INIT, -100), - ("ready_first", PhysicsEvent.PHYSICS_READY, 0), - ("bindings", manager.binding_init_event, 11), ("ready_last", PhysicsEvent.PHYSICS_READY, 20), ]: manager.register_callback( @@ -808,15 +830,22 @@ def test_binding_readiness_preserves_priorities_across_resets(monkeypatch, share ) # Stage sharing is selected after assets and listeners have already registered. if shared: - sim.get_or_create_backend(OvstageBackendCfg(populate_physics=True, defer_render_copies=True)) + scene = sim.get_or_create_backend(OvstageBackendCfg(populate_physics=True, defer_render_copies=True)) + complete_copies = scene.complete_render_copies + + def check_consumers_before_copies(): + assert all(asset.is_initialized for asset in consumers) + complete_copies() + + monkeypatch.setattr(scene, "complete_render_copies", check_consumers_before_copies) sim.reset() - assert events == [("model_init", (False,))] + ( - [("bindings", (True,)), ("ready_first", (True,)), ("ready_last", (True,))] - if shared - else [("ready_first", (False,)), ("bindings", (True,)), ("ready_last", (True,))] - ) + assert events == [ + ("model_init", (False,)), + ("ready_first", (shared,)), + ("ready_last", (True,)), + ] - # An isolated rendering stage must not change physics ownership or readiness ordering. + # Adding an isolated render stage cannot change physics ownership or readiness order. sim.get_or_create_backend(OvstageBackendCfg(scene_key=1)) consumers.append(RigidObject(RigidObjectCfg(prim_path="/World/Cube", spawn=None))) for rebuild in (False, True): @@ -825,15 +854,10 @@ def test_binding_readiness_preserves_priorities_across_resets(monkeypatch, share manager._warmup_done = False sim.reset() construction = [("model_init", (False, False))] if rebuild else [] - assert events == construction + ( - [("bindings", (True, True)), ("ready_first", (True, True)), ("ready_last", (True, True))] - if shared - else [ - ("ready_first", (not rebuild, False)), - ("bindings", (True, True)), - ("ready_last", (True, True)), - ] - ) + assert events == construction + [ + ("ready_first", (shared or not rebuild, shared)), + ("ready_last", (True, True)), + ] events.clear() sim.reset(soft=True) assert events == [] diff --git a/source/isaaclab_ov/test/sensors/test_contact_sensor.py b/source/isaaclab_ov/test/sensors/test_contact_sensor.py index 5c46edf57f9d..4ee7852f537f 100644 --- a/source/isaaclab_ov/test/sensors/test_contact_sensor.py +++ b/source/isaaclab_ov/test/sensors/test_contact_sensor.py @@ -512,7 +512,7 @@ def record_binding_patterns(physx, sensor_patterns, filter_patterns=None, **kwar @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) @pytest.mark.parametrize("filter_collisions", [False, True]) def test_heterogeneous_clone_contact_report_order(device, filter_collisions): - """Clone contact reporters retain numeric environment order and per-variant forces.""" + """Shared GPU and owned CPU reporters retain numeric environment order and variant forces.""" with _ovphysx_sim_context(device=device, dt=0.01) as sim: cfg = ContactSensorSceneCfg( num_envs=12, env_spacing=2.0, lazy_sensor_update=False, filter_collisions=filter_collisions @@ -544,8 +544,19 @@ def test_heterogeneous_clone_contact_report_order(device, filter_collisions): filter_prim_paths_expr=["/World/envs/env_*/Support", "/World/ground", "/World/envs/env_0/Object"], ) scene = InteractiveScene(cfg) - sim.reset() + if device.startswith("cuda"): + from isaaclab_ov.stage import OvstageBackendCfg + + sim.get_or_create_backend(OvstageBackendCfg(populate_physics=True, defer_render_copies=True)) + from isaaclab.physics import PhysicsEvent + + ready = [] sensor = scene["contact_sensor"] + sim.backend_manager.register_callback( + lambda _: ready.append(sensor.is_initialized), PhysicsEvent.PHYSICS_READY, order=-1000 + ) + sim.reset() + assert ready == [device.startswith("cuda")] assert sensor.contact_view.sensor_paths == [f"/World/envs/env_{i}/Object" for i in range(scene.num_envs)] assert sensor.contact_view.filter_paths == [ [f"/World/envs/env_{i}/Support", "/World/ground", "/World/envs/env_0/Object"] for i in range(scene.num_envs) diff --git a/source/isaaclab_ov/test/sensors/test_joint_wrench_sensor.py b/source/isaaclab_ov/test/sensors/test_joint_wrench_sensor.py index 0adf81efecf6..3b02d3a91878 100644 --- a/source/isaaclab_ov/test/sensors/test_joint_wrench_sensor.py +++ b/source/isaaclab_ov/test/sensors/test_joint_wrench_sensor.py @@ -155,14 +155,25 @@ def test_data_before_init_is_none(): # --------------------------------------------------------------------------- -@pytest.mark.parametrize("device", ["cuda:0", "cpu"]) -def test_initialization_and_shapes(sim, device): - """Sensor initializes on sim reset and exposes correctly-shaped buffers.""" +@pytest.mark.parametrize("device,shared", [("cuda:0", True), ("cpu", False)]) +def test_initialization_and_shapes(sim, device, shared): + """Shared wrench state precedes public callbacks while owned priorities stay unchanged.""" scene = InteractiveScene(_SingleJointSceneCfg(num_envs=2)) - sim.reset() - robot: Articulation = scene["robot"] sensor: JointWrenchSensor = scene["wrench"] + if shared: + from isaaclab_ov.stage import OvstageBackendCfg + + sim.get_or_create_backend(OvstageBackendCfg(populate_physics=True, defer_render_copies=True)) + ready = [] + from isaaclab.physics import PhysicsEvent + + sim.backend_manager.register_callback( + lambda _: ready.append(sensor.is_initialized), PhysicsEvent.PHYSICS_READY, order=-1000 + ) + sim.reset() + assert ready == [shared] + assert sensor.is_initialized sim.step() scene.update(sim.get_physics_dt())