Skip to content

Decouple physics-engine event terms into per-backend modules - #5915

Closed
ooctipus wants to merge 3 commits into
isaac-sim:developfrom
ooctipus:zhengyuz/decouple-physics-events
Closed

ooctipus wants to merge 3 commits into
isaac-sim:developfrom
ooctipus:zhengyuz/decouple-physics-events

Conversation

@ooctipus

@ooctipus ooctipus commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Splits the physics-property randomization event terms out of isaaclab.envs.mdp.events into a new isaaclab.envs.mdp.physics_events module: randomize_rigid_body_material, randomize_rigid_body_scale, randomize_rigid_body_mass, randomize_rigid_body_inertia, randomize_rigid_body_com, randomize_rigid_body_collider_offsets, randomize_physics_scene_gravity, randomize_joint_parameters, randomize_fixed_tendon_parameters, randomize_actuator_gains (plus the shared randomize_prop_by_op / validate_scale_range helpers). events.py now only holds backend-agnostic terms (resets, force/velocity, visual material/color).
  • Relocates the backend-specific implementations into isaaclab_<backend>.envs.mdp.physics_events for PhysX, Newton, and OVPhysX. The core public terms resolve the active backend's implementation at runtime via a small private resolver, so isaaclab.envs.mdp.events/physics_events no longer import pxr or any backend.
  • OVPhysX reuses the PhysX implementations for every term except material randomization, which has a dedicated no-op (the OVPhysX material tensor binding is not yet available).
  • Deprecates randomize_rigid_body_scale: it remains PhysX-only (Newton raises NotImplementedError) and emits a DeprecationWarning recommending multi-asset spawning (MultiAssetSpawnerCfg).
  • New extension envs/mdp packages follow the lazy __init__.py + .pyi stub convention.

Test plan

  • ./isaaclab.sh -p -m pytest source/isaaclab_physx/test/assets/test_newton_actuators_physx.py
  • ./isaaclab.sh -p -m pytest source/isaaclab_newton/test/assets/test_newton_actuators_newton.py
  • Run an env that uses randomize_rigid_body_material / randomize_joint_parameters on both the PhysX and Newton backends and confirm parity with the previous behavior.
  • Confirm randomize_rigid_body_scale raises on Newton and warns (deprecated) on PhysX.

Note: changelog fragments are not yet included; happy to add per-package fragments if desired.

@github-actions github-actions Bot added the isaac-lab Related to Isaac Lab team label Jun 2, 2026

@isaaclab-review-bot isaaclab-review-bot Bot left a comment •

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.

Incremental Update for 31b1948c (Force-push / Rebase)

The PR was force-pushed, rebasing commits to clean up history. Current state: 2 commits.

Commits Reviewed

SHA Message
dc9068665e0f split events
31b1948c42a3 Fix backend physics event exports

Changes vs. Previous Review

The functional content is identical to what was previously reviewed at 1f747b44. The force-push consolidated commits but made no substantive code changes.

✅ Bug Fixes Confirmed (Still Present)

  1. PhysX gravity distribution — self._distribution is used instead of hardcoded "uniform" ✅
  2. Newton collider offset statefulness — Local margin_for_gap variable prevents baseline corruption ✅
  3. Backend module exports — lazy_export() + .pyi stubs properly expose physics event classes ✅

Import Order Change (Newton)

The Newton physics_events.py has an import reordering:

# Before
from isaaclab.envs.mdp.physics_events import ...
from isaaclab_newton.assets import ...
from isaaclab_newton.physics.newton_manager import ...

# After  
from isaaclab_newton.assets import ...
from isaaclab_newton.physics.newton_manager import ...
from isaaclab.envs.mdp.physics_events import ...

This is a style-only change (groups isaaclab_newton imports before isaaclab imports). No functional impact.

Verdict

✅ LGTM — The rebased commits contain the same fixes from the previous review. No new issues introduced.


Previous review covered: Import resolution, collider offset statefulness fix, gravity distribution fix. All still present in rebased commits.

@greptile-apps

