Skip to content

[Fix] Create ContactSensor PhysX views per body so nested-hierarchy assets initialize - #6378

Merged
hujc7 merged 5 commits into
isaac-sim:developfrom
hujc7:jichuanh/contact-sensor-nested-view
Jul 16, 2026
Merged

hujc7 merged 5 commits into
isaac-sim:developfrom
hujc7:jichuanh/contact-sensor-nested-view

Conversation

@hujc7

@hujc7 hujc7 commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Description

ContactSensor initialization fails on assets whose rigid bodies are nested (child link prims authored under their parent link prim, as produced by the URDF importer in Isaac Sim 6.0 and later). The PhysX views were created from a single parent-level name alternation derived from the first matched body's parent:

bodies found (USD side):   .../Robot/pelvis
                           .../Robot/pelvis/left_hip
                           .../Robot/pelvis/left_hip/left_knee
pattern built (view side): .../Robot/(pelvis|left_hip|left_knee)   ← assumes one shared parent

Nested bodies do not share a parent, so the pattern matched only the first-level links and initialization raised Failed to initialize contact reporter for specified bodies.

Changes

The fix is two coupled changes — the second is a forced consequence of the first, not an independent choice:

  1. Create the views from one path expression per body (create_rigid_body_view / create_rigid_contact_view take a pattern list), reusing the per-body destination expressions that resolve_matching_prims_from_source already returns — the same approach as the ray caster and RigidObjectCollection. A single pattern cannot express nested bodies at all, so the list form is the only representation the view API offers for them. The list overload also requires filter_patterns as one filter list per sensor pattern; the sensor replicates its uniform filter list accordingly (per-body filter semantics are unchanged, filter_count stays the per-body count).
  2. Adapt all raw-view consumers to the resulting body-major row order. With a pattern list, the view enumerates matches grouped by pattern (row = body_id * num_envs + env_id) — the ordering is defined by the API's enumeration contract and is not selectable. The alternatives to adapting (permuting the flat arrays back to env-major on every simulation step, or expanding num_envs × num_bodies concrete paths to reconstruct env-major) add recurring hot-path or view-creation cost for no benefit, so the sensor adopts the same body-major convention RigidObjectCollection already documents. Every consumer of the raw flat data is updated: the three copy kernels, the body_names property (strides one path per body instead of slicing the first N), the debug-visualization pose fallback, and the raw-buffer indexing in the _test_friction_forces helper. Data buffers and the public data API keep their (num_envs, num_bodies, ...) layout — no user-facing change.

Also: the initialization error message now includes the actual view body counts to make future pattern mismatches diagnosable from logs.

Regression test

Authors a chain of kinematic rigid bodies with URDF-importer-style nested link prims directly under each environment prim (no scene/cloner — the code under test only needs the prims on the stage), creates a standalone ContactSensor over them, and asserts: initialization succeeds (pre-fix: deterministic RuntimeError), all bodies resolve with exact body_names order, and each (env, body) cell of data.pos_w matches that body's authored world position — pinning the row-to-cell mapping end-to-end. Parametrized over 1 and 6 environments on CPU and GPU.

Existing multi-env coverage (test_cube_stack_contact_filtering with 6 and 24 envs, and the task suites) exercises the ordering change on flat assets.

Fixes #5126

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with ./isaaclab.sh --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package (do not edit CHANGELOG.rst or bump extension.toml — CI handles that)
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

The PhysX rigid-body and contact views were created from a single
parent-level name alternation built from the first matched body's
parent. Bodies nested under other bodies (URDF importer output in
Isaac Sim 6.0+) do not share a parent, so sensor initialization
failed on such assets.

Create the views from one path expression per body, reusing the
per-body destination expressions that prim resolution already
returns. With a pattern list the views order bodies pattern-major
(body_id * num_envs + env_id), so the copy kernels and the debug
visualization switch from env-major to body-major indexing.
@github-actions github-actions Bot added the isaac-lab Related to Isaac Lab team label Jul 7, 2026
hujc7 added 2 commits July 7, 2026 01:26
CI on the previous commit surfaced three issues with the per-body
pattern lists:

