diff --git a/.gitignore b/.gitignore index 4a74400b8bef..95df5a35cb0e 100644 --- a/.gitignore +++ b/.gitignore @@ -61,6 +61,7 @@ _build **/runs/* **/logs/* **/recordings/* +**/recording/* # Local development tools and generated media. /tools/local/ diff --git a/docs/source/api/lab/isaaclab.visualizers.rst b/docs/source/api/lab/isaaclab.visualizers.rst index f18253c6f9de..07b406c12768 100644 --- a/docs/source/api/lab/isaaclab.visualizers.rst +++ b/docs/source/api/lab/isaaclab.visualizers.rst @@ -27,6 +27,7 @@ The following classes are part of the public :mod:`isaaclab.visualizers` API. VisualizerBackendCfg WindowCfg PerspectiveCameraCfg + TrackingCameraCfg SceneCameraCfg ImageViewCfg ImageView @@ -51,6 +52,9 @@ The following classes are part of the public :mod:`isaaclab.visualizers` API. .. autoclass:: PerspectiveCameraCfg :show-inheritance: +.. autoclass:: TrackingCameraCfg + :show-inheritance: + .. autoclass:: SceneCameraCfg :show-inheritance: diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 20176ffa7117..da05b532d3d0 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -309,9 +309,9 @@ Visualizer Overview staircase sub-terrain

Picking, visualization markers, camera selection, pause controls, Visible Envs, and recording work in - the RTX view of a windowed Newton visualizer, and picking draws the drag arrow there. Joint, contact, spring, - center-of-mass, and inertia overlays are drawn in the RTX view too; the collision, visual, edge, and wireframe - overlays apply to the OpenGL view only. + the RTX view of a windowed Newton visualizer, and picking draws the drag arrow there. The model overlays + (joint, contact, spring, center-of-mass, inertia, collision, visual, edge, and wireframe) apply to the OpenGL + view only. .. warning:: @@ -553,14 +553,14 @@ task's wrist-mounted and ego cameras. The view is supported in the Kit, Newton, Rerun, and Viser visualizers. **Kit** opens it as a separate **Streaming View** viewport, which can sit side by side with the default viewport for dual monitoring. **Newton** provides a **Camera Source** selector in the sidebar for switching between perspective and scene-camera -views. +views. A perspective view can also be a *tracking camera* that follows a robot or frames an environment. Selecting a scene sensor in **Camera Source** shows its channel: the **Channel** selector lists the sensor's outputs (RGB, depth, normals, or segmentation), and depth, normals, and segmentation are converted to colors for display. When the sensor is declared once per environment, **Tiled Envs** sets how many of its feeds are tiled into the window. See :doc:`/source/how-to/visualizer_streaming_camera_view` for the ``VisualizerCfg`` options, display -sources, troubleshooting, migration from generated cameras, and step-by-step examples. +sources, tracking cameras that follow a robot, troubleshooting, migration from generated cameras, and step-by-step examples. Visualization Markers @@ -662,6 +662,16 @@ streaming views, and renderer-based sensor data capture. +.. _visualization-newton-recording: + +Newton Window Recording +~~~~~~~~~~~~~~~~~~~~~~~ + +The **Recording** section of the Newton visualizer saves two things: an ``mp4`` video of the window and a ``.png`` +screenshot of the window. Files go to the output +folder set by :class:`~isaaclab_visualizers.newton.NewtonRecordingCfg`. Video and screenshots can include the HUD +panels with their **Include HUD** options. + .. _record_video_cli: Pass ``--video [SOURCE]`` on the command line for a quick recording, or define multiple @@ -778,22 +788,23 @@ Watch training live in Kit while recording from a separate headless Newton angle ``--viz kit --video viz:newton`` and giving each visualizer its own camera. See :ref:`Recording from an independent camera angle ` for the configuration. -**Following a moving robot (Kit)** +**Following a moving robot** -Lock the Kit camera to a moving asset instead of updating ``eye``/``lookat`` yourself every -step, running with ``--viz kit``: +Declare a *tracking camera* instead of updating ``eye``/``lookat`` every step; see :ref:`how-to-visualizer-tracking-cameras`. +This is Newton GL only. Kit ignores a ``TrackingCameraCfg`` and follows an asset with +``KitBackendCfg(origin_type="asset", origin_track_path="robot")`` instead. For Newton GL: .. code-block:: python - from isaaclab_visualizers.kit import KitBackendCfg - - from isaaclab.visualizers import VisualizerCfg - - from isaaclab_tasks.utils.presets import MultiBackendVisualizerCfg + from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg sim_cfg.visualizer_cfgs = VisualizerCfg( - eye=(4.0, 4.0, 2.0), - backend=MultiBackendVisualizerCfg(kit=KitBackendCfg(origin_type="asset", origin_track_path="robot")), + cameras=[ + TrackingCameraCfg( + track_path="robot", # or "robot/panda_hand" to track a specific body + eye=(4.0, 4.0, 2.0), # offset from the tracked asset + ), + ], ) **Sharing a live view with a remote teammate** @@ -821,7 +832,7 @@ share button in the native UI. Every Newton viewer has a **Visible Envs** slider in its left panel that sets how many environments are drawn. It changes only what is rendered, not the simulation. In the RTX view the OVRTX renderer is shared with scene cameras, so the hidden environments also drop out of their images while the RTX view is shown; -the HUD notes this next to the slider. +the HUD notes this next to the slider. Deformable (soft) objects are not hidden in the RTX view. Resolution Rules ~~~~~~~~~~~~~~~~ @@ -988,8 +999,8 @@ Limitations - ✗ - ✓ -In Newton's RTX view, the collision, visual, edge, and wireframe overlays are not available; joint, contact, spring, -center-of-mass, and inertia overlays are. +In Newton's RTX view, only the picking drag arrow is drawn; the model overlays (joint, contact, spring, +center-of-mass, inertia, collision, visual, edge, and wireframe) are not available. **Lighting differences across visualizers** @@ -1002,7 +1013,9 @@ authored scene through Isaac Lab's OVRTX renderer, shared with cameras using the ``OVRTXRendererCfg``. The Newton window displays the rendered GPU image and handles window controls; Newton's ``ViewerRTX`` is not constructed. Scene transforms, deformable geometry, and material updates follow the camera renderer's normal synchronization. Perspective resolution stays -fixed when the window is resized; the window scales the image for presentation. +fixed when the window is resized; the window scales the image for presentation. Use the RTX view in one Newton +window per run: windows with equal renderer settings share the renderer, the viewer camera and the viewer lights. +Visualization markers appear in the RTX view through the viewer camera, not through an ordinary scene camera. Configure lights and environment placement in the scene. Viewer-only ``rtx_environment`` rigs and ``world_spacing`` are no longer supported: declare scene lights for studio lighting, remove scene lights for an unlit scene, and set ``InteractiveSceneCfg.env_spacing`` for world placement. diff --git a/docs/source/how-to/record_video.rst b/docs/source/how-to/record_video.rst index 3d93433e9052..bc0bf072ebf4 100644 --- a/docs/source/how-to/record_video.rst +++ b/docs/source/how-to/record_video.rst @@ -282,6 +282,8 @@ The ``source`` string selects what to capture: - Newton visualizer viewport, in whichever renderer the window shows (OpenGL or RTX) * - ``"viz:newton:streaming_view"`` - Newton streaming camera panel, requires ``streaming_view=True`` + * - ``"viz:newton:tracking"`` + - First ``TrackingCameraCfg`` of the visualizer, whichever view the window shows; see :ref:`how-to-visualizer-tracking-cameras` * - ``"sensor:"`` - ``env.scene.sensors[name]``, RGB (default) * - ``"sensor::rgb"`` @@ -308,6 +310,11 @@ types are accepted here too, e.g. ``VideoRecorderCfg(source="newton")`` is equiv headless runs. The recorder source remains ``"viz:newton"``; ``newton_rtx`` selects the renderer when launching the visualizer. +.. note:: + + Recording a Tracking Camera with ``"viz:newton:tracking"`` while the window shows another source briefly draws the + tracking view in the window on each recorded frame. + Clip control ------------ diff --git a/docs/source/how-to/visualizer_streaming_camera_view.rst b/docs/source/how-to/visualizer_streaming_camera_view.rst index 830730f68465..a0dd9766ea8d 100644 --- a/docs/source/how-to/visualizer_streaming_camera_view.rst +++ b/docs/source/how-to/visualizer_streaming_camera_view.rst @@ -7,8 +7,9 @@ Streaming a camera view in a visualizer .. currentmodule:: isaaclab -Display ground-truth camera frames from many environments in one live visualizer panel. For how the view works and which visualizers support it, see -:ref:`visualization-streaming-camera-view`. +This guide shows how to show ground-truth camera frames from many environments in one live +panel of a visualizer, and how to add a view that follows a robot (see :ref:`how-to-visualizer-tracking-cameras`). +For how the view works and which visualizers support it, see :ref:`visualization-streaming-camera-view`. Sharing a view with recording @@ -125,6 +126,7 @@ for dual monitoring. The **Newton** visualizer has a **Camera Source** selector in the sidebar. Selecting a scene camera displays its tiled output in the main viewport instead of rendering a perspective view behind it. Selecting a perspective camera restores interactive scene rendering and picking. +A tracking camera is listed as **Tracking Camera**; see :ref:`how-to-visualizer-tracking-cameras`. Without an explicit ``cameras`` list, Newton starts in perspective and offers scene cameras that provide every requested ``streaming_gt_types`` channel. An explicit @@ -244,6 +246,50 @@ Unselected cameras are still allocated and may render if another consumer reads scene uses eager sensor updates. ``streaming_envs`` selects displayed tiles, not capture work. +.. _how-to-visualizer-tracking-cameras: + +Tracking cameras that follow a robot +------------------------------------ + +A ``TrackingCameraCfg`` frames an environment or follows an asset in it. Its ``eye`` and ``lookat`` are +offsets [m] from the environment origin, or from the tracked asset, so it frames the robot wherever the scene puts +it. In the OpenGL renderer the visualizer renders it from its own camera, so nothing is added to the scene and the view +keeps the viewport's markers and shadows. In RTX the window follows it by moving the OVRTX viewer camera, which is a +camera in the scene, and OpenGL shadows do not apply. + +.. code-block:: python + + from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg + + env_cfg.sim.visualizer_cfgs = VisualizerCfg( + cameras=[ + TrackingCameraCfg( + eye=(1.8, -3.0, 1.1), + lookat=(0.15, 0.0, 0.0), + track_path="robot", + follow_heading=True, + heading_smoothing_time_constant=0.2, + ) + ], + ) + +* ``env_index``: the environment to frame or follow; defaults to the middle one. +* ``track_path``: a scene asset (``"robot"``) or one of its bodies (``"robot/base"``). Without it, the view stays + fixed in the environment. +* ``follow_heading``: rotate the offsets with the asset's yaw, keeping the horizon level. + ``heading_smoothing_time_constant`` [s] damps rapid turns. + +A free view at the visualizer's own ``eye`` and ``lookat`` is added before the first tracking camera, so the +interactive camera stays free. + +* **Newton:** **Camera Source** lists the tracking camera as **Tracking Camera** beside **Perspective**, and the + window follows it in both the OpenGL and RTX renderers. A **Tracking Camera** group edits its environment, asset, + body, eye, look-at, focal length and heading settings while it runs; **Reset to Task Default** restores the + declaration. Record it with ``--video viz:newton:tracking``, whichever view the window shows. Plain + ``--video viz:newton`` records whichever renderer the window shows. +* **Kit**, **Viser** and **Rerun** ignore tracking cameras. + + Examples -------- diff --git a/docs/source/isaaclab/migrating.rst b/docs/source/isaaclab/migrating.rst index 5baf0fb55a05..91464d912737 100644 --- a/docs/source/isaaclab/migrating.rst +++ b/docs/source/isaaclab/migrating.rst @@ -2718,7 +2718,7 @@ plus the corresponding ``KitBackendCfg``, ``NewtonGLBackendCfg``, and translated once, preserving explicit per-view overrides. Both forms use the same runtime implementation. Deprecated declarations emit ``DeprecationWarning``; update the configuration at its declaration site. -The Rerun visualizer (``--viz rerun``, ``RerunBackendCfg``) is deprecated in Isaac Lab 3.2 and will be removed in +The Rerun visualizer (``--viz rerun``, ``RerunBackendCfg``) is deprecated in Isaac Lab 3.1 and will be removed in Isaac Lab 3.3. Creating it emits a ``FutureWarning``. Switch to the Viser visualizer, which is also web-based and supports recording and replay: use ``--viz viser`` or ``VisualizerCfg(backend=ViserBackendCfg())``. diff --git a/docs/source/isaaclab/quickstart.rst b/docs/source/isaaclab/quickstart.rst index 28bf70e7d8bd..c89b251473ee 100644 --- a/docs/source/isaaclab/quickstart.rst +++ b/docs/source/isaaclab/quickstart.rst @@ -208,7 +208,7 @@ without spaces, such as ``--viz newton,viser``. - Open the web-based Viser visualizer, useful for remote connections. - ``viser`` * - ``--viz rerun`` - - Stream the task to the Rerun visualizer. Deprecated in Isaac Lab 3.2 and removed in 3.3; use ``--viz viser``. + - Stream the task to the Rerun visualizer. Deprecated in Isaac Lab 3.1 and removed in 3.3; use ``--viz viser``. - ``rerun`` * - ``--viz kit`` - Open the Kit visualizer when it is available in your environment. diff --git a/source/isaaclab/changelog.d/tracking-camera-tracking.added.rst b/source/isaaclab/changelog.d/tracking-camera-tracking.added.rst new file mode 100644 index 000000000000..ac872ee9e05a --- /dev/null +++ b/source/isaaclab/changelog.d/tracking-camera-tracking.added.rst @@ -0,0 +1,5 @@ +* Added :class:`~isaaclab.visualizers.TrackingCameraCfg`, a perspective camera that frames an environment or follows + an asset with optional smoothed heading. Added the ``viz::tracking`` video source, which records the first + tracking camera whichever view the window shows. A visualizer opts in by overriding + :attr:`~isaaclab.visualizers.BaseVisualizer.has_tracking_view` and + :meth:`~isaaclab.visualizers.BaseVisualizer.render_tracking_rgb_array`, which Newton GL does. diff --git a/source/isaaclab/changelog.d/tracking-camera-tracking.minor b/source/isaaclab/changelog.d/tracking-camera-tracking.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/envs/utils/video_recorder.py b/source/isaaclab/isaaclab/envs/utils/video_recorder.py index b619ad682529..441c8bd8862a 100644 --- a/source/isaaclab/isaaclab/envs/utils/video_recorder.py +++ b/source/isaaclab/isaaclab/envs/utils/video_recorder.py @@ -70,7 +70,15 @@ def __init__(self, cfg: VideoRecorderCfg, env: object): f"Enable streaming_view on {viz.cfg.backend.visualizer_type!r} to record its sensor view." ) # Legacy recording follows camera selection in the window. - self._capture = viz.render_tiled_rgb_array if channel == "streaming_view" else viz.render_rgb_array + if channel == "tracking": + if not viz.has_tracking_view: + raise RuntimeError( + f"The {viz.cfg.backend.visualizer_type!r} visualizer has no tracking camera to record. Add a " + "TrackingCameraCfg to its cameras, on a visualizer that supports tracking cameras." + ) + self._capture = viz.render_tracking_rgb_array + else: + self._capture = viz.render_tiled_rgb_array if channel == "streaming_view" else viz.render_rgb_array self.cfg = cfg self._env = env diff --git a/source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py b/source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py index 75a67aa3d55e..25872455c585 100644 --- a/source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py +++ b/source/isaaclab/isaaclab/envs/utils/video_recorder_cfg.py @@ -21,7 +21,7 @@ def parse_video_source(source: str) -> tuple[str, str, str]: """Split a string :attr:`VideoRecorderCfg.source` into ``(kind, name, sub)``. ``kind`` is ``"viz"`` or ``"sensor"``; ``name`` is the canonical visualizer type (``""`` for a bare - ``"viz"``) or the sensor name; ``sub`` is ``"streaming_view"``, a sensor channel, or ``""``. + ``"viz"``) or the sensor name; ``sub`` is ``"streaming_view"``, ``"tracking"``, a sensor channel, or ``""``. The prefix ``visualizer`` is the long form of ``viz``, as ``--visualizer`` is of ``--viz``; the ``newton_gl`` and ``newton_rtx`` aliases are mapped to ``newton``. A bare visualizer type is shorthand for ``viz:``. @@ -36,14 +36,18 @@ def parse_video_source(source: str) -> tuple[str, str, str]: name, sub = (*parts, "", "")[:2] if kind == "viz" and not parts: return kind, "", "" - if kind == "viz" and parts[1:] in ([], ["streaming_view"]) and name in (*VISUALIZER_TYPES, *VISUALIZER_ALIASES): + if ( + kind == "viz" + and parts[1:] in ([], ["streaming_view"], ["tracking"]) + and name in (*VISUALIZER_TYPES, *VISUALIZER_ALIASES) + ): return kind, VISUALIZER_ALIASES.get(name, name), sub if kind == "sensor" and 1 <= len(parts) <= 2 and name and sub in ("", *SENSOR_CHANNELS): return kind, name, sub raise ValueError( - f"Invalid video source {source!r}: expected '', 'viz', 'viz:', 'viz::streaming_view' or " - f"'sensor:[:]', with one of {', '.join(VISUALIZER_TYPES)} and one of " - f"{', '.join(SENSOR_CHANNELS)}." + f"Invalid video source {source!r}: expected '', 'viz', 'viz:', 'viz::streaming_view', " + f"'viz::tracking' or 'sensor:[:]', with one of " + f"{', '.join(VISUALIZER_TYPES)} and one of {', '.join(SENSOR_CHANNELS)}." ) @@ -66,6 +70,8 @@ class VideoRecorderCfg: camera: the one ``--viz`` selected, else a headless one added for the recording. * ``"viz::streaming_view"`` – the streaming camera panel of that visualizer (requires ``streaming_view=True`` on its :class:`~isaaclab.visualizers.VisualizerCfg`). + * ``"viz::tracking"`` – the first :class:`~isaaclab.visualizers.TrackingCameraCfg` of + that visualizer, whichever view its window shows. Only Newton GL supports it. * ``"sensor:"`` – scene sensor, RGB channel (default); no visualizer is added. * ``"sensor::"`` – scene sensor channel: ``rgb``, ``depth`` (colorized via the turbo colormap), ``segmentation`` or ``normals`` (colorized). diff --git a/source/isaaclab/isaaclab/sim/simulation_context.py b/source/isaaclab/isaaclab/sim/simulation_context.py index a23aafb42fd7..972a15288d77 100644 --- a/source/isaaclab/isaaclab/sim/simulation_context.py +++ b/source/isaaclab/isaaclab/sim/simulation_context.py @@ -36,7 +36,13 @@ from ..utils.version import has_kit from ..visualizers.base_visualizer import BaseVisualizer from ..visualizers.image_view import ImageView -from ..visualizers.visualizer_cfg import PerspectiveCameraCfg, SceneCameraCfg, VisualizerCfg, migrate_visualizer_cfgs +from ..visualizers.visualizer_cfg import ( + PerspectiveCameraCfg, + SceneCameraCfg, + TrackingCameraCfg, + VisualizerCfg, + migrate_visualizer_cfgs, +) from .utils import create_new_stage from .utils import stage as stage_utils @@ -51,6 +57,27 @@ logger = logging.getLogger(__name__) +def _with_free_view( + cameras: list[PerspectiveCameraCfg | SceneCameraCfg], + eye: tuple[float, float, float], + lookat: tuple[float, float, float], + focal_length: float, +) -> list[PerspectiveCameraCfg | SceneCameraCfg]: + """Return *cameras* with a free perspective view added when it has tracking cameras but no free view of its own. + + A tracking camera follows a robot or frames an environment, so the interactive view that a user moves stays + available beside it, at the visualizer's own ``eye``, ``lookat`` and ``focal_length``. The free view goes + right before the first tracking camera, so scene cameras declared ahead of it stay first. This camera policy is + temporary here: the visualizers should resolve their own camera lists from ``VisualizerCfg.cameras``. + """ + perspective = [camera for camera in cameras if isinstance(camera, PerspectiveCameraCfg)] + if perspective and all(isinstance(camera, TrackingCameraCfg) for camera in perspective): + free = PerspectiveCameraCfg(eye=eye, lookat=lookat, focal_length=focal_length) + first_tracking = next(i for i, camera in enumerate(cameras) if isinstance(camera, PerspectiveCameraCfg)) + return [*cameras[:first_tracking], free, *cameras[first_tracking:]] + return cameras + + class SimulationContext: """Controls simulation lifecycle including physics stepping and rendering. @@ -426,12 +453,15 @@ def initialize_visualizers(self, config_filter: Callable[[Any], bool] | None = N eye=visualizer.cfg.eye, lookat=visualizer.cfg.lookat, focal_length=visualizer.cfg.focal_length ) ]) # fmt: skip + cameras = _with_free_view(cameras, visualizer.cfg.eye, visualizer.cfg.lookat, visualizer.cfg.focal_length) if visualizer.cfg.view is None and visualizer.cfg.streaming_view: sensors = self._scene_data_provider.get_camera_sensors() env_template = self._clone_plan.env_template if self._clone_plan is not None else DEFAULT_ENV_TEMPLATE for gt_type in visualizer.cfg.streaming_gt_types: sensor_key_for_gt_type(gt_type) - if visualizer.cfg.cameras is None: + # tracking cameras only add to the scene cameras the visualizer would find on its own + discovered = visualizer.cfg.cameras is None or visualizer.cfg.tracking_cameras_only() + if discovered: if visualizer.cfg.streaming_sensor_prim_path is not None: cameras.insert(0, SceneCameraCfg(prim_path=visualizer.cfg.streaming_sensor_prim_path)) else: diff --git a/source/isaaclab/isaaclab/visualizers/__init__.pyi b/source/isaaclab/isaaclab/visualizers/__init__.pyi index a230550c4afe..f170d6c27475 100644 --- a/source/isaaclab/isaaclab/visualizers/__init__.pyi +++ b/source/isaaclab/isaaclab/visualizers/__init__.pyi @@ -10,6 +10,7 @@ __all__ = [ "KeyEventSource", "KeyboardSubscription", "PerspectiveCameraCfg", + "TrackingCameraCfg", "SceneCameraCfg", "VisualizerCfg", "VisualizerBackendCfg", @@ -24,6 +25,7 @@ from .visualizer_cfg import ( ImageViewCfg, PerspectiveCameraCfg, SceneCameraCfg, + TrackingCameraCfg, VisualizerBackendCfg, VisualizerCfg, WindowCfg, diff --git a/source/isaaclab/isaaclab/visualizers/base_visualizer.py b/source/isaaclab/isaaclab/visualizers/base_visualizer.py index 8e6e3a52f8e3..192fbccca591 100644 --- a/source/isaaclab/isaaclab/visualizers/base_visualizer.py +++ b/source/isaaclab/isaaclab/visualizers/base_visualizer.py @@ -123,7 +123,9 @@ def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraC pool = self._env_ids if self._env_ids is not None else range(num_envs) num_tiles = min(int(self.cfg.streaming_envs), _VISUALIZER_MAX_TILES, len(pool)) env_ids = sorted(random.sample(pool, num_tiles)) - automatic_sources = self.cfg.cameras is None and self.cfg.streaming_sensor_prim_path is None + automatic_sources = ( + self.cfg.cameras is None or self.cfg.tracking_cameras_only() + ) and self.cfg.streaming_sensor_prim_path is None rtx_path = getattr(self.cfg.backend, "rtx_camera_path", None) for camera in cameras: if isinstance(camera, PerspectiveCameraCfg): @@ -158,6 +160,23 @@ def render_tiled_rgb_array(self) -> np.ndarray | None: return None return self.current_image_view.read_rgb(self._sim.get_physics_step_count()) + @property + def has_tracking_view(self) -> bool: + """Whether this visualizer displays a Tracking Camera that a recording can read. + + ``False`` unless the visualizer supports tracking cameras and overrides this together with + :meth:`render_tracking_rgb_array`. + """ + return False + + def render_tracking_rgb_array(self) -> np.ndarray: + """Download the first Tracking Camera view for CPU consumers, whatever the window shows. + + Raises: + NotImplementedError: If the visualizer does not support tracking cameras. + """ + raise NotImplementedError(f"{type(self).__name__} does not support tracking cameras.") + @abstractmethod def step(self, dt: float) -> None: """Update visualization for one step. diff --git a/source/isaaclab/isaaclab/visualizers/camera_follower.py b/source/isaaclab/isaaclab/visualizers/camera_follower.py new file mode 100644 index 000000000000..0c88a05091da --- /dev/null +++ b/source/isaaclab/isaaclab/visualizers/camera_follower.py @@ -0,0 +1,202 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""World poses for perspective views tied to an environment or an asset.""" + +from __future__ import annotations + +import copy +import math +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from ..scene import InteractiveScene + from .visualizer_cfg import TrackingCameraCfg + +_RESET_JUMP = 1.0 +"""Distance [m] an asset moves between two updates only when its environment resets.""" + +_RESET_YAW_JUMP = 1.5 +"""Heading change [rad] between two close updates that a robot only makes when its environment resets.""" + +_MAX_YAW_RATE = 4.0 * math.pi +"""Turn rate [rad/s] no robot exceeds, which widens the reset threshold for updates far apart in time. + +Updates follow the render cadence, so a view rendered only now and then, or with a large render interval, sees the +robot turn further between two updates without any reset.""" + +_CATCH_UP_LAG = math.pi / 2 +"""Lag [rad] behind the robot heading beyond which the camera heading catches up faster.""" + + +class CameraFollower: + """Turns a :class:`~isaaclab.visualizers.TrackingCameraCfg` tied to an environment into world poses. + + A view that only has :attr:`~isaaclab.visualizers.TrackingCameraCfg.env_index` stays fixed relative to that + environment's origin. A view with :attr:`~isaaclab.visualizers.TrackingCameraCfg.track_path` follows the + asset's position, and its yaw when ``follow_heading`` is set, with the heading filtered over time. + + The follower works on a copy of the camera config, so the settings it resolves or a user edits (environment, asset, + pose, heading) never write back into the task's own config, which other environments may be built from. + """ + + def __init__(self, cfg: TrackingCameraCfg, scene: InteractiveScene, env_ids: Sequence[int] | None = None) -> None: + """Bind *cfg* to *scene*. + + Args: + cfg: The tracking camera, copied. Its ``env_index`` None selects the middle environment. + scene: The scene to read environment origins and assets from. + env_ids: The visible environments, or None when all are; the middle one is picked from these. + """ + self.cfg = copy.copy(cfg) + self._scene = scene + self._env = 0 + self._yaw: float | None = None + self._raw_yaw: float | None = None + self._last_position: list[float] | None = None + self._time: float | None = None + if cfg.env_index is not None: + self.set_env(cfg.env_index) + else: + ids = list(env_ids) if env_ids else range(scene.num_envs) + self.set_env(ids[(len(ids) - 1) // 2]) + self._asset = None + self._body_index: int | None = None + self._body_name = "" + if cfg.track_path: + self.set_track_path(cfg.track_path) + + @property + def env(self) -> int: + """Environment whose origin or asset the view follows.""" + return self._env + + def set_track_path(self, track_path: str | None) -> None: + """Follow another asset or body, or only the environment origin when *track_path* is empty. + + Args: + track_path: ``"asset"`` for an asset root or ``"asset/body"`` for one of its bodies; None or an empty + string stops following an asset. + + Raises: + ValueError: If the asset is not an articulation or rigid object of the scene, or the body does not match + exactly one body of an initialized asset. + """ + asset, body_name = None, "" + if track_path: + asset_name, _, body_name = track_path.partition("/") + if asset_name not in self.asset_names(): + raise ValueError( + f"track_path refers to an unknown scene asset: {asset_name!r}. Only articulations and rigid" + " objects can be followed." + ) + asset = self._scene[asset_name] + if body_name and asset.is_initialized and len(asset.find_bodies(body_name)[0]) != 1: + raise ValueError(f"track_path must match exactly one body: {track_path!r}.") + self.cfg.track_path = track_path or None # the copy's + self._asset, self._body_name, self._body_index = asset, body_name, None + self._yaw = self._raw_yaw = self._last_position = self._time = None + + def reset(self) -> None: + """Forget the heading history, so the next pose is not smoothed against the previous episode.""" + self._yaw = self._raw_yaw = self._last_position = self._time = None + + def asset_names(self) -> list[str]: + """Return the names of the scene assets the view can follow.""" + scene = self._scene + return [*scene.articulations, *scene.rigid_objects] + + def body_names(self, asset_name: str) -> list[str]: + """Return the body names of the scene asset *asset_name*, or an empty list when it has none.""" + try: + return list(getattr(self._scene[asset_name], "body_names", [])) + except KeyError: + return [] + + def set_env(self, index: int) -> None: + """Follow environment *index* from now on, with the heading filter starting afresh. + + Raises: + ValueError: If *index* is outside the scene's environments. + """ + if not 0 <= index < self._scene.num_envs: + raise ValueError(f"env_index {index} is outside the {self._scene.num_envs} environments of the scene.") + self._env = int(index) + self.cfg.env_index = self._env # the copy's, so the task's config keeps its own env_index + self._yaw = self._raw_yaw = self._last_position = self._time = None + + def pose(self, time: float) -> tuple[tuple[float, float, float], tuple[float, float, float]] | None: + """Return the world eye and look-at target at simulation *time*, or None until the asset is ready. + + Args: + time: Simulation time [s]. Only the heading filter uses it, through the time since the previous call. + """ + cfg = self.cfg + origin = self._scene.env_origins[self._env] + if self._asset is None: + offsets = torch.tensor((cfg.eye, cfg.lookat), dtype=torch.float32, device=origin.device) + eye, target = (origin + offsets).tolist() + return tuple(eye), tuple(target) + asset = self._asset + if not asset.is_initialized: + return None + data = asset.data + if self._body_name: + if self._body_index is None: + body_ids, _ = asset.find_bodies(self._body_name) + if len(body_ids) != 1: + raise ValueError(f"track_path must match exactly one body: {cfg.track_path!r}.") + self._body_index = body_ids[0] + position = data.body_pos_w.torch[self._env, self._body_index] + quat = data.body_quat_w.torch[self._env, self._body_index] + else: + position, quat = data.root_pos_w.torch[self._env], data.root_quat_w.torch[self._env] + if cfg.follow_heading: + # one device-to-host copy per frame + state = torch.cat((position, quat)).tolist() + dt, self._time = (0.0 if self._time is None else max(time - self._time, 0.0)), time + yaw = self._filtered_yaw(state[3:], state[:3], dt) + cos, sin = math.cos(yaw), math.sin(yaw) + # the state is already on the host, so the offsets turn there without another device round trip + eye, target = ( + (state[0] + cos * x - sin * y, state[1] + sin * x + cos * y, state[2] + z) + for x, y, z in (cfg.eye, cfg.lookat) + ) + return eye, target + offsets = torch.tensor((cfg.eye, cfg.lookat), dtype=torch.float32, device=position.device) + eye, target = (position + offsets).tolist() + return tuple(eye), tuple(target) + + def _filtered_yaw(self, quat: list[float], position: list[float], dt: float) -> float: + """Return the yaw of the xyzw *quat*, filtered so the camera follows the turn in the direction it happened. + + The heading is tracked unwrapped, so a camera that falls more than half a turn behind keeps turning the same + way instead of reversing, and it catches up faster the further it lags. The first sample, and the sample after + an environment resets, is not filtered. + """ + x, y, z, w = quat + yaw = math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z)) + last, self._last_position = self._last_position, position + reset = self._yaw is None or last is None or math.dist(position, last) > _RESET_JUMP + step = 0.0 if reset else math.remainder(yaw - self._raw_yaw, math.tau) + if not reset: + # an environment can reset in place with a new heading; the raw heading is compared, since the filtered + # one lags behind a steady turn + reset = abs(step) > max(_RESET_YAW_JUMP, _MAX_YAW_RATE * dt) + # signed heading changes add up, so the target keeps the direction of the turn + self._raw_yaw = yaw if reset else self._raw_yaw + step + tau = self.cfg.heading_smoothing_time_constant + if tau > 0.0 and not reset: + lag = self._raw_yaw - self._yaw + if abs(lag) > _CATCH_UP_LAG: + tau *= _CATCH_UP_LAG / abs(lag) + yaw = self._yaw + -math.expm1(-dt / tau) * lag + else: + yaw = self._raw_yaw + self._yaw = yaw + return yaw diff --git a/source/isaaclab/isaaclab/visualizers/visualizer_cfg.py b/source/isaaclab/isaaclab/visualizers/visualizer_cfg.py index 91268ff3c0dc..d80ceb0fadec 100644 --- a/source/isaaclab/isaaclab/visualizers/visualizer_cfg.py +++ b/source/isaaclab/isaaclab/visualizers/visualizer_cfg.py @@ -52,6 +52,48 @@ class PerspectiveCameraCfg: """Perspective camera focal length [mm].""" +@configclass +class TrackingCameraCfg(PerspectiveCameraCfg): + """A camera that frames an environment or follows an asset in it, however the scene is laid out. + + The Newton GL window shows it in either renderer. Only Newton GL supports it; other visualizers ignore it. + """ + + eye: tuple[float, float, float] = (4.0, -4.0, 3.0) + """Eye position [m], as an offset from the tracked asset, or from the origin of :attr:`env_index`.""" + + lookat: tuple[float, float, float] = (0.0, 0.0, 0.0) + """Look-at target [m], in the same frame as :attr:`eye`.""" + + env_index: int | None = None + """Environment to frame, or the one holding the tracked asset; None picks the middle one of the visible + environments.""" + + track_path: str | None = None + """Scene asset to follow, or None for a view fixed relative to the environment origin. + + Use ``"robot"`` for an asset root or ``"robot/base"`` for a named body, which must match exactly one body. + """ + + follow_heading: bool = False + """Rotate :attr:`eye` and :attr:`lookat` with the tracked asset's yaw, keeping the horizon level. + + Without it the offsets stay aligned with the world axes. Only used with :attr:`track_path`. + """ + + heading_smoothing_time_constant: float = 0.0 + """Exponential heading-filter time constant [s]; zero follows the heading immediately. + + Larger values damp rapid turns more, with more lag. Only used with :attr:`follow_heading`. + """ + + def __post_init__(self) -> None: + if self.env_index is not None and self.env_index < 0: + raise ValueError("env_index must be non-negative.") + if not math.isfinite(self.heading_smoothing_time_constant) or self.heading_smoothing_time_constant < 0.0: + raise ValueError("heading_smoothing_time_constant must be finite and non-negative.") + + @configclass class SceneCameraCfg: """Select an existing scene camera's output as the visualizer's main view. @@ -189,11 +231,13 @@ class VisualizerCfg: """Render on demand without opening a native viewer window.""" # Primary interactive camera settings - cameras: list[PerspectiveCameraCfg | SceneCameraCfg] | None = None + cameras: list[PerspectiveCameraCfg | TrackingCameraCfg | SceneCameraCfg] | None = None """Camera sources available to the visualizer. - PerspectiveCameraCfg configures the interactive view and may appear at most once; SceneCameraCfg refers - to an existing scene sensor. Newton GL and RTX display the first source and offer a dropdown for switching sources. + PerspectiveCameraCfg configures the interactive view and may appear at most once, TrackingCameraCfg a view that + frames an environment or follows an asset, and SceneCameraCfg refers to an existing scene sensor. + Newton GL and RTX display the first source and offer a dropdown for switching sources. Newton GL adds a free + view in front of a leading TrackingCameraCfg and shows that one first. Kit, Rerun, and Viser display the first scene source in their camera panel. None uses eye/lookat/focal_length and the streaming settings below. Every explicit scene source must provide all requested streaming_gt_types channels. @@ -295,9 +339,16 @@ def validate_config(self) -> None: for backend in backends: if backend.visualizer_type != "newton": raise ValueError("VisualizerCfg.view requires the Newton visualizer.") - if self.cameras is not None or self.streaming_sensor_prim_path is not None: + # tracking cameras only add views, so a task that declares one still accepts an explicit view, which wins + if (self.cameras is not None and not self.tracking_cameras_only()) or ( + self.streaming_sensor_prim_path is not None + ): raise ValueError("Choose view or legacy cameras/streaming_sensor_prim_path, not both.") + def tracking_cameras_only(self) -> bool: + """Whether every declared camera is a :class:`TrackingCameraCfg`, so scene cameras are still discovered.""" + return bool(self.cameras) and all(isinstance(camera, TrackingCameraCfg) for camera in self.cameras) + def __post_init__(self) -> None: if self.background_color is not None: if len(self.background_color) != 3 or any(not 0.0 <= value <= 1.0 for value in self.background_color): @@ -307,12 +358,22 @@ def __post_init__(self) -> None: if self.cameras is not None: if not self.cameras: raise ValueError("cameras must contain at least one display source.") - if sum(isinstance(camera, PerspectiveCameraCfg) for camera in self.cameras) > 1: + if ( + sum( + isinstance(camera, PerspectiveCameraCfg) and not isinstance(camera, TrackingCameraCfg) + for camera in self.cameras + ) + > 1 + ): raise ValueError( "cameras may contain at most one PerspectiveCameraCfg, the viewer's interactive camera." ) - self.streaming_view = any(isinstance(camera, SceneCameraCfg) for camera in self.cameras) - if isinstance(camera := self.cameras[0], PerspectiveCameraCfg): + # tracking cameras only add to the cameras the visualizer finds, so they leave the streaming choice alone + if not self.tracking_cameras_only(): + self.streaming_view = any(isinstance(camera, SceneCameraCfg) for camera in self.cameras) + if isinstance(camera := self.cameras[0], PerspectiveCameraCfg) and not isinstance( + camera, TrackingCameraCfg + ): self.eye, self.lookat, self.focal_length = camera.eye, camera.lookat, camera.focal_length diff --git a/source/isaaclab/test/envs/test_video_recorder.py b/source/isaaclab/test/envs/test_video_recorder.py index 84207866b689..8948476fea7a 100644 --- a/source/isaaclab/test/envs/test_video_recorder.py +++ b/source/isaaclab/test/envs/test_video_recorder.py @@ -58,6 +58,7 @@ def __init__(self, viz_type: str, frame: np.ndarray | None = None): self.cfg = VisualizerCfg(backend=VisualizerBackendCfg(visualizer_type=viz_type)) self._frame = frame if frame is not None else _FRAME.copy() self.render_calls = 0 + self.has_tracking_view = True def render_rgb_array(self) -> np.ndarray: self.render_calls += 1 @@ -67,6 +68,11 @@ def supports_markers(self) -> bool: return True +def _without_tracking_view(viz: _FakeViz) -> _FakeViz: + viz.has_tracking_view = False + return viz + + def _make_env(visualizers=(), sensors: dict | None = None): env = SimpleNamespace(sim=MagicMock(), scene=SimpleNamespace(), step_dt=0.02) env.sim.visualizers = list(visualizers) @@ -264,6 +270,15 @@ def test_source_resolves_frame(source, make_env, caplog): assert not caplog.records +def test_a_tracking_source_records_the_tracking_camera_not_the_selected_one(): + viz = _FakeViz("newton") + task_frame = np.full_like(_FRAME, 7) + viz.render_tracking_rgb_array = lambda: task_frame + recorder = VideoRecorder(_cfg(source="viz:newton:tracking"), _make_env(visualizers=[viz])) + assert recorder._capture() is task_frame + assert viz.render_calls == 0 + + @pytest.mark.parametrize( "source,make_env,error,message", [ @@ -275,6 +290,18 @@ def test_source_resolves_frame(source, make_env, caplog): RuntimeError, "Enable streaming_view", ), + ( + "viz:newton:tracking", + lambda: _make_env(visualizers=[_without_tracking_view(_FakeViz("newton"))]), + RuntimeError, + "has no tracking camera to record", + ), + ( + "viz:kit:tracking", + lambda: _make_env(visualizers=[_without_tracking_view(_FakeViz("kit"))]), + RuntimeError, + "has no tracking camera to record", + ), ("sensor:missing", lambda: _make_env(sensors={"tiled_camera": MagicMock()}), ValueError, "missing"), ("sensor:tiled_camera:depth", lambda: _make_env(sensors={"tiled_camera": _rgb_sensor()}), KeyError, "depth"), ], diff --git a/source/isaaclab/test/visualizers/test_camera_follower.py b/source/isaaclab/test/visualizers/test_camera_follower.py new file mode 100644 index 000000000000..d47ca426ef89 --- /dev/null +++ b/source/isaaclab/test/visualizers/test_camera_follower.py @@ -0,0 +1,265 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for perspective views tied to an environment or an asset.""" + +from __future__ import annotations + +import math +from types import SimpleNamespace + +import pytest +import torch + +from isaaclab.sim.simulation_context import _with_free_view as with_free_view +from isaaclab.visualizers import PerspectiveCameraCfg, SceneCameraCfg, TrackingCameraCfg, VisualizerCfg +from isaaclab.visualizers.camera_follower import CameraFollower + +pytestmark = pytest.mark.kitless + + +def _quat_z(yaw: float) -> list[float]: + """Quaternion (x, y, z, w) of a rotation of *yaw* about +Z.""" + return [0.0, 0.0, math.sin(yaw / 2), math.cos(yaw / 2)] + + +class _Scene: + """Two environments, 10 m apart, with a robot at the origin of the second.""" + + num_envs = 2 + env_origins = torch.tensor([[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]]) + + def __init__(self, ready: bool = True): + data = SimpleNamespace( + root_pos_w=SimpleNamespace(torch=torch.tensor([[0.0, 0.0, 0.5], [10.0, 0.0, 0.5]])), + root_quat_w=SimpleNamespace(torch=torch.tensor([[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0]])), + ) + self.robot = SimpleNamespace(is_initialized=ready, data=data) + self.articulations, self.rigid_objects = {"robot": self.robot}, {} + + def __getitem__(self, name): + if name == "contact_forces": # a scene entry that is not an asset + return SimpleNamespace(is_initialized=True) + return self.robot + + +def _eye(follower: CameraFollower, time: float = 0.1) -> torch.Tensor: + return torch.tensor(follower.pose(time)[0]) + + +def test_a_view_with_an_environment_stays_fixed_relative_to_its_origin(): + cfg = TrackingCameraCfg(env_index=1, eye=(1.0, 2.0, 3.0), lookat=(0.0, 0.0, 1.0)) + eye, target = CameraFollower(cfg, _Scene()).pose(0.1) + assert eye == (11.0, 2.0, 3.0) + assert target == (10.0, 0.0, 1.0) + + +def test_a_tracked_view_follows_the_asset_and_rotates_with_its_heading(): + scene = _Scene() + cfg = TrackingCameraCfg(env_index=1, track_path="robot", eye=(-3.0, 0.0, 1.0), follow_heading=True) + follower = CameraFollower(cfg, scene) + torch.testing.assert_close(_eye(follower), torch.tensor([7.0, 0.0, 1.5])) + # turned a quarter turn, the robot's back is at -y + scene.robot.data.root_quat_w.torch[1] = torch.tensor(_quat_z(math.pi / 2)) + torch.testing.assert_close(_eye(follower), torch.tensor([10.0, -3.0, 1.5]), atol=1e-5, rtol=0) + # without heading the offsets stay aligned with the world axes + follower.cfg.follow_heading = False + torch.testing.assert_close(_eye(follower), torch.tensor([7.0, 0.0, 1.5])) + + +def test_smoothing_lags_a_turn_but_not_a_reset(): + def run(jump: float) -> torch.Tensor: + scene = _Scene() + cfg = TrackingCameraCfg(track_path="robot", eye=(-3.0, 0.0, 1.0), follow_heading=True) + cfg.heading_smoothing_time_constant = 0.5 + follower = CameraFollower(cfg, scene) + follower.pose(0.0) + scene.robot.data.root_quat_w.torch[0] = torch.tensor(_quat_z(0.2)) # 2 rad/s + scene.robot.data.root_pos_w.torch[0, 0] += jump # an environment reset also moves the asset + return _eye(follower) + + smooth, reset = run(0.0), run(5.0) + assert smooth[1] > -0.3 # filtered toward the new heading + torch.testing.assert_close(reset[1], torch.tensor(-3.0 * math.sin(0.2)), atol=1e-4, rtol=0) # the new one at once + + +def test_a_reset_in_place_with_a_new_heading_is_not_smoothed_but_a_real_turn_is(): + def run(yaw: float) -> torch.Tensor: + scene = _Scene() + cfg = TrackingCameraCfg(track_path="robot", eye=(-3.0, 0.0, 1.0), follow_heading=True) + cfg.heading_smoothing_time_constant = 0.5 + follower = CameraFollower(cfg, scene) + follower.pose(0.0) + scene.robot.data.root_quat_w.torch[0] = torch.tensor(_quat_z(yaw)) # the position does not change + return torch.tensor(follower.pose(0.02)[0]) + + torch.testing.assert_close(run(math.pi / 2)[1], torch.tensor(-3.0), atol=1e-4, rtol=0) # 78 rad/s: a reset + assert run(0.05)[1] > -0.05 # 2.5 rad/s: a turn; unfiltered it would be -0.15 + + +def test_a_view_waits_for_its_asset_and_rejects_bad_targets(): + assert CameraFollower(TrackingCameraCfg(track_path="robot"), _Scene(ready=False)).pose(0.1) is None + with pytest.raises(ValueError, match="outside"): + CameraFollower(TrackingCameraCfg(env_index=2), _Scene()) + with pytest.raises(ValueError, match="non-negative"): + TrackingCameraCfg(env_index=-1) + with pytest.raises(ValueError, match="non-negative"): + TrackingCameraCfg(heading_smoothing_time_constant=-1.0) + + +def test_tracking_cameras_get_a_free_view_beside_them(): + free, task = PerspectiveCameraCfg(), TrackingCameraCfg(env_index=0) + args = ((1.0, 2.0, 3.0), (0.0, 0.0, 0.0), 30.0) + assert with_free_view([task], *args)[0].eye == (1.0, 2.0, 3.0) + assert len(with_free_view([task], *args)) == 2 + assert with_free_view([free, task], *args) == [free, task] + # scene cameras declared ahead of the tracking camera stay first + sensor = SceneCameraCfg(prim_path="/cam") + views = with_free_view([sensor, task], *args) + assert views[0] is sensor and views[1].eye == (1.0, 2.0, 3.0) and views[2] is task + assert with_free_view([SceneCameraCfg(prim_path="/cam")], *args) == [SceneCameraCfg(prim_path="/cam")] + # a tracking camera first does not replace the visualizer's own pose or its streaming choice + cfg = VisualizerCfg(eye=(7.0, 0.0, 0.0), streaming_view=True, cameras=[task]) + assert cfg.eye == (7.0, 0.0, 0.0) and cfg.streaming_view + assert not VisualizerCfg(streaming_view=True, cameras=[free]).streaming_view + + +class _NamedScene(_Scene): + """A scene that knows its assets by name, as an interactive scene does.""" + + def __init__(self): + super().__init__() + self.robot.body_names = ["base", "LF_FOOT"] + self.robot.find_bodies = lambda name: ( + [self.robot.body_names.index(name)] if name in self.robot.body_names else [], + [], + ) + self.articulations, self.rigid_objects = {"robot": self.robot}, {"cube": SimpleNamespace(is_initialized=True)} + + def __getitem__(self, name): + try: + return {**self.articulations, **self.rigid_objects}[name] + except KeyError: + raise KeyError(name) from None + + +def test_the_followed_asset_can_be_switched_and_cleared_while_running(): + cfg = TrackingCameraCfg(env_index=1, eye=(1.0, 0.0, 0.0), lookat=(0.0, 0.0, 0.0)) + follower = CameraFollower(cfg, _NamedScene()) + assert _eye(follower).tolist() == [11.0, 0.0, 0.0] # Fixed relative to the environment origin. + + follower.set_track_path("robot") + assert follower.cfg.track_path == "robot" + assert _eye(follower).tolist() == [11.0, 0.0, 0.5] # Offset from the robot at (10, 0, 0.5). + + follower.set_track_path(None) + assert follower.cfg.track_path is None + assert _eye(follower).tolist() == [11.0, 0.0, 0.0] + + +def test_an_unknown_asset_or_ambiguous_body_is_rejected_and_keeps_the_current_target(): + cfg = TrackingCameraCfg(env_index=0, track_path="robot") + follower = CameraFollower(cfg, _NamedScene()) + + with pytest.raises(ValueError, match="unknown scene asset"): + follower.set_track_path("ghost") + with pytest.raises(ValueError, match="exactly one body"): + follower.set_track_path("robot/no_such_body") + + assert follower.cfg.track_path == "robot" + follower.set_track_path("robot/LF_FOOT") + assert follower.cfg.track_path == "robot/LF_FOOT" + + +def test_the_follower_leaves_the_task_camera_config_untouched(): + cfg = TrackingCameraCfg(eye=(1.0, 0.0, 0.0), lookat=(0.0, 0.0, 0.0)) + follower = CameraFollower(cfg, _NamedScene()) # no env_index: the middle environment is picked + follower.set_env(1) + follower.set_track_path("robot") + follower.cfg.eye = (5.0, 5.0, 5.0) # a user edit in the window + + assert follower.env == 1 and follower.cfg.track_path == "robot" + assert cfg.env_index is None and cfg.track_path is None and cfg.eye == (1.0, 0.0, 0.0) + + +def test_only_articulations_and_rigid_objects_can_be_followed(): + follower = CameraFollower(TrackingCameraCfg(env_index=0), _Scene()) + + with pytest.raises(ValueError, match="Only articulations and rigid objects"): + follower.set_track_path("contact_forces") + + +def test_the_followable_assets_and_bodies_are_listed(): + follower = CameraFollower(TrackingCameraCfg(env_index=0), _NamedScene()) + + assert follower.asset_names() == ["robot", "cube"] + assert follower.body_names("robot") == ["base", "LF_FOOT"] + assert follower.body_names("cube") == [] + assert follower.body_names("missing") == [] + + +def test_a_steady_turn_with_heavy_smoothing_is_not_mistaken_for_an_environment_reset(): + cfg = TrackingCameraCfg(env_index=0, track_path="robot", follow_heading=True, heading_smoothing_time_constant=2.0) + follower = CameraFollower(cfg, _NamedScene()) + previous = None + for step in range(120): # one radian per second sampled at 10 Hz, so the filter lags by more than a reset jump + raw = 0.1 * step + yaw = follower._filtered_yaw([0.0, 0.0, math.sin(raw / 2), math.cos(raw / 2)], [0.0, 0.0, 0.5], 0.1) + if previous is not None: + assert abs(math.remainder(yaw - previous, math.tau)) < 0.2 + previous = yaw + + +def test_a_camera_lagging_more_than_half_a_turn_keeps_turning_the_same_way(): + cfg = TrackingCameraCfg(env_index=0, track_path="robot", follow_heading=True, heading_smoothing_time_constant=50.0) + follower = CameraFollower(cfg, _NamedScene()) + yaws = [] + for step in range(100): # a robot spinning at 2 rad/s, far faster than the filter follows + raw = 0.2 * step + yaws.append(follower._filtered_yaw([0.0, 0.0, math.sin(raw / 2), math.cos(raw / 2)], [0.0, 0.0, 0.5], 0.1)) + assert all(later >= earlier for earlier, later in zip(yaws, yaws[1:])) + assert yaws[-1] > yaws[0] + + +def test_a_turn_between_two_widely_spaced_updates_is_not_mistaken_for_a_reset(): + cfg = TrackingCameraCfg(env_index=0, track_path="robot", follow_heading=True, heading_smoothing_time_constant=1.0) + follower = CameraFollower(cfg, _NamedScene()) + follower._filtered_yaw(_quat_z(0.0), [0.0, 0.0, 0.5], 0.0) + # 2 rad in a second, as seen by a view that renders only now and then: smoothed, not snapped + smoothed = follower._filtered_yaw(_quat_z(2.0), [0.0, 0.0, 0.5], 1.0) + assert 0.0 < smoothed < 2.0 + # the same turn between two close updates is a reset, so the camera snaps + follower.reset() + follower._filtered_yaw(_quat_z(0.0), [0.0, 0.0, 0.5], 0.0) + assert follower._filtered_yaw(_quat_z(2.0), [0.0, 0.0, 0.5], 0.01) == pytest.approx(2.0) + + +def test_the_heading_filter_starts_afresh_after_a_reset(): + cfg = TrackingCameraCfg(env_index=0, track_path="robot", follow_heading=True, heading_smoothing_time_constant=1.0) + follower = CameraFollower(cfg, _NamedScene()) + follower._filtered_yaw([0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.5], 0.1) + + follower.reset() + + assert follower._filtered_yaw([0.0, 0.0, 0.2, 0.98], [0.0, 0.0, 0.5], 0.1) == pytest.approx(0.4027, abs=1e-3) + + +def test_without_an_env_index_the_middle_visible_environment_is_followed(): + class _Many(_Scene): + num_envs = 256 + env_origins = torch.zeros(256, 3) + + assert CameraFollower(TrackingCameraCfg(), _Many()).env == 127 + assert CameraFollower(TrackingCameraCfg(), _Many(), env_ids=[3, 10, 40]).env == 10 + assert CameraFollower(TrackingCameraCfg(env_index=5), _Many()).env == 5 + + +def test_an_explicit_view_is_accepted_beside_the_tasks_tracking_cameras(): + from isaaclab.visualizers import ImageViewCfg + + view = ImageViewCfg(source=PerspectiveCameraCfg()) + VisualizerCfg(view=view, cameras=[TrackingCameraCfg(env_index=0)]).validate_config() + with pytest.raises(ValueError, match="not both"): + VisualizerCfg(view=view, cameras=[PerspectiveCameraCfg()]).validate_config() diff --git a/source/isaaclab/test/visualizers/test_visualizer.py b/source/isaaclab/test/visualizers/test_visualizer.py index b0b3b065bea3..99e0bcf48cc9 100644 --- a/source/isaaclab/test/visualizers/test_visualizer.py +++ b/source/isaaclab/test/visualizers/test_visualizer.py @@ -113,6 +113,14 @@ def is_running(self) -> bool: return True +def test_a_visualizer_has_no_tracking_view_unless_it_supports_tracking_cameras(): + visualizer = _DummyVisualizer(VisualizerCfg(backend=VisualizerBackendCfg(visualizer_type="dummy"))) + + assert visualizer.has_tracking_view is False + with pytest.raises(NotImplementedError, match="does not support tracking cameras"): + visualizer.render_tracking_rgb_array() + + @pytest.mark.parametrize( "env_ids, cap, num_envs, expected", [ diff --git a/source/isaaclab_rl/changelog.d/hud-run-info.added.rst b/source/isaaclab_rl/changelog.d/hud-run-info.added.rst new file mode 100644 index 000000000000..b62a2ce90420 --- /dev/null +++ b/source/isaaclab_rl/changelog.d/hud-run-info.added.rst @@ -0,0 +1 @@ +* Added ``describe_run`` to the RSL-RL play and train entrypoints so the Newton GL HUD header names the task and run. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index c59a592e596f..31d734b4a78c 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -34,6 +34,7 @@ apply_video_recording, close_env, create_isaaclab_env, + describe_run, enable_cameras_for_video, normalize_task_name, pre_launch_video_config, @@ -184,6 +185,7 @@ def run(argv: list[str]) -> None: convert_marl_to_single_agent=isinstance(env_cfg, DirectMARLEnvCfg), ) cleanup.callback(lambda: close_env(env)) + describe_run(env, args_cli.task, "play", log_dir) screen.stage("Loading policy") env = wrap_rsl_rl_env(env, agent_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/train_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/train_rsl_rl.py index 04c7d1f82c4d..a88980eb9ccb 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/train_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/train_rsl_rl.py @@ -31,6 +31,7 @@ apply_video_recording, close_env, create_isaaclab_env, + describe_run, dump_train_configs, enable_cameras_for_video, pre_launch_video_config, @@ -134,6 +135,7 @@ def _run(args_cli: argparse.Namespace) -> None: convert_marl_to_single_agent=isinstance(env_cfg, DirectMARLEnvCfg), ) cleanup.callback(lambda: close_env(env)) + describe_run(env, args_cli.task, "train", log_dir) env = wrap_sensor_capture(env, rank_dir, args_cli) screen.stage("Preparing agent") diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/common.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/common.py index 95168d664610..423acb74b025 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/common.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/common.py @@ -555,6 +555,20 @@ def create_isaaclab_env( return env +def describe_run(env: gym.Env, task: str, mode: str, log_dir: str | None) -> None: + """Show the task and run in the HUD header of every visualizer that has one. + + Args: + env: Environment, possibly wrapped, whose simulation owns the visualizers. + task: Task name. + mode: ``"play"`` or ``"train"``. + log_dir: Run log directory, or None when the run has none. + """ + for visualizer in env.unwrapped.sim.visualizers: + if hasattr(visualizer, "set_run_info"): + visualizer.set_run_info(task, mode, os.path.basename(log_dir) if log_dir else None) + + def close_env(env: gym.Env) -> None: """Close the outermost environment wrapper; another SIGINT forces exit. diff --git a/source/isaaclab_tasks/changelog.d/tracking-camera-tracking.added.rst b/source/isaaclab_tasks/changelog.d/tracking-camera-tracking.added.rst new file mode 100644 index 000000000000..ef2cc7e525f7 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/tracking-camera-tracking.added.rst @@ -0,0 +1,2 @@ +* Added tracking cameras to the core tasks: a fixed view of the environment, or a view that follows the robot for + locomotion tasks. Record them with ``--video viz:newton_gl:tracking``. diff --git a/source/isaaclab_tasks/changelog.d/tracking-camera-tracking.minor b/source/isaaclab_tasks/changelog.d/tracking-camera-tracking.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/pour_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/pour_env_cfg.py index e5414286225b..2a695bdc8ab7 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/pour_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/pour_env_cfg.py @@ -39,7 +39,7 @@ from isaaclab.sim.spawners.materials import RigidBodyMaterialBaseCfg from isaaclab.utils import configclass, replace from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils.presets import MultiBackendVisualizerCfg @@ -536,6 +536,7 @@ class FrankaPourResetDatasetEnvCfg(ManagerBasedRLEnvCfg): eye=(1.4, 1.4, 0.9), lookat=(0.5, 0.0, 0.1), backend=MultiBackendVisualizerCfg(kit=KitBackendCfg(origin_type="env", origin_env_index=0)), + cameras=[TrackingCameraCfg(eye=(1.4, 1.4, 0.9), lookat=(0.5, 0.0, 0.1))], ) ) observations: ResetDatasetObservationsCfg = ResetDatasetObservationsCfg() @@ -813,6 +814,8 @@ def play_mode(self) -> None: super().play_mode() self.scene.num_envs = 1 self.sim.visualizer_cfgs.eye = (0.9, 0.65, 0.5) + if self.sim.visualizer_cfgs.cameras: + self.sim.visualizer_cfgs.cameras[0].eye = (0.9, 0.65, 0.5) self.curriculum_freeze = True diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/multitask_manipulation/multitask_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/multitask_manipulation/multitask_env_cfg.py index afa2be946181..68ddb0f1a3ae 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/multitask_manipulation/multitask_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/multitask_manipulation/multitask_env_cfg.py @@ -499,7 +499,7 @@ def __post_init__(self): self.sim.visualizer_cfgs = VisualizerCfg(eye=(-3.0, 3.0, 2.5), lookat=(0.0, 0.0, 0.5)) def validate_config(self) -> None: - """Validate the minimum batch size required to instantiate all task views.""" + """Validate the minimum batch size: one environment per task.""" if self.scene.num_envs < 3: raise ValueError("IsaacContrib-Multitask-Manipulation requires at least three environments, one per task.") diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/ur10_particle_push/ur10_particle_push_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/ur10_particle_push/ur10_particle_push_env_cfg.py index cffef958df4c..6ba02a584c6c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/ur10_particle_push/ur10_particle_push_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/ur10_particle_push/ur10_particle_push_env_cfg.py @@ -36,7 +36,7 @@ from isaaclab.sim.spawners.materials import RigidBodyMaterialBaseCfg from isaaclab.utils import configclass, replace from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils.presets import MultiBackendVisualizerCfg @@ -620,6 +620,7 @@ class UR10ParticlePushEnvCfg(ManagerBasedRLEnvCfg): eye=(1.7, 1.5, 1.0), lookat=(0.55, 0.0, 0.0), backend=MultiBackendVisualizerCfg(kit=KitBackendCfg(origin_type="env", origin_env_index=0)), + cameras=[TrackingCameraCfg(eye=(1.7, 1.5, 1.0), lookat=(0.55, 0.0, 0.0))], ), ) actions: ActionsCfg = ActionsCfg() diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/cabinet/cabinet_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/cabinet/cabinet_env_cfg.py index 6136a9b2aa9b..d1baf8922c05 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/cabinet/cabinet_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/cabinet/cabinet_env_cfg.py @@ -29,7 +29,7 @@ from isaaclab.sim import SimulationCfg from isaaclab.utils import clone, configclass, replace from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg, preset @@ -119,7 +119,11 @@ class CabinetPhysicsCfg(PresetCfg): CABINET_SIM_CFG = SimulationCfg( dt=preset(default=1 / 600, isaacsim_physx=1 / 60, ovphysx=1 / 60, physx=1 / 60, newton_steel=1 / 60), render_interval=1, - visualizer_cfgs=VisualizerCfg(eye=(-2.0, 2.0, 2.0), lookat=(0.8, 0.0, 0.5)), + visualizer_cfgs=VisualizerCfg( + eye=(-2.0, 2.0, 2.0), + lookat=(0.8, 0.0, 0.5), + cameras=[TrackingCameraCfg(eye=(-1.8, 2.0, 1.6), lookat=(0.55, 0.0, 0.5), focal_length=28.0)], + ), physics=CabinetPhysicsCfg(), ) """Shared simulation configuration for manager-based and direct cabinet tasks.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_direct_camera_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_direct_camera_env_cfg.py index 81b5ae82b470..532189c5a08c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_direct_camera_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_direct_camera_env_cfg.py @@ -10,7 +10,6 @@ import math from isaaclab.utils import configclass -from isaaclab.visualizers import VisualizerCfg from isaaclab_tasks.utils import PresetCfg @@ -60,8 +59,8 @@ class BaseCartpoleCameraEnvCfg(CartpoleEnvCfg): def __post_init__(self): super().__post_init__() - # the base sets the proprioceptive camera view; widen it to see the camera environments - self.sim.visualizer_cfgs = VisualizerCfg(eye=(20.0, 20.0, 20.0)) + # widen the viewport to see the camera environments; the tracking camera stays as the base declares it + self.sim.visualizer_cfgs.eye = (20.0, 20.0, 20.0) default = BaseCartpoleCameraEnvCfg() depth = BaseCartpoleCameraEnvCfg(observation_space=[1, 96, 96]) diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_direct_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_direct_env_cfg.py index 5f28fecd51e4..01e01bcfdb39 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_direct_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_direct_env_cfg.py @@ -15,7 +15,7 @@ from isaaclab.scene import InteractiveSceneCfg from isaaclab.sim import SimulationCfg from isaaclab.utils import configclass, replace -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_assets.robots.cartpole import CARTPOLE_CFG @@ -70,4 +70,13 @@ class CartpoleEnvCfg(DirectRLEnvCfg): rew_scale_pole_vel = -0.005 def __post_init__(self): - self.sim.visualizer_cfgs = VisualizerCfg(eye=(8.0, 0.0, 5.0)) + self.sim.visualizer_cfgs = VisualizerCfg( + eye=(8.0, 0.0, 5.0), + cameras=[ + TrackingCameraCfg( + eye=(8.0, 0.0, 2.5), + lookat=(0.0, 0.0, 2.5), + focal_length=24.0, + ), + ], + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_manager_camera_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_manager_camera_env_cfg.py index 58fb025eb12d..e52f91d5f0a9 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_manager_camera_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_manager_camera_env_cfg.py @@ -12,7 +12,6 @@ from isaaclab.managers import SceneEntityCfg from isaaclab.utils import configclass from isaaclab.utils.images import is_depth_like -from isaaclab.visualizers import VisualizerCfg from isaaclab_tasks.utils import PresetCfg @@ -145,8 +144,9 @@ def __post_init__(self): self.scene.ground = None # reset: smaller initial pole angle than the proprioceptive task self.events.reset_pole_position.params["position_range"] = (-0.125 * math.pi, 0.125 * math.pi) - # visualizer settings - self.sim.visualizer_cfgs = VisualizerCfg(eye=(20.0, 20.0, 20.0), lookat=(0.0, 0.0, 0.0)) + # widen the viewport to see the camera environments; the tracking camera stays as the base declares it + self.sim.visualizer_cfgs.eye = (20.0, 20.0, 20.0) + self.sim.visualizer_cfgs.lookat = (0.0, 0.0, 0.0) rgb = BaseCartpoleCameraEnvCfg(observations=image_observations_cfg("rgb")) depth = BaseCartpoleCameraEnvCfg(observations=image_observations_cfg("depth")) diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_manager_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_manager_env_cfg.py index 959a3ab8919a..ed2242fbb67d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_manager_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/cartpole_manager_env_cfg.py @@ -18,7 +18,7 @@ from isaaclab.managers import TerminationTermCfg as DoneTerm from isaaclab.scene import InteractiveSceneCfg from isaaclab.utils import configclass, replace -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_assets.robots.cartpole import CARTPOLE_CFG @@ -181,4 +181,13 @@ def __post_init__(self): self.sim.render_interval = self.decimation self.sim.physics = CartpolePhysicsCfg() # visualizer settings - self.sim.visualizer_cfgs = VisualizerCfg(eye=(8.0, 0.0, 5.0)) + self.sim.visualizer_cfgs = VisualizerCfg( + eye=(8.0, 0.0, 5.0), + cameras=[ + TrackingCameraCfg( + eye=(8.0, 0.0, 2.5), + lookat=(0.0, 0.0, 2.5), + focal_length=24.0, + ), + ], + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/fourbar_pole/fourbar_pole_manager_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/fourbar_pole/fourbar_pole_manager_env_cfg.py index c5294085dc75..e0b62e0345d6 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/fourbar_pole/fourbar_pole_manager_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/fourbar_pole/fourbar_pole_manager_env_cfg.py @@ -24,7 +24,7 @@ from isaaclab.managers import TerminationTermCfg as DoneTerm from isaaclab.scene import InteractiveSceneCfg from isaaclab.utils import configclass, replace -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg @@ -239,8 +239,16 @@ def __post_init__(self) -> None: # general settings self.decimation = 2 self.episode_length_s = 5 - # Match Newton GL / --video camera to the task viewport when --viz newton creates the visualizer. - self.sim.visualizer_cfgs = VisualizerCfg(eye=(12.0, 0.0, 4.0)) + self.sim.visualizer_cfgs = VisualizerCfg( + eye=(12.0, 0.0, 4.0), + cameras=[ + TrackingCameraCfg( + eye=(4.5, 0.0, 1.8), + lookat=(0.0, 0.0, 1.8), + focal_length=24.0, + ), + ], + ) # simulation settings self.sim.dt = 1 / 120 self.sim.render_interval = self.decimation diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/handover/handover_common.py b/source/isaaclab_tasks/isaaclab_tasks/core/handover/handover_common.py index 2a5aa63d41a4..75fc56fe7f8e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/handover/handover_common.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/handover/handover_common.py @@ -13,7 +13,7 @@ from isaaclab.markers import VisualizationMarkersCfg from isaaclab.utils import index_fill_ from isaaclab.utils.math import quat_apply -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.core.reorient.utils import SuccessTracker @@ -35,7 +35,12 @@ # The camera is world-framed, so this aims at the environment nearest the grid center for the # default 2048 environments (x = 0.75 m); other counts shift the grid. -VISUALIZER_CFG = VisualizerCfg(eye=(2.35, -0.5, 1.1), lookat=(0.75, -0.5, 0.55), focal_length=35.0) +VISUALIZER_CFG = VisualizerCfg( + eye=(2.35, -0.5, 1.1), + lookat=(0.75, -0.5, 0.55), + focal_length=35.0, + cameras=[TrackingCameraCfg(eye=(1.15, -1.65, 1.15), lookat=(0.0, -0.5, 0.55), focal_length=35.0)], +) """Recording view facing one hand pair from the side, with both hands and the object between them.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/lift/config/franka_soft/franka_soft_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/lift/config/franka_soft/franka_soft_env_cfg.py index ea3dcc43b223..fb3e8c541bbb 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/lift/config/franka_soft/franka_soft_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/lift/config/franka_soft/franka_soft_env_cfg.py @@ -41,7 +41,7 @@ from isaaclab.sim.spawners.from_files.from_files_cfg import GroundPlaneCfg from isaaclab.utils import configclass, replace from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg, preset from isaaclab_tasks.utils.presets import MultiBackendRendererCfg @@ -637,7 +637,11 @@ def __post_init__(self): self.sim.render_interval = self.decimation self.sim.physics = PhysicsCfg() # visualizer settings - self.sim.visualizer_cfgs = VisualizerCfg(eye=(0.75, 0.25, 0.65), lookat=(0.0, 0.75, 0.4)) + self.sim.visualizer_cfgs = VisualizerCfg( + eye=(0.75, 0.25, 0.65), + lookat=(0.0, 0.75, 0.4), + cameras=[TrackingCameraCfg(eye=(1.8, -1.8, 1.5), lookat=(0.35, 0.0, 0.35), focal_length=28.0)], + ) def play_mode(self): super().play_mode() diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/lift/lift_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/lift/lift_env_cfg.py index 57bad79b08cd..f0a3aa0c630f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/lift/lift_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/lift/lift_env_cfg.py @@ -36,7 +36,7 @@ from isaaclab.utils import configclass from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR from isaaclab.utils.noise import UniformNoiseCfg as Unoise -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg @@ -605,7 +605,17 @@ def __post_init__(self): self.sim.render_interval = self.decimation self.sim.physics = PhysicsCfg() # visualizer settings - self.sim.visualizer_cfgs = VisualizerCfg(eye=(-2.25, 0.0, 0.75), lookat=(0.0, 0.0, 0.45)) + self.sim.visualizer_cfgs = VisualizerCfg( + eye=(-2.25, 0.0, 0.75), + lookat=(0.0, 0.0, 0.45), + cameras=[ + TrackingCameraCfg( + eye=(-1.8, -1.8, 1.45), + lookat=(-0.3, 0.0, 0.45), + focal_length=28.0, + ), + ], + ) def play_mode(self): super().play_mode() diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_common.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_common.py index e75c92037f7e..1627a74121ca 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_common.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_common.py @@ -13,9 +13,24 @@ from isaaclab.physics import PhysxAutoCfg from isaaclab.terrains import TerrainImporterCfg from isaaclab.utils import configclass +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg +VISUALIZER_CFG = VisualizerCfg( + cameras=[ + TrackingCameraCfg( + eye=(3.5, -1.0, 2.8), + lookat=(0.0, 0.0, 0.0), + focal_length=26.0, + track_path="robot", + follow_heading=True, + heading_smoothing_time_constant=0.5, + ), + ], +) +"""Recording view following the Ant with smoothed heading.""" + TERRAIN_CFG = TerrainImporterCfg( prim_path="/World/ground", terrain_type="plane", diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_direct_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_direct_env_cfg.py index 6528ef1497e2..990052b295f5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_direct_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_direct_env_cfg.py @@ -21,6 +21,7 @@ FEET_BODY_NAMES, JOINT_GEARS, TERRAIN_CFG, + VISUALIZER_CFG, WALK_TARGET_POS, AntPhysicsCfg, ) @@ -51,7 +52,12 @@ class AntEnvCfg(DirectRLEnvCfg): state_space = 0 # simulation - sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, physics=AntPhysicsCfg()) + sim: SimulationCfg = SimulationCfg( + dt=1 / 120, + render_interval=decimation, + physics=AntPhysicsCfg(), + visualizer_cfgs=VISUALIZER_CFG.copy(), + ) # scene scene: AntDirectSceneCfg = AntDirectSceneCfg(num_envs=4096, env_spacing=5.0) diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_manager_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_manager_env_cfg.py index 39ff41505502..4a5d85704e96 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_manager_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/ant_manager_env_cfg.py @@ -25,6 +25,7 @@ FEET_BODY_NAMES, JOINT_GEARS, TERRAIN_CFG, + VISUALIZER_CFG, WALK_TARGET_POS, AntPhysicsCfg, ) @@ -186,6 +187,7 @@ def __post_init__(self): self.sim.dt = 1 / 120 self.sim.render_interval = self.decimation self.sim.physics = AntPhysicsCfg() + self.sim.visualizer_cfgs = VISUALIZER_CFG.copy() self.sim.physics_material.static_friction = 1.0 self.sim.physics_material.dynamic_friction = 1.0 self.sim.physics_material.restitution = 0.0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_common.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_common.py index 0c3a8f69fd45..86a2ff15d96f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_common.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_common.py @@ -13,9 +13,24 @@ from isaaclab.physics import PhysxAutoCfg from isaaclab.terrains import TerrainImporterCfg from isaaclab.utils import configclass +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg +VISUALIZER_CFG = VisualizerCfg( + cameras=[ + TrackingCameraCfg( + eye=(2.5, -3.5, 0.9), + lookat=(0.0, 0.0, -0.5), + focal_length=26.0, + track_path="robot", + follow_heading=True, + heading_smoothing_time_constant=0.5, + ), + ], +) +"""Recording view following the Humanoid with smoothed heading.""" + TERRAIN_CFG = TerrainImporterCfg( prim_path="/World/ground", terrain_type="plane", diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_direct_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_direct_env_cfg.py index a790078d7302..58d256d01127 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_direct_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_direct_env_cfg.py @@ -17,7 +17,14 @@ from isaaclab_assets.robots.humanoid import HUMANOID_CFG -from .humanoid_common import FEET_BODY_NAMES, JOINT_GEARS, TERRAIN_CFG, WALK_TARGET_POS, HumanoidPhysicsCfg +from .humanoid_common import ( + FEET_BODY_NAMES, + JOINT_GEARS, + TERRAIN_CFG, + VISUALIZER_CFG, + WALK_TARGET_POS, + HumanoidPhysicsCfg, +) @configclass @@ -45,7 +52,12 @@ class HumanoidEnvCfg(DirectRLEnvCfg): state_space = 0 # simulation - sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, physics=HumanoidPhysicsCfg()) + sim: SimulationCfg = SimulationCfg( + dt=1 / 120, + render_interval=decimation, + physics=HumanoidPhysicsCfg(), + visualizer_cfgs=VISUALIZER_CFG.copy(), + ) # scene scene: HumanoidDirectSceneCfg = HumanoidDirectSceneCfg(num_envs=4096, env_spacing=5.0) diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_manager_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_manager_env_cfg.py index e3656ac32dd5..ec15bc82c12a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_manager_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/humanoid_manager_env_cfg.py @@ -26,6 +26,7 @@ FEET_BODY_NAMES, JOINT_EFFORT_LIMITS, JOINT_GEARS, + VISUALIZER_CFG, WALK_TARGET_POS, HumanoidPhysicsCfg, ) @@ -197,6 +198,7 @@ def __post_init__(self): self.sim.dt = 1 / 120 self.sim.render_interval = self.decimation self.sim.physics = HumanoidPhysicsCfg() + self.sim.visualizer_cfgs = VISUALIZER_CFG.copy() self.sim.physics_material.static_friction = 1.0 self.sim.physics_material.dynamic_friction = 1.0 self.sim.physics_material.restitution = 0.0 diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/pendulum/pendulum_marl_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/pendulum/pendulum_marl_env_cfg.py index 4eb79b94baa0..7587918c0973 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/pendulum/pendulum_marl_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/pendulum/pendulum_marl_env_cfg.py @@ -18,6 +18,7 @@ from isaaclab.scene import InteractiveSceneCfg from isaaclab.sim import SimulationCfg from isaaclab.utils import configclass, replace +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg @@ -76,7 +77,20 @@ class PendulumMARLEnvCfg(DirectMARLEnvCfg): state_space = -1 # simulation - sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, physics=PendulumPhysicsCfg()) + sim: SimulationCfg = SimulationCfg( + dt=1 / 120, + render_interval=decimation, + physics=PendulumPhysicsCfg(), + visualizer_cfgs=VisualizerCfg( + cameras=[ + TrackingCameraCfg( + eye=(8.0, 0.0, 2.3), + lookat=(0.0, 0.0, 2.3), + focal_length=24.0, + ), + ], + ), + ) cart_dof_name = "slider_to_cart" pole_dof_name = "cart_to_pole" diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reach/config/ur_10/joint_pos_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/reach/config/ur_10/joint_pos_env_cfg.py index 5a28372278b8..821a994e3abd 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reach/config/ur_10/joint_pos_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reach/config/ur_10/joint_pos_env_cfg.py @@ -25,6 +25,8 @@ class UR10ReachEnvCfg(ReachEnvCfg): def __post_init__(self): super().__post_init__() + self.sim.visualizer_cfgs.cameras[0].eye = (2.2, -2.2, 1.6) + self.sim.visualizer_cfgs.cameras[0].lookat = (0.3, 0.0, 0.45) # switch robot to ur10 self.scene.robot = replace(UR10_CFG, prim_path="{ENV_REGEX_NS}/Robot") diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reach/reach_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/reach/reach_env_cfg.py index f863cc92ac80..eb9d422bc9ec 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reach/reach_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reach/reach_env_cfg.py @@ -28,7 +28,7 @@ from isaaclab.scene import InteractiveSceneCfg from isaaclab.utils import configclass from isaaclab.utils.noise import UniformNoiseCfg as Unoise -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg, preset @@ -80,7 +80,10 @@ class ReachPhysicsCfg(PresetCfg): dt=preset(default=1 / 120, newton_nerd=REACH_DECIMATION / 120), render_interval=preset(default=REACH_DECIMATION, newton_nerd=1), physics=ReachPhysicsCfg(), - visualizer_cfgs=VisualizerCfg(eye=(3.5, 3.5, 3.5)), + visualizer_cfgs=VisualizerCfg( + eye=(3.5, 3.5, 3.5), + cameras=[TrackingCameraCfg(eye=(1.8, -1.8, 1.5), lookat=(0.3, 0.0, 0.4), focal_length=28.0)], + ), ) """Shared simulation defaults for Reach tasks.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/allegro_hand/allegro_hand_direct_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/allegro_hand/allegro_hand_direct_env_cfg.py index 5a41dc14a01f..73119ddcf4ff 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/allegro_hand/allegro_hand_direct_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/allegro_hand/allegro_hand_direct_env_cfg.py @@ -102,3 +102,4 @@ def play_mode(self) -> None: viewer.eye = VISUALIZER_CFG.eye viewer.lookat = VISUALIZER_CFG.lookat viewer.focal_length = VISUALIZER_CFG.focal_length + viewer.cameras = [camera.replace() for camera in VISUALIZER_CFG.cameras] diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_camera_manager_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_camera_manager_env_cfg.py index a9d1f1c1fe4f..34c612297a5b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_camera_manager_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_camera_manager_env_cfg.py @@ -131,6 +131,7 @@ def play_mode(self): viewer.eye = CAMERA_VISUALIZER_CFG.eye viewer.lookat = CAMERA_VISUALIZER_CFG.lookat viewer.focal_length = CAMERA_VISUALIZER_CFG.focal_length + viewer.cameras = [camera.replace() for camera in CAMERA_VISUALIZER_CFG.cameras] # mutate rather than replace: subclasses may have disabled the CNN self.feature_extractor.train = False self.feature_extractor.load_checkpoint = True diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_direct_camera_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_direct_camera_env_cfg.py index 5fb3962efe8f..a1d080ae0131 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_direct_camera_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_direct_camera_env_cfg.py @@ -203,6 +203,7 @@ def play_mode(self): viewer.eye = CAMERA_VISUALIZER_CFG.eye viewer.lookat = CAMERA_VISUALIZER_CFG.lookat viewer.focal_length = CAMERA_VISUALIZER_CFG.focal_length + viewer.cameras = [camera.replace() for camera in CAMERA_VISUALIZER_CFG.cameras] # inference for CNN self.feature_extractor.train = False self.feature_extractor.load_checkpoint = True diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_direct_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_direct_env_cfg.py index 9d95e79fbde4..207579fd7fa2 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_direct_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/shadow_hand/shadow_hand_direct_env_cfg.py @@ -104,3 +104,4 @@ def play_mode(self) -> None: viewer.eye = VISUALIZER_CFG.eye viewer.lookat = VISUALIZER_CFG.lookat viewer.focal_length = VISUALIZER_CFG.focal_length + viewer.cameras = [camera.replace() for camera in VISUALIZER_CFG.cameras] diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/reorient_manager_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/reorient_manager_env_cfg.py index 0c642e671ff6..9919ab9af948 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/reorient_manager_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/reorient_manager_env_cfg.py @@ -245,3 +245,4 @@ def play_mode(self) -> None: viewer.eye = VISUALIZER_CFG.eye viewer.lookat = VISUALIZER_CFG.lookat viewer.focal_length = VISUALIZER_CFG.focal_length + viewer.cameras = [camera.replace() for camera in VISUALIZER_CFG.cameras] diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/utils.py b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/utils.py index 6d6c12b2ff18..92b11eb96a24 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/utils.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/utils.py @@ -19,7 +19,7 @@ import isaaclab.utils.math as math_utils from isaaclab.utils import index_fill_ from isaaclab.utils.math import quat_from_angle_axis, quat_mul -from isaaclab.visualizers import VisualizerCfg +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg if TYPE_CHECKING: from isaaclab.assets import Articulation @@ -28,10 +28,20 @@ GOAL_MARKER_OFFSET = (-0.08, -0.09, 0.06) """Goal-cube display offset from the in-hand position [m], beside the hand in the recording view.""" -VISUALIZER_CFG = VisualizerCfg(eye=(0.995, -0.80, 0.85), lookat=(0.375, -0.28, 0.53), focal_length=35.0) +VISUALIZER_CFG = VisualizerCfg( + eye=(0.995, -0.80, 0.85), + lookat=(0.375, -0.28, 0.53), + focal_length=35.0, + cameras=[TrackingCameraCfg(eye=(0.62, -0.80, 0.85), lookat=(0.0, -0.28, 0.53), focal_length=35.0)], +) """Recording view of an environment in the 50-environment play grid.""" -CAMERA_VISUALIZER_CFG = VisualizerCfg(eye=(1.62, -1.80, 0.85), lookat=(1.0, -1.28, 0.53), focal_length=35.0) +CAMERA_VISUALIZER_CFG = VisualizerCfg( + eye=(1.62, -1.80, 0.85), + lookat=(1.0, -1.28, 0.53), + focal_length=35.0, + cameras=[TrackingCameraCfg(eye=(0.62, -0.80, 0.85), lookat=(0.0, -0.28, 0.53), focal_length=35.0)], +) """Recording view of an environment in the camera tasks' 64-environment play grid.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/anymal_d/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/anymal_d/rough_env_cfg.py index d04c2c15c7f0..581f4bfcea77 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/anymal_d/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/anymal_d/rough_env_cfg.py @@ -18,6 +18,7 @@ class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg): def __post_init__(self): super().__post_init__() + self.sim.visualizer_cfgs.cameras[0].eye = (2.0, -3.0, 1.4) self.sim.physics.newton_steel.solver_cfg.iterations = 16 # scene diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/cassie/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/cassie/rough_env_cfg.py index 1c4b565934bb..356aaa0ff2ef 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/cassie/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/cassie/rough_env_cfg.py @@ -67,6 +67,7 @@ class CassieRoughEnvCfg(LocomotionVelocityRoughEnvCfg): def __post_init__(self): super().__post_init__() + self.sim.visualizer_cfgs.cameras[0].lookat = (0.15, 0.0, -0.25) # scene self.scene.robot = replace(CASSIE_CFG, prim_path="{ENV_REGEX_NS}/Robot") diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/go2/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/go2/rough_env_cfg.py index ee2b37439d81..41ef67f8b79d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/go2/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/go2/rough_env_cfg.py @@ -43,6 +43,7 @@ class UnitreeGo2RoughEnvCfg(LocomotionVelocityRoughEnvCfg): def __post_init__(self): super().__post_init__() + self.sim.visualizer_cfgs.cameras[0].eye = (1.5, -2.5, 1.1) # simulation # execute the DC motor actuators through the backend-native path diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/h1/rough_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/h1/rough_env_cfg.py index 304f0fc6f57a..3d562536643c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/h1/rough_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/config/h1/rough_env_cfg.py @@ -77,6 +77,7 @@ class H1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): def __post_init__(self): super().__post_init__() + self.sim.visualizer_cfgs.cameras[0].eye = (2.5, -3.5, 1.3) # scene self.scene.robot = replace(H1_MINIMAL_CFG, prim_path="{ENV_REGEX_NS}/Robot") diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/velocity_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/velocity_env_cfg.py index 76e1477193a6..cd15fc7b94f4 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/velocity/velocity_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/velocity/velocity_env_cfg.py @@ -40,6 +40,7 @@ from isaaclab.utils import configclass, replace from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR from isaaclab.utils.noise import UniformNoiseCfg as Unoise +from isaaclab.visualizers import TrackingCameraCfg, VisualizerCfg from isaaclab_tasks.utils import PresetCfg @@ -357,7 +358,23 @@ class CurriculumCfg: ## -VELOCITY_SIM_CFG = SimulationCfg(dt=0.005, render_interval=4, physics=RoughPhysicsCfg()) +VELOCITY_SIM_CFG = SimulationCfg( + dt=0.005, + render_interval=4, + physics=RoughPhysicsCfg(), + visualizer_cfgs=VisualizerCfg( + cameras=[ + TrackingCameraCfg( + eye=(1.8, -3.0, 1.1), + lookat=(0.15, 0.0, 0.0), + focal_length=26.0, + track_path="robot", + follow_heading=True, + heading_smoothing_time_constant=0.2, + ) + ] + ), +) """Shared simulation defaults for locomotion velocity tasks.""" diff --git a/source/isaaclab_visualizers/changelog.d/newton-camera-readout.changed.rst b/source/isaaclab_visualizers/changelog.d/newton-camera-readout.changed.rst new file mode 100644 index 000000000000..83da719599a8 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-camera-readout.changed.rst @@ -0,0 +1 @@ +* Changed the Newton visualizer's camera readout in Camera View to list Position, Rotation (pitch and yaw), and FOV. diff --git a/source/isaaclab_visualizers/changelog.d/newton-camera-speed.added.rst b/source/isaaclab_visualizers/changelog.d/newton-camera-speed.added.rst new file mode 100644 index 000000000000..c082dfa5fe02 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-camera-speed.added.rst @@ -0,0 +1 @@ +* Added **Camera Speed** and **Shift Boost** sliders to the Newton visualizer's camera controls, which set how fast the keyboard moves the free camera and how much faster it moves while Shift is held. diff --git a/source/isaaclab_visualizers/changelog.d/newton-gl-recording-section.added.rst b/source/isaaclab_visualizers/changelog.d/newton-gl-recording-section.added.rst new file mode 100644 index 000000000000..4bccabec7b88 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-gl-recording-section.added.rst @@ -0,0 +1,5 @@ +* Added a Recording section to the Newton GL HUD that records the window to an ``mp4`` video and takes screenshots. + A video stays in a temporary file when stopped and is kept with Save. +* Added :class:`~isaaclab_visualizers.newton.NewtonRecordingCfg` (``NewtonGLBackendCfg.recording``) with the + output folder, file prefix, auto-numbering, and timestamp options shared by all recordings, plus the video frame + rate and a video length after which recording stops by itself. diff --git a/source/isaaclab_visualizers/changelog.d/newton-hud-layout.changed.rst b/source/isaaclab_visualizers/changelog.d/newton-hud-layout.changed.rst new file mode 100644 index 000000000000..6440f01da776 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-hud-layout.changed.rst @@ -0,0 +1,10 @@ +* Changed the Newton visualizer HUD. An always-visible header shows the task and run, physics backend, environment + count, step and simulation time, simulation rate, and a paused badge. Below it are the **Playback**, **Camera View** + (grouped under **Camera Source**, **Rendering**, **Camera Settings**, **Camera Data**, and a **Window** group that + holds the VSync checkbox), **Scene** (visible envs, visualization markers, visual overlays), and **Control Bindings** + sections, with tooltips throughout. The window and HUD are now named "Newton Visualizer", Newton's Selection API + panel is the "Articulation Selection", and the Focal Length slider is limited to 5-64 mm. The Window FPS slider and + the RTX Background selector were removed. +* Changed the performance and model statistics overlay of the Newton visualizer to start closed, behind a "Stats" + button. +* Added tooltips to each visualization marker group and to each live plot. diff --git a/source/isaaclab_visualizers/changelog.d/newton-hud-track-env-only.added.rst b/source/isaaclab_visualizers/changelog.d/newton-hud-track-env-only.added.rst new file mode 100644 index 000000000000..a79bcd21f6f4 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-hud-track-env-only.added.rst @@ -0,0 +1,2 @@ +* Added a "Show Only This Env" option to the Newton visualizer's Tracking Camera controls. It draws only the camera's + environment, follows it when the camera changes environment, and greys out the Scene > Visible Envs slider while on. diff --git a/source/isaaclab_visualizers/changelog.d/newton-pause-keys.changed.rst b/source/isaaclab_visualizers/changelog.d/newton-pause-keys.changed.rst new file mode 100644 index 000000000000..c3f6e395f383 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-pause-keys.changed.rst @@ -0,0 +1,3 @@ +* **Breaking:** Changed the Newton visualizer's Space key to pause the simulation, and added Shift + Space to pause + rendering, which Space used to do. The **Pause Simulation** and **Pause Rendering** tooltips and the **Control + Bindings** list name their keys. diff --git a/source/isaaclab_visualizers/changelog.d/newton-recording-hud.changed.rst b/source/isaaclab_visualizers/changelog.d/newton-recording-hud.changed.rst new file mode 100644 index 000000000000..0a42fdbf8b48 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-recording-hud.changed.rst @@ -0,0 +1,4 @@ +* Moved the recording status text out of the HUD header into the Recording section: a red REC line with the elapsed + time, an unsaved-video note, and a green confirmation after saving. The section title turns red while recording. +* The default recording output folder is now ``recording`` in the working directory, which Git ignores. A relative + recording output folder lands in the repository when running from a source checkout. diff --git a/source/isaaclab_visualizers/changelog.d/newton-recording-include-hud.added.rst b/source/isaaclab_visualizers/changelog.d/newton-recording-include-hud.added.rst new file mode 100644 index 000000000000..9aa7d0dc73f2 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-recording-include-hud.added.rst @@ -0,0 +1,2 @@ +* Added an "Include HUD" checkbox for video and for screenshots to the Recording section of the Newton visualizer. Both are + off by default, so recordings still show only the scene. diff --git a/source/isaaclab_visualizers/changelog.d/newton-recording-keeps-unsaved-clip.fixed.rst b/source/isaaclab_visualizers/changelog.d/newton-recording-keeps-unsaved-clip.fixed.rst new file mode 100644 index 000000000000..f00897a8e843 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-recording-keeps-unsaved-clip.fixed.rst @@ -0,0 +1,6 @@ +* The Newton GL Recording section keeps an unsaved video until the next recording has been encoded, so a failed Start + no longer deletes it, and a screenshot without the HUD no longer shows the HUD when the video includes it. A video + that cannot be saved when the window closes now logs a warning naming the file that was left behind. +* A fixed-length recording whose encode failed no longer saves the earlier unsaved clip under a "Saved" message. A + window resize during a recording, and a failed frame read, now show a message instead of silently dropping frames or + stopping the simulation loop. diff --git a/source/isaaclab_visualizers/changelog.d/newton-rtx-overlays.changed.rst b/source/isaaclab_visualizers/changelog.d/newton-rtx-overlays.changed.rst new file mode 100644 index 000000000000..ce4289afcde5 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-rtx-overlays.changed.rst @@ -0,0 +1,2 @@ +* The Newton visualizer's RTX view draws only the picking drag arrow. The joint, contact, spring, center-of-mass and + inertia-box overlays remain OpenGL only. diff --git a/source/isaaclab_visualizers/changelog.d/newton-rtx-viewer-fixes.fixed.rst b/source/isaaclab_visualizers/changelog.d/newton-rtx-viewer-fixes.fixed.rst new file mode 100644 index 000000000000..50322446f736 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-rtx-viewer-fixes.fixed.rst @@ -0,0 +1,2 @@ +* Fixed the paused RTX view of the Newton visualizer not re-rendering after a change that left its data marked clean, + and a Newton window with ``rtx_camera=False`` adopting the viewer camera of another window. diff --git a/source/isaaclab_visualizers/changelog.d/newton-screenshot.added.rst b/source/isaaclab_visualizers/changelog.d/newton-screenshot.added.rst new file mode 100644 index 000000000000..189c18e7a805 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/newton-screenshot.added.rst @@ -0,0 +1,2 @@ +* Added a Screenshot (``.png``) button to the Recording section of the Newton visualizer that saves the current + window frame. diff --git a/source/isaaclab_visualizers/changelog.d/tracking-camera-tracking.added.rst b/source/isaaclab_visualizers/changelog.d/tracking-camera-tracking.added.rst new file mode 100644 index 000000000000..543e64fd58ee --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/tracking-camera-tracking.added.rst @@ -0,0 +1,7 @@ +* Added tracking camera support to the Newton GL visualizer. **Camera Source** lists it as "Tracking Camera" beside the + free "Perspective" view, and a Tracking Camera group edits its environment, asset, body, eye, look-at, focal length + and heading settings, with a reset to the task's declaration. + "Reset to Task Default" also works while RTX is selected, and the window remembers the free Perspective camera's pose + and focal length while another camera source is shown. + The Tracking Camera's environment is always drawn, taking the last place of the Visible Envs count when it would + otherwise be hidden, and "Show Only This Env" still draws only that environment. diff --git a/source/isaaclab_visualizers/changelog.d/tracking-camera-tracking.minor b/source/isaaclab_visualizers/changelog.d/tracking-camera-tracking.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/__init__.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/__init__.py index 41674bc65102..495af7067a4a 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/__init__.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/__init__.py @@ -13,7 +13,12 @@ from typing import TYPE_CHECKING -from .newton_visualizer_cfg import NewtonGLBackendCfg, NewtonGLVisualizerCfg, NewtonVisualizerCfg +from .newton_visualizer_cfg import ( + NewtonGLBackendCfg, + NewtonGLVisualizerCfg, + NewtonRecordingCfg, + NewtonVisualizerCfg, +) if TYPE_CHECKING: from .newton_visualizer import NewtonGLVisualizer @@ -26,6 +31,7 @@ # GL backend "NewtonGLVisualizer", "NewtonGLBackendCfg", + "NewtonRecordingCfg", # MPM particle-surface rendering "ParticleSurfaceRenderer", ] diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_overlay_meshes.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_overlay_meshes.py index 5adef712ba3d..cee7b2a9268a 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_overlay_meshes.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_overlay_meshes.py @@ -3,12 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Draw Newton's line and arrow overlays in the OVRTX view as thin meshes. +"""Draw Newton's line and arrow calls in the OVRTX view as thin meshes. -Newton's viewer builds its debug overlays (joints, contacts, springs, centers of mass, inertia boxes) from -:meth:`log_lines` and :meth:`log_arrows` calls that only the OpenGL viewer draws. :class:`OverlayMeshPublisher` -records those calls and republishes each batch as world-space meshes through -:meth:`~isaaclab_ov.renderers.OVRTXRenderer.log_mesh`, so the OVRTX view shows the same overlays. +Newton's viewer builds the drag arrow from :meth:`log_lines` and :meth:`log_arrows` calls that only the OpenGL viewer +draws. :class:`OverlayMeshPublisher` records those calls and republishes each batch as world-space meshes through +:meth:`~isaaclab_ov.renderers.OVRTXRenderer.log_mesh`, so the OVRTX view shows the arrow too. """ from __future__ import annotations diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_recording.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_recording.py new file mode 100644 index 000000000000..e6a62a2730a3 --- /dev/null +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_recording.py @@ -0,0 +1,422 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Recording section of the Newton GL HUD: video and screenshots.""" + +from __future__ import annotations + +import contextlib +import logging +import os +import re +import shutil +import subprocess +from datetime import datetime +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import numpy as np + +from isaaclab.paths import ISAACLAB_ROOT + +if TYPE_CHECKING: + from .newton_visualizer import NewtonGLVisualizer + +logger = logging.getLogger(__name__) + + +def resolve_output_dir(path: str) -> Path: + """Return the absolute recording folder for ``path``. + + A relative path lands in the repository when running from a source checkout, wherever the run was started, and + in the working directory otherwise, such as with an installed wheel. + """ + folder = Path(path).expanduser() + if folder.is_absolute(): + return folder + return (ISAACLAB_ROOT if (ISAACLAB_ROOT / "source").is_dir() else Path.cwd()) / folder + + +def hover_tooltip(imgui: Any, text: str) -> None: + """Show ``text`` while the last item is hovered, including when it is disabled.""" + if imgui.is_item_hovered(imgui.HoveredFlags_.allow_when_disabled): + imgui.set_tooltip(text) + + +_RED = (1.0, 0.35, 0.35, 1.0) +_YELLOW = (1.0, 0.8, 0.2, 1.0) +_GREEN = (0.45, 0.9, 0.5, 1.0) + + +def _ffmpeg_executable() -> str | None: + """Return an ffmpeg binary, preferring the one bundled with ``imageio-ffmpeg`` (the ``video`` extra).""" + try: + import imageio_ffmpeg # noqa: PLC0415 + + return imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + return shutil.which("ffmpeg") + + +class NewtonRecordingPanel: + """Records the Newton GL window while the HUD asks for it. + + * **Video** streams the displayed frames (OpenGL or RTX) to an ``mp4`` through ffmpeg, like ``--video``. + """ + + def __init__(self, owner: NewtonGLVisualizer): + """Create the panel. + + Args: + owner: Visualizer whose window and simulation state are recorded. + """ + self._owner = owner + cfg = owner.cfg.backend.recording + self.output_dir = cfg.output_dir + self.filename_prefix = cfg.filename_prefix + self.auto_increment = cfg.auto_increment + self.timestamp = cfg.timestamp + self.video_fps = cfg.video_fps or 0 + """Encoded frame rate [Hz]; ``0`` follows the window update rate.""" + self.video_length = cfg.video_length or 0.0 + """Video duration [s] after which recording stops by itself; ``0`` records until stopped.""" + self.video_path = "" + """File written by the latest video recording.""" + self._video_rate = 0 + self._video_limit: int | None = None + self._video_temp: Path | None = None + self._video_unsaved: Path | None = None + """Finished clip that stays in a temporary file until :meth:`save_video` keeps it.""" + self._video_unsaved_frames = 0 + self._video_unsaved_started: datetime | None = None + self._video_count = 0 + self._video: subprocess.Popen | bool | None = None + """The encoder, ``True`` while recording has started but the first frame has not arrived, or None.""" + self._video_started: datetime | None = None + self._video_frames = 0 + self._video_shape: tuple[int, int] | None = None + self._resize_reported = False + self.screenshot_path = "" + """File written by the latest screenshot.""" + self.video_include_hud = False + """Whether recorded video frames include the HUD panels.""" + self.screenshot_include_hud = False + """Whether screenshots include the HUD panels.""" + self._screenshot_pending = False + self._message = "" + + @property + def recording_video(self) -> bool: + """Whether video frames are being written.""" + return self._video is not None + + @property + def unsaved_video(self) -> bool: + """Whether a stopped video is waiting for :meth:`save_video`.""" + return self._video_unsaved is not None + + def draw(self, imgui: Any) -> None: + """Draw the Recording section.""" + imgui.set_next_item_open(False, imgui.Cond_.appearing) + active = self.recording_video + if active: # Keep the state visible when the section is collapsed. + imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(*_RED)) + expanded = imgui.collapsing_header("Recording (REC)###recording" if active else "Recording###recording") + if active: + imgui.pop_style_color() + hover_tooltip( + imgui, + "Record a video or take a screenshot", + ) + if not expanded: + return + imgui.separator() + self._draw_video(imgui) + self._draw_screenshot(imgui) + self._draw_output(imgui) + self._draw_message(imgui) + + def _draw_video(self, imgui: Any) -> None: + """Draw the video group: Start, Stop, Save, and status.""" + imgui.text("Video (.mp4)") + if self.recording_video: + if imgui.button("Stop##video"): + self.stop_video() + hover_tooltip(imgui, "Stop recording. Press Save to keep the video") + else: + if imgui.button("Start##video"): + self.start_video() + if imgui.is_item_hovered(): + imgui.set_tooltip("Record the window like --video; needs ffmpeg. Starting replaces an unsaved video.") + imgui.same_line() + saveable = self.unsaved_video # Saving clears it mid-frame, so the disabled scope must not re-read it. + if not saveable: + imgui.begin_disabled() + if imgui.button("Save##video"): + self.save_video() + if not saveable: + imgui.end_disabled() + if imgui.is_item_hovered(imgui.HoveredFlags_.allow_when_disabled): + imgui.set_tooltip("Keep the stopped video in the output folder") + imgui.same_line() + _c, self.video_include_hud = imgui.checkbox("Include HUD##video", self.video_include_hud) + hover_tooltip(imgui, "Draw the HUD panels into the recorded frames") + frames = self._video_frames if self.recording_video else self._video_unsaved_frames + elapsed = f"{frames / max(self._video_rate, 1):.2f} s ({frames} frames)" + if self.recording_video: + imgui.text_colored(imgui.ImVec4(*_RED), f"REC {elapsed}") + elif self.unsaved_video: + imgui.text_colored(imgui.ImVec4(*_YELLOW), f"Unsaved {elapsed}") + imgui.separator() + + def _draw_screenshot(self, imgui: Any) -> None: + """Draw the screenshot group.""" + imgui.text("Screenshot (.png)") + if imgui.button("Capture##screenshot"): + self.request_screenshot() + hover_tooltip(imgui, "Save the window image to the output folder") + imgui.same_line() + _c, self.screenshot_include_hud = imgui.checkbox("Include HUD##screenshot", self.screenshot_include_hud) + hover_tooltip(imgui, "Draw the HUD panels into the screenshot") + imgui.separator() + + def _draw_output(self, imgui: Any) -> None: + """Draw the output folder, file prefix, and numbering options.""" + imgui.text("Output") + _c, self.output_dir = imgui.input_text("Folder##recording", self.output_dir) + if imgui.is_item_hovered(): + imgui.set_tooltip( + f"Root folder, currently {resolve_output_dir(self.output_dir)}." + " Files go to /video and /screenshot" + ) + _c, self.filename_prefix = imgui.input_text("Prefix##recording", self.filename_prefix) + _c, self.auto_increment = imgui.checkbox("Auto-number", self.auto_increment) + if imgui.is_item_hovered(): + imgui.set_tooltip("Add _0001, _0002, ... so a new recording never overwrites an earlier one") + imgui.same_line() + _c, self.timestamp = imgui.checkbox("Timestamp", self.timestamp) + if imgui.is_item_hovered(): + imgui.set_tooltip("Add the start date and time to the file name") + imgui.separator() + + def _draw_message(self, imgui: Any) -> None: + """Draw the latest result message, green when saved and red when something failed.""" + if self._message: + imgui.separator() + failed = any( + word in self._message + for word in ("failed", "Could not", "needs ffmpeg", "no policy", "stopped unexpectedly", "resized") + ) + color = _GREEN if self._message.startswith("Saved") else _RED if failed else None + if color is None: + imgui.text_wrapped(self._message) + else: + imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(*color)) + imgui.text_wrapped(self._message) + imgui.pop_style_color() + + def _output_path(self, kind: str, suffix: str, when: datetime | None = None) -> Path: + """Return the next file of ``kind`` from the output settings, creating its folder. + + A numbered file is created empty, which reserves its name until the recording replaces it. + """ + folder = resolve_output_dir(self.output_dir) / kind + folder.mkdir(parents=True, exist_ok=True) + name = Path(self.filename_prefix).name or "newton" # The prefix names a file, never a folder. + if self.timestamp: + name = f"{name}_{(when or datetime.now()):%Y%m%d-%H%M%S}" + if not self.auto_increment: + return folder / f"{name}{suffix}" + pattern = re.compile(rf"^{re.escape(name)}_(\d+){re.escape(suffix)}$") + indices = [int(match.group(1)) for file in folder.iterdir() if (match := pattern.match(file.name))] + index = max(indices, default=0) + 1 + while True: + path = folder / f"{name}_{index:04d}{suffix}" + try: + with path.open("xb"): # Reserve the name, so another process cannot choose the same number. + pass + except FileExistsError: + index += 1 + continue + return path + + # ------------------------------------------------------------------ + # Video + # ------------------------------------------------------------------ + + def start_video(self) -> None: + """Start writing the displayed frames to :attr:`video_path`; the size is fixed by the first frame.""" + if self._video is not None: + return + if _ffmpeg_executable() is None: + self._message = "Video needs ffmpeg: install it or the 'video' extra." + return + self._video_frames, self._video_shape = 0, None + self._resize_reported = False + self._video_rate = self.video_fps or max(1, round(self._owner.cfg.window.fps)) + self._video_limit = round(self.video_length * self._video_rate) if self.video_length > 0 else None + folder = resolve_output_dir(self.output_dir) / "video" + try: + folder.mkdir(parents=True, exist_ok=True) + except OSError as exc: + self._message = f"Could not create the video folder: {exc}" + return + # Each recording gets its own file, so an unsaved clip survives until the new one has been encoded. + self._video_count += 1 + self._video_temp = folder / f".unsaved_video_{os.getpid()}_{id(self):x}_{self._video_count}.mp4" + self._video_started = datetime.now() + self._video = True # Opened on the first frame, once the framebuffer size is known. + self._message = "Recording video. Stop, then Save to keep it." + + def _write_video_frame(self, frame: np.ndarray) -> None: + if self._video is True: + height, width = frame.shape[:2] + path = self._video_temp + fps = self._video_rate + self._video_shape = (height, width) + try: + self._video = subprocess.Popen( # noqa: S603 + [ + _ffmpeg_executable(), "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", + "-s", f"{width}x{height}", "-r", str(fps), "-i", "-", "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", + "-c:v", "libx264", "-pix_fmt", "yuv420p", str(path), + ], + stdin=subprocess.PIPE, + ) # fmt: skip + except OSError as exc: + self._video = None + self._message = f"Could not start ffmpeg: {exc}" + return + if frame.shape[:2] != self._video_shape: + # The window was resized mid-recording; skip frames the encoder cannot accept, and say so once. + if not self._resize_reported: + self._resize_reported = True + self._message = "Window resized: video frames are skipped until it has the recorded size again." + return + video = self._video + try: + video.stdin.write(np.ascontiguousarray(frame).tobytes()) + except OSError: # Includes a broken pipe, which means ffmpeg has exited. + self._video = None + self._finish_encoder(video) + self._message = "ffmpeg stopped unexpectedly; video recording ended." + return + self._video_frames += 1 + if self._video_limit is not None and self._video_frames >= self._video_limit: + if self.stop_video(): + self.save_video() # A fixed length is meant to need no further clicks. + + def _finish_encoder(self, video: subprocess.Popen) -> bool: + """Close the encoder, wait for it, and keep its clip only when it exited cleanly; returns whether it did.""" + with contextlib.suppress(OSError): # A pipe the encoder already closed. + video.stdin.close() + succeeded = video.wait() == 0 + if succeeded and self._video_temp.exists(): + self._discard_unsaved_video() # The new clip replaces the earlier unsaved one. + self._video_unsaved = self._video_temp + self._video_unsaved_frames = self._video_frames + self._video_unsaved_started = self._video_started + return True + self._video_temp.unlink(missing_ok=True) # An earlier unsaved clip is kept. + return False + + def stop_video(self) -> bool: + """End the capture. The clip stays in a temporary file until :meth:`save_video` keeps it. + + Returns: + Whether this recording produced a new clip to save. + """ + video, self._video = self._video, None + if video is None: + return False + if video is True: + self._message = "No frame was recorded." + return False + if not self._finish_encoder(video): + self._message = "ffmpeg failed; the video was discarded." + logger.warning("[NewtonRecording] ffmpeg failed; the video recording was discarded.") + return False + self._message = f"Stopped after {self._video_frames} frames. Press Save to keep the video." + return True + + def save_video(self) -> None: + """Move the stopped video to its numbered file in the output folder.""" + temp = self._video_unsaved + if temp is None: + return + path = None + try: + path = self._output_path("video", ".mp4", self._video_unsaved_started) + shutil.move(temp, path) # Also works when the folder is on another filesystem. + except OSError as exc: # The clip stays in its temporary file, so Save can be pressed again. + if path is not None and self.auto_increment: + path.unlink(missing_ok=True) # Release the reserved name. + self._message = f"Could not save the video: {exc}" + logger.warning("[NewtonRecording] Could not save the video; the clip stays at %s: %s", temp, exc) + return + self._video_unsaved = None + self.video_path = str(path) + self._message = f"Saved {self._video_unsaved_frames} frames to {self.video_path}" + logger.info("[NewtonRecording] Wrote %d video frames to %s", self._video_unsaved_frames, self.video_path) + + def _discard_unsaved_video(self) -> None: + temp, self._video_unsaved = self._video_unsaved, None + if temp is not None: + temp.unlink(missing_ok=True) + + # ------------------------------------------------------------------ + # Per-frame capture + # ------------------------------------------------------------------ + + def capture(self, paused: bool = False) -> None: + """Record the frame that was just rendered; call once per window update, outside the frame. + + Args: + paused: Whether rendering is paused, when a video gets no new frames but a screenshot is still taken. + """ + owner = self._owner + jobs = [] + if self._video is not None and not paused: + jobs.append((self.video_include_hud, self._write_video_frame)) + if self._screenshot_pending: + self._screenshot_pending = False + jobs.append((self.screenshot_include_hud, self._write_screenshot)) + # Reading a frame with the HUD draws the HUD into the framebuffer, so the frames without it are read first. + for include_hud, write in sorted(jobs, key=lambda job: job[0]): + try: + frame = owner._viewer.get_frame(render_ui=include_hud).numpy() + except Exception as exc: # A transient read failure must not abort the simulation loop. + logger.warning("[NewtonRecording] Reading the window frame failed: %s", exc) + self.stop_video() + self._screenshot_pending = False + self._message = f"Frame capture failed: {exc}. The recording was stopped." + return + write(frame) + + def request_screenshot(self) -> None: + """Save the next rendered window frame, as a numbered PNG in the output folder.""" + self._screenshot_pending = True + + def _write_screenshot(self, frame: np.ndarray) -> None: + """Write one frame to the next screenshot file.""" + from PIL import Image # noqa: PLC0415 + + path = None + try: + path = self._output_path("screenshot", ".png") + Image.fromarray(np.ascontiguousarray(frame[..., :3], dtype=np.uint8)).save(path) + except Exception as exc: + if path is not None and self.auto_increment: + path.unlink(missing_ok=True) # Release the reserved name. + logger.exception("[NewtonRecording] Could not save the screenshot.") + self._message = f"Screenshot failed: {exc}" + return + self.screenshot_path = str(path) + self._message = f"Saved screenshot to {self.screenshot_path}" + + def close(self) -> None: + """Finish an open video recording, keeping a clip that was running or stopped but not yet saved.""" + self.stop_video() + self.save_video() 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..fd9b2d05fe97 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_rtx_appearance.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_rtx_appearance.py @@ -94,6 +94,8 @@ class SceneLight: path: str intensity: float color: tuple[float, float, float] + visible: bool = True + """Whether the scene authored the light visible; a light it hides stays hidden when the viewer shows lights.""" def find_scene_lights(stage: Any) -> list[SceneLight]: @@ -104,7 +106,16 @@ def find_scene_lights(stage: Any) -> list[SceneLight]: continue intensity, color = prim.GetAttribute("inputs:intensity"), prim.GetAttribute("inputs:color") if intensity and color and intensity.HasValue() and color.HasValue(): - lights.append(SceneLight(str(prim.GetPath()), float(intensity.Get()), tuple(float(c) for c in color.Get()))) + visibility = prim.GetAttribute("visibility") + authored_hidden = bool(visibility) and visibility.HasValue() and visibility.Get() == "invisible" + lights.append( + SceneLight( + str(prim.GetPath()), + float(intensity.Get()), + tuple(float(c) for c in color.Get()), + visible=not authored_hidden, + ) + ) return lights @@ -210,7 +221,7 @@ def apply_lights(self, active: bool = True) -> bool: paths = [light.path for light in self.lights] intensities = [light.intensity * scale for light in self.lights] colors = [np.multiply(light.color, tint) for light in self.lights] - visible = [scene_enabled] * len(paths) + visible = [scene_enabled and light.visible for light in self.lights] for reference, path, enabled, intensity, color in ( (self._dome_reference, _DOME_PATH, self.dome_enabled and active, self.dome_intensity, self.dome_color), (self._sun_reference, _SUN_PATH, self.sun_enabled and active, self.sun_intensity, self.sun_color), diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py index cb81c5dbd7ba..d94206212451 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py @@ -13,7 +13,9 @@ import math import os import sys +import threading import time +import webbrowser from collections.abc import Callable from functools import partial from pathlib import Path @@ -51,7 +53,8 @@ from isaaclab.utils.math import quat_apply, quat_from_matrix, quat_mul from isaaclab.visualizers.base_visualizer import _VISUALIZER_MAX_TILES as MAX_TILED_ENVS from isaaclab.visualizers.base_visualizer import BaseVisualizer -from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg, WindowCfg +from isaaclab.visualizers.camera_follower import CameraFollower +from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg, TrackingCameraCfg, WindowCfg from isaaclab_visualizers.desktop_entry import write_desktop_entry from isaaclab_visualizers.lidar_points import frame_visualizer_closeup, scene_has_lidar, sync_lidar_hits @@ -59,6 +62,7 @@ from isaaclab_visualizers.newton.newton_visualization_markers import render_newton_visualization_markers from .newton_key_event_source import NewtonKeyEventSource +from .newton_recording import NewtonRecordingPanel, hover_tooltip from .newton_rtx_appearance import SKY_TEXTURES, RtxAppearance logger = logging.getLogger(__name__) @@ -74,6 +78,9 @@ """Length of synthesized contact arrows in meters.""" +VISUALIZER_DOCS_URL = "https://isaac-sim.github.io/IsaacLab/main/source/concepts/visualization.html" +"""Published documentation of the visualizers, opened from the viewer's HUD.""" + _NEWTON_ICON_DIR = Path(newton.__file__).parent / "_src" / "viewer" / "gl" @@ -102,6 +109,10 @@ """What each marker group shows, by the last component of its prim path.""" +RTX_SHARED_SCENE_NOTE = "Note: with RTX on, this also changes RTX sensor cameras. Soft objects stay visible." +"""Shown beside the controls that hide environments while the RTX view is selected.""" + + def hud_note(imgui: Any, text: str) -> None: """Draw a short muted-blue note that the user should know about the control above or below it.""" imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(0.55, 0.7, 0.95, 0.85)) @@ -116,12 +127,6 @@ def hud_warning(imgui: Any, text: str) -> None: imgui.pop_style_color() -def hover_tooltip(imgui: Any, text: str) -> None: - """Show ``text`` while the last item is hovered, including when it is disabled.""" - if imgui.is_item_hovered(imgui.HoveredFlags_.allow_when_disabled): - imgui.set_tooltip(text) - - def marker_tooltip(prim_path: str) -> str: """Return a short description of the marker group at ``prim_path``, or a generic line when unknown.""" return _MARKER_TIPS.get(prim_path.rsplit("/", 1)[-1], "Show or hide this marker group") @@ -153,6 +158,46 @@ def term_summary(manager, term: str) -> str: _BACKEND_DISPLAY_NAMES = {"physx": "PhysX", "ovphysx": "OVPhysX", "newton": "Newton MJWarp"} +def _open_in_browser(url: str) -> None: + """Open *url* without blocking the render thread, since a console browser can hold ``webbrowser.open``.""" + threading.Thread(target=webbrowser.open, args=(url,), daemon=True).start() + + +@contextlib.contextmanager +def _header_tooltips(imgui, tips: dict[str, str], titles: dict[str, str] | None = None): + """Add tooltips and titles to the headers and text labels that another panel draws while this context is open. + + Args: + imgui: The ``imgui`` module. + tips: Tooltip text by the header's or text label's original text. + titles: Displayed title by the header's original label. The original label stays the header's ID, so its + open state and saved layout carry over. + """ + draw_header = imgui.collapsing_header + draw_text = imgui.text + titles = titles or {} + + def with_tooltip(label, *args, **kwargs): + shown = f"{titles[label]}###{label}" if label in titles else label + expanded = draw_header(shown, *args, **kwargs) + if label in tips: + hover_tooltip(imgui, tips[label]) + return expanded + + def text_with_tooltip(text, *args, **kwargs): + draw_text(text, *args, **kwargs) + if text in tips: + hover_tooltip(imgui, tips[text]) + + imgui.collapsing_header = with_tooltip + imgui.text = text_with_tooltip + try: + yield + finally: + imgui.collapsing_header = draw_header + imgui.text = draw_text + + def _imgui_optional_checkbox(imgui, label: str, value: bool, available: bool, tip: str, hint: str = "") -> bool: """Render a checkbox greyed out with the reason as tooltip when *available* is False, else with *hint*.""" if not available: @@ -185,13 +230,18 @@ class NewtonViewerGL(ViewerGL): keyboard_frame_hook: Callable[[], object] | None = None """Called after every frame while a :class:`NewtonKeyEventSource` listens, to track ImGui keyboard ownership.""" _owner = None + _recording_panel = None _show_stats = False """Whether the performance and model statistics overlay in the top-right corner is open.""" image_matches_camera = False """Whether the fullscreen image is rendered from :attr:`camera`, so picking rays and window fill are valid.""" _overlay_capture = None - """Publisher that also receives the line and arrow overlays, while the OVRTX view draws them.""" + """Publisher that also receives the drag arrow, while the OVRTX view draws it.""" _view_controls = None + _run_info: dict = {} + _steps_per_second = 0.0 + _real_time_factor = 0.0 + _rate_sample = (0.0, 0) PICKING_ARROW_SCALE = 4.0 """Screen-space size of the arrow drawn while dragging a body in the OpenGL view, relative to a contact arrow.""" @@ -286,7 +336,10 @@ def camera_speed(self) -> float: from pyglet.window import key boosted = self.is_key_down(key.LSHIFT) or self.is_key_down(key.RSHIFT) - return self._camera_speed * (self.CAMERA_SPEED_BOOST_MULTIPLIER if boosted else 1.0) + return self._camera_speed * (self.camera_speed_boost if boosted else 1.0) + + camera_speed_boost: float = CAMERA_SPEED_BOOST_MULTIPLIER + """Factor applied to the camera speed while Shift is held.""" @camera_speed.setter def camera_speed(self, value: float) -> None: @@ -308,20 +361,22 @@ def consume_reset_request(self) -> bool: def _patch_viewer_panel(self) -> None: """Replace Newton's left panel with an IsaacLab-oriented layout. - Section order: - - 1. **Simulation** (open) — physics backend, model info, playback and environment controls. - 2. **Live Plots** (closed) — injected when :meth:`~NewtonGLVisualizer.add_live_plots` - is called. - 3. **Model Overlays** and **Visualization Markers** (closed) — debug visibility controls. - 4. **Rendering Options** (open) — VSync, the renderer and camera source, and renderer-specific options. - 5. **Controls** (closed) — camera keyboard reference. - 6. **Selection API** (closed) — Newton's selection panel. - - The top-level Newton ``Pause / Step`` row is suppressed; pause/resume is - handled by the IsaacLab controls inside **Simulation**. + An always-visible header (task and run, physics backend and device, step and simulation + time, simulation rate and real-time factor, status badges, and a documentation link) sits above the + sections, which are ordered by how often they are used: + + 1. **Playback** (open) — pause, rendering pause, and reset controls, and any ``"side"`` UI callbacks. + 2. **Camera View** (closed) — renderer (OpenGL or RTX), camera source, and renderer-specific options. + 3. **Scene** (closed) — visible environments, visualization markers (a toggle per marker group, shared with Kit + and Viser), and visual overlays. + 4. **Recording** (closed) — video, screenshot, and their output settings. + 5. **Live Plots** (closed) — injected when :meth:`~NewtonGLVisualizer.add_live_plots` is called. + 6. **Articulation Selection** (closed) — Newton's Selection API panel. + 7. **Control Bindings** (closed) — the camera, keyboard, and mouse controls and what each one does. + + The top-level Newton ``Pause / Step`` row is suppressed; pause/resume is handled by the Isaac Lab controls + inside **Playback**. """ - import newton as nt gui = self.gui @@ -346,7 +401,8 @@ def _render_left_panel(_g=gui): imgui.ImVec2(io.display_size[0], panel_h), ) - if not imgui.begin(f"Newton Viewer v{nt.__version__}"): + # The window title already names the visualizer, so the panel has no title bar of its own. + if not imgui.begin("Newton Visualizer###newton_panel", flags=imgui.WindowFlags_.no_title_bar.value): imgui.end() return @@ -356,63 +412,59 @@ def _render_left_panel(_g=gui): for callback in _g._ui_callbacks.get("panel", []): callback(imgui) - # --- Simulation ------------------------------------------------- + viewer._draw_header(imgui) + + # --- Playback --------------------------------------------------- imgui.set_next_item_open(True, imgui.Cond_.appearing) - if imgui.collapsing_header("Simulation"): - imgui.separator() - imgui.text(f"Physics: {viewer._backend_display}") - if viewer.model is not None: - axis_names = ["X", "Y", "Z"] - imgui.text(f"Up Axis: {axis_names[viewer.model.up_axis]}") - gravity = viewer._metadata["gravity"] - imgui.text(f"Gravity: ({gravity[0]:.2f}, {gravity[1]:.2f}, {gravity[2]:.2f})") + playback_open = imgui.collapsing_header("Playback") + hover_tooltip(imgui, "Pause, resume, or reset the simulation") + if playback_open: imgui.separator() for callback in _g._ui_callbacks.get("side", []): callback(imgui) - if viewer._has_environment_controls(): - viewer._render_environment_controls(imgui) + + # --- Camera View ------------------------------------------------ + imgui.set_next_item_open(False, imgui.Cond_.appearing) + view_open = imgui.collapsing_header("Camera View") + hover_tooltip(imgui, "Choose the renderer and camera source, and adjust how the window draws") + if view_open: + if viewer._view_controls is not None: + viewer._view_controls(imgui) + + # --- Scene ------------------------------------------------------ + viewer._draw_scene_controls(imgui) + + # --- Recording -------------------------------------------------- + if viewer._recording_panel is not None: + viewer._recording_panel.draw(imgui) # --- Live Plots ------------------------------------------------- live_plots_cb = viewer._live_plots_callback if live_plots_cb is not None: live_plots_cb(imgui) - # --- Model overlays --------------------------------------------- - if viewer.model is not None: - imgui.set_next_item_open(False, imgui.Cond_.appearing) - if imgui.collapsing_header("Model Overlays"): - imgui.separator() - if viewer._fullscreen_image_active and not viewer.image_matches_camera: - imgui.text_disabled("OpenGL only") - hover_tooltip( - imgui, "Switch the Renderer to OpenGL to draw joints, contacts, and other overlays" - ) - elif viewer.image_matches_camera: - viewer._draw_model_overlays(imgui, rtx=True) - imgui.text_disabled("Collision, visual, edges, and wireframes: OpenGL only") - hud_note(imgui, "RTX: also changes what RTX sensor cameras see.") - else: - viewer._draw_model_overlays(imgui) - if viewer.marker_groups: - imgui.set_next_item_open(False, imgui.Cond_.appearing) - if imgui.collapsing_header("Visualization Markers"): - viewer._draw_marker_controls(imgui) - - # --- Rendering Options ------------------------------------------ - imgui.set_next_item_open(True, imgui.Cond_.appearing) - if imgui.collapsing_header("Rendering Options"): - imgui.separator() - _c, viewer.vsync = imgui.checkbox("VSync", viewer.vsync) - if viewer._view_controls is not None: - # these controls draw the rendering callbacks in their Lighting & Appearance group - viewer._view_controls(imgui) - else: - for callback in _g._ui_callbacks.get("rendering", []): - callback(imgui) + # --- Articulation Selection (Newton's Selection API) ------------ + with _header_tooltips( + imgui, + { + "Selection API": ( + "Newton's Selection API: select articulations by name pattern and inspect their joints, " + "links, and attributes" + ), + "Articulation Pattern:": "Name pattern selecting articulations; * matches any characters", + "Joint Filters (optional):": "Comma-separated joint names to include or exclude", + "Link Filters (optional):": "Comma-separated link names to include or exclude", + "Select Attribute:": "The attribute of the selected articulations to show", + }, + {"Selection API": "Articulation Selection"}, + ): + _g._render_selection_panel() - # --- Controls --------------------------------------------------- + # --- Control Bindings ------------------------------------------- imgui.set_next_item_open(False, imgui.Cond_.appearing) - if imgui.collapsing_header("Controls"): + controls_open = imgui.collapsing_header("Control Bindings###Controls") + hover_tooltip(imgui, "What each camera, keyboard, and mouse control does") + if controls_open: imgui.separator() picking = viewer.picking_enabled and ( not viewer._fullscreen_image_active or viewer.image_matches_camera @@ -422,7 +474,7 @@ def _render_left_panel(_g=gui): "Camera", [ "WASD - Move", - "Shift + WASD - Move 2x faster", + "Shift + WASD - Move faster (Shift Boost)", "QE - Up / down", "Left Click - Look around", "Middle Click - Orbit", @@ -440,7 +492,8 @@ def _render_left_panel(_g=gui): ( "Playback", [ - "Space - Pause / resume rendering", + "Space - Pause / resume the simulation", + "Shift + Space - Pause / resume rendering", ". - Step a frame (rendering paused)", ], ), @@ -456,12 +509,43 @@ def _render_left_panel(_g=gui): imgui.text(line) imgui.spacing() - # --- Selection API ---------------------------------------------- - _g._render_selection_panel() - imgui.end() gui._render_left_panel = _render_left_panel + render_stats = gui._render_stats_overlay + + def _hide_stats_button(imgui): + imgui.separator() + if imgui.small_button("Hide##stats"): + self._show_stats = False + hover_tooltip(imgui, "Close the performance and model statistics") + + gui._ui_callbacks.setdefault("stats", []).append(_hide_stats_button) + + def _render_overlays(_g=gui): + imgui, io, scale = _g.ui.imgui, _g.ui.io, _g.ui.dpi_scale + if self._show_stats: + render_stats() + else: # The statistics start closed; a small button in the corner opens them. + imgui.set_next_window_pos( + imgui.ImVec2(io.display_size[0] - 10 * scale, 10 * scale), pivot=imgui.ImVec2(1.0, 0.0) + ) + imgui.set_next_window_bg_alpha(0.7) + flags = ( + imgui.WindowFlags_.no_decoration.value + | imgui.WindowFlags_.always_auto_resize.value + | imgui.WindowFlags_.no_saved_settings.value + | imgui.WindowFlags_.no_focus_on_appearing.value + | imgui.WindowFlags_.no_nav.value + | imgui.WindowFlags_.no_move.value + ) + if imgui.begin("Performance Stats Toggle", flags=flags): + if imgui.small_button("Stats"): + self._show_stats = True + hover_tooltip(imgui, "Show the frame rate and the model's body, shape, and joint counts") + imgui.end() + + gui._render_stats_overlay = _render_overlays def _has_environment_controls(self) -> bool: """Return whether more than one environment can be shown, so the Environments section is useful.""" @@ -472,21 +556,64 @@ def _render_environment_controls(self, imgui) -> None: """Render the visible-environment count slider.""" owner = self._owner imgui.text("Visible Envs") + following = owner.tracking_env_only + if following: + imgui.begin_disabled() changed, new_count = imgui.slider_int("##VisibleEnvs", owner.visible_env_count, 1, owner.visible_env_limit) + if following: + imgui.end_disabled() + imgui.text_disabled("Showing only the tracking camera's env") + return if changed: owner.set_visible_env_count(new_count) if imgui.is_item_hovered(): imgui.set_tooltip("Number of environments drawn in the viewer; simulation is unaffected") if getattr(owner, "rtx_rendering", False): - hud_note(imgui, "RTX: also changes what RTX sensor cameras see.") + hud_note(imgui, RTX_SHARED_SCENE_NOTE) + + def _draw_scene_controls(self, imgui) -> None: + """Draw what can be shown in the scene: environments, visualization markers, and visual overlays.""" + imgui.set_next_item_open(False, imgui.Cond_.appearing) + expanded = imgui.collapsing_header("Scene") + hover_tooltip(imgui, "Choose which environments, markers, and visual overlays are drawn") + if not expanded: + return + imgui.separator() + if self._has_environment_controls(): + self._render_environment_controls(imgui) + self._draw_marker_controls(imgui) + if self.model is not None: + imgui.separator_text("Visual Overlays") + if self._fullscreen_image_active and not self.image_matches_camera: + imgui.text_disabled("OpenGL only") + hover_tooltip( + imgui, "Switch Camera View > Renderer to OpenGL to draw joints, contacts, and other overlays" + ) + elif self.image_matches_camera: + imgui.text_disabled("Visual overlays are currently supported in OpenGL mode only") + hover_tooltip( + imgui, "Switch Camera View > Renderer to OpenGL to draw joints, contacts, and other overlays" + ) + imgui.begin_disabled() + imgui.set_next_item_open(True, imgui.Cond_.appearing) + if imgui.tree_node("Overlay options"): + self._draw_model_overlays(imgui) + imgui.tree_pop() + imgui.end_disabled() + else: + imgui.set_next_item_open(True, imgui.Cond_.appearing) + if imgui.tree_node("Overlay options"): + self._draw_model_overlays(imgui) + imgui.tree_pop() def _draw_marker_controls(self, imgui) -> None: """Draw one toggle per visualization marker group the task registers.""" + imgui.separator_text("Visualization Markers") groups = list(self.marker_groups) if ( getattr(self._owner, "rtx_view_index", None) is not None ): # OVRTX draws the markers as prims of the shared scene - hud_note(imgui, "RTX: markers also show up in RTX sensor cameras.") + hud_note(imgui, "Note: with RTX on, markers also show in RTX sensor cameras.") if not groups: imgui.text_disabled("This task registers no visualization markers") hover_tooltip( @@ -510,8 +637,8 @@ def _draw_marker_controls(self, imgui) -> None: marker.set_visibility(False) hover_tooltip(imgui, "Hide every marker group") - def _draw_model_overlays(self, imgui, rtx: bool = False) -> None: - """Draw Newton's per-overlay toggles; the OVRTX view draws only the line and arrow overlays.""" + def _draw_model_overlays(self, imgui) -> None: + """Draw Newton's per-overlay toggles, which apply to the OpenGL view.""" renderer = self.renderer def tip(text: str) -> None: @@ -538,32 +665,18 @@ 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 + _lidar_available = self._lidar_available # these controls are only enabled in the OpenGL view 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", + "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 - if rtx: - self.show_springs = _imgui_optional_checkbox( - imgui, - "Show Springs", - self.show_springs, - _has_springs, - "No spring constraints in this environment", - "Draw spring constraints", - ) - _c, self.show_com = imgui.checkbox("Show Center of Mass", self.show_com) - tip("Draw each body's center of mass") - _c, self.show_inertia_boxes = imgui.checkbox("Show Inertia Boxes", self.show_inertia_boxes) - tip("Draw each body's inertia as a box") - return _has_cloth = _model.tri_count > 0 self.show_particles = _imgui_optional_checkbox( imgui, @@ -612,20 +725,79 @@ def tip(text: str) -> None: _c, self.show_inertia_boxes = imgui.checkbox("Show Inertia Boxes", self.show_inertia_boxes) tip("Draw each body's inertia as a box") + def _update_rates(self, steps: int, dt: float) -> None: + """Refresh the simulation rate and real-time factor from the step counter, about twice a second.""" + now = time.perf_counter() + wall, last_steps = self._rate_sample + if wall == 0.0: + self._rate_sample = (now, steps) + elif now - wall >= 0.5: + self._steps_per_second = max(0, steps - last_steps) / (now - wall) + self._real_time_factor = self._steps_per_second * dt + self._rate_sample = (now, steps) + + def set_run_info(self, task: str | None = None, mode: str | None = None, run: str | None = None) -> None: + """Name the run in the HUD header. + + Args: + task: Task name. + mode: How the run uses the task, such as ``"play"`` or ``"train"``. + run: Name of the run's log directory. + """ + self._run_info = {key: value for key, value in (("task", task), ("mode", mode), ("run", run)) if value} + + def _draw_header(self, imgui) -> None: + """Draw the always-visible summary: run, physics, scale, progress, rates, and status badges.""" + owner = self._owner + info = self._run_info + if "task" in info: + imgui.text_wrapped(f"Task: {info['task']}") + hover_tooltip(imgui, "Task this run was launched with") + if "run" in info or "mode" in info: + imgui.text(f"Run: {' · '.join(info[key] for key in ('mode', 'run') if key in info)}") + hover_tooltip(imgui, "How the task is used (play or train) and the name of the run's log directory") + device = getattr(getattr(owner, "_sim", None), "device", None) + imgui.text(f"Physics: {self._backend_display}" + (f" ({device})" if device else "")) + hover_tooltip(imgui, "Physics backend and the device it runs on") + if owner is not None and owner._num_envs: + imgui.text(f"Envs: {owner._num_envs:,}") + hover_tooltip(imgui, "Number of simulated environments") + if owner is not None and owner._sim is not None: + sim = owner._sim + steps, dt = sim.get_physics_step_count(), sim.get_physics_dt() + self._update_rates(steps, dt) + imgui.text(f"Step: {steps:,} Sim time: {steps * dt:.1f} s") + hover_tooltip(imgui, "Physics steps taken so far and the simulated time they add up to") + imgui.text(f"Sim: {self._steps_per_second:.0f} steps/s ({self._real_time_factor:.2f}x real time)") + hover_tooltip(imgui, "Physics steps per second. 1.00x means simulated time passes as fast as real time") + badges = [] + if self._paused_training or self._paused: + badges.append(("PAUSED", (1.0, 0.8, 0.2, 1.0))) + for index, (text, color) in enumerate(badges): + if index: + imgui.same_line() + imgui.text_colored(imgui.ImVec4(*color), f"[{text}]") + if imgui.text_link("Visualizer docs"): + _open_in_browser(VISUALIZER_DOCS_URL) + if imgui.is_item_hovered(): + imgui.set_tooltip(VISUALIZER_DOCS_URL) + imgui.same_line() + imgui.text_disabled(f"Newton v{newton.__version__}") + def _render_training_controls(self, imgui): - """Render the Isaac Lab playback controls inside the Simulation section.""" + """Render the Isaac Lab playback controls inside the Playback section.""" pause_label = "Resume Simulation" if self._paused_training else "Pause Simulation" if imgui.button(pause_label): self._paused_training = not self._paused_training hover_tooltip( imgui, - "Stop or resume stepping the simulation. The window keeps updating", + "Stop or resume stepping the simulation (Space). The window keeps updating", ) rendering_label = "Resume Rendering" if self._paused else "Pause Rendering" if imgui.button(rendering_label): self._paused = not self._paused - hover_tooltip(imgui, "Freeze or resume the window image (Space). The simulation keeps running") + hover_tooltip(imgui, "Freeze or resume the window image (Shift + Space). The simulation keeps running") if imgui.button("Reset Episode"): self._reset_requested = True @@ -687,6 +859,18 @@ def log_image(self, name: str, image: wp.array | np.ndarray, *, fullscreen: bool if fullscreen: self._fullscreen_image_active = True + def on_key_press(self, symbol, modifiers): + """Space pauses the simulation, and Shift + Space pauses rendering; Newton's other keys are kept.""" + from pyglet.window import key + + if symbol == key.SPACE and self.gui is not None and not self.gui.is_keyboard_capturing(): + if modifiers & key.MOD_SHIFT: + self._paused = not self._paused + else: + self._paused_training = not self._paused_training + return + super().on_key_press(symbol, modifiers) + def on_mouse_press(self, x, y, button, modifiers): """Image coordinates must not pick objects in the hidden perspective scene, unless it is the image's camera.""" if self._fullscreen_image_active and not self.image_matches_camera: @@ -783,12 +967,13 @@ class NewtonVisualizerBase(BaseVisualizer): _rtx_camera_path: str | None = None """Prim path of the viewer camera launch declared for this window; None accepts any viewer camera.""" _rtx_arrows_pending = False - _rtx_overlay_flags: tuple | None = None _rtx_visibility_limited = False + _capturing_another_view = False + _warned_recording_stopped = False _rtx_switch: str | None = None """``"requested"`` once the HUD asked for RTX and showed the wait message, ``"loading"`` until its first frame.""" - _borrowing_view = False - """Whether an off-screen capture has swapped the displayed view, so the window controls must not act on it.""" + _hidden_warned: frozenset = frozenset() + """Tracking views already reported as framing an environment the window does not draw.""" _rtx_appearance: RtxAppearance | None = None # The OpenGL window overrides these; the standalone RTX window has no OpenGL view to switch to. @@ -799,6 +984,9 @@ class NewtonVisualizerBase(BaseVisualizer): """Callbacks that draw a scene sensor's own controls in the Camera Sensor section; see :meth:`register_sensor_ui_callback`.""" + _track_env_only = False + """Whether only the selected Tracking Camera's environment is drawn.""" + def __init__(self, cfg): super().__init__(cfg) self._viewer = None @@ -806,11 +994,19 @@ def __init__(self, cfg): self._runtime_headless = cfg.headless self._last_present_time = -math.inf self._last_render_step = -1 + self._capturing_another_view = False self._pending_mesh_submissions: dict[str, dict[str, Any]] = {} self._camera_keys_enabled = True self._overlay_publisher = None self._pose_started = False self._marker_revision = -1 + self._followers: dict[object, CameraFollower] = {} + """Followers of the tracking cameras, by image view.""" + self._rtx_pose_view = None + """Tracking Camera view that moves the OVRTX camera, or None when the free camera drives it.""" + self._tracking_defaults: dict[object, dict] = {} + """What the task declared for each tracking camera, for Reset to Task Default.""" + self._tracking_error = "" self._perspective_pose: tuple | None = None """Last pose and focal length of the Perspective view, kept while another source is shown.""" self._sensor_tiles: dict[object, int] = {} @@ -824,12 +1020,27 @@ def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraC """Bind camera sources and the display mode shared by both windows.""" super().initialize(sim, cameras=cameras) # each perspective view renders itself, so a recorder can capture one the window does not show + scene = self._sim.get_scene_data_provider().get_interactive_scene() for view in self._image_views: if view.camera is not None: continue if view.render is not None: raise ValueError("A perspective image view must have exactly one rendering owner.") view.render = partial(self._capture_view, view) + source = view.cfg.source + if self._is_tracking_view(view): + if scene is None: + raise ValueError("A tracking camera needs an interactive scene to follow.") + # fail at initialization, not on a frame: a bad env_index or track_path raises here + self._followers[view] = follower = CameraFollower(source, scene, self._env_ids) + self._remember_tracking_defaults(view, follower) + if self._env_ids is not None and follower.env not in self._env_ids: + logger.warning( + "[NewtonVisualizer] A tracking camera frames environment %d, which is not among the visible " + "environments %s, so it will show an empty scene.", + follower.env, + list(self._env_ids), + ) self._runtime_headless = self.cfg.headless or ( sys.platform not in ("win32", "darwin") and not os.environ.get("DISPLAY") ) @@ -936,6 +1147,11 @@ def _rtx_renderers(self) -> tuple: renderers[id(renderer)] = renderer return tuple(renderers.values()) + @staticmethod + def _is_tracking_view(view) -> bool: + """Whether *view* is a tracking camera.""" + return isinstance(view.cfg.source, TrackingCameraCfg) + def _draw_rtx_unavailable(self, imgui) -> None: """Show the Renderer choice greyed out, since without the OVRTX viewer camera it cannot be made at runtime.""" imgui.begin_disabled() @@ -948,17 +1164,28 @@ def _draw_rtx_unavailable(self, imgui) -> None: hover_tooltip( imgui, "RTX adds an OVRTX camera, which costs some startup time and a little speed, so it is opt-in" ) - hud_note(imgui, "Launch with --viz newton_rtx to enable the RTX toggle.") + hud_note(imgui, "Use --viz newton_rtx to enable RTX.") def _draw_streaming_view_controls(self, imgui) -> None: """Choose one declared display source without reading the other sensors.""" - if self._borrowing_view: # an off-screen capture swapped the view; the window controls must not act on it + if ( + self._capturing_another_view + ): # an off-screen capture swapped the view; the window controls must not act on it return rtx_index = getattr(self, "rtx_view_index", None) + # The OVRTX camera is chosen with the Renderer toggle, so the list holds only the other sources. + indices = sorted( + (i for i in range(len(self._image_views)) if i != rtx_index), + key=lambda i: self._source_rank(self._image_views[i]), + ) + if indices: + self._draw_camera_source(imgui, indices, rtx_index) + if rtx_index is not None or isinstance(self, NewtonGLVisualizer): + imgui.separator_text("Rendering") if rtx_index is not None: rtx_on = self.rtx_rendering sensor = self.sensor_view_selected - if sensor: # The sensor draws its own image, so the choice would only leave the sensor view. + if sensor or not indices: # Without another source there is nothing to switch to or from. imgui.begin_disabled() imgui.text("Renderer") imgui.same_line() @@ -968,7 +1195,7 @@ def _draw_streaming_view_controls(self, imgui) -> None: imgui.set_tooltip( "Fast rasterizer with visual overlays and markers" if not sensor - else "A scene sensor is rendered by its own renderer. This applies to the free camera" + else "A scene sensor is rendered by its own renderer. This applies to the free and tracking cameras" ) imgui.same_line() if imgui.radio_button("RTX", rtx_on) and not rtx_on and self._rtx_switch is None: @@ -978,50 +1205,83 @@ def _draw_streaming_view_controls(self, imgui) -> None: imgui.set_tooltip( "OVRTX path-traced rendering of the scene; slower than OpenGL" if not sensor - else "A scene sensor is rendered by its own renderer. This applies to the free camera" + else "A scene sensor is rendered by its own renderer. This applies to the free and tracking cameras" ) - if sensor: + if sensor or not indices: imgui.end_disabled() if self._rtx_switch is not None: hud_warning(imgui, "Switching to RTX. The first frame can take a while and the window may not respond.") elif isinstance(self, NewtonGLVisualizer): self._draw_rtx_unavailable(imgui) self._draw_appearance(imgui) - self._draw_focal_length(imgui) - # The OVRTX camera is chosen with the Renderer toggle, so the list holds only the other sources. - indices = sorted( - (i for i in range(len(self._image_views)) if i != rtx_index), - key=lambda i: self._source_rank(self._image_views[i]), - ) + self._draw_navigation_controls(imgui) + self._draw_camera_info(imgui) + self._draw_window_options(imgui) + + def _draw_window_options(self, imgui) -> None: + """Draw the window options, last in the Camera View because they are rarely changed.""" + imgui.separator_text("Window") + _, self._viewer.vsync = imgui.checkbox("VSync", self._viewer.vsync) + hover_tooltip(imgui, "Match the window's frame rate to the display's refresh rate. Off by default") + + def _draw_camera_source(self, imgui, indices: list[int], rtx_index: int | None) -> None: + """Draw the Camera Source selector, and the output controls when a scene sensor is selected.""" + imgui.separator_text("Camera Source") labels = self._view_labels(indices) current = self._image_views.index(self.current_image_view) - if current == rtx_index: # RTX renders the free perspective source. - current = next( - (i for i in indices if self._image_views[i].camera is None), - indices[0], # No free perspective view: show the first source + if current == rtx_index: # RTX renders the free perspective source or follows a Tracking Camera. + pose_view = self._rtx_pose_view + current = ( + self._image_views.index(pose_view) + if pose_view is not None + else next( + ( + i + for i in indices + if self._image_views[i].camera is None and not self._is_tracking_view(self._image_views[i]) + ), + indices[0], # No free perspective view: show the first source + ) ) position = indices.index(current) - changed, chosen = imgui.combo("Camera Source", position, labels) + imgui.set_next_item_width(-1) # the section header names it, so the dropdown needs no label + changed, chosen = imgui.combo("##CameraSource", position, labels) if changed: self._choose_camera_source(indices[chosen]) if imgui.is_item_hovered(): - imgui.set_tooltip(labels[position]) - if self.sensor_view_selected: + imgui.set_tooltip( + "What the window shows: an interactive Perspective camera, a Tracking Camera defined by the task, " + "or any scene camera sensor, whose RGB, depth, and other visual outputs can be viewed" + ) + follower = self._followers.get(self._pose_source_view()) + if follower is None and self._track_env_only: + self._track_env_only = False # Only a Tracking Camera can restrict the visible environments. + self._apply_visible_worlds() + if follower is not None: + self._draw_tracking_camera_controls(imgui, follower) + elif self.sensor_view_selected: self._draw_sensor_controls(imgui, self.current_image_view) - self._draw_camera_info(imgui) + + def _draw_navigation_controls(self, imgui) -> None: + """Draw the free camera's lens and keyboard speed; a scene sensor has fixed intrinsics and does not move.""" + if self.sensor_view_selected: + return + imgui.separator_text("Camera Settings") + self._draw_focal_length(imgui) + self._draw_camera_speed(imgui) def _draw_camera_info(self, imgui) -> None: """Draw the navigation camera's position, field of view, and orientation.""" camera = getattr(self._viewer, "camera", None) if camera is None or self.sensor_view_selected: # A sensor draws its own image, not this camera's view. return - imgui.separator() + imgui.separator_text("Camera Data") pos = camera.pos - imgui.text_disabled(f"Position: ({pos[0]:.2f}, {pos[1]:.2f}, {pos[2]:.2f})") + imgui.text(f"Position: ({pos[0]:.2f}, {pos[1]:.2f}, {pos[2]:.2f})") hover_tooltip(imgui, "World position of the camera [m]") - imgui.text_disabled(f"Rotation: (pitch {camera.pitch:.1f}, yaw {camera.yaw:.1f}) deg") + imgui.text(f"Rotation: (pitch {camera.pitch:.1f}, yaw {camera.yaw:.1f}) deg") hover_tooltip(imgui, "Look direction: pitch up or down, yaw around the vertical axis") - imgui.text_disabled(f"FOV: {camera.fov:.1f} deg") + imgui.text(f"FOV: {camera.fov:.1f} deg") hover_tooltip(imgui, "Vertical field of view; the Focal Length slider changes it") def _rtx_appearance_controller(self) -> RtxAppearance | None: @@ -1054,13 +1314,14 @@ def _rtx_appearance_controller(self) -> RtxAppearance | None: return self._rtx_appearance def _draw_appearance(self, imgui) -> None: - """Draw the lighting and appearance options of the active renderer, right below the Camera Source selector.""" + """Draw the lighting and appearance options of the active renderer, below the renderer toggle.""" rtx_rendering = getattr(self, "rtx_rendering", None) if rtx_rendering is None: # the standalone RTX window has no OpenGL rendering callbacks or toggle return if rtx_rendering: self._draw_rtx_appearance(imgui) - hud_note(imgui, "RTX: lighting also changes what RTX sensor cameras see.") # shown with the section closed + # shown with the section closed + hud_note(imgui, "Note: with RTX on, lighting also changes RTX sensor cameras.") return callbacks = self._viewer.gui._ui_callbacks.get("rendering") if self._viewer.gui is not None else None if callbacks and imgui.tree_node("Lighting & Appearance###appearance"): @@ -1089,6 +1350,11 @@ def light_changed(changed: bool) -> bool: def intensity(label: str, value: float, high: float) -> tuple[bool, float]: return imgui.slider_float(label, value, 0.0, high, "%.0f", imgui.SliderFlags_.logarithmic) + imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(0.55, 0.7, 0.95, 0.85)) + imgui.text_wrapped( + "In RTX mode, changing the lighting edits the scene itself, so cameras that share its renderer see it too." + ) + imgui.pop_style_color() imgui.separator_text("Lights") if appearance.lights: changed, appearance.scene_enabled = imgui.checkbox("Scene Lights", appearance.scene_enabled) @@ -1204,8 +1470,10 @@ def _draw_sky_texture(self, imgui, appearance: RtxAppearance) -> bool: return edited def _source_rank(self, view) -> int: - """Order the Camera Source list: the free Perspective, then scene sensors.""" - return 0 if view.camera is None else 1 + """Order the Camera Source list: the free Perspective, then Tracking Cameras, then scene sensors.""" + if view.camera is not None: + return 2 + return 1 if self._is_tracking_view(view) else 0 def register_sensor_ui_callback(self, callback: Callable[[Any, Camera], None]) -> None: """Draw a scene sensor's own controls in the Camera Sensor section, below the Camera Source selector. @@ -1299,13 +1567,14 @@ def _invalidate_sensor_view(self, view) -> None: self._last_render_step = -1 def _draw_focal_length(self, imgui) -> None: - """Draw the focal length of the free camera; sensors have fixed intrinsics.""" - view = self.current_image_view + """Draw the focal length of the free camera or the Tracking Camera; sensors have fixed intrinsics.""" + view = self._pose_source_view() rtx_index = getattr(self, "rtx_view_index", None) rtx_view = self._image_views[rtx_index] if rtx_index is not None else None if view.camera is not None and view is not rtx_view: return - source = self.cfg + follower = self._followers.get(view) + source = follower.cfg if follower is not None else self.cfg # a Tracking Camera edits the follower's copy changed, focal = imgui.slider_float("Focal Length", float(source.focal_length), 5.0, 64.0, "%.0f mm") hover_tooltip(imgui, "Lens focal length of the camera; smaller values see a wider area") if changed: @@ -1314,13 +1583,145 @@ def _draw_focal_length(self, imgui) -> None: view.invalidate() self._last_render_step = -1 + def _draw_camera_speed(self, imgui) -> None: + """Draw the keyboard speed of the free camera, which RTX follows; tracking cameras and sensors do not move.""" + if self.sensor_view_selected or self._is_tracking_view(self._pose_source_view()): + return + speed = float(self._viewer._camera_speed) + changed, speed = imgui.slider_float( + "Camera Speed", speed, 0.1, 50.0, "%.1f m/s", imgui.SliderFlags_.logarithmic + ) + hover_tooltip(imgui, "How fast the WASD keys move the camera") + if changed: + self._viewer.camera_speed = speed + changed, boost = imgui.slider_float("Shift Boost", float(self._viewer.camera_speed_boost), 1.0, 10.0, "%.1fx") + hover_tooltip(imgui, "How much faster the camera moves while Shift is held") + if changed: + self._viewer.camera_speed_boost = boost + + def _draw_tracking_camera_controls(self, imgui, follower: CameraFollower) -> None: + """Edit the selected Tracking Camera: what it follows, where it sits, and where it looks.""" + cfg = follower.cfg + edited = False + + def tip(text: str) -> None: + hover_tooltip(imgui, text) + + imgui.separator_text("Tracking Camera") + changed, env = imgui.input_int("Environment", follower.env) + tip("Environment the camera follows") + if changed and 0 <= env < self._sim.get_scene_data_provider().num_envs: + follower.set_env(env) + self._sync_tracked_env() + edited = True + asset_name, _, body_name = (cfg.track_path or "").partition("/") + assets = ["None (fixed in environment)", *follower.asset_names()] + changed, index = imgui.combo("Asset", assets.index(asset_name) if asset_name in assets else 0, assets) + tip("Scene asset the camera follows. None keeps it fixed relative to the environment") + if changed: + edited |= self._set_tracking_path(follower, assets[index] if index else None) + if asset_name: + bodies = ["Root", *follower.body_names(asset_name)] + changed, index = imgui.combo("Body", bodies.index(body_name) if body_name in bodies else 0, bodies) + tip("Body of the asset the camera follows. Root follows the asset itself") + if changed: + edited |= self._set_tracking_path(follower, f"{asset_name}/{bodies[index]}" if index else asset_name) + changed, only = imgui.checkbox("Show Only This Env", self._track_env_only) + tip("Draw only the camera's environment, following it when the environment changes") + if self.rtx_rendering: + hud_note(imgui, RTX_SHARED_SCENE_NOTE) + if changed: + self._track_env_only = only + self._apply_visible_worlds() + edited = True + changed, eye = imgui.input_float3("Eye (m)", list(cfg.eye)) + tip("Camera position, as an offset from the followed asset or the environment origin") + if changed: + cfg.eye, edited = tuple(float(v) for v in eye), True + changed, lookat = imgui.input_float3("Look At (m)", list(cfg.lookat)) + tip("Point the camera looks at, as an offset from the followed asset or the environment origin") + if changed: + cfg.lookat, edited = tuple(float(v) for v in lookat), True + if asset_name: + changed, cfg.follow_heading = imgui.checkbox("Follow Heading", cfg.follow_heading) + tip("Turn with the asset's heading, so the camera stays behind it and level") + edited |= changed + if cfg.follow_heading: + changed, smoothing = imgui.slider_float( + "Smoothing", cfg.heading_smoothing_time_constant, 0.0, 2.0, "%.2f s" + ) + tip("Heading filter time constant; larger values damp turns more but lag") + if changed: + cfg.heading_smoothing_time_constant, edited = smoothing, True + if imgui.button("Reset to Task Default"): + edited |= self._reset_tracking_camera(follower) + tip("Restore what the task declared for this camera") + if self._tracking_error: + imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(1.0, 0.35, 0.35, 1.0)) + imgui.text_wrapped(self._tracking_error) + imgui.pop_style_color() + if edited: + self._apply_view_pose(self._pose_source_view()) # a paused window does not move the camera by itself + self.current_image_view.invalidate() + self._last_render_step = -1 + + def _set_tracking_path(self, follower: CameraFollower, track_path: str | None) -> bool: + """Follow ``track_path``, reporting an unknown asset or ambiguous body instead of raising.""" + try: + follower.set_track_path(track_path) + except ValueError as exc: + self._tracking_error = str(exc) + return False + self._tracking_error = "" + return True + + def _reset_tracking_camera(self, follower: CameraFollower) -> bool: + """Restore the camera's declared pose, optics, and target; returns whether anything changed.""" + defaults = self._tracking_defaults.get(self._pose_source_view()) # In RTX the Tracking view is not current. + if defaults is None: + return False + cfg = follower.cfg + cfg.eye, cfg.lookat, cfg.focal_length = defaults["eye"], defaults["lookat"], defaults["focal_length"] + cfg.follow_heading = defaults["follow_heading"] + cfg.heading_smoothing_time_constant = defaults["heading_smoothing_time_constant"] + follower.set_env(defaults["env"]) + self._sync_tracked_env() + return self._set_tracking_path(follower, defaults["track_path"]) or True + + @property + def tracking_env_only(self) -> bool: + """Whether only the selected Tracking Camera's environment is drawn.""" + return self._track_env_only and self._followers.get(self._pose_source_view()) is not None + + def _select_visible_env_ids(self) -> list[int] | None: + """Return the environments to draw; the base keeps the ones it has.""" + return getattr(self, "_env_ids", None) + + def _sync_tracked_env(self) -> None: + """Redraw the visible environments when the Tracking Camera or its environment changed what they are.""" + if self._viewer is not None and self._select_visible_env_ids() != getattr(self, "_env_ids", None): + self._apply_visible_worlds() + def _view_labels(self, indices: list[int] | None = None) -> list[str]: - """Name the listed image views: a free view is the Perspective.""" + """Name the listed image views, each with a short descriptor in parentheses like the scene sensors have. + + A free view is a ``Perspective (interactive)``, a tracking view ``Tracking Camera (follows robot)`` or + ``Tracking Camera (fixed to env)`` when it follows no asset. + """ views = self._image_views if indices is None else [self._image_views[i] for i in indices] - return [ - "Perspective" if view.camera is None else self._sensor_label(view.cfg.source, view.camera.cfg.data_types) - for view in views - ] + tracking = [v for v in views if self._is_tracking_view(v)] + labels = [] + for view in views: + if view.camera is not None: + labels.append(self._sensor_label(view.cfg.source, view.camera.cfg.data_types)) + elif self._is_tracking_view(view): + name = "Tracking Camera" if len(tracking) == 1 else f"Tracking Camera {tracking.index(view) + 1}" + follower = self._followers.get(view) # a window edit changes the follower's copy, not the task's cfg + asset = ((follower.cfg if follower else view.cfg.source).track_path or "").partition("/")[0] + labels.append(f"{name} (follows {asset})" if asset else f"{name} (fixed to env)") + else: + labels.append("Perspective (interactive)") + return labels _OUTPUT_NAMES = { "rgb": "RGB", @@ -1350,20 +1751,40 @@ def _sensor_label(prim_path: str, data_types=()) -> str: kind = " + ".join(outputs[:3]) + " " if outputs else "" return f"{prim_path.rstrip('/').rsplit('/', 1)[-1]} ({kind}sensor)" + def _pose_source_view(self): + """Return the view whose camera settings are shown: the one driving the OVRTX camera, or the current view.""" + if getattr(self, "rtx_rendering", False) and self._rtx_pose_view is not None: + return self._rtx_pose_view + return self.current_image_view + def _choose_camera_source(self, index: int) -> None: - """Switch the camera source; a free source keeps the OVRTX renderer when it is on.""" + """Switch the camera source; a free or Tracking Camera source keeps the OVRTX renderer when it is on.""" view = self._image_views[index] if self.rtx_rendering and view.camera is None: - return # the OVRTX camera already follows the Perspective + followed_tracking = self._rtx_pose_view is not None + if followed_tracking or self._is_tracking_view(view): + self._remember_perspective_pose() + self._rtx_pose_view = view if self._is_tracking_view(view) else None + if self._rtx_pose_view is not None: + self._apply_view_pose(view) + elif not self._restore_perspective_pose(): # back to a Perspective that was never left + self._apply_declared_pose(view.cfg.source) + self.current_image_view.invalidate() + self._sync_tracked_env() + return # otherwise the OVRTX camera already follows the Perspective self._select_camera(index) + self._sync_tracked_env() def _remember_perspective_pose(self) -> None: """Save the Perspective's pose before another source takes over the viewer camera.""" current = self.current_image_view if current is None or self._viewer is None: return - # The viewer camera holds the Perspective's pose while it is shown, and while the OVRTX camera follows it. - if current.camera is None or (self.rtx_rendering and any(v.camera is None for v in self._image_views)): + # The viewer camera holds the Perspective's pose while it is shown, and while the OVRTX camera follows it + # rather than a Tracking Camera. + shown = current.camera is None and not self._is_tracking_view(current) + following = self.rtx_rendering and self._rtx_pose_view is None + if shown or (following and any(v.camera is None and not self._is_tracking_view(v) for v in self._image_views)): camera = self._viewer.camera pos = camera.pos self._perspective_pose = ( @@ -1383,6 +1804,57 @@ def _restore_perspective_pose(self) -> bool: self._viewer.camera.fov = self._focal_length_to_vertical_fov_degrees(focal) return True + def _remember_tracking_defaults(self, view, follower: CameraFollower) -> None: + """Keep what the task declared for a tracking *view*, which its reset control restores.""" + source = view.cfg.source + self._tracking_defaults[view] = { + "eye": source.eye, + "lookat": source.lookat, + "focal_length": source.focal_length, + "track_path": source.track_path, + "follow_heading": source.follow_heading, + "heading_smoothing_time_constant": source.heading_smoothing_time_constant, + "env": follower.env, + } + + def _apply_view_pose(self, view) -> bool: + """Point the viewer camera where a tracking camera looks, leaving the configured poses untouched. + + Returns: + Whether the view had a pose yet; a view that follows an asset has none until the asset is ready. + """ + follower = self._followers.get(view) + if follower is None: + return False + try: + pose = follower.pose(self._sim.get_physics_step_count() * self._sim.get_physics_dt()) + except ValueError as exc: # a body that only turned out to be ambiguous once the asset was initialized + asset_name = (follower.cfg.track_path or "").partition("/")[0] + self._set_tracking_path(follower, asset_name or None) + self._tracking_error = f"{exc} Following the asset's root instead." + logger.warning("[NewtonVisualizer] %s", self._tracking_error) + return False + if pose is None: + return False + eye, target = pose + offsets = self._viewer.world_offsets + if offsets is not None and not getattr(self, "rtx_rendering", False): # only OpenGL draws at the offsets + shift = wp.to_torch(offsets)[follower.env].tolist() + eye = tuple(a + b for a, b in zip(eye, shift)) + target = tuple(a + b for a, b in zip(target, shift)) + camera = self._viewer.camera + camera.pos = PygletVec3(*eye) + camera.look_at(target) + self._viewer.set_camera(camera.pos, camera.pitch, camera.yaw) + camera.fov = self._focal_length_to_vertical_fov_degrees(follower.cfg.focal_length) + return True + + def _apply_declared_pose(self, source: PerspectiveCameraCfg) -> None: + """Move the viewer camera to the pose and focal length a free Perspective source declares.""" + self.set_camera_view(source.eye, source.lookat) + self.cfg.focal_length = source.focal_length + self._viewer.camera.fov = self._focal_length_to_vertical_fov_degrees() + def _release_rtx_scene(self) -> None: """Give the scene cameras that share the OVRTX renderer back the overlays and lights the viewer added.""" if self._overlay_publisher is not None: @@ -1402,16 +1874,20 @@ def _select_camera(self, index: int, *, keep_pose: bool = False) -> None: leaving_rtx = self.rtx_rendering and index != self.rtx_view_index if leaving_rtx: self._release_rtx_scene() + # the hidden viewer camera goes back to rendering only when read, whichever source replaces it + self._image_views[self.rtx_view_index].camera.cfg.render_on_demand = True self.current_image_view = self._image_views[index] if leaving_rtx: self._apply_rtx_visible_envs() # restore every environment to the sensors that share the renderer + if index != getattr(self, "rtx_view_index", None): + self._rtx_pose_view = None camera = self.current_image_view.cfg.source self.current_image_view.invalidate() if isinstance(camera, PerspectiveCameraCfg): - if not keep_pose and not self._restore_perspective_pose(): - self.set_camera_view(camera.eye, camera.lookat) - self.cfg.focal_length = camera.focal_length - self._viewer.camera.fov = self._focal_length_to_vertical_fov_degrees() + if isinstance(camera, TrackingCameraCfg): + self._apply_view_pose(self.current_image_view) + elif not keep_pose and not self._restore_perspective_pose(): + self._apply_declared_pose(camera) elif keep_pose: self._place_scene_camera_at_viewer(self.current_image_view.camera) else: @@ -1464,26 +1940,47 @@ def _navigate_scene_camera(self) -> None: camera.set_world_poses(positions + translation, quat_mul(orientations, rotation), convention="opengl") self.current_image_view.invalidate() + def _warn_if_hidden(self, view) -> None: + """Warn once when a recorded Tracking Camera frames an environment the window does not draw.""" + follower = self._followers.get(view) + if follower is None or view in self._hidden_warned: + return + visible = getattr(self, "_env_ids", None) + if visible is not None and follower.env not in visible: + self._hidden_warned = self._hidden_warned | {view} + logger.warning( + "[NewtonVisualizer] The recorded Tracking Camera frames environment %d, which the window does not " + "draw (visible environments %s or 'Show Only This Env'), so the clip shows an empty scene.", + follower.env, + list(visible), + ) + def _capture_view(self, view, output: wp.array | None) -> wp.array: """Capture a perspective *view*, borrowing the viewer camera when the window shows another one.""" current = self.current_image_view - # a free view records what an RTX window shows - if view is current or self.rtx_rendering: + # a free view records what an RTX window shows, and so does the tracking camera the RTX view follows + if view is current or ( + self.rtx_rendering and (not self._is_tracking_view(view) or view is self._rtx_pose_view) + ): return self._capture_frame(output) camera = self._viewer.camera saved = (PygletVec3(camera.pos.x, camera.pos.y, camera.pos.z), camera.pitch, camera.yaw, camera.fov) try: - self._borrowing_view = True + self._capturing_another_view = True # the HUD recording keeps the frames the window itself shows self.current_image_view = view - source = view.cfg.source # a free view renders from its declared pose and optics - camera.pos = PygletVec3(*source.eye) - camera.look_at(source.lookat) - self._viewer.set_camera(camera.pos, camera.pitch, camera.yaw) - camera.fov = self._focal_length_to_vertical_fov_degrees(source.focal_length) + if self._is_tracking_view(view): # rendering may be paused, which leaves the camera where it was + self._warn_if_hidden(view) + self._apply_view_pose(view) + else: # a free view renders from its declared pose and optics + source = view.cfg.source + camera.pos = PygletVec3(*source.eye) + camera.look_at(source.lookat) + self._viewer.set_camera(camera.pos, camera.pitch, camera.yaw) + camera.fov = self._focal_length_to_vertical_fov_degrees(source.focal_length) self._last_render_step = -1 return self._capture_frame(output) finally: - self._borrowing_view = False + self._capturing_another_view = False self.current_image_view = current camera.fov = saved[3] self._viewer.set_camera(*saved[:3]) @@ -1528,10 +2025,15 @@ def reset(self, soft: bool = False) -> None: """Invalidate the displayed frame after a simulation reset.""" super().reset(soft) self._last_render_step = -1 + for follower in self._followers.values(): + follower.reset() # the heading filter must not carry the previous episode over def close(self) -> None: """Detach perspective producers before releasing the visualizer's borrowed views.""" self._pending_mesh_submissions.clear() + self._followers.clear() + self._tracking_defaults.clear() + self._hidden_warned = frozenset() self._perspective_pose = None self._sensor_tiles.clear() if self._rtx_appearance is not None: @@ -1540,7 +2042,8 @@ def close(self) -> None: self._rtx_appearance.close() self._rtx_appearance = None for view in self._image_views: - if view.camera is None and view.render is not None: # the perspective views bound in initialize + owned = isinstance(view.render, partial) and view.render.func == self._capture_view + if owned: view.render = None view.invalidate() super().close() @@ -1619,10 +2122,31 @@ def render_rgb_array(self) -> np.ndarray: ) return self.current_image_view.read_rgb(frame_id) + @property + def has_tracking_view(self) -> bool: + """Whether a tracking camera is declared.""" + return any(self._is_tracking_view(view) for view in self._image_views) + + def render_tracking_rgb_array(self) -> np.ndarray: + """Download the first tracking camera view, whatever the window shows.""" + view = next((v for v in self._image_views if self._is_tracking_view(v)), None) + if view is None: + raise RuntimeError("The visualizer declares no tracking camera. Add a TrackingCameraCfg to its cameras.") + frame = view.frame + # while rendering is paused the tracking view keeps its last frame, instead of picking up the window's view + frame_id = ( + frame.timestamp + if self._viewer is not None and self._viewer.is_paused() and frame.data is not None + else self._sim.get_physics_step_count() + ) + return view.read_rgb(frame_id) + class NewtonGLVisualizer(NewtonVisualizerBase): """Newton model rendering, picking, and contact overlays used by the GL visualizer.""" + _recording: NewtonRecordingPanel | None = None + @property def visual_material_writer(self): """Return the shared Newton model color-writer factory.""" @@ -1729,6 +2253,7 @@ def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraC self._cfg_visible_env_ids = self._env_ids self._num_envs = num_envs self._viewer._owner = self + self._recording = self._viewer._recording_panel = NewtonRecordingPanel(self) self._apply_visible_worlds() self._viewer._paused = False self._viewer.picking_enabled = self._picking_enabled @@ -1800,7 +2325,8 @@ def _render_frame(self) -> None: """Render one GL frame for the window or an on-demand capture.""" viewer = self._viewer appearance = self._rtx_appearance - if self._rtx_switch == "requested": # the previous frame showed the message + # the previous window frame showed the message; a capture borrowing the view must not start the switch + if self._rtx_switch == "requested" and not self._capturing_another_view: self._rtx_switch = "loading" try: self.set_rtx_rendering(True) @@ -1817,6 +2343,10 @@ def _render_frame(self) -> None: raise try: viewer.image_matches_camera = self.rtx_rendering + pose_view = self._pose_source_view() + # a paused scene is frozen, and so is its camera + if self._is_tracking_view(pose_view) and not viewer.is_paused(): + self._apply_view_pose(pose_view) if self.current_image_view.camera is not None: self._navigate_scene_camera() self._refresh_rtx_markers() @@ -1840,7 +2370,7 @@ def _render_frame(self) -> None: for name, arguments in self._pending_mesh_submissions.items(): viewer.log_mesh(name, **arguments) self._pending_mesh_submissions.clear() - if not viewer.is_paused(): + if not viewer.is_paused() and not self._capturing_another_view: # a capture must not add plot samples self._render_live_plots() finally: viewer.end_frame() @@ -1848,12 +2378,21 @@ def _render_frame(self) -> None: self._rtx_switch = None if not viewer.is_running(): self._viewer_picking_binding.deactivate() + if self._recording is not None and not self._capturing_another_view: + if viewer.is_running(): + self._recording.capture(paused=viewer.is_paused()) + elif not self._warned_recording_stopped: + # A closed window has released its OpenGL resources; close() finishes the encoder instead. + self._warned_recording_stopped = True + logger.warning( + "[NewtonVisualizer] The window closed, so the HUD recording stops here and is saved on exit." + ) self._last_render_step = self._sim.get_physics_step_count() if self.current_image_view.camera is None: self.current_image_view.invalidate() def _log_rtx_overlays(self) -> bool: - """Draw the line and arrow overlays the HUD enables, and the drag arrow, as meshes in OVRTX. + """Draw the drag arrow as meshes in OVRTX; Newton's model overlays are drawn in OpenGL only. Returns: Whether the drag arrow is being drawn, which an OVRTX view that is not stepping must render again. @@ -1862,45 +2401,22 @@ def _log_rtx_overlays(self) -> bool: if publisher is None or not self.rtx_rendering: return False renderers = self._rtx_renderers - overlays = any( - getattr(viewer, flag) - for flag in ("show_joints", "show_contacts", "show_springs", "show_com", "show_inertia_boxes") - ) dragging = viewer.picking_enabled and viewer.picking is not None and viewer.picking.is_picking() - flags = tuple( - getattr(viewer, flag) - for flag in ("show_joints", "show_contacts", "show_springs", "show_com", "show_inertia_boxes") - ) - changed = flags != self._rtx_overlay_flags # a paused view must render again to show the change - self._rtx_overlay_flags = flags - if not overlays and not dragging: + if not dragging: publisher.hide_all(renderers) - return changed + return False if viewer.is_paused(): return False state = self._update_state() if state.body_q is not None and not len(state.body_q): return False viewer._overlay_capture = publisher - # Contact disks are instanced meshes that only the OpenGL view draws, and they dominate the contact cost. - disks = viewer.show_contact_disks - viewer.show_contact_disks = False try: - if overlays: - # Only the overlays are needed, not the per-shape instances that log_state also updates for OpenGL. - getattr(viewer, "_log_non_shape_state", viewer.log_state)(state) - contacts = self._sim.backend_manager.get_contacts() if self.physics_backend == "newton" else None - if contacts is not None: - viewer.log_contacts(contacts, state) - else: - self._log_scene_contact_sensor_arrows() - else: - viewer._render_picking_line(state) + viewer._render_picking_line(state) finally: viewer._overlay_capture = None - viewer.show_contact_disks = disks publisher.publish(renderers) - return bool(dragging) or changed + return True def _refresh_rtx_markers(self) -> None: """Render the OVRTX cameras again when a marker group is shown, hidden, or moved, which OVRTX draws as prims.""" @@ -1927,7 +2443,7 @@ def _refresh_paused_rtx_view(self, arrows_changed: bool) -> None: return if not (arrows_changed or self._rtx_arrows_pending or view.frame.timestamp < 0): return - view.camera._is_outdated.fill_(True) + view.camera._invalidate_buffers() # also marks the data dirty, which a zero-step update needs to render view.camera.update(0.0, force_recompute=True) view.invalidate() self._rtx_arrows_pending = arrows_changed # One more render shows the arrows gone. @@ -1958,6 +2474,8 @@ def rtx_view_index(self) -> int | None: def _is_viewer_camera(self, prim_path: str) -> bool: """Whether *prim_path* is the viewer camera launch declared for this window, or any viewer camera if none.""" + if getattr(self.cfg.backend, "rtx_camera", None) is False: # this window opted out, so it takes no camera + return False declared = self._rtx_camera_path return prim_path == declared if declared else prim_path.startswith("/World/viewer_camera_") @@ -1982,20 +2500,38 @@ def set_rtx_rendering(self, enabled: bool) -> None: rtx_index = self.rtx_view_index if rtx_index is None: raise RuntimeError("The scene has no OVRTX viewer camera; see NewtonGLBackendCfg.rtx_camera.") - free = [i for i, view in enumerate(self._image_views) if view.camera is None] + free = [ + i for i, view in enumerate(self._image_views) if view.camera is None and not self._is_tracking_view(view) + ] # While the RTX view is shown its camera joins the scene's shared render, so reading it does not submit every # camera product a second time; otherwise it renders only on demand. self._image_views[rtx_index].camera.cfg.render_on_demand = not enabled if enabled: + # A Tracking Camera keeps moving the OVRTX camera, which has no pose of its own. + current = self.current_image_view + self._rtx_pose_view = current if self._is_tracking_view(current) else None self._select_camera(rtx_index, keep_pose=True) self._apply_rtx_visible_envs() if self._rtx_appearance is not None and self._rtx_appearance.available: self._rtx_appearance.apply_lights() else: - target = free[0] if free else next(i for i in range(len(self._image_views)) if i != rtx_index) + back = self._rtx_pose_view # _select_camera clears it after the outgoing pose is saved + fallback = free[0] if free else next(i for i in range(len(self._image_views)) if i != rtx_index) + target = self._image_views.index(back) if back is not None else fallback # Only a perspective view continues from the viewer's pose; a scene sensor keeps the task's own placement. self._select_camera(target, keep_pose=self._image_views[target].camera is None) + def set_run_info(self, task: str | None = None, mode: str | None = None, run: str | None = None) -> None: + """Name the run in the HUD header. + + Args: + task: Task name. + mode: How the run uses the task, such as ``"play"`` or ``"train"``. + run: Name of the run's log directory. + """ + if self._viewer is not None: + self._viewer.set_run_info(task, mode, run) + @property def visible_env_limit(self) -> int: """Largest value of the visible-environment count: the environments the cfg allows, else all.""" @@ -2004,12 +2540,14 @@ def visible_env_limit(self) -> int: @property def visible_env_count(self) -> int: """Number of environments currently shown.""" + if self.tracking_env_only: + return 1 if self._visible_env_count is not None: return min(self._visible_env_count, self.visible_env_limit) return self.visible_env_limit def set_visible_env_count(self, count: int) -> None: - """Show only the first ``count`` environments. + """Show only the first ``count`` environments; a Tracking Camera's environment takes the last place if missing. Args: count: Number of environments to show, clamped to ``[1, visible_env_limit]``. @@ -2018,11 +2556,18 @@ def set_visible_env_count(self, count: int) -> None: self._apply_visible_worlds() def _select_visible_env_ids(self) -> list[int] | None: - """Resolve the environments to show from the cfg and the HUD count.""" + """Resolve the environments to show from the cfg, the HUD count, and the Tracking Camera.""" + if self.tracking_env_only: + return [self._followers[self._pose_source_view()].env] if self._visible_env_count is None: return self._cfg_visible_env_ids - ids = self._cfg_visible_env_ids if self._cfg_visible_env_ids is not None else range(self._num_envs) - return list(ids)[: self._visible_env_count] + allowed = list(self._cfg_visible_env_ids if self._cfg_visible_env_ids is not None else range(self._num_envs)) + ids = allowed[: self._visible_env_count] + follower = self._followers.get(self._pose_source_view()) + if follower is not None and follower.env in allowed and follower.env not in ids: + # the Tracking Camera's own environment is always drawn: it takes the place of the last one counted + ids = sorted([*ids[:-1], follower.env]) + return ids def _drop_shape_instancers(self) -> None: """Free the GL shape instancers so they are re-allocated for the new visible worlds. @@ -2119,9 +2664,13 @@ def close(self) -> None: self._overlay_publisher.hide_all(self._rtx_renderers) except Exception: logger.debug("[NewtonVisualizer] The overlay meshes could not be hidden.", exc_info=True) - if self._picking_enabled: - # Captured graphs retain neutral picking inputs until their last replay. - self._viewer_picking_binding.deactivate() + try: + if self._recording is not None: + self._recording.close() + finally: + if self._picking_enabled: + # Captured graphs retain neutral picking inputs until their last replay. + self._viewer_picking_binding.deactivate() if sys.platform == "win32" and self._viewer is not None and not self._runtime_headless: window = self._viewer.renderer.window if window.context is not None: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py index 30d539292409..f33051331d07 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py @@ -18,6 +18,34 @@ from .newton_visualizer import NewtonGLVisualizer +@configclass +class NewtonRecordingCfg: + """Output settings of the Recording section in the Newton GL HUD. + + Every output lands in ``//``, where ``kind`` is ``video`` or ``screenshot``. + The HUD edits a copy of these values while the window is open. + """ + + output_dir: str = "recording" + """Root folder of all recordings. Relative paths resolve against the repository folder when running from a source + checkout, and against the working directory otherwise.""" + + filename_prefix: str = "newton" + """Start of every recording's file name.""" + + auto_increment: bool = True + """Append a counter (``_0001``, ``_0002``, ...) so a new recording never overwrites an earlier one.""" + + timestamp: bool = False + """Append the date and time (``YYYYmmdd-HHMMSS``) to the file name; a video uses the time its recording started.""" + + video_fps: int | None = None + """Frame rate of the encoded video [Hz]. ``None`` uses the window's update rate (:attr:`WindowCfg.fps`).""" + + video_length: float | None = None + """Duration of the video [s] after which recording stops by itself. ``None`` records until stopped.""" + + @configclass class NewtonGLBackendCfg(VisualizerBackendCfg): """Newton visualizer options: OpenGL rendering and model display, and the optional OVRTX view.""" @@ -85,6 +113,9 @@ class NewtonGLBackendCfg(VisualizerBackendCfg): light_color: tuple[float, float, float] = (1.0, 1.0, 1.0) """Light color RGB [0, 1].""" + recording: NewtonRecordingCfg = NewtonRecordingCfg() + """Defaults of the HUD's Recording section.""" + rtx_camera: bool | None = None """Declare an OVRTX viewer camera so the HUD can switch the main view between Newton GL and OVRTX. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer.py index d46da6df1eb5..064e78a89079 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/rerun/rerun_visualizer.py @@ -219,7 +219,7 @@ def __init__(self, cfg: VisualizerCfg): cfg: Rerun visualizer configuration. """ warnings.warn( - "The Rerun visualizer is deprecated in Isaac Lab 3.2 and will be removed in Isaac Lab 3.3. " + "The Rerun visualizer is deprecated in Isaac Lab 3.1 and will be removed in Isaac Lab 3.3. " "Use the Viser visualizer instead (--viz viser, or VisualizerCfg(backend=ViserBackendCfg())).", FutureWarning, stacklevel=2, diff --git a/source/isaaclab_visualizers/test/test_newton_adapter.py b/source/isaaclab_visualizers/test/test_newton_adapter.py index c7dc28cf1e83..399cffcdc32b 100644 --- a/source/isaaclab_visualizers/test/test_newton_adapter.py +++ b/source/isaaclab_visualizers/test/test_newton_adapter.py @@ -12,6 +12,7 @@ import sys import textwrap from contextlib import nullcontext +from functools import partial from types import SimpleNamespace from unittest.mock import Mock, call @@ -39,7 +40,7 @@ from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils import validate from isaaclab.utils.warp import ProxyArray -from isaaclab.visualizers import PerspectiveCameraCfg, SceneCameraCfg, VisualizerCfg, WindowCfg +from isaaclab.visualizers import PerspectiveCameraCfg, SceneCameraCfg, TrackingCameraCfg, VisualizerCfg, WindowCfg from isaaclab.visualizers.base_visualizer import BaseVisualizer @@ -437,6 +438,27 @@ def test_newton_gl_viewer_rendering_pause_state_stays_in_sync_with_space_key(): assert viewer.is_rendering_paused() is False +def test_newton_gl_viewer_space_pauses_the_simulation_and_shift_space_pauses_rendering(monkeypatch): + """Space and Shift + Space toggle the two pauses, unless a text field has the keyboard.""" + from pyglet.window import key + + viewer = NewtonViewerGL.__new__(NewtonViewerGL) + viewer._paused, viewer._paused_training = False, False + viewer.gui = SimpleNamespace(is_keyboard_capturing=lambda: False) + + viewer.on_key_press(key.SPACE, 0) + assert (viewer._paused_training, viewer._paused) == (True, False) + + viewer.on_key_press(key.SPACE, key.MOD_SHIFT) + assert (viewer._paused_training, viewer._paused) == (True, True) + + viewer.gui = SimpleNamespace(is_keyboard_capturing=lambda: True) + # Newton's own handler is not under test + monkeypatch.setattr(NewtonViewerGL.__mro__[1], "on_key_press", lambda *_: None) + viewer.on_key_press(key.SPACE, 0) + assert viewer._paused_training is True + + def test_newton_gl_viewer_skips_picking_only_while_a_fullscreen_image_is_shown(monkeypatch): """Clicks on a fullscreen sensor image, which Newton dispatches during ``end_frame()``, must not pick in the hidden perspective scene, and picking must resume once a frame shows the scene again. @@ -681,7 +703,7 @@ def _make_newton_visualizer(viewer, scene_data_provider=None, state=None, *, cfg from isaaclab.visualizers import ImageView, ImageViewCfg view = ImageView(ImageViewCfg(source=PerspectiveCameraCfg())) - view.render = visualizer._capture_frame + view.render = partial(visualizer._capture_view, view) visualizer.current_image_view, visualizer._image_views = view, [view] if viewer is not None and isinstance(visualizer, NewtonGLVisualizer): visualizer._viewer_picking_binding.bind(viewer) @@ -1430,6 +1452,46 @@ def get_term_cfg(self, name): assert term_summary(object(), "anything") == "" # Managers without a term accessor. +def test_the_rtx_view_keeps_following_the_tracking_camera_and_returns_to_it(): + from isaaclab.visualizers import PerspectiveCameraCfg + + def view(source, camera=None): + return SimpleNamespace(camera=camera, cfg=SimpleNamespace(source=source), invalidate=Mock()) + + rtx_camera = SimpleNamespace(cfg=SimpleNamespace(prim_path="/World/viewer_camera_0")) + free, rtx, tracking = ( + view(PerspectiveCameraCfg()), + view(PerspectiveCameraCfg(), rtx_camera), + view(TrackingCameraCfg(env_index=0)), + ) + visualizer = object.__new__(NewtonGLVisualizer) + visualizer._image_views = [free, rtx, tracking] + visualizer.cfg = SimpleNamespace(backend=SimpleNamespace(rtx_camera_path="/World/viewer_camera_0")) + visualizer.current_image_view = tracking + visualizer._rtx_pose_view = None + + pose_view_when_selecting = [] + + def select(index, keep_pose=False): + pose_view_when_selecting.append(visualizer._rtx_pose_view) + visualizer.current_image_view = visualizer._image_views[index] + if index != visualizer.rtx_view_index: + visualizer._rtx_pose_view = None + + visualizer._select_camera = select + visualizer._apply_rtx_visible_envs = lambda: None + + visualizer.set_rtx_rendering(True) + + assert visualizer.rtx_rendering and visualizer._pose_source_view() is tracking + + visualizer.set_rtx_rendering(False) + + assert visualizer.current_image_view is tracking and visualizer._rtx_pose_view is None + # Selecting away saves the outgoing pose first, which must still see the Tracking Camera driving the viewer. + assert pose_view_when_selecting[-1] is tracking + + def test_sensor_labels_name_the_outputs_of_the_sensor(): label = NewtonGLVisualizer._sensor_label assert label("/World/envs/env_[^/]+/Camera", ["rgb", "depth"]) == "Camera (RGB + depth sensor)" @@ -1463,6 +1525,7 @@ def test_a_mesh_logged_to_the_rtx_view_refreshes_its_cached_image(): view = Mock(camera=camera) renderer = Mock() visualizer._is_initialized, visualizer._viewer = True, object() + visualizer.cfg = SimpleNamespace(backend=SimpleNamespace(rtx_camera=None)) visualizer._pending_mesh_submissions = {} visualizer._image_views, visualizer._sim = [view], SimpleNamespace(get_or_create_backend=lambda cfg: renderer) visualizer.current_image_view = object() @@ -1522,3 +1585,39 @@ def get_or_create_backend(cfg, camera=None): assert [cfg.source for cfg in created] == ["/World/viewer_camera_1_rtx"] assert visualizer.rtx_view_index == 1 + + +def test_switching_camera_source_refreshes_the_visible_environment(): + visualizer = _make_newton_visualizer(_Viewer()) + visualizer._image_views = [SimpleNamespace(camera=None)] + visualizer._select_camera = Mock() + visualizer._sync_tracked_env = Mock() + + visualizer._choose_camera_source(0) + + visualizer._select_camera.assert_called_once_with(0) + visualizer._sync_tracked_env.assert_called_once_with() + + +def test_newton_visualizer_shows_only_the_tracking_camera_env(): + viewer = _Viewer() + viewer.set_visible_worlds = Mock() + viewer.set_world_offsets = Mock() + visualizer = _make_newton_visualizer(viewer) + visualizer._cfg_visible_env_ids, visualizer._visible_env_count, visualizer._num_envs = None, None, 8 + view = object() + follower = SimpleNamespace(env=5) + visualizer._followers = {view: follower} + visualizer._pose_source_view = lambda: view + visualizer._track_env_only = True + + visualizer._sync_tracked_env() + assert visualizer.tracking_env_only and visualizer.visible_env_count == 1 + viewer.set_visible_worlds.assert_called_with([5]) + + follower.env = 2 + visualizer._sync_tracked_env() + viewer.set_visible_worlds.assert_called_with([2]) + + visualizer._followers = {} # Tracking Camera deselected: the HUD count applies again + assert not visualizer.tracking_env_only and visualizer.visible_env_count == 8 diff --git a/source/isaaclab_visualizers/test/test_newton_recording.py b/source/isaaclab_visualizers/test/test_newton_recording.py new file mode 100644 index 000000000000..0630f276629e --- /dev/null +++ b/source/isaaclab_visualizers/test/test_newton_recording.py @@ -0,0 +1,438 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for the Newton GL HUD recording panel without a window.""" + +import re +from types import SimpleNamespace +from unittest.mock import Mock + +import numpy as np +import pytest +from isaaclab_visualizers.newton import NewtonRecordingCfg, newton_recording +from isaaclab_visualizers.newton.newton_recording import NewtonRecordingPanel, _ffmpeg_executable, resolve_output_dir + +pytestmark = pytest.mark.kitless + + +class _Array: + def __init__(self, values): + self._values = np.asarray(values) + + def numpy(self): + return self._values + + +def _owner(frames=(), **recording): + state = SimpleNamespace(body_q=_Array([[0, 0, 1, 0, 0, 0, 1]]), joint_q=_Array([0.5, -0.5])) + frames = iter(frames) + viewer = SimpleNamespace(get_frame=lambda render_ui=False: _Array(next(frames))) + return SimpleNamespace( + _update_state=lambda: state, + _viewer=viewer, + _sim_time=0.0, + cfg=SimpleNamespace( + window=SimpleNamespace(fps=10.0), backend=SimpleNamespace(recording=NewtonRecordingCfg(**recording)) + ), + ) + + +def test_output_paths_number_stamp_or_overwrite(tmp_path): + panel = NewtonRecordingPanel(_owner(output_dir=str(tmp_path), filename_prefix="run")) + + first = panel._output_path("video", ".mp4") + first.touch() + assert [first.name, panel._output_path("video", ".mp4").name] == ["run_0001.mp4", "run_0002.mp4"] + + panel.auto_increment = False + assert panel._output_path("video", ".mp4").name == "run.mp4" + + panel.timestamp = True + assert re.fullmatch(r"run_\d{8}-\d{6}\.mp4", panel._output_path("scene", ".mp4").name) + assert (tmp_path / "scene").is_dir() + + +def test_numbered_files_are_reserved_so_two_savers_never_pick_the_same_name(tmp_path): + first = NewtonRecordingPanel(_owner(output_dir=str(tmp_path), filename_prefix="run")) + second = NewtonRecordingPanel(_owner(output_dir=str(tmp_path), filename_prefix="run")) + + names = [first._output_path("video", ".mp4").name, second._output_path("video", ".mp4").name] + + assert names == ["run_0001.mp4", "run_0002.mp4"] # the first name was taken before it was written + + +@pytest.mark.skipif(_ffmpeg_executable() is None, reason="ffmpeg is not installed") +def test_video_streams_frames_and_ignores_resized_ones(tmp_path): + frames = [np.full((16, 24, 3), 10 * i, np.uint8) for i in range(3)] + [np.zeros((8, 8, 3), np.uint8)] + panel = NewtonRecordingPanel(_owner(frames, output_dir=str(tmp_path))) + + panel.start_video() + for _ in frames: + panel.capture() + panel.stop_video() + panel.save_video() + + assert panel._video_frames == 3 + assert (tmp_path / "video" / "newton_0001.mp4").stat().st_size > 0 + assert not panel.recording_video + + +@pytest.mark.skipif(_ffmpeg_executable() is None, reason="ffmpeg is not installed") +def test_stopped_video_is_kept_only_when_saved(tmp_path): + frames = [np.zeros((16, 24, 3), np.uint8)] * 6 + panel = NewtonRecordingPanel(_owner(frames, output_dir=str(tmp_path))) + video_dir = tmp_path / "video" + + panel.start_video() + panel.capture() + panel.capture() + panel.stop_video() + + assert panel.unsaved_video and not panel.recording_video + assert [file.name for file in video_dir.iterdir()] == [panel._video_temp.name] # Nothing numbered yet. + + panel.start_video() # Starting again keeps the unsaved clip until the new one has been encoded. + assert panel.unsaved_video + panel.capture() + panel.stop_video() + panel.save_video() + + assert not panel.unsaved_video + assert [file.name for file in video_dir.iterdir()] == ["newton_0001.mp4"] + + +@pytest.mark.skipif(_ffmpeg_executable() is None, reason="ffmpeg is not installed") +def test_video_with_a_length_saves_itself(tmp_path): + frames = [np.zeros((16, 24, 3), np.uint8)] * 10 + panel = NewtonRecordingPanel(_owner(frames, output_dir=str(tmp_path), video_fps=4, video_length=1.0)) + + panel.start_video() + for _ in frames: + panel.capture() + + assert not panel.recording_video and not panel.unsaved_video + assert panel._video_frames == 4 # 1 s at 4 Hz + assert "Saved 4 frames" in panel._message + assert (tmp_path / "video" / "newton_0001.mp4").exists() + + +@pytest.mark.skipif(_ffmpeg_executable() is None, reason="ffmpeg is not installed") +def test_closing_keeps_a_running_video(tmp_path): + panel = NewtonRecordingPanel(_owner([np.zeros((16, 24, 3), np.uint8)] * 2, output_dir=str(tmp_path))) + + panel.start_video() + panel.capture() + panel.close() + + assert (tmp_path / "video" / "newton_0001.mp4").exists() + + +@pytest.mark.parametrize("source_checkout", [True, False]) +def test_relative_output_folder_follows_the_repository_only_in_a_source_checkout( + tmp_path, monkeypatch, source_checkout +): + root, cwd = tmp_path / "root", tmp_path / "cwd" + (root / "source" if source_checkout else root).mkdir(parents=True) + cwd.mkdir() + monkeypatch.setattr(newton_recording, "ISAACLAB_ROOT", root) + monkeypatch.chdir(cwd) + + assert resolve_output_dir("recording") == (root if source_checkout else cwd) / "recording" + assert resolve_output_dir(str(tmp_path / "absolute")) == tmp_path / "absolute" + + +class _StrictImgui: + """Imgui double that clicks one button and fails like imgui does on an unbalanced disabled scope.""" + + class HoveredFlags_: + allow_when_disabled = 1 + + def __init__(self, click: str): + self.click, self.disabled_depth = click, 0 + + def ImVec4(self, *values): # noqa: N802 + return values + + def button(self, label): + return label == self.click + + def checkbox(self, _label, value): + return False, value + + def begin_disabled(self): + self.disabled_depth += 1 + + def end_disabled(self): + assert self.disabled_depth > 0, "Calling EndDisabled() too many times!" + self.disabled_depth -= 1 + + def __getattr__(self, _name): + return lambda *args, **kwargs: False + + +def test_saving_a_video_keeps_the_disabled_scopes_balanced(tmp_path): + frames = [np.zeros((16, 24, 3), np.uint8)] * 3 + panel = NewtonRecordingPanel(_owner(frames, output_dir=str(tmp_path))) + panel.start_video() + panel.capture() + panel.stop_video() + imgui = _StrictImgui(click="Save##video") + + panel._draw_video(imgui) # Saving clears the unsaved video partway through the frame. + + assert not panel.unsaved_video and imgui.disabled_depth == 0 + + +def test_screenshot_writes_the_next_frame_as_a_numbered_png(tmp_path): + frame = np.zeros((4, 6, 3), np.uint8) + frame[..., 0] = 200 + panel = NewtonRecordingPanel(_owner(frames=[frame, frame], output_dir=str(tmp_path))) + + panel.request_screenshot() + panel.capture() + panel.capture() # Nothing is pending, so no second file. + panel.request_screenshot() + panel.capture() + + from PIL import Image + + folder = tmp_path / "screenshot" + assert sorted(file.name for file in folder.iterdir()) == ["newton_0001.png", "newton_0002.png"] + assert np.array(Image.open(folder / "newton_0001.png"))[0, 0].tolist() == [200, 0, 0] + assert panel.screenshot_path == str(folder / "newton_0002.png") + + +class _Encoder: + """Stand-in for the ffmpeg process whose input pipe can break.""" + + def __init__(self, broken=False, returncode=0): + self.broken, self.returncode, self.waited, self.written = broken, returncode, False, 0 + self.stdin = SimpleNamespace(write=self._write, close=self._close) + + def _write(self, data): + if self.broken: + raise BrokenPipeError + self.written += 1 + + def _close(self): + if self.broken: + raise BrokenPipeError + + def wait(self): + self.waited = True + return self.returncode + + +def _recording_to(tmp_path, encoder, **recording): + panel = NewtonRecordingPanel(_owner(output_dir=str(tmp_path), **recording)) + panel._video, panel._video_shape, panel._video_limit = encoder, (4, 4), None + panel._video_temp = tmp_path / ".unsaved_video.mp4" + panel._video_started = None + panel._video_temp.write_bytes(b"partial") + return panel + + +def test_a_broken_encoder_pipe_ends_the_recording_and_reaps_the_process(tmp_path): + encoder = _Encoder(broken=True, returncode=1) + panel = _recording_to(tmp_path, encoder) + + panel._write_video_frame(np.zeros((4, 4, 3), np.uint8)) + + assert not panel.recording_video and encoder.waited # The dead process is reaped, not left as a zombie. + assert not panel.unsaved_video and not panel._video_temp.exists() # A failed encode is not offered for saving. + assert "ffmpeg stopped unexpectedly" in panel._message + + +def test_an_encoder_that_exits_with_an_error_leaves_nothing_to_save(tmp_path): + panel = _recording_to(tmp_path, _Encoder(returncode=1)) + + panel.stop_video() + + assert not panel.unsaved_video and "ffmpeg failed" in panel._message + + +def test_an_unwritable_output_folder_is_reported_instead_of_raised(tmp_path): + blocker = tmp_path / "file" + blocker.write_text("not a folder") + panel = NewtonRecordingPanel(_owner(frames=[np.zeros((4, 6, 3), np.uint8)], output_dir=str(blocker))) + + panel.request_screenshot() + panel.capture() + assert "Screenshot failed" in panel._message + + +def test_each_panel_encodes_to_its_own_temporary_file_and_a_prefix_cannot_leave_the_folder(tmp_path, monkeypatch): + monkeypatch.setattr(newton_recording, "_ffmpeg_executable", lambda: "ffmpeg") + first = NewtonRecordingPanel(_owner(output_dir=str(tmp_path), filename_prefix="../outside")) + second = NewtonRecordingPanel(_owner(output_dir=str(tmp_path))) + first.start_video() + second.start_video() + + assert first._video_temp != second._video_temp + path = first._output_path("video", ".mp4") + assert path.parent == tmp_path / "video" + assert path.name == "outside_0001.mp4" + + +def test_a_screenshot_is_taken_while_rendering_is_paused_but_a_video_gets_no_frame(tmp_path): + panel = NewtonRecordingPanel(_owner(frames=[np.zeros((4, 6, 3), np.uint8)], output_dir=str(tmp_path))) + encoder = _Encoder() + panel._video, panel._video_shape = encoder, (4, 6) + + panel.request_screenshot() + panel.capture(paused=True) + + assert encoder.written == 0 and (tmp_path / "screenshot" / "newton_0001.png").exists() + + +def test_a_failed_save_is_reported_as_a_save_error_and_can_be_retried(tmp_path, monkeypatch): + panel = _recording_to(tmp_path, _Encoder(), video_length=0.0) + panel.stop_video() + assert panel.unsaved_video + + monkeypatch.setattr("shutil.move", Mock(side_effect=OSError("disk full"))) + panel.save_video() + + assert panel.unsaved_video and "disk full" in panel._message and "ffmpeg" not in panel._message + monkeypatch.undo() + panel.save_video() + assert not panel.unsaved_video and (tmp_path / "video" / "newton_0001.mp4").exists() + + +def test_hud_is_captured_only_when_the_toggle_asks_for_it(tmp_path): + requested = [] + owner = _owner(frames=[np.zeros((4, 6, 3), np.uint8)] * 2, output_dir=str(tmp_path)) + owner._viewer.get_frame = lambda render_ui=False: ( + requested.append(render_ui) or _Array(np.zeros((4, 6, 3), np.uint8)) + ) + panel = NewtonRecordingPanel(owner) + + panel.request_screenshot() + panel.capture() + panel.screenshot_include_hud = True + panel.request_screenshot() + panel.capture() + + assert requested == [False, True] + + +def test_starting_a_video_that_cannot_begin_keeps_the_unsaved_clip(tmp_path, monkeypatch): + panel = NewtonRecordingPanel(_owner(output_dir=str(tmp_path))) + clip = tmp_path / ".earlier.mp4" + clip.write_bytes(b"clip") + panel._video_unsaved = clip + blocker = tmp_path / "file" + blocker.write_text("not a folder") + panel.output_dir = str(blocker) + + monkeypatch.setattr(newton_recording, "_ffmpeg_executable", lambda: "ffmpeg") # whether or not it is installed + panel.start_video() # The video folder cannot be created. + + assert not panel.recording_video and "Could not create" in panel._message + assert panel.unsaved_video and clip.exists() + + monkeypatch.setattr(newton_recording, "_ffmpeg_executable", lambda: None) + panel.start_video() + assert panel.unsaved_video and clip.exists() + + +def test_a_new_clip_replaces_the_unsaved_one_only_once_it_is_encoded(tmp_path): + clip = tmp_path / ".earlier.mp4" + clip.write_bytes(b"clip") + failed = _recording_to(tmp_path, _Encoder(returncode=1)) + failed._video_unsaved, failed._video_unsaved_frames = clip, 7 + + failed.stop_video() + + assert failed.unsaved_video and clip.exists() and failed._video_unsaved_frames == 7 # The earlier clip is kept. + + done = _recording_to(tmp_path, _Encoder()) + done._video_unsaved, done._video_unsaved_frames = clip, 7 + done._video_frames = 3 + + done.stop_video() + + assert done._video_unsaved == done._video_temp and done._video_unsaved_frames == 3 and not clip.exists() + + +def test_a_screenshot_without_the_hud_is_read_before_a_video_frame_that_draws_it(tmp_path): + requested = [] + owner = _owner(output_dir=str(tmp_path)) + owner._viewer.get_frame = lambda render_ui=False: ( + requested.append(render_ui) or _Array(np.zeros((4, 6, 3), np.uint8)) + ) + panel = NewtonRecordingPanel(owner) + panel._video, panel._video_shape = _Encoder(), (4, 6) + panel.video_include_hud, panel.screenshot_include_hud = True, False + + panel.request_screenshot() + panel.capture() + + assert requested == [False, True] # The HUD drawn for the video must not reach the screenshot. + assert (tmp_path / "screenshot" / "newton_0001.png").exists() + + +def test_closing_warns_where_the_unsaved_clip_stays_when_it_cannot_be_saved(tmp_path, monkeypatch, caplog): + panel = _recording_to(tmp_path, _Encoder()) + monkeypatch.setattr("shutil.move", Mock(side_effect=OSError("disk full"))) + + with caplog.at_level("WARNING"): + panel.close() + + assert str(panel._video_temp) in caplog.text and "disk full" in caplog.text + assert panel._video_temp.exists() + + +def test_a_video_that_stopped_unexpectedly_is_shown_as_a_failure(): + panel = NewtonRecordingPanel(_owner()) + panel._message = "ffmpeg stopped unexpectedly; video recording ended." + imgui = Mock() + imgui.ImVec4 = lambda *color: color + + panel._draw_message(imgui) + + imgui.push_style_color.assert_called_once_with(imgui.Col_.text, newton_recording._RED) + + +def test_a_fixed_length_recording_whose_encode_failed_does_not_save_the_earlier_clip(tmp_path): + clip = tmp_path / ".earlier.mp4" + clip.write_bytes(b"clip") + panel = _recording_to(tmp_path, _Encoder(returncode=1)) + panel._video_unsaved, panel._video_unsaved_frames = clip, 7 + panel._video_shape, panel._video_limit = (4, 4), 1 + + panel._write_video_frame(np.zeros((4, 4, 3), np.uint8)) + + assert "ffmpeg failed" in panel._message and not panel.video_path # not overwritten by a 'Saved' message + assert panel.unsaved_video and clip.exists() + + +def test_a_window_resize_during_a_recording_is_reported_once(tmp_path): + panel = _recording_to(tmp_path, _Encoder()) + panel._video_shape = (4, 4) + + panel._write_video_frame(np.zeros((8, 8, 3), np.uint8)) + panel._message = "" + panel._write_video_frame(np.zeros((8, 8, 3), np.uint8)) + + assert panel._video_frames == 0 and panel._message == "" # reported on the first skipped frame only + panel._resize_reported = False + panel._write_video_frame(np.zeros((8, 8, 3), np.uint8)) + assert "Window resized" in panel._message + + +def test_a_failed_frame_read_stops_the_recording_instead_of_raising(tmp_path): + panel = _recording_to(tmp_path, _Encoder()) + + def unreadable(render_ui=False): + raise RuntimeError("GL read failed") + + panel._owner._viewer.get_frame = unreadable + panel.request_screenshot() + + panel.capture() + + assert not panel.recording_video and "Frame capture failed" in panel._message + assert not panel._screenshot_pending diff --git a/source/isaaclab_visualizers/test/test_newton_rtx_appearance.py b/source/isaaclab_visualizers/test/test_newton_rtx_appearance.py index 9226ecfe1269..04263f533f38 100644 --- a/source/isaaclab_visualizers/test/test_newton_rtx_appearance.py +++ b/source/isaaclab_visualizers/test/test_newton_rtx_appearance.py @@ -35,9 +35,13 @@ def Get(self): class _Prim: - def __init__(self, path, kind, intensity=None, color=None): + def __init__(self, path, kind, intensity=None, color=None, visibility=None): self._path, self._kind = path, kind - self._attrs = {"inputs:intensity": _Attr(intensity), "inputs:color": _Attr(color)} + self._attrs = { + "inputs:intensity": _Attr(intensity), + "inputs:color": _Attr(color), + "visibility": _Attr(visibility), + } def GetPath(self): return self._path @@ -119,6 +123,23 @@ def test_scene_lights_are_on_and_the_dome_and_distant_lights_are_off_by_default( assert _states(native) == {"/World/sun": "inherited"} +def test_a_light_the_scene_authored_invisible_stays_hidden(): + stage = _Stage( + [ + _Prim("/World/on", "DistantLight", 1.0, (1.0, 1.0, 1.0)), + _Prim("/World/off", "DomeLight", 1.0, (1.0, 1.0, 1.0), visibility="invisible"), + ] + ) + native = _Native() + renderer = SimpleNamespace(_use_ovstage=False, backend=SimpleNamespace(renderer=native)) + appearance = RtxAppearance(stage, renderer, "/Render/product") + + assert appearance.apply_lights() + assert _states(native) == {"/World/on": "inherited", "/World/off": "invisible"} + assert appearance.suspend() + assert _states(native) == {"/World/on": "inherited", "/World/off": "invisible"} + + def test_scene_lights_take_an_intensity_scale_and_a_color_tint(): appearance, native = _appearance() appearance.scene_scale, appearance.scene_tint = 0.5, (1.0, 0.0, 0.0) diff --git a/source/isaaclab_visualizers/test/test_newton_task_views.py b/source/isaaclab_visualizers/test/test_newton_task_views.py index 2ec760426e10..2f4fff56ecf9 100644 --- a/source/isaaclab_visualizers/test/test_newton_task_views.py +++ b/source/isaaclab_visualizers/test/test_newton_task_views.py @@ -3,12 +3,13 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Unit tests for the camera sources of the Newton GL window.""" +"""Unit tests for the Tracking Camera views of the Newton GL window.""" from __future__ import annotations from types import SimpleNamespace +import numpy as np import pytest import torch @@ -16,7 +17,8 @@ from isaaclab_visualizers.newton.newton_visualizer import NewtonGLVisualizer, NewtonVisualizerBase from pyglet.math import Vec3 -from isaaclab.visualizers import PerspectiveCameraCfg +from isaaclab.visualizers import PerspectiveCameraCfg, TrackingCameraCfg +from isaaclab.visualizers.camera_follower import CameraFollower pytestmark = pytest.mark.kitless @@ -35,13 +37,14 @@ def look_at(self, target): class _Scene: num_envs = 2 env_origins = torch.tensor([[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]]) + articulations, rigid_objects = {"robot": None}, {} def __getitem__(self, name): return SimpleNamespace(is_initialized=False) class _View: - """An image view; a class, not a namespace, so that it can key the pose dictionary.""" + """An image view; a class, not a namespace, so that it can key the follower dictionary.""" def __init__(self, source, camera=None): self.cfg, self.camera = SimpleNamespace(source=source), camera @@ -62,14 +65,32 @@ def set_camera(pos, pitch, yaw): viz._viewer = SimpleNamespace(camera=camera, set_camera=set_camera) viz._sim = SimpleNamespace(get_physics_step_count=lambda: 10, get_physics_dt=lambda: 0.1) viz._image_views = list(views) - viz.rtx_rendering, viz._perspective_pose = False, None + viz._followers = {view: CameraFollower(view.cfg.source, _Scene()) for view in views if viz._is_tracking_view(view)} + viz.rtx_rendering, viz._rtx_pose_view, viz._perspective_pose = False, None, None return viz -def test_a_lone_free_view_is_called_perspective(): - viz = _visualizer([_view(PerspectiveCameraCfg())]) +def test_a_lone_free_view_is_called_perspective_and_a_task_view_the_tracking_camera(): + free, task = _view(PerspectiveCameraCfg()), _view(TrackingCameraCfg(env_index=0, eye=(2.0, 0.0, 1.0))) + viz = _visualizer([free, task]) + + assert viz._view_labels([0, 1]) == ["Perspective (interactive)", "Tracking Camera (fixed to env)"] + assert [viz._is_tracking_view(view) for view in viz._image_views] == [False, True] + + +def test_tracking_cameras_are_numbered_only_when_several_share_a_name(): + views = [ + _view(PerspectiveCameraCfg()), + _view(TrackingCameraCfg(env_index=0)), + _view(TrackingCameraCfg(env_index=1)), + ] + viz = _visualizer(views) - assert viz._view_labels([0]) == ["Perspective"] + assert viz._view_labels([0, 1, 2]) == [ + "Perspective (interactive)", + "Tracking Camera 1 (fixed to env)", + "Tracking Camera 2 (fixed to env)", + ] def test_scene_cameras_are_named_by_their_prim_without_the_environment_pattern(): @@ -77,22 +98,22 @@ def test_scene_cameras_are_named_by_their_prim_without_the_environment_pattern() sensor = _View("/World/envs/env_[^/]+/Robot/wrist_camera", camera=camera) viz = _visualizer([_view(PerspectiveCameraCfg()), sensor]) - assert viz._view_labels([0, 1]) == ["Perspective", "wrist_camera (RGB sensor)"] + assert viz._view_labels([0, 1]) == ["Perspective (interactive)", "wrist_camera (RGB sensor)"] -def test_the_camera_list_puts_perspective_first_then_sensors(): +def test_the_camera_list_puts_perspective_first_then_tracking_cameras_then_sensors(): sensor = _View("/World/envs/env_[^/]+/Camera", camera=object()) - free = _view(PerspectiveCameraCfg()) - viz = _visualizer([sensor, free]) + tracking, free = _view(TrackingCameraCfg(env_index=0)), _view(PerspectiveCameraCfg()) + viz = _visualizer([sensor, tracking, free]) - order = sorted(range(2), key=lambda i: viz._source_rank(viz._image_views[i])) + order = sorted(range(3), key=lambda i: viz._source_rank(viz._image_views[i])) - assert order == [1, 0] + assert order == [2, 1, 0] def test_the_free_perspective_pose_is_kept_while_another_source_is_shown(): - free = _view(PerspectiveCameraCfg()) - viz = _visualizer([free]) + free, task = _view(PerspectiveCameraCfg()), _view(TrackingCameraCfg(env_index=0)) + viz = _visualizer([free, task]) viz._focal_length_to_vertical_fov_degrees = lambda focal=None: 40.0 viz.current_image_view = free viz._viewer.camera.fov = 0.0 @@ -100,13 +121,43 @@ def test_the_free_perspective_pose_is_kept_while_another_source_is_shown(): camera.pos, camera.pitch, camera.yaw = (1.0, 2.0, 3.0), -10.0, 45.0 viz._remember_perspective_pose() - camera.pos, camera.pitch, camera.yaw = (9.0, 9.0, 9.0), 0.0, 0.0 # A sensor moved it. + camera.pos, camera.pitch, camera.yaw = (9.0, 9.0, 9.0), 0.0, 0.0 # A Tracking Camera or sensor moved it. viz.cfg.focal_length = 50.0 assert viz._restore_perspective_pose() assert (tuple(camera.pos), camera.pitch, camera.yaw, viz.cfg.focal_length) == ((1.0, 2.0, 3.0), -10.0, 45.0, 12.0) +def test_resetting_the_tracking_camera_works_while_the_rtx_view_is_current(): + view = _view(TrackingCameraCfg(env_index=0, eye=(2.0, 0.0, 1.0), lookat=(0.0, 0.0, 0.5), focal_length=24.0)) + rtx = _View("/World/viewer_camera_0_rtx", camera=object()) + viz = _visualizer([view]) + cfg = view.cfg.source + viz._tracking_defaults = { + view: { + "eye": cfg.eye, + "lookat": cfg.lookat, + "focal_length": cfg.focal_length, + "track_path": cfg.track_path, + "follow_heading": cfg.follow_heading, + "heading_smoothing_time_constant": cfg.heading_smoothing_time_constant, + "env": 0, + } + } + viz.current_image_view, viz.rtx_rendering, viz._rtx_pose_view = ( + rtx, + True, + view, + ) # RTX is showing the Tracking Camera. + viz._tracking_error = "" + + follower = viz._followers[view] + follower.cfg.eye = (9.0, 9.0, 9.0) # an edit in the window, made on the follower's own copy + assert viz._reset_tracking_camera(follower) + + assert follower.cfg.eye == (2.0, 0.0, 1.0) and cfg.eye == (2.0, 0.0, 1.0) + + def test_a_perspective_that_was_never_left_has_no_pose_to_restore(): viz = _visualizer([_view(PerspectiveCameraCfg())]) @@ -134,7 +185,9 @@ def test_sensor_ui_callbacks_draw_in_the_camera_sensor_section_with_the_selected def _rtx_view(): camera = SimpleNamespace(cfg=SimpleNamespace(prim_path="/World/viewer_camera_0", renderer_cfg="ovrtx")) - return _View("/World/viewer_camera_0", camera=camera) + view = _View("/World/viewer_camera_0", camera=camera) + view.invalidate = lambda: None + return view def _switchable(views): @@ -179,6 +232,25 @@ def test_choosing_the_perspective_while_rtx_is_shown_keeps_the_rtx_view(): assert viz.current_image_view is rtx and viz.rtx_rendering +def test_picking_a_sensor_while_rtx_is_on_returns_the_rtx_camera_to_rendering_on_demand(): + rtx = _rtx_view() + sensor = _View("/World/sensor", camera=SimpleNamespace(cfg=SimpleNamespace(prim_path="/World/sensor"))) + sensor.invalidate = lambda: None + viz = _switchable([_view(PerspectiveCameraCfg()), rtx, sensor]) + viz._viewer.picking = None + viz._viewer.camera.get_view_matrix = lambda: np.eye(4) + viz._release_rtx_scene = lambda: None + viz._place_scene_camera_at_viewer = lambda camera: None + viz._pose_started = False + viz.current_image_view = rtx + rtx.camera.cfg.render_on_demand = False # the shared render while RTX is shown + + NewtonGLVisualizer._select_camera(viz, 2, keep_pose=True) + + assert rtx.camera.cfg.render_on_demand is True + assert viz.current_image_view is sensor + + def test_the_rtx_switch_waits_a_frame_so_the_message_is_shown_first(): viz = _switchable([_view(PerspectiveCameraCfg()), _rtx_view()]) viz._rtx_switch = "requested" @@ -326,3 +398,159 @@ def test_a_free_view_records_the_rtx_window_instead_of_an_opengl_render(): assert viz._capture_view(free, None) == "window frame" assert viz.current_image_view is rtx + + +@pytest.mark.parametrize("borrowed", [True, False]) +def test_capturing_a_view_the_window_does_not_show_stays_out_of_the_hud_recording(borrowed): + free = _view(PerspectiveCameraCfg()) + free.invalidate = lambda: None + viz = _switchable([free, _rtx_view()]) + viz._rtx_appearance, viz._sim_time = None, 0.0 + viz._pending_mesh_submissions = {} + viz._last_render_step = 0 + viz._sim.get_physics_step_count = lambda: 0 + viz._capturing_another_view = borrowed # a borrowed capture renders the frame through the same path + captured = [] + viz._recording = SimpleNamespace(capture=lambda paused: captured.append(paused)) + viz._viewer = SimpleNamespace( + begin_frame=lambda t: None, end_frame=lambda: None, is_paused=lambda: True, is_running=lambda: True + ) + + NewtonGLVisualizer._render_frame(viz) + + assert captured == ([] if borrowed else [True]) # only a frame the window itself shows reaches the recording + + +def test_a_capture_marks_the_borrowed_view_while_it_renders(): + shown, other = _view(TrackingCameraCfg(env_index=0)), _view(TrackingCameraCfg(env_index=1)) + viz = _switchable([shown, other]) + viz._viewer.camera.pos = Vec3(0.0, 0.0, 0.0) + viz._viewer.camera.pitch = viz._viewer.camera.yaw = 0.0 + viz._viewer.set_camera = lambda *args: None + viz._viewer.world_offsets = None + seen = [] + viz._capture_frame = lambda output: seen.append(viz._capturing_another_view) + + viz._capture_view(other, None) + + assert seen == [True] and not viz._capturing_another_view + + +def test_the_camera_speed_slider_sets_the_free_cameras_keyboard_speed(): + free, tracking = _view(PerspectiveCameraCfg()), _view(TrackingCameraCfg(env_index=0)) + viz = _switchable([free, tracking]) + viz._viewer = SimpleNamespace(_camera_speed=5.0, camera_speed=5.0, camera_speed_boost=2.0) + viz._pose_source_view = lambda: viz.current_image_view + imgui = SimpleNamespace( + slider_float=lambda *args: (True, 12.0), + SliderFlags_=SimpleNamespace(logarithmic=0), + is_item_hovered=lambda *args: False, + HoveredFlags_=SimpleNamespace(allow_when_disabled=0), + ) + viz.current_image_view = tracking + viz._draw_camera_speed(imgui) + assert viz._viewer.camera_speed == 5.0 # a tracking camera does not move with the keys + + viz.current_image_view = free + viz._draw_camera_speed(imgui) + assert viz._viewer.camera_speed == 12.0 and viz._viewer.camera_speed_boost == 12.0 + + +def test_a_window_with_only_the_rtx_camera_draws_its_camera_controls(): + from unittest.mock import Mock + + viz = _switchable([_rtx_view()]) + viz.current_image_view = viz._image_views[0] + viz._capturing_another_view = False + viz._draw_appearance = viz._draw_navigation_controls = lambda imgui: None + viz._draw_camera_info = viz._draw_window_options = lambda imgui: None + imgui = Mock() + imgui.is_item_hovered.return_value = False + imgui.radio_button.return_value = False # disabled radio buttons are never clicked + + viz._draw_streaming_view_controls(imgui) # no other source to list: must not raise + + imgui.combo.assert_not_called() + imgui.begin_disabled.assert_called_once() + + +def test_camera_view_controls_are_grouped_under_headers_in_order(): + from unittest.mock import Mock + + viz = _switchable([_view(PerspectiveCameraCfg()), _rtx_view()]) + viz._capturing_another_view = False + order = [] + viz._draw_appearance = lambda imgui: order.append("appearance") + viz._draw_focal_length = lambda imgui: order.append("focal length") + viz._draw_camera_speed = lambda imgui: order.append("camera speed") + imgui = Mock() + imgui.is_item_hovered.return_value = False + imgui.combo.side_effect = lambda *args: order.append("camera source") or (False, 0) + imgui.radio_button.side_effect = lambda *args: order.append("renderer") or False + imgui.separator_text.side_effect = lambda text: order.append(text) + imgui.checkbox.side_effect = lambda label, value: (False, value) + viz._viewer.vsync = False + camera = viz._viewer.camera + camera.pos, camera.pitch, camera.yaw, camera.fov = (1.0, 2.0, 3.0), 0.0, 0.0, 40.0 + + viz._draw_streaming_view_controls(imgui) + + assert order == [ + "Camera Source", + "camera source", + "Rendering", + "renderer", + "renderer", + "appearance", + "Camera Settings", + "focal length", + "camera speed", + "Camera Data", + "Window", + ] + imgui.text_disabled.assert_not_called() # the camera data is plain text, not greyed out + assert [call.args[0].split(":")[0] for call in imgui.text.call_args_list] == [ + "Renderer", + "Position", + "Rotation", + "FOV", + ] + + +def test_the_vsync_checkbox_sets_the_window_vsync(): + from unittest.mock import Mock + + viz = _switchable([_view(PerspectiveCameraCfg()), _rtx_view()]) + viz._viewer.vsync = False + imgui = Mock() + imgui.checkbox.return_value = (True, True) + + viz._draw_window_options(imgui) + + assert viz._viewer.vsync is True + + +def test_the_docs_link_does_not_block_the_render_thread(monkeypatch): + import threading + + from isaaclab_visualizers.newton import newton_visualizer + + release, started = threading.Event(), threading.Event() + monkeypatch.setattr(newton_visualizer.webbrowser, "open", lambda url: (started.set(), release.wait(5))) + + newton_visualizer._open_in_browser("https://example.com") # returns while the browser call is still blocked + + assert started.wait(5) + release.set() + + +def test_a_window_that_forbids_the_rtx_camera_takes_no_viewer_camera(): + from isaaclab_visualizers.newton.newton_visualizer import NewtonGLVisualizer + + viz = NewtonGLVisualizer.__new__(NewtonGLVisualizer) + viz._rtx_camera_path = None + + viz.cfg = SimpleNamespace(backend=SimpleNamespace(rtx_camera=None)) + assert viz._is_viewer_camera("/World/viewer_camera_0") + viz.cfg = SimpleNamespace(backend=SimpleNamespace(rtx_camera=False)) + assert not viz._is_viewer_camera("/World/viewer_camera_0") diff --git a/source/isaaclab_visualizers/test/test_newton_tracking_cameras.py b/source/isaaclab_visualizers/test/test_newton_tracking_cameras.py new file mode 100644 index 000000000000..6a2994b4fa30 --- /dev/null +++ b/source/isaaclab_visualizers/test/test_newton_tracking_cameras.py @@ -0,0 +1,270 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for Newton viewer perspective views that follow an asset or frame an environment.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +import torch +import warp as wp + +pytest.importorskip("newton") +from isaaclab_visualizers.newton.newton_visualizer import NewtonGLVisualizer, NewtonVisualizerBase +from pyglet.math import Vec3 + +from isaaclab.visualizers import PerspectiveCameraCfg, TrackingCameraCfg +from isaaclab.visualizers.camera_follower import CameraFollower + +pytestmark = pytest.mark.kitless + + +class _Camera: + """The viewer camera: a position, a look-at target stored as angles, and a field of view.""" + + def __init__(self): + self.pos, self.pitch, self.yaw, self.fov = Vec3(1.0, 1.0, 1.0), 0.1, 0.2, 40.0 + self.target = None + + def look_at(self, target): + self.target = tuple(target) + + +class _Scene: + num_envs = 2 + env_origins = torch.tensor([[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]]) + articulations, rigid_objects = {"robot": None}, {} + + def __getitem__(self, name): + return SimpleNamespace(is_initialized=False) + + +def _visualizer(views) -> NewtonVisualizerBase: + viz = NewtonVisualizerBase.__new__(NewtonVisualizerBase) + viz.cfg = SimpleNamespace(focal_length=12.0, eye=(4.0, -4.0, 3.0), lookat=(0.0, 0.0, 0.0)) + viz._followers, viz._last_render_step = {}, 5 + viz._tracking_defaults, viz._tracking_error = {}, "" + camera = _Camera() + + def set_camera(pos, pitch, yaw): + camera.pos, camera.pitch, camera.yaw = pos, pitch, yaw + + viz._viewer = SimpleNamespace(camera=camera, set_camera=set_camera, is_paused=lambda: False, world_offsets=None) + viz._sim = SimpleNamespace( + get_scene_data_provider=lambda: SimpleNamespace(get_interactive_scene=lambda: _Scene()), + get_physics_step_count=lambda: 10, + get_physics_dt=lambda: 0.1, + ) + viz._image_views = list(views) + viz._followers = { + view: CameraFollower(view.cfg.source, _Scene()) + for view in views + if isinstance(view.cfg.source, TrackingCameraCfg) + } + viz.current_image_view = viz._image_views[0] + return viz + + +class _View: + """A perspective image view: hashable like the real one, with no scene camera.""" + + camera, render = None, None + + def __init__(self, cfg: PerspectiveCameraCfg): + self.cfg = SimpleNamespace(source=cfg) + self.frame = SimpleNamespace(data=None, timestamp=-1) + + +def _view(cfg: PerspectiveCameraCfg) -> _View: + return _View(cfg) + + +def test_a_tracking_camera_points_the_viewer_without_changing_the_configured_pose(): + task = _view(TrackingCameraCfg(env_index=1, eye=(1.0, 2.0, 3.0), lookat=(0.0, 0.0, 1.0), focal_length=24.0)) + viz = _visualizer([task]) + assert viz._apply_view_pose(task) + camera = viz._viewer.camera + assert (camera.pos.x, camera.pos.y, camera.pos.z) == (11.0, 2.0, 3.0) + assert camera.target == (10.0, 0.0, 1.0) + assert camera.fov == pytest.approx(35.34, abs=0.05) # 2 * atan(15.2908 / (2 * 24)) for USD's default aperture + assert viz.cfg.eye == (4.0, -4.0, 3.0) and viz.cfg.focal_length == 12.0 + + +def test_capturing_another_view_hands_the_viewer_camera_back(): + free, task = _view(PerspectiveCameraCfg()), _view(TrackingCameraCfg(env_index=1, eye=(1.0, 2.0, 3.0))) + viz = _visualizer([free, task]) + seen = {} + + def capture(output): + # the window's own view is borrowed for the capture, and the camera moves while it renders + seen["view"] = viz.current_image_view + viz._viewer.camera.pos, viz._viewer.camera.fov = Vec3(11.0, 2.0, 3.0), 20.0 + return "frame" + + viz._capture_frame = capture + assert viz._capture_view(task, None) == "frame" + assert seen["view"] is task + camera = viz._viewer.camera + assert (camera.pos.x, camera.pos.y, camera.pos.z, camera.fov) == (1.0, 1.0, 1.0, 40.0) + assert viz.current_image_view is free and viz._last_render_step == -1 + + +def test_the_tracking_camera_recording_picks_the_first_tied_view(): + free = _view(PerspectiveCameraCfg()) + first, second = _view(TrackingCameraCfg(track_path="robot")), _view(TrackingCameraCfg(env_index=1)) + viz = _visualizer([free, first, second]) + viz._sim.get_physics_step_count = lambda: 3 + first.read_rgb, second.read_rgb = (lambda step: ("first", step)), (lambda step: ("second", step)) + assert viz.render_tracking_rgb_array() == ("first", 3) + + +def test_the_tracking_camera_recording_reports_a_visualizer_without_one(): + with pytest.raises(RuntimeError, match="declares no tracking camera"): + _visualizer([_view(PerspectiveCameraCfg())]).render_tracking_rgb_array() + + +def test_the_selector_names_each_camera_with_a_short_descriptor(): + camera = SimpleNamespace(cfg=SimpleNamespace(data_types=["rgba"])) + sensor = SimpleNamespace(camera=camera, cfg=SimpleNamespace(source="/World/envs/env_0/cam")) + viz = _visualizer([_view(PerspectiveCameraCfg()), _view(TrackingCameraCfg(env_index=1))]) + viz._image_views.append(sensor) + assert viz._view_labels() == ["Perspective (interactive)", "Tracking Camera (fixed to env)", "cam (RGB sensor)"] + + viz = _visualizer([_view(TrackingCameraCfg(env_index=0)), _view(TrackingCameraCfg(track_path="robot"))]) + assert viz._view_labels() == ["Tracking Camera 1 (fixed to env)", "Tracking Camera 2 (follows robot)"] + + # the label follows what the window made the camera follow, not what the task declared + viz = _visualizer([_view(TrackingCameraCfg(env_index=0, track_path="robot"))]) + viz._followers[viz._image_views[0]].set_track_path(None) + assert viz._view_labels() == ["Tracking Camera (fixed to env)"] + + +def test_resetting_the_tracking_camera_restores_what_the_task_declared(): + task = _view(TrackingCameraCfg(env_index=0, eye=(1.0, 0.0, 0.0), track_path="robot", follow_heading=True)) + viz = _visualizer([task]) + follower = viz._followers[task] + cfg = follower.cfg # the follower edits its own copy, not the task's camera + viz._remember_tracking_defaults(task, follower) + cfg.eye, cfg.follow_heading = (5.0, 5.0, 5.0), False + follower.set_env(1) + follower.set_track_path(None) + + assert viz._reset_tracking_camera(follower) + assert (cfg.eye, cfg.track_path, cfg.follow_heading, follower.env) == ((1.0, 0.0, 0.0), "robot", True, 0) + + +def test_an_unknown_asset_is_reported_and_the_camera_keeps_following_its_target(): + task = _view(TrackingCameraCfg(env_index=0, track_path="robot")) + viz = _visualizer([task]) + viz._tracking_error = "" + follower = viz._followers[task] + + class _Scene2(_Scene): + def __getitem__(self, name): + return super().__getitem__(name) + + follower._scene = _Scene2() + assert not viz._set_tracking_path(follower, "ghost") + assert "unknown scene asset" in viz._tracking_error and task.cfg.source.track_path == "robot" + assert viz._set_tracking_path(follower, "robot") and viz._tracking_error == "" + + +def test_a_visualizer_reports_whether_it_declares_a_tracking_view(): + free, task = _view(PerspectiveCameraCfg()), _view(TrackingCameraCfg(env_index=1)) + assert not _visualizer([free]).has_tracking_view + assert _visualizer([free, task]).has_tracking_view + + +def test_the_tracking_camera_recording_keeps_its_last_frame_while_rendering_is_paused(): + tracking = _view(TrackingCameraCfg(track_path="robot")) + viz = _visualizer([_view(PerspectiveCameraCfg()), tracking]) + viz._sim.get_physics_step_count = lambda: 9 + viz._viewer.is_paused = lambda: True + tracking.frame = SimpleNamespace(data=object(), timestamp=4) + tracking.read_rgb = lambda step: step + assert viz.render_tracking_rgb_array() == 4 + + +def test_a_tracking_camera_follows_the_world_offset_the_viewer_draws_its_environment_at(): + task = _view(TrackingCameraCfg(env_index=1, eye=(1.0, 2.0, 3.0), lookat=(0.0, 0.0, 1.0))) + viz = _visualizer([task]) + viz._viewer.world_offsets = wp.array([[0.0, 0.0, 0.0], [5.0, 0.0, 0.0]], dtype=wp.vec3) + assert viz._apply_view_pose(task) + camera = viz._viewer.camera + assert (camera.pos.x, camera.pos.y, camera.pos.z) == (16.0, 2.0, 3.0) + + +def test_a_tracking_camera_ignores_the_world_offset_while_the_window_shows_rtx(): + task = _view(TrackingCameraCfg(env_index=1, eye=(1.0, 2.0, 3.0), lookat=(0.0, 0.0, 1.0))) + viz = _visualizer([task]) + viz._viewer.world_offsets = wp.array([[0.0, 0.0, 0.0], [5.0, 0.0, 0.0]], dtype=wp.vec3) + viz.rtx_rendering = True # OVRTX draws the environments where the scene has them + assert viz._apply_view_pose(task) + assert viz._viewer.camera.pos.x == 11.0 + + +def test_the_tracking_cameras_environment_is_drawn_even_beyond_the_visible_count(): + task = _view(TrackingCameraCfg(env_index=0)) + viz = _visualizer([task]) + follower = viz._followers[task] + follower._scene = SimpleNamespace(num_envs=8, env_origins=torch.zeros(8, 3)) + follower.set_env(3) + glviz = NewtonGLVisualizer.__new__(NewtonGLVisualizer) + glviz.__dict__.update(viz.__dict__) + glviz._cfg_visible_env_ids, glviz._num_envs, glviz._track_env_only = None, 8, False + + glviz._visible_env_count = 2 + assert glviz._select_visible_env_ids() == [0, 3] # the camera's environment takes the last counted place + glviz._visible_env_count = 4 + assert glviz._select_visible_env_ids() == [0, 1, 2, 3] # already among the first ones: nothing changes + follower.set_env(7) + glviz._visible_env_count = 1 + assert glviz._select_visible_env_ids() == [7] + glviz._followers.clear() # no Tracking Camera shown: the plain first environments + assert glviz._select_visible_env_ids() == [0] + + +def test_a_focal_length_edit_stays_on_the_follower_and_reset_restores_it(): + task = _view(TrackingCameraCfg(env_index=0, focal_length=24.0)) + viz = _visualizer([task]) + follower = viz._followers[task] + viz._remember_tracking_defaults(task, follower) + viz.current_image_view = task + viz.rtx_rendering = False + task.invalidate = lambda: None + imgui = Mock() + imgui.slider_float.return_value = (True, 40.0) + imgui.is_item_hovered.return_value = False + viz._draw_focal_length(imgui) + + assert follower.cfg.focal_length == 40.0 and task.cfg.source.focal_length == 24.0 + assert viz._reset_tracking_camera(follower) and follower.cfg.focal_length == 24.0 + + +def test_a_body_that_turns_out_ambiguous_later_falls_back_to_the_asset_root_instead_of_raising(): + task = _view(TrackingCameraCfg(env_index=0, track_path="robot/base")) + viz = _visualizer([task]) + follower = viz._followers[task] + viz._tracking_error = "" + + def bad_pose(time): + raise ValueError("track_path must match exactly one body: 'robot/base'.") + + follower.pose = bad_pose + assert viz._apply_view_pose(task) is False + assert follower.cfg.track_path == "robot" and "root instead" in viz._tracking_error + + +def test_a_recorded_tracking_camera_in_a_hidden_environment_is_reported_once(caplog): + task = _view(TrackingCameraCfg(env_index=1)) + viz = _visualizer([task]) + viz._env_ids = [0] + with caplog.at_level("WARNING"): + viz._warn_if_hidden(task) + viz._warn_if_hidden(task) + assert sum("empty scene" in r.message for r in caplog.records) == 1 diff --git a/source/isaaclab_visualizers/test/test_newton_visualizer_viewer_release.py b/source/isaaclab_visualizers/test/test_newton_visualizer_viewer_release.py index 9b8ef5c17982..e12f5a8f33eb 100644 --- a/source/isaaclab_visualizers/test/test_newton_visualizer_viewer_release.py +++ b/source/isaaclab_visualizers/test/test_newton_visualizer_viewer_release.py @@ -94,7 +94,7 @@ def test_close_unbinds_the_perspective_views_it_rendered(): def test_window_controls_do_not_need_a_capture_to_have_run(): """A fresh visualizer is not borrowing a view, so its window controls draw before the first capture.""" - assert NewtonGLVisualizer(VisualizerCfg(backend=NewtonGLBackendCfg()))._borrowing_view is False + assert NewtonGLVisualizer(VisualizerCfg(backend=NewtonGLBackendCfg()))._capturing_another_view is False def test_window_without_the_rtx_camera_shows_a_disabled_renderer_toggle():