greptile-apps Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR decouples physics-engine-specific event terms from the generic isaaclab.envs.mdp.events module by introducing a new physics_events.py in the core package plus per-backend implementations under isaaclab_physx, isaaclab_newton, and isaaclab_ovphysx. A small runtime resolver (_resolve_backend_event) dispatches to the correct backend at construction time, eliminating pxr/warp imports from the public surface.

  • Backend-agnostic terms (resets, external forces, visual material) remain in events.py; all physics-property randomization terms move to physics_events.py with delegation to per-backend classes.
  • randomize_rigid_body_scale is deprecated and raises NotImplementedError on Newton; OVPhysX reuses PhysX implementations except for material randomization (documented no-op).
  • Backend modules adopt a lazy __init__.py + .pyi stub convention consistent with the rest of the codebase.

Confidence Score: 3/5

Two real behavioral defects need fixing: gravity randomization on PhysX silently falls back to uniform regardless of configuration, and the Newton collider-offset implementation permanently overwrites stored defaults on each call.

The PhysX gravity implementation hardcodes distribution='uniform' inside randomize_prop_by_op, discarding any configured distribution. Newton's RandomizeRigidBodyColliderOffsets mutates self.default_margin in-place, making repeated resets over disjoint env_ids subsets accumulate drift.

source/isaaclab_physx/isaaclab_physx/envs/mdp/physics_events.py (gravity distribution) and source/isaaclab_newton/isaaclab_newton/envs/mdp/physics_events.py (collider default margin mutation)

Important Files Changed

Filename Overview
source/isaaclab/isaaclab/envs/mdp/physics_events.py New public module with backend-agnostic wrappers delegating via _resolve_backend_event; confusing deprecation+error ordering for randomize_rigid_body_scale on Newton.
source/isaaclab_physx/isaaclab_physx/envs/mdp/physics_events.py PhysX backend implementations; RandomizePhysicsSceneGravity hardcodes distribution="uniform", silently ignoring any user-configured distribution.
source/isaaclab_newton/isaaclab_newton/envs/mdp/physics_events.py Newton backend implementations; RandomizeRigidBodyColliderOffsets mutates self.default_margin on every call, diverging from original defaults across resets.
source/isaaclab_ovphysx/isaaclab_ovphysx/envs/mdp/physics_events.py OVPhysX no-op for material randomization with a clear warning; all other terms fall through to PhysX backend.
source/isaaclab/isaaclab/envs/mdp/events.py Physics-property randomization moved to physics_events.py; now holds only backend-agnostic resets and visual-material terms.
source/isaaclab/isaaclab/envs/mdp/init.pyi Stub updated to re-export physics terms from physics_events and visual/reset terms from events; split looks correct.
source/isaaclab_ovphysx/isaaclab_ovphysx/envs/mdp/init.py Stale _EventTermFactory reference in docstring; the actual router is _resolve_backend_event.

Reviews (1): Last reviewed commit: "Decouple physics-engine event terms into..." | Re-trigger Greptile

Comment on lines +265 to +274
gravity = randomize_prop_by_op(
gravity,
(self._dist_param_0.cpu(), self._dist_param_1.cpu()),
None,
slice(None),
operation=operation,
distribution="uniform",
)
gravity = gravity[0].tolist()
self._physics_sim_view.set_gravity(self._carb.Float3(*gravity))

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.

P1 Distribution parameter silently ignored on PhysX

randomize_prop_by_op is called with a hardcoded distribution="uniform", so any value configured in cfg.params["distribution"] (e.g. "log_uniform" or "gaussian") is silently discarded. Newton's RandomizePhysicsSceneGravity.__init__ correctly caches the configured distribution function in self._dist_fn, but the PhysX implementation never stores it. A user who sets distribution="gaussian" on PhysX will silently get uniform sampling with no error or warning.

Comment on lines +158 to +160
)
self.default_margin[env_ids] = margin[env_ids]
margin_view[env_ids] = margin[env_ids]

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.

P1 default_margin mutated across calls, diverging from original defaults

self.default_margin[env_ids] = margin[env_ids] permanently overwrites the stored defaults. On the next reset for a different env_ids subset, those environments' default margin is the previously randomized value rather than the original scene default. The PhysX counterpart always clones from self.default_rest_offsets (never mutated). Because the operation is currently hardcoded to "abs" the mutation does not affect output values today, but would silently break if "add" or "scale" support is added.

Comment on lines +11 to +13
OVPhysX reuses the PhysX implementations for most event terms (see the ``ovphysx -> physx``
fallback in :class:`~isaaclab.envs.mdp.physics_events._EventTermFactory`); only terms that need a
different OVPhysX behavior are defined here.

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 The docstring references _EventTermFactory, a class that does not exist in the codebase. The runtime routing is the module-level function _resolve_backend_event in isaaclab.envs.mdp.physics_events.

Suggested change
OVPhysX reuses the PhysX implementations for most event terms (see the ``ovphysx -> physx``
fallback in :class:`~isaaclab.envs.mdp.physics_events._EventTermFactory`); only terms that need a
different OVPhysX behavior are defined here.
OVPhysX reuses the PhysX implementations for most event terms (see the ``ovphysx -> physx``
fallback in :func:`~isaaclab.envs.mdp.physics_events._resolve_backend_event`); only terms that need a
different OVPhysX behavior are defined here.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +116 to +124
warnings.warn(
"'randomize_rigid_body_scale' is deprecated and only supported on the PhysX backend. Prefer"
" multi-asset spawning (see :class:`~isaaclab.sim.MultiAssetSpawnerCfg`) with per-scale USD"
" variants instead.",
DeprecationWarning,
stacklevel=2,
)
# the USD scale authoring is backend-specific; resolve the active backend's implementation
_resolve_backend_event("RandomizeRigidBodyScale")(env, env_ids, scale_range, asset_cfg, relative_child_path)

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 Confusing warning/error ordering for Newton users

On Newton, randomize_rigid_body_scale first emits a DeprecationWarning saying the function is "only supported on the PhysX backend", then immediately raises NotImplementedError. Users on Newton see the deprecation first, implying it could work if they switch backends, before hitting an uncaught error. The Newton path should skip the PhysX-flavored deprecation warning and raise NotImplementedError directly.

@ooctipus
ooctipus force-pushed the zhengyuz/decouple-physics-events branch 5 times, most recently from 1f45c56 to ce76b25 Compare June 3, 2026 08:48
@ooctipus
ooctipus force-pushed the zhengyuz/decouple-physics-events branch from 1f747b4 to 31b1948 Compare June 5, 2026 03:02

@hujc7 hujc7 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 am wondering how much work or if it would be possible to unify at backend level for the mdps needing specific implementation. If there's behavior difference, I think it could be explained in mdp description?

@@ -0,0 +1,989 @@
# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).

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.

Is the rename better? following the existing convention, I think a events folder needs to be created within with it's can be more granularly structured.

return impl_cls(*args, **kwargs)


def randomize_rigid_body_scale(

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.

does not seem to use backend specific impl.

)

# construct the backend-specific implementation via the converter
self._impl = _resolve_backend_event("RandomizeRigidBodyMaterial", cfg, env, self.asset, self.asset_cfg)

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.

Why do we need a resolve_backend_event? Couldn't users just pick the event from the backend they want? I.e. we no longer keep this in IsaacLab and we leave it to the users to pick the right event. THis could make sense since these terms may not have the same contracts / definitions depending on the backend and trying to unify them may be more work than what it's worth?

@StafaH
StafaH requested a review from a team September 25, 2026 20:28
StafaH added a commit that referenced this pull request Sep 27, 2026
## Description

Move backend-specific MDP event implementations into backend
`envs/mdp/events.py` modules. Tasks keep using the shared
`isaaclab.envs.mdp` terms and existing parameters.

Alternative prototype for #5915.

### Routing

| Terms | Implementation selection |
| --- | --- |
| Physics materials, collider offsets, gravity | Resolved
`SimulationCfg.physics` type: `NewtonCfg`, `OvPhysxCfg`, or `PhysxCfg` |
| Replicator color and texture | Kit runtime, independently of physics;
kitless construction reports the requirement |
| Per-shape visual channels | Existing renderer/visualizer selection |
| Visual material channels | Existing `RenderContext` API |
| Actuator gains | Existing actuator-owner APIs; Newton controllers can
also run under PhysX |
| Mass, inertia, COM, joints, tendons, resets, wrenches, observations,
rewards, terminations, actions | Existing shared asset and sensor APIs |
| Rigid-body scale | Shared USD stage before simulation starts |

