Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
16 changes: 16 additions & 0 deletions docs/source/concepts/physics-backends/ovphysx.rst
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,22 @@ some property tensors are CPU-only. :class:`~isaaclab_ov.sim.views.OvPhysxView`
validates these requirements and can reinterpret supported flat scalar layouts
as structured Warp values, but it does not move data between CPU and GPU.

On a CUDA simulation, :meth:`~isaaclab_ov.sim.views.OvPhysxView.read_into` of
simulation state (poses, velocities, accelerations, joint state, Jacobians,
mass matrices, deformable nodes) replays an OvPhysX session read captured into
a CUDA graph on the first read of each destination buffer. Pass a buffer kept
across calls; for a one-off read, call ``get_attribute`` without ``out``. The
replay runs on the caller's current Warp stream, so work queued on that stream
afterwards sees the values; work on another non-blocking stream waits for that

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Make cross-stream waiting explicit

“Work on another non-blocking stream waits” implies automatic coordination. Callers must arrange that wait, including for cached SceneDataProvider poses; state the responsibility explicitly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f4f6672: ovphysx.rst, the read_into docstring and the SceneDataProvider transforms docstring say work on another non-blocking stream must first wait for that stream, and that the caller arranges the wait.

stream first. This includes the cached poses ``SceneDataProvider`` returns,
which are filled on the stream of the call that refreshed them. A structural edit made through the native handle,
such as enabling or disabling a rigid body or adding or removing prims, is not
reported by OvPhysX: call ``sim.backend_manager.invalidate_session_reads()``
before the edit, which waits for replays in flight and releases the captured
graphs, and read again only after the edit. Close and recreate a view whose
prims the edit disables, removes or replaces, since its bindings no longer
apply.

Use ``try_binding_for`` when a tensor type might not apply to the selected
prims. Reacquire raw bindings and convenience views after reset paths that
rebuild the stage or runtime, or after teardown. Destroy raw bindings and close
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* Added :meth:`~isaaclab_ov.physics.OvPhysxManager.invalidate_session_reads`, called before a structural edit made
through the native ``PhysX`` handle, such as enabling or disabling a rigid body, so the OvPhysX session reads wait for
replays in flight and capture again.
11 changes: 11 additions & 0 deletions source/isaaclab_ov/changelog.d/ovphysx-session-reads.changed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
* Changed :meth:`~isaaclab_ov.sim.views.OvPhysxView.read_into` and
:meth:`~isaaclab_ov.sim.views.OvPhysxView.get_attribute` to read the simulation state of a CUDA simulation through

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Qualify the get_attribute claim

The fragment says get_attribute uses session reads, but calls without out still read bindings. Specify that only its out path changes.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f4f6672: the fragment names get_attribute with out.

captured ovphysx session reads instead of blocking ``TensorBinding`` reads: articulation root poses and velocities;
link poses, velocities, accelerations and incoming joint forces; joint positions and velocities; Jacobians and mass
matrices; rigid-body poses, velocities and accelerations, articulation links included; and
deformable nodal positions and velocities. Each read replays a CUDA graph on the caller's current Warp stream
without waiting on the host; each destination buffer captures its own graph on its first read, so pass a buffer
kept across calls. Values and row order are unchanged, except that joint quantities, which the session
reports in degrees, may differ in the last bit, and deformable positions, which the session reports in the
simulation mesh's frame, carry float32 rounding from that transform. Properties, contacts, gravity
compensation forces and every read of a CPU simulation still read their bindings.
Empty file.
94 changes: 86 additions & 8 deletions source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@
import ovphysx
import ovstage
import warp as wp
from ovphysx.types import CompiledStageCacheMode, GlobalConfigKey
from ovphysx.types import CompiledStageCacheMode, GlobalConfigKey, TensorType

from pxr import Plug, Sdf, Usd, UsdPhysics
from pxr import Plug, Sdf, Usd, UsdGeom, UsdPhysics

from isaaclab.physics import PhysicsEvent, PhysicsManager
from isaaclab.scene_data import SceneDataBackend, SceneDataFormat
Expand All @@ -46,6 +46,7 @@
from isaaclab_ov._clone import CloneRecipe, clone_transforms_from_positions
from isaaclab_ov.cloner import OvPhysxReplicateContext
from isaaclab_ov.cloner.replicate import _serialize_stage
from isaaclab_ov.sim.views.ovphysx_session_reads import OvPhysxSessionReads

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Use the required relative import

This same-package module is within the guide’s three-dot limit. Import it through ..sim.views rather than its absolute package path.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept absolute to match the other isaaclab_ov imports in this module, which are all absolute; converting that block is a separate cleanup.

from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView
from isaaclab_ov.stage import OvstageBackend, OvstageBackendCfg

Expand Down Expand Up @@ -178,7 +179,14 @@ def _ensure_setup(self) -> None:
for group in bodies.groups:
body_paths.extend(bodies.dictionary.get_path_strings(group.prim_list))
if body_paths:
backend.rigid_body_view = backend.physx.create_tensor_binding(prim_paths=body_paths)
# The poses publish through the view's session reads; the binding gives the rows and their order.
backend.rigid_body_view = OvPhysxView(
backend.physx,
prim_paths=body_paths,
device=device,
tensor_types=[TensorType.RIGID_BODY_POSE],
eager=True,
)
self.setup(backend, device, entries)
self._pending_setup = None

Expand Down Expand Up @@ -301,12 +309,16 @@ def native_geometry_formats(self) -> tuple[Any, ...]:

@property
def transforms(self) -> SceneDataFormat.Transform:
"""Publish native rigid-body poses [m, xyzw]."""
"""Publish native rigid-body poses [m, xyzw].

On CUDA the poses are filled on the stream of the call that refreshed them this frame; a reader on another
non-blocking stream waits for that stream first.
"""
self._ensure_setup()
if self._transforms.timestamp != self.transforms_timestamp:
self._manager.pre_render()
if self._transforms.data.transforms is not None:
self.backend.rigid_body_view.read(self._transforms.data.transforms)
self.backend.rigid_body_view.read_into(TensorType.RIGID_BODY_POSE, self._transforms.data.transforms)
self._transforms.timestamp = self.transforms_timestamp
return self._transforms.data

