Skip to content
Merged
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
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,7 @@ def test_visualizer_step_renders_markers_and_closes_frame(monkeypatch, caplog, m

class Viewer:
show_contacts = False
show_lidar_hits = False
_server = SimpleNamespace(get_clients=lambda: {0: object()})

def is_paused(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* Replaced the every-tenth-step lidar hit upload with an opt-in overlay. Newton GL and Viser expose a
checkbox. ``NewtonGLBackendCfg.show_lidar_hits`` and ``ViserBackendCfg.show_lidar_hits`` enable it
at launch.
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ def __init__(self, cfg: VisualizerCfg):
self._simulation_app = None
self._viewport_window = None
self._viewport_api = None
self._step_counter = 0
self._hidden_env_visibilities: dict[str, str] = {}
# PointInstancer prim path -> (had authored invisibleIds, previous value) for partial viz restore.
self._point_instancer_invisible_ids_backup: dict[str, tuple[bool, object]] = {}
Expand Down Expand Up @@ -199,7 +198,7 @@ def step(self, dt: float) -> None:
return
self._app_pumped_this_step = False
self._sim_time += dt
self._step_counter += 1

# Headless mode: skip the app update and camera panel refresh; rendering is
# triggered on demand by render_rgb_array() / render_tiled_rgb_array().
if self._runtime_headless:
Expand Down Expand Up @@ -233,7 +232,7 @@ def _draw_lidar_points(self) -> None:
Debug draw is a viewport overlay, so the lidar product does not scan the points. A missing
debug-draw interface is reported once and the step continues.
"""
hits = collect_lidar_hits(self._sim, self._env_ids, self._step_counter)
hits = collect_lidar_hits(self._sim, self._env_ids)
Comment thread
huidongc marked this conversation as resolved.
Resolved
if hits is None:
return
draw = self._lidar_debug_draw()
Expand Down
83 changes: 63 additions & 20 deletions source/isaaclab_visualizers/isaaclab_visualizers/lidar_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from __future__ import annotations

import math
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any

import numpy as np
import torch
Expand All @@ -23,9 +23,6 @@
from isaaclab.visualizers.base_visualizer import BaseVisualizer


LIDAR_LOG_INTERVAL = 10
Comment thread
huidongc marked this conversation as resolved.
Resolved
"""Visualizer steps between host copies of one environment's lidar hits."""

LIDAR_POINT_RADIUS = 0.02
"""Sphere radius, in meters, used by viewers that log a point batch."""

Expand Down Expand Up @@ -207,42 +204,88 @@ def frame_visualizer_closeup(visualizer: BaseVisualizer, cameras) -> None:
camera.lookat = lookat


def collect_lidar_hits(
sim: SimulationContext, env_ids: list[int] | None, step_counter: int
) -> list[tuple[str, np.ndarray]] | None:
"""Return every visualized environment's lidar hits on every tenth visualizer step.
def _ovrtx_lidar_cls() -> type | None:
Comment thread
huidongc marked this conversation as resolved.
Resolved
"""Return :class:`~isaaclab_ov.renderers.ovrtx_lidar_sensor.OVRTXLidar`, or None if it is unavailable."""
try:
from isaaclab_ov.renderers.ovrtx_lidar_sensor import OVRTXLidar
except ImportError:
return None
return OVRTXLidar


def scene_has_lidar(sim: SimulationContext) -> bool:
"""Return whether the interactive scene owns an OvRTX lidar.

Args:
sim: Simulation whose interactive scene is searched.

Returns:
True when at least one sensor is an OvRTX lidar.
"""
scene = sim.get_scene_data_provider().get_interactive_scene()
lidar_cls = _ovrtx_lidar_cls()
if scene is None or lidar_cls is None:
return False
return any(isinstance(sensor, lidar_cls) for sensor in scene.sensors.values())


def collect_lidar_hits(sim: SimulationContext, env_ids: list[int] | None) -> list[tuple[str, np.ndarray]]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Kit window updates fail

collect_lidar_hits now accepts two arguments, but KitVisualizer._draw_lidar_points still passes three. Every non-headless Kit step reaches that call, even without a lidar sensor, and raises TypeError before the app update. Preserve the existing Kit call and its ten-step interval, or update Kit alongside this change.

Comment thread
huidongc marked this conversation as resolved.
Resolved
"""Return every visualized environment's lidar hits.

``env_ids`` None includes every environment. Each lidar is included even when its cloud is
empty, so a viewer can hide the previous batch. Other sensors are ignored.

Args:
sim: Simulation whose interactive scene owns the lidars.
env_ids: Visualized environments. None includes every environment.
step_counter: Visualizer step. Hits are collected when this is a multiple of
:data:`LIDAR_LOG_INTERVAL`.

Returns:
``(sensor_name, points)`` pairs, or None when this step is not logged.
``(sensor_name, points)`` pairs.
"""
if step_counter % LIDAR_LOG_INTERVAL != 0:
return None
scene = sim.get_scene_data_provider().get_interactive_scene()
if scene is None:
return []

try:
from isaaclab_ov.renderers.ovrtx_lidar_sensor import OVRTXLidar
except ImportError:
lidar_cls = _ovrtx_lidar_cls()
if scene is None or lidar_cls is None:
return []

selected = None if env_ids is None else list(env_ids)
hits = []
for name, sensor in scene.sensors.items():
if isinstance(sensor, OVRTXLidar):
if isinstance(sensor, lidar_cls):
hits.append((name, lidar_world_points(sensor, selected)))
return hits


def sync_lidar_hits(
sim: SimulationContext,
env_ids: list[int] | None,
viewer: Any,
enabled: bool,
previous_names: list[str],
) -> list[str]:
"""Upload lidar hits when enabled, or hide the previous batch when disabled.

A disabled step with no previous names does not read the scene. A disabled step with previous
names logs empty clouds so the last batch disappears.

Args:
sim: Simulation whose interactive scene owns the lidars.
env_ids: Visualized environments. None includes every environment.
viewer: Newton or Viser viewer.
enabled: Whether lidar hits are copied and uploaded this step.
previous_names: Sensor names logged on a previous enabled step.

Returns:
Sensor names logged this step, or an empty list when the cloud is hidden.
"""
if not enabled:
if previous_names:
log_lidar_hits(viewer, [(name, np.empty((0, 3), dtype=np.float32)) for name in previous_names])
return []
hits = collect_lidar_hits(sim, env_ids)
log_lidar_hits(viewer, hits)
return [name for name, _ in hits]


def log_lidar_hits(viewer, hits: list[tuple[str, np.ndarray]], radius: float = LIDAR_POINT_RADIUS) -> None:
"""Log collected hits through a viewer ``log_points`` method.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg, WindowCfg

from isaaclab_visualizers.desktop_entry import write_desktop_entry
from isaaclab_visualizers.lidar_points import collect_lidar_hits, frame_visualizer_closeup, log_lidar_hits
from isaaclab_visualizers.lidar_points import frame_visualizer_closeup, scene_has_lidar, sync_lidar_hits
Comment thread
huidongc marked this conversation as resolved.
Resolved
from isaaclab_visualizers.newton.newton_overlay_meshes import OverlayMeshPublisher
from isaaclab_visualizers.newton.newton_visualization_markers import render_newton_visualization_markers

Expand Down Expand Up @@ -176,6 +176,9 @@ class NewtonViewerGL(ViewerGL):
"""Newton GL window with Isaac Lab controls and device-image presentation."""

_contacts_available = True
_lidar_available = False
Comment thread
huidongc marked this conversation as resolved.
Resolved
show_lidar_hits = False
"""Whether lidar hits are copied onto the host and drawn in the OpenGL view."""
CAMERA_SPEED_BOOST_MULTIPLIER = 2.0
camera_keys_suspended = False
"""Set while keyboard camera movement is disabled (see :meth:`NewtonVisualizerBase.set_camera_keys_enabled`)."""
Expand Down Expand Up @@ -535,6 +538,15 @@ def tip(text: str) -> None:
tip("Length of the contact arrows")
_, renderer.arrow_scale = imgui.slider_float("Contact Width", renderer.arrow_scale, 0.25, 5.0)
tip("Width of the contact arrows")
_lidar_available = (not rtx) and self._lidar_available
self.show_lidar_hits = _imgui_optional_checkbox(
imgui,
"Show Lidar Hits",
self.show_lidar_hits,
_lidar_available,
"OpenGL only" if rtx else "No lidar sensors in this environment",
"Copy and draw lidar hits",
)
_model = self.model
_has_particles = _model.particle_count > 0
_has_springs = _model.spring_count > 0
Expand Down Expand Up @@ -1667,7 +1679,7 @@ def __init__(self, cfg: VisualizerCfg):
self._cfg_visible_env_ids: list[int] | None = None
self._visible_env_count: int | None = None
self._num_envs = 0
self._lidar_step_counter = 0
self._logged_lidar_names: list[str] = []

# ------------------------------------------------------------------
# GL lifecycle
Expand Down Expand Up @@ -1776,13 +1788,13 @@ def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraC
# out "Show Contacts" when neither native Newton contacts nor a ContactSensor
# exists in the scene.
self._viewer._contacts_available = newton_backend_active or bool(scene_data_provider.get_contact_sensors())
self._viewer._lidar_available = scene_has_lidar(sim)

def _log_lidar_points(self, viewer: Any) -> None:
def _log_lidar_hits(self, viewer: Any) -> None:
Comment thread
huidongc marked this conversation as resolved.
Resolved
"""Log every visualized environment's lidar hits into the Newton GL scene."""
self._lidar_step_counter += 1
hits = collect_lidar_hits(self._sim, self._env_ids, self._lidar_step_counter)
if hits is not None:
log_lidar_hits(viewer, hits)
self._logged_lidar_names = sync_lidar_hits(
self._sim, self._env_ids, viewer, viewer.show_lidar_hits, self._logged_lidar_names
)

def _render_frame(self) -> None:
"""Render one GL frame for the window or an on-demand capture."""
Expand Down Expand Up @@ -1824,7 +1836,7 @@ def _render_frame(self) -> None:
self._log_scene_contact_sensor_arrows()
if self.cfg.enable_markers:
render_newton_visualization_markers(viewer, self._env_ids, num_envs=self.backend.model.num_envs)
self._log_lidar_points(viewer)
self._log_lidar_hits(viewer)
Comment thread
huidongc marked this conversation as resolved.
Resolved
for name, arguments in self._pending_mesh_submissions.items():
viewer.log_mesh(name, **arguments)
self._pending_mesh_submissions.clear()
Expand Down Expand Up @@ -2300,6 +2312,7 @@ def _configure_viewer(self) -> None:
self._viewer.show_inertia_boxes = self.cfg.backend.show_inertia_boxes
self._viewer.show_com = self.cfg.backend.show_com
self._viewer.show_particles = self.cfg.backend.show_particles
self._viewer.show_lidar_hits = self.cfg.backend.show_lidar_hits
self._viewer.up_axis = 2 # Z-up
self._viewer.scaling = 1.0
self._viewer.particle_color = self.cfg.backend.particle_color
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ class NewtonGLBackendCfg(VisualizerBackendCfg):
show_particles: bool = True
"""Show simulation particles. Set to False to hide them, for example in a surface-only view."""

show_lidar_hits: bool = False
Comment thread
huidongc marked this conversation as resolved.
Resolved
"""Show lidar hit visualization. Set to True to copy and draw hits; a dense scan is expensive to upload."""

particle_color: tuple[float, float, float] | None = None
"""Optional particle color RGB [0, 1]. Uses Newton viewer defaults when ``None``."""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from isaaclab.visualizers.base_visualizer import BaseVisualizer
from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg

from isaaclab_visualizers.lidar_points import collect_lidar_hits, frame_visualizer_closeup, log_lidar_hits
from isaaclab_visualizers.lidar_points import frame_visualizer_closeup, sync_lidar_hits
from isaaclab_visualizers.newton.newton_visualization_markers import render_newton_visualization_markers
from isaaclab_visualizers.newton_adapter import log_geo_with_expanded_plane_scale

Expand Down Expand Up @@ -289,7 +289,7 @@ def __init__(self, cfg: VisualizerCfg):
self.backend = None
self._pending_camera_pose: tuple[tuple[float, float, float], tuple[float, float, float]] | None = None
self._warned_marker_render_failure = False
self._lidar_step_counter = 0
self._logged_lidar_names: list[str] = []
self._paused_rendering = False
self._paused_simulation = False

Expand Down Expand Up @@ -327,6 +327,7 @@ def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraC
self._viewer.set_model(self.backend.model)
self._geometry_change_version = self.backend.geometry_change_version
self._viewer.show_particles = self.cfg.backend.show_particles
self._viewer.show_lidar_hits = self.cfg.backend.show_lidar_hits
# set_model() clears model-dependent GUI elements; build the sidebar afterwards.
self._setup_isaaclab_sidebar(self._viewer._server)
self._viewer.set_visible_worlds(self._env_ids)
Expand Down Expand Up @@ -398,7 +399,7 @@ def step(self, dt: float) -> None:
self._viewer.log_state(self.backend.state_0)
if self.cfg.enable_markers:
self._render_markers(self.backend.model.num_envs)
self._log_lidar_points()
self._log_lidar_hits()
self._render_live_plots()
self._push_streaming_frame()
finally:
Expand All @@ -417,14 +418,13 @@ def _push_streaming_frame(self) -> None:
# the browser canvas. Black bars are added on whichever axis needs it.
self._viewer._server.scene.set_background_image(_letterbox_16_9(composite), format="jpeg")

def _log_lidar_points(self) -> None:
"""Log one lidar environment's hits into the Viser scene."""
def _log_lidar_hits(self) -> None:
"""Log lidar hits into the Viser scene when the overlay is enabled."""
if self._viewer is None:
return
self._lidar_step_counter += 1
hits = collect_lidar_hits(self._sim, self._env_ids, self._lidar_step_counter)
if hits is not None:
log_lidar_hits(self._viewer, hits)
self._logged_lidar_names = sync_lidar_hits(
self._sim, self._env_ids, self._viewer, self._viewer.show_lidar_hits, self._logged_lidar_names
)

def _render_markers(self, num_envs: int) -> None:
"""Render marker overlays without letting them interrupt Viser body updates."""
Expand Down Expand Up @@ -566,6 +566,7 @@ def _(_):
("Springs", "show_springs"),
("Cloth", "show_triangles"),
("Inertia Boxes", "show_inertia_boxes"),
("Lidar Hits", "show_lidar_hits"),
]
with vis_folder:
for label, attr in _VIZ_FLAGS:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ class ViserBackendCfg(VisualizerBackendCfg):
panel in the Viser sidebar.
"""

show_lidar_hits: bool = False
"""Copy lidar hits to the viewer and draw them.

Off by default. A dense scan is expensive to move to the host and upload every visualizer step.
Viser exposes a runtime checkbox.
"""


@configclass
class ViserVisualizerCfg(ViserBackendCfg, VisualizerCfg):
Expand Down
34 changes: 28 additions & 6 deletions source/isaaclab_visualizers/test/test_lidar_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
frame_visualizer_closeup,
lidar_world_points,
log_lidar_hits,
sync_lidar_hits,
)

from isaaclab.test.utils import DeviceScope, test_devices
Expand Down Expand Up @@ -86,8 +87,8 @@ def __del__(self):
return _Lidar()


def test_collect_lidar_hits_returns_lidar_clouds_on_the_interval():
"""Only lidar sensors are returned, and only on every tenth step."""
def _lidar_sim():
Comment thread
huidongc marked this conversation as resolved.
Resolved
"""Simulation stand-in with one hit lidar, one empty lidar, and a non-lidar sensor."""
scene = SimpleNamespace(
sensors={
"range": _world_lidar(torch.tensor([[[1.0, 2.0, 3.0]]]), torch.tensor([[True]])),
Expand All @@ -97,10 +98,12 @@ def test_collect_lidar_hits_returns_lidar_clouds_on_the_interval():
"camera": object(),
}
)
sim = SimpleNamespace(get_scene_data_provider=lambda: SimpleNamespace(get_interactive_scene=lambda: scene))
return SimpleNamespace(get_scene_data_provider=lambda: SimpleNamespace(get_interactive_scene=lambda: scene))


assert collect_lidar_hits(sim, [0], 9) is None
hits = collect_lidar_hits(sim, [0], 10)
def test_collect_lidar_hits_returns_lidar_clouds():
"""Only lidar sensors are returned, including an empty cloud so a viewer can hide the last batch."""
hits = collect_lidar_hits(_lidar_sim(), [0])
assert [name for name, _ in hits] == ["range", "empty"]
np.testing.assert_allclose(hits[0][1], [[1.0, 2.0, 3.0]])
assert hits[1][1].shape == (0, 3)
Expand All @@ -114,7 +117,7 @@ def test_collect_lidar_hits_draws_every_environment_without_a_subset():
)
scene = SimpleNamespace(sensors={"lidar": sensor})
sim = SimpleNamespace(get_scene_data_provider=lambda: SimpleNamespace(get_interactive_scene=lambda: scene))
hits = collect_lidar_hits(sim, None, 10)
hits = collect_lidar_hits(sim, None)
np.testing.assert_allclose(hits[0][1], [[70.0, -70.0, 1.0], [10.0, -10.0, 2.0]])


Expand Down Expand Up @@ -171,6 +174,25 @@ class _ViewerViser(_RecordingViewer):
"""Name matches the Viser viewer, which copies the batch on the CPU."""


def test_sync_lidar_hits_hides_previous_clouds_until_enabled():
"""A disabled overlay hides the last batch without reading the scene. Enabling uploads lidar hits."""
viewer = _ViewerViser("cpu")
assert sync_lidar_hits(None, [0], viewer, False, []) == []
assert viewer.batches == []

assert sync_lidar_hits(None, [0], viewer, False, ["range"]) == []
name, cloud, _, _ = viewer.batches[0]
assert name == "lidar/range"
assert cloud is None

names = sync_lidar_hits(_lidar_sim(), [0], viewer, True, [])
assert names == ["range", "empty"]
uploaded = [batch[0] for batch in viewer.batches[1:]]
assert uploaded == ["lidar/range", "lidar/empty"]
np.testing.assert_allclose(viewer.batches[1][1].numpy(), [[1.0, 2.0, 3.0]])
assert viewer.batches[2][1] is None


@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA))
def test_log_lidar_hits_allocates_gl_points_on_the_viewer_device(device: str) -> None:
"""A GL viewer must receive positions and colors on its own device."""
Expand Down
Loading
Loading