- body_names sliced the first num_sensors view paths, which under
  body-major ordering repeats the first body across envs; stride by
  num_envs instead to pick one path per body.
- create_rigid_contact_view requires filter_patterns as one list per
  sensor pattern when given a pattern list; replicate the filter list
  accordingly.
- The Newton visualizer contact-arrow fallback reshaped raw view
  transforms env-major; reshape body-major and transpose.

Also run the nested-hierarchy test scene with replicate_physics
disabled (the chain is hand-authored USD, not a clonable referenced
asset) and include body counts in the initialization error message.
The nested-hierarchy regression test previously spawned its
hand-authored chain through InteractiveScene, but scene cloning
materializes environment copies backend-side from the env_0
prototype, which does not cover a hand-authored AssetBaseCfg asset;
at multiple envs the views saw only env_0's bodies.

Author the kinematic chain directly under each environment prim and
create the ContactSensor standalone: the code paths under test (prim
resolution, per-body view creation, body-major data kernels) only
depend on the prims existing on the stage. Validate per-body world
positions per env, which pins the (env, body) cell mapping exactly.
@hujc7
hujc7 marked this pull request as ready for review July 7, 2026 04:29
@greptile-apps

greptile-apps Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes ContactSensor initialization failures on assets with nested rigid-body hierarchies (as produced by the URDF importer in Isaac Sim 6.0+) by switching from a single parent-level glob alternation to one per-body path expression when creating PhysX views.

  • Core fix: create_rigid_body_view and create_rigid_contact_view now receive a list of per-body path globs instead of a single parent/(body_a|body_b|...) pattern, enabling bodies nested under other bodies to be addressed.
  • Ordering convention change: The list-based API produces body-major flat indexing (view_id = body_id * num_envs + env_id); all Warp kernels, the body_names property, debug-vis fallback, and the Newton visualizer are updated accordingly.
  • Test additions: A regression test for nested hierarchies (1 and 6 envs on CPU/GPU) plus a fix to the raw-buffer indexing in _test_friction_forces that was already wrong for any multi-body sensor.

Confidence Score: 4/5

The fix is well-scoped and consistent — per-body glob patterns, body-major kernel indexing, body_names stride, and Newton visualizer reshape are all coherent. The regression test covers nested hierarchies on CPU and GPU across 1 and 6 environments. The one unverified edge case is how the PhysX binding handles a list of empty filter sub-lists vs. a flat empty list for sensors with no contact filtering configured.

The indexing convention change (env-major to body-major) touches every data path in the sensor — kernels, debug-vis, and the Newton visualizer — and the PR keeps them consistent throughout. The _test_friction_forces raw-buffer indexing fix was independently correct. The only open question is the filter_patterns=[[], [], ...] vs. [] distinction for the no-filter case, which is a common code path that has not been explicitly validated.

contact_sensor.py around the create_rigid_contact_view call — specifically the filter_patterns construction when filter_prim_paths_expr is empty.

Important Files Changed

