Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
* Added the ``isaac_sim`` (``--viz isaac-sim``) visualizer type to the visualizer registry and ``--viz`` selection.
Launch preparation declares its perspective cameras as scene cameras, as for ``newton_rtx``.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* Fixed kitless USD file spawns, such as visualization markers, dropping their
:class:`~isaaclab.sim.spawners.materials.PreviewSurfaceCfg` visual material. Preview surfaces are plain ``UsdShade``
and are now authored and bound without Kit; only MDL materials are still skipped.
2 changes: 1 addition & 1 deletion source/isaaclab/isaaclab/app/sim_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ def validate_launch( # noqa: C901
# Declare RTX perspective cameras before scene construction; runtime viewers only borrow their output.
scene_cfg = next((node for node in configs if isinstance(node, InteractiveSceneCfg)), None)
for viewer_index, visualizer in enumerate(viewers):
if not isinstance(visualizer.backend, NewtonRTXBackendCfg) or scene_cfg is None:
if not isinstance(visualizer.backend, (NewtonRTXBackendCfg, IsaacSimBackendCfg)) or scene_cfg is None:
continue
sources = (
[visualizer.view.source] if visualizer.view is not None else list(visualizer.cameras or [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -756,7 +756,8 @@ def spawn_from_usd_file(
shader, _, _ = UsdShade.Material(prim).ComputeSurfaceSource(context)
if shader:
_author_material_inputs(shader.GetPrim(), cfg.visual_material)
elif has_kit():
elif has_kit() or isinstance(cfg.visual_material, PreviewSurfaceCfg):
# Preview surfaces are plain UsdShade, so they are authored without Kit too; MDL materials need Kit.
material_path = (
cfg.visual_material_path
if cfg.visual_material_path.startswith("/")
Expand All @@ -765,7 +766,7 @@ def spawn_from_usd_file(
cfg.visual_material.func(material_path, cfg.visual_material)
bind_visual_material(prim_path, material_path, stage=stage)
else:
logger.warning("Skipping visual material application for '%s' in kitless mode.", prim_path)
logger.warning("Skipping MDL visual material application for '%s' in kitless mode.", prim_path)

for part_path, material_path in cfg.visual_material_bindings.items():
from pxr import UsdShade # noqa: PLC0415
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
* Added :attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.stage_provider` and
:attr:`~isaaclab_ov.stage.OvstageBackendCfg.stage_provider`, which let an application create the OVStage that an
OVRTX renderer's scene is populated into, for example a viewer that also reads the stage through its own stage
context. Population starts after any ordinals the provided stage already holds.
* Added :meth:`~isaaclab_ov.renderers.OVRTXRenderer.request_pick` and
:meth:`~isaaclab_ov.renderers.OVRTXRenderer.set_selection_outline`: viewport picking of a camera's next render and a
selection outline in every render product.
9 changes: 7 additions & 2 deletions source/isaaclab_ov/isaaclab_ov/cloner/replicate.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext],
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"
provided = any(renderer.cfg.stage_provider is not None for renderer in renderers)
use_ovstage = share_ovstage or value == "1" or provided
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:
Expand Down Expand Up @@ -225,7 +226,11 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext],
if use_ovstage:
domains = ovstage.PopulationDomain.ALL if share_ovstage else ovstage.PopulationDomain.RENDERING
scene = sim.get_or_create_backend(
OvstageBackendCfg(scene_key=None if share_ovstage else backend_cfg, population_domains=domains)
OvstageBackendCfg(
scene_key=None if share_ovstage else backend_cfg,
population_domains=domains,
stage_provider=renderer.cfg.stage_provider,
)
)
renderer.backend = sim.get_or_create_backend(backend_cfg)
renderer.scene = scene if use_ovstage else renderer.backend
Expand Down
96 changes: 96 additions & 0 deletions source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,12 @@
import os
import sys
import tempfile
import threading
import weakref
from builtins import ExceptionGroup
from collections import deque
from collections.abc import Callable, Iterable, Iterator, Sequence
from concurrent.futures import Future
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, TypeVar

Expand Down Expand Up @@ -59,6 +61,7 @@
Renderer,
RendererConfig,
RenderProductSetOutputs,
SelectionGroupStyle,
Semantic,
TextureStreamingMode,
)
Expand Down Expand Up @@ -320,6 +323,13 @@ def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext):
self.markers: dict[Any, OVRTXMarkers] = {}
self.marker_groups: Iterable = ()
self.geometry_callbacks: dict[Any, Callable[[OVRTXRenderer], None]] = {}
self._selection_lock = threading.Lock()
self._picks: dict[str, tuple[tuple[float, float, float, float], Future]] = {}
"""Pick rectangles per render product, answered by the product's next synchronous render."""
self._selection: list[str] | None = None
"""Selection outline to apply before the next render, or ``None`` if unchanged."""
self._outlined: list[str] = []
self._selection_styled = False
self.geometry_resources = contextlib.ExitStack()
self._sdp = self._sim.get_scene_data_provider()
self._transforms_timestamp = -1
Expand Down Expand Up @@ -939,6 +949,89 @@ def _process_render_products(
data.warp_buffers[str(RenderBufferKind.RGBA)],
)

def request_pick(self, camera_path: str, rect: tuple[float, float, float, float]) -> Future:
"""Ask which prims a camera's next render shows in a rectangle of its image; thread-safe.

Args:
camera_path: Prim path of a camera this renderer renders.
rect: ``(left, top, right, bottom)`` in ``[0, 1]`` with a top-left origin.

Returns:
A future of the hit prim paths in hit order, without repeats. A newer request for the same camera
cancels it. Synchronous renders answer picks; asynchronous rendering leaves them pending.

Raises:
KeyError: This renderer renders no camera at ``camera_path``.
"""
product = next(
(data.render_product_path for data in self._camera_render_data if camera_path in data.camera_paths), None
)
if product is None:
raise KeyError(f"No OVRTX camera at {camera_path!r}")
future: Future = Future()
with self._selection_lock:
previous = self._picks.get(product)
self._picks[product] = (rect, future)
if previous is not None:
previous[1].cancel()
return future

@property
def has_pending_picks(self) -> bool:
"""Whether a pick waits for a render."""
with self._selection_lock:
return bool(self._picks)

def set_selection_outline(self, paths: Sequence[str]) -> None:
"""Outline ``paths`` in every product from the next render on; an empty selection clears it. Thread-safe."""
with self._selection_lock:
self._selection = list(paths)

def _prepare_selection(self, products: set[str]) -> dict[str, tuple[tuple[float, float, float, float], Future]]:
"""Apply a changed selection outline and enqueue the picks the next render answers."""
with self._selection_lock:
selection, self._selection = self._selection, None
picks = {product: self._picks.pop(product) for product in list(self._picks) if product in products}
renderer = self.backend.renderer
if selection is not None:
if not self._selection_styled:
# Kit's selection colour: an orange outline and no fill.
style = SelectionGroupStyle(outline_color=(1.0, 0.6, 0.0, 1.0), fill_color=(0.0, 0.0, 0.0, 0.0))
renderer.set_selection_group_styles({1: style})
self._selection_styled = True
if self._outlined:
renderer.set_selection_outline_group_strings(self._outlined, 0)
if selection:
renderer.set_selection_outline_group_strings(selection, 1)
self._outlined = selection
for product, (rect, _) in picks.items():
renderer.enqueue_pick_query(product, *rect)
return picks

def _answer_picks(self, picks: dict[str, tuple[Any, Future]], products: RenderProductSetOutputs) -> None:
"""Resolve picks from their products' pick-hit output."""
for product, (_, future) in picks.items():
if future.done():
continue
try:
paths: list[str] = []
frames = products[product].frames if product in products.keys() else ()
render_vars = frames[0].render_vars if frames else {}
hits = next((var for name, var in render_vars.items() if "pick_hit" in name), None)
if hits is not None:
mapping = hits.map(device=Device.CPU)
try:
ids = np.from_dlpack(mapping["primPath"]).reshape(-1).tolist()
finally:
mapping.unmap()
for path_id in ids:
path = self.backend.renderer.resolve_prim_path_id(path_id) if path_id else None
if path and path not in paths:
paths.append(path)
future.set_result(paths)
except Exception as error: # noqa: BLE001 - a failed pick goes to its caller, not to rendering
future.set_exception(error)

def update_transforms(self) -> None:
"""Write changed SDP transforms to OVRTX."""
binding = self._object_xform_binding
Expand Down Expand Up @@ -1110,6 +1203,7 @@ def render_batch(self, render_data: Sequence[OVRTXCameraRenderData]) -> None:
if self.backend.renderer is None or not self._camera_render_data:
return
products = self.backend.render_products.copy()
picks = self._prepare_selection(products) if not self.cfg.async_rendering or self._use_ovstage else {}
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:
Expand All @@ -1134,6 +1228,7 @@ def render_batch(self, render_data: Sequence[OVRTXCameraRenderData]) -> None:
previous.wait().fetch()
else:
result = self.backend.renderer.step(render_products=products, delta_time=_RENDER_DELTA_TIME)
self._answer_picks(picks, result)
self._process_render_products(render_data, result)
finally:
if material_writer is not None:
Expand All @@ -1153,6 +1248,7 @@ def render_batch(self, render_data: Sequence[OVRTXCameraRenderData]) -> None:
result = self.backend.renderer.step(
render_products=products, delta_time=_RENDER_DELTA_TIME, ordinal=ordinal
)
self._answer_picks(picks, result)
self._process_render_products(render_data, result)

def cleanup(self, render_data: OVRTXCameraRenderData | None) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ class OVRTXRendererCfg(RendererCfg):
cloning_contexts: tuple[type | str, ...] = ("isaaclab_ov.cloner:OvrtxReplicateContext",)
"""Request native OVRTX copies; clone preparation may select a shared OVStage instead."""

stage_provider: str | None = None
"""``module:callable`` that creates this renderer's OVStage scene; see
:attr:`~isaaclab_ov.stage.OvstageBackendCfg.stage_provider`.

Setting it selects an OVStage scene for this renderer, so an application can supply a stage it also reads, such as
a viewer whose panes read the stage through their own stage context. ``None`` keeps the default scene selection.
"""

async_rendering: bool = False
"""Trade one capture of camera latency for pipelined rendering. Defaults to False (synchronous).

Expand Down
43 changes: 35 additions & 8 deletions source/isaaclab_ov/isaaclab_ov/stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,15 @@ class OvstageBackendCfg(BackendCfg):
"""None selects the simulation scene; isolated consumers use their configuration or instance identity."""
population_domains: ovstage.PopulationDomain = ovstage.PopulationDomain.RENDERING
"""USD domains to populate. Physics consumers require PHYSICS or ALL."""
stage_provider: str | None = None
"""``module:callable`` that creates the stage instead of :func:`create_ovstage`, or ``None``.

The callable takes the stage name and returns a context manager whose value has a ``stage`` attribute: the
:class:`ovstage.Stage` to populate. The value stays available as :attr:`OvstageBackend.stage_owner` until the
backend closes, so an application that created the stage (for example a viewer that registers it with its own
stage context) can find it. The stage may already hold sealed ordinals; population starts after them. If the value
has a ``prepare_population(usda) -> usda`` method, population uses the USD it returns.
"""


class OvstageBackend:
Expand All @@ -177,26 +186,33 @@ def __init__(self, cfg: OvstageBackendCfg):
self.clone_positions: np.ndarray | None = None
self.resources = contextlib.ExitStack()
"""Release borrowers before paths and stage, in reverse registration order."""
self.stage_owner = None
"""The value the configured :attr:`OvstageBackendCfg.stage_provider` created, or ``None``."""
self.reset()

def populate(self, usda: str) -> None:
"""Import the exported prototypes and apply the clone context's prepared operations.

Population commits ordinal 1. Consumers may then author render products and poses
starting at ordinal 2, after every cloned camera path exists.
Population commits the first ordinal after those the stage was created with (ordinal 1 for a stage from
:func:`create_ovstage`). Consumers then author render products and poses at later ordinals, after every
cloned camera path exists.

Args:
usda: USD scene containing the routed prototypes and their materials.
"""
if self.ordinal:
return

# Ordinal 0 is the empty state; population and cloning form the first committed write.
ovstage.population.open_usd_from_string(self.stage, usda, ordinal=1, domains=self.cfg.population_domains)
prepare = getattr(self.stage_owner, "prepare_population", None)
if prepare is not None:
usda = prepare(usda)
# Population and cloning form the first committed write after the stage's initial state.
ordinal = self._initial_floor + 1
ovstage.population.open_usd_from_string(self.stage, usda, ordinal=ordinal, domains=self.cfg.population_domains)
ovstage_replicate(
self.stage, self.paths, self.clone_copies, self.clone_env_paths, self.clone_positions, ordinal=1
self.stage, self.paths, self.clone_copies, self.clone_env_paths, self.clone_positions, ordinal=ordinal
)
self.ordinal = 1
self.ordinal = ordinal
self.commit()

@contextlib.contextmanager
Expand Down Expand Up @@ -226,14 +242,25 @@ def commit(self) -> int:
def close(self) -> None:
"""Release borrowers, then the path dictionary and stage."""
self.resources.close()
self.stage = self.paths = None
self.stage = self.paths = self.stage_owner = None

def reset(self) -> None:
"""Recreate the native stage after all consumers detach, retaining the prepared clone operations."""
self.close()
self.ordinal = self.next_camera_id = 0
with contextlib.ExitStack() as resources:
self.stage = resources.enter_context(create_ovstage("isaaclab.scene"))
# A stage Isaac Lab creates starts empty; a provided one may already hold sealed ordinals.
self._initial_floor = 0
if self.cfg.stage_provider is None:
self.stage = resources.enter_context(create_ovstage("isaaclab.scene"))
else:
from isaaclab.utils.string import string_to_callable

self.stage_owner = resources.enter_context(
string_to_callable(self.cfg.stage_provider)("isaaclab.scene")
)
self.stage = self.stage_owner.stage
self._initial_floor = self.stage.fetch_ordinal(self.stage.get_attribute_write_floor())
self.paths = resources.enter_context(ovstage.PathDictionary(self.stage))
self.resources = resources.pop_all()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
* Added a prototype ``isaac_sim`` visualizer backend (``--viz isaac-sim``,
:class:`~isaaclab_visualizers.isaac_sim.IsaacSimBackendCfg`) that shows an Isaac Lab simulation in the Isaac Sim 7
viewer application, with its stage tree, property and content panes and transport controls. One OVStage is the data
layer for Isaac Lab and the viewer: Isaac Lab populates it through its clone plan, writes body poses and
visualization markers at ordinals it owns, and renders the viewer with OVRTX. The application host runs no
scheduler; Isaac Lab drives every update.
viewer application, with its stage tree, property and content panes and transport controls. The viewer shows Isaac
Lab's own OVRTX scene: its cameras are scene cameras on a shared OVRTX renderer whose scene stage the application
host creates, so the host's panes read the stage Isaac Lab renders. The host runs no scheduler; Isaac Lab drives
every update.
Clicking a prim selects and outlines it; the transform gizmo moves and rotates the Isaac Lab asset that owns it
(an articulation or rigid object, per environment), also while paused.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@

"""Isaac Sim 7 viewer visualizer backend (prototype), selected with ``--viz isaac-sim``.

One OVStage is the data layer for Isaac Lab and the Isaac Sim 7 viewer application. Isaac Lab owns its ordinals: it
writes body poses and visualization markers, applies the application host's commands, seals, and renders the viewer's
render products with OVRTX. The host supplies its stage tree, property and content panes, transport controls and frame
streaming; it runs no scheduler, and Isaac Lab drives every update.
The viewer shows Isaac Lab's own OVRTX scene. Its cameras are scene cameras on a shared OVRTX renderer whose scene stage
the Isaac Sim 7 application host creates, so the host's stage tree and property panes read the stage Isaac Lab renders.
Isaac Lab populates that stage, owns its ordinals, and draws body poses and visualization markers through its renderer.
The host supplies its panes, transport controls and frame streaming; it runs no scheduler, and Isaac Lab drives every
update.

Prototype requirements, not yet captured by the package dependencies:

Expand Down
Loading
Loading