Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 25 additions & 22 deletions docs/source/api/lab_ov/isaaclab_ov.cloner.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Shared mode uses early physics attachment without an additional flag:
<desc id="shared-stage-flow-desc">
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.
Expand Down Expand Up @@ -102,15 +102,15 @@ Shared mode uses early physics attachment without an additional flag:
<text x="300" y="239">Execute native physics clones</text>
<text x="300" y="263">Wait for completion</text>
<text x="300" y="351">Run physics warmup</text>
<text x="300" y="439">Initialize asset and contact bindings</text>
<text x="300" y="463" font-family="monospace">binding_init_event</text>
<text x="300" y="551">Acquire scene-data bindings</text>
<text x="300" y="639">Clone remaining render prims and place environments</text>
<text x="300" y="439">Initialize physics consumers</text>
<text x="300" y="463">Acquire scene-data bindings</text>
<text x="300" y="551">Clone remaining render prims</text>
<text x="300" y="639">Apply environment placement</text>
<text x="300" y="663" font-weight="bold">Seal ordinal 2 (rendering-only)</text>
<text x="300" y="739" font-family="monospace">Publish PHYSICS_READY</text>
<text x="300" y="763">Startup callbacks and camera preparation can proceed</text>
<text x="300" y="835">Attach OVRTX during renderer preparation</text>
<text x="300" y="859">Continue normal rendering</text>
<text x="300" y="763">Native physics queries and control writes are safe</text>
<text x="300" y="835">Initialize cameras and renderer</text>
<text x="300" y="859">Physics consumers already initialized</text>
</g>
</svg>

Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
11 changes: 6 additions & 5 deletions source/isaaclab/isaaclab/assets/asset_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand Down
36 changes: 12 additions & 24 deletions source/isaaclab/isaaclab/physics/physics_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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],
Expand Down Expand Up @@ -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:
Expand Down
19 changes: 5 additions & 14 deletions source/isaaclab/isaaclab/sensors/sensor_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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(
Expand All @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
* Reduced shared-OVStage joint-wrench initialization work by resolving native articulation
selections from clone-plan paths.
Original file line number Diff line number Diff line change
@@ -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.
52 changes: 20 additions & 32 deletions source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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."""
Expand All @@ -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()
Expand Down Expand Up @@ -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.

Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()

Expand Down
Loading
Loading