Filename Overview
source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py Core sensor logic: per-body glob list creation, body-major indexing in update kernels, body_names stride fix, and debug-vis reshape correction — all internally consistent; see filter_patterns note.
source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/kernels.py Warp kernels updated from env-major to body-major flat indexing (sensor * num_envs + env); parameter renames match the calling site.
source/isaaclab_physx/test/sensors/test_contact_sensor.py New regression test for nested hierarchy (validates initialization, body ordering, and pos_w through kernels); _test_friction_forces raw-buffer indexing corrected from env-major to body-major.
source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py Fallback contact-arrow origin reshape corrected from view(-1, num_bodies, 7) to view(num_bodies, -1, 7).transpose(0,1) to match body-major ordering.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant CS as ContactSensor._initialize_impl
    participant RMP as resolve_matching_prims_from_source
    participant PSV as PhysicsSimView
    participant BPV as body_physx_view (body-major)
    participant CV as contact_view (body-major)
    participant K as Warp Kernels

    CS->>RMP: parent_expr, has_contact_report callback
    RMP-->>CS: body_matches [(prim, expr), ...] per body
    CS->>CS: "body_path_globs = [expr.replace(".*","*") for _, expr in body_matches]"
    CS->>PSV: create_rigid_body_view(body_path_globs)
    PSV-->>CS: "BPV (count = num_bodies * num_envs, body-major)"
    CS->>PSV: "create_rigid_contact_view(body_path_globs, filter_patterns=[filters]*N)"
    PSV-->>CS: "CV (body-major: flat_idx = body_id*num_envs + env_id)"

    Note over CS,CV: View flat layout: [body0_env0, body0_env1,...,body1_env0,...]

    CS->>BPV: "get_transforms() - (B*N, 7) body-major"
    BPV-->>K: flat poses
    K->>K: "src_idx = sensor * num_envs + env"
    K-->>CS: dst_pos[env, sensor], dst_quat[env, sensor]

    CS->>CV: "get_net_contact_forces() - (B*N,) body-major"
    CV-->>K: net_forces_flat
    K->>K: "src_idx = sensor * num_envs + env"
    K-->>CS: net_forces_w[env, sensor]
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant CS as ContactSensor._initialize_impl
    participant RMP as resolve_matching_prims_from_source
    participant PSV as PhysicsSimView
    participant BPV as body_physx_view (body-major)
    participant CV as contact_view (body-major)
    participant K as Warp Kernels

    CS->>RMP: parent_expr, has_contact_report callback
    RMP-->>CS: body_matches [(prim, expr), ...] per body
    CS->>CS: "body_path_globs = [expr.replace(".*","*") for _, expr in body_matches]"
    CS->>PSV: create_rigid_body_view(body_path_globs)
    PSV-->>CS: "BPV (count = num_bodies * num_envs, body-major)"
    CS->>PSV: "create_rigid_contact_view(body_path_globs, filter_patterns=[filters]*N)"
    PSV-->>CS: "CV (body-major: flat_idx = body_id*num_envs + env_id)"

    Note over CS,CV: View flat layout: [body0_env0, body0_env1,...,body1_env0,...]

    CS->>BPV: "get_transforms() - (B*N, 7) body-major"
    BPV-->>K: flat poses
    K->>K: "src_idx = sensor * num_envs + env"
    K-->>CS: dst_pos[env, sensor], dst_quat[env, sensor]

    CS->>CV: "get_net_contact_forces() - (B*N,) body-major"
    CV-->>K: net_forces_flat
    K->>K: "src_idx = sensor * num_envs + env"
    K-->>CS: net_forces_w[env, sensor]
Loading

Reviews (1): Last reviewed commit: "Author nested-chain test prims per env w..." | Re-trigger Greptile

Comment on lines 326 to 329
self._contact_view = self._physics_sim_view.create_rigid_contact_view(
body_names_glob,
filter_patterns=filter_prim_paths_glob,
body_path_globs,
filter_patterns=[filter_prim_paths_glob] * len(body_path_globs),
max_contact_data_count=self.cfg.max_contact_data_count_per_prim * len(body_names) * self._num_envs,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 filter_patterns structure changes shape when no filter paths are configured

When cfg.filter_prim_paths_expr is empty, filter_prim_paths_glob is [], so filter_patterns becomes [[], [], ...] (one empty list per body) instead of the previous [] (a single flat empty list). If create_rigid_contact_view distinguishes between these two forms when processing a list-based pattern argument, sensors without any contact filter paths could behave differently than before. It's worth confirming the PhysX binding accepts a list of empty sub-lists as "no filter for each body" equivalently to a top-level empty list, or alternatively guard the construction: filter_patterns=[filter_prim_paths_glob] * len(body_path_globs) if filter_prim_paths_glob else [].

With no configured filters, replicating the empty list per sensor
pattern produced a list of empty lists where the API default is a
flat empty list. Both forms work, but the flat form matches the
documented default and avoids relying on tolerance of empty inner
lists.

@AntoineRichard AntoineRichard left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I don't see why we make some changes to the kernels to adress the nested hierarchy. I feel like this should only be a change on the regex side? Then if we want to process flat arrays that's a different story. But I don't see why that'd be necessary.

Comment on lines 385 to 509
@@ -389,7 +397,7 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None):
net_forces_flat,
force_matrix_flat,
env_mask,
self._num_sensors,
self._num_envs,
self._num_filter_shapes,
self._history_length,
self.cfg.force_threshold,
@@ -411,12 +419,12 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None):