`SimulationContext` and `BackendCfg` retain resource ownership. Physics
dispatch happens once at term construction and supports resolved
`PhysxAutoCfg`. No manager-name matching or new physics-manager factory
hooks were added.

Public parameters, defaults, sampling behavior, and the Replicator
terms' material/RNG attributes are preserved. PhysX gravity now passes a
plain vector to `set_gravity`; `carb.Float3` is unnecessary. Unsupported
backend/runtime combinations fail at construction. No new dependencies.

## Tests and validation

Backend event tests live in their owning packages and call the shared
`isaaclab.envs.mdp` API. The latest follow-up replaced custom fake
assets, views, managers, scenes, and writers with real native classes.
Small local USD scenes are shared across related tests; no asset
download is needed for the new physics event fixtures. Runtime device
masks select the devices through `test_devices`; the analytic
observation test covers CPU and CUDA.

Core retains construction-error checks and an independent analytic
gravity observation check using real `ProxyArray` buffers. Small
namespace containers remain for those inputs and for OV's event context;
they contain no backend implementation. The Newton visual rebind test
swaps a real model with a copy owning new color storage and uses the
original writer.

| Owner | Coverage |
| --- | --- |
| PhysX | Default/reordered bodies with unequal shape counts,
integer/slice selectors, native material consistency and collider
writes, Gaussian gravity verified through acceleration, native
fixed-tendon writes, Replicator texture/color |
| Newton | Body/shape mapping, collider margin/gap translation and
clamping, gravity selectors/global-world isolation, repeated add/scale
and mutable bounds, native joint friction/damping, actual visual writer
and model rebinding |
| Kamino | Real initialized solver and native model; original material
groups survive repeated randomization and propagate across worlds |
| OVPhysX | Reordered body subsets, empty/permuted full selections,
native material/collider bindings, real visual-material buffers and
RenderContext slice writes, Gaussian gravity verified through physical
velocity |

24 focused cases passed in this follow-up: core 7, Newton 7, PhysX 6,
OVPhysX 4. The physics event files took approximately 7.18s (PhysX),
6.38s (Newton including Kamino), and 4.40s (OVPhysX) in warm runs.
Newton's previous mock files took 3.20s; the native suite also absorbs
the former core joint test. Texture/color tests passed in 11.34s with
two environments instead of sixteen.

Mutation checks detected broken body mappings, gravity writes/global-row
selection, collider clamping, tendon flushing, viscous friction, visual
selection/rebinding, and persistent Kamino grouping. A separate
Kamino-only mutation confirmed grouping coverage independently of body
mapping. All mutations were restored.

The latest follow-up changes only tests (619 added / 838 removed lines,
including relocations). Formatting, lint, and changelog checks passed.
Documentation was unchanged in the test follow-ups; its build passed in
the earlier implementation commit. Existing backend asset integration
coverage remains, except the newly added PhysX event snippets that were
consolidated into the native event fixture.

The kitless-runtime regression previously failed against the preceding
implementation and passed with the explicit runtime check. All 35
existing public parameter lists/defaults in core `events.py` were
compared with the preceding implementation; other shared term
implementations are unchanged.

Full training and a Kamino rollout were not run. A Newton-plus-Kit
texture environment probe stopped before event execution: disabling
physics replication left Newton without a model builder. This
scene-construction limit is unchanged.

## Type of change

- Refactor preserving supported public behavior
- Documentation update

## Release backport

- [x] Backport this pull request to the active release branch after it
merges into `develop`

## Checklist

- [x] I have read and understood the contribution guidelines
- [x] I have run the pre-commit checks with `uv run isaaclab -f`
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my feature works
- [x] I have added a changelog fragment for every touched source package
- [x] My name already exists in `CONTRIBUTORS.md`
@StafaH

StafaH commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

Closing this as it was superceded by #8067

@StafaH StafaH closed this Sep 27, 2026
@ooctipus
ooctipus deleted the zhengyuz/decouple-physics-events branch October 14, 2026 14:28
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

None yet

Development

Successfully merging this pull request may close these issues.

4 participants