Expand Down Expand Up @@ -341,6 +353,9 @@ def __init__(self, cfg: OvPhysxBackendCfg, *, scene: OvstageBackend | None = Non
self.owns_scene = scene is None
self.stage: Any = None
self.rigid_body_view: Any = None
self.session_reads: OvPhysxSessionReads | None = None
"""Session reads behind :meth:`OvPhysxView.read_into`; ``None`` before a stage attaches or on a CPU scene."""
self._device = cfg.device

def load(self, stage_usda: str, *, disable_compiled_stage_cache: bool = False) -> None:
"""Replace the attached scene after draining its native bindings.
Expand All @@ -351,9 +366,10 @@ def load(self, stage_usda: str, *, disable_compiled_stage_cache: bool = False) -
"""
if self.stage is not None:
if self.rigid_body_view is not None:
self.rigid_body_view.destroy()
self.rigid_body_view.close()
self.rigid_body_view = None
OvPhysxView._close_all_for(self.physx)
self._close_session_reads()
self.physx.wait_task(self.physx.detach_ovstage())
self.scene.reset()
self.stage = None
Expand All @@ -372,6 +388,8 @@ def load(self, stage_usda: str, *, disable_compiled_stage_cache: bool = False) -
self.scene.close()
self.scene = None
raise
if wp.get_device(self._device).is_cuda: # a CPU scene reads its bindings
self.session_reads = OvPhysxSessionReads(self.physx, self.stage, self._device)

def close(self) -> None:
"""Release bindings, the runtime, and its stage in native teardown order."""
Expand All @@ -387,9 +405,10 @@ def close(self) -> None:
try:
try:
if self.rigid_body_view is not None:
self.rigid_body_view.destroy()
self.rigid_body_view.close()
self.rigid_body_view = None
OvPhysxView._close_all_for(physx)
self._close_session_reads()
finally:
try:
physx.wait_task(physx.detach_ovstage())
Expand All @@ -414,6 +433,14 @@ def close(self) -> None:
self.scene.close()
self.stage = None

def _close_session_reads(self) -> None:
"""Release the captured reads after their views and before the stage detaches."""
if self.session_reads is not None:
try:
self.session_reads.close()
finally:
self.session_reads = None


class _OvPhysxEvent(Enum):
"""Internal binding phase after native cloning and before render expansion.
Expand Down Expand Up @@ -441,6 +468,8 @@ def __init__(self, cfg: OvPhysxCfg):
self.backend: OvPhysxBackend | None = None
"""Native resource borrowed from the context registry after warmup."""
self._stage_usda: str | None = None
self._loaded_stage: Usd.Stage | None = None
""":attr:`_stage_usda` parsed, on demand, for :meth:`_loaded_world_transforms`."""
self._warmup_done: bool = False
self._requires_full_stage: bool = False
self._clone_recipes: list[CloneRecipe] = []
Expand Down Expand Up @@ -563,6 +592,7 @@ def initialize(self, sim_context: SimulationContext) -> None:
self._warmup_done = False
self._requires_full_stage = False
self._stage_usda = None
self._loaded_stage = None
self._clone_recipes = []
# SimulationContext retains this backend; native bindings remain deferred until the first SDP read.
self._scene_data_backend = OvPhysxSceneDataBackend(self)
Expand Down Expand Up @@ -609,14 +639,32 @@ def update_kinematics(self) -> None:
if not self.kinematics_dirty:
return
if self.backend is not None and self.backend.physx is not None:
self.backend.physx.update_articulations_kinematic()
reads = self.backend.session_reads
if reads is None:
self.backend.physx.update_articulations_kinematic()
else:
# Link-pose replays read the refreshed poses on this stream (ovphysx device guide).
self.backend.physx.update_articulations_kinematic(cuda_stream=int(reads.stream.cuda_stream or 0))
self.kinematics_dirty = False

def invalidate_session_reads(self) -> None:
"""Wait for every OvPhysX session read in flight and capture each again on its next call.

Call it before a structural edit made through the native ``PhysX`` handle, such as a rigid body enabled or
disabled or prims added or removed, and read again only after the edit: OvPhysX does not report such an edit,
and a replay in flight, or one captured before the edit, may read wrong rows or freed memory. Close and
recreate a view whose prims the edit disables, removes or replaces: its bindings no longer apply.
"""
if self.backend is not None and self.backend.session_reads is not None:
self.backend.session_reads.invalidate()

def step(self) -> None:
"""Step the simulation by one physics timestep."""
if self.backend is None or self.backend.physx is None:
return
dt = self.get_physics_dt()
if self.backend.session_reads is not None:
self.backend.session_reads.wait() # ovphysx forbids stepping while a captured read replays
self.backend.physx.step_sync(dt=dt)
self.kinematics_dirty = True
self.update_kinematics()
Expand Down Expand Up @@ -648,6 +696,7 @@ def close(self) -> None:
self._atexit_registered = False
finally:
self._stage_usda = None
self._loaded_stage = None
self._gravity_stage = None
self._warmup_done = False
self._requires_full_stage = False
Expand Down Expand Up @@ -786,6 +835,7 @@ def _warmup_and_load(self) -> None:
preserve_physics_ancestors=shared_scene is not None,
)
self._stage_usda = stage_usda
self._loaded_stage = None

self.backend = sim.get_or_create_backend(
OvPhysxBackendCfg(
Expand All @@ -798,6 +848,11 @@ def _warmup_and_load(self) -> None:
atexit.register(self._close_at_exit)
self._atexit_registered = True
self.backend.load(stage_usda, disable_compiled_stage_cache=self._cfg.disable_compiled_stage_cache)
if self.backend.session_reads is not None:
# Session reads of Jacobians and mass matrices do not refresh kinematics themselves, as binding reads did.
self.backend.session_reads.refresh_kinematics = self.update_kinematics
# Session reads report deformable points in the sim-mesh frame; the stage just loaded holds those frames.
self.backend.session_reads.world_transforms = self._loaded_world_transforms
logger.info("OvPhysxManager: attached OVStage to ovphysx (device=%s)", ovphysx_device)

for source, targets, transforms, env_ids, _ in native_clones:
Expand All @@ -822,6 +877,29 @@ def _warmup_and_load(self) -> None:
shared_scene.complete_render_copies()
self._warmup_done = True

def _loaded_world_transforms(self, paths: list[str]) -> np.ndarray:
"""World transform of each prim on the stage ovphysx loaded, as column-vector float32 4x4 matrices [m].

The serialized stage is parsed on the first call and kept until the next load.

Raises:
ValueError: If a prim is not on the loaded stage.
"""
# 1. Parse the stage ovphysx loaded, once per load.
if self._loaded_stage is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Critical · Implementation — Refresh frames after native replacement

invalidate_session_reads recaptures graphs but _loaded_stage still supplies the original frame. A same-path deformable replacement with a changed frame returns wrong world points; refresh the frame source.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Known limit, listed in the PR description: the frames come from the stage ovphysx loaded, and no Lab caller replaces a deformable at the same path through native OVStage edits, so this stays out of scope.

layer = Sdf.Layer.CreateAnonymous(".usda")
layer.ImportFromString(self._stage_usda)
self._loaded_stage = Usd.Stage.Open(layer)
# 2. Each prim's local-to-world, as column vectors.
cache = UsdGeom.XformCache()
frames = np.empty((len(paths), 4, 4), dtype=np.float32)
for row, path in enumerate(paths):
prim = self._loaded_stage.GetPrimAtPath(path)
if not prim.IsValid():
raise ValueError(f"{path} is not on the stage ovphysx loaded.")
frames[row] = np.array(cache.GetLocalToWorldTransform(prim)).T # USD matrices act on row vectors
return frames

def _close_at_exit(self) -> None:
"""Release a live OVPhysX runtime without leaking an atexit exception."""
if self.backend is None or self.backend.physx is None:
Expand Down
Loading
Loading