# -- Pose --
if self.cfg.track_pose:
# PhysX returns (N*B, 7) float32 -> (N*B,) transformf
# PhysX returns (B*N, 7) float32 -> (B*N,) transformf, body-major
poses_flat = self.body_physx_view.get_transforms().view(wp.transformf)
wp.launch(
split_flat_pose_to_pos_quat,
dim=(self._num_envs, self._num_sensors),
inputs=[poses_flat, env_mask, self._num_sensors],
inputs=[poses_flat, env_mask, self._num_envs],
outputs=[self._data._pos_w, self._data._quat_w],
device=self.device,
)
@@ -436,7 +444,7 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None):
buffer_count,
buffer_start_indices,
env_mask,
self._num_sensors,
self._num_envs,
True,
float("nan"),
],
@@ -458,7 +466,7 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None):
buffer_count,
buffer_start_indices,
env_mask,
self._num_sensors,
self._num_envs,
False,
0.0,
],
@@ -493,9 +501,9 @@ def _debug_vis_callback(self, event):
if self.cfg.track_pose:
frame_origins = self._data.pos_w.torch # (N, B, 3)
else:
pose = self.body_physx_view.get_transforms() # (N*B, 7) float32
pose = self.body_physx_view.get_transforms() # (B*N, 7) float32, body-major
pose_torch = wp.to_torch(pose)
frame_origins = pose_torch.view(-1, self._num_sensors, 7)[:, :, :3]
frame_origins = pose_torch.view(self._num_sensors, -1, 7).transpose(0, 1)[:, :, :3]
# visualize
self.contact_visualizer.visualize(frame_origins.reshape(-1, 3), marker_indices=marker_indices.reshape(-1))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

These changes seem unrelated?

@hujc7 hujc7 Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

the main reason is that the shape/order of the array is changed if we call the API, create_rigid_contact_view, with array instead of a string. I tried to avoid it, let me confirm again.

