From 5f8359a7f5c29ad7b4974c4521fb32736960126c Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Wed, 25 Nov 2026 14:11:30 -0800 Subject: [PATCH 1/8] Remove deprecated OVRTX scene APIs in favor of OvStage --- .github/PULL_REQUEST_TEMPLATE.md | 4 +- .../actions/_lib/test_performance_workflow.py | 22 +- .github/test-subsets/postmerge-rendering.toml | 12 - .github/workflows/arm-ci.yml | 2 - .github/workflows/build.yaml | 12 +- docs/source/api/lab_ov/isaaclab_ov.cloner.rst | 19 +- docs/source/concepts/renderers.rst | 52 +- docs/source/concepts/sensors/camera.rst | 5 +- .../benchmarking/run_benchmarks.rst | 20 +- .../cartpole/newton-ovrtx-async-rgb.png | 3 - .../cartpole/ovphysx-ovrtx-async-rgb.png | 3 - .../test/rendering/rendering_cases.py | 14 +- .../test/rendering/rendering_runner.py | 3 +- .../rendering/test_rendering_architecture.py | 4 +- .../changelog.d/ovstage-only.changed.rst | 5 + .../changelog.d/ovstage-only.major | 0 .../isaaclab_ov/cloner/__init__.py | 2 - .../isaaclab_ov/cloner/replicate.py | 87 +- .../isaaclab_ov/renderers/ovrtx_renderer.py | 1010 +++++------------ .../renderers/ovrtx_renderer_cfg.py | 12 +- .../isaaclab_ov/renderers/visual_materials.py | 65 +- .../isaaclab_ov/test/test_ovrtx_clone_plan.py | 168 ++- .../test/test_ovrtx_deformable_bindings.py | 165 +-- .../test/test_ovrtx_renderer_contract.py | 997 ++++++---------- .../test/test_ovrtx_visual_material_sync.py | 115 +- .../changelog.d/ovstage-only.changed.rst | 1 + .../contrib/rizon_sharpa_coffee/rendering.py | 39 +- .../changelog.d/ovstage-only.skip | 0 .../test/test_ovxr_renderer.py | 2 +- .../changelog.d/ovstage-only.changed.rst | 1 + .../newton/newton_rtx_appearance.py | 51 +- .../test/test_newton_rtx_appearance.py | 48 +- 32 files changed, 956 insertions(+), 1987 deletions(-) delete mode 100644 source/_isaaclab_testing/test/rendering/golden_images/renderers/cartpole/newton-ovrtx-async-rgb.png delete mode 100644 source/_isaaclab_testing/test/rendering/golden_images/renderers/cartpole/ovphysx-ovrtx-async-rgb.png create mode 100644 source/isaaclab_ov/changelog.d/ovstage-only.changed.rst create mode 100644 source/isaaclab_ov/changelog.d/ovstage-only.major create mode 100644 source/isaaclab_tasks/changelog.d/ovstage-only.changed.rst create mode 100644 source/isaaclab_teleop/changelog.d/ovstage-only.skip create mode 100644 source/isaaclab_visualizers/changelog.d/ovstage-only.changed.rst diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index a461be2a1ded..edc80a726d0a 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -47,8 +47,8 @@ To upload images to a PR -- simply drag and drop an image while in edit mode and ## Checklist Docker and GPU tests run on demand. Push the commits you want tested, then -comment `run-ci` on the pull request, or `run-ci ovstage` to include kitless OVStage rendering tests for that run. -Subsequent pushes and plain `run-ci` comments do not run OVStage tests unless you comment `run-ci ovstage` again. +comment `run-ci` on the pull request. Kitless OvStage rendering tests run with every activated build. +The `run-ci ovstage` command remains an alias for existing workflows. - [ ] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [ ] I have run the [`pre-commit` checks](https://pre-commit.com/) with `uv run isaaclab --format` diff --git a/.github/actions/_lib/test_performance_workflow.py b/.github/actions/_lib/test_performance_workflow.py index 8d033714624b..4652748b33c0 100644 --- a/.github/actions/_lib/test_performance_workflow.py +++ b/.github/actions/_lib/test_performance_workflow.py @@ -33,14 +33,14 @@ def test_ci_activation_and_runner_selection() -> None: paginated = [[{"event": "commented"}], [{"event": "labeled", "actor": None}, _labeled("isaaclab-bot[bot]")]] ignored = [[_labeled("github-actions[bot]"), {"event": "commented", "actor": {"login": "human"}}]] cases = [ - ("push", "push", "", "", [], True, True, False, True), - ("actions bot", "pull_request", "synchronize", "", ignored, False, False, True, False), - ("removed human label", "pull_request", "synchronize", "", [removed_label], False, True, True, False), - ("paginated bot label", "pull_request", "synchronize", "", paginated, False, True, True, False), - ("API error", "pull_request", "synchronize", "", [], True, False, True, False), - ("explicit rerun", "pull_request", "labeled", "ci:run-docker", [], True, True, True, False), - ("ovstage rerun", "pull_request", "labeled", "ci:run-ovstage", [], True, True, True, True), - ("other label", "pull_request", "labeled", "triage", [], True, True, False, False), + ("push", "push", "", "", [], True, True, False), + ("actions bot", "pull_request", "synchronize", "", ignored, False, False, True), + ("removed human label", "pull_request", "synchronize", "", [removed_label], False, True, True), + ("paginated bot label", "pull_request", "synchronize", "", paginated, False, True, True), + ("API error", "pull_request", "synchronize", "", [], True, False, True), + ("explicit rerun", "pull_request", "labeled", "ci:run-docker", [], True, True, True), + ("ovstage rerun", "pull_request", "labeled", "ci:run-ovstage", [], True, True, True), + ("other label", "pull_request", "labeled", "triage", [], True, True, False), ] data = { "script": activation["with"]["script"], @@ -58,7 +58,7 @@ def test_ci_activation_and_runner_selection() -> None: const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor; (async () => { for (const row of input.cases) { - const [name, eventName, action, label, pages, error, activated, expectedCancel, expectedOvstage] = row; + const [name, eventName, action, label, pages, error, activated, expectedCancel] = row; const outputs = {}; const context = {eventName, payload: {action, pull_request: {number: 42}, label: {name: label}}, repo: {owner: 'owner', repo: 'lab'}}; @@ -84,8 +84,10 @@ def test_ci_activation_and_runner_selection() -> None: evaluate(input.ovstage), ], [activated ? ['self-hosted', 'gpu'] : ['ubuntu-latest'], - activated, !activated, expectedCancel, expectedOvstage], + activated, !activated, expectedCancel, true], name); + needs.build.result = 'failure'; + assert.equal(evaluate(input.ovstage), false, name + ': failed build'); } })(); """ diff --git a/.github/test-subsets/postmerge-rendering.toml b/.github/test-subsets/postmerge-rendering.toml index 4d61b7f5c302..84e4da072680 100644 --- a/.github/test-subsets/postmerge-rendering.toml +++ b/.github/test-subsets/postmerge-rendering.toml @@ -14,14 +14,7 @@ rendering-correctness = [ rendering-correctness-kitless-legacy = [ "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_newton_warp.py::test_rendering[legacy-cartpole-newton-newton_warp]", "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_newton_warp.py::test_rendering_optix[legacy-rendering_scene-newton-newton_warp]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-cartpole-newton-ovrtx]", "source/_isaaclab_testing/test/rendering/test_rendering_kitless_ovphysx_newton_warp.py::test_rendering[legacy-cartpole-ovphysx-newton_warp]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_ovphysx_ovrtx.py::test_rendering[legacy-cartpole-ovphysx-ovrtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-franka_cloth-newton-ovrtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-franka_soft-newton-ovrtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-franka_cable-newton-ovrtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-cartpole-newton-ovrtx-async]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_ovphysx_ovrtx.py::test_rendering[legacy-cartpole-ovphysx-ovrtx-async]", ] rendering-correctness-kitless-ovstage = [ @@ -40,11 +33,6 @@ rendering-correctness-kitless-ovstage = [ ovrtx-cache-warm = [ "source/_isaaclab_testing/test/rendering/test_rendering_kit.py::test_rendering[rendering_scene-newton-isaac_rtx]", "source/_isaaclab_testing/test/rendering/test_rendering_kit.py::test_rendering[rendering_scene-physx-isaac_rtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-cartpole-newton-ovrtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_ovphysx_ovrtx.py::test_rendering[legacy-cartpole-ovphysx-ovrtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-franka_cloth-newton-ovrtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-franka_soft-newton-ovrtx]", - "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[legacy-franka_cable-newton-ovrtx]", "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[ovstage-cartpole-newton-ovrtx]", "source/_isaaclab_testing/test/rendering/test_rendering_kitless_ovphysx_ovrtx.py::test_rendering[ovstage-cartpole-ovphysx-ovrtx]", "source/_isaaclab_testing/test/rendering/test_rendering_kitless_newton_ovrtx.py::test_rendering[ovstage-franka_cloth-newton-ovrtx]", diff --git a/.github/workflows/arm-ci.yml b/.github/workflows/arm-ci.yml index e63c104de9a1..e14c2d18f825 100644 --- a/.github/workflows/arm-ci.yml +++ b/.github/workflows/arm-ci.yml @@ -187,8 +187,6 @@ jobs: isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} ci-marker: arm_ci - # ovstage rendering cases are post-merge only on x86 as well. - test-k-expr: not ovstage test-jobs: "4" extra-pip-packages: "${{ steps.ov_pins.outputs.ovrtx }} ${{ steps.ov_pins.outputs.ovphysx }}" warp-cache: ${{ github.event_name == 'push' && 'save' || 'restore' }} diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index d9ef1a0ccc54..d3705af1179e 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -899,7 +899,7 @@ jobs: container-name: isaac-lab-rendering-correctness-test omni-github-test-type: rendering-correctness - # Separate jobs preserve the required legacy check name when skipped and let ovstage use its own trigger. + # Keep the existing required Newton-Warp check name; OVRTX runs in the OvStage job below. test-rendering-correctness-kitless-legacy: name: "rendering-correctness-kitless (legacy)" runs-on: [self-hosted, gpu] @@ -933,9 +933,7 @@ jobs: wheelhouse-packages: ${{ env.USE_OVPHYSX_WHEELHOUSE == 'true' && 'ovphysx' || '' }} include-files: >- test_rendering_kitless_newton_newton_warp.py, - test_rendering_kitless_newton_ovrtx.py, - test_rendering_kitless_ovphysx_newton_warp.py, - test_rendering_kitless_ovphysx_ovrtx.py + test_rendering_kitless_ovphysx_newton_warp.py test-k-expr: legacy test-node-ids-file: ${{ github.event_name == 'push' && '.github/test-subsets/postmerge-rendering.toml' || '' }} test-node-ids-key: ${{ github.event_name == 'push' && 'rendering-correctness-kitless-legacy' || '' }} @@ -945,16 +943,14 @@ jobs: container-name: "isaac-lab-rendering-correctness-kitless-legacy-test" omni-github-test-type: "rendering-correctness-kitless-legacy" - # Post-merge by default; pull requests opt in per run with ``run-ci ovstage``. + # OvStage is the only OVRTX scene path and runs on every activated PR build. test-rendering-correctness-kitless-ovstage: name: "rendering-correctness-kitless (ovstage)" runs-on: [self-hosted, gpu] timeout-minutes: 120 continue-on-error: ${{ github.event_name == 'workflow_dispatch' }} needs: [build, config] - if: >- - (github.event_name != 'pull_request' || github.event.label.name == 'ci:run-ovstage') && - needs.build.result == 'success' + if: needs.build.result == 'success' env: USE_OVPHYSX_WHEELHOUSE: ${{ needs.config.outputs.ovphysx_wheelhouse_image != '' && ((github.event_name == 'pull_request' && github.base_ref == github.event.repository.default_branch && github.event.pull_request.head.repo.full_name == github.repository) || (github.event_name != 'pull_request' && github.ref_name == github.event.repository.default_branch)) }} steps: diff --git a/docs/source/api/lab_ov/isaaclab_ov.cloner.rst b/docs/source/api/lab_ov/isaaclab_ov.cloner.rst index 6d4467bb9b19..3fd20d12aacb 100644 --- a/docs/source/api/lab_ov/isaaclab_ov.cloner.rst +++ b/docs/source/api/lab_ov/isaaclab_ov.cloner.rst @@ -6,7 +6,7 @@ Clone contexts route assets to the representation that owns their copies: * :class:`~isaaclab_ov.cloner.OvPhysxReplicateContext` prepares native physics replication. -* :class:`~isaaclab_ov.cloner.OvrtxReplicateContext` prepares copies for an OVRTX engine's internal scene. +* :class:`~isaaclab_ov.cloner.OvrtxReplicateContext` acquires the OVRTX engine and routes its copies to OvStage. * :class:`~isaaclab_ov.cloner.OvstageReplicateContext` prepares copies for simulation-owned OVStage resources, independently of their consumers. An OVRTX engine borrowing that stage does not clone it again. @@ -15,16 +15,15 @@ Clone contexts route assets to the representation that owns their copies: Clone routing ------------- -``OvrtxReplicateContext.prepare`` in ``isaaclab_ov/cloner/replicate.py`` selects the representation -before native resource initialization. Without environment overrides, OVRTX uses native cloning with -both OVPhysX and Newton. OVPhysX also retains native physics cloning. +``OvrtxReplicateContext.prepare`` in ``isaaclab_ov/cloner/replicate.py`` acquires a simulation-owned +OvStage before constructing its OVRTX borrower. OVRTX always uses OvStage for population, cloning, +queries, and attribute writes, with either Newton or OVPhysX physics. The deprecated renderer-owned +scene API and ``ovrtx_replicate`` helper have been removed. Use +:func:`~isaaclab_ov.cloner.ovstage_replicate` for native rendering copies. -``ISAAC_LAB_OVRTX_USE_OVSTAGE=1`` selects independent OVStage rendering with either physics backend; -``0`` selects native OVRTX cloning. Set the flag before creating the simulation. Reset retains the -selected route. This flag alone never enables physics/rendering stage sharing. - -To share one OVStage with OVPhysX and OVRTX, set ``ISAAC_LAB_SHARE_OVSTAGE=1``. Sharing requires -OVPhysX and selects OVStage rendering regardless of ``ISAAC_LAB_OVRTX_USE_OVSTAGE``. +``ISAAC_LAB_OVRTX_USE_OVSTAGE`` is no longer read; remove it from launch scripts. +To share one OvStage with OVPhysX and OVRTX, set ``ISAAC_LAB_SHARE_OVSTAGE=1`` before creating +the simulation. Sharing requires OVPhysX; otherwise rendering uses an independent OvStage. Sharing remains experimental and opt-in. It retains native physics cloning and populates complete original worlds in one stage before OVPhysX attaches. ``OvstageReplicateContext`` also receives the diff --git a/docs/source/concepts/renderers.rst b/docs/source/concepts/renderers.rst index f4da82122837..78e540e328c0 100644 --- a/docs/source/concepts/renderers.rst +++ b/docs/source/concepts/renderers.rst @@ -397,52 +397,18 @@ token per instance; markers without that ownership information remain shared. .. _renderers-async-data-flow: -Asynchronous Rendering ----------------------- +OvStage rendering and migration +------------------------------- -:attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.async_rendering` returns a camera's previous capture -while rendering its next image. This allows rendering to overlap simulation and Python work. -The first capture, including after reset, waits for a fresh image. The ovstage path stays synchronous. +OVRTX renders synchronously through OvStage. Scene writes finish and the stage ordinal is sealed +before each render; camera outputs contain the current capture. -Latency is one capture, not necessarily one physics or control step. State observations remain -current, so enabling this option changes the policy's observation timing; training may need to -account for that delay. Physics and policy computation may also use the GPU. +The deprecated renderer-owned scene path and its asynchronous pipeline have been removed. +:attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.async_rendering` remains a compatibility option: +setting it to ``True`` logs a warning and still renders synchronously. Remove this override from +existing configurations. Delayed-image ``capture`` metadata is no longer produced by OVRTX. +Use the camera's current pose and intrinsic fields with its rendered image. -For a camera capturing once per environment step, steady-state operation is: - -.. code-block:: text - - Synchronous: physics k -> submit image k -> wait/read image k -> policy - Asynchronous: physics k -> submit image k -> wait/read image k-1 -> policy - | | - +---- image k renders ------------+--> physics k+1 - -The first image is returned immediately after priming and repeated once on the next capture. - -Each camera owns its pending observations. Reading camera A never changes camera B's pixels or -metadata, even when they share a native render submission. Reset discards that camera's pending -observations. A partial environment reset re-primes the whole tiled camera product, without -invalidating other cameras. - -Live fields such as ``camera.data.pos_w`` and ``camera.data.intrinsic_matrices`` remain current. -Use the capture metadata when pairing delayed pixels with a pose or calibration, for example -when deprojecting depth: - -.. code-block:: python - - data = camera.data - depth = data.output["distance_to_image_plane"] - capture = data.info["distance_to_image_plane"]["capture"] - position, orientation = capture["pos_w"], capture["quat_w_world"] - intrinsics, frame = capture["intrinsic_matrices"], capture["frame"] - -Capture metadata remains unchanged on later captures. Direct renderer callers use -:meth:`~isaaclab.renderers.BaseRenderer.prepare_capture` before submitting a capture and -:meth:`~isaaclab.renderers.BaseRenderer.read_output` to publish it. - -SDP fills renderer-owned transform and geometry buffers, including deformable meshes, particles, -and cables. Two buffers alternate per write and are reused only after OVRTX consumes them. -Physics can therefore update its live arrays while the previous capture renders. .. _renderers-ovrtx-render-product-split: diff --git a/docs/source/concepts/sensors/camera.rst b/docs/source/concepts/sensors/camera.rst index 9b7ff75c9df3..6ca1d3108078 100644 --- a/docs/source/concepts/sensors/camera.rst +++ b/docs/source/concepts/sensors/camera.rst @@ -365,8 +365,7 @@ capture renders every environment. The camera calls each processor with ``env_ma environments due for the capture, whose frame and timestamp advance. Stateful processors (frame stacking, temporal filters, video generation) use it to advance only those rows. -With asynchronous rendering, images may be delayed or repeated, and processors receive ``env_mask=None``. -Use synchronous rendering (``async_rendering=False``) for processors that advance frame history. +OVRTX captures synchronously through OvStage, so its processors receive the mask for the current capture. Post-render image signal processing ----------------------------------- @@ -375,7 +374,7 @@ Post-render image signal processing The shipped processor is PPISP (Physically Plausible Image Signal Processing), which converts the scene-linear ``rgb_hdr`` output through responsivity, exposure, vignetting, color correction, and a camera response function into ``rgb`` and ``rgba``. The camera requests ``rgb_hdr`` from the renderer. -PPISP is stateless and supports asynchronous rendering with both ``PpispProcessorCfg`` and deprecated ``isp_cfg``. +PPISP is stateless. :class:`~isaaclab_ppisp.PpispProcessorCfg` accepts :class:`~isaaclab_ppisp.PpispCfg` for explicit coefficients or coefficients imported from a USD camera, or :class:`~isaaclab.sensors.camera.CameraISPMode` to diff --git a/docs/source/developer-tools/benchmarking/run_benchmarks.rst b/docs/source/developer-tools/benchmarking/run_benchmarks.rst index cf3fc3956165..f769ef61ce19 100644 --- a/docs/source/developer-tools/benchmarking/run_benchmarks.rst +++ b/docs/source/developer-tools/benchmarking/run_benchmarks.rst @@ -63,23 +63,9 @@ From a source installation, run: --output_path ./benchmark_results \ physics=isaacsim_physx -OVRTX camera tasks can compare synchronous against asynchronous (pipelined) rendering through a -Hydra override on the camera's renderer configuration: - -.. code-block:: bash - - uv run --extra ovrtx isaaclab benchmark runtime \ - --task Isaac-Cartpole-Camera-Direct \ - --num_envs 256 \ - --warmup_steps 30 \ - --num_steps 200 \ - --benchmark_formatter schema,omniperf \ - --output_path ./results/ovrtx_async \ - physics=newton_mjwarp renderer=ovrtx presets=rgb \ - env.scene.tiled_camera.renderer_cfg.async_rendering=True - -Only the OVRTX renderer implements asynchronous rendering. -See :ref:`renderers-async-data-flow` for how states, observations, and frames line up in each mode. +OVRTX camera tasks render synchronously through OvStage. The former +``env.scene.tiled_camera.renderer_cfg.async_rendering=True`` override no longer enables pipelining. +See :ref:`renderers-async-data-flow` for migration details. Read the result ~~~~~~~~~~~~~~~ diff --git a/source/_isaaclab_testing/test/rendering/golden_images/renderers/cartpole/newton-ovrtx-async-rgb.png b/source/_isaaclab_testing/test/rendering/golden_images/renderers/cartpole/newton-ovrtx-async-rgb.png deleted file mode 100644 index 8431d28113fa..000000000000 --- a/source/_isaaclab_testing/test/rendering/golden_images/renderers/cartpole/newton-ovrtx-async-rgb.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e2b5260e55ef0b60792e78acb96b244fdd5ceafffdd1f580440ca2b24d43d673 -size 2988 diff --git a/source/_isaaclab_testing/test/rendering/golden_images/renderers/cartpole/ovphysx-ovrtx-async-rgb.png b/source/_isaaclab_testing/test/rendering/golden_images/renderers/cartpole/ovphysx-ovrtx-async-rgb.png deleted file mode 100644 index 46fe7f9faed3..000000000000 --- a/source/_isaaclab_testing/test/rendering/golden_images/renderers/cartpole/ovphysx-ovrtx-async-rgb.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ab75faf86bab063c6fcaacaf265d51c254aac748b3d7cb39b895d89e1756193b -size 2942 diff --git a/source/_isaaclab_testing/test/rendering/rendering_cases.py b/source/_isaaclab_testing/test/rendering/rendering_cases.py index b6f1c9fae15e..d4ee66d77a59 100644 --- a/source/_isaaclab_testing/test/rendering/rendering_cases.py +++ b/source/_isaaclab_testing/test/rendering/rendering_cases.py @@ -108,7 +108,7 @@ def golden_filename(self, aov: RenderBufferKind, namespace: str | None = None) - KITLESS_CASES = tuple( (stage, case) for case in _KITLESS_CASES - for stage in (("legacy", "ovstage") if case.renderer == "ovrtx" else ("legacy",)) + for stage in (("ovstage",) if case.renderer == "ovrtx" else ("legacy",)) ) @@ -172,7 +172,7 @@ class SceneCoverage: scene=scene, ), ) - for stage in (("legacy", "ovstage") if case.renderer == "ovrtx" else ("legacy",)) + for stage in (("ovstage",) if case.renderer == "ovrtx" else ("legacy",)) ) # Cable instance segmentation crashes native OVRTX (NVBUG#6463802); exercise its other channels. _CABLE_AOVS = (RenderBufferKind.RGB, RenderBufferKind.ALBEDO, RenderBufferKind.DEPTH, RenderBufferKind.NORMALS) @@ -233,7 +233,7 @@ class SceneCoverage: scene="gaussian_splats_raspberry_4envs", ), ) - for stage in ("legacy", "ovstage") + for stage in ("ovstage",) ) KIT_RENDERING_CASES = ( KIT_CASES @@ -265,7 +265,7 @@ class SceneCoverage: + SPECIALIZED_KITLESS_CASES + GAUSSIAN_KITLESS_CASES + ( - *((stage, RenderCase("newton", "ovrtx", _CABLE_AOVS, scene="franka_cable")) for stage in ("legacy", "ovstage")), + *((stage, RenderCase("newton", "ovrtx", _CABLE_AOVS, scene="franka_cable")) for stage in ("ovstage",)), ("legacy", RenderCase("newton", "newton_warp", (RenderBufferKind.RGB,), scene="kuka_materials")), ( "legacy", @@ -273,11 +273,7 @@ class SceneCoverage: ), *( (stage, RenderCase("newton", "ovrtx", (RenderBufferKind.RGB,), scene="kuka_materials")) - for stage in ("legacy", "ovstage") - ), - *( - ("legacy", RenderCase(physics, "ovrtx", (RenderBufferKind.RGB,), scene="cartpole", variant="async")) - for physics in ("newton", "ovphysx") + for stage in ("ovstage",) ), ) ) diff --git a/source/_isaaclab_testing/test/rendering/rendering_runner.py b/source/_isaaclab_testing/test/rendering/rendering_runner.py index 16f4978fe38e..a0c0be020605 100644 --- a/source/_isaaclab_testing/test/rendering/rendering_runner.py +++ b/source/_isaaclab_testing/test/rendering/rendering_runner.py @@ -63,7 +63,7 @@ def run_rendering_case( scene.cfg.camera.renderer_cfg = { "isaac_rtx": IsaacRtxRendererCfg(), "newton_warp": NewtonWarpRendererCfg(), - "ovrtx": OVRTXRendererCfg(async_rendering=case.variant == "async"), + "ovrtx": OVRTXRendererCfg(), }[case.renderer] if case.scene == "rendering_scene": # Explicit colors and shadows belong to this synthetic fixture, not every scene. @@ -235,7 +235,6 @@ def run_rendering_case( def run_kitless_rendering_case(stage_variant: str, case: RenderCase, request: Any, monkeypatch: Any) -> None: """Apply the ``stage_variant`` setting and run one kitless rendering case.""" monkeypatch.delenv("ISAAC_LAB_SHARE_OVSTAGE", raising=False) - monkeypatch.setenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", str(int(stage_variant == "ovstage"))) run_rendering_case(case, request, golden_namespace=None, artifact_namespace=stage_variant) diff --git a/source/_isaaclab_testing/test/rendering/test_rendering_architecture.py b/source/_isaaclab_testing/test/rendering/test_rendering_architecture.py index aa9d5795916d..4a0d0c4e8f2c 100644 --- a/source/_isaaclab_testing/test/rendering/test_rendering_architecture.py +++ b/source/_isaaclab_testing/test/rendering/test_rendering_architecture.py @@ -41,7 +41,7 @@ def test_rendering_is_downstream_and_task_independent() -> None: def test_case_and_golden_inventory() -> None: - """Each case is unique; both OVRTX readers share one complete reference inventory.""" + """Each case is unique; the rendering paths have one complete reference inventory.""" kit_ids = [case.id for case in KIT_RENDERING_CASES] kitless_ids = [f"{stage}-{case.id}" for stage, case in KITLESS_RENDERING_CASES] assert len(kit_ids) == len(set(kit_ids)) @@ -54,7 +54,7 @@ def test_case_and_golden_inventory() -> None: root = _SUITE / "golden_images/renderers" assert {path.relative_to(root) for path in root.rglob("*.png")} == expected subsets = tomllib.loads((_SOURCE.parent / ".github/test-subsets/postmerge-rendering.toml").read_text()) - suite = _SUITE.relative_to(_SOURCE.parent) + suite = _SUITE.relative_to(_SOURCE.parent).as_posix() nodes = {f"{suite}/test_rendering_kit.py::test_rendering[{case}]" for case in kit_ids} | { f"{suite}/test_rendering_kitless_{case.physics}_{case.renderer}.py::test_rendering[{stage}-{case.id}]" for stage, case in KITLESS_RENDERING_CASES diff --git a/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst b/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst new file mode 100644 index 000000000000..3e55a62e7a72 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst @@ -0,0 +1,5 @@ +* **Breaking:** Removed the deprecated OVRTX-owned scene API and ``ovrtx_replicate``. All OVRTX cameras, + lidars, materials, meshes, and markers now use OvStage. Remove ``ISAAC_LAB_OVRTX_USE_OVSTAGE`` from launch + scripts and use ``ovstage_replicate`` for native rendering copies. Sharing with OVPhysX remains opt-in + through ``ISAAC_LAB_SHARE_OVSTAGE=1``. Rendering is synchronous; ``async_rendering=True`` warns and no + longer pipelines captures. diff --git a/source/isaaclab_ov/changelog.d/ovstage-only.major b/source/isaaclab_ov/changelog.d/ovstage-only.major new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_ov/isaaclab_ov/cloner/__init__.py b/source/isaaclab_ov/isaaclab_ov/cloner/__init__.py index 41d60bbf1014..c4f9fbaa6af6 100644 --- a/source/isaaclab_ov/isaaclab_ov/cloner/__init__.py +++ b/source/isaaclab_ov/isaaclab_ov/cloner/__init__.py @@ -8,7 +8,6 @@ OvrtxReplicateContext, OvstageReplicateContext, ovphysx_replicate, - ovrtx_replicate, ovstage_replicate, ) @@ -17,6 +16,5 @@ "OvrtxReplicateContext", "OvstageReplicateContext", "ovphysx_replicate", - "ovrtx_replicate", "ovstage_replicate", ] diff --git a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py index e27531e151e3..5d14cae86e86 100644 --- a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py +++ b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py @@ -27,13 +27,9 @@ from isaaclab_ov.stage import ovstage_replicate as ovstage_replicate if TYPE_CHECKING: - import ovrtx - from isaaclab.cloner import ClonePlan from isaaclab.sim import SimulationContext - from isaaclab_ov.renderers.ovrtx_renderer import OVRTXBackend - logger = logging.getLogger(__name__) @@ -159,7 +155,7 @@ def replicate(self, plan: ClonePlan, asset_prototype_ids: tuple[int, ...]) -> No class OvrtxReplicateContext(cloner.ReplicateContext): - """Prepare routed copies for OVRTX engines that own their scene internally.""" + """Acquire OVRTX engines and route their scene copies through OvStage.""" replicate_priority = 100 @@ -175,30 +171,23 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext], """ renderers = sim.get_backends(OVRTXRendererCfg) if not renderers: + routing.pop(OvrtxReplicateContext, None) return initialized = next((renderer for renderer in renderers if renderer.backend is not None), None) if initialized is not None: - use_ovstage = initialized._use_ovstage share_ovstage = initialized.backend.cfg.scene_key is None else: - # Default to native OVRTX cloning to preserve camera-task throughput on both physics backends. - # Keep sharing opt-in until OVPhysX cold binding and shared-stage update performance are fixed. with_ovphysx = sim.backend_manager.clone_context_type is OvPhysxReplicateContext - value = os.environ.get("ISAAC_LAB_OVRTX_USE_OVSTAGE", "0").strip() - if value not in {"0", "1"}: - raise ValueError(f"Invalid ISAAC_LAB_OVRTX_USE_OVSTAGE: {value!r}. Expected 0 or 1.") share_ovstage = os.environ.get("ISAAC_LAB_SHARE_OVSTAGE") == "1" - use_ovstage = share_ovstage or value == "1" if share_ovstage and not with_ovphysx: raise ValueError("Shared OVStage cloning requires OVPhysX.") if share_ovstage and sim.backend_manager.backend is not None and sim.backend_manager.backend.owns_scene: raise RuntimeError("Configure OVRTX cameras before the first OVPhysX reset to share its OVStage.") - if use_ovstage: - if share_ovstage: - # Keep the physics route so the existing planner builds native clone recipes. - routing.setdefault(OvstageReplicateContext, set()).update(routing.get(OvPhysxReplicateContext, ())) - routing.setdefault(OvstageReplicateContext, set()).update(routing.pop(OvrtxReplicateContext, ())) - sim.clone_contexts.pop(OvrtxReplicateContext, None) + if share_ovstage: + # Keep the physics route so the existing planner builds native clone recipes. + routing.setdefault(OvstageReplicateContext, set()).update(routing.get(OvPhysxReplicateContext, ())) + routing.setdefault(OvstageReplicateContext, set()).update(routing.pop(OvrtxReplicateContext, ())) + sim.clone_contexts.pop(OvrtxReplicateContext, None) # Stage ownership is settled before native construction. Register the stage before its borrowers. for renderer in renderers: @@ -213,7 +202,6 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext], scene_key=None if share_ovstage else renderer.cfg, log_file_path=renderer.cfg.log_file_path, log_level=renderer.cfg.log_level, - use_ovstage=use_ovstage, read_gpu_transforms=read_gpu_transforms == "1", motion_bvh=renderer.cfg.motion_bvh, device=sim.device, @@ -222,33 +210,18 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext], raise ValueError( "A shared OVStage requires one OVRTX engine; use the same native logging/transform settings." ) - scene = None - if use_ovstage: - scene = sim.get_or_create_backend( - OvstageBackendCfg( - scene_key=None if share_ovstage else backend_cfg, - populate_physics=share_ovstage, - defer_render_copies=share_ovstage, - ) + scene = sim.get_or_create_backend( + OvstageBackendCfg( + scene_key=None if share_ovstage else backend_cfg, + populate_physics=share_ovstage, + defer_render_copies=share_ovstage, ) + ) renderer.backend = sim.get_or_create_backend(backend_cfg) - renderer.scene = scene if use_ovstage else renderer.backend - renderer._use_ovstage = use_ovstage - if renderer.cfg.async_rendering and use_ovstage: + renderer.scene = scene + if renderer.cfg.async_rendering: logger.warning("Asynchronous OVRTX rendering is unsupported with ovstage; rendering synchronously.") - def replicate(self, plan: ClonePlan, asset_prototype_ids: tuple[int, ...]) -> None: - """Publish routed copies, environment paths and positions to native OVRTX scene owners. - - Engines borrowing an OVStage receive their copies through that stage's context. - - Args: - plan: Replication layout shared by every clone backend. - asset_prototype_ids: Asset definitions routed to native OVRTX scenes. - """ - backends = [backend for backend in self._sim.get_backends(OVRTXBackendCfg) if not backend.cfg.use_ovstage] - _prepare_scene_copies(plan, asset_prototype_ids, backends) - class OvstageReplicateContext(cloner.ReplicateContext): """Prepare routed copies for simulation-owned stages, independently of their consumers.""" @@ -266,7 +239,7 @@ def replicate(self, plan: ClonePlan, asset_prototype_ids: tuple[int, ...]) -> No def _prepare_scene_copies( - plan: ClonePlan, asset_prototype_ids: tuple[int, ...], backends: Sequence[OVRTXBackend | OvstageBackend] + plan: ClonePlan, asset_prototype_ids: tuple[int, ...], backends: Sequence[OvstageBackend] ) -> None: """Store prepared subtree copies on their owners; consumers never reinterpret the clone plan.""" if not backends: @@ -305,34 +278,6 @@ def _prepare_scene_copies( backend.clone_positions = plan.positions -def ovrtx_replicate( - renderer: ovrtx.Renderer, - copies: Sequence[tuple[str, Sequence[str]]], - env_paths: Sequence[str], - positions: np.ndarray | None = None, -) -> None: - """Apply prepared subtree copies and environment placement to a native OVRTX scene. - - Args: - renderer: Native renderer holding the source prims. - copies: Source paths paired with destination paths, ordered with parents before children. - Sources with no destinations are retained prototypes; self-copies must be excluded. - env_paths: Environment-root paths in placement order. - positions: Optional environment positions [m], shape ``[len(env_paths), 3]``. - """ - from ovrtx import PrimMode, Semantic # noqa: PLC0415 - - for source, targets in copies: - if targets: - renderer.clone_usd(source, targets) - if positions is not None and env_paths: - xforms = np.tile(np.eye(4, dtype=np.float64), (len(env_paths), 1, 1)) - xforms[:, 3, :3] = positions - renderer.write_attribute( - env_paths, "omni:xform", xforms, semantic=Semantic.XFORM_MAT4x4, prim_mode=PrimMode.MUST_EXIST - ) - - def ovphysx_replicate( stage: Usd.Stage, sources: Sequence[str], diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 47f326f59fc9..537d223226b4 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -10,9 +10,8 @@ - **ovrtx_renderer.py** (this file): Orchestrates USD loading/cloning, camera and object bindings, and output buffers, borrowing native handles from OVRTXBackend. Each frame it: updates camera/object transforms (using kernels), steps the renderer, then extracts - tiles from the tiled framebuffer (kernels). Under asynchronous rendering, each camera keeps - its own pending ``step_async`` render operation and publishes it at the next ``read_output``. - The ovrtx binding write operations retain their input buffers until ovrtx has consumed them. + tiles from the tiled framebuffer (kernels). Scene writes complete through OvStage before + each synchronous render consumes the sealed ordinal. - **ovrtx_renderer_kernels.py**: Warp GPU kernels for OVRTX rendering pipeline. @@ -32,11 +31,9 @@ import tempfile import warnings import weakref -from builtins import ExceptionGroup -from collections import deque from collections.abc import Callable, Iterable, Iterator, Sequence from pathlib import Path -from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar +from typing import TYPE_CHECKING, Any, Literal logger = logging.getLogger(__name__) @@ -55,16 +52,10 @@ from ovrtx import ( - AttributeFilterMode, - BindingFlag, - DataAccess, Device, - FilterKind, - PrimMode, Renderer, RendererConfig, RenderProductSetOutputs, - Semantic, TextureStreamingMode, ) from PIL import Image @@ -78,7 +69,6 @@ from isaaclab.sim import PreviewSurfaceCfg, SimulationContext, use_stage from isaaclab.utils.warp import ProxyArray -from isaaclab_ov.cloner import ovrtx_replicate from isaaclab_ov.renderers.ovrtx_annotator_utils import ( IdentifierMap, RgbaColor, @@ -117,7 +107,7 @@ ) if TYPE_CHECKING: - from ovrtx import AttributeBinding, FrameOutput, Operation, PendingFetch, RenderVarOutput + from ovrtx import FrameOutput, RenderVarOutput from isaaclab.renderers.base_renderer import VisualMaterialBatch from isaaclab.sensors import LidarData @@ -287,7 +277,7 @@ def _resolve_env_light_partitions( class OVRTXBackend: - """Own one native renderer, independently of its camera products and optional OVStage.""" + """Own one native renderer, independently of its camera products and OvStage.""" def __init__(self, cfg: OVRTXBackendCfg): self.cfg = cfg @@ -310,18 +300,11 @@ def __init__(self, cfg: OVRTXBackendCfg): motion_bvh=cfg.motion_bvh, read_gpu_transforms=cfg.read_gpu_transforms, keep_system_alive=True, - suppress_deprecation_warnings=True, texture_streaming_mode=TextureStreamingMode.SYNCHRONOUS, ) # Redirection may initialize the native library and must use the same settings. redirect_shader_cache(native_cfg) self.next_camera_id = 0 - if not cfg.use_ovstage: - # Prepared by clone dispatch, consumed after camera overrides are authored. - self.clone_copies: list[tuple[str, list[str]]] = [] - self.clone_env_paths: list[str] = [] - self.population_env_paths: list[str] = [] - self.clone_positions: np.ndarray | None = None self.renderer = Renderer(native_cfg) def detach(self) -> None: @@ -447,7 +430,7 @@ def __init__( """ self.spec = spec self.camera_paths = camera_paths - self.camera_xform_binding: AttributeBinding[wp.array] | ovstage.Query | None = None + self.camera_xform_binding: ovstage.Query | None = None self.resources = contextlib.ExitStack() self.width = spec.cfg.width self.height = spec.cfg.height @@ -472,11 +455,7 @@ def __init__( # "auto" and "all" both start with one render product for all environments. self._set_layout(render_scope_name, max_envs if isinstance(max_envs, int) else self.num_envs) self.warp_buffers: dict[str, wp.array] = {} - self.intrinsic_bindings: list[AttributeBinding] = [] - self.camera_writes = _AsyncWriteBuffers[wp.array]() - self.pending: tuple[Operation[PendingFetch[RenderProductSetOutputs]], dict | None] | None = None - self.ready: tuple[Operation[PendingFetch[RenderProductSetOutputs]], dict | None] | None = None - self.capture: dict[str, ProxyArray] = {} + self.camera_matrices: wp.array | None = None # Per-output metadata collected during render() and copied into CameraData.info by read_output(). # Populated for "semantic_segmentation" (with an "idToLabels" mapping) and # "instance_segmentation" (with "idToLabels" and "idToSemantics" mappings). @@ -530,13 +509,10 @@ def cleanup(self) -> None: is closed. The render product paths remain as identifiers for renderer bookkeeping. """ try: - with self.resources: - self.camera_writes.close() + self.resources.close() finally: - self.pending = self.ready = None - self.capture = {} + self.camera_matrices = None self.camera_xform_binding = None - self.intrinsic_bindings.clear() self.warp_buffers.clear() self.renderer_info.clear() @@ -604,15 +580,15 @@ def __init__(self, scope: str, sample_dt: float, lidar_paths: list[str]): self.lidar_paths = lidar_paths self.render_product_path = f"/{scope}/RenderProduct" self.point_cloud_path = f"/{scope}/Vars/PointCloud" - self.xform_binding: AttributeBinding[wp.array] | ovstage.Query | None = None + self.xform_binding: ovstage.Query | None = None self.resources = contextlib.ExitStack() - self.pose_writes = _AsyncWriteBuffers[wp.array]() + self.pose_matrices: wp.array | None = None self.sample_dt = sample_dt def cleanup(self) -> None: """Release the pose writes before releasing the binding.""" with self.resources: - self.pose_writes.close() + self.pose_matrices = None self.xform_binding = None @@ -643,7 +619,7 @@ def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext): self.geometry_resources = contextlib.ExitStack() self._sdp = self._sim.get_scene_data_provider() self._transforms_timestamp = -1 - self._transform_writes = _AsyncWriteBuffers(SceneDataFormat.TransposedMatrix44d() for _ in range(2)) + self._transform_buffer = SceneDataFormat.TransposedMatrix44d() self._object_scales: wp.array | None = None self._geometry_paths: list[str] = [] self._visible_envs: np.ndarray | None = None @@ -651,8 +627,6 @@ def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext): self._hidden_envs: wp.array | None = None self._body_envs: wp.array | None = None self._hidden_matrices: dict[int, wp.array] = {} - self._geometry_offsets: dict[str, int] = {} - self._geometry_writes = _AsyncWriteBuffers[wp.array]() self._geometry_timestamp = -1 self._initialized_scene = False # Flat scratch buffers for colorized segmentation, one per output, sized for the largest atlas. @@ -662,13 +636,11 @@ def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext): self._visual_material_writer_ref: weakref.ReferenceType[OVRTXVisualMaterialWriter] | None = None # Clone preparation resolves scene ownership before acquiring native resources. - self._use_ovstage = False - self._needs_transform_initialization = False - self.scene: OvstageBackend | OVRTXBackend | None = None + self.scene: OvstageBackend | None = None self.backend: OVRTXBackend | None = None """Native engine borrowed from the simulation registry after clone preparation.""" - self._object_xform_binding: AttributeBinding[wp.array] | ovstage.Query | None = None - self._geometry_points_binding: AttributeBinding[list[wp.array]] | ovstage.Query | None = None + self._object_xform_binding: ovstage.Query | None = None + self._geometry_points_binding: ovstage.Query | None = None self._bindings = contextlib.ExitStack() self._env_paths: Sequence[str] = () @@ -688,35 +660,18 @@ def prepare_stage(self, stage: Usd.Stage, num_envs: int) -> None: logger.info("Preparing stage (%d envs)...", num_envs) env_paths = self._env_paths = self.scene.clone_env_paths light_partitions = _resolve_env_light_partitions(stage, env_paths, copies=self.scene.clone_copies) - if self.cfg.temp_usd_dir is not None or not self._use_ovstage or not self.scene.ordinal: + if self.cfg.temp_usd_dir is not None or not self.scene.ordinal: if self.cfg.temp_usd_dir is not None: _write_file(Path(self.cfg.temp_usd_dir), "pre_ovrtx_renderer_stage.usda", stage.ExportToString()) # Physics population needs fully composed instance collider data. usd = export_stage_to_string( stage, self.scene.clone_env_paths, source_paths=tuple(source for source, _ in self.scene.clone_copies), keep_env_roots=False, env_paths=self.scene.population_env_paths, - preserve_references=not (self._use_ovstage and self.scene.cfg.populate_physics), + preserve_references=not self.scene.cfg.populate_physics, ) # fmt: skip - if not self._use_ovstage: - # Author the camera mode before loading the stage: changing it later - # leaves cached camera poses stale until another scene update. - settings_path = Sdf.Path(stage.GetMetadata("renderSettingsPrimPath") or "/Render/IsaacLabSettings") - layer = Sdf.Layer.CreateAnonymous() - layer.ImportFromString(usd) - attribute = layer.GetAttributeAtPath(settings_path.AppendProperty(_GPU_CAMERA_TRANSFORMS_ATTRIBUTE)) - if attribute is None: - attribute = Sdf.AttributeSpec( - layer.GetPrimAtPath(settings_path), _GPU_CAMERA_TRANSFORMS_ATTRIBUTE, Sdf.ValueTypeNames.Bool - ) - attribute.default = False - usd = layer.ExportToString() if self.cfg.temp_usd_dir is not None: _write_file(Path(self.cfg.temp_usd_dir), "ovrtx_renderer_stage.usda", usd) - if self._use_ovstage: - self.scene.populate(usd) - else: - self.backend.renderer.open_usd_from_string(usd) - ovrtx_replicate(self.backend.renderer, self.scene.clone_copies, env_paths, self.scene.clone_positions) + self.scene.populate(usd) partition_writes = ( (env_paths, "primvars:omni:scenePartition", [f"env_{i}" for i in range(len(env_paths))]), (list(light_partitions), "omni:scenePartition", list(light_partitions.values())), @@ -724,43 +679,34 @@ def prepare_stage(self, stage: Usd.Stage, num_envs: int) -> None: for paths, attribute_name, tokens in partition_writes: if not paths: continue - if self._use_ovstage: - with self.scene.query(paths) as query: - self.scene.stage.write_attribute( - query, attribute_name, ordinal=self.scene.ordinal, - tensors=np.array( - [self.scene.paths.intern_token(token).raw_id for token in tokens], dtype=np.uint64 - ), - is_array=False, semantic=ovstage.AttributeSemantic.TOKEN_ID, - ).wait() # fmt: skip - else: - self.backend.renderer.write_attribute( - paths, attribute_name, tokens, - semantic=Semantic.TOKEN_STRING, prim_mode=PrimMode.CREATE_NEW, - ) # fmt: skip - self._setup_xform_bindings(stage) - self._setup_geometry_bindings() - if self._use_ovstage: - # OVRTX 0.7's GPU camera cache mixes tiled views and misses pose updates. - # Disable only camera reads before registering products (and before attaching - # an OVStage), retaining GPU instance transforms for large articulated scenes. - settings_path = str(stage.GetMetadata("renderSettingsPrimPath") or "/Render/IsaacLabSettings") - cpu_cameras = np.array([False], dtype=np.bool_) - with self.scene.query([settings_path]) as query: + with self.scene.query(paths) as query: self.scene.stage.write_attribute( - query, _GPU_CAMERA_TRANSFORMS_ATTRIBUTE, ordinal=self.scene.ordinal, - tensors=cpu_cameras, is_array=False, + query, attribute_name, ordinal=self.scene.ordinal, + tensors=np.array( + [self.scene.paths.intern_token(token).raw_id for token in tokens], dtype=np.uint64 + ), + is_array=False, semantic=ovstage.AttributeSemantic.TOKEN_ID, ).wait() # fmt: skip - if self._use_ovstage: - self.scene.commit() - if not self.backend.attached: - self.backend.renderer.attach_ovstage(self.scene.stage) - self.backend.attached = True - self.scene.resources.callback(self.backend.detach) - self.scene.resources.callback(self._sim.render_context.reset_stage_prepare_flag) - self.scene.resources.callback(self.close) + self._setup_xform_bindings(stage) + self._setup_geometry_bindings() + # OVRTX 0.7's GPU camera cache mixes tiled views and misses pose updates. + # Disable only camera reads before registering products (and before attaching + # an OVStage), retaining GPU instance transforms for large articulated scenes. + settings_path = str(stage.GetMetadata("renderSettingsPrimPath") or "/Render/IsaacLabSettings") + cpu_cameras = np.array([False], dtype=np.bool_) + with self.scene.query([settings_path]) as query: + self.scene.stage.write_attribute( + query, _GPU_CAMERA_TRANSFORMS_ATTRIBUTE, ordinal=self.scene.ordinal, + tensors=cpu_cameras, is_array=False, + ).wait() # fmt: skip + self.scene.commit() + if not self.backend.attached: + self.backend.renderer.attach_ovstage(self.scene.stage) + self.backend.attached = True + self.scene.resources.callback(self.backend.detach) + self.scene.resources.callback(self._sim.render_context.reset_stage_prepare_flag) + self.scene.resources.callback(self.close) self._initialized_scene = True - self._needs_transform_initialization = not self._use_ovstage and self.backend.cfg.read_gpu_transforms def _setup_xform_bindings(self, stage: Usd.Stage) -> None: """Bind SDP body paths and preserve their authored scales when writing world poses.""" @@ -785,28 +731,14 @@ def _setup_xform_bindings(self, stage: Usd.Stage) -> None: scales = [scales_by_path.get(path, (1.0, 1.0, 1.0)) for path in object_paths] self._object_scales = wp.array(scales, dtype=wp.vec3f, device=self._device) reset_xforms = np.ones(len(object_paths), dtype=np.bool_) - if self._use_ovstage: - self._object_xform_binding = self._bindings.enter_context(self.scene.query(object_paths)) - self.scene.stage.write_attribute( - self._object_xform_binding, - "omni:resetXformStack", - ordinal=self.scene.ordinal, - tensors=reset_xforms, - is_array=False, - ).wait() - else: - self._object_xform_binding = self.backend.renderer.bind_attribute( - prim_paths=object_paths, - attribute_name="omni:xform", - semantic=Semantic.XFORM_MAT4x4, - prim_mode=PrimMode.EXISTING_ONLY, - ) - if self._object_xform_binding is None: - raise RuntimeError("Failed to create OVRTX object bindings") - self._bindings.callback(self._object_xform_binding.unbind) - self.backend.renderer.write_attribute( - prim_paths=object_paths, attribute_name="omni:resetXformStack", tensor=reset_xforms - ) + self._object_xform_binding = self._bindings.enter_context(self.scene.query(object_paths)) + self.scene.stage.write_attribute( + self._object_xform_binding, + "omni:resetXformStack", + ordinal=self.scene.ordinal, + tensors=reset_xforms, + is_array=False, + ).wait() def _setup_geometry_bindings(self) -> None: """Bind SDP's world-space point prims without applying inherited transforms again.""" @@ -817,56 +749,22 @@ def _setup_geometry_bindings(self) -> None: prim_count = len(self._geometry_paths) reset_xforms = np.ones(prim_count, dtype=np.bool_) identity_xforms = np.tile(np.eye(4, dtype=np.float64), (prim_count, 1, 1)) - if self._use_ovstage: - self._geometry_points_binding = self._bindings.enter_context(self.scene.query(self._geometry_paths)) - self.scene.stage.write_attribute( - self._geometry_points_binding, - "omni:resetXformStack", - ordinal=self.scene.ordinal, - tensors=reset_xforms, - is_array=False, - ).wait() - self.scene.stage.write_attribute( - self._geometry_points_binding, - "omni:xform", - ordinal=self.scene.ordinal, - tensors=xform_tensor_from_numpy(identity_xforms), - is_array=False, - semantic=ovstage.AttributeSemantic.MATRIX, - ).wait() - else: - if self.cfg.async_rendering: - count = 0 - for path, array in points.items(): - self._geometry_offsets[path] = count - count += len(array) - self._geometry_writes = _AsyncWriteBuffers( - wp.empty(count, wp.vec3f, device=self._device) for _ in range(2) - ) - self.backend.renderer.write_attribute( - prim_paths=self._geometry_paths, - attribute_name="omni:resetXformStack", - tensor=reset_xforms, - prim_mode=PrimMode.MUST_EXIST, - ) - self.backend.renderer.write_attribute( - prim_paths=self._geometry_paths, - attribute_name="omni:xform", - tensor=identity_xforms, - semantic=Semantic.XFORM_MAT4x4, - prim_mode=PrimMode.MUST_EXIST, - ) - self._geometry_points_binding = self.backend.renderer.bind_array_attribute( - prim_paths=self._geometry_paths, - attribute_name="points", - dtype=np.float32, - shape=(3,), - prim_mode=PrimMode.MUST_EXIST, - flags=BindingFlag.OPTIMIZE, - ) - if self._geometry_points_binding is None: - raise RuntimeError("Failed to create OVRTX geometry point bindings") - self._bindings.callback(self._geometry_points_binding.unbind) + self._geometry_points_binding = self._bindings.enter_context(self.scene.query(self._geometry_paths)) + self.scene.stage.write_attribute( + self._geometry_points_binding, + "omni:resetXformStack", + ordinal=self.scene.ordinal, + tensors=reset_xforms, + is_array=False, + ).wait() + self.scene.stage.write_attribute( + self._geometry_points_binding, + "omni:xform", + ordinal=self.scene.ordinal, + tensors=xform_tensor_from_numpy(identity_xforms), + is_array=False, + semantic=ovstage.AttributeSemantic.MATRIX, + ).wait() def _resolve_environment_sensor_paths( self, prim_paths: list[str], count: int, *, environment_order: bool @@ -922,82 +820,48 @@ def create_lidar_render_data( ) try: - if self._use_ovstage: - reference = ovstage.population.add_usd_reference_from_string(self.scene.stage, usd, f"/{scope}") - render_data.resources.callback(self._remove_usd_reference, reference) - - ovstage.population.apply_usd_changes(self.scene.stage, ordinal=self.scene.ordinal) - - with self.scene.query([product_path]) as query: - self.scene.stage.write_attribute( - query, - "camera", - ordinal=self.scene.ordinal, - tensors=np.array( - [self.scene.paths.intern_path(path).raw_id for path in lidar_paths], - dtype=np.uint64, - ), - is_array=True, - semantic=ovstage.AttributeSemantic.RELATIONSHIP_PATH_ID, - ).wait() - - render_data.xform_binding = render_data.resources.enter_context(self.scene.query(lidar_paths)) + reference = ovstage.population.add_usd_reference_from_string(self.scene.stage, usd, f"/{scope}") + render_data.resources.callback(self._remove_usd_reference, reference) + ovstage.population.apply_usd_changes(self.scene.stage, ordinal=self.scene.ordinal) + + with self.scene.query([product_path]) as query: self.scene.stage.write_attribute( - render_data.xform_binding, - "omni:resetXformStack", + query, + "camera", ordinal=self.scene.ordinal, - tensors=np.full(num_envs, True, dtype=np.bool_), - is_array=False, + tensors=np.array( + [self.scene.paths.intern_path(path).raw_id for path in lidar_paths], + dtype=np.uint64, + ), + is_array=True, + semantic=ovstage.AttributeSemantic.RELATIONSHIP_PATH_ID, ).wait() - if lidar_partitions: - self.scene.stage.write_attribute( - render_data.xform_binding, - "omni:scenePartition", - ordinal=self.scene.ordinal, - tensors=np.array( - [self.scene.paths.intern_token(partition).raw_id for partition in lidar_partitions], - dtype=np.uint64, - ), - is_array=False, - semantic=ovstage.AttributeSemantic.TOKEN_ID, - ).wait() - else: - reference = self.backend.renderer.add_usd_reference_from_string(usd, f"/{scope}") - render_data.resources.callback(self.backend.renderer.remove_usd, reference) - - self.backend.renderer.write_array_attribute( - prim_paths=[product_path], - attribute_name="camera", - tensors=[lidar_paths], - ) + render_data.xform_binding = render_data.resources.enter_context(self.scene.query(lidar_paths)) - render_data.xform_binding = self.backend.renderer.bind_attribute( - prim_paths=lidar_paths, - attribute_name="omni:xform", - semantic=Semantic.XFORM_MAT4x4, - prim_mode=PrimMode.EXISTING_ONLY, - ) - render_data.resources.callback(render_data.xform_binding.unbind) - - self.backend.renderer.write_attribute( - prim_paths=lidar_paths, - attribute_name="omni:resetXformStack", - tensor=np.full(num_envs, True, dtype=np.bool_), - ) + self.scene.stage.write_attribute( + render_data.xform_binding, + "omni:resetXformStack", + ordinal=self.scene.ordinal, + tensors=np.full(num_envs, True, dtype=np.bool_), + is_array=False, + ).wait() - if lidar_partitions: - self.backend.renderer.write_attribute( - lidar_paths, - "omni:scenePartition", - lidar_partitions, - semantic=Semantic.TOKEN_STRING, - ) + if lidar_partitions: + self.scene.stage.write_attribute( + render_data.xform_binding, + "omni:scenePartition", + ordinal=self.scene.ordinal, + tensors=np.array( + [self.scene.paths.intern_token(partition).raw_id for partition in lidar_partitions], + dtype=np.uint64, + ), + is_array=False, + semantic=ovstage.AttributeSemantic.TOKEN_ID, + ).wait() - render_data.pose_writes = _AsyncWriteBuffers( - wp.empty(num_envs, wp.mat44d, device=self._device) for _ in range(1) - ) + render_data.pose_matrices = wp.empty(num_envs, wp.mat44d, device=self._device) except Exception: render_data.cleanup() raise @@ -1056,22 +920,14 @@ def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData) if delta_time <= 0.0: delta_time = _RENDER_DELTA_TIME - # The first step initializes GPU transforms from authored poses and must not advance any - # lidar clock. The capture itself includes only the lidar whose pose was just written. - products = {data.render_product_path for data in lidars} + # Capture only the lidar whose pose was just written. requested = {render_data.render_product_path} material_writer = self._visual_material_writer_ref() if self._visual_material_writer_ref is not None else None try: if material_writer is not None: material_writer.publish() - if self._needs_transform_initialization: - self.backend.renderer.step(render_products=products, delta_time=0.0) - self._needs_transform_initialization = False - if self._use_ovstage: - ordinal = self.scene.commit() - else: - result = self.backend.renderer.step(render_products=requested, delta_time=delta_time) + ordinal = self.scene.commit() finally: if material_writer is not None: primary_active = sys.exc_info()[0] is not None @@ -1082,8 +938,7 @@ def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData) raise logger.warning("Error draining material writes after a failed render: %s", exc, exc_info=True) - if self._use_ovstage: - result = self.backend.renderer.step(render_products=requested, delta_time=delta_time, ordinal=ordinal) + result = self.backend.renderer.step(render_products=requested, delta_time=delta_time, ordinal=ordinal) self._publish_lidar_output(render_data, result, lidar_data) @@ -1156,24 +1011,19 @@ def update_lidar( if binding is None: return stream = self._warp_device.stream - matrices = render_data.pose_writes.acquire(stream) + matrices = render_data.pose_matrices wp.launch( create_lidar_transforms_kernel, len(matrices), [positions, orientations, matrices], device=self._device ) - if self._use_ovstage: - self.scene.stage.write_attribute( - binding, - "omni:xform", - ordinal=self.scene.ordinal, - tensors=xform_tensor_from_warp(matrices), - is_array=False, - semantic=ovstage.AttributeSemantic.MATRIX, - cuda_stream=stream.cuda_stream or 1, - ).wait() - else: - operation = render_data.pose_writes.submit(binding, matrices, stream) - if not self.cfg.async_rendering: - operation.wait() + self.scene.stage.write_attribute( + binding, + "omni:xform", + ordinal=self.scene.ordinal, + tensors=xform_tensor_from_warp(matrices), + is_array=False, + semantic=ovstage.AttributeSemantic.MATRIX, + cuda_stream=stream.cuda_stream or 1, + ).wait() def cleanup_lidar(self, render_data: OVRTXLidarRenderData | None) -> None: """Release one lidar's native resources.""" @@ -1203,59 +1053,27 @@ def create_render_data(self, spec: CameraRenderSpec) -> OVRTXCameraRenderData: ) try: self._add_render_products(render_data, spec) - if self._use_ovstage: - render_data.camera_xform_binding = render_data.resources.enter_context(self.scene.query(camera_paths)) + render_data.camera_xform_binding = render_data.resources.enter_context(self.scene.query(camera_paths)) + self.scene.stage.write_attribute( + render_data.camera_xform_binding, + "omni:resetXformStack", + ordinal=self.scene.ordinal, + tensors=np.full(spec.num_instances, True, dtype=np.bool_), + is_array=False, + ).wait() + if camera_partitions: self.scene.stage.write_attribute( render_data.camera_xform_binding, - "omni:resetXformStack", + "omni:scenePartition", ordinal=self.scene.ordinal, - tensors=np.full(spec.num_instances, True, dtype=np.bool_), + tensors=np.array( + [self.scene.paths.intern_token(partition).raw_id for partition in camera_partitions], + dtype=np.uint64, + ), is_array=False, + semantic=ovstage.AttributeSemantic.TOKEN_ID, ).wait() - if camera_partitions: - self.scene.stage.write_attribute( - render_data.camera_xform_binding, - "omni:scenePartition", - ordinal=self.scene.ordinal, - tensors=np.array( - [self.scene.paths.intern_token(partition).raw_id for partition in camera_partitions], - dtype=np.uint64, - ), - is_array=False, - semantic=ovstage.AttributeSemantic.TOKEN_ID, - ).wait() - else: - render_data.camera_xform_binding = self.backend.renderer.bind_attribute( - prim_paths=camera_paths, - attribute_name="omni:xform", - semantic=Semantic.XFORM_MAT4x4, - prim_mode=PrimMode.EXISTING_ONLY, - ) - render_data.resources.callback(render_data.camera_xform_binding.unbind) - self.backend.renderer.write_attribute( - prim_paths=camera_paths, - attribute_name="omni:resetXformStack", - tensor=np.full(spec.num_instances, True, dtype=np.bool_), - ) - if camera_partitions: - self.backend.renderer.write_attribute( - camera_paths, - "omni:scenePartition", - camera_partitions, - semantic=Semantic.TOKEN_STRING, - ) - render_data.camera_writes = _AsyncWriteBuffers( - wp.empty(spec.num_instances, wp.mat44d, device=self._device) - for _ in range(2 if self.cfg.async_rendering and not self._use_ovstage else 1) - ) - if not self._use_ovstage: - for name in _CAMERA_INTRINSIC_ATTRIBUTES: - binding = self.backend.renderer.bind_attribute( - prim_paths=camera_paths, attribute_name=name, dtype="float32", - prim_mode=PrimMode.EXISTING_ONLY, flags=BindingFlag.OPTIMIZE, - ) # fmt: skip - render_data.resources.callback(binding.unbind) - render_data.intrinsic_bindings.append(binding) + render_data.camera_matrices = wp.empty(spec.num_instances, wp.mat44d, device=self._device) except Exception: render_data.cleanup() raise @@ -1279,48 +1097,17 @@ def set_outputs(self, render_data: OVRTXCameraRenderData, output_data: dict[str, name: proxy.warp for name, proxy in output_data.items() if name != str(RenderBufferKind.RGB) } - def prepare_capture(self, render_data: OVRTXCameraRenderData, camera_data: CameraData, frame: ProxyArray) -> None: - """Snapshot delayed-image metadata without changing live camera state.""" - if self.cfg.async_rendering and not self._use_ovstage: - render_data.capture = { - name: ProxyArray(wp.clone(value.warp)) - for name, value in ( - ("pos_w", camera_data.pos_w), - ("quat_w_world", camera_data.quat_w_world), - ("intrinsic_matrices", camera_data.intrinsic_matrices), - ("frame", frame), - ) - } - def read_output( self, render_data: OVRTXCameraRenderData, camera_data: CameraData | None = None, ) -> None: """Publish the pixels of the render products of this sensor, and copy matching metadata when requested.""" - if self.cfg.async_rendering and not self._use_ovstage and render_data.ready is None: - return - capture = {} - if render_data.ready is not None: - operation, capture = render_data.ready - if capture is None: - render_data.ready = None - return - try: - result = operation.wait().fetch() - except Exception as error: - self._note_failed_frame(error) - raise - self._process_render_products((render_data,), result) - if render_data.ready is render_data.pending: - # Retain the native operation, but do not publish this priming image twice. - render_data.pending = (operation, None) - render_data.ready = None if camera_data is not None: assert camera_data.info is not None, "CameraData.info should be created in CameraData.allocate" for output_name in camera_data.info: info = render_data.renderer_info.get(output_name) - camera_data.info[output_name] = {**(info or {}), "capture": capture} if capture else info + camera_data.info[output_name] = info @contextlib.contextmanager def _map_render_var_to_dlpack(self, render_var: RenderVarOutput) -> Iterator[wp.array]: @@ -1646,19 +1433,6 @@ def _process_render_frame( with self._map_render_var_to_dlpack(motion_var) as tiled_motion_vectors_data: self._launch_extract_all_tiles(render_data, tiled_motion_vectors_data, output_buffers["motion_vectors"]) - def drain_pending_renders(self, cameras: Sequence[OVRTXCameraRenderData] | None = None) -> list[Exception]: - """Complete native work without publishing observations into any camera.""" - cameras = self._camera_render_data if cameras is None else cameras - operations = {frame[0] for data in cameras for frame in (data.pending, data.ready) if frame is not None} - errors = [] - for operation in operations: - try: - operation.wait().fetch() - except Exception as error: - self._note_failed_frame(error) - errors.append(error) - return errors - def _note_failed_frame(self, error: Exception, num_smaller_layouts: int = 0) -> None: """Add a note about render product splits to an error about a failed frame. @@ -1691,19 +1465,6 @@ def _note_failed_frame(self, error: Exception, num_smaller_layouts: int = 0) -> note += f" Camera sensors with several environments in one render product: {', '.join(cameras)}." error.add_note(note) - def reset(self, render_data: OVRTXCameraRenderData, env_ids: Sequence[int] | None = None) -> None: - """Retire pre-reset frames. The next capture primes every tiled render product of this sensor. - - Pending captures cover every environment tile, so they are not separable per environment - and ``env_ids`` is not consulted. - """ - del env_ids - errors = self.drain_pending_renders((render_data,)) - render_data.pending = render_data.ready = None - render_data.capture = {} - if errors: - raise ExceptionGroup("OVRTX renders failed during camera reset", errors) - def _process_render_products( self, render_data: Sequence[OVRTXCameraRenderData], products: RenderProductSetOutputs ) -> None: @@ -1786,7 +1547,7 @@ def _hide_environment_bodies(self, matrices: wp.array, stream: wp.Stream) -> wp. return matrices body_envs = self._body_environment_ids() # A published buffer may be shared with other consumers, so hidden poses are written to a copy. The copy is - # kept per source buffer: an asynchronous write still reads it until the source buffer is acquired again. + # kept per source buffer so visibility overrides do not alter the shared SDP publication. hidden = self._hidden_matrices.get(matrices.ptr) if hidden is None or len(hidden) != len(matrices): hidden = self._hidden_matrices[matrices.ptr] = wp.empty(len(matrices), dtype=wp.mat44d, device=self._device) @@ -1808,27 +1569,21 @@ def update_transforms(self) -> None: if self._transforms_timestamp == timestamp: return stream = self._warp_device.stream - asynchronous = self.cfg.async_rendering and not self._use_ovstage - output = self._transform_writes.acquire(stream) - if not self._sdp.get_transforms(output, allow_passthrough=not asynchronous, scales=self._object_scales): + output = self._transform_buffer + if not self._sdp.get_transforms(output, allow_passthrough=True, scales=self._object_scales): return matrices = self._hide_environment_bodies(output.matrices, stream) - if self._use_ovstage: - # The write waits for consumption; the producing CUDA stream orders access to the - # borrowed buffer. - self.scene.stage.write_attribute( - binding, - "omni:xform", - ordinal=self.scene.ordinal, - tensors=xform_tensor_from_warp(matrices), - is_array=False, - semantic=ovstage.AttributeSemantic.MATRIX, - cuda_stream=stream.cuda_stream or 1, - ).wait() - elif asynchronous: - self._transform_writes.submit(binding, matrices, stream) - else: - binding.write(matrices, data_access=DataAccess.ASYNC, cuda_stream=stream.cuda_stream or 1) + # The write waits for consumption; the producing CUDA stream orders access to the + # borrowed buffer. + self.scene.stage.write_attribute( + binding, + "omni:xform", + ordinal=self.scene.ordinal, + tensors=xform_tensor_from_warp(matrices), + is_array=False, + semantic=ovstage.AttributeSemantic.MATRIX, + cuda_stream=stream.cuda_stream or 1, + ).wait() self._transforms_timestamp = timestamp def update_geometries(self) -> None: @@ -1851,32 +1606,20 @@ def update_geometries(self) -> None: if binding is None: return stream = self._warp_device.stream - asynchronous = self.cfg.async_rendering and not self._use_ovstage - if asynchronous: - output = self._geometry_writes.acquire(stream) - self._sdp.get_geometry_points(output=output, offsets=self._geometry_offsets) - offsets = list(self._geometry_offsets.values()) - points = [output[start:end] for start, end in zip(offsets, [*offsets[1:], len(output)], strict=True)] - else: - points = self._sdp.get_geometry_points() - points = [points[path] for path in self._geometry_paths] + points = self._sdp.get_geometry_points() + points = [points[path] for path in self._geometry_paths] timestamp = self._sdp.backend.geometry_timestamp if self._geometry_timestamp == timestamp: return - if self._use_ovstage: - self.scene.stage.write_attribute( - binding, - "points", - ordinal=self.scene.ordinal, - tensors=[points_tensor_from_warp(array) for array in points], - is_array=True, - semantic=ovstage.AttributeSemantic.POINT, - cuda_stream=stream.cuda_stream or 1, - ).wait() - elif asynchronous: - self._geometry_writes.submit(binding, points, stream) - else: - binding.write(points, data_access=DataAccess.ASYNC, cuda_stream=stream.cuda_stream or 1) + self.scene.stage.write_attribute( + binding, + "points", + ordinal=self.scene.ordinal, + tensors=[points_tensor_from_warp(array) for array in points], + is_array=True, + semantic=ovstage.AttributeSemantic.POINT, + cuda_stream=stream.cuda_stream or 1, + ).wait() self._geometry_timestamp = timestamp def update_camera( @@ -1891,52 +1634,31 @@ def update_camera( if binding is None: return stream = self._warp_device.stream - matrices = render_data.camera_writes.acquire(stream) + matrices = render_data.camera_matrices wp.launch( create_camera_transforms_kernel, len(matrices), [positions, orientations, matrices], device=self._device ) - if self._use_ovstage: - self.scene.stage.write_attribute( - binding, - "omni:xform", - ordinal=self.scene.ordinal, - tensors=xform_tensor_from_warp(matrices), - is_array=False, - semantic=ovstage.AttributeSemantic.MATRIX, - cuda_stream=stream.cuda_stream or 1, - ).wait() - else: - operation = render_data.camera_writes.submit(binding, matrices, stream) - if not self.cfg.async_rendering: - operation.wait() + self.scene.stage.write_attribute( + binding, + "omni:xform", + ordinal=self.scene.ordinal, + tensors=xform_tensor_from_warp(matrices), + is_array=False, + semantic=ovstage.AttributeSemantic.MATRIX, + cuda_stream=stream.cuda_stream or 1, + ).wait() def update_camera_intrinsics(self, render_data: OVRTXCameraRenderData, intrinsics: wp.array, parameters: wp.array): - """Publish calibration columns from GPU memory into the renderer-owned scene.""" - # A runtime calibration change is a scene write for this camera's bindings, so its - # in-flight renders must finish first. Other cameras keep their pipelines. - errors = self.drain_pending_renders((render_data,)) - if errors: - raise ExceptionGroup("OVRTX renders failed before calibration update", errors) + """Publish calibration columns from GPU memory into OvStage.""" stream = wp.get_stream(parameters.device).cuda_stream or 1 - if self._use_ovstage: - self.scene.stage.write_attributes( - render_data.camera_xform_binding, - [ - ovstage.WriteDesc(attribute=name, tensors=parameters[row], is_array=False, cuda_stream=stream) - for row, name in enumerate(_CAMERA_INTRINSIC_ATTRIBUTES) - ], - ordinal=self.scene.ordinal, - ).wait() - else: - operations = [] - try: - for row, binding in enumerate(render_data.intrinsic_bindings): - operations.append( - binding.write_async(parameters[row], data_access=DataAccess.ASYNC, cuda_stream=stream) - ) - finally: - for operation in operations: - operation.wait() + self.scene.stage.write_attributes( + render_data.camera_xform_binding, + [ + ovstage.WriteDesc(attribute=name, tensors=parameters[row], is_array=False, cuda_stream=stream) + for row, name in enumerate(_CAMERA_INTRINSIC_ATTRIBUTES) + ], + ordinal=self.scene.ordinal, + ).wait() def render(self, render_data: OVRTXCameraRenderData) -> None: """Submit one camera capture; :meth:`read_output` publishes the available image.""" @@ -2071,65 +1793,42 @@ def _copy_render_product_attributes(self, source: str, targets: Sequence[str]) - The copy also writes the attributes that nobody changed. The runtime reports no difference between an authored value and a schema default, so the copy cannot leave these out. """ - if self._use_ovstage: - stage, paths = self.scene.stage, self.scene.paths - writes = [] - # The prims of the failed layout and their settings are sealed, because the failed step committed them. - everything = ovstage.OrdinalRange.latest(ovstage.ORDINAL_MAX) - with ( - self.scene.query([source]) as query, - stage.read_attributes(query, [paths.intern_token("*")], everything) as read, - ): - for group in read.groups(): - with group: - for column in group.columns: - if paths.token_to_string(column.attribute) in _PER_PRODUCT_ATTRIBUTES: - continue - # Each host copy holds the data row of the source prim. DLPack keeps a half as float16. - row = column.data_row_index(0) - if column.is_array: - # A read gives the components of each element as an axis, but an array write takes - # them only as lanes. Without the conversion, a float3[] arrives as a float[]. - value = np.array(np.from_dlpack(column.dlpack(row))) - tensors = [ovstage.typed_tensor_to_write(ovstage.make_dltensor(value))] - else: - tensors = np.array(np.from_dlpack(column.dlpack(0))[row : row + 1]) - writes.append( - ovstage.WriteDesc( - column.attribute, - tensors, - column.is_array, - index_map=[0] * len(targets), - semantic=column.semantic, - ) + stage, paths = self.scene.stage, self.scene.paths + writes = [] + # The prims of the failed layout and their settings are sealed, because the failed step committed them. + everything = ovstage.OrdinalRange.latest(ovstage.ORDINAL_MAX) + with ( + self.scene.query([source]) as query, + stage.read_attributes(query, [paths.intern_token("*")], everything) as read, + ): + for group in read.groups(): + with group: + for column in group.columns: + if paths.token_to_string(column.attribute) in _PER_PRODUCT_ATTRIBUTES: + continue + # Each host copy holds the data row of the source prim. DLPack keeps a half as float16. + row = column.data_row_index(0) + if column.is_array: + # A read gives the components of each element as an axis, but an array write takes + # them only as lanes. Without the conversion, a float3[] arrives as a float[]. + value = np.array(np.from_dlpack(column.dlpack(row))) + tensors = [ovstage.typed_tensor_to_write(ovstage.make_dltensor(value))] + else: + tensors = np.array(np.from_dlpack(column.dlpack(0))[row : row + 1]) + writes.append( + ovstage.WriteDesc( + column.attribute, + tensors, + column.is_array, + index_map=[0] * len(targets), + semantic=column.semantic, ) - # A write that adds attributes to the targets can change the borrowed data of an open read. So the copy - # writes the host copies after the release. - if writes: - with self.scene.query(targets) as query: - stage.write_attributes(query, writes, ordinal=self.scene.ordinal).wait() - else: - renderer = self.backend.renderer - render_products = renderer.query_prims( - require_all=[(FilterKind.PRIM_TYPE, "RenderProduct")], attribute_filter_mode=AttributeFilterMode.ALL - ) - for name, info in render_products[source].items(): - # A tag is the name of an applied schema and has no value. - if name in _PER_PRODUCT_ATTRIBUTES or info.semantic == Semantic.TAG: - continue - if info.is_array: - try: - (value,) = renderer.read_array_attribute(name, [source]).values() - except RuntimeError: - # OVRTX raises for an array without elements. - # The new render products then keep their own value. - continue - renderer.write_array_attribute(list(targets), name, [value] * len(targets), semantic=info.semantic) - else: - value = np.from_dlpack(renderer.read_attribute(name, [source])) - renderer.write_attribute( - list(targets), name, np.repeat(value, len(targets), axis=0), semantic=info.semantic - ) + ) + # A write that adds attributes to the targets can change the borrowed data of an open read. So the copy + # writes the host copies after the release. + if writes: + with self.scene.query(targets) as query: + stage.write_attributes(query, writes, ordinal=self.scene.ordinal).wait() def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> None: """Render one step with every registered render product, and read back the images of ``render_data``.""" @@ -2138,32 +1837,7 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No try: if material_writer is not None: material_writer.publish() - if self._needs_transform_initialization: - # OVRTX 0.6 initializes GPU world transforms on its first step using - # authored poses. Flush that initialization before capturing runtime - # camera poses, without advancing the sensor simulation clock. - self.backend.renderer.step(render_products=products, delta_time=0.0) - self._needs_transform_initialization = False - if self._use_ovstage: - ordinal = self.scene.commit() - elif self.cfg.async_rendering: - unread = {data.ready[0] for data in render_data if data.ready is not None} - operation = self.backend.renderer.step_async(render_products=products, delta_time=_RENDER_DELTA_TIME) - if self.backend.unrendered: - # The wait happens only until every sensor on the engine has a rendered frame. - # A failed frame then raises here, before a camera stores the failed operation. - # Only render_batch can replace the failed render products, so the error must raise in it. - operation.wait() - for data in render_data: - previous = data.pending - data.pending = (operation, data.capture) - data.ready = previous if previous is not None else data.pending - # Repeated submissions may replace unread results, but must still complete them. - for previous in unread: - previous.wait().fetch() - else: - result = self.backend.renderer.step(render_products=products, delta_time=_RENDER_DELTA_TIME) - self._process_render_products(render_data, result) + ordinal = self.scene.commit() finally: if material_writer is not None: # When another exception is already propagating, log the drain failure instead of @@ -2176,13 +1850,10 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No raise logger.warning("Error draining material writes after a failed render: %s", e, exc_info=True) - if self._use_ovstage: - # Stage writes and material reads finish before rendering. Consume only after advancing - # the ordinal so a failed readback cannot leave later writes at the sealed floor. - result = self.backend.renderer.step( - render_products=products, delta_time=_RENDER_DELTA_TIME, ordinal=ordinal - ) - self._process_render_products(render_data, result) + # Stage writes and material reads finish before rendering. Consume only after advancing + # the ordinal so a failed readback cannot leave later writes at the sealed floor. + result = self.backend.renderer.step(render_products=products, delta_time=_RENDER_DELTA_TIME, ordinal=ordinal) + self._process_render_products(render_data, result) def cleanup(self, render_data: OVRTXCameraRenderData | None) -> None: """Release the render data's buffers. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.cleanup`. @@ -2193,13 +1864,10 @@ def cleanup(self, render_data: OVRTXCameraRenderData | None) -> None: if render_data is None: return try: - self.reset(render_data) + render_data.cleanup() finally: - try: - render_data.cleanup() - finally: - if render_data in self._camera_render_data: - self._camera_render_data.remove(render_data) + if render_data in self._camera_render_data: + self._camera_render_data.remove(render_data) def _add_render_products(self, render_data: OVRTXCameraRenderData, spec: CameraRenderSpec) -> None: """Add the render products of ``render_data`` to the scene, and render them in every later step.""" @@ -2208,38 +1876,24 @@ def _add_render_products(self, render_data: OVRTXCameraRenderData, spec: CameraR spec, render_data, device_id=self._warp_device.ordinal, enable_shadows=self.cfg.enable_shadows ) # Registration mutates the shared scene; finish renders using its existing products first. - errors = self.drain_pending_renders() - if errors: - raise ExceptionGroup("OVRTX renders failed before render product registration", errors) if self.cfg.temp_usd_dir is not None: _write_combined_stage(Path(self.cfg.temp_usd_dir), usd) - if self._use_ovstage: - reference = ovstage.population.add_usd_reference_from_string(self.scene.stage, usd, f"/{scope}") - render_data.resources.callback(self._remove_usd_reference, reference) - ovstage.population.apply_usd_changes(self.scene.stage, ordinal=self.scene.ordinal) - # USD references drop external camera targets; author the relationship in Fabric. - for product in render_data.products: - with self.scene.query([product.path]) as query: - self.scene.stage.write_attribute( - query, - "camera", - ordinal=self.scene.ordinal, - tensors=np.array( - [self.scene.paths.intern_path(p).raw_id for p in product.camera_paths], dtype=np.uint64 - ), - is_array=True, - semantic=ovstage.AttributeSemantic.RELATIONSHIP_PATH_ID, - ).wait() - else: - reference = self.backend.renderer.add_usd_reference_from_string(usd, f"/{scope}") - render_data.resources.callback(self.backend.renderer.remove_usd, reference) - # One camera write for several products can give them wrong images, so write each product on its own. - for product in render_data.products: - self.backend.renderer.write_array_attribute( - prim_paths=[product.path], - attribute_name="camera", - tensors=[product.camera_paths], - ) + reference = ovstage.population.add_usd_reference_from_string(self.scene.stage, usd, f"/{scope}") + render_data.resources.callback(self._remove_usd_reference, reference) + ovstage.population.apply_usd_changes(self.scene.stage, ordinal=self.scene.ordinal) + # USD references drop external camera targets; author the relationship in Fabric. + for product in render_data.products: + with self.scene.query([product.path]) as query: + self.scene.stage.write_attribute( + query, + "camera", + ordinal=self.scene.ordinal, + tensors=np.array( + [self.scene.paths.intern_path(p).raw_id for p in product.camera_paths], dtype=np.uint64 + ), + is_array=True, + semantic=ovstage.AttributeSemantic.RELATIONSHIP_PATH_ID, + ).wait() for path in render_data.render_product_paths: self.backend.render_products.add(path) render_data.resources.callback(self.backend.render_products.discard, path) @@ -2254,8 +1908,6 @@ def close(self) -> None: try: with contextlib.ExitStack() as resources: resources.callback(self._bindings.close) - resources.callback(self._transform_writes.close) - resources.callback(self._geometry_writes.close) resources.callback(self.geometry_resources.close) for geometry in (*self.meshes.values(), *self.markers.values()): resources.callback(geometry.close) @@ -2266,8 +1918,7 @@ def close(self) -> None: finally: self._object_xform_binding = self._geometry_points_binding = None self._object_scales = None - self._transform_writes = _AsyncWriteBuffers(SceneDataFormat.TransposedMatrix44d() for _ in range(2)) - self._geometry_offsets.clear() + self._transform_buffer = SceneDataFormat.TransposedMatrix44d() self._geometry_paths = [] self._geometry_timestamp = -1 self._transforms_timestamp = -1 @@ -2312,9 +1963,6 @@ def update( ) -> None: """Publish GPU geometry and apply explicitly supplied appearance changes.""" indices = indices.view(wp.int32) - errors = self.renderer.drain_pending_renders() - if errors: - raise ExceptionGroup("OVRTX renders failed before mesh update", errors) if normals is None: if self._normals is None or len(self._normals) != len(points): self._normals = wp.empty_like(points) @@ -2395,14 +2043,10 @@ def update( sampler.CreateInput("scale", Sdf.ValueTypeNames.Float4).Set((*appearance[1], 1.0)) self._native_resources.close() usd = self.stage.GetRootLayer().ExportToString() - if self.renderer._use_ovstage: - reference = ovstage.population.add_usd_reference_from_string(self.renderer.scene.stage, usd, self.path) - self._native_resources.callback(self.renderer._remove_usd_reference, reference) - ovstage.population.apply_usd_changes(self.renderer.scene.stage, ordinal=self.renderer.scene.ordinal) - self.query = self._native_resources.enter_context(self.renderer.scene.query([self.path])) - else: - reference = self.renderer.backend.renderer.add_usd_reference_from_string(usd, self.path) - self._native_resources.callback(self.renderer.backend.renderer.remove_usd, reference) + reference = ovstage.population.add_usd_reference_from_string(self.renderer.scene.stage, usd, self.path) + self._native_resources.callback(self.renderer._remove_usd_reference, reference) + ovstage.population.apply_usd_changes(self.renderer.scene.stage, ordinal=self.renderer.scene.ordinal) + self.query = self._native_resources.enter_context(self.renderer.scene.query([self.path])) attributes = {"points": points, "normals": normals} if uvs is not None: attributes["primvars:st"] = uvs @@ -2410,52 +2054,39 @@ def update( attributes.update(faceVertexIndices=indices, faceVertexCounts=self._face_counts) stream = wp.get_stream(points.device).cuda_stream or 1 for name, values in attributes.items(): - if self.renderer._use_ovstage: - semantic = { - "points": ovstage.AttributeSemantic.POINT, - "normals": ovstage.AttributeSemantic.NORMAL, - "primvars:st": ovstage.AttributeSemantic.TEXTURE_COORDINATE, - }.get(name, ovstage.AttributeSemantic.NONE) - if name in ("points", "normals"): - values = points_tensor_from_warp(values) - elif name == "primvars:st": - values = ovstage.make_dltensor( - values, dtype=ovstage.DLDataType(code=ovstage.DLDataTypeCode.kDLFloat, bits=32, lanes=2) - ) - self.renderer.scene.stage.write_attribute( - self.query, - name, - ordinal=self.renderer.scene.ordinal, - tensors=[values], - is_array=True, - semantic=semantic, - cuda_stream=stream, - ).wait() - else: - self.renderer.backend.renderer.write_array_attribute( - [self.path], name, [values], data_access=DataAccess.ASYNC, cuda_stream=stream + semantic = { + "points": ovstage.AttributeSemantic.POINT, + "normals": ovstage.AttributeSemantic.NORMAL, + "primvars:st": ovstage.AttributeSemantic.TEXTURE_COORDINATE, + }.get(name, ovstage.AttributeSemantic.NONE) + if name in ("points", "normals"): + values = points_tensor_from_warp(values) + elif name == "primvars:st": + values = ovstage.make_dltensor( + values, dtype=ovstage.DLDataType(code=ovstage.DLDataTypeCode.kDLFloat, bits=32, lanes=2) ) - token = "invisible" if hidden or not len(points) else "inherited" - if self.renderer._use_ovstage: self.renderer.scene.stage.write_attribute( self.query, - "visibility", + name, ordinal=self.renderer.scene.ordinal, - tensors=np.array([self.renderer.scene.paths.intern_token(token).raw_id], dtype=np.uint64), - is_array=False, - semantic=ovstage.AttributeSemantic.TOKEN_ID, + tensors=[values], + is_array=True, + semantic=semantic, + cuda_stream=stream, ).wait() - else: - self.renderer.backend.renderer.write_attribute( - [self.path], "visibility", [token], semantic=Semantic.TOKEN_STRING - ) + token = "invisible" if hidden or not len(points) else "inherited" + self.renderer.scene.stage.write_attribute( + self.query, + "visibility", + ordinal=self.renderer.scene.ordinal, + tensors=np.array([self.renderer.scene.paths.intern_token(token).raw_id], dtype=np.uint64), + is_array=False, + semantic=ovstage.AttributeSemantic.TOKEN_ID, + ).wait() def close(self) -> None: """Release the mesh reference while the shared renderer remains alive.""" - with self.resources: - errors = self.renderer.drain_pending_renders() - if errors: - raise ExceptionGroup("OVRTX renders failed before mesh cleanup", errors) + self.resources.close() class OVRTXMarkers: @@ -2513,9 +2144,6 @@ def update( token = "inherited" if visible else "invisible" UsdGeom.Imageable(self._stage.GetDefaultPrim()).GetVisibilityAttr().Set(token) if indices != self._layout: - errors = renderer.drain_pending_renders() - if errors: - raise ExceptionGroup("OVRTX renders failed before marker geometry update", errors) self._resources.close() self._stage.RemovePrim("/Markers/Instances") self._local_transforms = wp.array( @@ -2532,39 +2160,24 @@ def update( if indices: usd = self._stage.GetRootLayer().ExportToString() with self._resources: - if renderer._use_ovstage: - reference = ovstage.population.add_usd_reference_from_string( - renderer.scene.stage, usd, self._path - ) - self._resources.callback(renderer._remove_usd_reference, reference) - ovstage.population.apply_usd_changes(renderer.scene.stage, ordinal=renderer.scene.ordinal) - self._root_query = self._resources.enter_context(renderer.scene.query([self._path])) - self._query = self._resources.enter_context(renderer.scene.query(paths)) - else: - reference = renderer.backend.renderer.add_usd_reference_from_string(usd, self._path) - self._resources.callback(renderer.backend.renderer.remove_usd, reference) - self._binding = renderer.backend.renderer.bind_attribute( - paths, "omni:xform", semantic=Semantic.XFORM_MAT4x4 - ) - self._resources.callback(self._binding.unbind) + reference = ovstage.population.add_usd_reference_from_string(renderer.scene.stage, usd, self._path) + self._resources.callback(renderer._remove_usd_reference, reference) + ovstage.population.apply_usd_changes(renderer.scene.stage, ordinal=renderer.scene.ordinal) + self._root_query = self._resources.enter_context(renderer.scene.query([self._path])) + self._query = self._resources.enter_context(renderer.scene.query(paths)) self._resources = self._resources.pop_all() self._layout = indices if not indices: return if visible != self._visible: - if renderer._use_ovstage: - renderer.scene.stage.write_attribute( - self._root_query, - "visibility", - ordinal=renderer.scene.ordinal, - tensors=np.array([renderer.scene.paths.intern_token(token).raw_id], dtype=np.uint64), - is_array=False, - semantic=ovstage.AttributeSemantic.TOKEN_ID, - ).wait() - else: - renderer.backend.renderer.write_attribute( - [self._path], "visibility", [token], semantic=Semantic.TOKEN_STRING - ) + renderer.scene.stage.write_attribute( + self._root_query, + "visibility", + ordinal=renderer.scene.ordinal, + tensors=np.array([renderer.scene.paths.intern_token(token).raw_id], dtype=np.uint64), + is_array=False, + semantic=ovstage.AttributeSemantic.TOKEN_ID, + ).wait() self._visible = visible stream = wp.stream_from_torch(torch.cuda.current_stream(translations.device)) wp.launch( @@ -2581,66 +2194,21 @@ def update( device=renderer._device, stream=stream, ) - if renderer._use_ovstage: - renderer.scene.stage.write_attribute( - self._query, - "omni:xform", - ordinal=renderer.scene.ordinal, - tensors=xform_tensor_from_warp(self._transforms), - is_array=False, - semantic=ovstage.AttributeSemantic.MATRIX, - cuda_stream=stream.cuda_stream or 1, - ).wait() - else: - self._binding.write(self._transforms, data_access=DataAccess.ASYNC, cuda_stream=stream.cuda_stream or 1) + renderer.scene.stage.write_attribute( + self._query, + "omni:xform", + ordinal=renderer.scene.ordinal, + tensors=xform_tensor_from_warp(self._transforms), + is_array=False, + semantic=ovstage.AttributeSemantic.MATRIX, + cuda_stream=stream.cuda_stream or 1, + ).wait() def close(self) -> None: """Release bindings and geometry before the renderer's native scene closes.""" if self._renderer is None: return - renderer, self._renderer = self._renderer, None - with self._resources: - errors = renderer.drain_pending_renders() - if errors: - raise ExceptionGroup("OVRTX renders failed before marker cleanup", errors) + self._renderer = None + self._resources.close() self._transforms = self._selection = self._stage = None self._local_transforms = None - - -_BufferT = TypeVar("_BufferT", wp.array, SceneDataFormat.TransposedMatrix44d) - - -class _AsyncWriteBuffers(Generic[_BufferT]): - """Retain GPU buffers until native writes finish; reuse them in submission order.""" - - def __init__(self, buffers: Iterable[_BufferT] = ()): - self._writes: deque[tuple[_BufferT, Operation[bool] | None, wp.Stream | None]] = deque( - (buffer, None, None) for buffer in buffers - ) - - def acquire(self, stream: wp.Stream) -> _BufferT: - """Wait until the next buffer is writable on the given stream.""" - buffer, operation, producer = self._writes[0] - if operation is not None: - operation.wait() - if producer != stream: - stream.wait_stream(producer) - return buffer - - def submit( - self, binding: AttributeBinding, values: wp.array | list[wp.array], stream: wp.Stream - ) -> Operation[bool]: - """Submit a write and retain its inputs; a failed submission does not advance the buffers.""" - operation = binding.write_async(values, data_access=DataAccess.ASYNC, cuda_stream=stream.cuda_stream or 1) - self._writes[0] = (self._writes[0][0], operation, stream) - self._writes.rotate(-1) - return operation - - def close(self) -> None: - """Complete every pending write before releasing storage, including on failure.""" - with contextlib.ExitStack() as writes: - writes.callback(self._writes.clear) - for _, operation, producer in self._writes: - if operation is not None: - writes.callback(wp.synchronize_stream, producer) - writes.callback(operation.wait) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py index 80f3e0c90272..4d7196a879ea 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py @@ -35,8 +35,6 @@ class OVRTXBackendCfg(BackendCfg): # FIXME: revert once OVRTX stops warning on every cloned attribute without data. log_level: str = "error" """Native renderer log level.""" - use_ovstage: bool = MISSING - """Whether the engine borrows a simulation-owned OVStage instead of using its internal stage.""" read_gpu_transforms: bool = MISSING """Whether OVRTX reads its GPU transform cache, resolved before native construction.""" device: str = MISSING @@ -66,16 +64,12 @@ class OVRTXRendererCfg(RendererCfg): """The launcher that registers the OVRTX runtime before the stage is created.""" cloning_contexts: tuple[type | str, ...] = ("isaaclab_ov.cloner:OvrtxReplicateContext",) - """Request native OVRTX copies; clone preparation may select a shared OVStage instead.""" + """Route scene copies through OvStage; sharing with OvPhysX is optional.""" async_rendering: bool = False - """Trade one capture of camera latency for pipelined rendering. Defaults to False (synchronous). + """Compatibility option; OvStage always renders synchronously. - Each camera returns its previous capture while rendering its next image. The first capture - and the first capture after reset wait for a fresh image. Live pose and calibration fields - stay current. ``camera.data.info[output_name]["capture"]`` carries the image's matching - ``pos_w``, ``quat_w_world``, ``intrinsic_matrices``, and per-environment ``frame`` indices. - The ovstage path does not support pipelining and renders synchronously. + Setting this to True logs a warning and uses synchronous rendering. """ max_envs_per_render_product: int | Literal["auto", "all"] = "auto" diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/visual_materials.py b/source/isaaclab_ov/isaaclab_ov/renderers/visual_materials.py index 3138cf964e8a..4191788c8db2 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/visual_materials.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/visual_materials.py @@ -15,7 +15,6 @@ import torch import warp as wp -from ovrtx import BindingFlag, DataAccess, PrimMode if TYPE_CHECKING: from isaaclab.renderers.base_renderer import VisualMaterialBatch @@ -39,11 +38,9 @@ def __init__(self, renderer: OVRTXRenderer, batches: tuple[VisualMaterialBatch, device = None for batch in batches: values = batch.values.detach() - if values.dtype == torch.float32 and values.ndim == 1: - dtype, shape = "float32", None - elif values.dtype == torch.float32 and values.ndim == 2 and values.shape[1] in (2, 3): - dtype, shape = "float32", (values.shape[1],) - else: + if values.dtype != torch.float32 or not ( + values.ndim == 1 or (values.ndim == 2 and values.shape[1] in (2, 3)) + ): raise TypeError( f"OVRTX visual-material channel {batch.channel!r} requires float, float2, or float3; " f"got dtype={values.dtype}, shape={tuple(values.shape)}." @@ -56,26 +53,13 @@ def __init__(self, renderer: OVRTXRenderer, batches: tuple[VisualMaterialBatch, for input_name, input_group in itertools.groupby(batch.input_names): end = start + sum(1 for _ in input_group) rows = slice(start, end) - groups.append( - (batch.channel, f"inputs:{input_name}", list(batch.shader_paths[rows]), rows, dtype, shape) - ) + groups.append((batch.channel, f"inputs:{input_name}", list(batch.shader_paths[rows]), rows)) start = end self._device = str(device) self._event = wp.Event(device=self._device) with contextlib.ExitStack() as resources: - for channel, attribute_name, shader_paths, rows, dtype, shape in groups: - if renderer._use_ovstage: - address = resources.enter_context(renderer.scene.query(shader_paths)) - else: - address = renderer.backend.renderer.bind_attribute( - prim_paths=shader_paths, - attribute_name=attribute_name, - dtype=dtype, - shape=shape, - prim_mode=PrimMode.EXISTING_ONLY, - flags=BindingFlag.OPTIMIZE, - ) - resources.callback(address.unbind) + for channel, attribute_name, shader_paths, rows in groups: + address = resources.enter_context(renderer.scene.query(shader_paths)) self._addresses.append((channel, address, attribute_name, rows)) self._resources = resources.pop_all() @@ -97,26 +81,14 @@ def publish(self) -> None: for channel, address, attribute_name, rows in self._addresses: if channel not in channels: continue - if renderer._use_ovstage: - operation = renderer.scene.stage.write_attribute( - address, - attribute_name, - ordinal=renderer.scene.ordinal, - tensors=self._buffers[channel][rows], - is_array=False, - cuda_event=self._event.cuda_event, - ) - else: - # The event orders the read after the producers (access sync). The stream - # receives the done fence: work later enqueued on it waits for the read, so - # the next refill of these zero-copy buffers cannot race it. Fills and - # refills run on this device's current Warp stream. - operation = address.write_async( - self._buffers[channel][rows], - data_access=DataAccess.ASYNC, - cuda_event=self._event.cuda_event, - cuda_stream=wp.get_stream(self._device).cuda_stream or 1, - ) + operation = renderer.scene.stage.write_attribute( + address, + attribute_name, + ordinal=renderer.scene.ordinal, + tensors=self._buffers[channel][rows], + is_array=False, + cuda_event=self._event.cuda_event, + ) operations.append(operation) finally: self._operations = tuple(operations) @@ -142,14 +114,7 @@ def close(self) -> None: """Drain writes and release every compiled backend address.""" try: with self._resources: - try: - self.drain() - finally: - renderer = self._renderer_ref() - if renderer is not None: - # A render may still read these bindings when RenderContext closes its writers. - for error in renderer.drain_pending_renders(): - logger.warning("Error draining in-flight render before material release: %s", error) + self.drain() finally: self._addresses.clear() self._dirty_channels.clear() diff --git a/source/isaaclab_ov/test/test_ovrtx_clone_plan.py b/source/isaaclab_ov/test/test_ovrtx_clone_plan.py index 0b957af6a5d5..bd0c6fa03fd8 100644 --- a/source/isaaclab_ov/test/test_ovrtx_clone_plan.py +++ b/source/isaaclab_ov/test/test_ovrtx_clone_plan.py @@ -37,9 +37,7 @@ if not _MISSING_MODULES: from isaaclab_ov.cloner import ( # noqa: E402 - OvrtxReplicateContext, OvstageReplicateContext, - ovrtx_replicate, ovstage_replicate, ) from isaaclab_ov.renderers import OVRTXRendererCfg # noqa: E402 @@ -99,14 +97,24 @@ def _make_ovrtx_renderer_without_backend() -> OVRTXRenderer: cfg=SimpleNamespace(read_gpu_transforms=False), ) renderer.scene = renderer.backend - renderer.backend.renderer = SimpleNamespace( - open_usd_from_string=Mock(), - add_usd_reference_from_string=lambda *args, **kwargs: 1, - remove_usd=lambda reference: None, - clone_usd=lambda *args, **kwargs: None, - write_array_attribute=lambda *args, **kwargs: None, - write_attribute=lambda *args, **kwargs: None, - ) + renderer.backend.renderer = SimpleNamespace() + from isaaclab_ov.stage import OvstageBackend + + renderer.backend.attached = False + renderer.scene.ordinal = 0 + renderer.scene.stage = Mock() + renderer.scene.paths = Mock() + renderer.scene.paths.intern_token.side_effect = lambda token: SimpleNamespace(raw_id=1) + renderer.scene.paths.intern_path.side_effect = lambda path: SimpleNamespace(raw_id=hash(path) % 2**63) + renderer.scene.stage.query_from_path_list.side_effect = contextlib.nullcontext + renderer.scene.query = OvstageBackend.query.__get__(renderer.scene) + renderer.scene.commit = OvstageBackend.commit.__get__(renderer.scene) + renderer.scene.populate = Mock() + renderer.scene.resources = contextlib.ExitStack() + renderer.scene.cfg.populate_physics = False + renderer.backend.renderer.attach_ovstage = Mock() + renderer.backend.detach = Mock() + renderer._sim.render_context = SimpleNamespace(reset_stage_prepare_flag=lambda: None) renderer._warp_device = SimpleNamespace(ordinal=0) renderer.scene.next_camera_id = 0 return renderer @@ -135,85 +143,68 @@ def _make_camera_render_spec(num_envs: int = 1, device: str = "cpu") -> CameraRe def _prepare_clones(renderer, plan, routed=None): from isaaclab_ov.renderers.ovrtx_renderer_cfg import OVRTXBackendCfg - cfg = OVRTXBackendCfg(scene_key=renderer.cfg, use_ovstage=renderer._use_ovstage, read_gpu_transforms=True) - if renderer._use_ovstage: - from isaaclab_ov.stage import OvstageBackendCfg + cfg = OVRTXBackendCfg(scene_key=renderer.cfg, read_gpu_transforms=True) + from isaaclab_ov.stage import OvstageBackendCfg - cfg = OvstageBackendCfg(scene_key=cfg) + cfg = OvstageBackendCfg(scene_key=cfg) renderer.scene.cfg = cfg sim = SimpleNamespace(_backend_registry=[(cfg, renderer.scene)]) sim.get_backends = SimulationContext.get_backends.__get__(sim) routed = tuple(range(len(plan.asset_cfgs))) if routed is None else routed - context = OvstageReplicateContext if renderer._use_ovstage else OvrtxReplicateContext + context = OvstageReplicateContext context(sim).replicate(plan, routed) @pytest.mark.parametrize( - "use_ovstage, names, worlds, weights, copies", + "names, worlds, weights, copies", [ - pytest.param(False, ("",), ((0,),), (1,), [(0, "", [1, 2, 3])], id="environment-roots"), - pytest.param( - True, + (("",), ((0,),), (1,), [(0, "", [1, 2, 3])]), + ( ("/Robot", "/Object", "/Light", "/Robot/Camera"), ((3, 0, 2), (3, 0, 1)), (1, 3), [(0, "/Robot", [1, 2, 3]), (1, "/Object", [2, 3])], - id="nested-assets", ), ], ) -def test_native_replication_applies_compositions_then_positions( - monkeypatch, use_ovstage, names, worlds, weights, copies -): +def test_native_replication_applies_compositions_then_positions(monkeypatch, names, worlds, weights, copies): """Native replication gates hierarchy preparation before copies and placement.""" renderer = _make_ovrtx_renderer_without_backend() - renderer._use_ovstage = use_ovstage positions = np.array([[0, 0, 0], [2, -1, 0.5], [-3, 4, 1.5], [5, 2, 0]], dtype=np.float32) assets = tuple(AssetBaseCfg(prim_path="/World/envs/env_[^/]+" + name) for name in names) plan = make_clone_plan(assets, worlds, 4, weights=weights, positions=positions) _prepare_clones(renderer, plan) native = Mock() backend = renderer.backend - if use_ovstage: - import ovstage + import ovstage - paths = Mock() - paths.create_path_list_from_strings.return_value = "env_paths" - native.query_from_path_list.return_value = contextlib.nullcontext("env_query") - monkeypatch.setattr("isaaclab_ov.stage.xform_tensor_from_numpy", lambda value: value) - ovstage_replicate( - native, paths, backend.clone_copies, backend.clone_env_paths, backend.clone_positions, ordinal=3 - ) - native.compute_hierarchy.assert_called_once_with( - input_ordinal=3, output_ordinal=3, model=ovstage.HierarchyComputationModel.CPU_INCREMENTAL - ) - paths.create_path_list_from_strings.assert_called_once_with(backend.clone_env_paths) - paths.destroy_path_list.assert_called_once_with("env_paths") - actual = native.write_attribute.call_args.kwargs["tensors"] - assert native.write_attribute.call_args.args == ("env_query", "omni:xform") - assert native.write_attribute.call_args.kwargs["ordinal"] == 3 - clone_calls = native.clone.call_args_list - else: - ovrtx_replicate(native, backend.clone_copies, backend.clone_env_paths, backend.clone_positions) - actual_paths, attribute, actual = native.write_attribute.call_args.args - assert actual_paths == backend.clone_env_paths - assert attribute == "omni:xform" - clone_calls = native.clone_usd.call_args_list + paths = Mock() + paths.create_path_list_from_strings.return_value = "env_paths" + native.query_from_path_list.return_value = contextlib.nullcontext("env_query") + monkeypatch.setattr("isaaclab_ov.stage.xform_tensor_from_numpy", lambda value: value) + ovstage_replicate(native, paths, backend.clone_copies, backend.clone_env_paths, backend.clone_positions, ordinal=3) + native.compute_hierarchy.assert_called_once_with( + input_ordinal=3, output_ordinal=3, model=ovstage.HierarchyComputationModel.CPU_INCREMENTAL + ) + paths.create_path_list_from_strings.assert_called_once_with(backend.clone_env_paths) + paths.destroy_path_list.assert_called_once_with("env_paths") + actual = native.write_attribute.call_args.kwargs["tensors"] + assert native.write_attribute.call_args.args == ("env_query", "omni:xform") + assert native.write_attribute.call_args.kwargs["ordinal"] == 3 + clone_calls = native.clone.call_args_list assert clone_calls == [ call( f"/World/envs/env_{world}{suffix}", [f"/World/envs/env_{target}{suffix}" for target in targets], - **({"ordinal": 3} if use_ovstage else {}), + **({"ordinal": 3}), ) for world, suffix, targets in copies ] calls = [ - method[0] - for method in native.method_calls - if method[0] in {"compute_hierarchy", "clone", "clone_usd", "write_attribute"} + method[0] for method in native.method_calls if method[0] in {"compute_hierarchy", "clone", "write_attribute"} ] - preparation = ["compute_hierarchy"] if use_ovstage else [] - assert calls == preparation + ["clone" if use_ovstage else "clone_usd"] * len(copies) + ["write_attribute"] + preparation = ["compute_hierarchy"] + assert calls == preparation + ["clone"] * len(copies) + ["write_attribute"] assert backend.clone_env_paths == [f"/World/envs/env_{world}" for world in range(4)] expected = np.tile(np.eye(4, dtype=np.float64), (4, 1, 1)) expected[:, 3, :3] = positions @@ -258,7 +249,6 @@ def test_object_bindings_preserve_source_and_destination_scales(env_template): + [f"{env_template.format(index)}/Object_1" for index in (0, 2)] + ["/World/Shared", "/World/envs/Unplanned"] ) - renderer.backend.renderer.bind_attribute = Mock() renderer._setup_xform_bindings(stage) np.testing.assert_allclose( @@ -338,10 +328,14 @@ def test_create_render_data_writes_combined_stage_on_the_simulation_device(tmp_p scene.SetMetadata("metersPerUnit", 1.0) open_calls: list[str] = [] - renderer.backend.renderer.open_usd_from_string = lambda usd_string: open_calls.append(usd_string) + renderer.scene.populate = lambda usd_string: open_calls.append(usd_string) reference_calls = [] - renderer.backend.renderer.add_usd_reference_from_string = lambda usd, path: reference_calls.append((usd, path)) - renderer.backend.renderer.bind_attribute = lambda **kwargs: SimpleNamespace(unbind=lambda: None) + monkeypatch.setattr( + ovrtx_renderer_module.ovstage.population, + "add_usd_reference_from_string", + lambda stage, usd, path: reference_calls.append((usd, path)), + ) + monkeypatch.setattr(ovrtx_renderer_module.ovstage.population, "apply_usd_changes", lambda *args, **kwargs: None) renderer.backend.renderer.write_attribute = lambda *args, **kwargs: None class Device: @@ -399,21 +393,27 @@ def test_create_render_data_binds_camera_after_cloning(monkeypatch, global_camer call_order: list[str] = [] write_array_calls: list[tuple[list[str], str, list[list[str]]]] = [] - renderer.backend.renderer.open_usd_from_string = lambda _usd_string: call_order.append("open") + renderer.scene.populate = lambda _usd_string: call_order.extend(("open", "clone")) _prepare_clones(renderer, plan) - monkeypatch.setattr(ovrtx_renderer_module, "ovrtx_replicate", lambda *args: call_order.append("clone")) - - def _write_array_attribute(prim_paths: list[str], attribute_name: str, tensors: list[list[str]]) -> None: - call_order.append("rewrite_cameras") - write_array_calls.append((prim_paths, attribute_name, tensors)) - - renderer.backend.renderer.write_array_attribute = _write_array_attribute - renderer.backend.renderer.bind_attribute = lambda **_kwargs: SimpleNamespace(unbind=lambda: None) - renderer.backend.renderer.write_attribute = ( - lambda prim_paths=None, attribute_name=None, *args, **kwargs: call_order.append("partitions") - if attribute_name == "primvars:omni:scenePartition" - else None + + path_ids = {} + renderer.scene.paths.create_path_list_from_strings.side_effect = list + renderer.scene.paths.intern_path.side_effect = lambda path: SimpleNamespace( + raw_id=path_ids.setdefault(path, len(path_ids)) ) + + def write(query, name, **kwargs): + if name == "camera": + call_order.append("rewrite_cameras") + paths = list(path_ids) + write_array_calls.append((query, name, [[paths[int(i)] for i in kwargs["tensors"]]])) + elif name == "primvars:omni:scenePartition": + call_order.append("partitions") + return SimpleNamespace(wait=lambda: None) + + renderer.scene.stage.write_attribute.side_effect = write + monkeypatch.setattr(ovrtx_renderer_module.ovstage.population, "add_usd_reference_from_string", Mock()) + monkeypatch.setattr(ovrtx_renderer_module.ovstage.population, "apply_usd_changes", Mock()) renderer.prepare_stage(_make_multi_env_stage(num_envs), num_envs) spec = _make_camera_render_spec(num_envs=1 if global_camera else num_envs) if global_camera: @@ -477,7 +477,7 @@ def test_prepare_stage_exports_only_clone_sources_and_their_materials(monkeypatc sim = SimpleNamespace(_backend_registry=[(cfg, backend)]) sim.get_backends = SimulationContext.get_backends.__get__(sim) OvstageReplicateContext(sim).replicate(plan, (0,)) - exported_usd = renderer.backend.renderer.open_usd_from_string.call_args.args[0] + exported_usd = renderer.scene.populate.call_args.args[0] backend.populate(exported_usd) assert imported.call_args.args == (native, exported_usd) assert imported.call_args.kwargs["domains"] == ovstage.PopulationDomain.RENDERING @@ -485,7 +485,7 @@ def test_prepare_stage_exports_only_clone_sources_and_their_materials(monkeypatc native.advance_write_floor.assert_called_once_with(ordinal=1) backend.close() exported = Usd.Stage.CreateInMemory() - assert exported.GetRootLayer().ImportFromString(renderer.backend.renderer.open_usd_from_string.call_args.args[0]) + assert exported.GetRootLayer().ImportFromString(renderer.scene.populate.call_args.args[0]) settings = exported.GetPrimAtPath(exported.GetMetadata("renderSettingsPrimPath")) assert settings.GetAttribute("omni:rtx:scenePartitioning:showAllPartitionsByDefault").Get() is True binding = UsdShade.MaterialBindingAPI(exported.GetPrimAtPath(f"{source}/Body")).GetDirectBindingRel() @@ -621,19 +621,13 @@ def test_clone_context_omits_covered_children_and_honors_routing(child_source, r renderer_cfg = OVRTXRendererCfg() configs = ( - OVRTXBackendCfg(scene_key=renderer_cfg, use_ovstage=False, read_gpu_transforms=True), OvstageBackendCfg(scene_key=renderer_cfg), - OVRTXBackendCfg(scene_key=renderer_cfg, use_ovstage=True, read_gpu_transforms=True), + OVRTXBackendCfg(scene_key=renderer_cfg, read_gpu_transforms=True), ) - for selected, context in enumerate((OvrtxReplicateContext, OvstageReplicateContext)): - backends = [SimpleNamespace() for _ in configs] - sim = SimpleNamespace(_backend_registry=list(zip(configs, backends)), backend_manager=SimpleNamespace()) - sim.get_backends = SimulationContext.get_backends.__get__(sim) - for cfg, backend in sim._backend_registry: - backend.cfg = cfg - context(sim).replicate(plan, routed) - assert backends[selected].clone_copies == expected - assert not vars(sim.backend_manager) - assert all( - vars(backend) == {"cfg": configs[index]} for index, backend in enumerate(backends) if index != selected - ) + backends = [SimpleNamespace(cfg=cfg) for cfg in configs] + sim = SimpleNamespace(_backend_registry=list(zip(configs, backends)), backend_manager=SimpleNamespace()) + sim.get_backends = SimulationContext.get_backends.__get__(sim) + OvstageReplicateContext(sim).replicate(plan, routed) + assert backends[0].clone_copies == expected + assert not vars(sim.backend_manager) + assert vars(backends[1]) == {"cfg": configs[1]} diff --git a/source/isaaclab_ov/test/test_ovrtx_deformable_bindings.py b/source/isaaclab_ov/test/test_ovrtx_deformable_bindings.py index 85e1d1dbb461..1e2dc97e7783 100644 --- a/source/isaaclab_ov/test/test_ovrtx_deformable_bindings.py +++ b/source/isaaclab_ov/test/test_ovrtx_deformable_bindings.py @@ -31,7 +31,6 @@ from isaaclab_ov.renderers import OVRTXRendererCfg from isaaclab_ov.renderers.ovrtx_renderer import OVRTXRenderer from isaaclab_ov.stage import OvstageBackend - from ovrtx import DataAccess from pxr import Gf, Usd, UsdGeom @@ -53,13 +52,9 @@ def _make_renderer_without_backend() -> tuple[OVRTXRenderer, MagicMock]: return renderer, renderer.backend.renderer -@pytest.mark.parametrize("mode", ["sync", "async", "ovstage"]) -def test_geometry_bindings_follow_mixed_sdp_points_and_pointer_swaps(mode): +def test_geometry_bindings_follow_mixed_sdp_points_and_pointer_swaps(): """Mesh, particle and curve points share one binding and retain publication ordering.""" renderer, native = _make_renderer_without_backend() - renderer.cfg.async_rendering = mode == "async" - use_ovstage = mode == "ovstage" - renderer._use_ovstage = use_ovstage renderer._warp_device = SimpleNamespace(stream=SimpleNamespace(cuda_stream=42)) points = { path: wp.array(np.arange(count * 3, dtype=np.float32).reshape(count, 3), dtype=wp.vec3f, device="cpu") @@ -88,42 +83,24 @@ def read_points(_format): publication.get_geometry_batches = read_points renderer._sdp = SceneDataProvider(publication) - if use_ovstage: - renderer.scene.ordinal = 7 - renderer.scene.paths = SimpleNamespace( - create_path_list_from_strings=lambda paths: paths, destroy_path_list=lambda paths: None - ) - renderer.scene.stage = MagicMock() - renderer.scene.stage.query_from_path_list.side_effect = contextlib.nullcontext - publication.points = {} - renderer._setup_geometry_bindings() - renderer.update_geometries() - renderer.scene.stage.write_attribute.assert_not_called() - publication.points = points - renderer._sdp = SceneDataProvider(publication) - renderer._setup_geometry_bindings() - assert renderer._geometry_points_binding == list(points) - write = renderer.scene.stage.write_attribute - assert [call.args[1] for call in write.call_args_list] == ["omni:resetXformStack", "omni:xform"] - np.testing.assert_array_equal(write.call_args_list[0].kwargs["tensors"], np.ones(len(points), dtype=np.bool_)) - write.reset_mock() - else: - publication.points = {} - renderer._setup_geometry_bindings() - renderer.update_geometries() - native.bind_array_attribute.assert_not_called() - publication.points = points - renderer._sdp = SceneDataProvider(publication) - renderer._setup_geometry_bindings() - assert native.bind_array_attribute.call_args.kwargs["prim_paths"] == list(points) - np.testing.assert_array_equal( - native.write_attribute.call_args_list[0].kwargs["tensor"], np.ones(len(points), dtype=np.bool_) - ) - np.testing.assert_array_equal( - native.write_attribute.call_args_list[1].kwargs["tensor"], np.tile(np.eye(4), (len(points), 1, 1)) - ) - binding = renderer._geometry_points_binding - write = binding.write_async if mode == "async" else binding.write + renderer.scene.ordinal = 7 + renderer.scene.paths = SimpleNamespace( + create_path_list_from_strings=lambda paths: paths, destroy_path_list=lambda paths: None + ) + renderer.scene.stage = MagicMock() + renderer.scene.stage.query_from_path_list.side_effect = contextlib.nullcontext + publication.points = {} + renderer._setup_geometry_bindings() + renderer.update_geometries() + renderer.scene.stage.write_attribute.assert_not_called() + publication.points = points + renderer._sdp = SceneDataProvider(publication) + renderer._setup_geometry_bindings() + assert renderer._geometry_points_binding == list(points) + write = renderer.scene.stage.write_attribute + assert [call.args[1] for call in write.call_args_list] == ["omni:resetXformStack", "omni:xform"] + np.testing.assert_array_equal(write.call_args_list[0].kwargs["tensors"], np.ones(len(points), dtype=np.bool_)) + write.reset_mock() write.side_effect = RuntimeError("native write failed") with pytest.raises(RuntimeError, match="native write failed"): @@ -133,55 +110,30 @@ def read_points(_format): renderer.update_geometries() renderer.update_geometries() assert write.call_count == 1 - data = write.call_args.kwargs["tensors"] if use_ovstage else write.call_args.args[0] + data = write.call_args.kwargs["tensors"] for item, array in zip(data, points.values(), strict=True): - if mode == "async": - assert item.ptr != array.ptr - np.testing.assert_array_equal(item.numpy(), array.numpy()) - else: - assert (item.data if use_ovstage else item.ptr) == array.ptr + assert (item.data) == array.ptr kwargs = write.call_args.kwargs assert kwargs["cuda_stream"] == 42 - if use_ovstage: - assert kwargs["ordinal"] == 7 and kwargs["is_array"] - else: - assert kwargs["data_access"] is DataAccess.ASYNC + assert kwargs["ordinal"] == 7 and kwargs["is_array"] # The producer advances its timestamp during the request, not before the consumer calls it. publication.points = {path: wp.clone(array) for path, array in reversed(tuple(points.items()))} renderer.update_geometries() renderer.update_geometries() assert write.call_count == 2 - data = write.call_args.kwargs["tensors"] if use_ovstage else write.call_args.args[0] + data = write.call_args.kwargs["tensors"] for item, path in zip(data, points, strict=True): array = publication.points[path] - if mode == "async": - np.testing.assert_array_equal(item.numpy(), array.numpy()) - else: - assert (item.data if use_ovstage else item.ptr) == array.ptr - if mode == "async": - # Mutating live physics storage cannot change either queued snapshot. - snapshots = [call.args[0] for call in write.call_args_list] - for array in publication.points.values(): - array.fill_(wp.vec3f(-1)) - for snapshot in snapshots: - for item, array in zip(snapshot, points.values(), strict=True): - np.testing.assert_array_equal(item.numpy(), array.numpy()) - publication.geometry_timestamp += 1 - renderer.update_geometries() - write.return_value.wait.assert_called() - assert write.call_args.args[0][0].ptr == snapshots[0][0].ptr - binding.write.assert_not_called() + assert (item.data) == array.ptr -@pytest.mark.parametrize("mode, scaled", [("sync", False), ("async", True), ("ovstage", True)]) -def test_update_transforms_consumes_sdp_matrices_once_per_publication(monkeypatch, mode, scaled): - """Borrow synchronous publications or convert directly into retained asynchronous write buffers.""" +@pytest.mark.parametrize("scaled", [False, True]) +def test_update_transforms_consumes_sdp_matrices_once_per_publication(monkeypatch, scaled): + """Reuse SDP publications or retained scaled transform buffers.""" from isaaclab.scene_data import SceneDataFormat, SceneDataProvider renderer, _ = _make_renderer_without_backend() - renderer.cfg.async_rendering = mode == "async" - use_ovstage = mode == "ovstage" paths = ["/World/Shared", "/World/envs/env_1/Object"] poses = np.array([[1, 2, 3, 0, 0, 0, 1], [4, 5, 6, 0, 0, 0, 1]], dtype=np.float32) transforms = SceneDataFormat.Transform() @@ -193,70 +145,53 @@ def test_update_transforms_consumes_sdp_matrices_once_per_publication(monkeypatc UsdGeom.Xform.Define(stage, paths[0]).AddScaleOp().Set(Gf.Vec3d(2, 3, 4) if scaled else Gf.Vec3d(1)) renderer.scene.clone_copies = [(paths[0], [])] renderer._warp_device = SimpleNamespace(stream=SimpleNamespace(cuda_stream=0)) - renderer._use_ovstage = use_ovstage renderer.scene.ordinal = 5 writes = [] - if use_ovstage: - renderer.scene.paths = SimpleNamespace( - create_path_list_from_strings=lambda paths: paths, destroy_path_list=lambda paths: None - ) - renderer.scene.stage = SimpleNamespace( - query_from_path_list=contextlib.nullcontext, - write_attribute=lambda query, attribute, **kwargs: ( - writes.append((query, attribute, kwargs)) or SimpleNamespace(wait=lambda: None) - ), - ) - monkeypatch.setattr(ovrtx_renderer_module, "xform_tensor_from_warp", lambda matrices: matrices) - renderer._setup_xform_bindings(stage) - assert renderer._object_xform_binding == paths - writes.clear() - else: - renderer._setup_xform_bindings(stage) - assert renderer.backend.renderer.bind_attribute.call_args.kwargs["prim_paths"] == paths - renderer._object_xform_binding.write = lambda matrices, **kwargs: writes.append((None, matrices, kwargs)) - operation = MagicMock() - renderer._object_xform_binding.write_async = lambda matrices, **kwargs: ( - writes.append((None, matrices, kwargs)) or operation - ) + renderer.scene.paths = SimpleNamespace( + create_path_list_from_strings=lambda paths: paths, destroy_path_list=lambda paths: None + ) + renderer.scene.stage = SimpleNamespace( + query_from_path_list=contextlib.nullcontext, + write_attribute=lambda query, attribute, **kwargs: ( + writes.append((query, attribute, kwargs)) or SimpleNamespace(wait=lambda: None) + ), + ) + monkeypatch.setattr(ovrtx_renderer_module, "xform_tensor_from_warp", lambda matrices: matrices) + renderer._setup_xform_bindings(stage) + assert renderer._object_xform_binding == paths + writes.clear() renderer.update_transforms() renderer.update_transforms() assert len(writes) == 1 - matrices = writes[0][2]["tensors"] if use_ovstage else writes[0][1] + matrices = writes[0][2]["tensors"] expected = np.tile(np.eye(4), (2, 1, 1)) if scaled: expected[0, :3, :3] = np.diag([2, 3, 4]) expected[:, 3, :3] = poses[:, :3] np.testing.assert_array_equal(matrices.numpy(), expected) assert writes[0][2]["cuda_stream"] == 1 # Torch's default stream, not "no sync" - if use_ovstage: - assert writes[0][2]["ordinal"] == 5 - else: - assert writes[0][2]["data_access"] is DataAccess.ASYNC + assert writes[0][2]["ordinal"] == 5 if not scaled: other, native = _make_renderer_without_backend() other._sdp = renderer._sdp - other.scene.clone_copies = renderer.scene.clone_copies + other.scene = renderer.scene + other.scene.stage.write_attribute = lambda query, attribute, **kwargs: SimpleNamespace(wait=lambda: None) other._setup_xform_bindings(stage) other.update_transforms() - assert native.bind_attribute.return_value.write.call_args.args[0] is matrices + assert other._transform_buffer.matrices is matrices + renderer.scene.stage.write_attribute = lambda query, attribute, **kwargs: ( + writes.append((query, attribute, kwargs)) or SimpleNamespace(wait=lambda: None) + ) poses[:, 0] += 10 transforms.transforms.assign(poses) backend.transforms_timestamp += 1 renderer.update_transforms() assert len(writes) == 2 - updated = writes[1][2]["tensors"] if use_ovstage else writes[1][1] - assert (updated is matrices) == (mode != "async") + updated = writes[1][2]["tensors"] + assert updated is matrices expected[:, 3, :3] = poses[:, :3] np.testing.assert_array_equal(updated.numpy(), expected) - if mode == "async": - # The new capture has not overwritten the previous borrowed input. - np.testing.assert_array_equal(matrices.numpy()[:, 3, 0], poses[:, 0] - 10) - operation.wait.assert_not_called() - backend.transforms_timestamp += 1 - renderer.update_transforms() - operation.wait.assert_called_once_with() - assert writes[2][1] is matrices diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 4d306b46a2ad..04b91d56187f 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -11,10 +11,9 @@ import logging import sys import types -from builtins import ExceptionGroup from collections.abc import Callable from typing import Literal -from unittest.mock import MagicMock, call +from unittest.mock import MagicMock import numpy as np import pytest @@ -49,7 +48,6 @@ OVRTXCameraRenderData, OVRTXRenderer, OVRTXRenderProduct, - _AsyncWriteBuffers, _gpu_side_render_var_sync_enabled, ) else: @@ -122,31 +120,28 @@ def _make_ovrtx_renderer_without_backend() -> OVRTXRenderer: renderer.backend.attached = False renderer.backend.render_products = set() renderer.backend.unrendered = {} - cfg = OVRTXBackendCfg(scene_key=renderer.cfg, use_ovstage=False, read_gpu_transforms=True, device="cpu") + cfg = OVRTXBackendCfg(scene_key=renderer.cfg, read_gpu_transforms=True, device="cpu") renderer.scene.stage = renderer.scene.paths = None renderer.backend.cfg = cfg SimulationContext.instance()._backend_registry.append((cfg, renderer.backend)) return renderer -def _camera_scope_exists(renderer: OVRTXRenderer, render_scope_name: str, use_ovstage: bool) -> bool: +def _camera_scope_exists(renderer: OVRTXRenderer, render_scope_name: str) -> bool: scope = f"/{render_scope_name}/" - if use_ovstage: - import ovstage + import ovstage - camera_filter = ovstage.Filter([ovstage.Predicate("usd-path", ovstage.FilterOp.PREFIX, [scope])]) - with renderer.scene.stage.query(filter=camera_filter) as query: - return query.result().total_prim_count > 0 - return any(path.startswith(scope) for path in renderer.backend.renderer.query_prims()) + camera_filter = ovstage.Filter([ovstage.Predicate("usd-path", ovstage.FilterOp.PREFIX, [scope])]) + with renderer.scene.stage.query(filter=camera_filter) as query: + return query.result().total_prim_count > 0 -def _make_mocked_scene_renderer(monkeypatch, use_ovstage: bool, clone_env_paths: list[str]) -> OVRTXRenderer: +def _make_mocked_scene_renderer(monkeypatch, clone_env_paths: list[str] = ()) -> OVRTXRenderer: """Return a renderer whose scene and backend are mocks, so render data can be created without OVRTX.""" renderer = _make_ovrtx_renderer_without_backend() renderer._initialized_scene = True renderer._device = "cpu" renderer.scene.clone_env_paths = clone_env_paths - renderer._use_ovstage = use_ovstage renderer.scene.ordinal = 1 renderer.backend.renderer = MagicMock() renderer.scene.stage = MagicMock() @@ -189,19 +184,19 @@ def _simulation_registry(monkeypatch): @pytest.mark.parametrize( - "settings, with_physics, use_ovstage, shared_physics", + "settings, with_physics, shared_physics", [ - pytest.param((None, None), False, False, False, id="other-default"), - pytest.param((None, None), True, False, False, id="ovphysx-default"), - pytest.param(("1", None), False, True, False, id="other-ovstage"), - pytest.param(("1", None), True, True, False, id="ovphysx-render-only"), - pytest.param(("0", None), True, False, False, id="ovphysx-native"), - pytest.param((None, "1"), True, True, True, id="shared"), - pytest.param(("0", "1"), True, True, True, id="shared-override"), + ((None, None), False, False), + ((None, None), True, False), + (("1", None), False, False), + (("1", None), True, False), + (("0", None), True, False), + ((None, "1"), True, True), + (("0", "1"), True, True), ], ) def test_ovrtx_renderer_config_enables_supported_runtime_options( - monkeypatch, tmp_path, settings, with_physics, use_ovstage, shared_physics + monkeypatch, tmp_path, settings, with_physics, shared_physics ): """Preparation resolves routes before native allocation; registry ownership outlives borrowers.""" from isaaclab_ov.cloner import OvPhysxReplicateContext, OvrtxReplicateContext, OvstageReplicateContext @@ -232,7 +227,7 @@ def __init__(self, **kwargs): monkeypatch.setattr( ovrtx_renderer_module, "Renderer", lambda cfg: types.SimpleNamespace(destroy=lambda: destroyed.append(cfg)) ) - SimulationContext.instance().device = "cuda:1" if use_ovstage else "cpu" + SimulationContext.instance().device = "cuda:1" devices = { "cpu": types.SimpleNamespace(is_cuda=False), "cuda:1": types.SimpleNamespace(is_cuda=True, ordinal=1), @@ -260,11 +255,11 @@ def create_stage(name, config): sim = SimulationContext.instance() if with_physics: sim.backend_manager.clone_context_type = OvPhysxReplicateContext - if use_ovstage and with_physics: + if with_physics: # An asset route alone does not configure a renderer or authorize changing physics ownership. routes = {OvPhysxReplicateContext: {0}, OvrtxReplicateContext: {1}} OvrtxReplicateContext.prepare(sim, routes) - assert routes == {OvPhysxReplicateContext: {0}, OvrtxReplicateContext: {1}} + assert routes == {OvPhysxReplicateContext: {0}} cfg = OVRTXRendererCfg() renderer = sim.get_or_create_backend(cfg) shared = sim.get_or_create_backend(replace(cfg)) @@ -291,13 +286,12 @@ def create_stage(name, config): assert loaded == [str(dependency)] * (1 if shared_physics else 2) assert len(redirected) == (1 if shared_physics else 2) assert renderer.backend.renderer is not None - assert config_kwargs.get("active_cuda_gpus") == ("1" if use_ovstage else None) + assert config_kwargs.get("active_cuda_gpus") == ("1") # Camera compatibility must retain the requested GPU scene-transform path, # including when simulation tensors originate on the CPU. assert config_kwargs["read_gpu_transforms"] is True - assert config_kwargs["suppress_deprecation_warnings"] is True assert config_kwargs["texture_streaming_mode"] is ovrtx_renderer_module.TextureStreamingMode.SYNCHRONOUS - expected_contexts = {OvstageReplicateContext if use_ovstage else OvrtxReplicateContext} + expected_contexts = {OvstageReplicateContext} if with_physics: expected_contexts.add(OvPhysxReplicateContext) assert set(sim.clone_contexts) == expected_contexts @@ -308,13 +302,12 @@ def create_stage(name, config): assert bool(sim.backend_manager._clone_recipes) is with_physics # Repeated preparation retains the selected resource identity. resources = tuple(sim._backend_registry) - monkeypatch.setenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", str(int(not use_ovstage))) + monkeypatch.setenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", "0") OvrtxReplicateContext.prepare(sim, {OvrtxReplicateContext: set()}) assert tuple(sim._backend_registry) == resources - if use_ovstage: - assert renderer.scene.cfg.population_domains == ovrtx_renderer_module.ovstage.PopulationDomain.RENDERING - assert renderer.scene.cfg.populate_physics is shared_physics - assert renderer.scene.cfg.defer_render_copies is shared_physics + assert renderer.scene.cfg.population_domains == ovrtx_renderer_module.ovstage.PopulationDomain.RENDERING + assert renderer.scene.cfg.populate_physics is shared_physics + assert renderer.scene.cfg.defer_render_copies is shared_physics if shared_physics: with pytest.raises(ValueError, match="one OVRTX engine"): sim.get_or_create_backend(replace(renderer.cfg, log_level="verbose")) @@ -336,33 +329,22 @@ def create_stage(name, config): assert len(destroyed) == (1 if shared_physics else 2) assert redirected == destroyed assert not stage_releases - if use_ovstage: - for scene in dict.fromkeys((renderer.scene, other.scene)): - SimulationContext.instance().close_backend(scene) - assert stage_releases == ["paths", "stage"] * (1 if shared_physics else 2) + for scene in dict.fromkeys((renderer.scene, other.scene)): + SimulationContext.instance().close_backend(scene) + assert stage_releases == ["paths", "stage"] * (1 if shared_physics else 2) sim.close_backend(renderer) sim.close_backend(other) assert not sim._backend_registry -# Each missing output runs with and without batching; ``use_ovstage`` only changes the ordinal bookkeeping. +# Each missing output runs with and without batching. @pytest.mark.parametrize( - ("missing_output", "batch", "use_ovstage"), - [ - (None, False, False), - (None, True, True), - ("product", False, True), - ("product", True, False), - ("frame", False, False), - ("frame", True, True), - ], + "missing_output, batch", + [(None, False), (None, True), ("product", False), ("product", True), ("frame", False), ("frame", True)], ) -def test_ovrtx_render_submits_every_product_and_routes_requested_outputs( - monkeypatch, use_ovstage, missing_output, batch -): +def test_ovrtx_render_submits_every_product_and_routes_requested_outputs(monkeypatch, missing_output, batch): """A submission covers every registered product, fills each requested camera, and rejects gaps.""" renderer = _make_ovrtx_renderer_without_backend() - renderer._use_ovstage = use_ovstage renderer._initialized_scene = True renderer._visual_material_writer_ref = None renderer.scene.ordinal = 7 @@ -417,13 +399,9 @@ def advance_write_floor(*, ordinal): *[path for camera in cameras for path in camera.render_product_paths], "/Render/UnrequestedCamera", } - if use_ovstage: - assert submissions[0]["ordinal"] == 7 - assert published_ordinals == [7] - assert renderer.scene.ordinal == 8 - else: - assert "ordinal" not in submissions[0] - assert not published_ordinals + assert submissions[0]["ordinal"] == 7 + assert published_ordinals == [7] + assert renderer.scene.ordinal == 8 def test_lidar_and_camera_captures_use_separate_steps(monkeypatch): @@ -432,8 +410,7 @@ def test_lidar_and_camera_captures_use_separate_steps(monkeypatch): from isaaclab.sensors import LidarData - renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) - renderer._needs_transform_initialization = False + renderer = _make_mocked_scene_renderer(monkeypatch, clone_env_paths=[]) camera = _make_ovrtx_camera_render_data() renderer._camera_render_data.append(camera) renderer.backend.render_products.update(camera.render_product_paths) @@ -454,7 +431,7 @@ def test_lidar_and_camera_captures_use_separate_steps(monkeypatch): data = LidarData(1, 1, "cpu") renderer.render_lidar(lidar, data) - native.step.assert_called_with(render_products={lidar.render_product_path}, delta_time=0.1) + native.step.assert_called_with(render_products={lidar.render_product_path}, delta_time=0.1, ordinal=2) publish.assert_called_once_with(lidar, native.step.return_value, data) @@ -462,7 +439,7 @@ def test_lidar_readback_propagates_cpu_map_failure(monkeypatch): """A failed fallback map must reach the caller rather than publish an all-miss scan.""" from isaaclab.sensors import LidarData - renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) + renderer = _make_mocked_scene_renderer(monkeypatch, clone_env_paths=[]) renderer._warp_device = types.SimpleNamespace(stream=types.SimpleNamespace(cuda_stream=1)) lidar = ovrtx_renderer_module.OVRTXLidarRenderData("Lidar", 0.1, ["/Lidar"]) cloud = MagicMock() @@ -482,7 +459,7 @@ def test_lidar_capture_fails_when_unavailable(monkeypatch, missing): from isaaclab.sensors import LidarData - renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) + renderer = _make_mocked_scene_renderer(monkeypatch, clone_env_paths=[]) cfg = OVRTXLidarCfg( prim_path="/Lidar", update_period=0.1, azimuth_deg=[0.0], elevation_deg=[0.0], fire_time_ns=[0], channel_id=[0] ) @@ -504,15 +481,12 @@ def test_ovrtx_render_batch_empty_sequence_does_not_require_initialized_backend( renderer.render_batch([]) -@pytest.mark.parametrize("mode", ["sync", "ovstage", "async"]) @pytest.mark.parametrize("failed_frame", [True, False], ids=["failed-frame", "other-error"]) -def test_ovrtx_failed_frame_error_names_the_render_product_split(mode, failed_frame): +def test_ovrtx_failed_frame_error_names_the_render_product_split(failed_frame): """A failed frame gets one note about the render product split. Other step errors stay unchanged.""" renderer = _make_ovrtx_renderer_without_backend() renderer._initialized_scene = True renderer._visual_material_writer_ref = None - renderer._use_ovstage = mode == "ovstage" - renderer.cfg.async_rendering = mode == "async" renderer.scene.ordinal = 1 renderer.scene.stage = types.SimpleNamespace(advance_write_floor=lambda *, ordinal: MagicMock()) unsplit = _make_ovrtx_camera_render_data() @@ -524,20 +498,12 @@ def test_ovrtx_failed_frame_error_names_the_render_product_split(mode, failed_fr renderer.backend.render_products.update(camera.render_product_paths) reason = "The renderer failed to produce a frame (render_products='...')." if failed_frame else "device lost" error = RuntimeError(f"Operation 'step' failed:\n {reason}") - operation = MagicMock() - operation.wait.side_effect = error - renderer.backend.renderer = types.SimpleNamespace( - step=MagicMock(side_effect=error), step_async=lambda **kwargs: operation - ) + renderer.backend.renderer = types.SimpleNamespace(step=MagicMock(side_effect=error)) - # Under asynchronous rendering, the step failure surfaces when read_output waits for the frame. with pytest.raises(RuntimeError) as raised: renderer.render(unsplit) renderer.read_output(unsplit) assert raised.value is error - if mode == "async": - # The drain gets the same error object again. The note must not repeat. - assert renderer.drain_pending_renders() == [error] notes = getattr(error, "__notes__", []) if failed_frame: assert len(notes) == 1 @@ -583,11 +549,9 @@ def _add_search_camera( return renderer.create_render_data(CameraRenderSpec(cfg, "cpu", num_envs, paths, num_envs)) -def _make_search_cameras( - monkeypatch, use_ovstage: bool, num_envs: int, cameras: list[tuple[int | Literal["auto", "all"], int]] -): +def _make_search_cameras(monkeypatch, num_envs: int, cameras: list[tuple[int | Literal["auto", "all"], int]]): """Return a mocked renderer and one registered sensor per ``(max_envs_per_render_product, width)``.""" - renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage, [f"/World/envs/env_{i}" for i in range(num_envs)]) + renderer = _make_mocked_scene_renderer(monkeypatch, [f"/World/envs/env_{i}" for i in range(num_envs)]) renderer.scene.paths.intern_path.side_effect = lambda path: types.SimpleNamespace(raw_id=0) renderer.scene.paths.intern_token.side_effect = lambda token: types.SimpleNamespace(raw_id=0) monkeypatch.setattr(renderer, "_process_render_frame", MagicMock()) @@ -618,17 +582,7 @@ def step(*, render_products, **kwargs): raise RuntimeError(error) return {path: types.SimpleNamespace(frames=[object()]) for path in render_products} - def step_async(**kwargs): - # Cameras keep operations in sets, so the fake must be hashable. - operation = MagicMock() - try: - operation.wait.return_value.fetch.return_value = step(**kwargs) - except RuntimeError as failure: - operation.wait.side_effect = failure - return operation - renderer.backend.renderer.step = step - renderer.backend.renderer.step_async = step_async return submissions @@ -657,17 +611,9 @@ def _referenced_render_vars(add_usd_reference: MagicMock) -> dict[str, list[str] } -@pytest.mark.parametrize( - ("use_ovstage", "asynchronous"), [(False, False), (True, False), (False, True)], ids=["legacy", "ovstage", "async"] -) -def test_ovrtx_render_batch_halves_envs_per_render_product_while_the_first_frame_fails( - monkeypatch, caplog, use_ovstage, asynchronous -): +def test_ovrtx_render_batch_halves_envs_per_render_product_while_the_first_frame_fails(monkeypatch, caplog): """A sensor with "auto" starts with one product, and each failed first frame halves its environments per product.""" - renderer, (camera,) = _make_search_cameras(monkeypatch, use_ovstage, 5, [("auto", 64)]) - renderer.cfg.async_rendering = asynchronous - # The legacy path fails in its first step with zero time. The asynchronous mode fails in the wait for the operation. - renderer._needs_transform_initialization = not use_ovstage and not asynchronous + renderer, (camera,) = _make_search_cameras(monkeypatch, 5, [("auto", 64)]) fail_all = False submissions = _install_step(renderer, lambda products: fail_all or len(products) < 3) @@ -681,12 +627,11 @@ def test_ovrtx_render_batch_halves_envs_per_render_product_while_the_first_frame {"/RenderCamera_1/RenderProduct_0", "/RenderCamera_1/RenderProduct_1"}, {f"/RenderCamera_2/RenderProduct_{k}" for k in range(3)}, ] - # On the legacy path, the working layout is stepped two times: first with zero time, then for the frame. - assert submissions == layouts + ([] if use_ovstage or asynchronous else [layouts[2]]) + assert submissions == layouts assert [product.num_envs for product in camera.products] == [2, 2, 1] # The scene references the layer of the last layout at its scope. The layer defines the stepped render products, # and they render the RenderVar that the sensor reads its rgb output from. - population = ovrtx_renderer_module.ovstage.population if use_ovstage else renderer.backend.renderer + population = ovrtx_renderer_module.ovstage.population assert _referenced_render_vars(population.add_usd_reference_from_string) == { path: [camera.render_var_keys["LdrColor"]] for path in layouts[2] } @@ -697,18 +642,8 @@ def test_ovrtx_render_batch_halves_envs_per_render_product_while_the_first_frame # A layout that rendered is final: a later failure reaches the caller. fail_all = True - if asynchronous: + with pytest.raises(RuntimeError, match="failed to produce a frame"): renderer.render_batch([camera]) - # A camera sensor that registers now first waits for the pending frame. Its error raises before the scene - # changes. - with pytest.raises(ExceptionGroup, match="before render product registration") as group: - _add_search_camera(renderer, "late", 5, "auto", 64) - (failure,) = group.value.exceptions - assert "failed to produce a frame" in str(failure) - camera.pending = camera.ready = None - else: - with pytest.raises(RuntimeError, match="failed to produce a frame"): - renderer.render_batch([camera]) assert submissions[-1] == layouts[2] assert renderer.backend.render_products == layouts[2] @@ -717,25 +652,15 @@ def test_ovrtx_render_batch_halves_envs_per_render_product_while_the_first_frame assert renderer.backend.render_products == set() -@pytest.mark.parametrize( - ("use_ovstage", "asynchronous", "num_envs", "products_per_step"), - [ - # 64 environments stop after the limit of 4 smaller layouts, with 4 environments per render product. - pytest.param(False, False, 64, [1, 2, 4, 8, 16], id="limit-legacy"), - pytest.param(False, True, 64, [1, 2, 4, 8, 16], id="limit-async"), - # 4 environments stop after 2 smaller layouts, because 1 environment per render product cannot be halved. - pytest.param(True, False, 4, [1, 2, 4], id="one-env-ovstage"), - ], -) +@pytest.mark.parametrize("num_envs, products_per_step", [(64, [1, 2, 4, 8, 16]), (4, [1, 2, 4])]) def test_ovrtx_render_batch_stops_the_split_search_after_the_last_smaller_layout( - monkeypatch, caplog, use_ovstage, asynchronous, num_envs, products_per_step + monkeypatch, caplog, num_envs, products_per_step ): """The search tries each smaller layout one time, down to 1 environment per render product. It tries at most 4 smaller layouts. Then it raises the last failure. """ - renderer, (camera,) = _make_search_cameras(monkeypatch, use_ovstage, num_envs, [("auto", 64)]) - renderer.cfg.async_rendering = asynchronous + renderer, (camera,) = _make_search_cameras(monkeypatch, num_envs, [("auto", 64)]) submissions = _install_step(renderer, lambda products: True) with pytest.raises(RuntimeError, match="failed to produce a frame") as error: @@ -760,7 +685,7 @@ def test_ovrtx_render_batch_stops_the_split_search_after_the_last_smaller_layout @pytest.mark.parametrize("max_envs, layout", [(4, [4, 4]), ("all", [8])], ids=["integer", "all"]) def test_ovrtx_render_batch_does_not_search_without_auto(monkeypatch, caplog, max_envs, layout): """A failed frame of a sensor with "all" or an integer reaches the caller after one step, with the same layout.""" - renderer, (camera,) = _make_search_cameras(monkeypatch, False, 8, [(max_envs, 64)]) + renderer, (camera,) = _make_search_cameras(monkeypatch, 8, [(max_envs, 64)]) failed = camera.render_product_paths submissions = _install_step(renderer, lambda products: True) @@ -780,7 +705,7 @@ def test_ovrtx_render_batch_does_not_search_without_auto(monkeypatch, caplog, ma def test_ovrtx_split_search_names_an_auto_sensor_without_one_camera_path_per_environment(monkeypatch, caplog): """The search cannot split an "auto" sensor with only one camera path. A warning and the error note name it.""" - renderer, _ = _make_search_cameras(monkeypatch, False, 8, []) + renderer, _ = _make_search_cameras(monkeypatch, 8, []) cfg = _make_camera_cfg(["rgb"]) # The camera is not below an environment root, so the renderer cannot complete its camera paths. cfg.prim_path = "/World/Camera" @@ -804,7 +729,7 @@ def test_ovrtx_split_search_names_an_auto_sensor_without_one_camera_path_per_env @pytest.mark.parametrize( "written, failing_write", - [(0, "add_usd_reference_from_string"), (1, "add_usd_reference_from_string"), (1, "query_prims")], + [(0, "add_usd_reference_from_string"), (1, "add_usd_reference_from_string"), (1, "read_attributes")], ids=["first-write-fails", "last-write-fails", "last-copy-fails"], ) def test_ovrtx_split_search_retires_every_failed_product_before_a_scene_write(monkeypatch, written, failing_write): @@ -812,13 +737,18 @@ def test_ovrtx_split_search_retires_every_failed_product_before_a_scene_write(mo The sensors without new render products leave the search. Their later renders name the write error as the cause. """ - renderer, cameras = _make_search_cameras(monkeypatch, False, 8, [("auto", 64), ("auto", 64)]) + renderer, cameras = _make_search_cameras(monkeypatch, 8, [("auto", 64), ("auto", 64)]) failed = set(renderer.backend.render_products) submissions = _install_step(renderer, lambda products: True) - # The scene writes of the first ``written`` sensors succeed, and the write of the next sensor fails. query_prims + # The scene writes of the first ``written`` sensors succeed, and the write of the next sensor fails. The read # starts the copy of the render product attributes, after the new render products joined the steps. scene_writes = [MagicMock()] * written + [OSError("scene write")] - getattr(renderer.backend.renderer, failing_write).side_effect = scene_writes + owner = ( + ovrtx_renderer_module.ovstage.population + if failing_write == "add_usd_reference_from_string" + else renderer.scene.stage + ) + getattr(owner, failing_write).side_effect = scene_writes with pytest.raises(OSError, match="scene write") as error: renderer.render_batch(cameras) @@ -842,10 +772,10 @@ def test_ovrtx_split_search_retires_every_failed_product_before_an_interrupted_s An interrupt, for example Ctrl+C, is no ``Exception``, so it skips the clean-up after a failed scene write. OVRTX can abort when a later step renders a failed render product again. """ - renderer, cameras = _make_search_cameras(monkeypatch, False, 8, [("auto", 64), ("auto", 64)]) + renderer, cameras = _make_search_cameras(monkeypatch, 8, [("auto", 64), ("auto", 64)]) failed = set(renderer.backend.render_products) _install_step(renderer, lambda products: True) - renderer.backend.renderer.add_usd_reference_from_string.side_effect = KeyboardInterrupt + ovrtx_renderer_module.ovstage.population.add_usd_reference_from_string.side_effect = KeyboardInterrupt with pytest.raises(KeyboardInterrupt): renderer.render_batch(cameras) @@ -856,29 +786,29 @@ def test_ovrtx_split_search_retires_every_failed_product_before_an_interrupted_s def test_ovrtx_split_search_leaves_out_a_sensor_removed_before_its_first_frame(monkeypatch): """A sensor removed before its first frame gets no new render products when the first frame fails.""" - renderer, (kept, removed) = _make_search_cameras(monkeypatch, False, 8, [("auto", 64), ("auto", 64)]) + renderer, (kept, removed) = _make_search_cameras(monkeypatch, 8, [("auto", 64), ("auto", 64)]) renderer.cleanup(removed) failed = kept.render_product_paths - add_usd_reference = renderer.backend.renderer.add_usd_reference_from_string + add_usd_reference = ovrtx_renderer_module.ovstage.population.add_usd_reference_from_string add_usd_reference.reset_mock() submissions = _install_step(renderer, lambda products: len(products) < 2) renderer.render_batch([kept]) # Only the kept sensor gets a new scope, and no step renders a render product of the removed sensor. - assert [c.args[1] for c in add_usd_reference.call_args_list] == [f"/{kept.render_scope_name}"] + assert [c.args[2] for c in add_usd_reference.call_args_list] == [f"/{kept.render_scope_name}"] assert submissions == [set(failed), set(kept.render_product_paths)] def test_ovrtx_split_search_skips_a_sensor_removed_during_the_search(monkeypatch): """A sensor that a cleanup removes during the search gets no new render products. The search goes on.""" - renderer, (first, removed, last) = _make_search_cameras(monkeypatch, False, 8, [("auto", 64)] * 3) + renderer, (first, removed, last) = _make_search_cameras(monkeypatch, 8, [("auto", 64)] * 3) failed = set(renderer.backend.render_products) removed_paths = removed.render_product_paths - add_usd_reference = renderer.backend.renderer.add_usd_reference_from_string + add_usd_reference = ovrtx_renderer_module.ovstage.population.add_usd_reference_from_string add_usd_reference.reset_mock() - def write_and_clean_up(usd, path): + def write_and_clean_up(stage, usd, path): # The scene write of the first sensor cleans up the second sensor, for example through a callback. add_usd_reference.side_effect = None renderer.cleanup(removed) @@ -891,7 +821,7 @@ def write_and_clean_up(usd, path): # Of equal sensors, the first in the order of the engine is halved. The last sensor keeps its split. assert [[product.num_envs for product in camera.products] for camera in (first, last)] == [[4, 4], [8]] - assert [c.args[1] for c in add_usd_reference.call_args_list] == [ + assert [c.args[2] for c in add_usd_reference.call_args_list] == [ f"/{first.render_scope_name}", f"/{last.render_scope_name}", ] @@ -904,11 +834,11 @@ def test_ovrtx_split_search_gives_up_with_a_sensor_removed_during_the_search(mon """A search that gives up raises the failed frame, also if a cleanup removes a sensor during the search.""" # A sensor with 1 environment cannot be halved, so the search gives up on the "auto" sensor. It still moves the # sensor with an integer split to new render products, and that scene write cleans up the "auto" sensor. - renderer, (fixed, removed) = _make_search_cameras(monkeypatch, False, 1, [(1, 64), ("auto", 64)]) + renderer, (fixed, removed) = _make_search_cameras(monkeypatch, 1, [(1, 64), ("auto", 64)]) failed = set(renderer.backend.render_products) - add_usd_reference = renderer.backend.renderer.add_usd_reference_from_string + add_usd_reference = ovrtx_renderer_module.ovstage.population.add_usd_reference_from_string - def write_and_clean_up(usd, path): + def write_and_clean_up(stage, usd, path): add_usd_reference.side_effect = None renderer.cleanup(removed) return MagicMock() @@ -925,7 +855,7 @@ def write_and_clean_up(usd, path): def test_ovrtx_render_batch_does_not_search_after_another_error(monkeypatch): """An error other than a failed frame reaches the caller unchanged and leaves the render products alone.""" - renderer, (camera,) = _make_search_cameras(monkeypatch, False, 8, [("auto", 64)]) + renderer, (camera,) = _make_search_cameras(monkeypatch, 8, [("auto", 64)]) layout = camera.render_product_paths submissions = _install_step(renderer, lambda products: True, "Operation 'step' failed: device lost") @@ -1036,7 +966,7 @@ def test_ovrtx_split_search_halves_the_sensor_with_the_largest_buffer_first( monkeypatch, caplog, sensors, samples, too_large, layouts ): """Each failed step halves one sensor with "auto", the highest pixels times samples per pixel first.""" - renderer, cameras = _make_search_cameras(monkeypatch, False, 16, sensors) + renderer, cameras = _make_search_cameras(monkeypatch, 16, sensors) for index, spp in samples.items(): cameras[index].spec.cfg.render_settings = {"omni:rtx:rtpt:spp": ("Int", spp)} # A step fails while a sensor of too_large has more than 8 environments in its first and largest render product. @@ -1054,11 +984,11 @@ def test_ovrtx_split_search_halves_the_sensor_with_the_largest_buffer_first( def test_ovrtx_split_search_covers_every_renderer_of_a_shared_engine(monkeypatch): """One step renders the products of every renderer on the engine, so the search can halve another one's sensor.""" - renderer, (small,) = _make_search_cameras(monkeypatch, True, 16, [("auto", 32)]) + renderer, (small,) = _make_search_cameras(monkeypatch, 16, [("auto", 32)]) other = OVRTXRenderer(OVRTXRendererCfg(enable_shadows=True), sim=SimulationContext.instance()) other.backend = other.scene = renderer.backend other._device = "cpu" - other._use_ovstage = other._initialized_scene = True + other._initialized_scene = True large = _add_search_camera(other, "large", 16, "auto", 64) shadows = {} build = ovrtx_renderer_module.build_render_product_as_string @@ -1081,142 +1011,103 @@ def record_shadows(spec, render_data, **kwargs): assert shadows == {small.render_scope_name: False, large.render_scope_name: True} -def _install_attribute_store(renderer: OVRTXRenderer, use_ovstage: bool) -> dict: +def _install_attribute_store(renderer: OVRTXRenderer) -> dict: """Replace the attribute reads and writes of the scene with fakes over a dictionary. - Like OVRTX, the legacy fake raises when it reads a tag or an array without elements. Like OVStage, the OVStage fake - rejects a write of the prim path, and both a write and the release of a read group invalidate the data of the reads. + The fake rejects a write of the prim path. Both a write and the release of a read group invalidate borrowed data. A write of the OVStage fake reads its data only in its wait, because only the wait guarantees that OVStage read it. Returns: The attributes of each render product: ``{path: {name: (value, is_array, semantic)}}``. """ - import ovrtx import ovstage store = {} - if use_ovstage: - renderer.scene.stage.query_from_path_list.side_effect = contextlib.nullcontext - renderer.scene.paths.intern_token.side_effect = lambda name: types.SimpleNamespace(raw_id=0, name=name) - renderer.scene.paths.token_to_string.side_effect = lambda token: token.name - # The data that the read groups borrow. In OVStage, a write that adds attributes to other prims can change the - # data of an open read group. So a write invalidates this data like the release of a group. - borrowed = [] - - def invalidate_borrowed(*exc_info): - # A write that reads invalid data copies the sentinel 99. - for tensor in borrowed: - tensor[...] = np.array(99).astype(tensor.dtype) - - def column(name, value, is_array, semantic): - # OVStage can map the row of a prim in the query to another data row of the column. So the fake puts - # the value of the one prim after a row of zeros. - rows = [np.zeros_like(value), np.array(value)] - # An array column has one tensor per data row. A fixed-size column has one tensor with all data rows. - tensors = rows if is_array else [np.stack(rows)] - borrowed.extend(tensors) - return types.SimpleNamespace( - attribute=types.SimpleNamespace(name=name), - is_array=is_array, - semantic=semantic, - data_row_index=lambda local: local + 1, - # Like OVStage, the NumPy view of a column gives a half as uint16. - array=lambda index: tensors[index].view(np.uint16) if value.dtype == np.float16 else tensors[index], - # Like the borrowed view of OVStage, a NumPy array supports DLPack and keeps a half as float16. - dlpack=lambda index: tensors[index], - ) - - def array_values(tensor): - # Like OVStage, an array write takes the components of an element only from the lanes, not from the - # shape. So a float3[] in the shape (n, 3) without lanes arrives as a float[] of 3 * n values. - if not isinstance(tensor, ovstage.DLTensor): - return np.from_dlpack(tensor).reshape(-1) - values = ovstage.dltensor_to_numpy(tensor) - if (tensor.dtype.code, tensor.dtype.bits) == (ovstage.DLDataTypeCode.kDLFloat, 16): - # dltensor_to_numpy gives a half as uint16. - values = values.view(np.float16) - return values.reshape(-1, tensor.dtype.lanes) if tensor.dtype.lanes > 1 else values - - def read_attributes(query, attributes, ordinal_range): - assert [token.name for token in attributes] == ["*"] - (path,) = query - group = MagicMock(columns=[column(name, *entry) for name, entry in store[path].items()]) - group.__enter__.return_value = group - group.__exit__.side_effect = invalidate_borrowed - read = MagicMock() - read.__enter__.return_value.groups.return_value = [group] - return read - - def write_attributes(query, writes, ordinal): - if any(write.attribute.name == "usd-path" for write in writes): - raise ovstage.OvstageError( - ovstage.ErrorCode.NOT_SUPPORTED, - "built-in attribute 'usd-path' is derived on demand and cannot be written", - ) - invalidate_borrowed() - - def wait(): - for write in writes: - # Target i reads the source data row index_map[i]. An array has one tensor per data row. A - # fixed-size attribute has all data rows in one tensor. Like OVStage, the write copies the data. - tensors = write.tensors if isinstance(write.tensors, (list, tuple)) else [write.tensors] - rows = [array_values(tensor) for tensor in tensors] if write.is_array else np.from_dlpack(*tensors) - for path, index in zip(query, write.index_map, strict=True): - store[path][write.attribute.name] = (np.array(rows[index]), write.is_array, write.semantic) - - return types.SimpleNamespace(wait=wait) - - renderer.scene.stage.read_attributes.side_effect = read_attributes - renderer.scene.stage.write_attributes.side_effect = write_attributes - return store - native = renderer.backend.renderer + renderer.scene.stage.query_from_path_list.side_effect = contextlib.nullcontext + renderer.scene.paths.intern_token.side_effect = lambda name: types.SimpleNamespace(raw_id=0, name=name) + renderer.scene.paths.token_to_string.side_effect = lambda token: token.name + # The data that the read groups borrow. In OVStage, a write that adds attributes to other prims can change the + # data of an open read group. So a write invalidates this data like the release of a group. + borrowed = [] + + def invalidate_borrowed(*exc_info): + # A write that reads invalid data copies the sentinel 99. + for tensor in borrowed: + tensor[...] = np.array(99).astype(tensor.dtype) + + def column(name, value, is_array, semantic): + # OVStage can map the row of a prim in the query to another data row of the column. So the fake puts + # the value of the one prim after a row of zeros. + rows = [np.zeros_like(value), np.array(value)] + # An array column has one tensor per data row. A fixed-size column has one tensor with all data rows. + tensors = rows if is_array else [np.stack(rows)] + borrowed.extend(tensors) + return types.SimpleNamespace( + attribute=types.SimpleNamespace(name=name), + is_array=is_array, + semantic=semantic, + data_row_index=lambda local: local + 1, + # Like OVStage, the NumPy view of a column gives a half as uint16. + array=lambda index: tensors[index].view(np.uint16) if value.dtype == np.float16 else tensors[index], + # Like the borrowed view of OVStage, a NumPy array supports DLPack and keeps a half as float16. + dlpack=lambda index: tensors[index], + ) - def write_attribute(prim_paths, attribute_name, tensor, semantic=ovrtx.Semantic.NONE): - for path, value in zip(prim_paths, tensor, strict=True): - store.setdefault(path, {})[attribute_name] = (np.asarray(value), False, semantic) + def array_values(tensor): + # Like OVStage, an array write takes the components of an element only from the lanes, not from the + # shape. So a float3[] in the shape (n, 3) without lanes arrives as a float[] of 3 * n values. + if not isinstance(tensor, ovstage.DLTensor): + return np.from_dlpack(tensor).reshape(-1) + values = ovstage.dltensor_to_numpy(tensor) + if (tensor.dtype.code, tensor.dtype.bits) == (ovstage.DLDataTypeCode.kDLFloat, 16): + # dltensor_to_numpy gives a half as uint16. + values = values.view(np.float16) + return values.reshape(-1, tensor.dtype.lanes) if tensor.dtype.lanes > 1 else values + + def read_attributes(query, attributes, ordinal_range): + assert [token.name for token in attributes] == ["*"] + (path,) = query + group = MagicMock(columns=[column(name, *entry) for name, entry in store[path].items()]) + group.__enter__.return_value = group + group.__exit__.side_effect = invalidate_borrowed + read = MagicMock() + read.__enter__.return_value.groups.return_value = [group] + return read + + def write_attributes(query, writes, ordinal): + if any(write.attribute.name == "usd-path" for write in writes): + raise ovstage.OvstageError( + ovstage.ErrorCode.NOT_SUPPORTED, + "built-in attribute 'usd-path' is derived on demand and cannot be written", + ) + invalidate_borrowed() - def write_array_attribute(prim_paths, attribute_name, tensors, semantic=ovrtx.Semantic.NONE): - for path, value in zip(prim_paths, tensors, strict=True): - store.setdefault(path, {})[attribute_name] = (np.asarray(value), True, semantic) + def wait(): + for write in writes: + # Target i reads the source data row index_map[i]. An array has one tensor per data row. A + # fixed-size attribute has all data rows in one tensor. Like OVStage, the write copies the data. + tensors = write.tensors if isinstance(write.tensors, (list, tuple)) else [write.tensors] + rows = [array_values(tensor) for tensor in tensors] if write.is_array else np.from_dlpack(*tensors) + for path, index in zip(query, write.index_map, strict=True): + store[path][write.attribute.name] = (np.array(rows[index]), write.is_array, write.semantic) - def read(name, paths): - entries = [store[path][name] for path in paths] - if any( - semantic == ovrtx.Semantic.TAG or (is_array and not value.size) for value, is_array, semantic in entries - ): - raise RuntimeError(f"Read returned no data for {name!r}") - return [value for value, _, _ in entries] + return types.SimpleNamespace(wait=wait) - native.query_prims.side_effect = lambda **kwargs: { - path: { - name: ovrtx.AttributeInfo(name, None, is_array, semantic) - for name, (_, is_array, semantic) in entries.items() - } - for path, entries in store.items() - } - native.read_attribute.side_effect = lambda name, paths: np.stack(read(name, paths)) - native.read_array_attribute.side_effect = lambda name, paths: dict(zip(paths, read(name, paths), strict=True)) - native.write_attribute.side_effect = write_attribute - native.write_array_attribute.side_effect = write_array_attribute + renderer.scene.stage.read_attributes.side_effect = read_attributes + renderer.scene.stage.write_attributes.side_effect = write_attributes return store -@pytest.mark.parametrize("use_ovstage", [False, True], ids=["legacy", "ovstage"]) -def test_ovrtx_split_search_copies_the_attributes_of_the_failed_render_product(monkeypatch, use_ovstage): +def test_ovrtx_split_search_copies_the_attributes_of_the_failed_render_product(monkeypatch): """Attributes written onto the failed render product reach the new ones, which keep their own layout. - The copy skips the attributes of the layout, tags and arrays without elements, and goes on after each of them. + The copy skips layout attributes and the derived prim path while preserving scalar, array and half values. """ - import ovrtx import ovstage - renderer, (camera,) = _make_search_cameras(monkeypatch, use_ovstage, 4, [("auto", 64)]) - store = _install_attribute_store(renderer, use_ovstage) - token, path_id = ( - (ovstage.AttributeSemantic.TOKEN_ID, ovstage.AttributeSemantic.RELATIONSHIP_PATH_ID) - if use_ovstage - else (ovrtx.Semantic.TOKEN_ID, ovrtx.Semantic.PATH_ID) - ) + renderer, (camera,) = _make_search_cameras(monkeypatch, 4, [("auto", 64)]) + store = _install_attribute_store(renderer) + token, path_id = (ovstage.AttributeSemantic.TOKEN_ID, ovstage.AttributeSemantic.RELATIONSHIP_PATH_ID) add_render_products = renderer._add_render_products def add_and_author(data, spec): @@ -1228,8 +1119,7 @@ def add_and_author(data, spec): "camera": (np.arange(product.num_envs, dtype=np.uint64), True, path_id), "orderedVars": (np.array([f"/{data.render_scope_name}/Vars/LdrColor"]), True, path_id), } - if use_ovstage: - store[product.path]["usd-path"] = (np.array(product.path), False, 0) + store[product.path]["usd-path"] = (np.array(product.path), False, 0) monkeypatch.setattr(renderer, "_add_render_products", add_and_author) (failed,) = camera.render_product_paths @@ -1239,14 +1129,7 @@ def add_and_author(data, spec): "camera": (np.arange(4, dtype=np.uint64), True, path_id), "orderedVars": (np.array(["/RenderCamera_0/Vars/LdrColor"]), True, path_id), } - if use_ovstage: - # OVStage reads the path of a prim like an attribute, but rejects a write of it. - left_out["usd-path"] = (np.array(failed), False, 0) - else: - # OVRTX lists an applied schema as a tag without a value. Like OVRTX, the fake raises when it reads the tag - # or the array without elements. - left_out["OmniRtxSettingsCommonAdvancedAPI_1"] = (None, False, ovrtx.Semantic.TAG) - left_out["omni:rtx:debug:view:target"] = (np.array([], dtype=np.uint64), True, 0) + left_out["usd-path"] = (np.array(failed), False, 0) # A script writes the samples per pixel and the antialiasing mode. The layer authors waitForEvents. These # attributes come after the left-out attributes, so the copy must go on after each skipped attribute. store[failed] = { @@ -1255,12 +1138,10 @@ def add_and_author(data, spec): "omni:rtx:post:aa:op": (np.uint64(42), False, token), "omni:rtx:waitForEvents": (np.array([7, 8], dtype=np.uint64), True, token), } - if use_ovstage: - # The NumPy view of an OVStage column gives a half as uint16, which OVStage does not write as a half. - store[failed]["omni:test:half"] = (np.float16(0.5), False, 0) - store[failed]["omni:test:half_array"] = (np.array([0.5, 1.5], dtype=np.float16), True, 0) - # An OVStage read gives the 3 components of each element of a float3[] as an axis. - store[failed]["omni:test:float3s"] = (np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), True, 0) + store[failed]["omni:test:half"] = (np.float16(0.5), False, 0) + store[failed]["omni:test:half_array"] = (np.array([0.5, 1.5], dtype=np.float16), True, 0) + # An OVStage read gives the 3 components of each element of a float3[] as an axis. + store[failed]["omni:test:float3s"] = (np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), True, 0) _install_step(renderer, lambda products: len(products) < 2) renderer.render_batch([camera]) @@ -1279,34 +1160,23 @@ def add_and_author(data, spec): "omni:rtx:post:aa:op": (42, False, token), "omni:rtx:waitForEvents": ([7, 8], True, token), } - if use_ovstage: - expected["usd-path"] = (path, False, 0) - expected["omni:test:half"] = (0.5, False, 0) - expected["omni:test:half_array"] = ([0.5, 1.5], True, 0) - expected["omni:test:float3s"] = ([[1, 2, 3], [4, 5, 6]], True, 0) + expected["usd-path"] = (path, False, 0) + expected["omni:test:half"] = (0.5, False, 0) + expected["omni:test:half_array"] = ([0.5, 1.5], True, 0) + expected["omni:test:float3s"] = ([[1, 2, 3], [4, 5, 6]], True, 0) # No tag and no array without elements reach the new render products. assert attributes == expected - if use_ovstage: - assert store[path]["omni:test:half"][0].dtype == store[path]["omni:test:half_array"][0].dtype == np.float16 + assert store[path]["omni:test:half"][0].dtype == store[path]["omni:test:half_array"][0].dtype == np.float16 @pytest.mark.integration @pytest.mark.rendering -@pytest.mark.parametrize( - "use_ovstage, asynchronous, geometry", - [ - (False, False, "rigid"), - (True, False, "rigid"), - *[(False, True, kind) for kind in ("mesh", "particles", "cable")], - ], - ids=["legacy", "ovstage", "async-mesh", "async-particles", "async-cable"], -) -def test_ovrtx_multiple_cameras_render_independent_views(monkeypatch, capfd, use_ovstage, asynchronous, geometry): +@pytest.mark.parametrize("geometry", ["rigid", "mesh", "particles", "cable"]) +def test_ovrtx_multiple_cameras_render_independent_views(monkeypatch, capfd, geometry): """Cameras preserve independent captures, GPU input lifetimes, and reset/cleanup boundaries. - In the asynchronous rows, the second camera is a split sensor with two render products. + For deformable geometry, the second camera is split across two render products. """ - from ovrtx import PrimMode from pxr import Gf, Usd, UsdGeom, UsdLux @@ -1319,14 +1189,11 @@ def test_ovrtx_multiple_cameras_render_independent_views(monkeypatch, capfd, use if not torch.cuda.is_available(): pytest.skip("OVRTX rendering requires CUDA") SimulationContext.instance().device = "cuda:0" - monkeypatch.setenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", str(int(use_ovstage))) - env_template = "/Lab/Cells/Cell{}" if use_ovstage else "/World/envs/env_{}" + env_template = "/Lab/Cells/Cell{}" stage = Usd.Stage.CreateInMemory() UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) UsdGeom.SetStageMetersPerUnit(stage, 1.0) UsdGeom.Xform.Define(stage, env_template.format(0)) - if not use_ovstage: - UsdGeom.Xform.Define(stage, env_template.format(1)) if geometry == "rigid": light = UsdLux.DomeLight.Define(stage, env_template.format(0) + "/Dome") light.CreateIntensityAttr(300.0) @@ -1383,7 +1250,7 @@ def test_ovrtx_multiple_cameras_render_independent_views(monkeypatch, capfd, use ) ) - renderer = SimulationContext.instance().get_or_create_backend(OVRTXRendererCfg(async_rendering=asynchronous)) + renderer = SimulationContext.instance().get_or_create_backend(OVRTXRendererCfg()) publication = types.SimpleNamespace( transform_paths=[], geometry_timestamp=0, get_geometry_batches=lambda _format: batches ) @@ -1419,18 +1286,16 @@ def check_depth(rd, data, expected): ["rgb", "distance_to_image_plane"] if index == 0 else ["rgb", "distance_to_image_plane", "normals"] ) cfg.height, cfg.width = height, width - # One environment per render product splits the second camera in the asynchronous rows. The renderer + # One environment per render product splits the second deformable camera. The renderer # reads this value when it registers the camera. - split = asynchronous and index == 1 + split = geometry != "rigid" and index == 1 renderer.cfg.max_envs_per_render_product = 1 if split else "auto" spec = CameraRenderSpec( cfg=cfg, device="cuda:0", num_instances=2, view_count=2, - camera_prim_paths=tuple( - env_template.format(i) + f"/cam{index}" for i in range(1 if use_ovstage else 2) - ), + camera_prim_paths=tuple(env_template.format(i) + f"/cam{index}" for i in range(1)), ) rd = renderer.create_render_data(spec) assert len(rd.products) == (2 if split else 1) @@ -1471,20 +1336,15 @@ def capture_lighting() -> np.ndarray: noise = np.abs(ordinary - baseline[-8:].mean(axis=0)).mean(axis=(2, 3, 4)).max(axis=0) color = np.asarray([[0.9, 0.02, 0.02]], dtype=np.float32) dome_path = env_template.format(0) + "/Dome" - if use_ovstage: - with renderer.scene.query([dome_path]) as query: - renderer.scene.stage.write_attribute( - query, - "inputs:color", - ordinal=renderer.scene.ordinal, - tensors=color, - is_array=False, - ).wait() - renderer.scene.commit() - else: - renderer.backend.renderer.write_attribute( - [dome_path], "inputs:color", color, prim_mode=PrimMode.MUST_EXIST - ) + with renderer.scene.query([dome_path]) as query: + renderer.scene.stage.write_attribute( + query, + "inputs:color", + ordinal=renderer.scene.ordinal, + tensors=color, + is_array=False, + ).wait() + renderer.scene.commit() changed = capture_lighting() delta = np.abs(changed - before).mean(axis=(2, 3, 4)) assert delta[-8:, 0].mean() > 15.0, f"Selected dome update was not rendered: {delta[-8:].mean(axis=0)}" @@ -1505,14 +1365,10 @@ def capture_lighting() -> np.ndarray: for rd, data in cameras: renderer.read_output(rd, data) check_depth(*cameras[0], 4.5) - check_depth(*cameras[1], 3.5 if asynchronous else 5.5) - - if asynchronous: - renderer.render_batch([rd for rd, _ in cameras]) - for rd, data in cameras: - renderer.read_output(rd, data) - check_depth(*cameras[1], 5.5) - # Reuse camera buffers across producer streams without advancing the other camera. + check_depth(*cameras[1], 5.5) + + if geometry != "rigid": + # Reuse camera conversion buffers across producer streams without advancing the other camera. for height in (6.0, 8.0, 9.0): with wp.ScopedStream(wp.Stream("cuda:0")): positions = ProxyArray(wp.array([[0.0, 0, height]] * 2, dtype=wp.vec3f, device="cuda:0")) @@ -1520,45 +1376,40 @@ def capture_lighting() -> np.ndarray: renderer.render(cameras[0][0]) renderer.read_output(*cameras[0]) wp.synchronize_stream() + check_depth(*cameras[0], height - 0.5) check_depth(*cameras[1], 5.5) - check_depth(*cameras[0], 7.5) - renderer.reset(cameras[0][0]) - renderer.render(cameras[0][0]) - renderer.read_output(*cameras[0]) - check_depth(*cameras[0], 8.5) for height in (1.0, 2.0, 3.0): with wp.ScopedStream(wp.Stream("cuda:0")): for (source, _), vertices in zip(batches, initial_points, strict=True): source.points.assign(vertices + (0, 0, height)) publication.geometry_timestamp += 1 renderer.update_geometries() - # Physics may overwrite its storage immediately after SDP snapshots it. + # OvStage must consume the source before physics refills it. for source, _ in batches: source.points.fill_(wp.vec3f(-100)) renderer.render_batch([rd for rd, _ in cameras]) for rd, data in cameras: renderer.read_output(rd, data) wp.synchronize_stream() - check_depth(*cameras[0], 8.5 - (height - 1)) - check_depth(*cameras[1], 5.5 - (height - 1)) + check_depth(*cameras[0], 8.5 - height) + check_depth(*cameras[1], 5.5 - height) renderer.reset(cameras[1][0], [0]) renderer.render(cameras[1][0]) renderer.read_output(*cameras[1]) check_depth(*cameras[1], 2.5) - assert all(_camera_scope_exists(renderer, rd.render_scope_name, use_ovstage) for rd, _ in cameras) + assert all(_camera_scope_exists(renderer, rd.render_scope_name) for rd, _ in cameras) renderer.cleanup(cameras[0][0]) - assert not _camera_scope_exists(renderer, cameras[0][0].render_scope_name, use_ovstage) + assert not _camera_scope_exists(renderer, cameras[0][0].render_scope_name) renderer.render(cameras[1][0]) renderer.read_output(*cameras[1]) - check_depth(*cameras[1], 2.5 if asynchronous else 5.5) + check_depth(*cameras[1], 5.5 if geometry == "rigid" else 2.5) renderer.cleanup(cameras[1][0]) renderer.cleanup(cameras[1][0]) - assert not _camera_scope_exists(renderer, cameras[1][0].render_scope_name, use_ovstage) + assert not _camera_scope_exists(renderer, cameras[1][0].render_scope_name) finally: renderer.close() SimulationContext.instance().close_backend(renderer.backend) - if use_ovstage: - SimulationContext.instance().close_backend(renderer.scene) + SimulationContext.instance().close_backend(renderer.scene) # The default log level keeps native cloning quiet; lower levels print a warning per attribute of every cloned # environment, over a million lines at 8192 environments. assert "has no valid data" not in capfd.readouterr().out @@ -1590,16 +1441,14 @@ def _segmentation_key(pixel: torch.Tensor) -> int | tuple[int, ...]: @pytest.mark.integration @pytest.mark.rendering @pytest.mark.parametrize( - "use_ovstage, colorize_semantic, colorize_instance, simple_shading_types", + "colorize_semantic, colorize_instance, simple_shading_types", [ - pytest.param( - False, True, False, ("simple_shading_constant_diffuse", "simple_shading_diffuse_mdl"), id="legacy" - ), - pytest.param(True, False, True, ("simple_shading_full_mdl",), id="ovstage"), + (True, False, ("simple_shading_constant_diffuse", "simple_shading_diffuse_mdl")), + (False, True, ("simple_shading_full_mdl",)), ], ) def test_ovrtx_split_sensor_outputs_match_single_product( - monkeypatch, use_ovstage, colorize_semantic, colorize_instance, simple_shading_types + monkeypatch, colorize_semantic, colorize_instance, simple_shading_types ): """A sensor split into render products gives the outputs of one render product, in environment order. @@ -1611,8 +1460,7 @@ def test_ovrtx_split_sensor_outputs_match_single_product( The colorize settings apply to every sensor of a renderer, and each renderer start and stop costs seconds. So the two rows swap the colorize values. Simple shading is a data type of a camera, so the rows spread the three - simple shading types over their camera kinds. An asynchronous row would not test the wait for a failed step, - because the injected failure raises before that wait. + simple shading types over their camera kinds. """ import ovrtx import ovstage @@ -1628,13 +1476,12 @@ def test_ovrtx_split_sensor_outputs_match_single_product( pytest.skip("OVRTX rendering requires CUDA") num_envs = len(_SPLIT_CAMERA_POSITIONS) SimulationContext.instance().device = "cuda:0" - monkeypatch.setenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", str(int(use_ovstage))) - env_template = "/Lab/Cells/Cell{}" if use_ovstage else "/World/envs/env_{}" + env_template = "/Lab/Cells/Cell{}" stage = Usd.Stage.CreateInMemory() UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) UsdGeom.SetStageMetersPerUnit(stage, 1.0) UsdLux.DomeLight.Define(stage, "/World/Light").CreateIntensityAttr(1000.0) - for index in range(1 if use_ovstage else num_envs): + for index in range(1): UsdGeom.Xform.Define(stage, env_template.format(index)) # A render product has at most one simple shading type, and simple shading excludes rgb. So each simple shading # type needs a camera kind of its own. @@ -1680,7 +1527,7 @@ def step(renderer, render_products, *args, **kwargs): return step - # Both the legacy and the ovstage path render each frame with step. + # Every frame renders synchronously at a sealed stage ordinal. monkeypatch.setattr(ovrtx.Renderer, "step", record_products(ovrtx.Renderer.step)) cfg = OVRTXRendererCfg( colorize_semantic_segmentation=colorize_semantic, colorize_instance_segmentation=colorize_instance @@ -1720,9 +1567,7 @@ def add_camera(data_types, max_envs): device="cuda:0", num_instances=num_envs, view_count=num_envs, - camera_prim_paths=tuple( - env_template.format(i) + f"/cam{len(cameras)}" for i in range(1 if use_ovstage else num_envs) - ), + camera_prim_paths=tuple(env_template.format(i) + f"/cam{len(cameras)}" for i in range(1)), ) rd = renderer.create_render_data(spec) data = CameraData.allocate( @@ -1779,10 +1624,6 @@ def check_labels(reference, split): def write_texture_settings(path): # A script writes the settings with the runtime API, directly onto a render product. (scale_name, token_name), (scale, token) = texture_settings, texture_settings.values() - if not use_ovstage: - renderer.backend.renderer.write_attribute([path], scale_name, np.array([scale], np.float32)) - renderer.backend.renderer.write_attribute([path], token_name, [token], semantic=ovrtx.Semantic.TOKEN_STRING) - return token_id = np.array([renderer.scene.paths.intern_token(token).raw_id], np.uint64) with renderer.scene.query([path]) as query: for name, tensors, semantic in ( @@ -1795,11 +1636,6 @@ def write_texture_settings(path): def read_texture_settings(path): # A token reads back as its ID. Render products with the same token have the same ID. - if not use_ovstage: - return [ - np.from_dlpack(renderer.backend.renderer.read_attribute(name, [path])).item() - for name in texture_settings - ] names = [renderer.scene.paths.intern_token(name) for name in texture_settings] current = ovstage.OrdinalRange.latest(ovstage.ORDINAL_MAX) with renderer.scene.query([path]) as query, renderer.scene.stage.read_attributes(query, names, current) as read: @@ -1858,111 +1694,19 @@ def check_outputs(pairs): # Cleanup discards every render product of the sensor. The failed layout stays in the scene until then. # The remaining sensors do not render again here. The multi-camera test checks rendering after a cleanup. - assert _camera_scope_exists(renderer, failed_scope, use_ovstage) + assert _camera_scope_exists(renderer, failed_scope) while cameras: rd, _ = cameras.pop() renderer.cleanup(rd) - assert not _camera_scope_exists(renderer, rd.render_scope_name, use_ovstage) + assert not _camera_scope_exists(renderer, rd.render_scope_name) assert renderer.backend.render_products == { path for other, _ in cameras for path in other.render_product_paths } - assert not _camera_scope_exists(renderer, failed_scope, use_ovstage) + assert not _camera_scope_exists(renderer, failed_scope) finally: renderer.close() SimulationContext.instance().close_backend(renderer.backend) - if use_ovstage: - SimulationContext.instance().close_backend(renderer.scene) - - -@pytest.mark.parametrize("batch", [False, True], ids=["lazy", "batched"]) -def test_async_cameras_publish_independently_with_capture_metadata_and_reset(monkeypatch, batch): - """Real captures match delayed metadata; generated images and other cameras cannot replace them.""" - renderer = _make_ovrtx_renderer_without_backend() - renderer.cfg.async_rendering = True - renderer._initialized_scene = True - renderer._visual_material_writer_ref = None - cameras = [_make_ovrtx_camera_render_data(f"RenderCamera_{index}") for index in range(2)] - renderer._camera_render_data = cameras.copy() - camera_data = [] - for camera in cameras: - data = CameraData.allocate(["rgb"], 2, 2, 2, "cpu", renderer.supported_output_types()) - data.create_buffers(2, "cpu") - renderer.set_outputs(camera, data.output) - camera_data.append(data) - renderer.backend.render_products.update(camera.render_product_paths) - frame = ProxyArray(wp.zeros(2, dtype=wp.int64, device="cpu")) - operations = [] - ordinal = 0 - - def submit(render_products, delta_time): - operation = MagicMock() - frames = [types.SimpleNamespace(end_time=float(ordinal), value=ordinal)] - if batch: - # SDK capture times identify the real image independently of the returned list order. - frames.insert(0, types.SimpleNamespace(end_time=ordinal - 0.5, value=-ordinal)) - frames.append(types.SimpleNamespace(end_time=ordinal - 0.25, value=-ordinal)) - operation.wait.return_value.fetch.return_value = { - path: types.SimpleNamespace(frames=frames) for path in render_products - } - operations.append(operation) - return operation - - def consume(camera, frame, buffers): - buffers["rgba"].fill_(frame.value) - - renderer.backend.renderer = types.SimpleNamespace(step_async=submit) - consume = MagicMock(side_effect=consume) - monkeypatch.setattr(renderer, "_process_render_frame", consume) - - def capture(value, indices): - nonlocal ordinal - ordinal = value - frame.warp.fill_(value) - for index in indices: - data = camera_data[index] - data.pos_w.warp.fill_(wp.vec3f(value)) - data.intrinsic_matrices.warp.fill_(wp.mat33f(value)) - renderer.prepare_capture(cameras[index], data, frame) - if batch: - renderer.render_batch([cameras[index] for index in indices]) - else: - for index in indices: - renderer.render(cameras[index]) - for index in indices: - renderer.read_output(cameras[index], camera_data[index]) - - capture(1, (0, 1)) - capture(2, (0, 1)) - capture(3, (0,)) - assert consume.call_count == 3 # Priming images are not extracted again on the next capture. - for index, expected in enumerate((2, 1)): - data = camera_data[index] - np.testing.assert_array_equal(data.output["rgb"].warp.numpy(), expected) - for name in ("frame", "pos_w", "intrinsic_matrices"): - np.testing.assert_array_equal(data.info["rgb"]["capture"][name].warp.numpy(), expected) - np.testing.assert_array_equal(camera_data[0].pos_w.warp.numpy(), 3) - saved_capture = camera_data[0].info["rgb"]["capture"] - renderer.read_output(cameras[0], camera_data[0]) - assert camera_data[0].info["rgb"]["capture"] is saved_capture - assert renderer.drain_pending_renders() == [] - np.testing.assert_array_equal(camera_data[1].output["rgb"].warp.numpy(), 1) - - renderer.reset(cameras[0]) - capture(4, (0,)) - np.testing.assert_array_equal(camera_data[0].output["rgb"].warp.numpy(), 4) - np.testing.assert_array_equal(saved_capture["pos_w"].warp.numpy(), 2) - capture(5, (0, 1)) - assert consume.call_count == 5 - np.testing.assert_array_equal(camera_data[0].output["rgb"].warp.numpy(), 4) - np.testing.assert_array_equal(camera_data[1].output["rgb"].warp.numpy(), 2) - renderer.cleanup(cameras[0]) - - monkeypatch.setattr(renderer, "_process_render_frame", MagicMock(side_effect=RuntimeError("output extraction"))) - with pytest.raises(RuntimeError, match="output extraction"): - capture(6, (1,)) - renderer.cleanup(cameras[1]) - assert all(operation.wait.called for operation in operations) - assert renderer._camera_render_data == [] + SimulationContext.instance().close_backend(renderer.scene) def test_ovrtx_set_outputs_wraps_caller_torch_zero_copy(): @@ -2037,9 +1781,25 @@ def map_hdr(render_var): clone.assert_called_once_with(source, device="cpu") -@pytest.mark.parametrize("use_ovstage", [False, True]) -def test_ovrtx_process_frame_reads_authored_camera_render_vars(monkeypatch, use_ovstage): - """Both OVRTX APIs extract each camera's outputs using keys from its authored USD. +def test_inactive_ovrtx_route_does_not_acquire_native_resources(): + """An asset's rendering route is harmless when no OVRTX consumer is configured.""" + from isaaclab_ov.cloner import OvrtxReplicateContext + + from isaaclab.cloner import make_clone_plan, replicate + + sim = SimulationContext.instance() + sim.plan = make_clone_plan( + (AssetBaseCfg(prim_path="/World/envs/env_[^/]+/Visual", cloning_contexts=(OvrtxReplicateContext,)),), + ((0,),), + 2, + ) + replicate(sim.plan) + assert not sim.clone_contexts + assert not sim._backend_registry + + +def test_ovrtx_process_frame_reads_authored_camera_render_vars(monkeypatch): + """OVRTX extracts each camera's outputs using keys from its authored USD. The 5 environments fill an atlas of 3 x 2 tiles, and each tile has its own value. So a tile that is read from the wrong position gives a wrong value. @@ -2047,7 +1807,7 @@ def test_ovrtx_process_frame_reads_authored_camera_render_vars(monkeypatch, use_ from pxr import Usd num_envs = 5 - renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage, [f"/World/envs/env_{i}" for i in range(num_envs)]) + renderer = _make_mocked_scene_renderer(monkeypatch, [f"/World/envs/env_{i}" for i in range(num_envs)]) stages = {} build_render_product = ovrtx_renderer_module.build_render_product_as_string @@ -2123,14 +1883,13 @@ def tiled(values, channels, dtype): render_data.cleanup() -@pytest.mark.parametrize("use_ovstage", [False, True]) -def test_ovrtx_process_frame_stitches_split_frames_in_env_order(monkeypatch, use_ovstage): +def test_ovrtx_process_frame_stitches_split_frames_in_env_order(monkeypatch): """A split sensor registers one product per environment range and writes each product's frame into that range.""" from .test_ovrtx_annotator_utils import _encode_identifier_map num_envs = 5 camera_paths = [f"/World/envs/env_{i}/cam" for i in range(num_envs)] - renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage, [f"/World/envs/env_{i}" for i in range(num_envs)]) + renderer = _make_mocked_scene_renderer(monkeypatch, [f"/World/envs/env_{i}" for i in range(num_envs)]) renderer.cfg.colorize_semantic_segmentation = False renderer.scene.paths.intern_path.side_effect = lambda path: types.SimpleNamespace(raw_id=camera_paths.index(path)) renderer.scene.paths.intern_token.side_effect = lambda token: types.SimpleNamespace( @@ -2144,17 +1903,10 @@ def test_ovrtx_process_frame_stitches_split_frames_in_env_order(monkeypatch, use paths = render_data.render_product_paths assert paths == tuple(f"/RenderCamera_0/RenderProduct_{k}" for k in range(3)) assert renderer.backend.render_products == set(paths) - slices = [camera_paths[0:2], camera_paths[2:4], camera_paths[4:5]] - if use_ovstage: - queried = [c.args[0] for c in renderer.scene.paths.create_path_list_from_strings.call_args_list] - assert queried[:3] == [[path] for path in paths] - writes = [c for c in renderer.scene.stage.write_attribute.call_args_list if c.args[1] == "camera"] - assert [c.kwargs["tensors"].tolist() for c in writes] == [[0, 1], [2, 3], [4]] - else: - assert renderer.backend.renderer.write_array_attribute.call_args_list == [ - call(prim_paths=[path], attribute_name="camera", tensors=[cameras]) - for path, cameras in zip(paths, slices, strict=True) - ] + queried = [c.args[0] for c in renderer.scene.paths.create_path_list_from_strings.call_args_list] + assert queried[:3] == [[path] for path in paths] + writes = [c for c in renderer.scene.stage.write_attribute.call_args_list if c.args[1] == "camera"] + assert [c.kwargs["tensors"].tolist() for c in writes] == [[0, 1], [2, 3], [4]] # Products 0 and 1 hold two environments side by side, the last product holds one. Every product # carries the scene-wide label map, which is decoded once from the first product. @@ -2363,7 +2115,6 @@ def test_segmentation_outputs_share_metadata_and_clear_stale_labels(monkeypatch, @pytest.mark.parametrize( "setting, value, error", [ - ("ISAAC_LAB_OVRTX_USE_OVSTAGE", "true", "Expected 0 or 1"), ("ISAAC_LAB_SHARE_OVSTAGE", "1", "requires OVPhysX"), ], ) @@ -2436,47 +2187,32 @@ def test_ovrtx_map_render_var_orders_the_read_against_render_completion( assert events == ([] if gpu_side else ["wait"]) + ["consume", ("release", expected_stream)] -@pytest.mark.parametrize( - "use_ovstage, cleanup_directly, failure", - [(stage, direct, None) for stage in (False, True) for direct in (False, True)] - + [(False, False, "render"), (False, False, "write")], -) -def test_ovrtx_cleanup_releases_only_the_given_render_data(monkeypatch, cleanup_directly, use_ovstage, failure): - """Release only the given camera, even if its pending native operations fail.""" +@pytest.mark.parametrize("cleanup_directly, failure", [(False, False), (True, False), (False, True)]) +def test_ovrtx_cleanup_releases_only_the_given_render_data(monkeypatch, cleanup_directly, failure): + """Release only the given camera, including path handles when its query release fails.""" events = [] - renderer = _make_renderer_with_backend(events, use_ovstage) + renderer = _make_renderer_with_backend(events) other_camera = renderer._camera_render_data[0] render_data = _make_ovrtx_camera_render_data("RenderCamera_to_remove") renderer._camera_render_data.append(render_data) render_data.warp_buffers = {"rgba": wp.zeros((8, 16, 4), dtype=wp.uint8, device="cpu")} render_data.renderer_info = {"semantic_segmentation": {"idToLabels": {}}} - if use_ovstage: - render_data.camera_xform_binding = "to_remove" - render_data.resources.callback(renderer.scene.paths.destroy_path_list, "to_remove") - render_data.resources.enter_context(renderer.scene.stage.query_from_path_list("to_remove")) - else: - render_data.camera_xform_binding = _RecordingBinding(events, "pose") - render_data.resources.callback(render_data.camera_xform_binding.unbind) - render_data.intrinsic_bindings = [_RecordingBinding(events, "intrinsics")] - render_data.resources.callback(render_data.intrinsic_bindings[0].unbind) - - operations = [MagicMock(), MagicMock()] - operations[-1].wait.side_effect = RuntimeError("device lost") - if failure == "render": - render_data.pending = (operations[-1], {}) - elif failure == "write": - render_data.camera_writes = _AsyncWriteBuffers((object(), object())) - binding = MagicMock() - binding.write_async.side_effect = operations - stream = types.SimpleNamespace(cuda_stream=0) - for _ in operations: - render_data.camera_writes.submit(binding, object(), stream) - monkeypatch.setattr(wp, "synchronize_stream", lambda _stream: None) + render_data.camera_xform_binding = "to_remove" + render_data.resources.callback(renderer.scene.paths.destroy_path_list, "to_remove") + + @contextlib.contextmanager + def query(): + try: + yield "to_remove" + finally: + events.append("release_query:to_remove") + if failure: + raise RuntimeError("release failed") + + render_data.resources.enter_context(query()) if failure: - with pytest.raises(ExceptionGroup if failure == "render" else RuntimeError): + with pytest.raises(RuntimeError, match="release failed"): renderer.cleanup(render_data) - if failure == "write": - operations[0].wait.assert_called_once_with() if cleanup_directly: render_data.cleanup() @@ -2484,25 +2220,18 @@ def test_ovrtx_cleanup_releases_only_the_given_render_data(monkeypatch, cleanup_ renderer.cleanup(render_data) renderer.cleanup(render_data) - expected = ( - ["release_query:to_remove", "destroy_path_list:to_remove"] - if use_ovstage - else ["unbind:intrinsics", "unbind:pose"] - ) + expected = ["release_query:to_remove", "destroy_path_list:to_remove"] assert events == expected assert renderer._camera_render_data == [other_camera] assert render_data.camera_xform_binding is None - assert render_data.intrinsic_bindings == [] assert render_data.warp_buffers == {} assert render_data.renderer_info == {} - assert render_data.pending is render_data.ready is None assert renderer._initialized_scene is True -@pytest.mark.parametrize("stage_mode", ["legacy", "typed_handles"]) +@pytest.mark.parametrize("stage_mode", ["typed_handles"]) def test_pose_and_intrinsic_updates_target_the_given_camera(monkeypatch, stage_mode): """Distinct cameras, including a prototype-only wrist camera, bind every environment independently.""" - use_ovstage = stage_mode != "legacy" class Handle: def __init__(self, raw_id): @@ -2511,8 +2240,7 @@ def __init__(self, raw_id): def __int__(self): raise TypeError("use .raw_id for explicit numeric conversion") - renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage, ["/Lab/Cell0", "/Lab/Cell1"]) - renderer.backend.renderer.bind_attribute.side_effect = lambda **kwargs: MagicMock() + renderer = _make_mocked_scene_renderer(monkeypatch, ["/Lab/Cell0", "/Lab/Cell1"]) paths = [[f"/Lab/Cell{i}/{name}" for i in range(2)] for name in ("CameraA", "Robot/ee_link/palm_link/CameraB")] paths[0].reverse() paths[0][0] = "/Lab/Cell1/Robot/CameraA" @@ -2521,20 +2249,19 @@ def __int__(self): renderer.scene.paths.intern_token.side_effect = {"env_0": Handle(10), "env_1": Handle(11)}.__getitem__ path_ids = {path: 2**63 + i for i, path in enumerate(dict.fromkeys(path for group in paths for path in group))} renderer.scene.paths.intern_path.side_effect = lambda path: Handle(path_ids[path]) - if use_ovstage: - renderer.scene.render_copies_pending = False - monkeypatch.setattr(renderer, "_setup_xform_bindings", lambda stage: None) - monkeypatch.setattr(renderer, "_setup_geometry_bindings", lambda: None) - renderer.scene.resources = contextlib.ExitStack() - renderer.prepare_stage(SimulationContext.instance().stage, 2) - partition_write = next( - call - for call in renderer.scene.stage.write_attribute.call_args_list - if call.args[1] == "primvars:omni:scenePartition" - ) - np.testing.assert_array_equal(partition_write.kwargs["tensors"], [10, 11]) - assert partition_write.kwargs["tensors"].dtype == np.uint64 - renderer.scene.paths.create_path_list_from_strings.reset_mock() + renderer.scene.render_copies_pending = False + monkeypatch.setattr(renderer, "_setup_xform_bindings", lambda stage: None) + monkeypatch.setattr(renderer, "_setup_geometry_bindings", lambda: None) + renderer.scene.resources = contextlib.ExitStack() + renderer.prepare_stage(SimulationContext.instance().stage, 2) + partition_write = next( + call + for call in renderer.scene.stage.write_attribute.call_args_list + if call.args[1] == "primvars:omni:scenePartition" + ) + np.testing.assert_array_equal(partition_write.kwargs["tensors"], [10, 11]) + assert partition_write.kwargs["tensors"].dtype == np.uint64 + renderer.scene.paths.create_path_list_from_strings.reset_mock() cameras = [ renderer.create_render_data( CameraRenderSpec( @@ -2547,30 +2274,20 @@ def __int__(self): ) for index, camera_paths in enumerate((paths[0], paths[1][1:], paths[2], paths[3])) ] - if use_ovstage: - relationships = [ - call.kwargs["tensors"] - for call in renderer.scene.stage.write_attribute.call_args_list - if call.args[1] == "camera" - ] - for relationship, expected_paths in zip(relationships, paths, strict=True): - np.testing.assert_array_equal( - relationship, np.array([path_ids[path] for path in expected_paths], np.uint64) - ) - assert relationship.dtype == np.uint64 - partitions = [ - call.kwargs["tensors"].tolist() - for call in renderer.scene.stage.write_attribute.call_args_list - if call.args[1] == "omni:scenePartition" - ] - assert partitions == [[11, 10], [10, 11], [11]] - else: - partitions = [ - call.args[2] - for call in renderer.backend.renderer.write_attribute.call_args_list - if len(call.args) > 1 and call.args[1] == "omni:scenePartition" - ] - assert partitions == [["env_1", "env_0"], ["env_0", "env_1"], ["env_1"]] + relationships = [ + call.kwargs["tensors"] + for call in renderer.scene.stage.write_attribute.call_args_list + if call.args[1] == "camera" + ] + for relationship, expected_paths in zip(relationships, paths, strict=True): + np.testing.assert_array_equal(relationship, np.array([path_ids[path] for path in expected_paths], np.uint64)) + assert relationship.dtype == np.uint64 + partitions = [ + call.kwargs["tensors"].tolist() + for call in renderer.scene.stage.write_attribute.call_args_list + if call.args[1] == "omni:scenePartition" + ] + assert partitions == [[11, 10], [10, 11], [11]] assert not vars(renderer).keys() & {"_camera_xform_binding", "_camera_xform_query", "_camera_paths_list"} monkeypatch.setattr(wp, "get_stream", lambda device: types.SimpleNamespace(cuda_stream=99)) monkeypatch.setattr(wp, "synchronize_stream", lambda stream: None) @@ -2580,11 +2297,7 @@ def __int__(self): rotations = np.array([[1, 2, 3, 4], [0, 0, 0, 1]], dtype=np.float32) rotations /= np.linalg.norm(rotations, axis=1, keepdims=True) renderer.update_camera(cameras[1], positions, wp.array(rotations, dtype=wp.quatf, device="cpu"), None) - matrices = ( - renderer.scene.stage.write_attribute.call_args.kwargs["tensors"] - if use_ovstage - else cameras[1].camera_xform_binding.write_async.call_args.args[0] - ) + matrices = renderer.scene.stage.write_attribute.call_args.kwargs["tensors"] from pxr import Gf # OpenGL's right/up/back axes are -Y/+Z/-X in the world camera convention. @@ -2596,84 +2309,54 @@ def __int__(self): np.testing.assert_allclose(matrices.numpy(), expected, atol=1e-6, rtol=0) parameters = wp.zeros((5, 2), dtype=wp.float32, device="cpu") renderer.update_camera_intrinsics(cameras[1], wp.zeros(2, dtype=wp.mat33f, device="cpu"), parameters) - if use_ovstage: - assert renderer.scene.stage.write_attributes.call_args.args[0] is cameras[1].camera_xform_binding - bound_paths = [call.args[0] for call in renderer.scene.paths.create_path_list_from_strings.call_args_list] - assert bound_paths == [ - entry - for camera, targets in zip(cameras, paths, strict=True) - for entry in ([_single_render_product(camera).path], targets) - ] - else: - bound_paths = [call.kwargs["prim_paths"] for call in renderer.backend.renderer.bind_attribute.call_args_list] - binding_count = 1 + len(ovrtx_renderer_module._CAMERA_INTRINSIC_ATTRIBUTES) - assert bound_paths == [targets for targets in paths for _ in range(binding_count)] - assert all(not binding.write_async.called for binding in cameras[0].intrinsic_bindings) - for row, binding in enumerate(cameras[1].intrinsic_bindings): - assert binding.write_async.call_args.args[0].ptr == parameters[row].ptr - bindings = list(cameras[1].intrinsic_bindings) - cameras[1].cleanup() - cameras[1].cleanup() - assert all(binding.unbind.call_count == 1 for binding in bindings) - assert all(not binding.unbind.called for binding in cameras[0].intrinsic_bindings) - - -class _RecordingBinding: - def __init__(self, events: list[str], name: str): - self._events = events - self._name = name - - def unbind(self) -> None: - self._events.append(f"unbind:{self._name}") + assert renderer.scene.stage.write_attributes.call_args.args[0] is cameras[1].camera_xform_binding + bound_paths = [call.args[0] for call in renderer.scene.paths.create_path_list_from_strings.call_args_list] + assert bound_paths == [ + entry + for camera, targets in zip(cameras, paths, strict=True) + for entry in ([_single_render_product(camera).path], targets) + ] -def _make_renderer_with_backend(events: list[str], use_ovstage: bool) -> OVRTXRenderer: +def _make_renderer_with_backend(events: list[str]) -> OVRTXRenderer: """Exercise real binding setup with recorded native resource lifetimes.""" from isaaclab_ov.stage import OvstageBackend, OvstageBackendCfg renderer = _make_ovrtx_renderer_without_backend() renderer._device = "cpu" - renderer._use_ovstage = use_ovstage renderer._sdp = types.SimpleNamespace( backend=types.SimpleNamespace(transform_paths=["object"]), get_geometry_points=lambda: {"geometry": wp.zeros(1, dtype=wp.vec3f, device="cpu")}, ) renderer.backend.renderer = types.SimpleNamespace( - bind_attribute=lambda **kwargs: _RecordingBinding(events, "object"), - bind_array_attribute=lambda **kwargs: _RecordingBinding(events, "geometry"), - write_attribute=lambda **kwargs: None, destroy=lambda: events.append("destroy_renderer"), ) render_data = _make_ovrtx_camera_render_data("RenderCamera_camera") - if use_ovstage: - - @contextlib.contextmanager - def query(paths): - try: - yield paths - finally: - events.append(f"release_query:{paths}") - - renderer.scene = OvstageBackend.__new__(OvstageBackend) - SimulationContext.instance()._backend_registry.insert( - 0, (OvstageBackendCfg(scene_key=renderer.cfg), renderer.scene) - ) - renderer.scene.stage = types.SimpleNamespace( - query_from_path_list=query, - write_attribute=lambda *args, **kwargs: types.SimpleNamespace(wait=lambda: None), - ) - renderer.scene.paths = types.SimpleNamespace( - create_path_list_from_strings=lambda paths: paths[0], - destroy_path_list=lambda paths: events.append(f"destroy_path_list:{paths}"), - ) - renderer.scene.resources = contextlib.ExitStack() - renderer.scene.resources.callback(events.append, "close_stage") - renderer.scene.ordinal = 7 - render_data.resources.callback(renderer.scene.paths.destroy_path_list, "camera") - render_data.camera_xform_binding = render_data.resources.enter_context(query("camera")) - else: - render_data.camera_xform_binding = _RecordingBinding(events, "camera") - render_data.resources.callback(render_data.camera_xform_binding.unbind) + + @contextlib.contextmanager + def query(paths): + try: + yield paths + finally: + events.append(f"release_query:{paths}") + + renderer.scene = OvstageBackend.__new__(OvstageBackend) + SimulationContext.instance()._backend_registry.insert( + 0, (OvstageBackendCfg(scene_key=renderer.cfg), renderer.scene) + ) + renderer.scene.stage = types.SimpleNamespace( + query_from_path_list=query, + write_attribute=lambda *args, **kwargs: types.SimpleNamespace(wait=lambda: None), + ) + renderer.scene.paths = types.SimpleNamespace( + create_path_list_from_strings=lambda paths: paths[0], + destroy_path_list=lambda paths: events.append(f"destroy_path_list:{paths}"), + ) + renderer.scene.resources = contextlib.ExitStack() + renderer.scene.resources.callback(events.append, "close_stage") + renderer.scene.ordinal = 7 + render_data.resources.callback(renderer.scene.paths.destroy_path_list, "camera") + render_data.camera_xform_binding = render_data.resources.enter_context(query("camera")) renderer.scene.clone_copies = [] renderer._setup_xform_bindings(SimulationContext.instance().stage) renderer._setup_geometry_bindings() @@ -2684,41 +2367,27 @@ def query(paths): return renderer -@pytest.mark.parametrize("use_ovstage", [False, True]) -def test_ovrtx_close_releases_bindings_before_registry_resources(use_ovstage): +def test_ovrtx_close_releases_bindings_before_registry_resources(): """Release every binding before its native owners, propagating failures after cleanup.""" events: list[str] = [] - renderer = _make_renderer_with_backend(events, use_ovstage) - if use_ovstage: - renderer.close() - else: - - def fail_release(): - raise RuntimeError("binding release failed") - - renderer._bindings.callback(fail_release) - with pytest.raises(RuntimeError, match="binding release failed"): - renderer.close() + renderer = _make_renderer_with_backend(events) renderer.close() - if use_ovstage: - assert len(events) == 6 - for name in ("camera", "object", "geometry"): - assert events.index(f"release_query:{name}") < events.index(f"destroy_path_list:{name}") - else: - assert sorted(events) == ["unbind:camera", "unbind:geometry", "unbind:object"] + renderer.close() + assert len(events) == 6 + for name in ("camera", "object", "geometry"): + assert events.index(f"release_query:{name}") < events.index(f"destroy_path_list:{name}") assert renderer._object_xform_binding is renderer._geometry_points_binding is None SimulationContext.instance().close_backend(renderer.backend) assert events[-1] == "destroy_renderer" - if use_ovstage: - assert "close_stage" not in events - SimulationContext.instance().close_backend(renderer.scene) - assert events[-1] == "close_stage" + assert "close_stage" not in events + SimulationContext.instance().close_backend(renderer.scene) + assert events[-1] == "close_stage" events.clear() renderer.close() assert events == [] -@pytest.mark.parametrize("stage_mode", ["legacy", "independent", "independent-physics", "shared", "shared-debug"]) +@pytest.mark.parametrize("stage_mode", ["independent", "independent-physics", "shared", "shared-debug"]) def test_scene_preparation_respects_physics_population_and_camera_transform_mode(monkeypatch, tmp_path, stage_mode): """Physics population requires composed geometry; camera GPU reads are disabled before attachment.""" from pxr import Sdf, Usd, UsdGeom, UsdRender @@ -2739,13 +2408,11 @@ def test_scene_preparation_respects_physics_population_and_camera_transform_mode populate_physics = shared or stage_mode == "independent-physics" events = [] renderer = _make_ovrtx_renderer_without_backend() - renderer._use_ovstage = stage_mode != "legacy" if stage_mode == "shared-debug": renderer.cfg.temp_usd_dir = str(tmp_path / "debug") monkeypatch.setattr(ovrtx_renderer_module.ovstage, "PopulationDomain", types.SimpleNamespace(NONE=0, RENDERING=1)) monkeypatch.setattr(renderer, "_setup_xform_bindings", lambda stage: None) monkeypatch.setattr(renderer, "_setup_geometry_bindings", lambda: None) - monkeypatch.setattr(ovrtx_renderer_module, "ovrtx_replicate", lambda *args: None) export_stage = ovrtx_renderer_module.export_stage_to_string def export(*args, **kwargs): @@ -2763,7 +2430,7 @@ def load(text): assert result.GetPrimAtPath("/World/Asset").HasAuthoredReferences() is not populate_physics assert (layer.GetPrimAtPath("/World/Asset/Geometry") is not None) is populate_physics value = layer.GetAttributeAtPath(Sdf.Path(settings_path).AppendProperty(attribute_name)).default - assert value is (stage_mode != "legacy") + assert value is True events.append("load") def write(query, name, *, ordinal, tensors, is_array): @@ -2777,7 +2444,7 @@ def attach(native_stage): assert "disable-camera-reads" in events events.append("attach") - renderer.backend.renderer = types.SimpleNamespace(open_usd_from_string=load, attach_ovstage=attach) + renderer.backend.renderer = types.SimpleNamespace(attach_ovstage=attach) renderer.scene = types.SimpleNamespace( clone_env_paths=[], clone_copies=[], @@ -2793,14 +2460,12 @@ def attach(native_stage): commit=lambda: events.append("commit"), resources=contextlib.ExitStack(), ) - if renderer._use_ovstage: - renderer.scene.render_copies_pending = False + renderer.scene.render_copies_pending = False renderer.prepare_stage(stage, 0) assert renderer.backend.cfg.read_gpu_transforms is True assert events.count("export") == (stage_mode != "shared") - assert events.count("disable-camera-reads") == (stage_mode != "legacy") - if stage_mode != "legacy": - assert events[-2:] == ["commit", "attach"] + assert events.count("disable-camera-reads") == 1 + assert events[-2:] == ["commit", "attach"] @pytest.mark.parametrize( diff --git a/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py b/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py index b407ce1fa070..f7d64e1bba5c 100644 --- a/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py +++ b/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py @@ -11,7 +11,6 @@ import pytest import torch -import warp as wp _REQUIRED_MODULES = ("isaaclab_ov", "ovrtx") _MISSING_MODULES = [module for module in _REQUIRED_MODULES if importlib.util.find_spec(module) is None] @@ -24,7 +23,6 @@ if not _MISSING_MODULES: from isaaclab_ov.renderers.ovrtx_renderer import OVRTXRenderer from isaaclab_ov.renderers.ovrtx_renderer_cfg import OVRTXRendererCfg - from ovrtx import DataAccess from isaaclab.renderers.base_renderer import VisualMaterialBatch @@ -43,37 +41,12 @@ def wait(self): class _NativeRecorder: def __init__(self, events: list[str]): self.events = events - self.bindings = [] - self.writes = [] - - def bind_attribute(self, prim_paths, attribute_name, **kwargs): - binding = _NativeBinding(self, tuple(prim_paths), attribute_name, kwargs) - self.bindings.append(binding) - return binding def step(self, **kwargs): self.events.append("step") return {path: SimpleNamespace(frames=[object()]) for path in kwargs["render_products"]} -class _NativeBinding: - def __init__(self, recorder, prim_paths, attribute_name, kwargs): - self.recorder = recorder - self.prim_paths = prim_paths - self.attribute_name = attribute_name - self.kwargs = kwargs - self.unbound = False - - def write_async(self, tensor, **kwargs): - self.recorder.events.append(f"write:{self.attribute_name}") - completion = _Completion(lambda: self.recorder.events.append(f"wait:{self.attribute_name}")) - self.recorder.writes.append((self, tensor, kwargs, completion)) - return completion - - def unbind(self): - self.unbound = True - - class _OvstageRecorder: def __init__(self, events: list[str]): self.events = events @@ -119,25 +92,22 @@ def destroy_path_list(self, path_list): self.destroyed.append(path_list) -def _renderer(*, use_ovstage: bool = False): +def _renderer(): events: list[str] = [] renderer = OVRTXRenderer.__new__(OVRTXRenderer) renderer.backend = SimpleNamespace(render_products=set(), unrendered={}) renderer.scene = renderer.backend renderer._initialized_scene = True - renderer._needs_transform_initialization = False - renderer._use_ovstage = use_ovstage renderer.backend.renderer = _NativeRecorder(events) renderer._visual_material_writer_ref = None renderer.cfg = OVRTXRendererCfg() renderer._camera_render_data = [] - if use_ovstage: - from isaaclab_ov.stage import OvstageBackend + from isaaclab_ov.stage import OvstageBackend - renderer.scene = OvstageBackend.__new__(OvstageBackend) - renderer.scene.stage = _OvstageRecorder(events) - renderer.scene.paths = _PathRecorder() - renderer.scene.ordinal = 7 + renderer.scene = OvstageBackend.__new__(OvstageBackend) + renderer.scene.stage = _OvstageRecorder(events) + renderer.scene.paths = _PathRecorder() + renderer.scene.ordinal = 7 return renderer, events @@ -152,46 +122,21 @@ def _batch(channel: str, input_names: tuple[str, ...], values: torch.Tensor) -> ) +@pytest.mark.skipif(importlib.util.find_spec("ovstage") is None, reason="requires optional module: ovstage") @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") -def test_legacy_compiles_typed_bindings_and_publishes_selected_channels_zero_copy(): +def test_ovstage_compiles_queries_and_publishes_selected_channel_zero_copy(): renderer, _events = _renderer() - colors = torch.tensor([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]], device="cuda") - roughness = torch.tensor([0.1, 0.9], device="cuda") - texture_scale = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device="cuda") + roughness = torch.tensor([0.2, 0.8], device="cuda") + color = torch.zeros((3, 3), device="cuda") + texture_scale = torch.ones((2, 2), device="cuda") writer = renderer.visual_material_writer( ( - _batch("color", ("diffuse_color_constant", "diffuse_color_constant", "diffuseColor"), colors), _batch("roughness", ("roughness", "roughness"), roughness), + _batch("color", ("diffuseColor", "diffuseColor", "diffuse_color_constant"), color), _batch("texture_scale", ("texture_scale", "texture_scale"), texture_scale), ) ) - - writer( - {"texture_scale": torch.tensor([0], dtype=torch.int32, device="cuda")}, - torch.tensor([0], dtype=torch.int32, device="cuda"), - ) - assert renderer.backend.renderer.writes == [] - assert len(renderer.backend.renderer.bindings) == 4 - with wp.ScopedStream(wp.stream_from_torch(torch.cuda.default_stream())): - writer.publish() - - writes = {write[0].attribute_name: write for write in renderer.backend.renderer.writes} - assert set(writes) == {"inputs:texture_scale"} - write = writes["inputs:texture_scale"] - assert write[1].untyped_storage().data_ptr() == texture_scale.untyped_storage().data_ptr() - assert write[2]["data_access"] is DataAccess.ASYNC - assert write[2]["cuda_event"] == writer._event.cuda_event - assert write[2]["cuda_stream"] == 1 - writer.drain() - assert all(write[3].wait_count == 1 for write in renderer.backend.renderer.writes) - - -@pytest.mark.skipif(importlib.util.find_spec("ovstage") is None, reason="requires optional module: ovstage") -@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") -def test_ovstage_compiles_queries_and_publishes_selected_channel_zero_copy(): - renderer, _events = _renderer(use_ovstage=True) - roughness = torch.tensor([0.2, 0.8], device="cuda") - writer = renderer.visual_material_writer((_batch("roughness", ("roughness", "roughness"), roughness),)) + assert len(renderer.scene.paths.created) == 4 writer( {"roughness": torch.tensor([0], dtype=torch.int32, device="cuda")}, torch.tensor([1], dtype=torch.int32, device="cuda"), @@ -212,15 +157,8 @@ def test_ovstage_compiles_queries_and_publishes_selected_channel_zero_copy(): assert completion.wait_count == 1 -@pytest.mark.parametrize( - ("use_ovstage", "expected_events"), - ( - (False, ["publish", "step", "drain"]), - (True, ["publish", "floor", "wait:floor", "drain", "step"]), - ), -) -def test_render_publishes_and_drains_material_writes_at_backend_boundary(use_ovstage, expected_events): - renderer, events = _renderer(use_ovstage=use_ovstage) +def test_render_publishes_and_drains_material_writes_at_backend_boundary(): + renderer, events = _renderer() paths = ("/Render/Product0", "/Render/Product1") renderer._camera_render_data = [ SimpleNamespace(render_product_paths=(path,), warp_buffers={}, first_frame_error=None) for path in paths @@ -239,7 +177,7 @@ def drain(self): renderer._visual_material_writer_ref = lambda: writer renderer.render_batch(renderer._camera_render_data) - assert events == expected_events + assert events == ["publish", "floor", "wait:floor", "drain", "step"] @pytest.mark.parametrize( @@ -247,7 +185,7 @@ def drain(self): (("publish", ["publish", "drain"]), ("floor", ["publish", "floor", "drain"])), ) def test_ovstage_drain_does_not_mask_publish_or_floor_failure(failure, expected_events): - renderer, events = _renderer(use_ovstage=True) + renderer, events = _renderer() renderer._camera_render_data = [ SimpleNamespace(render_product_paths=("/RenderCamera_0/Product",), first_frame_error=None) ] @@ -277,22 +215,17 @@ def advance_write_floor(**_kwargs): @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") -@pytest.mark.parametrize("use_ovstage", [False, True]) -def test_writer_close_drains_and_releases_compiled_addresses(use_ovstage): - renderer, _events = _renderer(use_ovstage=use_ovstage) +def test_writer_close_drains_and_releases_compiled_addresses(): + renderer, _events = _renderer() writer = renderer.visual_material_writer((_batch("roughness", ("roughness",), torch.zeros(1, device="cuda")),)) writer(None) writer.publish() writer.close() writer.close() - if use_ovstage: - assert renderer.scene.stage.released == [f"query:{paths}" for paths in renderer.scene.paths.created] - assert renderer.scene.paths.destroyed == renderer.scene.paths.created - assert all(op.wait_count == 1 for op in renderer.scene.stage.completions) - else: - assert all(binding.unbound for binding in renderer.backend.renderer.bindings) - assert all(write[3].wait_count == 1 for write in renderer.backend.renderer.writes) + assert renderer.scene.stage.released == [f"query:{paths}" for paths in renderer.scene.paths.created] + assert renderer.scene.paths.destroyed == renderer.scene.paths.created + assert all(op.wait_count == 1 for op in renderer.scene.stage.completions) @pytest.mark.parametrize("values", [torch.zeros(1, dtype=torch.float64), torch.zeros(1, 4)]) @@ -306,7 +239,7 @@ def test_compilation_rejects_unsupported_device_buffers_before_backend_mutation( renderer.visual_material_writer((valid, invalid)) assert renderer._visual_material_writer_ref is None - assert renderer.backend.renderer.bindings == [] + assert renderer.scene.paths.created == [] def test_compilation_rejects_host_buffers_without_fallback(): @@ -315,7 +248,7 @@ def test_compilation_rejects_host_buffers_without_fallback(): renderer.visual_material_writer((_batch("color", ("diffuseColor",), torch.zeros(1, 3)),)) assert renderer._visual_material_writer_ref is None - assert renderer.backend.renderer.bindings == [] + assert renderer.scene.paths.created == [] def test_writer_factory_requires_ingested_detached_scene(): diff --git a/source/isaaclab_tasks/changelog.d/ovstage-only.changed.rst b/source/isaaclab_tasks/changelog.d/ovstage-only.changed.rst new file mode 100644 index 000000000000..c8dd34af9162 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/ovstage-only.changed.rst @@ -0,0 +1 @@ +* Migrated coffee-demo geometry updates to the OvStage-only OVRTX rendering path. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/rizon_sharpa_coffee/rendering.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/rizon_sharpa_coffee/rendering.py index e2fe5966e254..d9f86faff075 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/rizon_sharpa_coffee/rendering.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/rizon_sharpa_coffee/rendering.py @@ -8,7 +8,6 @@ from __future__ import annotations import math -from builtins import ExceptionGroup from typing import TYPE_CHECKING import numpy as np @@ -54,15 +53,11 @@ def _update_geometry(self, renderer) -> None: if self.rendering is not None: import ovstage from isaaclab_ov.stage import OVSTAGE_POINT_DTYPE - from ovrtx import DataAccess from pxr import Usd, UsdGeom, UsdShade self.rendering.update() queries = self._geometry_queries.setdefault(renderer, {}) - errors = renderer.drain_pending_renders() - if errors: - raise ExceptionGroup("RTX renders failed before coffee geometry update", errors) root = f"/Coffee_{id(self)}" attributes = {f"{root}/Grains": {"points": self.rendering._points}} if self.rendering._water is not None or not queries: @@ -96,32 +91,22 @@ def _update_geometry(self, renderer) -> None: UsdShade.MaterialBindingAPI.Apply(water.GetPrim()).Bind(material) usd = stage.GetRootLayer().ExportToString() renderer.geometry_resources.callback(self._geometry_queries.pop, renderer, None) - if renderer._use_ovstage: - reference = ovstage.population.add_usd_reference_from_string(renderer.scene.stage, usd, root) - renderer.geometry_resources.callback(renderer._remove_usd_reference, reference) - ovstage.population.apply_usd_changes(renderer.scene.stage, ordinal=renderer.scene.ordinal) - for path in attributes: - queries[path] = renderer.geometry_resources.enter_context(renderer.scene.query([path])) - else: - reference = renderer.backend.renderer.add_usd_reference_from_string(usd, root) - renderer.geometry_resources.callback(renderer.backend.renderer.remove_usd, reference) - queries.update(dict.fromkeys(attributes)) + reference = ovstage.population.add_usd_reference_from_string(renderer.scene.stage, usd, root) + renderer.geometry_resources.callback(renderer._remove_usd_reference, reference) + ovstage.population.apply_usd_changes(renderer.scene.stage, ordinal=renderer.scene.ordinal) + for path in attributes: + queries[path] = renderer.geometry_resources.enter_context(renderer.scene.query([path])) stream = wp.get_stream(self.rendering._model.device).cuda_stream or 1 semantics = {"points": ovstage.AttributeSemantic.POINT, "normals": ovstage.AttributeSemantic.NORMAL} for path, values in attributes.items(): for name, array in values.items(): - if renderer._use_ovstage: - renderer.scene.stage.write_attribute( - queries[path], name, ordinal=renderer.scene.ordinal, - tensors=[ovstage.make_dltensor(array, dtype=OVSTAGE_POINT_DTYPE) - if name in ("points", "normals", "primvars:displayColor") else array], - is_array=True, semantic=semantics.get(name, ovstage.AttributeSemantic.NONE), - cuda_stream=stream, - ).wait() # fmt: skip - else: - renderer.backend.renderer.write_array_attribute( - [path], name, [array], data_access=DataAccess.ASYNC, cuda_stream=stream - ) + renderer.scene.stage.write_attribute( + queries[path], name, ordinal=renderer.scene.ordinal, + tensors=[ovstage.make_dltensor(array, dtype=OVSTAGE_POINT_DTYPE) + if name in ("points", "normals", "primvars:displayColor") else array], + is_array=True, semantic=semantics.get(name, ovstage.AttributeSemantic.NONE), + cuda_stream=stream, + ).wait() # fmt: skip class CoffeeRendering: diff --git a/source/isaaclab_teleop/changelog.d/ovstage-only.skip b/source/isaaclab_teleop/changelog.d/ovstage-only.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_teleop/test/test_ovxr_renderer.py b/source/isaaclab_teleop/test/test_ovxr_renderer.py index cdad2269fdb5..53128337ca7a 100644 --- a/source/isaaclab_teleop/test/test_ovxr_renderer.py +++ b/source/isaaclab_teleop/test/test_ovxr_renderer.py @@ -1309,7 +1309,7 @@ def _register_ordinary_ovrtx(kind): if kind == "renderer": sim.get_or_create_backend(OVRTXRendererCfg(log_file_path="ordinary.log")) else: - cfg = OVRTXBackendCfg(use_ovstage=False, read_gpu_transforms=True, device=sim.device) + cfg = OVRTXBackendCfg(read_gpu_transforms=True, device=sim.device) sim._backend_registry.append((cfg, object())) diff --git a/source/isaaclab_visualizers/changelog.d/ovstage-only.changed.rst b/source/isaaclab_visualizers/changelog.d/ovstage-only.changed.rst new file mode 100644 index 000000000000..2fb6eaee25ff --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/ovstage-only.changed.rst @@ -0,0 +1 @@ +* Migrated Newton RTX viewer lighting and background controls to OvStage queries and population. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_rtx_appearance.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_rtx_appearance.py index f2e96bff5981..95d8da293be6 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_rtx_appearance.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_rtx_appearance.py @@ -151,16 +151,30 @@ def reset_settings(self) -> None: @property def available(self) -> bool: - """Whether the renderer accepts attribute writes; the shared-stage path does not yet.""" - return not self._renderer._use_ovstage and self._renderer.backend.renderer is not None + """Whether the renderer has a live OvStage for appearance writes.""" + return self._renderer.scene is not None and self._renderer.scene.stage is not None def _write(self, paths: list[str], attribute: str, tensor: Any, **kwargs: Any) -> bool: - from ovrtx import PrimMode + import ovstage + from isaaclab_ov.stage import xform_tensor_from_numpy try: - self._renderer.backend.renderer.write_attribute( - prim_paths=paths, attribute_name=attribute, tensor=tensor, prim_mode=PrimMode.MUST_EXIST, **kwargs - ) + scene = self._renderer.scene + semantic = kwargs.pop("semantic", ovstage.AttributeSemantic.NONE) + if semantic == ovstage.AttributeSemantic.TOKEN_ID: + tensor = np.array([scene.paths.intern_token(token).raw_id for token in tensor], dtype=np.uint64) + elif semantic == ovstage.AttributeSemantic.MATRIX: + tensor = xform_tensor_from_numpy(tensor) + with scene.query(paths) as query: + scene.stage.write_attribute( + query, + attribute, + ordinal=scene.ordinal, + tensors=tensor, + is_array=False, + semantic=semantic, + **kwargs, + ).wait() except Exception as exc: logger.exception("[NewtonRtxAppearance] Could not write %s.", attribute) self.error = f"Could not change {attribute}: {exc}" @@ -171,7 +185,16 @@ def _write(self, paths: list[str], attribute: str, tensor: Any, **kwargs: Any) - def _add(self, usd: str, path: str, what: str) -> Any | None: """Add a light layer to the OVRTX stage and return its reference, or None after reporting why not.""" try: - return self._renderer.backend.renderer.add_usd_reference_from_string(usd, path) + import ovstage + + scene = self._renderer.scene + reference = ovstage.population.add_usd_reference_from_string(scene.stage, usd, path) + try: + ovstage.population.apply_usd_changes(scene.stage, ordinal=scene.ordinal) + except Exception: + ovstage.population.remove_usd(scene.stage, reference) + raise + return reference except Exception as exc: logger.exception("[NewtonRtxAppearance] Could not add the %s.", what) self.error = f"Could not add the {what}: {exc}" @@ -202,7 +225,7 @@ def apply_lights(self, active: bool = True) -> bool: """ if active and not self._ensure_lights(): return False - from ovrtx import Semantic + from ovstage import AttributeSemantic scene_enabled, scale, tint = (self.scene_enabled, self.scene_scale, self.scene_tint) if active else ( True, 1.0, (1.0, 1.0, 1.0) @@ -224,7 +247,7 @@ def apply_lights(self, active: bool = True) -> bool: return False states = ["inherited" if show else "invisible" for show in visible] wrote = ( - self._write(paths, "visibility", states, semantic=Semantic.TOKEN_STRING) + self._write(paths, "visibility", states, semantic=AttributeSemantic.TOKEN_ID) and self._write(paths, "inputs:intensity", np.array(intensities, np.float32)) and self._write(paths, "inputs:color", np.array(colors, np.float32)) ) @@ -233,20 +256,20 @@ def apply_lights(self, active: bool = True) -> bool: [_SUN_PATH], "omni:xform", sun_matrix(self.sun_elevation, self.sun_azimuth)[None], - semantic=Semantic.XFORM_MAT4x4, + semantic=AttributeSemantic.MATRIX, ) return wrote def apply_background(self) -> bool: """Write the background type and, for a solid color, the color.""" - from ovrtx import Semantic + from ovstage import AttributeSemantic solid = self.background == 1 wrote = self._write( [self._product], "omni:rtx:background:source:type", ["color" if solid else "domeLight"], - semantic=Semantic.TOKEN_STRING, + semantic=AttributeSemantic.TOKEN_ID, ) if solid and wrote: wrote = self._write( @@ -306,7 +329,7 @@ def _apply_texture(self) -> bool: reference, self._dome_reference = self._dome_reference, None if reference is not None: try: - self._renderer.backend.renderer.remove_usd(reference) + self._renderer._remove_usd_reference(reference) except Exception: logger.debug("[NewtonRtxAppearance] The dome light was already removed.", exc_info=True) return self.apply_lights() @@ -334,6 +357,6 @@ def close(self) -> None: for reference in references: if reference is not None: try: - self._renderer.backend.renderer.remove_usd(reference) + self._renderer._remove_usd_reference(reference) except Exception: logger.debug("[NewtonRtxAppearance] A viewer light was already removed.", exc_info=True) diff --git a/source/isaaclab_visualizers/test/test_newton_rtx_appearance.py b/source/isaaclab_visualizers/test/test_newton_rtx_appearance.py index 9226ecfe1269..4091d3c38bb6 100644 --- a/source/isaaclab_visualizers/test/test_newton_rtx_appearance.py +++ b/source/isaaclab_visualizers/test/test_newton_rtx_appearance.py @@ -7,12 +7,15 @@ from __future__ import annotations +import contextlib import time from types import SimpleNamespace +from unittest.mock import Mock import numpy as np import pytest +ovstage = pytest.importorskip("ovstage") pytest.importorskip("ovrtx") from isaaclab_visualizers.newton import newton_rtx_appearance as module from isaaclab_visualizers.newton.newton_rtx_appearance import RtxAppearance, find_scene_lights, sun_matrix @@ -62,10 +65,15 @@ def __init__(self, fail: bool = False, fail_add: bool = False): self.writes, self.fail, self.fail_add = [], fail, fail_add self.added, self.removed = [], [] - def write_attribute(self, **kwargs): + def write_attribute(self, query, attribute, *, tensors, semantic, **kwargs): if self.fail: raise RuntimeError("write refused") - self.writes.append(kwargs) + if semantic == ovstage.AttributeSemantic.TOKEN_ID: + tensors = [self.tokens[int(token)] for token in tensors] + elif semantic == ovstage.AttributeSemantic.MATRIX: + tensors = ovstage.dltensor_to_numpy(tensors).reshape(-1, 4, 4) + self.writes.append(dict(prim_paths=query, attribute_name=attribute, tensor=tensors, **kwargs)) + return SimpleNamespace(wait=lambda: None) def add_usd_reference_from_string(self, usd, path): if self.fail_add: @@ -77,12 +85,37 @@ def remove_usd(self, reference): self.removed.append(reference) -def _appearance(native=None, background_color=None, ovstage=False): +@pytest.fixture(autouse=True) +def _population(monkeypatch): + monkeypatch.setattr( + ovstage.population, + "add_usd_reference_from_string", + lambda stage, usd, path: stage.add_usd_reference_from_string(usd, path), + ) + monkeypatch.setattr(ovstage.population, "apply_usd_changes", Mock()) + monkeypatch.setattr(ovstage.population, "remove_usd", lambda stage, ref: stage.remove_usd(ref)) + + +def _appearance(native=None, background_color=None): prims = [ _Prim("/World/sun", "DistantLight", 3000.0, (0.75, 0.75, 0.75)), _Prim("/World/cube", "Cube", 1.0, (1, 1, 1)), ] - renderer = SimpleNamespace(_use_ovstage=ovstage, backend=SimpleNamespace(renderer=native or _Native())) + native = native or _Native() + native.tokens = [] + + def intern(token): + if token not in native.tokens: + native.tokens.append(token) + return SimpleNamespace(raw_id=native.tokens.index(token)) + + renderer = SimpleNamespace( + scene=SimpleNamespace( + stage=native, ordinal=7, paths=SimpleNamespace(intern_token=intern), query=contextlib.nullcontext + ), + backend=SimpleNamespace(renderer=native), + _remove_usd_reference=native.remove_usd, + ) return RtxAppearance( _Stage(prims), renderer, "/RenderCamera_0/RenderProduct", background_color ), renderer.backend.renderer @@ -346,9 +379,10 @@ def test_closing_removes_the_viewer_lights_once(): assert native.removed == ["reference:/NewtonViewerDome:1", "reference:/NewtonViewerSun:2"] -def test_the_controls_are_unavailable_on_the_shared_stage_path(): - appearance, _ = _appearance(ovstage=True) - +def test_the_controls_require_a_live_stage(): + appearance, _ = _appearance() + assert appearance.available + appearance._renderer.scene.stage = None assert not appearance.available From 99b4b82fdb046a165b23b22e125a5dc551db3a17 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Wed, 25 Nov 2026 14:35:37 -0800 Subject: [PATCH 2/8] Deprecate async_rendering and ovrtx_replicate instead of dropping them Restore ovrtx_replicate as a deprecated alias and turn the async_rendering log message into a DeprecationWarning. Drop the camera and foveated-camera code that still treated async_rendering as pipelined, and remove the test setup for the ISAAC_LAB_OVRTX_USE_OVSTAGE variable that is no longer read. --- docs/source/api/lab_ov/isaaclab_ov.cloner.rst | 4 +- docs/source/concepts/renderers.rst | 8 ++-- .../changelog.d/ovstage-only.fixed.rst | 2 + .../isaaclab/sensors/camera/camera.py | 3 -- .../renderers/test_camera_output_contract.py | 17 ------- .../test_simulation_render_context.py | 14 +++--- .../changelog.d/ovstage-only.changed.rst | 1 + .../sensors/foveated_rtx_camera.py | 5 -- source/isaaclab_fovi/test/test_rtx_camera.py | 8 ---- .../changelog.d/ovstage-only.changed.rst | 9 ++-- .../changelog.d/ovstage-only.deprecated.rst | 3 ++ .../isaaclab_ov/cloner/__init__.py | 2 + .../isaaclab_ov/cloner/replicate.py | 47 ++++++++++++++++++- .../renderers/ovrtx_renderer_cfg.py | 4 +- .../test/test_ovrtx_renderer_contract.py | 30 ++++-------- ...t_ovrtx_renderer_rigid_object_rendering.py | 2 - 16 files changed, 81 insertions(+), 78 deletions(-) create mode 100644 source/isaaclab/changelog.d/ovstage-only.fixed.rst create mode 100644 source/isaaclab_fovi/changelog.d/ovstage-only.changed.rst create mode 100644 source/isaaclab_ov/changelog.d/ovstage-only.deprecated.rst diff --git a/docs/source/api/lab_ov/isaaclab_ov.cloner.rst b/docs/source/api/lab_ov/isaaclab_ov.cloner.rst index 3fd20d12aacb..96eed33aa5ce 100644 --- a/docs/source/api/lab_ov/isaaclab_ov.cloner.rst +++ b/docs/source/api/lab_ov/isaaclab_ov.cloner.rst @@ -17,8 +17,8 @@ Clone routing ``OvrtxReplicateContext.prepare`` in ``isaaclab_ov/cloner/replicate.py`` acquires a simulation-owned OvStage before constructing its OVRTX borrower. OVRTX always uses OvStage for population, cloning, -queries, and attribute writes, with either Newton or OVPhysX physics. The deprecated renderer-owned -scene API and ``ovrtx_replicate`` helper have been removed. Use +queries, and attribute writes, with either Newton or OVPhysX physics. The renderer-owned scene API, +deprecated in OVRTX 0.4, is no longer used. ``ovrtx_replicate`` is deprecated; use :func:`~isaaclab_ov.cloner.ovstage_replicate` for native rendering copies. ``ISAAC_LAB_OVRTX_USE_OVSTAGE`` is no longer read; remove it from launch scripts. diff --git a/docs/source/concepts/renderers.rst b/docs/source/concepts/renderers.rst index 78e540e328c0..3589ddcde1a0 100644 --- a/docs/source/concepts/renderers.rst +++ b/docs/source/concepts/renderers.rst @@ -403,10 +403,10 @@ OvStage rendering and migration OVRTX renders synchronously through OvStage. Scene writes finish and the stage ordinal is sealed before each render; camera outputs contain the current capture. -The deprecated renderer-owned scene path and its asynchronous pipeline have been removed. -:attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.async_rendering` remains a compatibility option: -setting it to ``True`` logs a warning and still renders synchronously. Remove this override from -existing configurations. Delayed-image ``capture`` metadata is no longer produced by OVRTX. +The renderer-owned scene path, deprecated in OVRTX 0.4, and its asynchronous pipeline have been +removed. :attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.async_rendering` is deprecated and has no +effect: setting it to ``True`` emits a :class:`DeprecationWarning` and still renders synchronously. +Remove this override from existing configurations. Delayed-image ``capture`` metadata is no longer produced by OVRTX. Use the camera's current pose and intrinsic fields with its rendered image. diff --git a/source/isaaclab/changelog.d/ovstage-only.fixed.rst b/source/isaaclab/changelog.d/ovstage-only.fixed.rst new file mode 100644 index 000000000000..904d9d5725f9 --- /dev/null +++ b/source/isaaclab/changelog.d/ovstage-only.fixed.rst @@ -0,0 +1,2 @@ +* Fixed camera tensor processors receiving no environment mask when an OVRTX camera set ``async_rendering=True``; + OVRTX now renders synchronously, so processors receive the mask of the current capture. diff --git a/source/isaaclab/isaaclab/sensors/camera/camera.py b/source/isaaclab/isaaclab/sensors/camera/camera.py index 7a1c84e3118a..bfae52c167f2 100644 --- a/source/isaaclab/isaaclab/sensors/camera/camera.py +++ b/source/isaaclab/isaaclab/sensors/camera/camera.py @@ -823,9 +823,6 @@ def _apply_tensor_processors(self, env_mask: wp.array) -> None: """Run the processors in order on the capture and publish their outputs.""" if not self.cfg.tensor_processors: return - # The current mask cannot describe an earlier asynchronous request's image. - if getattr(self.cfg.renderer_cfg, "async_rendering", False): - env_mask = None buffers = dict(self._render_outputs) for index, processor_cfg in enumerate(self.cfg.tensor_processors): # Construction needs the outputs of earlier processors, which exist after their first call. diff --git a/source/isaaclab/test/renderers/test_camera_output_contract.py b/source/isaaclab/test/renderers/test_camera_output_contract.py index 837792e6621d..d0367f0e6740 100644 --- a/source/isaaclab/test/renderers/test_camera_output_contract.py +++ b/source/isaaclab/test/renderers/test_camera_output_contract.py @@ -404,23 +404,6 @@ def processor(source: str, output: str) -> TensorProcessorCfg: validate(make_cfg("rgb_hdr", TensorProcessorCfg(func="ShadeDepth", inputs=["rgb_hdr"], outputs=["rgb"]))) -def test_camera_processors_allow_async_rendering(): - """Adding a processor requires no opt-in flag for asynchronous rendering.""" - pytest.importorskip("isaaclab_ov") - from isaaclab_ov.renderers.ovrtx_renderer_cfg import OVRTXRendererCfg - - cfg = CameraCfg( - height=32, - width=32, - prim_path="/World/Camera", - spawn=_SPAWN, - data_types=["rgb"], - renderer_cfg=OVRTXRendererCfg(async_rendering=True), - ) - cfg.tensor_processors = [TensorProcessorCfg(func=_ScaleProcessor, inputs=["rgb"], outputs=["half"])] - validate(cfg) - - @pytest.mark.parametrize("colorize", [True, False]) def test_newton_warp_segmentation_spec_follows_colorize_flags(colorize): """Segmentation specs are RGBA uint8 when colorized, else single-channel int32 (matching RTX).""" diff --git a/source/isaaclab/test/renderers/test_simulation_render_context.py b/source/isaaclab/test/renderers/test_simulation_render_context.py index ab10e322acdc..e50272f0d68c 100644 --- a/source/isaaclab/test/renderers/test_simulation_render_context.py +++ b/source/isaaclab/test/renderers/test_simulation_render_context.py @@ -301,11 +301,11 @@ def test_context_close_releases_writers_and_preserves_prepared_renderers(sim, fa class _CpuCamera(Camera): """Exercise capture timing with CPU buffers and an in-memory pose source.""" - def __init__(self, renderer, name, update_period=0.0, processors=(), outputs=(), async_rendering=False): + def __init__(self, renderer, name, update_period=0.0, processors=(), outputs=()): self.cfg = SimpleNamespace( update_period=update_period, update_latest_camera_pose=True, - renderer_cfg=SimpleNamespace(async_rendering=async_rendering), + renderer_cfg=SimpleNamespace(), tensor_processors=[ SimpleNamespace(func=Mock(return_value=processor), inputs=[], outputs=outputs) for processor in processors @@ -627,16 +627,16 @@ def test_camera_batch_respects_period_partial_reset_and_updated_pose(camera_batc renderer.render.assert_not_called() -@pytest.mark.parametrize("lazy,async_rendering", [(False, False), (True, False), (True, True)]) -def test_camera_processors_receive_the_due_environments(camera_batch_context, lazy, async_rendering): - """Synchronous captures forward the due mask; asynchronous captures cannot identify fresh rows.""" +@pytest.mark.parametrize("lazy", [False, True]) +def test_camera_processors_receive_the_due_environments(camera_batch_context, lazy): + """Captures forward the due mask to the processors.""" _, renderer, _ = camera_batch_context masks = [] processor = Mock( side_effect=lambda buffers, env_mask: masks.append(None if env_mask is None else env_mask.numpy().tolist()) or {} ) - camera = _CpuCamera(renderer, "camera", update_period=1.0, processors=[processor], async_rendering=async_rendering) + camera = _CpuCamera(renderer, "camera", update_period=1.0, processors=[processor]) scene = _camera_scene([camera], lazy=lazy) InteractiveScene.update(scene, 0.1) @@ -646,7 +646,7 @@ def test_camera_processors_receive_the_due_environments(camera_batch_context, la assert camera.data.info["pose"] == 0.0 # Only the reset environment is due for the second capture. - assert masks == ([None, None] if async_rendering else [[True, True], [False, True]]) + assert masks == [[True, True], [False, True]] def test_processor_outputs_carry_capture_metadata_and_match_their_configuration(camera_batch_context): diff --git a/source/isaaclab_fovi/changelog.d/ovstage-only.changed.rst b/source/isaaclab_fovi/changelog.d/ovstage-only.changed.rst new file mode 100644 index 000000000000..bfa8e32d1ce1 --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/ovstage-only.changed.rst @@ -0,0 +1 @@ +* Allowed ``mask_to_sensor_fov`` with ``async_rendering=True`` on OVRTX, since OVRTX now renders the current capture. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 3b58a42c0acf..678560675b90 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -68,11 +68,6 @@ class FoveatedRTXCamera(FoveatedCamera): def __init__(self, cfg: FoveatedCameraCfg): ovrtx = cfg.renderer_cfg.renderer_type == "ovrtx" - if ovrtx and cfg.renderer_cfg.async_rendering and cfg.mask_to_sensor_fov: - raise ValueError( - "OVRTX async_rendering returns the previous capture, which the sensor mask would cut with the current" - " gaze. Disable async_rendering or mask_to_sensor_fov." - ) # The parent ``Camera`` allocates the renderer-bound texture buffers; the published ones follow from them. self._texture_output: dict[str, ProxyArray] = {} self._foveated_output: dict[str, torch.Tensor] = {} diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index 1d666a4c3877..d08970490eb1 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -30,14 +30,6 @@ pytestmark = pytest.mark.kitless -def test_async_ovrtx_with_the_sensor_mask_is_rejected(monkeypatch) -> None: - # The camera never initializes, so its destructor has nothing to release. - monkeypatch.setattr(FoveatedRTXCamera, "__del__", lambda self: None, raising=False) - renderer = SimpleNamespace(renderer_type="ovrtx", async_rendering=True) - with pytest.raises(ValueError, match="async_rendering"): - FoveatedRTXCamera(SimpleNamespace(renderer_cfg=renderer, mask_to_sensor_fov=True)) - - def test_near_clip_comes_from_spawn_or_else_the_camera_prim() -> None: pxr = pytest.importorskip("pxr") stage = pxr.Usd.Stage.CreateInMemory() diff --git a/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst b/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst index 3e55a62e7a72..8d6b595607d8 100644 --- a/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst +++ b/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst @@ -1,5 +1,4 @@ -* **Breaking:** Removed the deprecated OVRTX-owned scene API and ``ovrtx_replicate``. All OVRTX cameras, - lidars, materials, meshes, and markers now use OvStage. Remove ``ISAAC_LAB_OVRTX_USE_OVSTAGE`` from launch - scripts and use ``ovstage_replicate`` for native rendering copies. Sharing with OVPhysX remains opt-in - through ``ISAAC_LAB_SHARE_OVSTAGE=1``. Rendering is synchronous; ``async_rendering=True`` warns and no - longer pipelines captures. +* **Breaking:** Removed the OVRTX-owned scene path, whose native scene API OVRTX deprecated in 0.4. All OVRTX + cameras, lidars, materials, meshes, and markers now use OvStage. Remove ``ISAAC_LAB_OVRTX_USE_OVSTAGE`` from + launch scripts. Sharing with OVPhysX remains opt-in through ``ISAAC_LAB_SHARE_OVSTAGE=1``. Rendering is + synchronous and no longer pipelines captures. diff --git a/source/isaaclab_ov/changelog.d/ovstage-only.deprecated.rst b/source/isaaclab_ov/changelog.d/ovstage-only.deprecated.rst new file mode 100644 index 000000000000..8e9c0d2bb71b --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovstage-only.deprecated.rst @@ -0,0 +1,3 @@ +* Deprecated :attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.async_rendering`, which has no effect now that OVRTX + renders synchronously through OvStage; setting it to ``True`` emits a :class:`DeprecationWarning`. +* Deprecated :func:`~isaaclab_ov.cloner.ovrtx_replicate` in favor of :func:`~isaaclab_ov.cloner.ovstage_replicate`. diff --git a/source/isaaclab_ov/isaaclab_ov/cloner/__init__.py b/source/isaaclab_ov/isaaclab_ov/cloner/__init__.py index c4f9fbaa6af6..41d60bbf1014 100644 --- a/source/isaaclab_ov/isaaclab_ov/cloner/__init__.py +++ b/source/isaaclab_ov/isaaclab_ov/cloner/__init__.py @@ -8,6 +8,7 @@ OvrtxReplicateContext, OvstageReplicateContext, ovphysx_replicate, + ovrtx_replicate, ovstage_replicate, ) @@ -16,5 +17,6 @@ "OvrtxReplicateContext", "OvstageReplicateContext", "ovphysx_replicate", + "ovrtx_replicate", "ovstage_replicate", ] diff --git a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py index 5d14cae86e86..a6767b5d1332 100644 --- a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py +++ b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py @@ -11,6 +11,7 @@ import math import os import re +import warnings from collections.abc import Iterable, Sequence from functools import cache, partial from typing import TYPE_CHECKING @@ -27,6 +28,8 @@ from isaaclab_ov.stage import ovstage_replicate as ovstage_replicate if TYPE_CHECKING: + import ovrtx + from isaaclab.cloner import ClonePlan from isaaclab.sim import SimulationContext @@ -220,7 +223,12 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext], renderer.backend = sim.get_or_create_backend(backend_cfg) renderer.scene = scene if renderer.cfg.async_rendering: - logger.warning("Asynchronous OVRTX rendering is unsupported with ovstage; rendering synchronously.") + warnings.warn( + "OVRTXRendererCfg.async_rendering is deprecated and has no effect: OVRTX renders synchronously" + " through OvStage. Remove the override; the field will be removed in a future release.", + DeprecationWarning, + stacklevel=2, + ) class OvstageReplicateContext(cloner.ReplicateContext): @@ -321,6 +329,43 @@ def ovphysx_replicate( sim.backend_manager._clone_recipes.extend(recipes) +def ovrtx_replicate( + renderer: ovrtx.Renderer, + copies: Sequence[tuple[str, Sequence[str]]], + env_paths: Sequence[str], + positions: np.ndarray | None = None, +) -> None: + """Apply prepared subtree copies and environment placement to a native OVRTX scene. + + .. deprecated:: + Isaac Lab no longer uses renderer-owned OVRTX scenes, and OVRTX deprecated their clone API in 0.4. + Use :func:`ovstage_replicate`. This function will be removed in a future release. + + Args: + renderer: Native renderer holding the source prims. + copies: Source paths paired with destination paths, ordered with parents before children. + Sources with no destinations are retained prototypes; self-copies must be excluded. + env_paths: Environment-root paths in placement order. + positions: Optional environment positions [m], shape ``[len(env_paths), 3]``. + """ + warnings.warn( + "ovrtx_replicate is deprecated; use ovstage_replicate. It will be removed in a future release.", + DeprecationWarning, + stacklevel=2, + ) + from ovrtx import PrimMode, Semantic # noqa: PLC0415 + + for source, targets in copies: + if targets: + renderer.clone_usd(source, targets) + if positions is not None and env_paths: + xforms = np.tile(np.eye(4, dtype=np.float64), (len(env_paths), 1, 1)) + xforms[:, 3, :3] = positions + renderer.write_attribute( + env_paths, "omni:xform", xforms, semantic=Semantic.XFORM_MAT4x4, prim_mode=PrimMode.MUST_EXIST + ) + + def _convert_legacy_joint_properties( layer: Sdf.Layer, friction_replacements: dict[str, tuple[float, float, float]] | None = None ) -> None: diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py index 4d7196a879ea..6d3dcd0d4401 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py @@ -67,9 +67,9 @@ class OVRTXRendererCfg(RendererCfg): """Route scene copies through OvStage; sharing with OvPhysX is optional.""" async_rendering: bool = False - """Compatibility option; OvStage always renders synchronously. + """Deprecated. OVRTX renders synchronously through OvStage, so this option has no effect. - Setting this to True logs a warning and uses synchronous rendering. + Setting this to True emits a :class:`DeprecationWarning`. The field will be removed in a future release. """ max_envs_per_render_product: int | Literal["auto", "all"] = "auto" diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 04b91d56187f..f8f2d27c4893 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -159,8 +159,7 @@ def _simulation_registry(monkeypatch): from isaaclab.renderers import RenderContext - for name in ("ISAAC_LAB_OVRTX_USE_OVSTAGE", "ISAAC_LAB_SHARE_OVSTAGE"): - monkeypatch.delenv(name, raising=False) + monkeypatch.delenv("ISAAC_LAB_SHARE_OVSTAGE", raising=False) registry = [] sim = types.SimpleNamespace( device="cpu", @@ -183,21 +182,8 @@ def _simulation_registry(monkeypatch): monkeypatch.setattr(SimulationContext, "_instance", sim) -@pytest.mark.parametrize( - "settings, with_physics, shared_physics", - [ - ((None, None), False, False), - ((None, None), True, False), - (("1", None), False, False), - (("1", None), True, False), - (("0", None), True, False), - ((None, "1"), True, True), - (("0", "1"), True, True), - ], -) -def test_ovrtx_renderer_config_enables_supported_runtime_options( - monkeypatch, tmp_path, settings, with_physics, shared_physics -): +@pytest.mark.parametrize("with_physics, shared_physics", [(False, False), (True, False), (True, True)]) +def test_ovrtx_renderer_config_enables_supported_runtime_options(monkeypatch, tmp_path, with_physics, shared_physics): """Preparation resolves routes before native allocation; registry ownership outlives borrowers.""" from isaaclab_ov.cloner import OvPhysxReplicateContext, OvrtxReplicateContext, OvstageReplicateContext @@ -233,9 +219,8 @@ def __init__(self, **kwargs): "cuda:1": types.SimpleNamespace(is_cuda=True, ordinal=1), } monkeypatch.setattr(ovrtx_renderer_module.wp, "get_device", devices.__getitem__) - for name, value in zip(("ISAAC_LAB_OVRTX_USE_OVSTAGE", "ISAAC_LAB_SHARE_OVSTAGE"), settings): - if value is not None: - monkeypatch.setenv(name, value) + if shared_physics: + monkeypatch.setenv("ISAAC_LAB_SHARE_OVSTAGE", "1") @contextlib.contextmanager def stage_resource(label): @@ -279,7 +264,9 @@ def create_stage(name, config): sim.render_context.ensure_initialize() # Adding a consumer must retain the route selected before native construction. monkeypatch.setenv("ISAAC_LAB_SHARE_OVSTAGE", str(int(not shared_physics))) - other = sim.get_or_create_backend(replace(cfg, enable_shadows=True)) + # The deprecated async flag only warns; the consumer still renders synchronously. + with pytest.warns(DeprecationWarning, match="async_rendering is deprecated"): + other = sim.get_or_create_backend(replace(cfg, enable_shadows=True, async_rendering=True)) assert other.backend is not None assert (other.backend is renderer.backend) is shared_physics assert (other.scene is renderer.scene) is shared_physics @@ -302,7 +289,6 @@ def create_stage(name, config): assert bool(sim.backend_manager._clone_recipes) is with_physics # Repeated preparation retains the selected resource identity. resources = tuple(sim._backend_registry) - monkeypatch.setenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", "0") OvrtxReplicateContext.prepare(sim, {OvrtxReplicateContext: set()}) assert tuple(sim._backend_registry) == resources assert renderer.scene.cfg.population_domains == ovrtx_renderer_module.ovstage.PopulationDomain.RENDERING diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_rigid_object_rendering.py b/source/isaaclab_ov/test/test_ovrtx_renderer_rigid_object_rendering.py index a1afb5a53d51..65293378fc5b 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_rigid_object_rendering.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_rigid_object_rendering.py @@ -50,7 +50,6 @@ def test_kinematic_rigid_object_scale_and_pose_are_rendered(monkeypatch: pytest. import ovstage from isaaclab_ov.renderers import ovrtx_renderer - monkeypatch.delenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", raising=False) monkeypatch.setenv("ISAAC_LAB_SHARE_OVSTAGE", "1") copies, attached = [], [] clone = ovstage.Stage.clone @@ -116,7 +115,6 @@ def test_shared_stage_isolates_contacts_and_interleaves_rendering_with_gravity(m from isaaclab.sensors import CameraCfg, ExposureCfg from isaaclab.utils import configclass, instantiate, replace - monkeypatch.setenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", "1") monkeypatch.setenv("ISAAC_LAB_SHARE_OVSTAGE", "1") @configclass From 691de664bb2a848b67d7c0211a57660ce95200c7 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Wed, 25 Nov 2026 15:49:04 -0800 Subject: [PATCH 3/8] Wait for particle geometry streaming before camera capture --- .../changelog.d/ovstage-particle-capture.fixed.rst | 3 +++ .../isaaclab_ov/renderers/ovrtx_renderer.py | 13 ++++++++++++- .../isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py | 10 +++++++++- 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 source/isaaclab_ov/changelog.d/ovstage-particle-capture.fixed.rst diff --git a/source/isaaclab_ov/changelog.d/ovstage-particle-capture.fixed.rst b/source/isaaclab_ov/changelog.d/ovstage-particle-capture.fixed.rst new file mode 100644 index 000000000000..43bee3f73d1c --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovstage-particle-capture.fixed.rst @@ -0,0 +1,3 @@ +* Fixed stale particle camera captures after OvStage geometry updates by waiting for renderer loading + on every capture in scenes with published geometry and USD particles. Other scenes retain the + first-capture-only wait to avoid extra steady-state render passes. diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 537d223226b4..186a18b4ed49 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -622,6 +622,7 @@ def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext): self._transform_buffer = SceneDataFormat.TransposedMatrix44d() self._object_scales: wp.array | None = None self._geometry_paths: list[str] = [] + self._has_particle_geometry = False self._visible_envs: np.ndarray | None = None self._hidden_marker_rows: torch.Tensor | None = None self._hidden_envs: wp.array | None = None @@ -689,6 +690,11 @@ def prepare_stage(self, stage: Usd.Stage, num_envs: int) -> None: ).wait() # fmt: skip self._setup_xform_bindings(stage) self._setup_geometry_bindings() + # Particle deformation can rebuild streamed geometry after the initial capture. + # Check the authored prototypes too: native clones need not exist on the USD stage. + self._has_particle_geometry = bool(self._geometry_paths) and any( + prim.IsA(UsdGeom.Points) for prim in stage.Traverse(Usd.TraverseInstanceProxies()) + ) # OVRTX 0.7's GPU camera cache mixes tiled views and misses pose updates. # Disable only camera reads before registering products (and before attaching # an OVStage), retaining GPU instance transforms for large articulated scenes. @@ -1873,7 +1879,11 @@ def _add_render_products(self, render_data: OVRTXCameraRenderData, spec: CameraR """Add the render products of ``render_data`` to the scene, and render them in every later step.""" scope = render_data.render_scope_name usd = build_render_product_as_string( - spec, render_data, device_id=self._warp_device.ordinal, enable_shadows=self.cfg.enable_shadows + spec, + render_data, + device_id=self._warp_device.ordinal, + enable_shadows=self.cfg.enable_shadows, + wait_for_streaming=self._has_particle_geometry, ) # Registration mutates the shared scene; finish renders using its existing products first. if self.cfg.temp_usd_dir is not None: @@ -1920,6 +1930,7 @@ def close(self) -> None: self._object_scales = None self._transform_buffer = SceneDataFormat.TransposedMatrix44d() self._geometry_paths = [] + self._has_particle_geometry = False self._geometry_timestamp = -1 self._transforms_timestamp = -1 self._output_id_color_buffers.clear() diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py index 1829d862dcf7..e91a1b0b6ab0 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py @@ -146,6 +146,7 @@ def build_render_product_as_string( *, device_id: int, enable_shadows: bool = False, + wait_for_streaming: bool = False, ) -> str: """Build a complete render product USD layer as a string. @@ -164,6 +165,9 @@ def build_render_product_as_string( enable_shadows: Whether lights cast shadows. Defaults to False. Only honored for the ``simple_shading_*`` data types, which are the ones that select RTX Minimal mode. + wait_for_streaming: Wait for loading on every capture for scenes with deforming particles. + Otherwise wait only on the first capture to avoid extra steady-state render passes. + Returns: Render product USD layer, including the USDA header and default prim metadata. """ @@ -210,6 +214,10 @@ def build_render_product_as_string( for _, name, source in render_var_configs ) + streaming_events = ( + '["AllLoadingFinished"]' if wait_for_streaming else '["AllLoadingFinished", "OnlyOnFirstRequest"]' + ) + def product_block(product: OVRTXRenderProduct) -> str: tiled_width = product.num_cols * render_data.width tiled_height = product.num_rows * render_data.height @@ -220,7 +228,7 @@ def product_block(product: OVRTXRenderProduct) -> str: uint[] deviceIds = [{device_id}] {bg_type_line} {render_mode_block} - token[] omni:rtx:waitForEvents = ["AllLoadingFinished", "OnlyOnFirstRequest"] + token[] omni:rtx:waitForEvents = {streaming_events} rel orderedVars = [{ordered_vars}] uniform int2 resolution = ({tiled_width}, {tiled_height}) }}''' From fc2b2a92ca1f01ecbed9e06a3810e1440dbbda78 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 07:09:11 -0800 Subject: [PATCH 4/8] Wait for loading when geometry callbacks publish particles Geometry callbacks, such as the coffee demo's grains, add USD Points to OvStage after camera products exist, so the stage check in prepare_stage cannot see them. Those products kept the first-capture-only loading wait, and the callback's particles were missing from the next captures. Move the wait flag to the shared engine. Switch the products of every renderer on the engine to wait on every capture when a scene has particles or when a geometry callback is registered. Signed-off-by: Alexander Temirov --- .../ovstage-particle-capture.fixed.rst | 5 +- .../isaaclab_ov/renderers/ovrtx_renderer.py | 29 ++++- .../isaaclab_ov/test/test_ovrtx_clone_plan.py | 1 + .../test/test_ovrtx_renderer_contract.py | 106 ++++++++++++++++++ 4 files changed, 134 insertions(+), 7 deletions(-) diff --git a/source/isaaclab_ov/changelog.d/ovstage-particle-capture.fixed.rst b/source/isaaclab_ov/changelog.d/ovstage-particle-capture.fixed.rst index 43bee3f73d1c..cc33fc9e0e7d 100644 --- a/source/isaaclab_ov/changelog.d/ovstage-particle-capture.fixed.rst +++ b/source/isaaclab_ov/changelog.d/ovstage-particle-capture.fixed.rst @@ -1,3 +1,4 @@ * Fixed stale particle camera captures after OvStage geometry updates by waiting for renderer loading - on every capture in scenes with published geometry and USD particles. Other scenes retain the - first-capture-only wait to avoid extra steady-state render passes. + on every capture in scenes with published geometry and USD particles, or with geometry callbacks, which + can add particles after cameras exist. Other scenes retain the first-capture-only wait to avoid extra + steady-state render passes. diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index a3cb3c24db2b..aee873338b1a 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -310,6 +310,8 @@ def __init__(self, cfg: OVRTXBackendCfg): self.cfg = cfg self.attached = False self.render_products: set[str] = set() + # Whether camera products wait for loading on every capture, which deforming particles need. + self.wait_for_loading = False # Camera sensors of every renderer on this engine without a rendered frame, and their renderers. self.unrendered: dict[OVRTXCameraRenderData, OVRTXRenderer] = {} # Resolve the wheel's native dependency here, including callers without a viewer. @@ -563,7 +565,6 @@ def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext): self._transform_buffer = SceneDataFormat.TransposedMatrix44d() self._object_scales: wp.array | None = None self._geometry_paths: list[str] = [] - self._has_particle_geometry = False self._visible_envs: np.ndarray | None = None self._hidden_marker_rows: torch.Tensor | None = None self._hidden_envs: wp.array | None = None @@ -633,9 +634,10 @@ def prepare_stage(self, stage: Usd.Stage, num_envs: int) -> None: self._setup_geometry_bindings() # Particle deformation can rebuild streamed geometry after the initial capture. # Check the authored prototypes too: native clones need not exist on the USD stage. - self._has_particle_geometry = bool(self._geometry_paths) and any( + if self._geometry_paths and any( prim.IsA(UsdGeom.Points) for prim in stage.Traverse(Usd.TraverseInstanceProxies()) - ) + ): + self._wait_for_loading() # OVRTX 0.7's GPU camera cache mixes tiled views and misses pose updates. # Disable only camera reads before registering products (and before attaching # an OVStage), retaining GPU instance transforms for large articulated scenes. @@ -1537,6 +1539,9 @@ def update_transforms(self) -> None: def update_geometries(self) -> None: """Write changed SDP geometry to OVRTX.""" + if self.geometry_callbacks: + # Callbacks can add particles after camera products exist, which the renderer cannot detect. + self._wait_for_loading() for callback in self.geometry_callbacks.values(): callback(self) for marker in tuple(self.markers): @@ -1812,7 +1817,7 @@ def _add_render_products(self, render_data: OVRTXCameraRenderData, spec: CameraR render_data, device_id=self._warp_device.ordinal, enable_shadows=self.cfg.enable_shadows, - wait_for_streaming=self._has_particle_geometry, + wait_for_streaming=self.backend.wait_for_loading, ) if self.cfg.temp_usd_dir is not None: _write_combined_stage(Path(self.cfg.temp_usd_dir), usd) @@ -1836,6 +1841,21 @@ def _add_render_products(self, render_data: OVRTXCameraRenderData, spec: CameraR self.backend.render_products.add(path) render_data.resources.callback(self.backend.render_products.discard, path) + def _wait_for_loading(self) -> None: + """Make every camera product of the engine, including later ones, wait for loading on every capture.""" + if self.backend.wait_for_loading: + return + self.backend.wait_for_loading = True + if not self.backend.render_products: + return + paths = sorted(self.backend.render_products) + events = np.array([self.scene.paths.intern_token("AllLoadingFinished").raw_id], dtype=np.uint64) + with self.scene.query(paths) as query: + self.scene.stage.write_attribute( + query, "omni:rtx:waitForEvents", ordinal=self.scene.ordinal, tensors=[events] * len(paths), + is_array=True, semantic=ovstage.AttributeSemantic.TOKEN_ID, + ).wait() # fmt: skip + def _remove_usd_reference(self, reference: int) -> None: """Publish removal of a private USD reference at the shared stage's current ordinal.""" ovstage.population.remove_usd(self.scene.stage, reference) @@ -1858,7 +1878,6 @@ def close(self) -> None: self._object_scales = None self._transform_buffer = SceneDataFormat.TransposedMatrix44d() self._geometry_paths = [] - self._has_particle_geometry = False self._geometry_timestamp = -1 self._transforms_timestamp = -1 self._output_id_color_buffers.clear() diff --git a/source/isaaclab_ov/test/test_ovrtx_clone_plan.py b/source/isaaclab_ov/test/test_ovrtx_clone_plan.py index bd0c6fa03fd8..59eaf8190729 100644 --- a/source/isaaclab_ov/test/test_ovrtx_clone_plan.py +++ b/source/isaaclab_ov/test/test_ovrtx_clone_plan.py @@ -93,6 +93,7 @@ def _make_ovrtx_renderer_without_backend() -> OVRTXRenderer: population_env_paths=[], clone_positions=None, render_products=set(), + wait_for_loading=False, unrendered={}, cfg=SimpleNamespace(read_gpu_transforms=False), ) diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index e13be004a19f..7ea69b256bf7 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -123,6 +123,7 @@ def _make_ovrtx_renderer_without_backend() -> OVRTXRenderer: renderer.scene.clone_env_paths = ["/World/envs/env_0", "/World/envs/env_1"] renderer.backend.attached = False renderer.backend.render_products = set() + renderer.backend.wait_for_loading = False renderer.backend.unrendered = {} cfg = OVRTXBackendCfg(scene_key=renderer.cfg, read_gpu_transforms=True, device="cpu") renderer.scene.stage = renderer.scene.paths = None @@ -1446,6 +1447,111 @@ def capture_lighting() -> np.ndarray: assert "has no valid data" not in capfd.readouterr().out +@pytest.mark.integration +@pytest.mark.rendering +def test_ovrtx_callback_particles_render_their_current_positions(): + """Particles that a geometry callback adds after the first capture render at their current positions.""" + + import ovstage + from isaaclab_ov.stage import OVSTAGE_POINT_DTYPE + + from pxr import Gf, Usd, UsdGeom, UsdLux + + from isaaclab.cloner import make_clone_plan, replicate + from isaaclab.scene_data import SceneDataProvider + + if not torch.cuda.is_available(): + pytest.skip("OVRTX rendering requires CUDA") + SimulationContext.instance().device = "cuda:0" + env_template = "/Lab/Cells/Cell{}" + stage = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + UsdGeom.Xform.Define(stage, env_template.format(0)) + UsdLux.DomeLight.Define(stage, "/World/Light").CreateIntensityAttr(1000.0) + camera = UsdGeom.Camera.Define(stage, env_template.format(0) + "/cam") + camera.CreateProjectionAttr("orthographic") + camera.CreateHorizontalApertureAttr(20.0) + camera.CreateVerticalApertureAttr(20.0) + camera.AddTranslateOp().Set(Gf.Vec3d(0, 0, 5)) + + renderer = SimulationContext.instance().get_or_create_backend(OVRTXRendererCfg()) + publication = types.SimpleNamespace( + transform_paths=[], geometry_timestamp=0, get_geometry_batches=lambda _format: [] + ) + renderer._sdp = SceneDataProvider(publication) + plan = make_clone_plan( + (AssetBaseCfg(prim_path=env_template.format("[^/]+"), cloning_contexts=renderer.cfg.cloning_contexts),), + ((0,),), + 2, + positions=np.zeros((2, 3), dtype=np.float32), + env_template=env_template, + ) + SimulationContext.instance().plan = plan + replicate(plan) + # Like the coffee demo, the callback owns its points and writes them into the shared scene every step. + points = wp.zeros(1, dtype=wp.vec3f, device="cuda:0") + queries = {} + + def publish(renderer): + if not queries: + layer = Usd.Stage.CreateInMemory() + layer.SetDefaultPrim(UsdGeom.Xform.Define(layer, "/Particles").GetPrim()) + grains = UsdGeom.Points.Define(layer, "/Particles/Grains") + grains.CreatePointsAttr([(0.0, 0.0, 0.0)]) + grains.CreateWidthsAttr([1.0]) + usd = layer.GetRootLayer().ExportToString() + ovstage.population.add_usd_reference_from_string(renderer.scene.stage, usd, "/Particles") + ovstage.population.apply_usd_changes(renderer.scene.stage, ordinal=renderer.scene.ordinal) + queries["grains"] = renderer.geometry_resources.enter_context(renderer.scene.query(["/Particles/Grains"])) + renderer.scene.stage.write_attribute( + queries["grains"], + "points", + ordinal=renderer.scene.ordinal, + tensors=[ovstage.make_dltensor(points, dtype=OVSTAGE_POINT_DTYPE)], + is_array=True, + semantic=ovstage.AttributeSemantic.POINT, + cuda_stream=wp.get_stream("cuda:0").cuda_stream or 1, + ).wait() + + try: + renderer.prepare_stage(stage, 2) + cfg = _make_camera_cfg(["distance_to_image_plane"]) + spec = CameraRenderSpec( + cfg=cfg, + device="cuda:0", + num_instances=2, + view_count=2, + camera_prim_paths=(env_template.format(0) + "/cam",), + ) + rd = renderer.create_render_data(spec) + data = CameraData.allocate( + data_types=cfg.data_types, + height=cfg.height, + width=cfg.width, + num_views=2, + device="cuda:0", + supported_specs=renderer.supported_output_types(), + ) + renderer.set_outputs(rd, data.output) + # The first capture is the only one that waits for loading unless the renderer knows about the particles. + renderer.update_geometries() + renderer.render(rd) + renderer.read_output(rd, data) + renderer.geometry_callbacks[publish] = publish + for height in (0.0, 1.0, 2.0, 3.0): + points.fill_(wp.vec3f(0.0, 0.0, height)) + renderer.update_geometries() + renderer.render(rd) + renderer.read_output(rd, data) + depth = data.output["distance_to_image_plane"].torch[:, cfg.height // 2, cfg.width // 2, 0] + torch.testing.assert_close(depth, torch.full((2,), 4.5 - height, device="cuda:0"), atol=0.02, rtol=0) + finally: + renderer.close() + SimulationContext.instance().close_backend(renderer.backend) + SimulationContext.instance().close_backend(renderer.scene) + + def _assert_split_outputs_match( reference: dict[str, ProxyArray], outputs: dict[str, ProxyArray], names: list[str] ) -> None: From c85d0260090882046bb04eca21f269bf4cb5df59 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 07:09:33 -0800 Subject: [PATCH 5/8] Keep deprecated OVRTX names and show their warnings Raise the async_rendering FutureWarning where OVRTXRenderer consumes its config, so Python shows it by default. Keep OVRTXBackendCfg.use_ovstage and OVRTXRenderer.drain_pending_renders, both in v3.0.0, as deprecated no-ops instead of removing them. Warn when ISAAC_LAB_OVRTX_USE_OVSTAGE is set, because it is now ignored. Name the removed capture metadata in the breaking changelog entry, file the camera mask change as changed, and add the testing-package skip fragment. Signed-off-by: Alexander Temirov --- docs/source/api/lab_ov/isaaclab_ov.cloner.rst | 2 +- docs/source/concepts/renderers.rst | 5 ++-- .../changelog.d/ovstage-only.skip | 0 .../changelog.d/ovstage-only.changed.rst | 2 ++ .../changelog.d/ovstage-only.fixed.rst | 2 -- .../isaaclab/sensors/camera/camera_data.py | 4 +-- .../changelog.d/ovstage-only.changed.rst | 7 +++-- .../changelog.d/ovstage-only.deprecated.rst | 5 +++- .../isaaclab_ov/cloner/replicate.py | 15 +++++----- .../isaaclab_ov/renderers/ovrtx_renderer.py | 30 +++++++++++++++++++ .../renderers/ovrtx_renderer_cfg.py | 7 ++++- .../test/test_ovrtx_renderer_contract.py | 18 +++++++++-- 12 files changed, 75 insertions(+), 22 deletions(-) create mode 100644 source/_isaaclab_testing/changelog.d/ovstage-only.skip create mode 100644 source/isaaclab/changelog.d/ovstage-only.changed.rst delete mode 100644 source/isaaclab/changelog.d/ovstage-only.fixed.rst diff --git a/docs/source/api/lab_ov/isaaclab_ov.cloner.rst b/docs/source/api/lab_ov/isaaclab_ov.cloner.rst index 96eed33aa5ce..5ead02813aba 100644 --- a/docs/source/api/lab_ov/isaaclab_ov.cloner.rst +++ b/docs/source/api/lab_ov/isaaclab_ov.cloner.rst @@ -21,7 +21,7 @@ queries, and attribute writes, with either Newton or OVPhysX physics. The render deprecated in OVRTX 0.4, is no longer used. ``ovrtx_replicate`` is deprecated; use :func:`~isaaclab_ov.cloner.ovstage_replicate` for native rendering copies. -``ISAAC_LAB_OVRTX_USE_OVSTAGE`` is no longer read; remove it from launch scripts. +``ISAAC_LAB_OVRTX_USE_OVSTAGE`` is ignored and warns when set; remove it from launch scripts. To share one OvStage with OVPhysX and OVRTX, set ``ISAAC_LAB_SHARE_OVSTAGE=1`` before creating the simulation. Sharing requires OVPhysX; otherwise rendering uses an independent OvStage. diff --git a/docs/source/concepts/renderers.rst b/docs/source/concepts/renderers.rst index caf59f143b7b..bcc20376e6be 100644 --- a/docs/source/concepts/renderers.rst +++ b/docs/source/concepts/renderers.rst @@ -405,8 +405,9 @@ before each render; camera outputs contain the current capture. The renderer-owned scene path, deprecated in OVRTX 0.4, and its asynchronous pipeline have been removed. :attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.async_rendering` is deprecated and has no -effect: setting it to ``True`` emits a :class:`DeprecationWarning` and still renders synchronously. -Remove this override from existing configurations. Delayed-image ``capture`` metadata is no longer produced by OVRTX. +effect: setting it to ``True`` emits a :class:`FutureWarning` and still renders synchronously. +Remove this override from existing configurations. ``OVRTXRenderer.drain_pending_renders`` is deprecated +and does nothing; remove its calls. OVRTX no longer produces delayed-image ``capture`` metadata. Use the camera's current pose and intrinsic fields with its rendered image. diff --git a/source/_isaaclab_testing/changelog.d/ovstage-only.skip b/source/_isaaclab_testing/changelog.d/ovstage-only.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/changelog.d/ovstage-only.changed.rst b/source/isaaclab/changelog.d/ovstage-only.changed.rst new file mode 100644 index 000000000000..2b1f4dec1234 --- /dev/null +++ b/source/isaaclab/changelog.d/ovstage-only.changed.rst @@ -0,0 +1,2 @@ +* Changed camera tensor processors to receive the environment mask of the current capture on OVRTX cameras, which + no longer deliver images asynchronously. Previously, ``async_rendering=True`` passed no mask. diff --git a/source/isaaclab/changelog.d/ovstage-only.fixed.rst b/source/isaaclab/changelog.d/ovstage-only.fixed.rst deleted file mode 100644 index 904d9d5725f9..000000000000 --- a/source/isaaclab/changelog.d/ovstage-only.fixed.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Fixed camera tensor processors receiving no environment mask when an OVRTX camera set ``async_rendering=True``; - OVRTX now renders synchronously, so processors receive the mask of the current capture. diff --git a/source/isaaclab/isaaclab/sensors/camera/camera_data.py b/source/isaaclab/isaaclab/sensors/camera/camera_data.py index fe71b32a218b..a0f77b20117d 100644 --- a/source/isaaclab/isaaclab/sensors/camera/camera_data.py +++ b/source/isaaclab/isaaclab/sensors/camera/camera_data.py @@ -45,8 +45,8 @@ def __init__(self): This contains extra information provided by the sensor such as semantic segmentation label mapping, prim paths. For semantic-based data, this corresponds to the ``"info"`` key in the output of the sensor. - Delayed OVRTX images also include ``"capture"``: snapshots of ``pos_w``, ``quat_w_world``, - ``intrinsic_matrices``, and per-environment ``frame`` indices matching the returned pixels. + Images that a renderer delivers asynchronously also include ``"capture"``: snapshots of ``pos_w``, + ``quat_w_world``, ``intrinsic_matrices``, and per-environment ``frame`` indices matching the returned pixels. Live pose and calibration fields are unchanged. Other outputs may have empty info. """ diff --git a/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst b/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst index 8d6b595607d8..f47eee7b5cab 100644 --- a/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst +++ b/source/isaaclab_ov/changelog.d/ovstage-only.changed.rst @@ -1,4 +1,5 @@ * **Breaking:** Removed the OVRTX-owned scene path, whose native scene API OVRTX deprecated in 0.4. All OVRTX - cameras, lidars, materials, meshes, and markers now use OvStage. Remove ``ISAAC_LAB_OVRTX_USE_OVSTAGE`` from - launch scripts. Sharing with OVPhysX remains opt-in through ``ISAAC_LAB_SHARE_OVSTAGE=1``. Rendering is - synchronous and no longer pipelines captures. + cameras, lidars, materials, meshes, and markers now use OvStage. ``ISAAC_LAB_OVRTX_USE_OVSTAGE`` is ignored and + warns when set; remove it from launch scripts. Sharing with OVPhysX remains opt-in through + ``ISAAC_LAB_SHARE_OVSTAGE=1``. Rendering is synchronous and no longer pipelines captures, so OVRTX no longer adds + ``"capture"`` metadata to :attr:`~isaaclab.sensors.camera.CameraData.info`. diff --git a/source/isaaclab_ov/changelog.d/ovstage-only.deprecated.rst b/source/isaaclab_ov/changelog.d/ovstage-only.deprecated.rst index 8e9c0d2bb71b..dc8135012120 100644 --- a/source/isaaclab_ov/changelog.d/ovstage-only.deprecated.rst +++ b/source/isaaclab_ov/changelog.d/ovstage-only.deprecated.rst @@ -1,3 +1,6 @@ * Deprecated :attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.async_rendering`, which has no effect now that OVRTX - renders synchronously through OvStage; setting it to ``True`` emits a :class:`DeprecationWarning`. + renders synchronously through OvStage; setting it to ``True`` emits a :class:`FutureWarning`. +* Deprecated :meth:`~isaaclab_ov.renderers.OVRTXRenderer.drain_pending_renders`, which does nothing now that every + capture completes before it is read, and :attr:`~isaaclab_ov.renderers.OVRTXBackendCfg.use_ovstage`, which has no + effect. * Deprecated :func:`~isaaclab_ov.cloner.ovrtx_replicate` in favor of :func:`~isaaclab_ov.cloner.ovstage_replicate`. diff --git a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py index a6767b5d1332..d7f154027234 100644 --- a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py +++ b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py @@ -176,6 +176,12 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext], if not renderers: routing.pop(OvrtxReplicateContext, None) return + if "ISAAC_LAB_OVRTX_USE_OVSTAGE" in os.environ: + warnings.warn( + "ISAAC_LAB_OVRTX_USE_OVSTAGE is ignored: OVRTX always renders through OvStage. Remove it.", + UserWarning, + stacklevel=2, + ) initialized = next((renderer for renderer in renderers if renderer.backend is not None), None) if initialized is not None: share_ovstage = initialized.backend.cfg.scene_key is None @@ -222,13 +228,6 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext], ) renderer.backend = sim.get_or_create_backend(backend_cfg) renderer.scene = scene - if renderer.cfg.async_rendering: - warnings.warn( - "OVRTXRendererCfg.async_rendering is deprecated and has no effect: OVRTX renders synchronously" - " through OvStage. Remove the override; the field will be removed in a future release.", - DeprecationWarning, - stacklevel=2, - ) class OvstageReplicateContext(cloner.ReplicateContext): @@ -337,7 +336,7 @@ def ovrtx_replicate( ) -> None: """Apply prepared subtree copies and environment placement to a native OVRTX scene. - .. deprecated:: + .. deprecated:: 3.2.0 Isaac Lab no longer uses renderer-owned OVRTX scenes, and OVRTX deprecated their clone API in 0.4. Use :func:`ovstage_replicate`. This function will be removed in a future release. diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index aee873338b1a..93b6e1673927 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -29,6 +29,7 @@ import os import sys import tempfile +import warnings import weakref from collections.abc import Callable, Iterable, Iterator, Sequence from pathlib import Path @@ -307,6 +308,13 @@ class OVRTXBackend: """Own one native renderer, independently of its camera products and OvStage.""" def __init__(self, cfg: OVRTXBackendCfg): + if not cfg.use_ovstage: + warnings.warn( + "OVRTXBackendCfg.use_ovstage is deprecated and has no effect: OVRTX always renders through OvStage." + " Remove the argument; the field will be removed in a future release.", + DeprecationWarning, + stacklevel=2, + ) self.cfg = cfg self.attached = False self.render_products: set[str] = set() @@ -549,6 +557,13 @@ def supported_output_types(self) -> dict[RenderBufferKind, RenderBufferSpec]: def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext): super().__init__(cfg, sim=sim) + if cfg.async_rendering: + warnings.warn( + "OVRTXRendererCfg.async_rendering is deprecated and has no effect: OVRTX renders synchronously" + " through OvStage. Remove the override; the field will be removed in a future release.", + FutureWarning, + stacklevel=2, + ) # A wrong value of the variable fails here, before the scene is built, and not at the first camera sensor. self._max_envs_per_render_product = _max_envs_per_render_product() self._warp_device = wp.get_device(self._sim.device) @@ -1795,6 +1810,21 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No result = self.backend.renderer.step(render_products=products, delta_time=delta_time, ordinal=ordinal) self._process_render_products(render_data, result) + def drain_pending_renders(self, cameras: Sequence[OVRTXCameraRenderData] | None = None) -> list[Exception]: + """Return no errors, because every capture completes before :meth:`render` returns. + + .. deprecated:: 3.2.0 + OVRTX renders synchronously through OvStage. Remove the call; this method will be removed in a future + release. + """ + warnings.warn( + "OVRTXRenderer.drain_pending_renders is deprecated and does nothing: OVRTX renders synchronously." + " Remove the call; the method will be removed in a future release.", + DeprecationWarning, + stacklevel=2, + ) + return [] + def cleanup(self, render_data: OVRTXCameraRenderData | None) -> None: """Release the render data's buffers. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.cleanup`. diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py index b55e9904a55c..014d6079f38a 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py @@ -35,6 +35,11 @@ class OVRTXBackendCfg(BackendCfg): # FIXME: revert once OVRTX stops warning on every cloned attribute without data. log_level: str = "error" """Native renderer log level.""" + use_ovstage: bool = True + """Deprecated. OVRTX always borrows a simulation-owned OvStage, so this option has no effect. + + Setting this to False emits a :class:`DeprecationWarning`. The field will be removed in a future release. + """ read_gpu_transforms: bool = MISSING """Whether OVRTX reads its GPU transform cache, resolved before native construction.""" device: str = MISSING @@ -69,7 +74,7 @@ class OVRTXRendererCfg(RendererCfg): async_rendering: bool = False """Deprecated. OVRTX renders synchronously through OvStage, so this option has no effect. - Setting this to True emits a :class:`DeprecationWarning`. The field will be removed in a future release. + Setting this to True emits a :class:`FutureWarning`. The field will be removed in a future release. """ temp_usd_dir: str | None = None diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 7ea69b256bf7..ba0152fc6858 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -274,9 +274,15 @@ def create_stage(name, config): sim.render_context.ensure_initialize() # Adding a consumer must retain the route selected before native construction. monkeypatch.setenv("ISAAC_LAB_SHARE_OVSTAGE", str(int(not shared_physics))) - # The deprecated async flag only warns; the consumer still renders synchronously. - with pytest.warns(DeprecationWarning, match="async_rendering is deprecated"): + # The deprecated options only warn; the consumer still renders synchronously through OvStage. + monkeypatch.setenv("ISAAC_LAB_OVRTX_USE_OVSTAGE", "0") + with ( + pytest.warns(FutureWarning, match="async_rendering is deprecated"), + pytest.warns(UserWarning, match="ISAAC_LAB_OVRTX_USE_OVSTAGE is ignored"), + ): other = sim.get_or_create_backend(replace(cfg, enable_shadows=True, async_rendering=True)) + with pytest.warns(DeprecationWarning, match="drain_pending_renders is deprecated"): + assert other.drain_pending_renders() == [] assert other.backend is not None assert (other.backend is renderer.backend) is shared_physics assert (other.scene is renderer.scene) is shared_physics @@ -333,6 +339,14 @@ def create_stage(name, config): assert not sim._backend_registry +def test_ovrtx_backend_warns_that_use_ovstage_is_deprecated(monkeypatch): + monkeypatch.setattr(ovrtx_renderer_module, "redirect_shader_cache", MagicMock()) + monkeypatch.setattr(ovrtx_renderer_module, "Renderer", MagicMock()) + cfg = OVRTXBackendCfg(use_ovstage=False, read_gpu_transforms=True, device="cpu") + with pytest.warns(DeprecationWarning, match="use_ovstage is deprecated"): + ovrtx_renderer_module.OVRTXBackend(cfg) + + # Each missing output runs with and without batching. @pytest.mark.parametrize( "missing_output, batch", From 3eb80c505347543d50e48a681249d122119fed5a Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 07:32:46 -0800 Subject: [PATCH 6/8] Reuse one hidden-pose copy now that scene writes wait The renderer kept one hidden-pose copy per SDP source buffer because an asynchronous write could still read the previous copy. OvStage writes now wait for consumption, so one copy serves every update. Keep the copy itself, so hiding environments never changes the shared publication. Signed-off-by: Alexander Temirov --- .../isaaclab_ov/renderers/ovrtx_renderer.py | 12 ++++++------ .../test/test_ovrtx_hidden_environments.py | 14 +++++++------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 93b6e1673927..919abc27b742 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -584,7 +584,7 @@ def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext): self._hidden_marker_rows: torch.Tensor | None = None self._hidden_envs: wp.array | None = None self._body_envs: wp.array | None = None - self._hidden_matrices: dict[int, wp.array] = {} + self._hidden_matrices: wp.array | None = None self._geometry_timestamp = -1 self._initialized_scene = False # Flat scratch buffers for colorized segmentation, one per output, sized for the largest tiled image. @@ -1512,11 +1512,11 @@ def _hide_environment_bodies(self, matrices: wp.array, stream: wp.Stream) -> wp. if self._hidden_envs is None: return matrices body_envs = self._body_environment_ids() - # A published buffer may be shared with other consumers, so hidden poses are written to a copy. The copy is - # kept per source buffer so visibility overrides do not alter the shared SDP publication. - hidden = self._hidden_matrices.get(matrices.ptr) - if hidden is None or len(hidden) != len(matrices): - hidden = self._hidden_matrices[matrices.ptr] = wp.empty(len(matrices), dtype=wp.mat44d, device=self._device) + # A published buffer may be shared with other consumers, so hidden poses are written to a copy. The scene + # write waits for consumption, so the next update can reuse it. + if self._hidden_matrices is None or len(self._hidden_matrices) != len(matrices): + self._hidden_matrices = wp.empty(len(matrices), dtype=wp.mat44d, device=self._device) + hidden = self._hidden_matrices wp.launch( hide_environment_bodies_kernel, len(matrices), diff --git a/source/isaaclab_ov/test/test_ovrtx_hidden_environments.py b/source/isaaclab_ov/test/test_ovrtx_hidden_environments.py index ca33f095259c..74093c947e9f 100644 --- a/source/isaaclab_ov/test/test_ovrtx_hidden_environments.py +++ b/source/isaaclab_ov/test/test_ovrtx_hidden_environments.py @@ -93,18 +93,18 @@ def test_bodies_map_to_the_environment_that_contains_their_prim_path(): assert renderer._body_environment_ids().numpy().tolist() == [0, 2, 3, 3, 3] -def test_hidden_poses_use_one_buffer_per_source_buffer(): +def test_hidden_poses_reuse_one_copy_and_leave_the_sources_unchanged(): renderer = _renderer(None) renderer._device = "cpu" renderer._body_envs = wp.array([0, 1], dtype=wp.int32, device="cpu") - renderer._hidden_matrices = {} + renderer._hidden_matrices = None renderer._hidden_envs = wp.array([1, 0, 0, 0], dtype=wp.uint8, device="cpu") renderer._sdp = SimpleNamespace(backend=SimpleNamespace(transform_paths=["a", "b"])) sources = [wp.zeros(2, dtype=wp.mat44d, device="cpu") for _ in range(2)] - first = [renderer._hide_environment_bodies(source, None) for source in sources] - again = [renderer._hide_environment_bodies(source, None) for source in sources] + hidden = [renderer._hide_environment_bodies(source, None) for source in sources] - # An asynchronous write may still read the previous frame's copy, so alternating sources must not share one. - assert first[0].ptr != first[1].ptr - assert [a.ptr for a in again] == [f.ptr for f in first] + # Scene writes wait for consumption, so every update reuses one copy; the shared publication keeps its poses. + assert hidden[0].ptr == hidden[1].ptr + assert hidden[1].numpy()[0].any() and not hidden[1].numpy()[1].any() + assert not any(source.numpy().any() for source in sources) From 50fde68432abfe90d28e3907c31518f3da2b2fdf Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 07:32:55 -0800 Subject: [PATCH 7/8] Remove single-path leftovers from tests, docs, and traces Build the OVRTX rendering cases as fixed OvStage pairs instead of loops over one stage, drop the one-value stage_mode parameter and range(1) camera paths, and remove the PPISP test that only covered the deprecated async_rendering. Record population, not a fake clone, in the camera ordering test, and check the second renderer's published transform. Keep ovrtx_replicate where main has it, stop tracing it, and correct the read_output, render, and material-module docstrings. Drop the unrelated as_posix change and the redundant camera-processor doc line. Signed-off-by: Alexander Temirov --- .github/PULL_REQUEST_TEMPLATE.md | 2 +- docs/source/concepts/sensors/camera.rst | 2 - scripts/benchmarks/nsys_trace.json | 1 - .../test/rendering/rendering_cases.py | 21 ++---- .../rendering/test_rendering_architecture.py | 2 +- .../renderers/test_camera_output_contract.py | 29 -------- .../isaaclab_ov/cloner/replicate.py | 74 +++++++++---------- .../isaaclab_ov/renderers/ovrtx_renderer.py | 4 +- .../isaaclab_ov/renderers/visual_materials.py | 2 +- .../isaaclab_ov/test/test_ovrtx_clone_plan.py | 6 +- .../test/test_ovrtx_deformable_bindings.py | 9 ++- .../test/test_ovrtx_renderer_contract.py | 7 +- 12 files changed, 61 insertions(+), 98 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index edc80a726d0a..865202a961cd 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -48,7 +48,7 @@ To upload images to a PR -- simply drag and drop an image while in edit mode and Docker and GPU tests run on demand. Push the commits you want tested, then comment `run-ci` on the pull request. Kitless OvStage rendering tests run with every activated build. -The `run-ci ovstage` command remains an alias for existing workflows. +`run-ci ovstage` still works and is the same as `run-ci`. - [ ] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [ ] I have run the [`pre-commit` checks](https://pre-commit.com/) with `uv run isaaclab --format` diff --git a/docs/source/concepts/sensors/camera.rst b/docs/source/concepts/sensors/camera.rst index 907c0fe609b1..59145fed4415 100644 --- a/docs/source/concepts/sensors/camera.rst +++ b/docs/source/concepts/sensors/camera.rst @@ -363,8 +363,6 @@ capture renders every environment. The camera calls each processor with ``env_ma environments due for the capture, whose frame and timestamp advance. Stateful processors (frame stacking, temporal filters, video generation) use it to advance only those rows. -OVRTX captures synchronously through OvStage, so its processors receive the mask for the current capture. - Post-render image signal processing ----------------------------------- diff --git a/scripts/benchmarks/nsys_trace.json b/scripts/benchmarks/nsys_trace.json index b57855a092a2..0fd4eb6f1e7c 100644 --- a/scripts/benchmarks/nsys_trace.json +++ b/scripts/benchmarks/nsys_trace.json @@ -264,7 +264,6 @@ "OVRTXRenderer.render", "OVRTXRenderer.render_batch", "OVRTXRenderer.read_output", - {"module": "isaaclab_ov.cloner.replicate", "function": "ovrtx_replicate"}, {"module": "isaaclab_ov.stage", "function": "ovstage_replicate"}, {"module": "isaaclab_ov.stage", "function": "export_stage_to_string"} ] diff --git a/source/_isaaclab_testing/test/rendering/rendering_cases.py b/source/_isaaclab_testing/test/rendering/rendering_cases.py index d4ee66d77a59..f4c5e5f22660 100644 --- a/source/_isaaclab_testing/test/rendering/rendering_cases.py +++ b/source/_isaaclab_testing/test/rendering/rendering_cases.py @@ -104,12 +104,8 @@ def golden_filename(self, aov: RenderBufferKind, namespace: str | None = None) - background_color=(1.0, 1.0, 0.0), ), ] -# Ovstage selects OVRTX's USD scene-reader path, independently of whether Newton or OVPhysX advances physics. -KITLESS_CASES = tuple( - (stage, case) - for case in _KITLESS_CASES - for stage in (("ovstage",) if case.renderer == "ovrtx" else ("legacy",)) -) +# OVRTX cases render through OvStage, independently of whether Newton or OVPhysX advances physics. +KITLESS_CASES = tuple(("ovstage" if case.renderer == "ovrtx" else "legacy", case) for case in _KITLESS_CASES) @dataclass(frozen=True) @@ -153,7 +149,7 @@ class SceneCoverage: for renderer in ("isaac_rtx", "newton_warp") ) SPECIALIZED_KITLESS_CASES = tuple( - (stage, case) + ("ovstage" if case.renderer == "ovrtx" else "legacy", case) for scene, coverage in SPECIALIZED_SCENE_COVERAGE.items() for physics in coverage.kitless_physics for case in ( @@ -172,7 +168,6 @@ class SceneCoverage: scene=scene, ), ) - for stage in (("ovstage",) if case.renderer == "ovrtx" else ("legacy",)) ) # Cable instance segmentation crashes native OVRTX (NVBUG#6463802); exercise its other channels. _CABLE_AOVS = (RenderBufferKind.RGB, RenderBufferKind.ALBEDO, RenderBufferKind.DEPTH, RenderBufferKind.NORMALS) @@ -218,7 +213,7 @@ class SceneCoverage: ) # OVRTX 0.6 returns no finite splat depth, so these scenes are compared on color only. GAUSSIAN_KITLESS_CASES = tuple( - (stage, case) + ("ovstage", case) for case in ( RenderCase( "newton", @@ -233,7 +228,6 @@ class SceneCoverage: scene="gaussian_splats_raspberry_4envs", ), ) - for stage in ("ovstage",) ) KIT_RENDERING_CASES = ( KIT_CASES @@ -265,16 +259,13 @@ class SceneCoverage: + SPECIALIZED_KITLESS_CASES + GAUSSIAN_KITLESS_CASES + ( - *((stage, RenderCase("newton", "ovrtx", _CABLE_AOVS, scene="franka_cable")) for stage in ("ovstage",)), + ("ovstage", RenderCase("newton", "ovrtx", _CABLE_AOVS, scene="franka_cable")), ("legacy", RenderCase("newton", "newton_warp", (RenderBufferKind.RGB,), scene="kuka_materials")), ( "legacy", RenderCase("newton", "newton_warp", (RenderBufferKind.RGB, RenderBufferKind.DEPTH), scene="franka_cable"), ), - *( - (stage, RenderCase("newton", "ovrtx", (RenderBufferKind.RGB,), scene="kuka_materials")) - for stage in ("ovstage",) - ), + ("ovstage", RenderCase("newton", "ovrtx", (RenderBufferKind.RGB,), scene="kuka_materials")), ) ) diff --git a/source/_isaaclab_testing/test/rendering/test_rendering_architecture.py b/source/_isaaclab_testing/test/rendering/test_rendering_architecture.py index 4a0d0c4e8f2c..e9b362c416ef 100644 --- a/source/_isaaclab_testing/test/rendering/test_rendering_architecture.py +++ b/source/_isaaclab_testing/test/rendering/test_rendering_architecture.py @@ -54,7 +54,7 @@ def test_case_and_golden_inventory() -> None: root = _SUITE / "golden_images/renderers" assert {path.relative_to(root) for path in root.rglob("*.png")} == expected subsets = tomllib.loads((_SOURCE.parent / ".github/test-subsets/postmerge-rendering.toml").read_text()) - suite = _SUITE.relative_to(_SOURCE.parent).as_posix() + suite = _SUITE.relative_to(_SOURCE.parent) nodes = {f"{suite}/test_rendering_kit.py::test_rendering[{case}]" for case in kit_ids} | { f"{suite}/test_rendering_kitless_{case.physics}_{case.renderer}.py::test_rendering[{stage}-{case.id}]" for stage, case in KITLESS_RENDERING_CASES diff --git a/source/isaaclab/test/renderers/test_camera_output_contract.py b/source/isaaclab/test/renderers/test_camera_output_contract.py index d0367f0e6740..8d0b06decdec 100644 --- a/source/isaaclab/test/renderers/test_camera_output_contract.py +++ b/source/isaaclab/test/renderers/test_camera_output_contract.py @@ -136,35 +136,6 @@ def test_camera_isp_is_resolved_during_construction(caplog, monkeypatch): assert not hasattr(BaseRenderer, "prepare_cameras") -def test_camera_async_ppisp_supports_explicit_and_legacy_configs(monkeypatch): - """Both explicit and deprecated PPISP configurations support asynchronous rendering.""" - pytest.importorskip("isaaclab_newton") - pytest.importorskip("newton") - pytest.importorskip("isaaclab_ov") - from isaaclab_newton.physics import NewtonCfg - from isaaclab_ov.renderers.ovrtx_renderer_cfg import OVRTXRendererCfg - from isaaclab_ppisp import PpispCfg, PpispProcessorCfg - - from isaaclab.sensors.camera import ExposureCfg - - with sim_utils.build_simulation_context(sim_cfg=sim_utils.SimulationCfg(device="cpu", physics=NewtonCfg())) as sim: - # Construction authors USD and validates configs; this test does not render. - monkeypatch.setattr( - type(sim), "get_or_create_backend", lambda self, cfg: SimpleNamespace(cleanup=lambda render_data: None) - ) - cfg = CameraCfg( - prim_path="/World/AsyncCamera", width=16, height=16, data_types=["rgb"], spawn=_SPAWN, - renderer_cfg=OVRTXRendererCfg(async_rendering=True), exposure=ExposureCfg(mode="neutral"), - tensor_processors=[PpispProcessorCfg(isp_cfg=PpispCfg())], - ) # fmt: skip - explicit = instantiate(cfg) - legacy_cfg = replace(cfg, prim_path="/World/LegacyCamera", tensor_processors=[], isp_cfg=PpispCfg()) - with pytest.warns(FutureWarning, match="isp_cfg is deprecated"): - legacy = instantiate(legacy_cfg) - assert len(explicit.cfg.tensor_processors) == len(legacy.cfg.tensor_processors) == 1 - assert explicit.cfg.renderer_cfg.async_rendering and legacy.cfg.renderer_cfg.async_rendering - - @contextlib.contextmanager def _newton_cube_scene(device: str, num_envs: int, **camera_kwargs): """Yield an unlit Newton camera above a cube in each environment, and a function that captures ``rgb_hdr``.""" diff --git a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py index d7f154027234..38318f610f34 100644 --- a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py +++ b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py @@ -285,6 +285,43 @@ def _prepare_scene_copies( backend.clone_positions = plan.positions +def ovrtx_replicate( + renderer: ovrtx.Renderer, + copies: Sequence[tuple[str, Sequence[str]]], + env_paths: Sequence[str], + positions: np.ndarray | None = None, +) -> None: + """Apply prepared subtree copies and environment placement to a native OVRTX scene. + + .. deprecated:: 3.2.0 + Isaac Lab no longer uses renderer-owned OVRTX scenes, and OVRTX deprecated their clone API in 0.4. + Use :func:`ovstage_replicate`. This function will be removed in a future release. + + Args: + renderer: Native renderer holding the source prims. + copies: Source paths paired with destination paths, ordered with parents before children. + Sources with no destinations are retained prototypes; self-copies must be excluded. + env_paths: Environment-root paths in placement order. + positions: Optional environment positions [m], shape ``[len(env_paths), 3]``. + """ + warnings.warn( + "ovrtx_replicate is deprecated; use ovstage_replicate. It will be removed in a future release.", + DeprecationWarning, + stacklevel=2, + ) + from ovrtx import PrimMode, Semantic # noqa: PLC0415 + + for source, targets in copies: + if targets: + renderer.clone_usd(source, targets) + if positions is not None and env_paths: + xforms = np.tile(np.eye(4, dtype=np.float64), (len(env_paths), 1, 1)) + xforms[:, 3, :3] = positions + renderer.write_attribute( + env_paths, "omni:xform", xforms, semantic=Semantic.XFORM_MAT4x4, prim_mode=PrimMode.MUST_EXIST + ) + + def ovphysx_replicate( stage: Usd.Stage, sources: Sequence[str], @@ -328,43 +365,6 @@ def ovphysx_replicate( sim.backend_manager._clone_recipes.extend(recipes) -def ovrtx_replicate( - renderer: ovrtx.Renderer, - copies: Sequence[tuple[str, Sequence[str]]], - env_paths: Sequence[str], - positions: np.ndarray | None = None, -) -> None: - """Apply prepared subtree copies and environment placement to a native OVRTX scene. - - .. deprecated:: 3.2.0 - Isaac Lab no longer uses renderer-owned OVRTX scenes, and OVRTX deprecated their clone API in 0.4. - Use :func:`ovstage_replicate`. This function will be removed in a future release. - - Args: - renderer: Native renderer holding the source prims. - copies: Source paths paired with destination paths, ordered with parents before children. - Sources with no destinations are retained prototypes; self-copies must be excluded. - env_paths: Environment-root paths in placement order. - positions: Optional environment positions [m], shape ``[len(env_paths), 3]``. - """ - warnings.warn( - "ovrtx_replicate is deprecated; use ovstage_replicate. It will be removed in a future release.", - DeprecationWarning, - stacklevel=2, - ) - from ovrtx import PrimMode, Semantic # noqa: PLC0415 - - for source, targets in copies: - if targets: - renderer.clone_usd(source, targets) - if positions is not None and env_paths: - xforms = np.tile(np.eye(4, dtype=np.float64), (len(env_paths), 1, 1)) - xforms[:, 3, :3] = positions - renderer.write_attribute( - env_paths, "omni:xform", xforms, semantic=Semantic.XFORM_MAT4x4, prim_mode=PrimMode.MUST_EXIST - ) - - def _convert_legacy_joint_properties( layer: Sdf.Layer, friction_replacements: dict[str, tuple[float, float, float]] | None = None ) -> None: diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 919abc27b742..018f2dd4b789 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -1064,7 +1064,7 @@ def read_output( render_data: OVRTXCameraRenderData, camera_data: CameraData | None = None, ) -> None: - """Publish the pixels of the render products of this sensor, and copy matching metadata when requested.""" + """Copy the metadata of each output into ``camera_data``; :meth:`render` already wrote the pixels.""" if camera_data is not None: assert camera_data.info is not None, "CameraData.info should be created in CameraData.allocate" for output_name in camera_data.info: @@ -1630,7 +1630,7 @@ def update_camera_intrinsics(self, render_data: OVRTXCameraRenderData, intrinsic ).wait() def render(self, render_data: OVRTXCameraRenderData) -> None: - """Submit one camera capture; :meth:`read_output` publishes the available image.""" + """Render one camera and write its outputs; see :meth:`render_batch`.""" self.render_batch((render_data,)) def log_mesh(self, name: str, *args, **kwargs) -> None: diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/visual_materials.py b/source/isaaclab_ov/isaaclab_ov/renderers/visual_materials.py index 4191788c8db2..bd801de29118 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/visual_materials.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/visual_materials.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Device-only visual-material writes for OVRTX-owned scenes.""" +"""Device-only visual-material writes to the OvStage scene that OVRTX renders.""" from __future__ import annotations diff --git a/source/isaaclab_ov/test/test_ovrtx_clone_plan.py b/source/isaaclab_ov/test/test_ovrtx_clone_plan.py index 59eaf8190729..7ebc45f276dc 100644 --- a/source/isaaclab_ov/test/test_ovrtx_clone_plan.py +++ b/source/isaaclab_ov/test/test_ovrtx_clone_plan.py @@ -381,7 +381,7 @@ def __str__(self): @pytest.mark.parametrize("global_camera", [False, True]) def test_create_render_data_binds_camera_after_cloning(monkeypatch, global_camera): - """Multi-environment initialization rewrites the RenderProduct cameras after cloning.""" + """Multi-environment initialization rewrites the RenderProduct cameras after population clones the scene.""" num_envs = 4 renderer = _make_ovrtx_renderer_without_backend() plan = make_clone_plan( @@ -394,7 +394,7 @@ def test_create_render_data_binds_camera_after_cloning(monkeypatch, global_camer call_order: list[str] = [] write_array_calls: list[tuple[list[str], str, list[list[str]]]] = [] - renderer.scene.populate = lambda _usd_string: call_order.extend(("open", "clone")) + renderer.scene.populate = lambda _usd_string: call_order.append("populate") _prepare_clones(renderer, plan) path_ids = {} @@ -422,7 +422,7 @@ def write(query, name, **kwargs): render_data = renderer.create_render_data(spec) (product,) = render_data.products - assert call_order == ["open", "clone", "partitions", "rewrite_cameras"] + assert call_order == ["populate", "partitions", "rewrite_cameras"] assert write_array_calls == [ ( [product.path], diff --git a/source/isaaclab_ov/test/test_ovrtx_deformable_bindings.py b/source/isaaclab_ov/test/test_ovrtx_deformable_bindings.py index 1e2dc97e7783..a7147c25058c 100644 --- a/source/isaaclab_ov/test/test_ovrtx_deformable_bindings.py +++ b/source/isaaclab_ov/test/test_ovrtx_deformable_bindings.py @@ -178,10 +178,15 @@ def test_update_transforms_consumes_sdp_matrices_once_per_publication(monkeypatc other, native = _make_renderer_without_backend() other._sdp = renderer._sdp other.scene = renderer.scene - other.scene.stage.write_attribute = lambda query, attribute, **kwargs: SimpleNamespace(wait=lambda: None) + published = [] + other.scene.stage.write_attribute = lambda query, attribute, **kwargs: ( + published.append(kwargs["tensors"]) or SimpleNamespace(wait=lambda: None) + ) other._setup_xform_bindings(stage) + published.clear() other.update_transforms() - assert other._transform_buffer.matrices is matrices + # Both renderers publish the shared SDP buffer instead of copying it. + assert len(published) == 1 and published[0] is matrices renderer.scene.stage.write_attribute = lambda query, attribute, **kwargs: ( writes.append((query, attribute, kwargs)) or SimpleNamespace(wait=lambda: None) diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index ba0152fc6858..ff0b7bd19f21 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -1341,7 +1341,7 @@ def check_depth(rd, data, expected): device="cuda:0", num_instances=2, view_count=2, - camera_prim_paths=tuple(env_template.format(i) + f"/cam{index}" for i in range(1)), + camera_prim_paths=(env_template.format(0) + f"/cam{index}",), ) rd = renderer.create_render_data(spec) assert len(rd.products) == (2 if split else 1) @@ -1750,7 +1750,7 @@ def add_camera(data_types, max_envs): renderer._max_envs_per_render_product = max_envs camera_cfg = _make_camera_cfg(data_types) camera_cfg.height = camera_cfg.width = _SPLIT_IMAGE_SIZE - paths = tuple(env_template.format(i) + f"/cam{len(cameras)}" for i in range(1)) + paths = (env_template.format(0) + f"/cam{len(cameras)}",) cameras.append(_add_live_camera(renderer, camera_cfg, paths, positions)) return cameras[-1] @@ -2418,8 +2418,7 @@ def query(): assert renderer._initialized_scene is True -@pytest.mark.parametrize("stage_mode", ["typed_handles"]) -def test_pose_and_intrinsic_updates_target_the_given_camera(monkeypatch, stage_mode): +def test_pose_and_intrinsic_updates_target_the_given_camera(monkeypatch): """Distinct cameras, including a prototype-only wrist camera, bind every environment independently.""" class Handle: From be63b95289b00a5e37869cab78c1017081712107 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 15:19:33 -0800 Subject: [PATCH 8/8] Remove obsolete renderer counter and clarify OvStage comment --- source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 018f2dd4b789..4395fa0fab73 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -340,7 +340,6 @@ def __init__(self, cfg: OVRTXBackendCfg): ) # Redirection may initialize the native library and must use the same settings. redirect_shader_cache(native_cfg) - self.next_camera_id = 0 self.renderer = Renderer(native_cfg) def detach(self) -> None: @@ -1854,7 +1853,7 @@ def _add_render_products(self, render_data: OVRTXCameraRenderData, spec: CameraR reference = ovstage.population.add_usd_reference_from_string(self.scene.stage, usd, f"/{scope}") render_data.resources.callback(self._remove_usd_reference, reference) ovstage.population.apply_usd_changes(self.scene.stage, ordinal=self.scene.ordinal) - # USD references drop external camera targets; author the relationship in Fabric. + # USD references drop external camera targets; author the relationship through OvStage. for product in render_data.products: with self.scene.query([product.path]) as query: self.scene.stage.write_attribute(