diff --git a/docs/source/concepts/physics-backends/ovphysx.rst b/docs/source/concepts/physics-backends/ovphysx.rst index 191037759346..2296c33368dc 100644 --- a/docs/source/concepts/physics-backends/ovphysx.rst +++ b/docs/source/concepts/physics-backends/ovphysx.rst @@ -431,6 +431,38 @@ 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, :class:`~isaaclab_ov.sim.views.OvPhysxView` replays OvPhysX +session reads and writes captured into CUDA graphs instead of blocking +``TensorBinding`` calls: + +- **Reads** (``read_into``, ``get_attribute`` with ``out``): poses, velocities, + accelerations, joint state, Jacobians, mass matrices and deformable nodes. +- **Writes** (``set_attribute`` from a Warp array, whole or by ``mask``): joint + targets, actuation forces, rigid-body poses and velocities, and whole wrench + writes. The next simulation step waits for them. +- **Still** ``TensorBinding``: articulation root and joint state, masked wrenches, + writes by ``indices`` or from host data, properties, and CPU simulations. + +The assets follow these rules; code that drives a view directly follows them too: + +- Pass destination, source and mask buffers kept across calls, since each + captures once; masks are Warp ``bool`` arrays on the simulation device. +- Make session calls and the view's ``TensorBinding`` calls on one stream, the + current Warp stream at the first replay; another stream raises ``RuntimeError``. +- Keep a view's prims in one ``UsdPhysics.Scene``; otherwise the first session + call raises ``ValueError``. +- After writing joint or root state, set + ``sim.backend_manager.kinematics_dirty = True`` before ``sim.forward()``. +- Make structural edits on the USD stage before the first ``sim.reset()``: + OvPhysX does not report edits made through the native handle. + +To record session calls into its own CUDA graph, a caller runs each once outside +the capture, then replays the graph on the session's stream, or on a stream that +first waits for it and that it synchronizes before the next step, closing a view +or a centre-of-mass write. It calls ``sim.forward()`` on that stream before the +replay after a state write, and captures the graph again after closing a view or +writing a centre of mass. + 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 diff --git a/source/isaaclab_newton/changelog.d/collection-shared-masked-copy.skip b/source/isaaclab_newton/changelog.d/collection-shared-masked-copy.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/isaaclab_newton/assets/kernels.py b/source/isaaclab_newton/isaaclab_newton/assets/kernels.py index 636be431f3cf..cc5dbf991608 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/kernels.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/kernels.py @@ -722,27 +722,6 @@ def set_body_link_velocity_to_sim( body_acc_w[env_id, body_id] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) -@wp.kernel -def set_body_link_pose_to_sim_mask( - data: wp.array2d(dtype=wp.transformf), - env_mask: wp.array(dtype=wp.bool), - body_mask: wp.array(dtype=wp.bool), - body_link_pose_w: wp.array2d(dtype=wp.transformf), -): - """Write masked body link pose data to simulation buffers. - - Args: - data: Input array of body link poses. Shape is (num_envs, num_bodies). - env_mask: Environments to write. Shape is (num_envs,). - body_mask: Bodies to write. Shape is (num_bodies,). - body_link_pose_w: Output array where body link poses are written. Shape is (num_envs, num_bodies). - """ - env_id, body_id = wp.tid() - if not env_mask[env_id] or not body_mask[body_id]: - return - body_link_pose_w[env_id, body_id] = data[env_id, body_id] - - @wp.kernel def set_body_com_pose_to_sim_mask( data: wp.array2d(dtype=wp.transformf), diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py index 592cd01deb26..6361caf4ef67 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py @@ -529,7 +529,7 @@ def write_body_link_pose_to_sim_mask( body_mask = self._resolve_body_mask(body_mask, body_ids) self.assert_shape_and_dtype_mask(body_poses, (env_mask, body_mask), wp.transformf, "body_poses") wp.launch( - shared_kernels.set_body_link_pose_to_sim_mask, + memory.make_masked_copy(wp.transformf, 2), dim=(env_mask.shape[0], body_mask.shape[0]), inputs=[body_poses, env_mask, body_mask], outputs=[self.data._sim_bind_body_link_pose_w], diff --git a/source/isaaclab_ov/changelog.d/ovphysx-collection-layout.fixed.rst b/source/isaaclab_ov/changelog.d/ovphysx-collection-layout.fixed.rst new file mode 100644 index 000000000000..85998196a1f2 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovphysx-collection-layout.fixed.rst @@ -0,0 +1,3 @@ +* Fixed :class:`~isaaclab_ov.assets.RigidObjectCollection` with seven bodies, or six for velocities, reading its fused + bindings as the instance-major layout of the test mock, which mis-sized its data and wrote and read state at the wrong + rows: the layout now comes from the rank of the pose binding. diff --git a/source/isaaclab_ov/changelog.d/ovphysx-session-reads.changed.rst b/source/isaaclab_ov/changelog.d/ovphysx-session-reads.changed.rst new file mode 100644 index 000000000000..af628572ce8a --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovphysx-session-reads.changed.rst @@ -0,0 +1,8 @@ +* Changed :meth:`~isaaclab_ov.sim.views.OvPhysxView.read_into` and + :meth:`~isaaclab_ov.sim.views.OvPhysxView.get_attribute` with ``out`` on a CUDA simulation to replay captured ovphysx + session reads of simulation state instead of blocking ``TensorBinding`` reads. Pass a destination kept across calls: + each captures once. Values are unchanged up to float32 rounding. A Jacobian or mass matrix read through the view no + longer refreshes the kinematics: call :meth:`~isaaclab_ov.physics.OvPhysxManager.update_kinematics` first, as + :class:`~isaaclab_ov.assets.ArticulationData` does. +* **Breaking:** Changed session reads and writes to raise ``ValueError`` for a view whose prims belong to several + ``UsdPhysics.Scene`` prims. diff --git a/source/isaaclab_ov/changelog.d/ovphysx-session-reads.minor b/source/isaaclab_ov/changelog.d/ovphysx-session-reads.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_ov/changelog.d/ovphysx-session-writes.changed.rst b/source/isaaclab_ov/changelog.d/ovphysx-session-writes.changed.rst new file mode 100644 index 000000000000..2ab03f237da3 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovphysx-session-writes.changed.rst @@ -0,0 +1,15 @@ +* Changed :meth:`~isaaclab_ov.sim.views.OvPhysxView.set_attribute` on a CUDA simulation to replay captured ovphysx + session writes of joint targets, actuation forces, rigid-body poses and velocities, and whole wrench writes, from a + Warp array, whole or by ``mask``, as an actuator's ``set_*_index`` command without ``env_ids`` does. The call returns + before the GPU write, which the next step waits for. Pass source and mask buffers kept across calls. Other writes keep + the ``TensorBinding`` write. +* Changed :meth:`~isaaclab_ov.physics.OvPhysxManager.update_kinematics` on a CUDA simulation to refresh over one held + query instead of creating one and waiting on every call. +* Changed the masked pose and velocity writers of :class:`~isaaclab_ov.assets.RigidObjectCollection` to write only the + selected (environment, body) entries, without converting the masks to indices on the host. +* **Breaking:** Changed session writes by ``mask`` to raise ``ValueError`` for a mask that is not a contiguous Warp + ``bool`` array on the simulation device. +* **Breaking:** Changed session reads and writes to raise ``RuntimeError`` on a stream other than the one the first + session call used. +* **Breaking:** Changed the mask writers and setters of :class:`~isaaclab_ov.assets.RigidObjectCollection` to raise + ``ValueError`` for a mask whose length is not the environment or body count. diff --git a/source/isaaclab_ov/changelog.d/ovphysx-session-writes.major b/source/isaaclab_ov/changelog.d/ovphysx-session-writes.major new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_ov/isaaclab_ov/assets/articulation/actuator_control.py b/source/isaaclab_ov/isaaclab_ov/assets/articulation/actuator_control.py index 74add9260ef8..b9bb5c26016d 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/articulation/actuator_control.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/articulation/actuator_control.py @@ -119,11 +119,13 @@ def stage_user_command( target_backend = articulation._get_backend_ordered_joint_buffer(user_buffer, backend_buffer) if env_mask is not None: articulation._root_view.set_attribute(tensor_type, target_backend, mask=env_mask) - elif env_ids is not None: + elif env_ids is not None and env_ids is not articulation._ALL_INDICES: articulation._root_view.set_attribute( tensor_type, target_backend, indices=articulation._get_sim_env_ids(env_ids) ) else: + # Every environment, as an action term's per-step target write without env_ids (they resolve to + # _ALL_INDICES): a whole write, which a CUDA simulation commits through its captured session write. articulation._root_view.set_attribute(tensor_type, target_backend) def submit_commands(self, collection: ActuatorCollection) -> None: diff --git a/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation.py b/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation.py index 1256fea0cfff..3ea11b265c4f 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation.py @@ -4112,18 +4112,11 @@ def _process_tendons(self) -> None: self._num_spatial_tendons = self._root_view.spatial_tendon_count if self._num_fixed_tendons > 0 or self._num_spatial_tendons > 0: - stage_usda = self._backend_manager._stage_usda - if stage_usda is not None: + stage = self._backend_manager.backend.usd_stage + if stage is not None: try: - from pxr import Sdf, Usd - from isaaclab.sim.utils.queries import get_all_matching_child_prims - layer = Sdf.Layer.CreateAnonymous("isaaclab_ov.usda") - if not layer.ImportFromString(stage_usda): - raise RuntimeError("Failed to import the serialized OVPhysX stage.") - stage = Usd.Stage.Open(layer) - articulation_root_path = getattr(self, "_articulation_root_path", None) if articulation_root_path is None: joint_prims = stage.Traverse() diff --git a/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation_data.py b/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation_data.py index c4c91140de00..4813268a5fec 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation_data.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation_data.py @@ -1073,6 +1073,7 @@ def body_com_jacobian_w(self) -> ProxyArray: shape = (self._num_instances, body_count, 6, self._num_joints + self._num_base_dofs) self._body_com_jacobian_w.data = ProxyArray(wp.empty(shape, wp.float32, self.device)) if self._body_com_jacobian_w.timestamp < self._sim_timestamp: + self._backend_manager.update_kinematics() # computed from the link poses, as body_link_pose_w refreshes has_body_ordering = self.has_body_ordering has_joint_ordering = self.has_joint_ordering if has_body_ordering or has_joint_ordering: @@ -1125,6 +1126,7 @@ def mass_matrix(self) -> ProxyArray: shape = self._view.binding_for(TT.MASS_MATRIX).shape self._mass_matrix.data = ProxyArray(wp.empty(shape, wp.float32, self.device)) if self._mass_matrix.timestamp < self._sim_timestamp: + self._backend_manager.update_kinematics() # computed from the link poses, as body_link_pose_w refreshes if self.has_joint_ordering: if self._mass_matrix_backend is None: self._mass_matrix_backend = wp.empty_like(self._mass_matrix.data.warp) diff --git a/source/isaaclab_ov/isaaclab_ov/assets/kernels.py b/source/isaaclab_ov/isaaclab_ov/assets/kernels.py index e0c3654f84dc..b8c266739e04 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/kernels.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/kernels.py @@ -926,6 +926,79 @@ def set_root_link_velocity_to_sim_mask( body_acc_w[i, j] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) +@wp.kernel +def set_body_com_pose_to_sim_mask( + data: wp.array2d(dtype=wp.transformf), + body_com_pose_b: wp.array2d(dtype=wp.transformf), + env_mask: wp.array(dtype=wp.bool), + body_mask: wp.array(dtype=wp.bool), + body_com_pose_w: wp.array2d(dtype=wp.transformf), + body_link_pose_w: wp.array2d(dtype=wp.transformf), +): + """Mask-scatter body COM poses into the cache and derive the corresponding link poses.""" + env_id, body_id = wp.tid() + if env_mask[env_id] and body_mask[body_id]: + body_com_pose_w[env_id, body_id] = data[env_id, body_id] + body_link_pose_w[env_id, body_id] = get_com_pose_in_link_frame_func( + data[env_id, body_id], body_com_pose_b[env_id, body_id] + ) + + +@wp.kernel +def set_body_com_velocity_to_sim_mask( + data: wp.array2d(dtype=wp.spatial_vectorf), + env_mask: wp.array(dtype=wp.bool), + body_mask: wp.array(dtype=wp.bool), + body_com_velocity_w: wp.array2d(dtype=wp.spatial_vectorf), + body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), +): + """Mask-scatter body COM velocities into the cache and zero the body accelerations.""" + env_id, body_id = wp.tid() + if env_mask[env_id] and body_mask[body_id]: + body_com_velocity_w[env_id, body_id] = data[env_id, body_id] + body_acc_w[env_id, body_id] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + + +@wp.kernel +def set_body_link_velocity_to_sim_mask( + data: wp.array2d(dtype=wp.spatial_vectorf), + body_com_pose_b: wp.array2d(dtype=wp.transformf), + body_link_pose_w: wp.array2d(dtype=wp.transformf), + env_mask: wp.array(dtype=wp.bool), + body_mask: wp.array(dtype=wp.bool), + body_link_velocity_w: wp.array2d(dtype=wp.spatial_vectorf), + body_com_velocity_w: wp.array2d(dtype=wp.spatial_vectorf), + body_acc_w: wp.array2d(dtype=wp.spatial_vectorf), +): + """Mask-scatter body link velocities into the cache, derive the COM velocities and zero the accelerations.""" + env_id, body_id = wp.tid() + if env_mask[env_id] and body_mask[body_id]: + body_link_velocity_w[env_id, body_id] = data[env_id, body_id] + body_com_velocity_w[env_id, body_id] = get_link_velocity_in_com_frame_func( + data[env_id, body_id], body_link_pose_w[env_id, body_id], body_com_pose_b[env_id, body_id] + ) + body_acc_w[env_id, body_id] = wp.spatial_vectorf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + + +@wp.kernel +def reshape_data_to_view_mask( + data: wp.array2d(dtype=Any), + env_mask: wp.array(dtype=wp.bool), + body_mask: wp.array(dtype=wp.bool), + view_data: wp.array(dtype=Any), + view_mask: wp.array(dtype=wp.bool), +): + """Mask variant of ``RigidObjectCollection.reshape_data_to_view_2d``: copy the selected (env, body) entries of the + instance-major ``data`` to their body-major view rows ``view_id = body_id * num_envs + env_id``, and mark those rows + in ``view_mask``; the other rows are unmarked.""" + env_id, body_id = wp.tid() + view_id = body_id * data.shape[0] + env_id + selected = env_mask[env_id] and body_mask[body_id] + view_mask[view_id] = selected + if selected: + view_data[view_id] = data[env_id, body_id] + + """ Articulation-only kernels (used by isaaclab_ov.assets.articulation). """ diff --git a/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection.py b/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection.py index caa7ce6803f4..a3b69e153750 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection.py @@ -206,19 +206,11 @@ def write_data_to_sim(self) -> None: _body_wrench_to_world, dim=(self._num_instances, self._num_bodies), inputs=[force_in, torque_in, poses, is_global], - outputs=[self._wrench_buf], + outputs=[self._wrench_kernel_out], device=self._device, ) - binding = self._get_binding(TT.LINK_WRENCH) - if binding is not None: - # The articulation-mode mock used by iface tests exposes an instance-major - # ``(N, B, 9)`` view directly; the native fused binding lays elements body- - # major flat as ``(N * B, 9)``. Dispatch via the binding's exposed shape. - if len(binding.shape) >= 2 and binding.shape[1] == self._num_bodies: - self._root_view.set_attribute(TT.LINK_WRENCH, self._wrench_buf) - else: - view = self.reshape_data_to_view_3d(self._wrench_buf, 9, device=self._device) - self._root_view.set_attribute(TT.LINK_WRENCH, view) + if self._has_wrench_binding: + self._root_view.set_attribute(TT.LINK_WRENCH, self._wrench_buf) inst.reset() def update(self, dt: float) -> None: @@ -415,7 +407,7 @@ def write_body_link_pose_to_sim_index( if not skip_forward: self.data._reset_pose() # set into simulation - self._binding_write(TT.LINK_POSE, self.data._body_link_pose_w.data, env_ids=env_ids) + self._write_to_view_index(TT.LINK_POSE, self.data._body_link_pose_w.data, env_ids=env_ids) self._backend_manager._scene_data_backend.transforms_timestamp += 1 def write_body_link_pose_to_sim_mask( @@ -441,21 +433,21 @@ def write_body_link_pose_to_sim_mask( skip_forward: Whether to skip invalidating cached data after the write. When True, the caller must invalidate stale cached data before reading it back. Defaults to False. """ - env_ids = self._resolve_env_ids(env_mask=env_mask) - body_ids = self._resolve_body_ids(body_mask=body_mask) - self.assert_shape_and_dtype(body_poses, (self._num_instances, self._num_bodies), wp.transformf, "body_poses") + env_mask = self._resolve_env_mask(env_mask) + body_mask = self._resolve_body_mask(body_mask) + self.assert_shape_and_dtype_mask(body_poses, (env_mask, body_mask), wp.transformf, "body_poses") wp.launch( - shared_kernels.set_body_link_pose_to_sim_kernel(env_ids, body_ids), - dim=(env_ids.shape[0], body_ids.shape[0]), - inputs=[body_poses, env_ids, body_ids, True], - outputs=[self.data._body_link_pose_w.data, self.data._body_link_state_w.data, self.data._body_state_w.data], + memory.make_masked_copy(wp.transformf, 2), + dim=(env_mask.shape[0], body_mask.shape[0]), + inputs=[body_poses, env_mask, body_mask], + outputs=[self.data._body_link_pose_w.data], device=self._device, ) # Invalidate dependent timestamps if not skip_forward: self.data._reset_pose() # set into simulation - self._binding_write(TT.LINK_POSE, self.data._body_link_pose_w.data, env_ids=env_ids) + self._write_to_view_mask(TT.LINK_POSE, self.data._body_link_pose_w.data, env_mask, body_mask) self._backend_manager._scene_data_backend.transforms_timestamp += 1 def write_body_com_pose_to_sim_index( @@ -502,7 +494,7 @@ def write_body_com_pose_to_sim_index( if not skip_forward: self.data._reset_pose(from_link=False) # set into simulation (OVPhysX only exposes the link frame) - self._binding_write(TT.LINK_POSE, self.data._body_link_pose_w.data, env_ids=env_ids) + self._write_to_view_index(TT.LINK_POSE, self.data._body_link_pose_w.data, env_ids=env_ids) self._backend_manager._scene_data_backend.transforms_timestamp += 1 def write_body_com_pose_to_sim_mask( @@ -529,27 +521,21 @@ def write_body_com_pose_to_sim_mask( skip_forward: Whether to skip invalidating cached data after the write. When True, the caller must invalidate stale cached data before reading it back. Defaults to False. """ - env_ids = self._resolve_env_ids(env_mask=env_mask) - body_ids = self._resolve_body_ids(body_mask=body_mask) - self.assert_shape_and_dtype(body_poses, (self._num_instances, self._num_bodies), wp.transformf, "body_poses") + env_mask = self._resolve_env_mask(env_mask) + body_mask = self._resolve_body_mask(body_mask) + self.assert_shape_and_dtype_mask(body_poses, (env_mask, body_mask), wp.transformf, "body_poses") wp.launch( - shared_kernels.set_body_com_pose_to_sim_kernel(env_ids, body_ids), - dim=(env_ids.shape[0], body_ids.shape[0]), - inputs=[body_poses, self.data.body_com_pose_b, env_ids, body_ids, True], - outputs=[ - self.data._body_com_pose_w.data, - self.data._body_link_pose_w.data, - self.data._body_com_state_w.data, - self.data._body_link_state_w.data, - self.data._body_state_w.data, - ], + shared_kernels.set_body_com_pose_to_sim_mask, + dim=(env_mask.shape[0], body_mask.shape[0]), + inputs=[body_poses, self.data.body_com_pose_b, env_mask, body_mask], + outputs=[self.data._body_com_pose_w.data, self.data._body_link_pose_w.data], device=self._device, ) # Invalidate dependent timestamps if not skip_forward: self.data._reset_pose(from_link=False) # set into simulation (OVPhysX only exposes the link frame) - self._binding_write(TT.LINK_POSE, self.data._body_link_pose_w.data, env_ids=env_ids) + self._write_to_view_mask(TT.LINK_POSE, self.data._body_link_pose_w.data, env_mask, body_mask) self._backend_manager._scene_data_backend.transforms_timestamp += 1 def write_body_com_velocity_to_sim_index( @@ -601,7 +587,7 @@ def write_body_com_velocity_to_sim_index( if not skip_forward: self.data._reset_velocity() # set into simulation - self._binding_write(TT.LINK_VELOCITY, self.data._body_com_vel_w.data, env_ids=env_ids) + self._write_to_view_index(TT.LINK_VELOCITY, self.data._body_com_vel_w.data, env_ids=env_ids) def write_body_com_velocity_to_sim_mask( self, @@ -629,28 +615,21 @@ def write_body_com_velocity_to_sim_mask( skip_forward: Whether to skip invalidating cached data after the write. When True, the caller must invalidate stale cached data before reading it back. Defaults to False. """ - env_ids = self._resolve_env_ids(env_mask=env_mask) - body_ids = self._resolve_body_ids(body_mask=body_mask) - self.assert_shape_and_dtype( - body_velocities, (self._num_instances, self._num_bodies), wp.spatial_vectorf, "body_velocities" - ) + env_mask = self._resolve_env_mask(env_mask) + body_mask = self._resolve_body_mask(body_mask) + self.assert_shape_and_dtype_mask(body_velocities, (env_mask, body_mask), wp.spatial_vectorf, "body_velocities") wp.launch( - shared_kernels.set_body_com_velocity_to_sim_kernel(env_ids, body_ids), - dim=(env_ids.shape[0], body_ids.shape[0]), - inputs=[body_velocities, env_ids, body_ids, True], - outputs=[ - self.data._body_com_vel_w.data, - self.data._body_com_acc_w.data, - self.data._body_state_w.data, - self.data._body_com_state_w.data, - ], + shared_kernels.set_body_com_velocity_to_sim_mask, + dim=(env_mask.shape[0], body_mask.shape[0]), + inputs=[body_velocities, env_mask, body_mask], + outputs=[self.data._body_com_vel_w.data, self.data._body_com_acc_w.data], device=self._device, ) # Invalidate dependent timestamps if not skip_forward: self.data._reset_velocity() # set into simulation - self._binding_write(TT.LINK_VELOCITY, self.data._body_com_vel_w.data, env_ids=env_ids) + self._write_to_view_mask(TT.LINK_VELOCITY, self.data._body_com_vel_w.data, env_mask, body_mask) def write_body_link_velocity_to_sim_index( self, @@ -708,7 +687,7 @@ def write_body_link_velocity_to_sim_index( if not skip_forward: self.data._reset_velocity(from_com=False) # set into simulation - self._binding_write(TT.LINK_VELOCITY, self.data._body_com_vel_w.data, env_ids=env_ids) + self._write_to_view_index(TT.LINK_VELOCITY, self.data._body_com_vel_w.data, env_ids=env_ids) def write_body_link_velocity_to_sim_mask( self, @@ -736,37 +715,21 @@ def write_body_link_velocity_to_sim_mask( skip_forward: Whether to skip invalidating cached data after the write. When True, the caller must invalidate stale cached data before reading it back. Defaults to False. """ - env_ids = self._resolve_env_ids(env_mask=env_mask) - body_ids = self._resolve_body_ids(body_mask=body_mask) - self.assert_shape_and_dtype( - body_velocities, (self._num_instances, self._num_bodies), wp.spatial_vectorf, "body_velocities" - ) + env_mask = self._resolve_env_mask(env_mask) + body_mask = self._resolve_body_mask(body_mask) + self.assert_shape_and_dtype_mask(body_velocities, (env_mask, body_mask), wp.spatial_vectorf, "body_velocities") wp.launch( - shared_kernels.set_body_link_velocity_to_sim_kernel(env_ids, body_ids), - dim=(env_ids.shape[0], body_ids.shape[0]), - inputs=[ - body_velocities, - self.data.body_com_pose_b, - self.data.body_link_pose_w, - env_ids, - body_ids, - True, - ], - outputs=[ - self.data._body_link_vel_w.data, - self.data._body_com_vel_w.data, - self.data._body_com_acc_w.data, - self.data._body_link_state_w.data, - self.data._body_state_w.data, - self.data._body_com_state_w.data, - ], + shared_kernels.set_body_link_velocity_to_sim_mask, + dim=(env_mask.shape[0], body_mask.shape[0]), + inputs=[body_velocities, self.data.body_com_pose_b, self.data.body_link_pose_w, env_mask, body_mask], + outputs=[self.data._body_link_vel_w.data, self.data._body_com_vel_w.data, self.data._body_com_acc_w.data], device=self._device, ) # Invalidate dependent timestamps if not skip_forward: self.data._reset_velocity(from_com=False) # set into simulation - self._binding_write(TT.LINK_VELOCITY, self.data._body_com_vel_w.data, env_ids=env_ids) + self._write_to_view_mask(TT.LINK_VELOCITY, self.data._body_com_vel_w.data, env_mask, body_mask) """ Operations - Setters. @@ -803,7 +766,7 @@ def set_masses_index( wp.copy(selected, values) wp.copy(self.data._cpu_body_mass, self.data._body_mass.data) wp.synchronize_stream(self._device) - self._binding_write( + self._write_to_view_index( TT.BODY_MASS, self.data._cpu_body_mass, env_ids=env_ids, @@ -844,7 +807,7 @@ def set_masses_mask( ) wp.copy(self.data._cpu_body_mass, self.data._body_mass.data) wp.synchronize_stream(self._device) - self._binding_write(TT.BODY_MASS, self.data._cpu_body_mass, env_ids=env_ids, device="cpu") + self._write_to_view_index(TT.BODY_MASS, self.data._cpu_body_mass, env_ids=env_ids, device="cpu") def set_coms_index( self, @@ -879,7 +842,7 @@ def set_coms_index( self.data._reset_body_com_pose_b_dependents() wp.copy(self.data._cpu_body_coms, self.data._body_com_pose_b.data.view(wp.float32)) wp.synchronize_stream(self._device) - self._binding_write( + self._write_to_view_index( TT.BODY_COM_POSE, self.data._cpu_body_coms, env_ids=env_ids, @@ -923,7 +886,7 @@ def set_coms_mask( self.data._reset_body_com_pose_b_dependents() wp.copy(self.data._cpu_body_coms, self.data._body_com_pose_b.data.view(wp.float32)) wp.synchronize_stream(self._device) - self._binding_write( + self._write_to_view_index( TT.BODY_COM_POSE, self.data._cpu_body_coms, env_ids=env_ids, @@ -964,7 +927,7 @@ def set_inertias_index( wp.copy(selected, values) wp.copy(self.data._cpu_body_inertia, self.data._body_inertia.data) wp.synchronize_stream(self._device) - self._binding_write( + self._write_to_view_index( TT.BODY_INERTIA, self.data._cpu_body_inertia, env_ids=env_ids, @@ -1008,7 +971,7 @@ def set_inertias_mask( ) wp.copy(self.data._cpu_body_inertia, self.data._body_inertia.data) wp.synchronize_stream(self._device) - self._binding_write( + self._write_to_view_index( TT.BODY_INERTIA, self.data._cpu_body_inertia, env_ids=env_ids, @@ -1127,9 +1090,36 @@ def _create_buffers(self) -> None: self._ALL_TRUE_ENV_MASK = wp.array(np.ones(N, dtype=bool), dtype=wp.bool, device=self._device) self._ALL_TRUE_BODY_MASK = wp.array(np.ones(B, dtype=bool), dtype=wp.bool, device=self._device) - # External wrench buffer: direct (N, B, 9) contiguous allocation. - # The fused LINK_WRENCH binding writes from a single (N, B, 9) buffer. - self._wrench_buf = wp.zeros((N, B, 9), dtype=wp.float32, device=self._device) + # External wrench rows the view writes, and the (N, B, 9) view of them the wrench kernel fills. The + # articulation-mode mock used by iface tests binds instance-major (N, B, 9) rows; the native fused binding lays + # them body-major flat as (N * B, 9) (view id = body * N + env), which the kernel fills through an + # instance-major strided view, so every write hands the view the same buffer. + self._fused_layout = self._data._fused_layout + binding = self._get_binding(TT.LINK_WRENCH) + self._has_wrench_binding = binding is not None + if binding is None or not self._fused_layout: + self._wrench_buf = wp.zeros((N, B, 9), dtype=wp.float32, device=self._device) + self._wrench_kernel_out = self._wrench_buf + else: + self._wrench_buf = wp.zeros((B * N, 9), dtype=wp.float32, device=self._device) + self._wrench_kernel_out = wp.array( + ptr=self._wrench_buf.ptr, + shape=(N, B, 9), + dtype=wp.float32, + strides=(9 * 4, N * 9 * 4, 4), + device=self._device, + ) + + # Masked pose and velocity writes on the native fused binding (_write_to_view_mask): the selected (env, body) + # entries in view order (view_id = body_id * N + env_id) and the view mask over them, refilled in place by every + # masked write, so its captured session write keeps reading the same buffers. The articulation-mode mock binds + # instance-major rows and takes the env mask instead. + pose = self._get_binding(TT.LINK_POSE) + self._view_bufs: dict[int, wp.array] = {} + if pose is not None and self._fused_layout: + self._view_bufs[TT.LINK_POSE] = wp.zeros(B * N, dtype=wp.transformf, device=self._device) + self._view_bufs[TT.LINK_VELOCITY] = wp.zeros(B * N, dtype=wp.spatial_vectorf, device=self._device) + self._view_mask = wp.zeros(B * N, dtype=wp.bool, device=self._device) self._instantaneous_wrench_composer = WrenchComposer(self, supports_world_at_com=True) self._permanent_wrench_composer = WrenchComposer(self, supports_world_at_com=True) @@ -1258,7 +1248,7 @@ def reshape_data_to_view_3d( ) return wp.clone(strided_view, device=device).reshape((self.num_bodies * self.num_instances, data_dim)) - def _binding_write( + def _write_to_view_index( self, tensor_type: int, instance_major_data: wp.array, @@ -1298,11 +1288,9 @@ def _binding_write( return if device is None: device = self._device - # Disambiguate via the binding's exposed shape: the articulation-mode - # mock returns a directly instance-major view ``(N, B[, D])`` while the - # native fused multi-prim binding lays elements body-major-flat with - # ``shape == (N * B[, D])``. - is_mock_layout = len(binding.shape) >= 2 and binding.shape[1] == self._num_bodies + # The articulation-mode mock returns a directly instance-major view ``(N, B[, D])``; the native fused + # multi-prim binding lays elements body-major-flat with ``shape == (N * B[, D])``. + is_mock_layout = not self._fused_layout if is_mock_layout: float32_data = ( instance_major_data if instance_major_data.dtype == wp.float32 else instance_major_data.view(wp.float32) @@ -1319,6 +1307,35 @@ def _binding_write( view_ids = self._env_body_ids_to_view_ids(env_ids, self._ALL_BODY_INDICES, device=device) self._root_view.set_attribute(tensor_type, view, indices=view_ids) + def _write_to_view_mask( + self, tensor_type: int, instance_major_data: wp.array, env_mask: wp.array, body_mask: wp.array + ) -> None: + """Write the selected (env, body) entries of an instance-major ``(N, B)`` buffer to a fused binding by mask. + + Mask counterpart of :meth:`_write_to_view_index`. On the native fused binding the entries go to their + body-major view rows (``view_id = body_id * N + env_id``, as :meth:`reshape_data_to_view_2d` lays them out) in a + buffer kept across calls, and the view mask marks them, so a CUDA simulation commits them through one captured + session write per type. The articulation-mode mock binds instance-major rows and takes the env mask. + + Args: + tensor_type: ``TT.LINK_POSE`` or ``TT.LINK_VELOCITY``. + instance_major_data: The written cache, shape ``(num_instances, num_bodies)``. + env_mask: Selected environments, shape ``(num_instances,)``, on ``self._device``. + body_mask: Selected bodies, shape ``(num_bodies,)``, on ``self._device``. + """ + view_buf = self._view_bufs.get(tensor_type) + if view_buf is None: + self._root_view.set_attribute(tensor_type, instance_major_data, mask=env_mask) + return + wp.launch( + shared_kernels.reshape_data_to_view_mask, + dim=(env_mask.shape[0], body_mask.shape[0]), + inputs=[instance_major_data, env_mask, body_mask], + outputs=[view_buf, self._view_mask], + device=self._device, + ) + self._root_view.set_attribute(tensor_type, view_buf, mask=self._view_mask) + """ Internal helper. """ @@ -1344,8 +1361,8 @@ def _env_body_ids_to_view_ids( Computes ``view_id = body_id * num_instances + env_id`` for each (env_id, body_id) pair. The output array is laid out column-major over the (env, body) grid, matching the PhysX ``root_view`` ordering. - The mask writers convert their masks to ids for this: a binding write mask must cover all - ``num_bodies * num_instances`` rows, so an env mask does not fit. + The index writers use it; the mask writers mark the same rows in a view mask + (:meth:`_write_to_view_mask`). Args: env_ids: Environment indices. @@ -1393,8 +1410,16 @@ def _resolve_env_mask(self, env_mask: wp.array | None) -> wp.array: Returns: A ``wp.bool`` array of shape (num_instances,) on ``self._device``. + + Raises: + ValueError: If the mask does not hold one entry per environment. """ - return resolve_1d_mask(mask=env_mask, all_mask=self._ALL_TRUE_ENV_MASK) + mask = resolve_1d_mask(mask=env_mask, all_mask=self._ALL_TRUE_ENV_MASK) + if mask.shape[0] != self._num_instances: # a shorter mask would leave the other rows' view-mask entries stale + raise ValueError( + f"env_mask must hold one entry per environment ({self._num_instances}), got {mask.shape[0]}." + ) + return mask def _resolve_body_mask(self, body_mask: wp.array | None) -> wp.array: """Resolve a body mask to a ``wp.bool`` array on ``self._device``. @@ -1406,8 +1431,14 @@ def _resolve_body_mask(self, body_mask: wp.array | None) -> wp.array: Returns: A ``wp.bool`` array of shape (num_bodies,) on ``self._device``. + + Raises: + ValueError: If the mask does not hold one entry per body. """ - return resolve_1d_mask(mask=body_mask, all_mask=self._ALL_TRUE_BODY_MASK) + mask = resolve_1d_mask(mask=body_mask, all_mask=self._ALL_TRUE_BODY_MASK) + if mask.shape[0] != self._num_bodies: # a shorter mask would leave the other rows' view-mask entries stale + raise ValueError(f"body_mask must hold one entry per body ({self._num_bodies}), got {mask.shape[0]}.") + return mask def _sim_env_ids_view(self, count: int) -> wp.array: """Return a cached prefix of the simulator-index scratch buffer.""" diff --git a/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection_data.py b/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection_data.py index cc123cb7bc3f..f9d2db6a2540 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection_data.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection_data.py @@ -94,15 +94,12 @@ def __init__( # never crosses devices. self._cpu_staging_buffers: dict[int, wp.array] = {} - # Read num_instances from the LINK_POSE binding. The native fused multi-prim binding lays - # elements out body-major-flat with ``shape == (N * B, 7)`` and ``count == N * B``. The - # articulation-mode mock used by iface tests exposes an instance-major view directly with - # ``shape == (N, B, 7)`` and ``count == N``. Dispatch via the binding's exposed shape. + # Read num_instances from the LINK_POSE binding: the native fused binding is body-major flat (N * B, 7) and + # counts N * B elements; the articulation-mode mock of the iface tests is instance-major (N, B, 7) and counts N. pose_binding = self._view.binding_for(TT.LINK_POSE) - if len(pose_binding.shape) >= 2 and pose_binding.shape[1] == num_bodies: - self.num_instances = pose_binding.count - else: - self.num_instances = pose_binding.count // num_bodies + self._fused_layout = len(pose_binding.shape) == 2 + pose_count = pose_binding.count + self.num_instances = pose_count // num_bodies if self._fused_layout else pose_count self._num_instances = self.num_instances if self._backend_manager._sim is not None and hasattr(self._backend_manager._sim, "cfg"): @@ -1040,13 +1037,9 @@ def _read_binding_into_instance_major(self, tensor_type: int, buf: TimestampedBu if binding is None: return - B = self.num_bodies - - # Disambiguate via the binding's exposed shape: the articulation-mode - # mock returns a directly instance-major view ``(N, B[, D])`` while the - # native fused multi-prim binding lays elements body-major-flat with - # ``shape == (N * B[, D])``. - is_mock_layout = len(binding.shape) >= 2 and binding.shape[1] == B + # The articulation-mode mock returns a directly instance-major view ``(N, B[, D])``; the native fused + # multi-prim binding lays elements body-major-flat with ``shape == (N * B[, D])``. + is_mock_layout = not self._fused_layout if is_mock_layout: if buf.data.dtype == wp.float32: diff --git a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py index e27531e151e3..2631d687a0ed 100644 --- a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py +++ b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py @@ -504,7 +504,7 @@ def _classify_physics(stage: Usd.Stage, source: str) -> tuple[bool, bool]: return has_physics, False -def _serialize_stage( +def _export_stage( stage: Usd.Stage, recipes: Sequence[CloneRecipe], full_stage: bool, @@ -513,7 +513,7 @@ def _serialize_stage( friction_replacements: dict[str, tuple[float, float, float]] | None = None, filter_render_only: bool = False, preserve_physics_ancestors: bool = False, -) -> tuple[str, list[CloneRecipe]]: +) -> tuple[Usd.Stage, list[CloneRecipe]]: """Export complete original worlds once and compile copies from those originals. Parsed bodies have native environment ID zero. An original-bearing world must therefore @@ -644,4 +644,4 @@ def _serialize_stage( del (parent.nameChildren if parent else layer.rootPrims)[spec.name] spec = parent - return layer.ExportToString(), list(native.values()) + return exported, list(native.values()) # the flattened, filtered stage ovphysx loads diff --git a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py index db79ce49bc00..a8f27bbed7e2 100644 --- a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py +++ b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py @@ -27,7 +27,7 @@ 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 @@ -45,7 +45,8 @@ 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.cloner.replicate import _export_stage +from isaaclab_ov.sim.views.ovphysx_captured_sessions import OvPhysxCapturedSessions from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView from isaaclab_ov.stage import OvstageBackend, OvstageBackendCfg @@ -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 @@ -297,12 +305,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 must first wait for that stream, which the reader arranges. + """ 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 @@ -337,27 +349,35 @@ 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 - - def load(self, stage_usda: str, *, disable_compiled_stage_cache: bool = False) -> None: + self.captured_sessions: OvPhysxCapturedSessions | None = None + """Session reads and writes behind :meth:`OvPhysxView.read_into` and :meth:`OvPhysxView.set_attribute`; ``None`` + before a stage attaches or on a CPU scene.""" + self.usd_stage: Usd.Stage | None = None + """The USD stage the attached scene was populated from: the lookups the ovstage stage cannot answer, such as + tendon names and deformable mesh frames; ``None`` before a stage attaches.""" + self._device = cfg.device + + def load(self, usd_stage: Usd.Stage, *, disable_compiled_stage_cache: bool = False) -> None: """Replace the attached scene after draining its native bindings. Args: - stage_usda: Exported USD scene to populate before physics attaches. + usd_stage: Exported USD scene to populate before physics attaches. disable_compiled_stage_cache: Bypass the compiled-stage cache for this attachment. """ 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_captured_sessions() self.physx.wait_task(self.physx.detach_ovstage()) self.scene.reset() - self.stage = None + self.stage = self.usd_stage = None if self.scene is None: # Include rendering data for native-instance collider dependencies as well as physics. self.scene = instantiate(OvstageBackendCfg(populate_physics=True)) try: - self.scene.populate(stage_usda) + self.scene.populate(usd_stage.GetRootLayer().ExportToString()) with _compiled_stage_cache_for_attach(disable_compiled_stage_cache): operation = self.physx.attach_ovstage(self.scene.stage, read_ordinal=self.scene.ordinal - 1) # Accepted attach failures can retain native ownership. Keep the stage for cleanup. @@ -368,6 +388,9 @@ def load(self, stage_usda: str, *, disable_compiled_stage_cache: bool = False) - self.scene.close() self.scene = None raise + self.usd_stage = usd_stage + if wp.get_device(self._device).is_cuda: # a CPU scene reads its bindings + self.captured_sessions = OvPhysxCapturedSessions(self.physx, self.stage, self._device, usd_stage) def close(self) -> None: """Release bindings, the runtime, and its stage in native teardown order.""" @@ -375,7 +398,7 @@ def close(self) -> None: if physx is None: if self.owns_scene and self.scene is not None: self.scene.close() - self.stage = None + self.stage = self.usd_stage = None return # Destroy errors may retain native ownership and require another close. @@ -383,9 +406,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_captured_sessions() finally: try: physx.wait_task(physx.detach_ovstage()) @@ -408,7 +432,15 @@ def close(self) -> None: self.physx = None if self.owns_scene and self.scene is not None: self.scene.close() - self.stage = None + self.stage = self.usd_stage = None + + def _close_captured_sessions(self) -> None: + """Release the captured reads and writes after their views and before the stage detaches.""" + if self.captured_sessions is not None: + try: + self.captured_sessions.close() + finally: + self.captured_sessions = None class _OvPhysxEvent(Enum): @@ -436,7 +468,6 @@ def __init__(self, cfg: OvPhysxCfg): self._cfg: OvPhysxCfg = cfg self.backend: OvPhysxBackend | None = None """Native resource borrowed from the context registry after warmup.""" - self._stage_usda: str | None = None self._warmup_done: bool = False self._requires_full_stage: bool = False self._clone_recipes: list[CloneRecipe] = [] @@ -558,7 +589,6 @@ def initialize(self, sim_context: SimulationContext) -> None: self._gravity_stage = None self._warmup_done = False self._requires_full_stage = False - self._stage_usda = None self._clone_recipes = [] # SimulationContext retains this backend; native bindings remain deferred until the first SDP read. self._scene_data_backend = OvPhysxSceneDataBackend(self) @@ -605,7 +635,11 @@ 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() + sessions = self.backend.captured_sessions + if sessions is None: + self.backend.physx.update_articulations_kinematic() + else: + sessions.update_kinematics() # over a held query, on the stream where the link-pose replays read it self.kinematics_dirty = False def step(self) -> None: @@ -613,6 +647,8 @@ def step(self) -> None: if self.backend is None or self.backend.physx is None: return dt = self.get_physics_dt() + if self.backend.captured_sessions is not None: + self.backend.captured_sessions.wait() # ovphysx forbids stepping while a captured replay runs self.backend.physx.step_sync(dt=dt) self.kinematics_dirty = True self.update_kinematics() @@ -643,7 +679,6 @@ def close(self) -> None: atexit.unregister(self._close_at_exit) self._atexit_registered = False finally: - self._stage_usda = None self._gravity_stage = None self._warmup_done = False self._requires_full_stage = False @@ -772,7 +807,7 @@ def _warmup_and_load(self) -> None: self._configure_physics_scenes(sim.stage, sim.cfg.physics_prim_path, self._cfg, ovphysx_device) - stage_usda, native_clones = _serialize_stage( + usd_stage, native_clones = _export_stage( sim.stage, self._clone_recipes, full_stage, @@ -781,7 +816,6 @@ def _warmup_and_load(self) -> None: filter_render_only=shared_scene is not None, preserve_physics_ancestors=shared_scene is not None, ) - self._stage_usda = stage_usda self.backend = sim.get_or_create_backend( OvPhysxBackendCfg( @@ -793,7 +827,7 @@ def _warmup_and_load(self) -> None: if not self._atexit_registered: 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) + self.backend.load(usd_stage, disable_compiled_stage_cache=self._cfg.disable_compiled_stage_cache) logger.info("OvPhysxManager: attached OVStage to ovphysx (device=%s)", ovphysx_device) for source, targets, transforms, env_ids, _ in native_clones: diff --git a/source/isaaclab_ov/isaaclab_ov/sim/views/ovphysx_captured_sessions.py b/source/isaaclab_ov/isaaclab_ov/sim/views/ovphysx_captured_sessions.py new file mode 100644 index 000000000000..35723e8bf683 --- /dev/null +++ b/source/isaaclab_ov/isaaclab_ov/sim/views/ovphysx_captured_sessions.py @@ -0,0 +1,957 @@ +# 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 + +"""Captured ovphysx session reads and writes of the GPU simulation state, behind :meth:`OvPhysxView.read_into` and +:meth:`OvPhysxView.set_attribute`. + +On a CUDA scene, :class:`OvPhysxCapturedSessions` serves the tensor types in :data:`READS` and :data:`WRITES`: +simulation state and controls that ovphysx keeps on the GPU. The first read of a (view, tensor type, destination) holds +an ovphysx query over the binding's prims, maps the session's rows onto the binding's layout, and captures "session +read + copy kernels" into one CUDA graph; a write captures "copy kernels + commit" the same way, from its source. Both +read the caller's buffers in place, so callers pass buffers kept across calls. Every later call replays the graph, or, +inside the caller's capture, records it into the caller's graph. Every other type, +and every read or write of a CPU scene, stays on the binding: ovphysx cannot capture its host-resident properties or +contacts, and an uncaptured session read or write costs more per call than the binding's. + +The module is internal to :mod:`isaaclab_ov`: :class:`OvPhysxBackend` owns one instance per CUDA ``PhysX`` instance, +:class:`OvPhysxView` routes its reads and writes to it, and :class:`OvPhysxManager` waits for its replays before a +step and closes it before the stage detaches. +""" + +from __future__ import annotations + +import contextlib +import math +from collections.abc import Callable, Iterable, Iterator +from dataclasses import dataclass, field +from typing import Any, ClassVar + +import numpy as np +import ovstage +import warp as wp +from ovphysx.types import SimObjectType, TensorType + +from pxr import Usd, UsdGeom + +_POSE = ("position", "orientation") +_VELOCITY = ("linearVelocity", "angularVelocity") +_ACCELERATION = ("linearAcceleration", "angularAcceleration") + +SESSION_ATTRIBUTES: dict[TensorType, tuple[SimObjectType, tuple[str, ...]]] = { + TensorType.ARTICULATION_ROOT_POSE: (SimObjectType.ARTICULATION, ("rootPosition", "rootOrientation")), + TensorType.ARTICULATION_ROOT_VELOCITY: (SimObjectType.ARTICULATION, ("rootLinearVelocity", "rootAngularVelocity")), + TensorType.ARTICULATION_JACOBIAN: (SimObjectType.ARTICULATION, ("jacobian",)), + TensorType.ARTICULATION_MASS_MATRIX: (SimObjectType.ARTICULATION, ("massMatrix",)), + TensorType.ARTICULATION_LINK_POSE: (SimObjectType.ARTICULATION_LINK, _POSE), + TensorType.ARTICULATION_LINK_VELOCITY: (SimObjectType.ARTICULATION_LINK, _VELOCITY), + TensorType.ARTICULATION_LINK_ACCELERATION: (SimObjectType.ARTICULATION_LINK, _ACCELERATION), + TensorType.ARTICULATION_LINK_INCOMING_JOINT_FORCE: (SimObjectType.ARTICULATION_LINK, ("linkIncomingJointForce",)), + TensorType.ARTICULATION_LINK_WRENCH: (SimObjectType.ARTICULATION_LINK, ("wrench",)), + TensorType.ARTICULATION_DOF_POSITION: (SimObjectType.ARTICULATION_JOINT, ("jointPosition",)), + TensorType.ARTICULATION_DOF_VELOCITY: (SimObjectType.ARTICULATION_JOINT, ("jointVelocity",)), + TensorType.ARTICULATION_DOF_POSITION_TARGET: (SimObjectType.ARTICULATION_JOINT, ("jointPositionTarget",)), + TensorType.ARTICULATION_DOF_VELOCITY_TARGET: (SimObjectType.ARTICULATION_JOINT, ("jointVelocityTarget",)), + TensorType.ARTICULATION_DOF_ACTUATION_FORCE: (SimObjectType.ARTICULATION_JOINT, ("jointActuationForce",)), + TensorType.RIGID_BODY_POSE: (SimObjectType.RIGID_BODY, _POSE), + TensorType.RIGID_BODY_VELOCITY: (SimObjectType.RIGID_BODY, _VELOCITY), + TensorType.RIGID_BODY_ACCELERATION: (SimObjectType.RIGID_BODY, _ACCELERATION), + TensorType.RIGID_BODY_WRENCH: (SimObjectType.RIGID_BODY, ("wrench",)), + TensorType.DEFORMABLE_SIM_NODAL_POSITION: (SimObjectType.DEFORMABLE_VOLUME, ("points",)), + TensorType.DEFORMABLE_SIM_NODAL_VELOCITY: (SimObjectType.DEFORMABLE_VOLUME, ("velocities",)), + TensorType.SURFACE_DEFORMABLE_SIM_POSITION: (SimObjectType.DEFORMABLE_SURFACE, ("points",)), + TensorType.SURFACE_DEFORMABLE_SIM_VELOCITY: (SimObjectType.DEFORMABLE_SURFACE, ("velocities",)), +} +"""The session attributes behind each tensor type a captured session reads or writes: the session object type, and +the attributes whose lanes, concatenated, form one binding row. The object type sets how session rows map onto binding +rows: one per prim (one per link of each articulation for links), one per joint axis, or one per node of a deformable +body. + +Kept by Lab, which chooses the types served here: ovphysx's ``tensor_binding_migration.md`` maps part of them, and +``read_write/readable.md`` lists every attribute.""" + +READS = frozenset( + ( + TensorType.ARTICULATION_ROOT_POSE, + TensorType.ARTICULATION_ROOT_VELOCITY, + TensorType.ARTICULATION_JACOBIAN, + TensorType.ARTICULATION_MASS_MATRIX, + TensorType.ARTICULATION_LINK_POSE, + TensorType.ARTICULATION_LINK_VELOCITY, + TensorType.ARTICULATION_LINK_ACCELERATION, + TensorType.ARTICULATION_LINK_INCOMING_JOINT_FORCE, + TensorType.ARTICULATION_DOF_POSITION, + TensorType.ARTICULATION_DOF_VELOCITY, + TensorType.RIGID_BODY_POSE, + TensorType.RIGID_BODY_VELOCITY, + TensorType.RIGID_BODY_ACCELERATION, + TensorType.DEFORMABLE_SIM_NODAL_POSITION, + TensorType.DEFORMABLE_SIM_NODAL_VELOCITY, + TensorType.SURFACE_DEFORMABLE_SIM_POSITION, + TensorType.SURFACE_DEFORMABLE_SIM_VELOCITY, + ) +) +"""Tensor types read through captured session reads. The asset tests compare each with its binding read.""" + +WRITES = frozenset( + ( + TensorType.ARTICULATION_DOF_POSITION_TARGET, + TensorType.ARTICULATION_DOF_VELOCITY_TARGET, + TensorType.ARTICULATION_DOF_ACTUATION_FORCE, + TensorType.ARTICULATION_LINK_WRENCH, + TensorType.RIGID_BODY_POSE, + TensorType.RIGID_BODY_VELOCITY, + TensorType.RIGID_BODY_WRENCH, + ) +) +"""Tensor types written through captured session writes. + +Every attribute here is a device column on a DirectGPU scene, so its commit can be captured. A ``wrench`` (force, +torque, world application point) applies for one step, as the binding's does. Host-resident properties (mass, inertia, +centre of mass, joint drive and limit properties) and deformable points and velocities, which ovphysx applies on the +host, stay on the binding. So do articulation root and joint state: a DirectGPU commit of them writes every +articulation of the scene back, unselected ones with their current values, and the next kinematic refresh then zeroes +their link accelerations and incoming joint forces until the next step. So do wrench writes by mask: a masked wrench +commit clears the wrench of every row it leaves out, so of two masked writes before a step only the second would apply +(ovphysx 0.8.1 ``read_write/writable.md``). The asset tests compare each type with its binding write.""" + +WRENCH_WRITES = frozenset((TensorType.ARTICULATION_LINK_WRENCH, TensorType.RIGID_BODY_WRENCH)) +"""Wrench writes: every view's graphs capture again after a centre-of-mass write (:data:`COM_WRITES`).""" + +COM_WRITES = frozenset((TensorType.ARTICULATION_BODY_COM_POSE, TensorType.RIGID_BODY_COM_POSE)) +"""Centre-of-mass writes (binding writes): ovphysx requires a wrench graph to capture again after one changes the centre +of mass of a body it writes, with no replay running meanwhile (ovphysx ``read_write/device.md``).""" + +_DEFORMABLES = (SimObjectType.DEFORMABLE_VOLUME, SimObjectType.DEFORMABLE_SURFACE) + +_ANGULAR_JOINT_TYPES = (2, 3, 4) +"""``dofJointType`` values whose axis the session reports in degrees: revolute, unwrapped revolute, spherical.""" + +_DEGREE_ATTRIBUTES = frozenset(("jointPosition", "jointVelocity", "jointPositionTarget", "jointVelocityTarget")) +"""Joint attributes the session holds in degrees (per second) on an angular axis; an actuation force has no angle.""" + + +class OvPhysxCapturedSessions: + """Captured ovphysx session reads and writes of one CUDA ``PhysX`` instance, owned by its :class:`OvPhysxBackend`. + + Each (view, tensor type, destination) holds one captured read: the queries it reads and the graph that refreshes the + destination from them. Each (view, tensor type, source, selection) holds one captured write, whole or through the + caller's mask buffer: the queries and open write sessions it commits and the graph that copies the source into + them. Both replay on one stream, the caller's current Warp stream at the first replay. + """ + + _by_physx: ClassVar[dict[int, OvPhysxCapturedSessions]] = {} + + def __init__(self, physx: Any, stage: Any, device: str, usd_stage: Usd.Stage) -> None: + self._physx = physx + self._stage = stage + self._device = wp.get_device(device) + # Captures: recorded on a stream owned here, replayed on the caller's stream (:attr:`caller_stream`). + self._capture_stream = wp.Stream(self._device) + self._reads: dict[tuple[int, TensorType, int], _Capture] = {} # by (id(view), tensor type, dst.ptr) + # by (id(view), tensor type, src.ptr, the mask's (ptr, shape, strides) or None) + self._writes: dict[tuple[int, TensorType, int, tuple | None], _Capture] = {} + self._stream: wp.Stream | None = None # the one stream every replay runs on: the first replay's + self._kinematics_query: Any = None # the held ARTICULATION query update_kinematics refreshes over + self._usd_stage = usd_stage # the USD stage ovphysx loaded, for its sim meshes' frames + OvPhysxCapturedSessions._by_physx[id(physx)] = self + + """ + Operations. + """ + + @classmethod + def for_physx(cls, physx: Any) -> OvPhysxCapturedSessions | None: + """Return the session reads and writes of ``physx``, or ``None`` on a CPU scene, which uses its bindings.""" + return cls._by_physx.get(id(physx)) + + @property + def caller_stream(self) -> wp.Stream: + """The caller's current stream on the simulation device: replays run on it. + + Its ``cuda_stream`` is ``None`` for Warp's null stream, the legacy default stream ovphysx takes as ``0``. + """ + return wp.get_stream(self._device) + + @staticmethod + def takes_read(tensor_type: TensorType) -> bool: + """Whether a read of ``tensor_type`` replays a captured session read: a type in :data:`READS`.""" + return tensor_type in READS + + @staticmethod + def takes_write(tensor_type: TensorType, values: Any, *, indices: Any, mask: Any = None) -> bool: + """Whether a write replays a captured session write: a type in :data:`WRITES`, whole or by mask, from a Warp + array the graph can keep reading. A write by ``indices`` or from host data, and a wrench write by mask, take the + binding; the mask must be a ``bool`` array on the simulation device (:meth:`write_from`).""" + # An ovphysx 0.8.1 masked wrench commit clears the wrench of the rows it leaves out, earlier writes' included. + if mask is not None and tensor_type in WRENCH_WRITES: + return False + # A host upload is a temporary the graph cannot keep reading. + return tensor_type in WRITES and indices is None and isinstance(values, wp.array) + + def before_binding_write(self, tensor_type: TensorType) -> None: + """Release every view's wrench writes before a centre-of-mass binding write; other types need nothing. + + A wrench graph must capture again once the centre of mass of a body it writes changes, which no replay may + overlap (ovphysx ``read_write/device.md``); another view may write the same body's wrench, so the release waits + for the replays and covers every view. + """ + if tensor_type in COM_WRITES: + self.release(None, WRENCH_WRITES) + + def read_into(self, view: Any, tensor_type: TensorType, binding: Any, dst: wp.array) -> None: + """Replay the captured read of ``tensor_type``, a type in :data:`READS`, into the flat binding-layout ``dst``. + + Inside the caller's capture on its current stream, the read records its graph into the caller's graph instead, + so each replay of that graph refreshes ``dst``. The read must have run once outside any capture, as in a warmup + step, and the caller's graph must be captured again after :meth:`release` or :meth:`invalidate`. + + A Jacobian or mass matrix replays from the link poses as last refreshed: unlike its binding read, it does not + refresh the kinematics, which :meth:`OvPhysxManager.update_kinematics` does, as for link-pose reads. + + Raises: + ValueError: If the session's rows cannot be laid out over the binding's. + RuntimeError: If the caller's capture cannot record the read. + """ + # 1. Destinations with nothing to read, e.g. the joints of an articulation without DOFs. + if dst.size == 0: + return + # 2. Capture the read on the first call for this view, type and destination, outside any capture. + stream = self._replay_stream() + key = (id(view), tensor_type, dst.ptr) + captured = self._reads.get(key) + if captured is None: + if self._device.is_capturing: + raise RuntimeError( + f"{tensor_type.name}: the read must capture, which a capture cannot record: read once outside any " + "capture into this buffer first." + ) + captured = self._reads[key] = self._capture_read(tensor_type, binding, dst) + # 3. Replay it on the replay stream, or record it into the caller's capture. + self._launch(captured.graph, stream) + + def write_from( + self, view: Any, tensor_type: TensorType, binding: Any, src: wp.array, mask: wp.array | None = None + ) -> None: + """Replay the captured write of ``tensor_type``, a type in :data:`WRITES`, from the flat binding-layout ``src``. + + ``src`` holds every binding row, as for the binding write; ``mask`` (one ``bool`` per binding instance) commits + only the selected instances' rows. The write reads ``src`` and ``mask`` in place, so callers pass buffers kept + across calls, as the assets do with their state and command buffers and their all-true mask, and the assets' + callers with their reset masks. Each (view, type, source buffer, mask buffer) captures once. The write runs on + the caller's current stream after the work queued there, and the next step waits for it. Inside the caller's + capture it records its graph into the caller's graph, as :meth:`read_into` does, once the same write has run + outside any capture. + + Raises: + ValueError: If ``mask`` is not a contiguous array of one ``bool`` per binding instance on the simulation + device, or the session's rows cannot be laid out over the binding's. + RuntimeError: If the write must capture inside the caller's capture, or the caller's capture cannot record + it. + """ + # 1. Sources with nothing to write, e.g. the joints of an articulation without DOFs. + if src.size == 0: + return + # 2. Capture the write on the first call for this view, type, source and mask buffer, outside any capture. + stream = self._replay_stream() + selection = None # a whole write; a masked one keys on its buffer, so an empty or reshaped mask never hits it + if mask is not None: + selection = (mask.ptr, mask.shape, mask.strides) + key = (id(view), tensor_type, src.ptr, selection) + captured = self._writes.get(key) + if captured is None: + if self._device.is_capturing: + raise RuntimeError( + f"{tensor_type.name}: the write must capture, which a capture cannot record: write once outside " + "any capture from this source and mask first." + ) + captured = self._writes[key] = self._capture_write(tensor_type, binding, src, mask) + # 3. Replay on the replay stream, or record into the caller's capture. + self._launch(captured.graph, stream) + + def update_kinematics(self) -> None: + """Refresh every articulation's link state from its joint state on the caller's stream, for + :meth:`~isaaclab_ov.physics.OvPhysxManager.update_kinematics`. + + Eager, over one held ARTICULATION query: the refresh only queues device work, where a refresh without a query + creates and releases one and waits for the refresh. It is not captured: PhysX launches the forward-kinematics + kernel only when a host flag that state writes set is set at the call, so a captured refresh would miss state + written outside its graph, as binding writes are. + """ + if self._kinematics_query is None: + self._kinematics_query = self._physx.query(SimObjectType.ARTICULATION).wait() + self._physx.update_articulations_kinematic(query=self._kinematics_query, cuda_stream=self._caller_cuda_stream()) + + def wait(self) -> None: + """Block until our replays, and the graphs a caller replays on the same stream, have finished: ovphysx + forbids stepping during one. + + A step takes no stream or event to order after, so the host drains the replay stream, as ovphysx's + ``rl_step_capture`` sample does before its steps. A caller that replays a graph recording ours on another stream + synchronizes it before stepping or a release. + """ + wp.synchronize_stream(self._stream or self.caller_stream) + + def release(self, view: Any | None, tensor_types: frozenset[TensorType] | None = None) -> None: + """Release the graphs, reads, writes and queries ``view`` captured (every view's when ``None``), or only those + of ``tensor_types``.""" + self.wait() + captures = [ + table.pop(key) + for table in (self._reads, self._writes) + for key in list(table) + if (view is None or key[0] == id(view)) and (tensor_types is None or key[1] in tensor_types) + ] + self._close(captures) + + def invalidate(self) -> None: + """Wait for every replay, then release every capture, so each read and write captures again. + + A wait refused inside a capture keeps every capture. + """ + self.wait() + captures = [*self._reads.values(), *self._writes.values()] + query, self._kinematics_query = self._kinematics_query, None # the edit may change its articulations + self._reads.clear() + self._writes.clear() + try: + self._close(captures) + finally: + if query is not None: + query.close().wait() + + def close(self) -> None: + """Release every capture before the stage detaches; the registry drops this instance even if a release fails.""" + try: + self.invalidate() + finally: + OvPhysxCapturedSessions._by_physx.pop(id(self._physx), None) + + """ + Replay. + """ + + def _replay_stream(self) -> wp.Stream: + """The caller's current stream, which outside a capture must be the stream the replays run on. + + Checked before a read or write captures, so a call on another stream builds nothing. + + Raises: + RuntimeError: If the stream is not capturing and is not the stream of the first replay. + """ + stream = self.caller_stream + if not stream.is_capturing and self._stream is not None and stream.cuda_stream != self._stream.cuda_stream: + raise RuntimeError( + "OvPhysX session reads and writes replay on one stream, the stream of the first replay; this call runs " + "on another. Make them on that stream." + ) + return stream + + def _launch(self, graph: wp.Graph, stream: wp.Stream) -> None: + """Replay a captured read or write on ``stream``, or record it into the caller's capture there. + + Every replay runs on one stream, the first replay's (:meth:`_replay_stream`): wait() drains it before the next + step (ovphysx cannot step during a replay). + """ + if stream.is_capturing: + self._insert_child_graph(graph, stream) + return + if self._stream is None: + self._stream = stream + wp.capture_launch(graph, stream=stream) + + @staticmethod + def _insert_child_graph(graph: wp.Graph, stream: wp.Stream) -> None: + """Record ``graph`` as a child node of the CUDA graph being captured on ``stream``. + + A capture cannot launch a graph, and :func:`warp.capture_if` takes one only as a conditional body, which + rejects the event waits of an ovphysx read: Warp's private child-graph insertion is the only way in. + """ + try: + from warp._src.context import runtime + + insert = runtime.core.wp_cuda_graph_insert_child_graph + except (ImportError, AttributeError) as error: + raise RuntimeError( + f"Warp {wp.__version__} cannot record a session read or write into the caller's graph." + ) from error + if not insert(stream.device.context, stream.cuda_stream, graph.graph): + raise RuntimeError(runtime.get_error_string()) + + def _caller_cuda_stream(self) -> int: + """The caller's stream as ovphysx takes it: ``0`` for Warp's null stream (the legacy default stream).""" + return int(self.caller_stream.cuda_stream or 0) + + """ + Capture. + """ + + def _capture_read(self, tensor_type: TensorType, binding: Any, dst: wp.array) -> _Capture: + """Map the session's rows onto ``dst``, then capture each held query's read and copy kernels in one graph.""" + captured = _Capture() + try: + # 1. Hold the queries and map each session row onto its binding row; the rows must cover dst. + rows = self._hold_and_map(tensor_type, binding, captured, write=False) + width = self._binding_width(tensor_type, captured, rows, dst.size) + # 2. Capture every held query's read and its copy kernels into one graph. + flat = dst.flatten() + with self._recording(captured): + if captured.padded: # the binding rows the session does not hold read zero, as the binding pads them + flat.zero_() + for held in captured.queries: + names_read = [name for name, _ in held.attributes] + held.read = self._physx.read( + held.query, names_read, cuda_stream=self._capture_stream.cuda_stream + ).wait() + columns = _result_columns(held.read.dictionary, _result_groups(held.read)) + self._copy_columns_to(held, columns, width, flat) + return captured + except BaseException: + captured.close() + raise + + def _capture_write(self, tensor_type: TensorType, binding: Any, src: wp.array, mask: wp.array | None) -> _Capture: + """Map the session's rows onto ``src``, then capture each held write session's fill and commit in one graph. + + The graph reads ``src`` and ``mask`` in place on each replay, turning ``mask`` into the one ``bool`` per session + row each commit reads. + """ + instances = binding.shape[0] + if mask is not None and ( + mask.dtype != wp.bool or mask.shape != (instances,) or not mask.is_contiguous or mask.device != self._device + ): + raise ValueError( + f"{tensor_type.name}: the mask must be a contiguous array of one bool per binding instance " + f"({instances}) on {self._device}." + ) + captured = _Capture() + try: + # 1. Hold the queries and their write sessions, map each session row onto its binding row, and allocate the + # row mask each commit of a masked write reads. + rows = self._hold_and_map(tensor_type, binding, captured, write=True) + width = self._binding_width(tensor_type, captured, rows, src.size) + if mask is not None: + for held in captured.queries: + held.mask = wp.zeros(held.binding_rows.shape[0], dtype=wp.bool, device=self._device) + # 2. Capture every held session's row mask, fill and commit into one graph. + flat = src.flatten() + with self._recording(captured): + for held in captured.queries: + if held.mask is not None: + wp.launch( + _select_session_rows, + dim=held.binding_rows.shape[0], + inputs=[mask, held.binding_rows, rows // instances], + outputs=[held.mask], + ) + self._fill_columns_from(held, width, flat) + for group in held.groups: + held.write.commit(group, cuda_stream=self._capture_stream.cuda_stream, mask=held.mask).wait() + return captured + except BaseException: + captured.close() + raise + + def _hold_and_map(self, tensor_type: TensorType, binding: Any, captured: _Capture, write: bool) -> int: + """Hold the queries of a read or write of ``tensor_type`` and map each session row onto its binding row. + + Returns the binding's rows. + """ + object_type, names = SESSION_ATTRIBUTES[tensor_type] + # The setup's warm read runs on the caller's stream, ordered with its work and the replays. + with ovstage.PathDictionary(self._stage) as paths: + if object_type == SimObjectType.ARTICULATION_JOINT: + rows = self._map_dof_rows(binding, names, paths, captured, write=write) + elif object_type in _DEFORMABLES: + rows = self._map_node_rows(object_type, binding, names, paths, captured) + else: + rows = self._map_prim_rows(object_type, binding, names, paths, captured, write=write) + return rows + + @staticmethod + def _binding_width(tensor_type: TensorType, captured: _Capture, rows: int, size: int) -> int: + """Lanes per binding row; the rows and lanes must cover the caller's buffer exactly.""" + width = sum(lanes for _, lanes in captured.queries[0].attributes) + if rows * width != size: + raise ValueError(f"{tensor_type.name}: {rows} rows of {width} lanes miss {size}.") + return width + + @contextlib.contextmanager + def _recording(self, captured: _Capture) -> Iterator[None]: + """Record what the block launches on the capture stream into ``captured.graph``.""" + self._physx.wait_all() # no deferred release may run inside the capture + with ( + wp.ScopedCapture(device=self._device, stream=self._capture_stream) as capture, + wp.ScopedStream(self._capture_stream, sync_enter=False), # zero_() and launches run on the current stream + ): + yield + captured.graph = capture.graph + + def _copy_columns_to(self, held: _HeldQuery, columns: dict[str, wp.array], width: int, dst: wp.array) -> None: + """Copy each of the held query's columns to its binding rows in ``dst``, on the capture stream.""" + count, offset = held.binding_rows.shape[0], 0 + for name, lanes in held.attributes: + # Points pass through their body's frame; other columns are copied lane by lane, scaled per row. + if held.frames is not None: + inputs = [columns[name], held.binding_rows, held.bodies, held.frames] + dim = count + kernel = _transform_to_binding_rows + else: + inputs = [columns[name], held.binding_rows, held.scales, lanes, offset, width] + dim = (count, lanes) + kernel = _copy_to_binding_rows + wp.launch(kernel, dim=dim, inputs=inputs, outputs=[dst], device=self._device, stream=self._capture_stream) + offset += lanes + + def _fill_columns_from(self, held: _HeldQuery, width: int, src: wp.array) -> None: + """Copy each binding row of ``src`` into its session row of the held write session's columns.""" + count, offset = held.binding_rows.shape[0], 0 + for name, lanes in held.attributes: + inputs = [src, held.binding_rows, held.scales, lanes, offset, width] + wp.launch( + _copy_from_binding_rows, + dim=(count, lanes), + inputs=inputs, + outputs=[held.columns[name]], + device=self._device, + stream=self._capture_stream, + ) + offset += lanes + + """ + Row mapping. + """ + + def _map_prim_rows( + self, + object_type: SimObjectType, + binding: Any, + names: tuple, + paths: Any, + captured: _Capture, + write: bool = False, + ) -> int: + """Held queries of a read or write with one binding row per prim, or per link of each articulation for links. + + A rigid-body binding's articulation links read as links, through a second query; a write covers rigid bodies + only. Returns the binding's rows. + """ + # 1. The binding row of each prim: its own, or each articulation's links in link order, padded to the longest. + if object_type == SimObjectType.ARTICULATION_LINK: + table = self._articulation_descriptors(binding, ("linkPath", "linkCount"), paths) + links, counts = binding.shape[1], table["linkCount"][:, 0] + if (counts > links).any(): + raise ValueError(f"The articulations hold {counts} links; the binding holds {links}.") + binding_row_of = { + paths.path_to_string(ovstage.PrimPath(int(table["linkPath"][index, link]))): index * links + link + for index, count in enumerate(counts) + for link in range(int(count)) + } + total = len(counts) * links + else: + binding_row_of = {prim: row for row, prim in enumerate(binding.prim_paths)} + total = len(binding_row_of) + captured.padded = captured.padded or len(binding_row_of) < total + rows = list(binding_row_of) + # 2. Read each object type the rows span and map each session row onto its binding row. + part_types = [object_type] + if object_type == SimObjectType.RIGID_BODY and not write: + # A rigid-body binding may hold articulation links, which the session reads as links. + part_types.append(SimObjectType.ARTICULATION_LINK) + mapped = 0 + for part_type in part_types: + opened = self._hold_query(part_type, rows, names, paths, captured, write) + if opened is not None: # a selection keeps only the prims of its object type + held, session_rows, _ = opened + self._upload_binding_rows(held, self._lookup_binding_rows(binding_row_of, session_rows)) + mapped += len(session_rows) + # 3. Every row the session holds is mapped. + if mapped != len(rows): + raise ValueError(f"The session holds {mapped} of the binding's {len(rows)} rows.") + return total + + def _map_dof_rows(self, binding: Any, names: tuple, paths: Any, captured: _Capture, write: bool = False) -> int: + """The held query of a joint read or write: one session row per joint axis. Returns the binding rows.""" + # 1. The binding row and unit scale of each (joint, axis ordinal) the binding holds: an angular axis of an + # attribute in degrees reads into radians and writes from them. + table = self._articulation_descriptors( + binding, ("dofJointPath", "dofAxisIndex", "dofCount", "dofJointType"), paths + ) + dofs, total = binding.shape[1], math.prod(binding.shape[:2]) + angle = (math.degrees(1.0) if write else math.radians(1.0)) if names[0] in _DEGREE_ATTRIBUTES else 1.0 + targets = {} # (joint path, axis ordinal) -> (binding row, scale) + for index, used in enumerate(table["dofCount"][:, 0]): + if used > dofs: + raise ValueError(f"{binding.prim_paths[index]} has {used} DOFs; the binding holds {dofs}.") + for dof in range(int(used)): + joint = paths.path_to_string(ovstage.PrimPath(int(table["dofJointPath"][index, dof]))) + angular = int(table["dofJointType"][index, dof]) in _ANGULAR_JOINT_TYPES + key = (joint, int(table["dofAxisIndex"][index, dof])) + targets[key] = (index * dofs + dof, angle if angular else 1.0) + captured.padded = captured.padded or len(targets) < total + # 2. Hold the joints; a joint's k-th session row is its axis ordinal k. + joints = list(dict.fromkeys(joint for joint, _ in targets)) + opened = self._hold_query(SimObjectType.ARTICULATION_JOINT, joints, names, paths, captured, write) + if opened is None: + raise ValueError(f"The session reads none of the binding's {len(targets)} joint axes.") + held, session_rows, _ = opened + keys, ordinal = [], {} + for joint in session_rows: + keys.append((joint, ordinal.get(joint, 0))) + ordinal[joint] = keys[-1][1] + 1 + if len(keys) != len(targets): + raise ValueError(f"The session read has {len(keys)} joint rows; the binding holds {len(targets)}.") + # 3. Map each row onto its binding row, angular axes from degrees to radians. + binding_rows = self._lookup_binding_rows({key: row for key, (row, _) in targets.items()}, keys) + self._upload_binding_rows(held, binding_rows, scales=[targets[key][1] for key in keys]) + return total + + def _map_node_rows( + self, + object_type: SimObjectType, + binding: Any, + names: tuple, + paths: Any, + captured: _Capture, + ) -> int: + """The held query of a deformable read: one session row per node, padded to the binding's widest body. + + ovphysx reports ``points`` in the sim-mesh frame and ``velocities`` in world; the points pass through each sim + mesh's world transform on the stage ovphysx loaded (:meth:`_sim_mesh_frames`). Returns the binding's node rows. + """ + # 1. Read the deformable prim of each binding body. + prims = self._deformable_prims(object_type, names[0], list(binding.prim_paths)) + opened = self._hold_query(object_type, prims, names, paths, captured) + session_rows, counts = (opened[1], opened[2]) if opened is not None else ([], []) + nodes = binding.shape[1] + if sorted(session_rows) != sorted(prims) or max(counts) > nodes: + raise ValueError( + f"The session reads {list(zip(session_rows, counts))[:3]}; the binding holds {nodes} nodes." + ) + # 2. Node i of body b lands on binding row b * nodes + i; the nodes of shorter bodies leave padded rows. + captured.padded = captured.padded or any(count < nodes for count in counts) + body_of = {prim: body for body, prim in enumerate(prims)} + bodies = np.repeat([body_of[prim] for prim in session_rows], counts) + binding_rows = bodies * nodes + np.concatenate([np.arange(count) for count in counts]) + # 3. Points also take their body's sim-mesh frame to world. + if names[0] == "points": + self._upload_binding_rows(opened[0], binding_rows, bodies=bodies, frames=self._sim_mesh_frames(prims)) + else: + self._upload_binding_rows(opened[0], binding_rows) + return math.prod(binding.shape[:2]) + + def _hold_query( + self, + object_type: SimObjectType, + prims: list[str], + names: tuple, + paths: Any, + captured: _Capture, + write: bool = False, + ) -> tuple[_HeldQuery, list[str], list[int]] | None: + """Hold a query over ``prims``: the held query, its session rows, and rows per prim. + + A read reads it once uncaptured, which plans the query and allocates its device columns for the captured read to + reuse (ovphysx ``read_write/device.md``, "Capturing a read in a CUDA graph"). A write opens the write session + its graph commits and keeps it open, with its groups' columns. Each attribute's lanes come from the groups. + Returns ``None`` when the session holds none of ``prims`` as ``object_type``. + """ + # 1. Hold the query; the capture owns it from here. + held = _HeldQuery(self._physx.query(object_type, prim_paths=[paths.intern_path(p) for p in prims]).wait()) + captured.queries.append(held) + # 2. Read it once, or open its write session: the groups give each attribute's lanes and the session rows. + if write: + opened = held.write = self._physx.write(held.query, list(names)).wait() + else: + opened = self._physx.read(held.query, list(names), cuda_stream=self._caller_cuda_stream()).wait() + dictionary = held.query.dictionary if write else opened.dictionary + try: + groups = _result_groups(opened) + if not groups: + captured.queries.remove(held) + return None + if any(group.tensors[0].device != self._device for group in groups): + raise ValueError(f"{object_type.name} columns are not on {self._device}; they cannot be captured.") + lanes = {} + for group in groups: + tensor = next((t for t in group.tensors if t.size), group.tensors[0]) + lanes[dictionary.token_to_string(group.attribute)] = math.prod(tensor.shape[1:]) + held.attributes = [(name, lanes[name]) for name in names] + if write: + held.groups = groups + held.columns = _result_columns(dictionary, groups) + counts = [int(tensor.shape[0]) for tensor in groups[0].tensors] + return held, _result_row_paths(dictionary, groups), counts + finally: + # 3. Release the warm read, and the query (and write session) when the session holds none of the prims. + try: + if not write: + opened.close().wait() + finally: + if held not in captured.queries: + if write: + held.write.close().wait() + held.query.close().wait() + + @staticmethod + def _lookup_binding_rows(binding_row_of: dict[Any, int], keys: list[Any]) -> list[int]: + """Binding row of each session row, by its key; a key no binding row holds is an error.""" + missing = [key for key in keys if key not in binding_row_of] + if missing: + raise ValueError( + f"The session read has rows {missing[:3]} that no binding row holds ({len(missing)} missing)." + ) + return [binding_row_of[key] for key in keys] + + def _upload_binding_rows( + self, held: _HeldQuery, binding_rows: Any, scales: Any = None, bodies: Any = None, frames: Any = None + ) -> None: + """Upload the binding row of each of the held query's session rows to the simulation device.""" + device = self._device + held.binding_rows = wp.array(np.asarray(binding_rows, dtype=np.int32), dtype=wp.int32, device=device) + held.scales = wp.array(np.asarray(scales if scales is not None else [], dtype=np.float32), device=device) + if frames is not None: + held.bodies = wp.array(np.asarray(bodies, dtype=np.int32), dtype=wp.int32, device=device) + held.frames = wp.array(frames, dtype=wp.mat44, device=device) + + def _articulation_descriptors(self, binding: Any, names: tuple, paths: Any) -> dict[str, np.ndarray]: + """Each of the articulation metadata columns ``names``, one row per binding articulation, in binding order.""" + roots = list(binding.prim_paths) + handles = [paths.intern_path(p) for p in roots] + with self._physx.read_sync(SimObjectType.ARTICULATION, list(names), prim_paths=handles) as result: + groups = _result_groups(result) + row_of = {path: row for row, path in enumerate(_result_row_paths(result.dictionary, groups))} + order = [row_of[root] for root in roots] + # Host columns are views of the read's memory: index (copy) them before the read closes. + return { + result.dictionary.token_to_string(group.attribute): group.tensors[0] + .numpy() + .reshape(len(row_of), -1)[order] + for group in groups + } + + def _deformable_prims(self, object_type: SimObjectType, attribute: str, prims: list[str]) -> list[str]: + """The deformable prim the session reads for each binding prim: the prim itself, or the one below it. + + A mesh-spawned body binds its outer prim, while the session reads the deformable mesh prim under it. + """ + # 1. Every prim the session reads as this deformable type. + with self._physx.read_sync(object_type, [attribute]) as result: + session = [ + path for group in _result_groups(result) for path in _result_row_paths(result.dictionary, [group]) + ] + # 2. Match each binding prim to itself or to the one deformable prim below it. + known = set(session) + found = [] + for prim in prims: + below = [prim] if prim in known else [path for path in session if path.startswith(prim + "/")] + if len(below) != 1: + raise ValueError(f"{prim} has {len(below)} {object_type.name} prims; one is required.") + found.append(below[0]) + return found + + def _sim_mesh_frames(self, paths: list[str]) -> np.ndarray: + """World transform of each prim on the stage ovphysx loaded, as column-vector float32 4x4 matrices [m]. + + Raises: + ValueError: If a prim is not on the loaded stage. + """ + cache = UsdGeom.XformCache() + frames = np.empty((len(paths), 4, 4), dtype=np.float32) + for row, path in enumerate(paths): + prim = self._usd_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 + + """ + Release. + """ + + @staticmethod + def _close(captures: list[_Capture]) -> None: + """Close every capture, then raise the first failure.""" + _release_all(captured.close for captured in captures) + + +## +# Host helpers (setup and release). +## + + +def _result_groups(result: Any) -> list[Any]: + """Every group of an ovphysx read or write session that carries data; an empty selection holds none.""" + groups = list(result.groups or []) + if not groups: + while (group := result.fetch_next().wait()) is not None: + groups.append(group) + return [group for group in groups if group.tensors] + + +def _result_row_paths(dictionary: Any, groups: list[Any]) -> list[str]: + """Prim path of each session row of a read or write, through its query's ``dictionary``.""" + first = groups[0] + handles = dictionary.get_paths(first.prim_list) + return [dictionary.path_to_string(handles[first.prim_offset + i]) for i in range(first.prim_count)] + + +def _result_columns(dictionary: Any, groups: list[Any]) -> dict[str, wp.array]: + """Each attribute's column as one flat ``float32`` array; an array group's per-prim tensors joined into one.""" + columns = {} + for group in groups: + # 1. The group's per-prim tensors must form one block; an empty prim carries no memory. + tensors = [tensor for tensor in group.tensors if tensor.size] or group.tensors[:1] + for before, after in zip(tensors, tensors[1:]): + if after.ptr != before.ptr + before.size * wp.types.type_size_in_bytes(before.dtype): + raise ValueError("The session read returns an array group whose tensors are not contiguous.") + # 2. One flat column per attribute. + name = dictionary.token_to_string(group.attribute) + if name in columns: # e.g. a jacobian or massMatrix over articulations of different structure: one group each + raise ValueError(f"The session holds {name!r} in several groups; one layout is required.") + size = sum(tensor.size for tensor in tensors) + columns[name] = wp.array(ptr=tensors[0].ptr, dtype=wp.float32, shape=(size,), device=tensors[0].device) + return columns + + +def _release_all(releases: Iterable[Callable[[], Any]]) -> None: + """Run every release, keeping on after a failure, then raise the first failure.""" + failures = [] + for release in releases: + try: + release() + except Exception as failure: # keep releasing the rest + failures.append(failure) + if failures: + raise failures[0] + + +## +# Kernels. +## + + +@wp.kernel +def _copy_to_binding_rows( + src: wp.array(dtype=wp.float32), + binding_rows: wp.array(dtype=wp.int32), + scales: wp.array(dtype=wp.float32), + lanes: wp.int32, + offset: wp.int32, + width: wp.int32, + dst: wp.array(dtype=wp.float32), +): + """Copy session row ``i`` to binding row ``binding_rows[i]``: ``dst[binding_rows[i], offset + k] = src[i, k]``. + + ``scales`` is empty except on joint reads: degrees to radians on angular axes, ``1`` on linear ones. + """ + i, k = wp.tid() + value = src[i * lanes + k] + if scales.shape[0] > 0: + value = value * scales[i] + dst[binding_rows[i] * width + offset + k] = value + + +@wp.kernel +def _transform_to_binding_rows( + src: wp.array(dtype=wp.float32), + binding_rows: wp.array(dtype=wp.int32), + bodies: wp.array(dtype=wp.int32), + frames: wp.array(dtype=wp.mat44), + dst: wp.array(dtype=wp.float32), +): + """Transform one deformable node per thread from its sim-mesh frame to world, onto its binding row.""" + i = wp.tid() + p = wp.transform_point(frames[bodies[i]], wp.vec3(src[i * 3], src[i * 3 + 1], src[i * 3 + 2])) + d = binding_rows[i] * 3 + dst[d] = p[0] + dst[d + 1] = p[1] + dst[d + 2] = p[2] + + +@wp.kernel +def _copy_from_binding_rows( + src: wp.array(dtype=wp.float32), + binding_rows: wp.array(dtype=wp.int32), + scales: wp.array(dtype=wp.float32), + lanes: wp.int32, + offset: wp.int32, + width: wp.int32, + dst: wp.array(dtype=wp.float32), +): + """Copy binding row ``binding_rows[i]`` to session row ``i``: ``dst[i, k] = src[binding_rows[i], offset + k]``. + + ``scales`` is empty except on joint writes: radians to degrees on angular axes, ``1`` on linear ones. + """ + i, k = wp.tid() + value = src[binding_rows[i] * width + offset + k] + if scales.shape[0] > 0: + value = value * scales[i] + dst[i * lanes + k] = value + + +@wp.kernel +def _select_session_rows( + instances: wp.array(dtype=wp.bool), + binding_rows: wp.array(dtype=wp.int32), + rows_per_instance: wp.int32, + mask: wp.array(dtype=wp.bool), +): + """Select session row ``i`` when its binding row's instance is selected: the row mask of a masked commit.""" + i = wp.tid() + mask[i] = instances[binding_rows[i] // rows_per_instance] + + +## +# Held state of the captured reads and writes. +## + + +@dataclass(eq=False) +class _HeldQuery: + """One query a captured read holds, and the binding row each of its session rows lands on.""" + + query: Any + attributes: list[tuple[str, int]] = field(default_factory=list) + """Session attribute and lanes of each column, in binding lane order.""" + binding_rows: wp.array | None = None + """Binding row of each session row.""" + scales: wp.array | None = None + """Factor per session row (degrees to radians on an angular joint axis); empty when none applies.""" + bodies: wp.array | None = None + """Body of each session row, indexing ``frames``.""" + frames: wp.array | None = None + """World transform (column-vector 4x4) of each body, for sim-mesh-local deformable points; ``None`` otherwise.""" + read: Any = None + """The read the graph replays; ovphysx binds it to the graph, so both stay open together.""" + write: Any = None + """The write session the graph commits; ovphysx binds it to the graph, so both stay open together.""" + groups: list[Any] = field(default_factory=list) + """The write session's groups, one per attribute, which the graph fills and commits.""" + columns: dict[str, wp.array] = field(default_factory=dict) + """Each write group's column as one flat array, by attribute.""" + mask: wp.array | None = None + """The mask a masked write's commit reads: one ``bool`` per session row, which the graph derives from the caller's + mask on each replay; ``None`` for a whole write.""" + + +@dataclass +class _Capture: + """The graph that refreshes one destination, or commits one source, and the queries it replays.""" + + queries: list[_HeldQuery] = field(default_factory=list) + graph: Any = None + padded: bool = False + """Whether the binding holds rows no session row fills (shorter articulations); a read zeroes them first.""" + + def close(self) -> None: + """Release the graph, then every read and write session, then every query, as ovphysx requires; raise the first + failure.""" + # 1. Drop the graph, then list the reads, write sessions and queries it bound, in release order. + self.graph = None + releases = [held.read.close for held in self.queries if held.read is not None] + releases += [held.write.close for held in self.queries if held.write is not None] + releases += [held.query.close for held in self.queries] + # 2. Release each, keeping on after a failure. + _release_all((lambda release=release: release().wait()) for release in releases) diff --git a/source/isaaclab_ov/isaaclab_ov/sim/views/ovphysx_view.py b/source/isaaclab_ov/isaaclab_ov/sim/views/ovphysx_view.py index 8840ec2f53c2..b33337f680a4 100644 --- a/source/isaaclab_ov/isaaclab_ov/sim/views/ovphysx_view.py +++ b/source/isaaclab_ov/isaaclab_ov/sim/views/ovphysx_view.py @@ -57,6 +57,8 @@ from isaaclab_ov._clone import ordered_clone_paths from isaaclab_ov.tensor_types import _CPU_ONLY_TYPES +from .ovphysx_captured_sessions import OvPhysxCapturedSessions + logger = logging.getLogger(__name__) @@ -353,10 +355,12 @@ def __init__( ) self._key_aliases[req_tt] = made_tt self._bindings: dict[Any, Any] = {} - # Cache of binding-scalar reinterpret views for read_into / get_attribute, keyed by the - # destination and binding identities. Reusing the same reinterpret object per binding + # Cache of binding-scalar reinterpret views for read_into / get_attribute / set_attribute, keyed by the + # buffer and binding identities. Reusing the same reinterpret object per binding # keeps the wheel's object-identity read cache (the TensorBinding.read fast path) warm. self._read_views: dict[tuple[int, int], wp.array] = {} + # Layouts of flat binding-scalar buffers already validated against their binding: such a buffer is its own view. + self._flat_layouts: set[tuple] = set() self._closed = False if eager: @@ -385,6 +389,14 @@ def close(self) -> None: return self._closed = True + sessions = OvPhysxCapturedSessions.for_physx(self._physx) + if sessions is not None: + try: + sessions.release(self) + except Exception: + logger.warning( + "Failed to release OVPhysX captured session reads and writes during shutdown.", exc_info=True + ) for binding in self._bindings.values(): try: binding.destroy() @@ -392,6 +404,7 @@ def close(self) -> None: logger.warning("Failed to destroy OVPhysX binding during shutdown.", exc_info=True) self._bindings.clear() self._read_views.clear() + self._flat_layouts.clear() self._physx = None self._live_views.discard(self) @@ -425,32 +438,37 @@ def get_attribute(self, name: str | Any, *, out: wp.array | None = None) -> wp.a a flat array matching the binding shape is allocated with the Warp scalar dtype resolved from the binding's DLPack metadata (see :data:`_ATTR_DTYPE`). """ + if out is not None: + self.read_into(name, out) + return out tt = self._resolve(name) binding = self._binding(tt) device = self._native_device(tt) - if out is not None: - self._check_device(out, device, tensor_type_name(tt), "destination") - binding.read(self._read_view(out, binding)) - return out alloc_shape, dtype = self._attribute_dtype(tt, binding) buf = wp.zeros(alloc_shape, dtype=dtype, device=device) # ``buf`` is freshly allocated here, so it is never a persistent destination: route it - # through ``_as_binding_view`` directly rather than ``_read_view``. Caching by ``id(buf)`` + # through ``_as_binding_view`` directly rather than ``_binding_view``. Caching by ``id(buf)`` # could never hit on a later call and would leak one entry (and keep ``buf`` alive) per # call in a step loop -- the read cache only pays off for a reused ``out``/``dst`` buffer. binding.read(self._as_binding_view(buf, binding, "destination")) return buf def read_into(self, name: str | Any, dst: wp.array) -> None: - """Fill ``dst`` in place from the attribute binding (zero-copy). + """Fill ``dst`` in place (zero-copy), by one of two paths. - ``dst`` may be a structured-dtype buffer (e.g. ``wp.transformf``); it is read - through a binding-scalar reinterpret view that matches the binding's flat shape, so - the structured GPU/CPU buffer is filled directly with no extra copy. This is the - path the asset data containers use. The reinterpret view for a given ``dst`` is - built once and reused across calls (see :meth:`_read_view`) so the wheel's - object-identity read cache stays warm -- callers can pass the structured buffer - directly each step without maintaining their own reinterpret cache. + ``dst`` may be a structured-dtype buffer (e.g. ``wp.transformf``); it is filled through a binding-scalar + reinterpret view that matches the binding's flat shape, with no extra copy. This is the path the asset data + containers use. + + - **Simulation state on a CUDA simulation** (the types in + :data:`~isaaclab_ov.sim.views.ovphysx_captured_sessions.READS`): replays a captured ovphysx session read into + ``dst`` without waiting for the GPU; work queued after it on the same stream sees the values. Each + destination captures once, so pass a buffer kept across calls; for a one-off read, call + :meth:`get_attribute` without ``out``. + - **Every other read, and every read of a CPU simulation**: a blocking ``TensorBinding`` read, through a + reinterpret view built once per ``dst`` (see :meth:`_binding_view`). + + Recording these reads into a caller's CUDA graph is covered in the OvPhysX backend guide. Args: name: Lowercased ``TensorType`` name or the member itself. @@ -462,11 +480,19 @@ def read_into(self, name: str | Any, dst: wp.array) -> None: OvPhysxView.DtypeMismatch: If ``dst``'s scalar element type does not match the binding-reported DLPack scalar dtype. OvPhysxView.ShapeMismatch: If ``dst`` is non-contiguous or its element count does not match. + RuntimeError: If a captured session read runs on another stream than the session replays. """ tt = self._resolve(name) binding = self._binding(tt) self._check_device(dst, self._native_device(tt), tensor_type_name(tt), "destination") - binding.read(self._read_view(dst, binding)) + view = self._binding_view(dst, binding, "destination") + # A collection key reads the type its binding was created as, in that binding's layout. + key = self._key_aliases.get(tt, tt) + sessions = OvPhysxCapturedSessions.for_physx(self._physx) + if sessions is not None and sessions.takes_read(key): + sessions.read_into(self, key, binding, view) + return + binding.read(view) def set_attribute( self, @@ -476,12 +502,21 @@ def set_attribute( indices: wp.array | None = None, mask: wp.array | None = None, ) -> None: - """Write a full attribute tensor; ``indices``/``mask`` select which rows apply. + """Write a full attribute tensor; ``indices``/``mask`` select which rows apply, by one of two paths. ``values`` may be a structured-dtype buffer read through a binding-reported scalar - dtype reinterpret view. If both ``indices`` and ``mask`` are given, ``mask`` wins and - the wheel emits a ``UserWarning`` -- this view forwards both verbatim to - ``TensorBinding.write`` and does not implement the precedence itself. + dtype reinterpret view. + + - **Controls and rigid-body state on a CUDA simulation, from a** ``wp.array`` **, whole or by** ``mask`` (the + types in :data:`~isaaclab_ov.sim.views.ovphysx_captured_sessions.WRITES`): replays a captured ovphysx session + write without waiting for the GPU, reading ``values`` and the ``bool`` ``mask`` in place, so pass the same + buffers on every call; the next step waits for it. + - **Every other write, articulation root and joint state and wrenches by mask included**: a blocking + ``TensorBinding`` write. A joint or root state write here refreshes no link poses, so the assets mark + :attr:`~isaaclab_ov.physics.OvPhysxManager.kinematics_dirty`, as a direct caller does; a centre-of-mass write + makes every view's wrench writes capture again. + + Recording these writes into a caller's CUDA graph is covered in the OvPhysX backend guide. Args: name: Lowercased ``TensorType`` name or the member itself. @@ -490,6 +525,9 @@ def set_attribute( mask: Optional boolean row mask to write. Raises: + ValueError: If a captured session write gets a mask that is not a contiguous ``bool`` array of one entry + per instance on the simulation device. + RuntimeError: If a captured session write runs on another stream than the session replays. OvPhysxView.ReadOnlyAttribute: If the attribute is read-only. OvPhysxView.DeviceMismatch: If ``values`` is not on the binding's native device. OvPhysxView.DtypeMismatch: If ``values``' scalar element type does not match the @@ -504,7 +542,16 @@ def set_attribute( device = self._native_device(tt) src = self._as_wp(values, device) self._check_device(src, device, attr, "source") - binding.write(self._as_binding_view(src, binding, "source"), indices=indices, mask=mask) + view = self._binding_view(src, binding, "source") + # As for reads, a collection key writes the type its binding was created as, in that binding's layout. + key = self._key_aliases.get(tt, tt) + sessions = OvPhysxCapturedSessions.for_physx(self._physx) + if sessions is not None and sessions.takes_write(key, values, indices=indices, mask=mask): + sessions.write_from(self, key, binding, view, mask=mask) + return + if sessions is not None: + sessions.before_binding_write(key) # a centre-of-mass write releases the captured wrench writes + binding.write(view, indices=indices, mask=mask) def get_material_properties(self) -> wp.array: """Read per-shape static friction, dynamic friction and restitution on the CPU. @@ -546,7 +593,9 @@ def binding_for(self, name: str | Any) -> _BindingLike: This is a raw escape hatch for asset-internal binding management: the returned binding's ``read``/``write`` **bypass** the view's device, dtype-reinterpret, shape, - and read-only guards. Prefer :meth:`get_attribute` / :meth:`read_into` / + and read-only guards, and the release of every view's captured wrench writes that a + centre-of-mass write needs: write a centre of mass through :meth:`set_attribute`. + Prefer :meth:`get_attribute` / :meth:`read_into` / :meth:`set_attribute` unless you are deliberately managing bindings directly. """ return self._binding(self._resolve(name)) @@ -788,22 +837,28 @@ def _as_binding_view(self, arr: wp.array, binding: Any, role: str) -> wp.array: ptr=arr.ptr, shape=tuple(binding.shape), dtype=binding_scalar, device=str(arr.device), copy=False ) - def _read_view(self, dst: wp.array, binding: Any) -> wp.array: - """Return the binding-scalar view of ``dst`` to hand to ``binding.read``, reused across calls. + def _binding_view(self, arr: wp.array, binding: Any, role: str) -> wp.array: + """Return the binding-scalar view of a read destination or write source, reused across calls. The wheel's ``TensorBinding.read`` has an object-identity read cache: it skips DLPack acquisition and the attribute-chain lookup when handed the *same* tensor object as the previous read. To keep that cache warm, the binding-scalar reinterpret of a structured - ``dst`` is built once and reused for that destination buffer; a pointer-staleness guard - rebuilds it if the buffer's backing storage moved. A ``dst`` that is already flat - binding scalar is its own stable identity, so it is returned directly (and not cached). + buffer is built once and reused for that buffer; a pointer-staleness guard rebuilds it + if the buffer's backing storage moved. A buffer that is already flat binding scalar is + its own view: its layout (address, dtype, shape, strides, device) is validated once and + remembered, so the per-call cost of a captured session read or write stays the replay. """ - key = (id(dst), id(binding)) + key = (id(arr), id(binding)) cached = self._read_views.get(key) - if cached is not None and cached.ptr == dst.ptr: + if cached is not None and cached.ptr == arr.ptr: return cached - view = self._as_binding_view(dst, binding, "destination") - if view is not dst: # structured dst -> cache the reinterpret; a flat scalar dst caches nothing + layout = (arr.ptr, arr.dtype, arr.shape, arr.strides, str(arr.device), id(binding)) + if layout in self._flat_layouts: + return arr + view = self._as_binding_view(arr, binding, role) + if view is arr: + self._flat_layouts.add(layout) + else: self._read_views[key] = view return view diff --git a/source/isaaclab_ov/isaaclab_ov/test/fixtures/views/captured_sessions.py b/source/isaaclab_ov/isaaclab_ov/test/fixtures/views/captured_sessions.py new file mode 100644 index 000000000000..69fb54a5f96f --- /dev/null +++ b/source/isaaclab_ov/isaaclab_ov/test/fixtures/views/captured_sessions.py @@ -0,0 +1,127 @@ +# 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 + +"""Helpers for tests that compare OvPhysX session reads and writes with their TensorBindings on a real simulation.""" + +from __future__ import annotations + +import contextlib +from collections.abc import Iterator +from unittest.mock import patch + +import torch +import warp as wp + +from isaaclab_ov.sim.views.ovphysx_captured_sessions import OvPhysxCapturedSessions +from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView + +REPLAY_ONLY = "read_into did not replay its captured session read" +"""Failure of a binding read or a new capture where only the captured read may serve the read.""" + +WRITE_REPLAY_ONLY = "set_attribute did not replay its captured session write" +"""Failure of a binding write or a new capture where only the captured write may serve the write.""" + + +def binding_values(view: OvPhysxView, tensor_type: int) -> wp.array: + """Read ``tensor_type`` straight from its TensorBinding: the reference a session read must match. + + Shape and device come from the binding itself, since ``get_attribute`` would run (and capture) a session read. + """ + binding = view.binding_for(tensor_type) + values = wp.zeros(tuple(binding.shape), dtype=wp.float32, device=view._native_device(view._resolve(tensor_type))) + binding.read(view._binding_view(values, binding, "destination")) + return values + + +@contextlib.contextmanager +def replays_only(view: OvPhysxView, tensor_type: int) -> Iterator[None]: + """Fail unless the one ``read_into`` inside replays a read captured earlier: no binding read, no new capture. + + Without it, a read that fell back to the binding would match the binding reference trivially. + """ + with ( + patch.object(type(view.binding_for(tensor_type)), "read", side_effect=AssertionError(REPLAY_ONLY)), + patch.object(OvPhysxCapturedSessions, "_capture_read", side_effect=AssertionError(REPLAY_ONLY)), + patch.object(wp, "capture_launch", wraps=wp.capture_launch) as launch, + ): + yield + assert launch.call_count == 1, REPLAY_ONLY + + +def binding_write( + view: OvPhysxView, + tensor_type: int, + values: wp.array, + *, + indices: wp.array | None = None, + mask: wp.array | None = None, +) -> None: + """Write ``values`` straight to the TensorBinding: the reference a session write must match.""" + binding = view.binding_for(tensor_type) + binding.write(view._as_binding_view(values, binding, "source"), indices=indices, mask=mask) + + +@contextlib.contextmanager +def writes_replay_only(view: OvPhysxView, tensor_type: int) -> Iterator[None]: + """Fail unless the one ``set_attribute`` inside replays a write captured earlier: no binding write, no capture.""" + with ( + patch.object(type(view.binding_for(tensor_type)), "write", side_effect=AssertionError(WRITE_REPLAY_ONLY)), + patch.object(OvPhysxCapturedSessions, "_capture_write", side_effect=AssertionError(WRITE_REPLAY_ONLY)), + patch.object(wp, "capture_launch", wraps=wp.capture_launch) as launch, + ): + yield + assert launch.call_count == 1, WRITE_REPLAY_ONLY + + +def session_and_binding_writes( + view: OvPhysxView, + tensor_type: int, + start: wp.array, + values: wp.array, + *, + indices: wp.array | None = None, + mask: wp.array | None = None, + replay: bool = False, +) -> tuple[torch.Tensor, torch.Tensor]: + """The binding's values after a session write of ``values``, and after the binding write of the same; both from + ``start``, written through the binding before each. ``replay`` requires the session write to replay a captured + write.""" + binding_write(view, tensor_type, start) + binding_write(view, tensor_type, values, indices=indices, mask=mask) + expected = wp.to_torch(binding_values(view, tensor_type)).clone() + binding_write(view, tensor_type, start) + with writes_replay_only(view, tensor_type) if replay else contextlib.nullcontext(): + view.set_attribute(tensor_type, values, indices=indices, mask=mask) + wp.synchronize_device(start.device) # the binding read below does not wait for the caller's stream + return wp.to_torch(binding_values(view, tensor_type)), expected + + +@wp.kernel +def _spin(iterations: int, sink: wp.array(dtype=wp.float32)): + """Keep the stream busy for a while, so the work queued after it is still pending on the host's next call.""" + value = float(0.0) + for i in range(iterations): + value = value * 0.5 + 1.0 + sink[0] = value + + +def session_write_then_binding_indices( + view: OvPhysxView, tensor_type: int, start: wp.array, values: wp.array, indices: wp.array +) -> tuple[torch.Tensor, torch.Tensor]: + """The binding's values after a session write of ``values`` and then the view's write of ``start`` at ``indices``, + and after the binding writes of the same: an indices write takes the binding, after the session writes queued on + the caller's stream, here still pending behind a busy kernel.""" + binding_write(view, tensor_type, start) + binding_write(view, tensor_type, values) + binding_write(view, tensor_type, start, indices=indices) + expected = wp.to_torch(binding_values(view, tensor_type)).clone() + binding_write(view, tensor_type, start) + wp.launch( + _spin, dim=1, inputs=[20_000_000, wp.zeros(1, dtype=wp.float32, device=start.device)], device=start.device + ) + view.set_attribute(tensor_type, values) + view.set_attribute(tensor_type, start, indices=indices) + wp.synchronize_device(start.device) + return wp.to_torch(binding_values(view, tensor_type)), expected diff --git a/source/isaaclab_ov/test/assets/test_articulation.py b/source/isaaclab_ov/test/assets/test_articulation.py index 070afd47ce98..0924fb83c966 100644 --- a/source/isaaclab_ov/test/assets/test_articulation.py +++ b/source/isaaclab_ov/test/assets/test_articulation.py @@ -50,7 +50,15 @@ from isaaclab_ov.assets.articulation.actuator_control import OvPhysxActuatorControl # noqa: E402 from isaaclab_ov.assets.articulation.articulation_data import ArticulationData # noqa: E402 from isaaclab_ov.physics import OvPhysxCfg, OvPhysxManager # noqa: E402 +from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView # noqa: E402 from isaaclab_ov.test.fixtures.views import MockOvPhysxBindingSet # noqa: E402 +from isaaclab_ov.test.fixtures.views.captured_sessions import ( # noqa: E402 + binding_values, + binding_write, + replays_only, + session_and_binding_writes, + session_write_then_binding_indices, +) import isaaclab.sim as sim_utils # noqa: E402 import isaaclab.utils.math as math_utils # noqa: E402 @@ -373,8 +381,8 @@ def scene(request: pytest.FixtureRequest) -> Iterator[_ArticulationScene]: def _read_binding_to_torch(articulation: Articulation, tensor_type: int, device: str | torch.device) -> torch.Tensor: - """Read an OVPhysX attribute on its native device and move it to *device*.""" - return wp.to_torch(articulation.root_view.get_attribute(tensor_type)).to(device) + """Read an OVPhysX attribute straight from its TensorBinding on its native device and move it to *device*.""" + return wp.to_torch(binding_values(articulation.root_view, tensor_type)).to(device) def _spawn_own_articulation(**cfg) -> Articulation: @@ -563,9 +571,11 @@ def test_zero_dof_articulation_data_has_empty_joint_properties(): def test_process_tendons_scopes_to_articulation_root(): """Tendon discovery should ignore joints that live outside the current articulation subtree.""" articulation = _make_articulation_shell() - stage_usda = _make_articulation_root_stage_usda() + layer = Sdf.Layer.CreateAnonymous("tendons.usda") + assert layer.ImportFromString(_make_articulation_root_stage_usda()) + stage = Usd.Stage.Open(layer) articulation._backend_manager = OvPhysxManager(OvPhysxCfg()) - articulation._backend_manager._stage_usda = stage_usda + articulation._backend_manager.backend = SimpleNamespace(usd_stage=stage) articulation._process_tendons() # the tendon is reported by its schema INSTANCE name, matching PhysX; scope leakage would @@ -780,6 +790,334 @@ def test_heterogeneous_articulation_clone_indexed_state(device, variant, tmp_pat binding.destroy() +def _chain_usd(path: Path, links: int) -> str: + """Write a fixed-base chain of ``links`` bodies joined by revolute joints; returns its USD path.""" + stage = Usd.Stage.CreateInMemory() + robot = UsdGeom.Xform.Define(stage, "/Robot").GetPrim() + stage.SetDefaultPrim(robot) + UsdPhysics.ArticulationRootAPI.Apply(robot) + for link in range(links): + body = UsdGeom.Xform.Define(stage, f"/Robot/Link{link}") + body.AddTranslateOp().Set((0.0, 0.0, 0.4 * link)) + UsdPhysics.RigidBodyAPI.Apply(body.GetPrim()) + UsdPhysics.MassAPI.Apply(body.GetPrim()).CreateMassAttr(1.0) + geometry = UsdGeom.Cube.Define(stage, f"/Robot/Link{link}/Geometry") + geometry.AddScaleOp().Set((0.1, 0.1, 0.1)) + UsdPhysics.CollisionAPI.Apply(geometry.GetPrim()) + UsdPhysics.FixedJoint.Define(stage, "/Robot/Fixed").CreateBody1Rel().SetTargets(["/Robot/Link0"]) + for link in range(1, links): + joint = UsdPhysics.RevoluteJoint.Define(stage, f"/Robot/Joint{link}") + joint.CreateBody0Rel().SetTargets([f"/Robot/Link{link - 1}"]) + joint.CreateBody1Rel().SetTargets([f"/Robot/Link{link}"]) + joint.CreateLocalPos0Attr((0.0, 0.0, 0.4)) + usd_path = str(path / f"chain_{links}.usda") + stage.Export(usd_path) + return usd_path + + +def _ball_slider_usd(path: Path) -> str: + """Write a fixed-base robot whose ``Ball`` joint frees two rotation axes, PhysX swing1 and swing2 (twist locked, + so their axis ordinals compact to 0 and 1), followed by a prismatic ``Slider``; returns its USD path.""" + stage = Usd.Stage.CreateInMemory() + robot = UsdGeom.Xform.Define(stage, "/Robot").GetPrim() + stage.SetDefaultPrim(robot) + UsdPhysics.ArticulationRootAPI.Apply(robot) + for link, name in enumerate(("Base", "Tip", "Carriage")): + body = UsdGeom.Xform.Define(stage, f"/Robot/{name}") + body.AddTranslateOp().Set((0.0, 0.0, 0.4 * link)) + UsdPhysics.RigidBodyAPI.Apply(body.GetPrim()) + UsdPhysics.MassAPI.Apply(body.GetPrim()).CreateMassAttr(1.0) + geometry = UsdGeom.Cube.Define(stage, f"/Robot/{name}/Geometry") + geometry.AddScaleOp().Set((0.1, 0.1, 0.1)) + UsdPhysics.CollisionAPI.Apply(geometry.GetPrim()) + UsdPhysics.FixedJoint.Define(stage, "/Robot/Fixed").CreateBody1Rel().SetTargets(["/Robot/Base"]) + ball = UsdPhysics.Joint.Define(stage, "/Robot/Ball") + for axis in ("transX", "transY", "transZ", "rotX"): # a low limit above the high one locks the axis + limit = UsdPhysics.LimitAPI.Apply(ball.GetPrim(), axis) + limit.CreateLowAttr(1.0) + limit.CreateHighAttr(-1.0) + slider = UsdPhysics.PrismaticJoint.Define(stage, "/Robot/Slider") + slider.CreateAxisAttr("X") + for joint, parent, child in ((ball, "Base", "Tip"), (slider, "Tip", "Carriage")): + joint.CreateBody0Rel().SetTargets([f"/Robot/{parent}"]) + joint.CreateBody1Rel().SetTargets([f"/Robot/{child}"]) + joint.CreateLocalPos0Attr((0.0, 0.0, 0.4)) + usd_path = str(path / "ball_slider.usda") + stage.Export(usd_path) + return usd_path + + +@pytest.mark.parametrize("device", _CUDA_DEVICES) +def test_session_reads_pad_shorter_articulations(device: str, tmp_path: Path) -> None: + """A view over articulations of different lengths and joint types reads and writes the binding's padded layout; + padding reads zero, a multi-axis joint's axes keep their order and a prismatic axis keeps its unit.""" + sim_cfg = SimulationCfg(physics=OvPhysxCfg(), device=device, gravity=(0.0, 0.0, 0.0)) + with build_simulation_context(device=device, sim_cfg=sim_cfg) as sim: + cfg = InteractiveSceneCfg(num_envs=1, env_spacing=2.0) + cfg.short = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Short", + spawn=sim_utils.UsdFileCfg(usd_path=_chain_usd(tmp_path, 2)), + actuators=_implicit(), + ) + cfg.long = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Long", + spawn=sim_utils.UsdFileCfg(usd_path=_chain_usd(tmp_path, 3)), + init_state=ArticulationCfg.InitialStateCfg(pos=(1.0, 0.0, 0.0), joint_pos={".*": 0.3}), + actuators=_implicit(), + ) + cfg.mixed = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Mixed", + spawn=sim_utils.UsdFileCfg(usd_path=_ball_slider_usd(tmp_path)), + init_state=ArticulationCfg.InitialStateCfg(pos=(2.0, 0.0, 0.0)), + actuators=_implicit(), + ) + scene = InteractiveScene(cfg) + sim.reset() + sim.step() + roots = [scene[name].root_view.prim_paths[0] for name in ("short", "long", "mixed")] + view = OvPhysxView(sim.backend_manager.get_physx_instance(), prim_paths=roots, device=device) + try: + # A distinct position per DOF, so a swapped axis or a scaled linear axis shows; padding stays zero. + positions = np.zeros(tuple(view.binding_for(TT.DOF_POSITION).shape), dtype=np.float32) + for row, name in enumerate(("short", "long", "mixed")): + for dof in range(scene[name].num_joints): + positions[row, dof] = (0.1 * (row + 1) + 0.02 * (dof + 1)) * (-1) ** dof + # The session writes land as the binding writes of the same distinct values do. + for tensor_type in (TT.DOF_POSITION, TT.DOF_POSITION_TARGET, TT.DOF_ACTUATION_FORCE): + start = binding_values(view, tensor_type) + written, expected = session_and_binding_writes( + view, tensor_type, start, wp.array(positions, device=device) + ) + _assert_write_matches(written, expected, f"padded {tensor_type.name}") + binding_write(view, TT.DOF_POSITION, wp.array(positions, device=device)) + for tensor_type in (TT.LINK_POSE, TT.LINK_VELOCITY, TT.DOF_POSITION, TT.DOF_VELOCITY): + expected = binding_values(view, tensor_type) + replayed = wp.zeros_like(expected) + view.read_into(tensor_type, replayed) # captures the read + replayed.fill_(-1.0) # the replay must write the padding too + with replays_only(view, tensor_type): + view.read_into(tensor_type, replayed) + _assert_session_matches(wp.to_torch(replayed), wp.to_torch(expected), tensor_type, tensor_type.name) + finally: + view.close() + + +@pytest.mark.parametrize("device", _CUDA_DEVICES) +def test_session_reads_record_into_the_callers_graph(device: str) -> None: + """Reads and a write made inside the caller's capture, after a warmup call, are recorded into the caller's graph: + each replay writes the joint targets its source then holds, and refreshes the destinations after the work captured + before them, after a step and after a joint write.""" + sim_cfg = SimulationCfg(physics=OvPhysxCfg(), device=device) + with build_simulation_context(device=device, sim_cfg=sim_cfg) as sim: + cfg = InteractiveSceneCfg(num_envs=2, env_spacing=2.0) + cfg.robot = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Robot", spawn=sim_utils.UsdFileCfg(usd_path=str(_FIXTURE)), actuators=_implicit() + ) + scene = InteractiveScene(cfg) + sim.reset() + robot = scene["robot"] + view = robot.root_view + tensor_types = (TT.DOF_POSITION, TT.LINK_POSE, TT.JACOBIAN) + replayed = {tensor_type: wp.zeros_like(binding_values(view, tensor_type)) for tensor_type in tensor_types} + for tensor_type in tensor_types: # the warmup step reads outside any capture + view.read_into(tensor_type, replayed[tensor_type]) + targets = wp.clone(binding_values(view, TT.DOF_POSITION_TARGET)) + view.set_attribute(TT.DOF_POSITION_TARGET, targets) # and writes outside any capture + stream = wp.Stream(device) + with wp.ScopedStream(stream), wp.ScopedCapture(device=device) as capture: + view.set_attribute(TT.DOF_POSITION_TARGET, targets) + for tensor_type in tensor_types: + replayed[tensor_type].fill_(-7.0) # captured before the read, which must land after it + view.read_into(tensor_type, replayed[tensor_type]) + for change in ("step", "joint write"): + if change == "step": + sim.step() + else: + robot.write_joint_position_to_sim_index(position=robot.data.joint_pos.torch + 0.1) + with wp.ScopedStream(stream): + sim.forward() # the caller refreshes the kinematics on its replay stream before launching + wp.to_torch(targets).add_(0.1) # the replay writes the targets the source holds now + wp.capture_launch(capture.graph, stream=stream) + wp.synchronize_stream(stream) + written = wp.to_torch(binding_values(view, TT.DOF_POSITION_TARGET)) + _assert_write_matches(written, wp.to_torch(targets), f"DOF_POSITION_TARGET after a {change}") + for tensor_type in tensor_types: + expected = wp.to_torch(binding_values(view, tensor_type)) + name = f"{tensor_type.name} after a {change}" + _assert_session_matches(wp.to_torch(replayed[tensor_type]), expected, tensor_type, name) + # A read that never ran outside any capture is refused before its setup, which a capture cannot record. + cold = wp.zeros_like(binding_values(view, TT.DOF_VELOCITY)) + with pytest.raises(RuntimeError, match="read once outside any capture"): + with wp.ScopedStream(stream), wp.ScopedCapture(device=device): + view.read_into(TT.DOF_VELOCITY, cold) + + +@pytest.mark.parametrize("device", _CUDA_DEVICES) +def test_session_writes_act_as_binding_writes(device: str) -> None: + """A replayed session write acts on the simulation as the binding write does: the link poses and velocities after a + kinematic refresh, and the state two steps later, match for every write type, an external wrench included.""" + sim_cfg = SimulationCfg(physics=OvPhysxCfg(), device=device) + with build_simulation_context(device=device, sim_cfg=sim_cfg) as sim: + cfg = InteractiveSceneCfg(num_envs=2, env_spacing=3.0) + cfg.robot = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=sim_utils.UsdFileCfg(usd_path=str(_FIXTURE)), + actuators=_implicit(), + init_state=ArticulationCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + ) + scene = InteractiveScene(cfg) + sim.reset() + sim.step() + manager, view = sim.backend_manager, scene["robot"].root_view + state_types = (TT.ROOT_POSE, TT.ROOT_VELOCITY, TT.DOF_POSITION, TT.DOF_VELOCITY) + written_types = (TT.DOF_POSITION_TARGET, TT.DOF_VELOCITY_TARGET, TT.DOF_ACTUATION_FORCE) + snapshot = {t: wp.clone(binding_values(view, t)) for t in (*written_types, *state_types)} + + def restore() -> None: + for tensor_type, values in snapshot.items(): + binding_write(view, tensor_type, values) + manager.kinematics_dirty = True + manager.update_kinematics() + + def observe() -> dict[str, torch.Tensor]: + wp.synchronize_device(device) + observed = (*state_types, TT.LINK_POSE, TT.LINK_VELOCITY) + return {t.name: wp.to_torch(binding_values(view, t)).clone() for t in observed} + + for tensor_type in written_types: + values = _shifted(snapshot[tensor_type], 0.3) + restore() + view.set_attribute(tensor_type, values) # captures, so the arm below replays + observed = {} + for arm in ("binding", "session"): + restore() + if arm == "binding": + binding_write(view, tensor_type, values) + else: + view.set_attribute(tensor_type, values) + manager.kinematics_dirty = True + manager.update_kinematics() + after_refresh = observe() + sim.step() + sim.step() + observed[arm] = {"refresh": after_refresh, "steps": observe()} + for phase in ("refresh", "steps"): + for name, expected in observed["binding"][phase].items(): + torch.testing.assert_close( + observed["session"][phase][name], + expected, + atol=1e-5, + rtol=1e-5, + msg=f"{tensor_type.name} write, {name} after the {phase}", + ) + # An external wrench applies for one step: it is written before each step, as the asset writes it. + wrench = torch.zeros(tuple(view.binding_for(TT.LINK_WRENCH).shape), device=device) + rows = wrench.view(-1, 9) # force, torque, world application point + rows[:, 2], rows[:, 5] = 20.0, 0.5 + rows[:, 6:9] = wp.to_torch(binding_values(view, TT.LINK_POSE)).view(-1, 7)[:, :3] + wrench = wp.from_torch(wrench) + view.set_attribute(TT.LINK_WRENCH, wrench) # captures, so the arm below replays + observed = {} + for arm in ("binding", "session"): + restore() + for _ in range(2): + if arm == "binding": + binding_write(view, TT.LINK_WRENCH, wrench) + else: + view.set_attribute(TT.LINK_WRENCH, wrench) + sim.step() + observed[arm] = observe() + for name, expected in observed["binding"].items(): + torch.testing.assert_close( + observed["session"][name], expected, atol=1e-5, rtol=1e-5, msg=f"LINK_WRENCH write, {name}" + ) + # A centre-of-mass write makes the wrench write capture again, as ovphysx requires, so it still acts as the + # binding's. + coms = wp.clone(binding_values(view, TT.BODY_COM_POSE)) + shifted_coms = wp.clone(coms) + wp.to_torch(shifted_coms).view(-1, 7)[:, 0] += 0.05 + view.set_attribute(TT.BODY_COM_POSE, shifted_coms) + observed = {} + for arm in ("binding", "session"): + restore() + for _ in range(2): + if arm == "binding": + binding_write(view, TT.LINK_WRENCH, wrench) + else: + view.set_attribute(TT.LINK_WRENCH, wrench) + sim.step() + observed[arm] = observe() + for name, expected in observed["binding"].items(): + torch.testing.assert_close( + observed["session"][name], expected, atol=1e-5, rtol=1e-5, msg=f"LINK_WRENCH after a COM write, {name}" + ) + view.set_attribute(TT.BODY_COM_POSE, coms) + restore() + + +@pytest.mark.parametrize("device", _CUDA_DEVICES) +def test_masked_state_writes_keep_the_unselected_joint_forces(device: str) -> None: + """A root or joint state write by mask, then a kinematic refresh, leave the incoming joint forces of the + environments it does not select, and of another articulation, as the last step computed them: the refresh clears + them only for the written environments (a session commit of articulation state would write every articulation).""" + with build_simulation_context(device=device, sim_cfg=SimulationCfg(physics=OvPhysxCfg(), device=device)) as sim: + robots = [ + _spawn_island(name, _IslandCfg(_implicit()), y_offset) for name, y_offset in (("A", 0.0), ("B", 10.0)) + ] + sim.reset() + for robot in robots: + robot.set_joint_position_target_index(target=robot.data.joint_pos.torch + 0.5) + written, first = robots[0], wp.array([True, False], dtype=wp.bool, device=device) + writes = { + "root pose": lambda: written.write_root_link_pose_to_sim_mask( + root_pose=written.data.root_link_pose_w.torch.clone(), env_mask=first + ), + "joint position": lambda: written.write_joint_position_to_sim_mask( + position=written.data.joint_pos.torch.clone(), env_mask=first + ), + } + for name, write in writes.items(): + for _ in range(10): + for robot in robots: + robot.write_data_to_sim() + sim.step() + for robot in robots: + robot.update(sim.get_physics_dt()) + forces = [wp.to_torch(binding_values(r.root_view, TT.LINK_INCOMING_JOINT_FORCE)).clone() for r in robots] + assert forces[0][1].abs().max() > 1.0, "the links hang under gravity, so their joints carry load" + write() + sim.forward() + after = [wp.to_torch(binding_values(r.root_view, TT.LINK_INCOMING_JOINT_FORCE)) for r in robots] + torch.testing.assert_close(after[0][1], forces[0][1], msg=f"{name}: the unselected environment") + torch.testing.assert_close(after[1], forces[1], msg=f"{name}: the other articulation") + + +@pytest.mark.parametrize("device", _CUDA_DEVICES) +def test_session_kinematic_reads_follow_joint_writes(device: str) -> None: + """The asset's Jacobian and mass matrix, which session reads serve, each see a joint write with no step in between. + + A binding read refreshes the kinematics itself; a session read does not, so the asset data refreshes them first, as + for link poses. The test builds its own scene: on the module scene it passed with that refresh removed once other + tests had run first. + """ + sim_cfg = SimulationCfg(physics=OvPhysxCfg(), device=device) + with build_simulation_context(device=device, sim_cfg=sim_cfg, auto_add_lighting=False) as sim: + # Without joint or body ordering, the asset's buffers hold the binding's layout. + island = replace(_ISLANDS["dynamics"], joint_ordering=None, body_ordering=None) + articulation = _spawn_island("dynamics", island, y_offset=0.0) + sim.reset() + data = articulation.data + for tensor_type, read in ((TT.JACOBIAN, "body_com_jacobian_w"), (TT.MASS_MATRIX, "mass_matrix")): + before = getattr(data, read).torch.clone() + joints = data.joint_pos.torch.clone() + joints[:, 1] += 0.2 + articulation.write_joint_position_to_sim_index(position=joints) + after = getattr(data, read).torch.clone() + assert not torch.equal(after, before), f"{read}: the read after the joint write kept the old kinematics" + expected = wp.to_torch(binding_values(articulation.root_view, tensor_type)) + torch.testing.assert_close(after.reshape(expected.shape), expected, atol=0.0, rtol=0.0, msg=read) + + @pytest.mark.parametrize("device", test_devices(DeviceScope.CPU)) @pytest.mark.parametrize( ("init_state", "match"), @@ -864,6 +1202,168 @@ def test_articulation_initialization_and_partial_state(scene: _ArticulationScene ) +@pytest.mark.parametrize("scene", _CUDA_DEVICES, indirect=True) +@pytest.mark.parametrize( + "tensor_type", + [ + TT.ROOT_POSE, + TT.ROOT_VELOCITY, + TT.LINK_POSE, + TT.LINK_VELOCITY, + TT.LINK_ACCELERATION, + TT.LINK_INCOMING_JOINT_FORCE, + TT.DOF_POSITION, + TT.DOF_VELOCITY, + TT.JACOBIAN, + TT.MASS_MATRIX, + ], +) +def test_session_reads_match_bindings(scene: _ArticulationScene, tensor_type: int) -> None: + """A session read fills ``read_into`` with the binding's values, rows and lanes, and refreshes them on later + reads after steps and writes.""" + replayed = {} + for name, articulation in scene.islands.items(): # the first read builds (and captures) each read + replayed[name] = wp.zeros_like(binding_values(articulation.root_view, tensor_type)) + articulation.root_view.read_into(tensor_type, replayed[name]) + for _ in range(3): + scene.sim.step() + floating = scene.islands["floating"] + pose = floating.data.default_root_pose.torch.clone() + pose[:, 2] += 0.25 + floating.write_root_pose_to_sim_index(root_pose=pose) + joints = floating.data.joint_pos.torch.clone() + joints[:, 1] += 0.2 + floating.write_joint_position_to_sim_index(position=joints) + expected = {} + for name, articulation in scene.islands.items(): + view = articulation.root_view + # This read, right after the writes, replays the read captured above. + with replays_only(view, tensor_type): + view.read_into(tensor_type, replayed[name]) + expected[name] = binding_values(view, tensor_type) + for name in scene.islands: + _assert_session_matches(wp.to_torch(replayed[name]), wp.to_torch(expected[name]), tensor_type, name) + + +@pytest.mark.parametrize("scene", _CUDA_DEVICES, indirect=True) +@pytest.mark.parametrize( + "tensor_type", + [TT.DOF_POSITION_TARGET, TT.DOF_VELOCITY_TARGET, TT.DOF_ACTUATION_FORCE], +) +def test_session_writes_match_bindings(scene: _ArticulationScene, tensor_type: int) -> None: + """A session write leaves the engine as the binding write of the same values does: a whole write, a replay after + its source changes in place, a write from a second source and a replay from the first, a masked write, and its + replay after the source and the mask change in place. On one articulation and type, as neither changes them: a mask + that is not a contiguous bool array on the simulation device, or is empty, is refused; an indices write takes the + binding, after the session writes queued before it.""" + once = tensor_type == TT.DOF_POSITION_TARGET + for name, articulation in scene.islands.items(): + view = articulation.root_view + start = wp.clone(binding_values(view, tensor_type)) + instances = view.binding_for(tensor_type).shape[0] + + def check(case: str, values: wp.array, **kwargs) -> None: + written, expected = session_and_binding_writes(view, tensor_type, start, values, **kwargs) + _assert_write_matches(written, expected, f"{name}: {case}") + + source = _shifted(start, 0.01) + check("whole write", source) + wp.copy(source, _shifted(start, 0.02)) + check("replay after the source changed", source, replay=True) + check("second source", _shifted(start, 0.03)) + check("replay from the first source", source, replay=True) + selected = wp.array([index == instances - 1 for index in range(instances)], dtype=wp.bool, device=start.device) + masked = _shifted(start, 0.04) + check("mask", masked, mask=selected) + wp.copy(masked, _shifted(start, 0.05)) + wp.copy(selected, wp.array([index % 2 == 0 for index in range(instances)], dtype=wp.bool, device=start.device)) + check("replay after the source and the mask changed", masked, mask=selected, replay=True) + if once: + once = False + strided = wp.array([True] * (2 * instances), dtype=wp.bool, device=start.device)[::2] + with pytest.raises(ValueError, match="contiguous array of one bool per binding instance"): + view.set_attribute(tensor_type, masked, mask=strided) + with pytest.raises(ValueError, match="contiguous array of one bool per binding instance"): + view.set_attribute(tensor_type, source, mask=wp.empty(0, dtype=wp.bool, device=start.device)) + for refused in ( + wp.array(selected.numpy().astype("uint8"), device=start.device), + wp.array(selected.numpy(), dtype=wp.bool, device="cpu"), + ): + with pytest.raises(ValueError, match="contiguous array of one bool per binding instance"): + view.set_attribute(tensor_type, masked, mask=refused) + indices = wp.array([0], dtype=wp.int32, device=start.device) + written, expected = session_write_then_binding_indices(view, tensor_type, start, source, indices) + _assert_write_matches(written, expected, f"{name}: indices write after a session write") + binding_write(view, tensor_type, start) + + +def _shifted(values: wp.array, amount: float) -> wp.array: + """A new array of ``values``, each element shifted by a distinct multiple of ``amount`` in ``[amount, 2 * amount)`` + so a swapped row shows.""" + shifted = wp.to_torch(values).clone() + ramp = torch.arange(shifted.numel(), device=shifted.device, dtype=shifted.dtype).reshape(shifted.shape) + shifted += amount * (1.0 + (ramp % 97) / 97) + return wp.from_torch(shifted) + + +def _assert_write_matches(written: torch.Tensor, expected: torch.Tensor, name: str) -> None: + """Session and binding writes agree; a joint quantity the session holds per degree may round the last bit.""" + torch.testing.assert_close(written, expected, atol=1e-6, rtol=1e-6, equal_nan=True, msg=name) + + +def _assert_session_matches(replayed: torch.Tensor, expected: torch.Tensor, tensor_type: int, name: str) -> None: + """Session and binding values agree; joint quantities the session reports per degree may round the last bit.""" + joint = tensor_type in (TT.DOF_POSITION, TT.DOF_VELOCITY) + rtol = 2.0**-22 if joint else 0.0 + if joint: # the likeliest cause of a mismatch is in the dependency + name += " (ovphysx still reports angular joint quantities in degrees? OvPhysxCapturedSessions._map_dof_rows)" + # The "tendon" island diverges to NaN on main too; both reads must then hold NaN at the same places. + torch.testing.assert_close(replayed, expected, atol=0.0, rtol=rtol, equal_nan=True, msg=name) + + +@pytest.mark.parametrize("scene", _CUDA_DEVICES, indirect=True) +@pytest.mark.parametrize("tensor_type", [TT.RIGID_BODY_POSE, TT.RIGID_BODY_VELOCITY, TT.RIGID_BODY_ACCELERATION]) +def test_session_rigid_body_reads_of_links_match_bindings(scene: _ArticulationScene, tensor_type: int) -> None: + """A rigid-body view over articulation links, as sensors attach to, reads them as links and matches the binding.""" + articulation = scene.islands["floating"] + paths = [ + f"/World/floating/Env_{env}/Robot/{body}" + for env in range(articulation.num_instances) + for body in BRANCHING_PHYSX_BODY_NAMES + ] + view = OvPhysxView(articulation._ovphysx, prim_paths=paths, device=scene.device) + try: + expected = binding_values(view, tensor_type) + replayed = wp.zeros_like(expected) + view.read_into(tensor_type, replayed) # captures the read + replayed.fill_(-1.0) + with replays_only(view, tensor_type): + view.read_into(tensor_type, replayed) + torch.testing.assert_close(wp.to_torch(replayed), wp.to_torch(expected), atol=0.0, rtol=0.0) + finally: + view.close() + + +@pytest.mark.parametrize("scene", _CUDA_DEVICES, indirect=True) +def test_gravity_force_reads_follow_set_gravity(scene: _ArticulationScene) -> None: + """The gravity compensation force follows ``set_gravity``: its kernel takes the scene gravity of each launch, which + a captured read would keep from its capture.""" + manager = scene.sim.backend_manager + view = scene.islands["dynamics"].root_view + forces = wp.zeros_like(binding_values(view, TT.GRAVITY_FORCE)) + view.read_into(TT.GRAVITY_FORCE, forces) + assert wp.to_torch(forces).abs().max() > 0.0 + try: + manager.set_gravity((0.0, 0.0, 0.0)) + scene.sim.step() + view.read_into(TT.GRAVITY_FORCE, forces) + expected = wp.to_torch(binding_values(view, TT.GRAVITY_FORCE)) + assert expected.abs().max() == 0.0 + torch.testing.assert_close(wp.to_torch(forces), expected, atol=0.0, rtol=0.0) + finally: + manager.set_gravity(tuple(scene.sim.cfg.gravity)) + + @pytest.mark.parametrize("scene", _ALL_DEVICES, indirect=True) def test_articulation_joint_and_body_properties_round_trip(scene: _ArticulationScene) -> None: """Prove selected joint and body properties reach real OVPhysX bindings and public getters.""" @@ -1753,6 +2253,9 @@ def test_root_link_vel_w_refreshes_fk_before_body_com_vel_w_read(scene: _Articul with monkeypatch.context() as patch: physx = Mock(wraps=scene.sim.backend_manager.backend.physx) patch.setattr(scene.sim.backend_manager.backend, "physx", physx) + sessions = scene.sim.backend_manager.backend.captured_sessions + if sessions is not None: # a CUDA scene refreshes through its captured sessions + patch.setattr(sessions, "_physx", physx) if render_first: scene.sim.backend_manager.pre_render() articulation.data.root_link_vel_w diff --git a/source/isaaclab_ov/test/assets/test_deformable_object.py b/source/isaaclab_ov/test/assets/test_deformable_object.py index cbf9cb1b8b4a..429a95644025 100644 --- a/source/isaaclab_ov/test/assets/test_deformable_object.py +++ b/source/isaaclab_ov/test/assets/test_deformable_object.py @@ -29,7 +29,7 @@ from isaaclab_ov.physics import OvPhysxCfg, OvPhysxManager # noqa: E402 from isaaclab_ov.physics.ovphysx_manager import OvPhysxSceneDataBackend # noqa: E402 -from pxr import Gf, Sdf, Usd, UsdGeom # noqa: E402 +from pxr import Gf, Usd, UsdGeom # noqa: E402 import isaaclab.sim as sim_utils # noqa: E402 import isaaclab.utils.math as math_utils # noqa: E402 @@ -43,6 +43,7 @@ from ..deformable_utils import ( # noqa: E402 pre_tetrahedralized_deformable_spawn_cfg, pretriangulated_surface_deformable_spawn_cfg, + spawn_pre_tetrahedralized_deformable, ) pytestmark = pytest.mark.ov @@ -86,10 +87,11 @@ def _generate_deformable_scene( num_objects: int = 2, height: float = 1.0, initial_rot: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0), + scale: tuple[float, float, float] | None = None, ) -> DeformableObject: - """Create independently authored deformables beneath matching parent prims.""" + """Create independently authored deformables beneath matching parent prims, scaled by ``scale``.""" for index in range(num_objects): - sim_utils.create_prim(f"/World/Table_{index}", "Xform", translation=(index * 1.0, 0.0, height)) + sim_utils.create_prim(f"/World/Table_{index}", "Xform", translation=(index * 1.0, 0.0, height), scale=scale) cfg = DeformableObjectCfg( prim_path="/World/Table_[^/]*/Object", spawn=spawn, @@ -970,10 +972,8 @@ def test_heterogeneous_mixed_deformable_rigid_scene_materializes_missing_targets runtime_paths = shape.root_view.prim_paths assert set(runtime_paths) == expected_paths assert len(runtime_paths) == len(set(runtime_paths)) == num_envs - assert sim.backend_manager._stage_usda is not None - layer = Sdf.Layer.CreateAnonymous("materialized.usda") - assert layer.ImportFromString(sim.backend_manager._stage_usda) - materialized_stage = Usd.Stage.Open(layer) + materialized_stage = sim.backend_manager.backend.usd_stage + assert materialized_stage is not None assert materialized_stage.GetPrimAtPath(camera_path).IsValid() assert all(materialized_stage.GetPrimAtPath(path).IsValid() for path in authored_deformable_paths) @@ -1011,3 +1011,127 @@ def test_heterogeneous_mixed_deformable_rigid_scene_materializes_missing_targets wp.to_torch(geometry[f"/World/envs/env_{index}/Object/simulation"]), deformable.data.nodal_pos_w.torch[index], ) + + # Session reads of the cloned bodies match the binding, plan placements included. + from isaaclab_ov.test.fixtures.views.captured_sessions import binding_values, replays_only + + view = deformable.root_view + for tensor_type in (deformable._sim_nodal_position_type, deformable._sim_nodal_velocity_type): + expected = binding_values(view, tensor_type) + values = wp.zeros_like(expected) + view.read_into(tensor_type, values) # captures the read + values.fill_(-1.0) + with replays_only(view, tensor_type): + view.read_into(tensor_type, values) + torch.testing.assert_close(wp.to_torch(values), wp.to_torch(expected), atol=1e-5, rtol=0.0) + + +_SESSION_DEFORMABLE_CASES = { + "volume": ( + pre_tetrahedralized_deformable_spawn_cfg, + ( + TT.DEFORMABLE_SIM_NODAL_POSITION, + TT.DEFORMABLE_SIM_NODAL_VELOCITY, + ), + ), + "surface": ( + pretriangulated_surface_deformable_spawn_cfg, + ( + TT.SURFACE_DEFORMABLE_SIM_POSITION, + TT.SURFACE_DEFORMABLE_SIM_VELOCITY, + ), + ), +} + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="OVPhysX deformables require CUDA") +@pytest.mark.parametrize("kind", list(_SESSION_DEFORMABLE_CASES)) +def test_session_deformable_reads_match_bindings(kind: str) -> None: + """Session reads of rotated, scaled, falling deformables match the binding: points taken from the sim-mesh frame + to world. + + The parents scale each axis differently and one node per body leaves the authored plane, so the out-of-plane axis + of the flat surface mesh is read too. Each captured read is built before the write and the steps, so the comparison + is of a later replay. + """ + from isaaclab_ov.test.fixtures.views.captured_sessions import binding_values, replays_only + + spawn, tensor_types = _SESSION_DEFORMABLE_CASES[kind] + with _ovphysx_sim_context(device="cuda:0", gravity_enabled=True) as sim: + deformable = _generate_deformable_scene( + spawn(), num_objects=2, initial_rot=(0.0, 0.0, 0.3826834, 0.9238795), scale=(1.2, 0.8, 2.0) + ) + sim.reset() + view = deformable.root_view + replayed = {} + for tensor_type in tensor_types: + replayed[tensor_type] = wp.zeros_like(binding_values(view, tensor_type)) + view.read_into(tensor_type, replayed[tensor_type]) + lifted = deformable.data.nodal_pos_w.torch.clone() + lifted[:, 1, 2] += 0.05 # the authored plane is the parent's xy plane + deformable.write_nodal_pos_to_sim_index(lifted) + for _ in range(5): + sim.step() + deformable.update(sim.cfg.dt) + expected = {} + for tensor_type, values in replayed.items(): + expected[tensor_type] = binding_values(view, tensor_type) + with replays_only(view, tensor_type): + view.read_into(tensor_type, values) + for tensor_type, values in replayed.items(): + # Points pass through the sim-mesh prim's world transform, in float32; velocities are copied. + points = tensor_type in (TT.DEFORMABLE_SIM_NODAL_POSITION, TT.SURFACE_DEFORMABLE_SIM_POSITION) + # The likeliest cause of a position mismatch is in the dependency. + hint = " (does ovphysx still report points in the sim-mesh frame? OvPhysxCapturedSessions._map_node_rows)" + torch.testing.assert_close( + wp.to_torch(values), + wp.to_torch(expected[tensor_type]), + atol=1e-6 if points else 0, + rtol=0.0, + msg=f"{tensor_type.name}{hint if points else ''}", + ) + del replayed, values, expected + + +def _keep_first_tetrahedron(stage: Usd.Stage, path: str) -> None: + """Cut a spawned five-node volume deformable down to its first tetrahedron: four nodes.""" + prim = stage.GetPrimAtPath(path) + points = list(prim.GetAttribute("points").Get())[:4] + for name in ("deformablePose:default:omniphysics:points", "omniphysics:restShapePoints", "points"): + prim.GetAttribute(name).Set(points) + prim.GetAttribute("velocities").Set([Gf.Vec3f()] * len(points)) + for name in ("omniphysics:restTetVtxIndices", "tetVertexIndices"): + prim.GetAttribute(name).Set([Gf.Vec4i(0, 1, 2, 3)]) + faces = [Gf.Vec3i(0, 2, 1), Gf.Vec3i(0, 1, 3), Gf.Vec3i(0, 3, 2), Gf.Vec3i(1, 2, 3)] + prim.GetAttribute("surfaceFaceVertexIndices").Set(faces) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="OVPhysX deformables require CUDA") +def test_session_deformable_reads_pad_shorter_bodies() -> None: + """A view over deformables with different node counts reads the binding's padding for the shorter body's missing + nodes, not what the destination held before.""" + from isaaclab_ov.sim.views import OvPhysxView + from isaaclab_ov.test.fixtures.views.captured_sessions import binding_values, replays_only + + with _ovphysx_sim_context(device="cuda:0") as sim: + paths = [] + for index in range(2): + sim_utils.create_prim(f"/World/Mixed_{index}", "Xform", translation=(index * 1.0, 0.0, 1.0)) + spawn_pre_tetrahedralized_deformable( + f"/World/Mixed_{index}/Object", pre_tetrahedralized_deformable_spawn_cfg() + ) + paths.append(f"/World/Mixed_{index}/Object/simulation") + _keep_first_tetrahedron(sim_utils.get_current_stage(), paths[1]) + sim.reset() + view = OvPhysxView(sim.backend_manager.get_physx_instance(), prim_paths=paths, device="cuda:0") + try: + expected = binding_values(view, TT.DEFORMABLE_SIM_NODAL_POSITION) + assert expected.shape[1] == 5, "the four-node body needs a padded row" + replayed = wp.zeros_like(expected) + view.read_into(TT.DEFORMABLE_SIM_NODAL_POSITION, replayed) # captures the read + replayed.fill_(-1.0) + with replays_only(view, TT.DEFORMABLE_SIM_NODAL_POSITION): + view.read_into(TT.DEFORMABLE_SIM_NODAL_POSITION, replayed) + torch.testing.assert_close(wp.to_torch(replayed), wp.to_torch(expected), atol=1e-5, rtol=0.0) + finally: + view.close() diff --git a/source/isaaclab_ov/test/assets/test_rigid_object.py b/source/isaaclab_ov/test/assets/test_rigid_object.py index 7b73064d123c..7c131b44067c 100644 --- a/source/isaaclab_ov/test/assets/test_rigid_object.py +++ b/source/isaaclab_ov/test/assets/test_rigid_object.py @@ -20,6 +20,7 @@ from __future__ import annotations +import contextlib from collections.abc import Iterator from dataclasses import dataclass @@ -36,6 +37,14 @@ from isaaclab_ov import tensor_types as TT # noqa: E402 from isaaclab_ov.assets import RigidObject, RigidObjectCollection # noqa: E402 from isaaclab_ov.physics import OvPhysxCfg # noqa: E402 +from isaaclab_ov.test.fixtures.views.captured_sessions import ( # noqa: E402 + binding_values, + binding_write, + replays_only, + session_and_binding_writes, + session_write_then_binding_indices, + writes_replay_only, +) import isaaclab.sim as sim_utils # noqa: E402 from isaaclab import cloner # noqa: E402 @@ -83,8 +92,13 @@ def _spawn_static_colliders() -> RigidObject: ) -def _spawn_collection(name: str, y_offset: float, spawn: sim_utils.SpawnerCfg | None = None) -> RigidObjectCollection: - """Author one canonical ``N=2, B=3`` local collection.""" +def _spawn_collection( + name: str, + y_offset: float, + spawn: sim_utils.SpawnerCfg | None = None, + bodies: tuple[str, ...] = ("left", "middle", "right"), +) -> RigidObjectCollection: + """Author one local collection of ``N=2`` environments, canonically of ``B=3`` bodies.""" if spawn is None: spawn = sim_utils.CuboidCfg( size=(0.2, 0.2, 0.2), @@ -102,7 +116,7 @@ def _spawn_collection(name: str, y_offset: float, spawn: sim_utils.SpawnerCfg | spawn=spawn, init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, float(body_index), 1.0)), ) - for body_index, body_name in enumerate(("left", "middle", "right")) + for body_index, body_name in enumerate(bodies) } ) ) @@ -292,6 +306,101 @@ def test_collection_initialization_with_no_rigid_body(device: str) -> None: assert not object_collection.is_initialized +@pytest.mark.parametrize("device", _CUDA) +def test_session_writes_act_as_binding_writes(device: str) -> None: + """A replayed session write of an external wrench, which cannot be read back, moves the bodies as the binding write + does: the poses and velocities match after the steps, for a whole write and for two writes by disjoint masks. Pose + and velocity writes are compared row by row in test_session_writes_match_bindings.""" + with build_simulation_context(device=device, sim_cfg=SimulationCfg(physics=OvPhysxCfg(), device=device)) as sim: + cubes = _spawn_cubes("Written", y_offset=0.0) + sim.reset() + sim.step() + view = cubes.root_view + state_types = (TT.RIGID_BODY_POSE, TT.RIGID_BODY_VELOCITY) + snapshot = {tensor_type: wp.clone(binding_values(view, tensor_type)) for tensor_type in state_types} + + def restore() -> None: + for tensor_type, values in snapshot.items(): + binding_write(view, tensor_type, values) + + # An external wrench applies for one step: it is written before each step, as the asset writes it. + wrench = torch.zeros(tuple(view.binding_for(TT.RIGID_BODY_WRENCH).shape), device=device) + rows = wrench.view(-1, 9) # force, torque, world application point + rows[:, 2], rows[:, 5] = 20.0, 0.5 + rows[:, 6:9] = wp.to_torch(snapshot[TT.RIGID_BODY_POSE]).view(-1, 7)[:, :3] + wrench = wp.from_torch(wrench) + view.set_attribute(TT.RIGID_BODY_WRENCH, wrench) # captures, so the arm below replays + observed = {} + for arm in ("binding", "session"): + restore() + for _ in range(2): + if arm == "binding": + binding_write(view, TT.RIGID_BODY_WRENCH, wrench) + else: + view.set_attribute(TT.RIGID_BODY_WRENCH, wrench) + sim.step() + wp.synchronize_device(device) + observed[arm] = {t.name: wp.to_torch(binding_values(view, t)).clone() for t in state_types} + for name, expected in observed["binding"].items(): + torch.testing.assert_close( + observed["session"][name], expected, atol=1e-5, rtol=1e-5, msg=f"RIGID_BODY_WRENCH write: {name}" + ) + # Two wrench writes by disjoint masks before a step both apply, as the binding's do. + masks = [ + wp.array([True, False], dtype=wp.bool, device=device), + wp.array([False, True], dtype=wp.bool, device=device), + ] + observed = {} + for arm in ("binding", "session"): + restore() + for mask in masks: + if arm == "binding": + binding_write(view, TT.RIGID_BODY_WRENCH, wrench, mask=mask) + else: + view.set_attribute(TT.RIGID_BODY_WRENCH, wrench, mask=mask) + sim.step() + wp.synchronize_device(device) + observed[arm] = wp.to_torch(binding_values(view, TT.RIGID_BODY_VELOCITY)).clone() + assert (observed["binding"].view(_NUM_CUBES, -1)[:, 2] > 0.0).all(), "each cube takes its own masked wrench" + torch.testing.assert_close(observed["session"], observed["binding"], atol=1e-5, rtol=1e-5) + + +@pytest.mark.parametrize("device", _CUDA) # the layout check is device-independent; CUDA also takes the session write +def test_collection_of_seven_bodies_writes_its_own_rows(device: str) -> None: + """A collection of seven bodies, whose fused pose binding rows also hold seven lanes, writes each selected + (environment, body) pose to its own row, by mask and by index. The index write covers every body of the environment: + a partial one rewinds the other bodies (test_partial_body_pose_write_preserves_unselected_bodies_after_steps).""" + bodies = tuple(f"body_{index}" for index in range(7)) + with build_simulation_context(device=device, sim_cfg=SimulationCfg(physics=OvPhysxCfg(), device=device)) as sim: + collection = _spawn_collection("Seven", y_offset=0.0, bodies=bodies) + sim.reset() + view = collection.root_view + + def poses() -> torch.Tensor: + raw = wp.to_torch(binding_values(view, TT.LINK_POSE)).reshape(len(bodies), _NUM_ENVS, 7) + return raw.transpose(0, 1).to(device).clone() + + start = poses() + values = start.clone() + values[..., :3] += 0.1 + collection.write_body_link_pose_to_sim_mask( + body_poses=wp.from_torch(values.contiguous(), dtype=wp.transformf), + env_mask=wp.array([False, True], dtype=wp.bool, device=device), + body_mask=wp.array([index in (0, 6) for index in range(len(bodies))], dtype=wp.bool, device=device), + ) + wp.synchronize_device(device) + expected = start.clone() + expected[1, [0, 6]] = values[1, [0, 6]] + torch.testing.assert_close(poses(), expected, msg="by mask") + expected[0, :, :3] += 0.2 + collection.write_body_link_pose_to_sim_index( + body_poses=wp.from_torch(expected[0:1].contiguous(), dtype=wp.transformf), + env_ids=torch.tensor([0], dtype=torch.int32, device=device), + ) + wp.synchronize_device(device) + torch.testing.assert_close(poses(), expected, msg="by index") + + @dataclass class _RigidScene: """Cuboid pairs and collections that share one real OVPhysX lifecycle.""" @@ -422,6 +531,151 @@ def test_initialization_with_kinematic_enabled(scene: _RigidScene) -> None: torch.testing.assert_close(cube_object.data.root_com_vel_w.torch, default_root_vel) +@pytest.mark.parametrize("scene", _CUDA_SCENES, indirect=True) +@pytest.mark.parametrize( + "tensor_type", + [ + TT.RIGID_BODY_POSE, + TT.RIGID_BODY_VELOCITY, + TT.RIGID_BODY_ACCELERATION, + TT.LINK_POSE, + TT.LINK_VELOCITY, + ], +) +def test_session_reads_match_bindings(scene: _RigidScene, tensor_type: int) -> None: + """A session read fills ``read_into`` with the binding's values in the binding's row order.""" + for _ in range(3): + scene.sim.step() + # A collection reads LINK_* through its RIGID_BODY_* binding (one collection: they share the layout); the cuboid + # pairs read the rigid-body types. + served = {TT.LINK_POSE: TT.RIGID_BODY_POSE, TT.LINK_VELOCITY: TT.RIGID_BODY_VELOCITY}.get(tensor_type) + owners = (scene.fused,) if served else (scene.dynamic, scene.kinematic, scene.spinning) + for owner in owners: + view = owner.root_view + expected = binding_values(view, tensor_type) + replayed = wp.zeros_like(expected) + view.read_into(tensor_type, replayed) # captures the read + replayed.fill_(-1.0) + with replays_only(view, tensor_type): + view.read_into(tensor_type, replayed) + torch.testing.assert_close(wp.to_torch(replayed), wp.to_torch(expected), atol=0.0, rtol=0.0) + + +@pytest.mark.parametrize("scene", _CUDA_SCENES, indirect=True) +@pytest.mark.parametrize("tensor_type", [TT.RIGID_BODY_POSE, TT.RIGID_BODY_VELOCITY]) +def test_session_writes_match_bindings(scene: _RigidScene, tensor_type: int) -> None: + """A session write leaves the bodies as the binding write of the same values does, in the binding's row order: a + whole write, a replay after its source changes in place, a masked write, and its replay after the source and the + mask change in place. On one owner and type, as neither changes it: an indices write takes the binding, after the + session writes queued before it.""" + once = tensor_type == TT.RIGID_BODY_POSE + for owner in (scene.dynamic, scene.kinematic, scene.spinning, scene.fused): + view = owner.root_view + start = wp.clone(binding_values(view, tensor_type)) + rows = view.binding_for(tensor_type).shape[0] + shift = torch.zeros_like(wp.to_torch(start)) + shift.view(rows, -1)[:, :3] = torch.arange(1, rows + 1, device=shift.device).unsqueeze(1) * 0.01 + + def check(case: str, values: wp.array, **kwargs) -> None: + written, expected = session_and_binding_writes(view, tensor_type, start, values, **kwargs) + torch.testing.assert_close(written, expected, atol=1e-6, rtol=1e-6, msg=f"{view.prim_paths[0]}: {case}") + + source = wp.from_torch(wp.to_torch(start) + shift) + check("whole write", source) + wp.to_torch(source).add_(shift) + check("replay after the source changed", source, replay=True) + selected = wp.array([row == rows - 1 for row in range(rows)], dtype=wp.bool, device=start.device) + masked = wp.from_torch(wp.to_torch(start) + 3 * shift) + check("mask", masked, mask=selected) + wp.to_torch(masked).add_(shift) + wp.copy(selected, wp.array([row % 2 == 0 for row in range(rows)], dtype=wp.bool, device=start.device)) + check("replay after the source and the mask changed", masked, mask=selected, replay=True) + if once: + once = False + indices = wp.array([0], dtype=wp.int32, device=start.device) + written, expected = session_write_then_binding_indices(view, tensor_type, start, source, indices) + torch.testing.assert_close( + written, + expected, + atol=1e-6, + rtol=1e-6, + msg=f"{view.prim_paths[0]}: indices write after a session write", + ) + binding_write(view, tensor_type, start) + + +@pytest.mark.parametrize("scene", _CUDA_SCENES, indirect=True) +def test_session_replays_run_on_one_stream(scene: _RigidScene) -> None: + """Replays run on the stream of the first one, so work queued there after a read sees the values; a read or write + made on another stream raises instead of replaying where the next step would not wait for it.""" + view = scene.dynamic.root_view + expected = binding_values(view, TT.RIGID_BODY_POSE) + device = expected.device + replayed = wp.zeros_like(expected) + view.read_into(TT.RIGID_BODY_POSE, replayed) # captures the read + replayed.fill_(-1.0) + copied = wp.zeros_like(expected) + wp.synchronize_device(device) + stream = wp.get_stream(device) + view.read_into(TT.RIGID_BODY_POSE, replayed) + wp.copy(copied, replayed) # queued after the replay on the same stream + wp.synchronize_stream(stream) # only this stream: a replay elsewhere leaves the copy holding -1 + torch.testing.assert_close(wp.to_torch(copied), wp.to_torch(expected), atol=0.0, rtol=0.0) + poses = wp.clone(binding_values(view, TT.RIGID_BODY_POSE)) + view.set_attribute(TT.RIGID_BODY_POSE, poses) # captures the write + for other in (wp.Stream(device), wp.get_device(device).null_stream): + with wp.ScopedStream(other), pytest.raises(RuntimeError, match="replay on one stream"): + view.read_into(TT.RIGID_BODY_POSE, replayed) + with wp.ScopedStream(other), pytest.raises(RuntimeError, match="replay on one stream"): + view.set_attribute(TT.RIGID_BODY_POSE, poses) + + +@pytest.mark.parametrize("scene", _CUDA_SCENES, indirect=True) +def test_asset_writes_record_into_the_callers_graph(scene: _RigidScene) -> None: + """An asset's mask writes, made inside the caller's capture after a warmup call, are recorded into the caller's + graph: each replay writes the data its buffers then hold to the environments its masks then select, and leaves the + others' engine state as it was, even where the asset's buffers hold other values.""" + cubes, device = scene.dynamic, scene.device + view = cubes.root_view + start = {t: wp.clone(binding_values(view, t)) for t in (TT.RIGID_BODY_POSE, TT.RIGID_BODY_VELOCITY)} + poses = wp.clone(cubes.data.root_link_pose_w.warp) + velocities = wp.zeros(_NUM_CUBES, dtype=wp.spatial_vectorf, device=device) + selected = wp.array([False, True], dtype=wp.bool, device=device) + moving = wp.array([True, False], dtype=wp.bool, device=device) + + def write() -> None: + cubes.write_root_link_pose_to_sim_mask(root_pose=poses, env_mask=selected) + cubes.write_root_com_velocity_to_sim_mask(root_velocity=velocities, env_mask=moving) + + write() # the warmup writes outside any capture + stream = wp.Stream(device) + with wp.ScopedStream(stream), wp.ScopedCapture(device=device) as capture: + write() + # The replay reads the data and the selections in place: change all of them. + wp.to_torch(poses).view(-1, 7)[:, :3] += torch.tensor([0.1, 0.2, 0.3], device=device) + wp.copy(selected, wp.array([True, False], dtype=wp.bool, device=device)) + wp.copy(moving, wp.array([False, True], dtype=wp.bool, device=device)) + wp.to_torch(velocities).view(-1, 6).copy_(torch.arange(6 * _NUM_CUBES, device=device).view(-1, 6) * 0.1) + # Move every environment through the binding, so the asset's buffers no longer hold the engine's state there: + # an unselected environment must keep the state the binding set. + engine_poses = wp.to_torch(start[TT.RIGID_BODY_POSE]).clone().view(-1, 7) + engine_poses[:, :3] -= 0.05 + engine_velocities = torch.full((_NUM_CUBES, 6), -0.3, device=device) + binding_write(view, TT.RIGID_BODY_POSE, wp.from_torch(engine_poses.flatten().contiguous())) + binding_write(view, TT.RIGID_BODY_VELOCITY, wp.from_torch(engine_velocities.flatten().contiguous())) + expected_poses, expected_velocities = engine_poses.clone(), engine_velocities.clone() + expected_poses[0] = wp.to_torch(poses).view(-1, 7)[0] + expected_velocities[1] = wp.to_torch(velocities).view(-1, 6)[1] + wp.capture_launch(capture.graph, stream=stream) + wp.synchronize_stream(stream) + written_poses = wp.to_torch(binding_values(view, TT.RIGID_BODY_POSE)).view(-1, 7) + written_velocities = wp.to_torch(binding_values(view, TT.RIGID_BODY_VELOCITY)).view(-1, 6) + torch.testing.assert_close(written_poses, expected_poses, atol=1e-6, rtol=1e-6, msg="RIGID_BODY_POSE by mask") + torch.testing.assert_close(written_velocities, expected_velocities, msg="RIGID_BODY_VELOCITY by mask") + for tensor_type, values in start.items(): + binding_write(view, tensor_type, values) + + @pytest.mark.parametrize("scene", _CUDA_SCENES, indirect=True) def test_body_root_state_properties(scene: _RigidScene) -> None: """Test the root and body link and COM states of cubes spinning about an offset center of mass.""" @@ -600,6 +854,57 @@ def test_wrench_reaches_only_the_selected_collection_body(scene: _RigidScene) -> assert torch.count_nonzero(composer.composed_torque.torch) == 0 +@pytest.mark.parametrize("scene", test_devices(), indirect=True) +def test_collection_masked_writes_write_only_the_selected_bodies(scene: _RigidScene) -> None: + """A masked pose or velocity write of a collection writes the selected (environment, body) entries and leaves every + other body as it was, the unselected bodies of a selected environment included. On CUDA, a second write from new + values and masks in the same buffers replays the captured session write. A mask shorter than the environment or + body count is refused, whatever the data's shape.""" + collection, device = scene.fused, scene.device + view = collection.root_view + env_mask = wp.zeros(_NUM_ENVS, dtype=wp.bool, device=device) + body_mask = wp.zeros(_NUM_BODIES, dtype=wp.bool, device=device) + writes = ( + (TT.LINK_POSE, 7, wp.transformf, "write_body_link_pose_to_sim_mask", "body_poses"), + (TT.LINK_VELOCITY, 6, wp.spatial_vectorf, "write_body_com_velocity_to_sim_mask", "body_velocities"), + ) + for tensor_type, lanes, dtype, writer, argument in writes: + for case, (envs, bodies) in enumerate( + (([False, True], [True, False, True]), ([True, False], [False, True, True])) + ): + wp.copy(env_mask, wp.array(envs, dtype=wp.bool, device=device)) + wp.copy(body_mask, wp.array(bodies, dtype=wp.bool, device=device)) + # The fused binding is body-major; the public data is environment-major. + before = wp.to_torch(binding_values(view, tensor_type)).reshape(_NUM_BODIES, _NUM_ENVS, lanes) + before = before.transpose(0, 1).to(device) + values = before.clone() + values[..., :3] += 0.1 * (case + 1) + selected = torch.tensor(envs, device=device)[:, None] & torch.tensor(bodies, device=device)[None, :] + expected = torch.where(selected[..., None], values, before) + replay = device in _CUDA and case == 1 + with writes_replay_only(view, tensor_type) if replay else contextlib.nullcontext(): + getattr(collection, writer)( + **{argument: wp.from_torch(values.contiguous(), dtype=dtype)}, + env_mask=env_mask, + body_mask=body_mask, + ) + wp.synchronize_device(device) # the binding read below does not wait for the caller's stream + after = wp.to_torch(binding_values(view, tensor_type)).reshape(_NUM_BODIES, _NUM_ENVS, lanes) + torch.testing.assert_close(after.transpose(0, 1).to(device), expected, msg=f"{writer}, case {case}") + # A short mask, with full or equally short data, is refused before it leaves stale view-mask rows. + for rows in (_NUM_ENVS, _NUM_ENVS - 1): + with pytest.raises(ValueError, match="one entry per environment"): + collection.write_body_link_pose_to_sim_mask( + body_poses=wp.zeros((rows, _NUM_BODIES), dtype=wp.transformf, device=device), + env_mask=wp.array([True] * (_NUM_ENVS - 1), dtype=wp.bool, device=device), + ) + with pytest.raises(ValueError, match="one entry per body"): + collection.write_body_link_pose_to_sim_mask( + body_poses=wp.zeros((_NUM_ENVS, _NUM_BODIES - 1), dtype=wp.transformf, device=device), + body_mask=wp.array([True] * (_NUM_BODIES - 1), dtype=wp.bool, device=device), + ) + + @pytest.mark.parametrize("scene", _CUDA_SCENES, indirect=True) @pytest.mark.xfail( strict=True, 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..8552dd790857 100644 --- a/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py +++ b/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py @@ -18,6 +18,8 @@ import pytest +from pxr import Usd + from isaaclab.test.utils import DeviceScope, test_devices pytestmark = pytest.mark.ov @@ -252,7 +254,7 @@ def wait_task(self, task): manager_module.OvPhysxView, "_close_all_for", lambda value: events.append(("close_views", value)) ) manager.backend.stage = object() - manager.backend.rigid_body_view = SimpleNamespace(destroy=lambda: events.append("destroy_view")) + manager.backend.rigid_body_view = SimpleNamespace(close=lambda: events.append("destroy_view")) scene = manager.backend.scene = SimpleNamespace( stage=object(), ordinal=2, @@ -260,10 +262,12 @@ def wait_task(self, task): populate=lambda usda: events.append(("populate", usda)), ) stage = manager.backend.stage + usd_stage = Usd.Stage.CreateInMemory() with pytest.raises(RuntimeError, match="detach failed") if fails else nullcontext(): - manager.backend.load("#usda 1.0") + manager.backend.load(usd_stage) + usda = usd_stage.GetRootLayer().ExportToString() assert events == ["destroy_view", ("close_views", physx), "reset", ("wait", receipt)] + ( - [] if fails else ["destroy_stage", ("populate", "#usda 1.0"), ("attach", scene.stage, 1)] + [] if fails else ["destroy_stage", ("populate", usda), ("attach", scene.stage, 1)] ) + ([("wait", receipt)] if not fails else []) assert manager.backend.rigid_body_view is None assert manager.backend.stage is (stage if fails else scene.stage) @@ -879,7 +883,9 @@ def warmup(self): else: physx = FakePhysX() - backend = SimpleNamespace(physx=physx, stage=None, owns_scene=True, load=lambda usda, **kwargs: None) + backend = SimpleNamespace( + physx=physx, stage=None, owns_scene=True, load=lambda usda, **kwargs: None, captured_sessions=None + ) stage = Usd.Stage.CreateInMemory() UsdPhysics.Scene.Define(stage, "/World/PhysicsScene") sim = manager._sim @@ -894,7 +900,7 @@ def warmup(self): sim.get_or_create_backend = lambda cfg, *, scene: backend monkeypatch.setattr(manager, "_device", "cuda:0") monkeypatch.setattr(manager, "_clone_recipes", clones) - monkeypatch.setattr(manager_module, "_serialize_stage", lambda *args, **kwargs: ("#usda 1.0", clones)) + monkeypatch.setattr(manager_module, "_export_stage", lambda *args, **kwargs: (Usd.Stage.CreateInMemory(), clones)) monkeypatch.setattr( manager, "_scene_data_backend", SimpleNamespace(_defer_setup=lambda *args: events.append("defer_bindings")) ) @@ -942,7 +948,7 @@ def wait(task): backend.scene = SimpleNamespace(stage=object(), ordinal=2, populate=lambda usda: None) backend.physx = SimpleNamespace(attach_ovstage=attach, wait_task=wait) with pytest.raises(RuntimeError, match="attach failed") if fail else nullcontext(): - backend.load("#usda 1.0", disable_compiled_stage_cache=True) + backend.load(Usd.Stage.CreateInMemory(), disable_compiled_stage_cache=True) assert mode == CompiledStageCacheMode.READ_ONLY assert backend.stage is backend.scene.stage diff --git a/source/isaaclab_ov/test/physics/test_ovphysx_scene_data_backend.py b/source/isaaclab_ov/test/physics/test_ovphysx_scene_data_backend.py index 66bf1e9f1222..977adfea04e4 100644 --- a/source/isaaclab_ov/test/physics/test_ovphysx_scene_data_backend.py +++ b/source/isaaclab_ov/test/physics/test_ovphysx_scene_data_backend.py @@ -12,6 +12,8 @@ import pytest +from pxr import Usd + pytestmark = pytest.mark.ov # The OVPhysX runtime wheel is optional. Skip gracefully when it is not installed; @@ -29,6 +31,8 @@ def manager(monkeypatch): backend.stage = backend.scene = None backend.owns_scene = True backend.rigid_body_view = None + backend.captured_sessions = None + backend._device = "cpu" manager = OvPhysxManager(OvPhysxCfg()) manager.backend = backend manager._scene_data_backend = OvPhysxSceneDataBackend(manager) @@ -152,7 +156,7 @@ def test_transforms_finish_dirty_kinematics_before_native_reads(manager, monkeyp poses = wp.zeros(1, dtype=wp.transformf, device="cpu") backend._transforms.data.transforms = poses backend.backend = manager.backend - backend.backend.rigid_body_view = SimpleNamespace(read=lambda _: calls.append("read")) + backend.backend.rigid_body_view = SimpleNamespace(read_into=lambda _tt, _dst: calls.append("read")) sdp = SceneDataProvider(backend) monkeypatch.setattr(manager, "kinematics_dirty", True) sdp.get_transforms(SceneDataFormat.Transform()) @@ -226,20 +230,28 @@ def destroy(self): monkeypatch.setattr(stage_module, "create_ovstage", FakeStage) physx = FakePhysX() manager.backend.physx = physx - manager.backend.rigid_body_view = SimpleNamespace(destroy=lambda: events.append(("destroy_view",))) + manager.backend.rigid_body_view = SimpleNamespace(close=lambda: events.append(("destroy_view",))) monkeypatch.setattr(om_mod.OvPhysxView, "_close_all_for", lambda value: events.append(("close_views", value))) + usd_stage = Usd.Stage.CreateInMemory() if failure == "attach": with pytest.raises(RuntimeError, match=f"{failure} failed"): - manager.backend.load("#usda 1.0") + manager.backend.load(usd_stage) else: - manager.backend.load("#usda 1.0") + manager.backend.load(usd_stage) stage = stages[0] assert manager.backend.stage is stage manager.backend.close() manager.backend.close() assert events == [ ("stage", "isaaclab.scene"), - ("populate", stage, "#usda 1.0", 1, om_mod.ovstage.PopulationDomain.RENDERING, True), + ( + "populate", + stage, + usd_stage.GetRootLayer().ExportToString(), + 1, + om_mod.ovstage.PopulationDomain.RENDERING, + True, + ), ("seal", 1), ("attach", stage, 1), ("wait_task", attach_task), @@ -351,7 +363,7 @@ def fail_population(*args, **kwargs): monkeypatch.setattr(stage_module, "create_ovstage", FakeStage) with pytest.raises(RuntimeError, match="population failed"): - manager.backend.load("#usda 1.0") + manager.backend.load(Usd.Stage.CreateInMemory()) assert manager.backend.stage is None assert destroyed == ["isaaclab.scene"] @@ -598,9 +610,11 @@ def read(kind, fields): finally: active = False - def bind(*, prim_paths): + def bind(*, prim_paths, tensor_type): assert prim_paths == expected_paths - return SimpleNamespace(count=2, prim_paths=prim_paths) + return SimpleNamespace( + count=2, prim_paths=prim_paths, tensor_type=tensor_type, shape=(2, 7), destroy=lambda: None + ) runtime = SimpleNamespace(create_tensor_binding=bind, read_sync=read) native = SimpleNamespace(physx=runtime, rigid_body_view=None) @@ -625,11 +639,13 @@ def test_transforms_read_native_buffer_only_when_dirty(manager): paths = ["/World/envs/env_0/Cart", "/World/envs/env_1/Cart", "/World/envs/env_0/Pole"] reads = [] - def read(dst): + def read_into(_tensor_type, dst): reads.append(dst.ptr) dst.assign(expected) - native = SimpleNamespace(physx=None, rigid_body_view=SimpleNamespace(count=len(paths), prim_paths=paths, read=read)) + native = SimpleNamespace( + physx=None, rigid_body_view=SimpleNamespace(count=len(paths), prim_paths=paths, read_into=read_into) + ) backend = module.OvPhysxSceneDataBackend(manager) publication = backend.transforms @@ -668,12 +684,12 @@ def test_failed_rigid_read_is_retried(manager): from isaaclab.scene_data import SceneDataFormat, SceneDataProvider - def fail_read(dst): + def fail_read(_tensor_type, dst): raise RuntimeError("simulated read failure") backend = OvPhysxSceneDataBackend(manager) backend._transforms.data.transforms = wp.empty(1, dtype=wp.transformf, device="cpu") - backend.backend = SimpleNamespace(rigid_body_view=SimpleNamespace(read=fail_read)) + backend.backend = SimpleNamespace(rigid_body_view=SimpleNamespace(read_into=fail_read)) sdp = SceneDataProvider(backend) for _ in range(2): diff --git a/source/isaaclab_ov/test/sim/usd_export_read_import.py b/source/isaaclab_ov/test/sim/usd_export_read_import.py index 04de38629184..8285c80bf2e4 100644 --- a/source/isaaclab_ov/test/sim/usd_export_read_import.py +++ b/source/isaaclab_ov/test/sim/usd_export_read_import.py @@ -15,7 +15,7 @@ from isaaclab_ov import tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView -from pxr import Usd, UsdPhysics +from pxr import Sdf, Usd, UsdPhysics from isaaclab.test.utils.usd_export import articulation_scope @@ -30,7 +30,9 @@ def _import(source: str, device: str): OvPhysxManager._ensure_physx_schemas_registered() backend = OvPhysxBackend(OvPhysxBackendCfg(device=device)) try: - backend.load(source) + layer = Sdf.Layer.CreateAnonymous("import.usda") + assert layer.ImportFromString(source) + backend.load(Usd.Stage.Open(layer)) yield backend.physx finally: backend.close() diff --git a/source/isaaclab_ov/test/test_cloner.py b/source/isaaclab_ov/test/test_cloner.py index 9d8786960ff3..be5f3a77697a 100644 --- a/source/isaaclab_ov/test/test_cloner.py +++ b/source/isaaclab_ov/test/test_cloner.py @@ -11,7 +11,7 @@ import numpy as np import pytest from isaaclab_ov.cloner import OvPhysxReplicateContext, ovphysx_replicate -from isaaclab_ov.cloner.replicate import _serialize_stage +from isaaclab_ov.cloner.replicate import _export_stage from isaaclab_ov.physics import OvPhysxCfg from isaaclab_ov.physics.ovphysx_manager import OvPhysxManager @@ -90,11 +90,8 @@ def test_nested_clone_uses_final_target_pose(monkeypatch): if np.dot(orientation, expected_orientation) < 0.0: orientation = -orientation assert orientation.tolist() == pytest.approx(expected_orientation.tolist()) - layer = Sdf.Layer.CreateAnonymous("export.usda") - serialized, native = _serialize_stage(stage, manager._clone_recipes, full_stage=True) + exported, native = _export_stage(stage, manager._clone_recipes, full_stage=True) assert not native - layer.ImportFromString(serialized) - exported = Usd.Stage.Open(layer) target = exported.GetPrimAtPath(targets[1] + "/Body") actual = UsdGeom.XformCache().GetLocalToWorldTransform(target).ExtractTranslation() expected = _pose_matrix(expected_transform[:3], expected_transform[3:]).Transform(Gf.Vec3d(2, 0, 0)) @@ -120,9 +117,7 @@ def test_ovphysx_context_consumes_plan(): assert recipes[0][3] == [0, 1, 2] assert recipes[1][3] == [0, 1] before = stage.ExportToString() - serialized, _ = _serialize_stage(stage, recipes, full_stage=True, plan=plan) - exported = Usd.Stage.CreateInMemory() - exported.GetRootLayer().ImportFromString(serialized) + exported, _ = _export_stage(stage, recipes, full_stage=True, plan=plan) for env_id, position in enumerate(positions): root = exported.GetPrimAtPath(f"/World/envs/env_{env_id}/Robot") actual = UsdGeom.XformCache().GetLocalToWorldTransform(root).ExtractTranslation() @@ -202,7 +197,7 @@ def test_raw_replicate_preserves_source_only_geometry_variants(monkeypatch): assert [(source, targets, env_ids) for source, targets, _, env_ids, _ in recipes] == [ (f"/World/envs/env_{i}/Object", [f"/World/envs/env_{i}/Object"], [i]) for i in range(2) ] - assert not _serialize_stage(stage, recipes, full_stage=False)[1] + assert not _export_stage(stage, recipes, full_stage=False)[1] def test_raw_replicate_preserves_articulation_geometry_variants_and_env_ids(monkeypatch): @@ -326,12 +321,9 @@ def test_clone_export_preserves_sources_and_independent_assets(full_stage, env_t before = stage.GetRootLayer().ExportToString() for _ in range(2): - layer = Sdf.Layer.CreateAnonymous("export.usda") - serialized, native = _serialize_stage( + exported, native = _export_stage( stage, recipes, full_stage, plan, preserve_physics_ancestors=preserve_physics_ancestors ) - assert layer.ImportFromString(serialized) - exported = Usd.Stage.Open(layer) for env_id, variant in enumerate(("cube", "sphere")): prim = exported.GetPrimAtPath(object_paths[env_id]) assert prim.GetAttribute("test:variant").Get() == variant @@ -375,15 +367,13 @@ def test_clone_export_rechecks_physics_after_source_edits(): joint = UsdPhysics.FixedJoint.Define(stage, source + "/Joint") recipes = [(source, [source, target], [], [0, 1], 0)] with pytest.raises(ValueError, match="without rigid bodies or colliders"): - _serialize_stage(stage, recipes, full_stage=False) + _export_stage(stage, recipes, full_stage=False) body_path = source + "/Body" UsdPhysics.RigidBodyAPI.Apply(UsdGeom.Xform.Define(stage, body_path).GetPrim()) joint.CreateBody1Rel().SetTargets([body_path]) before = stage.GetRootLayer().ExportToString() - serialized, native = _serialize_stage(stage, recipes, full_stage=False) - exported = Usd.Stage.CreateInMemory() - assert exported.GetRootLayer().ImportFromString(serialized) + exported, native = _export_stage(stage, recipes, full_stage=False) assert exported.GetPrimAtPath(body_path).HasAPI(UsdPhysics.RigidBodyAPI) assert not exported.GetPrimAtPath(target) assert native == [(source, [target], [], [1], 0)] @@ -392,7 +382,7 @@ def test_clone_export_rechecks_physics_after_source_edits(): joint.GetBody1Rel().ClearTargets(True) stage.RemovePrim(body_path) with pytest.raises(ValueError, match="without rigid bodies or colliders"): - _serialize_stage(stage, recipes, full_stage=False) + _export_stage(stage, recipes, full_stage=False) def test_full_stage_export_preserves_nested_authored_opinions(): @@ -408,11 +398,8 @@ def test_full_stage_export_preserves_nested_authored_opinions(): ("/Source/Robot/Link", ["/Target/Robot/Link", "/Other/Nested/Robot/Link"], [], [1, 2], 0), ("/Source/Robot", ["/Target/Robot"], [], [1], 0), ] - layer = Sdf.Layer.CreateAnonymous("export.usda") - serialized, native = _serialize_stage(stage, recipes, full_stage=True) + exported, native = _export_stage(stage, recipes, full_stage=True) assert not native - assert layer.ImportFromString(serialized) - exported = Usd.Stage.Open(layer) assert exported.GetPrimAtPath("/Target/Robot").GetAttribute("test:physics").Get() assert exported.GetPrimAtPath("/Target/Robot").IsA(UsdGeom.Mesh) assert exported.GetPrimAtPath("/Target/Robot/Camera").IsA(UsdGeom.Camera) @@ -428,7 +415,7 @@ def test_native_clone_export_rejects_source_overlap(): stage.DefinePrim("/World/Source", "Xform") before = stage.GetRootLayer().ExportToString() with pytest.raises(ValueError, match="overlaps a clone source"): - _serialize_stage(stage, [("/World/Source", ["/World"], [], [0], 0)], full_stage=False) + _export_stage(stage, [("/World/Source", ["/World"], [], [0], 0)], full_stage=False) assert stage.GetRootLayer().ExportToString() == before @@ -460,12 +447,7 @@ def test_export_translates_legacy_joint_properties_without_editing_instances(): instance.GetReferences().AddInternalReference("/Robot") instance.SetInstanceable(True) before = stage.GetRootLayer().ExportToString() - serialized, _ = _serialize_stage( - stage, [], full_stage=True, friction_replacements={"Angular|Linear": (0.2, 0.1, 0.0)} - ) - layer = Sdf.Layer.CreateAnonymous() - layer.ImportFromString(serialized) - exported = Usd.Stage.Open(layer) + exported, _ = _export_stage(stage, [], full_stage=True, friction_replacements={"Angular|Linear": (0.2, 0.1, 0.0)}) for root in ("/Robot", "/Instance"): fixed = exported.GetPrimAtPath(f"{root}/Fixed") assert fixed.GetAttribute("physxJoint:maxJointVelocity").Get() == 100.0 @@ -513,5 +495,5 @@ def test_export_rejects_unrepresentable_legacy_joint_properties( replacements = {"Joint": (0.2, 0.1, 0.01)} before = stage.GetRootLayer().ExportToString() with pytest.raises(ValueError, match=f"{message}.*(/Robot/Joint)|(/Robot/Joint).*{message}"): - _serialize_stage(stage, [], full_stage=True, friction_replacements=replacements) + _export_stage(stage, [], full_stage=True, friction_replacements=replacements) assert stage.GetRootLayer().ExportToString() == before