Comment on lines 14 to 254
@@ -32,7 +35,7 @@ def split_flat_pose_to_pos_quat(
if not mask[env]:
return

src_idx = env * num_bodies + sensor
src_idx = sensor * num_envs + env
dst_pos[env, sensor] = wp.transform_get_translation(src[src_idx])
dst_quat[env, sensor] = wp.transform_get_rotation(src[src_idx])

@@ -46,7 +49,7 @@ def unpack_contact_buffer_data(
buffer_count: wp.array2d(dtype=wp.uint32),
buffer_start_indices: wp.array2d(dtype=wp.uint32),
mask: wp.array(dtype=wp.bool),
num_bodies: wp.int32,
num_envs: wp.int32,
avg: bool,
default_val: wp.float32,
dst: wp.array3d(dtype=wp.vec3f),
@@ -55,14 +58,15 @@ def unpack_contact_buffer_data(

Each thread handles one (body, filter) pair for one environment. It reads
`count` contact entries starting at `start_index` and either averages or
sums them.
sums them. The flat buffer dimension is body-major (view created from one
pattern per body): ``flat_idx = body_id * num_envs + env_id``.

Args:
contact_data: Flat buffer of contact data. Shape is (total_contacts,) vec3f.
buffer_count: Count of contacts per (env*body, filter). Shape is (N*B, M) uint32.
buffer_start_indices: Start indices per (env*body, filter). Shape is (N*B, M) uint32.
buffer_count: Count of contacts per (body*env, filter). Shape is (B*N, M) uint32.
buffer_start_indices: Start indices per (body*env, filter). Shape is (B*N, M) uint32.
mask: Boolean mask for which environments to update. Shape is (N,).
num_bodies: Number of bodies per environment.
num_envs: Number of environments.
avg: If True, average the data; if False, sum it.
default_val: Default value for groups with zero contacts (e.g. NaN or 0.0).
dst: Destination buffer. Shape is (N, B, M).
@@ -72,7 +76,7 @@ def unpack_contact_buffer_data(
if not mask[env]:
return

flat_idx = env * num_bodies + sensor
flat_idx = sensor * num_envs + env
count = wp.int32(buffer_count[flat_idx, contact])
start = wp.int32(buffer_start_indices[flat_idx, contact])

@@ -192,7 +196,7 @@ def update_net_forces_kernel(
net_forces_flat: wp.array(dtype=wp.vec3f),
net_forces_matrix_flat: wp.array2d(dtype=wp.vec3f),
mask: wp.array(dtype=wp.bool),
num_sensors: int,
num_envs: int,
num_filter_shapes: int,
history_length: int,
contact_force_threshold: wp.float32,
@@ -210,13 +214,14 @@ def update_net_forces_kernel(
):
"""Update the net forces, force matrix and air/contact time for each (env, sensor) pair.

Launch with dim=(num_envs, num_sensors).
Launch with dim=(num_envs, num_sensors). The flat arrays are body-major (view created
from one pattern per body): ``src_idx = sensor_id * num_envs + env_id``.

Args:
net_forces_flat: Flat net forces. Shape is (num_envs*num_sensors,).
net_forces_matrix_flat: Flat force matrix. Shape is (num_envs*num_sensors, num_filter_shapes).
net_forces_flat: Flat net forces. Shape is (num_sensors*num_envs,).
net_forces_matrix_flat: Flat force matrix. Shape is (num_sensors*num_envs, num_filter_shapes).
mask: Mask array. Shape is (num_envs,).
num_sensors: Number of sensors per environment.
num_envs: Number of environments.
num_filter_shapes: Number of filter shapes.
history_length: Length of history.
contact_force_threshold: Threshold for the contact force.
@@ -243,7 +248,7 @@ def update_net_forces_kernel(
if timestamp[env] == 0.0:
return

src_idx = env * num_sensors + sensor
src_idx = sensor * num_envs + env

# Update net forces
net_forces_w[env, sensor] = net_forces_flat[src_idx]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I don't see why we need to change these kernels?

…ensor-nested-view

# Conflicts:
#	source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py
hujc7 added a commit that referenced this pull request Jul 16, 2026
…-hierarchy assets initialize (#6384)

# Description

The OVPhysX `ContactSensor` fails to initialize on assets whose rigid
bodies are nested (child link prims authored under their parent link
prim, as produced by the URDF importer in Isaac Sim 6.0 and later). The
contact-binding sensor patterns were built from the first matched body's
parent plus leaf names:

```
bodies found (USD side):   .../Robot/pelvis
                           .../Robot/pelvis/left_hip
                           .../Robot/pelvis/left_hip/left_knee
patterns built:            .../Robot/pelvis        ← exists
                           .../Robot/left_hip      ← names a prim that does not exist
                           .../Robot/left_knee     ← names a prim that does not exist
```

Nested bodies do not share a parent, so the binding bound only the
first-level links and initialization raised `Failed to initialize
contact binding for specified bodies` (`sensor_count` not a multiple of
the resolved body count). This is the OVPhysX counterpart of #6378
(PhysX, fixes #5126); verified by reproducing the pattern construction
against a nested stage: 1/3 patterns name an existing prim before the
fix, 3/3 after.

## Changes

- Build each sensor pattern from that body's own resolved path
expression (the per-body destination expressions
`resolve_matching_prims_from_source` already returns) instead of a
shared parent plus leaf names.
- Unlike the PhysX fix, **no data-ordering changes are needed**: the
binding already received one pattern per body (pattern-major ordering
documented and tested in `test_multi_body_per_sensor_indexing`), and
`body_names` is stored from resolution rather than derived from view
paths. The single-body pose pattern reuses `sensor_patterns[0]`.
- Include the constructed patterns in the initialization error message.
- Regression test: kinematic chains with URDF-importer-style nested link
prims authored directly under each environment prim, standalone sensor,
asserting initialization succeeds (pre-fix: deterministic
`RuntimeError`), exact body resolution and order, and data shape — at 1
and 3 environments on CPU and GPU.

## Verification status

- **Root cause reproduced locally before fixing** (construction level):
on a nested stage, the shipped pattern construction yields 1/3 patterns
naming existing prims; the fixed construction yields 3/3.
- **Both failure modes derived from the binding validation arithmetic**:
a loud init `RuntimeError` when the body count does not divide the bound
sensor count, and a silent env-count misinference (corrupted data
shapes) when it does. The regression test is parametrized to catch both
(1 and 3 envs).
- **The `isaaclab_ovphysx` test suite does not execute on fork PRs**
(`USE_OVPHYSX_WHEELHOUSE` is gated to same-repo branches), so the
regression test in this PR runs on the first `develop` CI after merge
and in the nightly compatibility workflow. A maintainer can run it
pre-merge by pushing the branch to the upstream repo.

Related to #5126 and #6378.

## Type of change

- Bug fix (non-breaking change which fixes an issue)

## Checklist

- [x] I have read and understood the [contribution
guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html)
- [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with
`./isaaclab.sh --format`
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have added a changelog fragment under
`source/<pkg>/changelog.d/` for every touched package (do **not** edit
`CHANGELOG.rst` or bump `extension.toml` — CI handles that)
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there
@hujc7
hujc7 merged commit 234c8c0 into isaac-sim:develop Jul 16, 2026
67 of 69 checks passed
@github-project-automation github-project-automation Bot moved this from In review to Done in Isaac Lab Jul 16, 2026
matthewtrepte pushed a commit to matthewtrepte/IsaacLab that referenced this pull request Aug 4, 2026
…-hierarchy assets initialize (isaac-sim#6384)

# Description

The OVPhysX `ContactSensor` fails to initialize on assets whose rigid
bodies are nested (child link prims authored under their parent link
prim, as produced by the URDF importer in Isaac Sim 6.0 and later). The
contact-binding sensor patterns were built from the first matched body's
parent plus leaf names:

```
bodies found (USD side):   .../Robot/pelvis
                           .../Robot/pelvis/left_hip
                           .../Robot/pelvis/left_hip/left_knee
patterns built:            .../Robot/pelvis        ← exists
                           .../Robot/left_hip      ← names a prim that does not exist
                           .../Robot/left_knee     ← names a prim that does not exist
```

Nested bodies do not share a parent, so the binding bound only the
first-level links and initialization raised `Failed to initialize
contact binding for specified bodies` (`sensor_count` not a multiple of
the resolved body count). This is the OVPhysX counterpart of isaac-sim#6378
(PhysX, fixes isaac-sim#5126); verified by reproducing the pattern construction
against a nested stage: 1/3 patterns name an existing prim before the
fix, 3/3 after.

## Changes

- Build each sensor pattern from that body's own resolved path
expression (the per-body destination expressions
`resolve_matching_prims_from_source` already returns) instead of a
shared parent plus leaf names.
- Unlike the PhysX fix, **no data-ordering changes are needed**: the
binding already received one pattern per body (pattern-major ordering
documented and tested in `test_multi_body_per_sensor_indexing`), and
`body_names` is stored from resolution rather than derived from view
paths. The single-body pose pattern reuses `sensor_patterns[0]`.
- Include the constructed patterns in the initialization error message.
- Regression test: kinematic chains with URDF-importer-style nested link
prims authored directly under each environment prim, standalone sensor,
asserting initialization succeeds (pre-fix: deterministic
`RuntimeError`), exact body resolution and order, and data shape — at 1
and 3 environments on CPU and GPU.

## Verification status

- **Root cause reproduced locally before fixing** (construction level):
on a nested stage, the shipped pattern construction yields 1/3 patterns
naming existing prims; the fixed construction yields 3/3.
- **Both failure modes derived from the binding validation arithmetic**:
a loud init `RuntimeError` when the body count does not divide the bound
sensor count, and a silent env-count misinference (corrupted data
shapes) when it does. The regression test is parametrized to catch both
(1 and 3 envs).
- **The `isaaclab_ovphysx` test suite does not execute on fork PRs**
(`USE_OVPHYSX_WHEELHOUSE` is gated to same-repo branches), so the
regression test in this PR runs on the first `develop` CI after merge
and in the nightly compatibility workflow. A maintainer can run it
pre-merge by pushing the branch to the upstream repo.

Related to isaac-sim#5126 and isaac-sim#6378.

## Type of change

- Bug fix (non-breaking change which fixes an issue)

## Checklist

- [x] I have read and understood the [contribution
guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html)
- [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with
`./isaaclab.sh --format`
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have added a changelog fragment under
`source/<pkg>/changelog.d/` for every touched package (do **not** edit
`CHANGELOG.rst` or bump `extension.toml` — CI handles that)
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there
matthewtrepte pushed a commit to matthewtrepte/IsaacLab that referenced this pull request Aug 4, 2026
…ssets initialize (isaac-sim#6378)

# Description

`ContactSensor` initialization fails on assets whose rigid bodies are
nested (child link prims authored under their parent link prim, as
produced by the URDF importer in Isaac Sim 6.0 and later). The PhysX
views were created from a single parent-level name alternation derived
from the first matched body's parent:

```
bodies found (USD side):   .../Robot/pelvis
                           .../Robot/pelvis/left_hip
                           .../Robot/pelvis/left_hip/left_knee
pattern built (view side): .../Robot/(pelvis|left_hip|left_knee)   ← assumes one shared parent
```

Nested bodies do not share a parent, so the pattern matched only the
first-level links and initialization raised `Failed to initialize
contact reporter for specified bodies`.

## Changes

The fix is two coupled changes — the second is a forced consequence of
the first, not an independent choice:

1. **Create the views from one path expression per body**
(`create_rigid_body_view` / `create_rigid_contact_view` take a pattern
list), reusing the per-body destination expressions that
`resolve_matching_prims_from_source` already returns — the same approach
as the ray caster and `RigidObjectCollection`. A single pattern cannot
express nested bodies at all, so the list form is the only
representation the view API offers for them. The list overload also
requires `filter_patterns` as one filter list per sensor pattern; the
sensor replicates its uniform filter list accordingly (per-body filter
semantics are unchanged, `filter_count` stays the per-body count).
2. **Adapt all raw-view consumers to the resulting body-major row
order.** With a pattern list, the view enumerates matches grouped by
pattern (`row = body_id * num_envs + env_id`) — the ordering is defined
by the API's enumeration contract and is not selectable. The
alternatives to adapting (permuting the flat arrays back to env-major on
every simulation step, or expanding num_envs × num_bodies concrete paths
to reconstruct env-major) add recurring hot-path or view-creation cost
for no benefit, so the sensor adopts the same body-major convention
`RigidObjectCollection` already documents. Every consumer of the raw
flat data is updated: the three copy kernels, the `body_names` property
(strides one path per body instead of slicing the first N), the
debug-visualization pose fallback, and the raw-buffer indexing in the
`_test_friction_forces` helper. **Data buffers and the public `data` API
keep their `(num_envs, num_bodies, ...)` layout — no user-facing
change.**

Also: the initialization error message now includes the actual view body
counts to make future pattern mismatches diagnosable from logs.

## Regression test

Authors a chain of kinematic rigid bodies with URDF-importer-style
nested link prims directly under each environment prim (no scene/cloner
— the code under test only needs the prims on the stage), creates a
standalone `ContactSensor` over them, and asserts: initialization
succeeds (pre-fix: deterministic `RuntimeError`), all bodies resolve
with exact `body_names` order, and each `(env, body)` cell of
`data.pos_w` matches that body's authored world position — pinning the
row-to-cell mapping end-to-end. Parametrized over 1 and 6 environments
on CPU and GPU.

Existing multi-env coverage (`test_cube_stack_contact_filtering` with 6
and 24 envs, and the task suites) exercises the ordering change on flat
assets.

Fixes isaac-sim#5126

## Type of change

- Bug fix (non-breaking change which fixes an issue)

## Checklist

- [x] I have read and understood the [contribution
guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html)
- [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with
`./isaaclab.sh --format`
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have added a changelog fragment under
`source/<pkg>/changelog.d/` for every touched package (do **not** edit
`CHANGELOG.rst` or bump `extension.toml` — CI handles that)
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

isaac-lab Related to Isaac Lab team

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants