From 0ee0b67964cc5f9c776ac08a27b64cc53f2317b0 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:27:32 -0800 Subject: [PATCH 01/81] Add isaaclab_fovi foveated camera sensors Add the isaaclab_fovi package with foveated camera sensors for the Newton and RTX renderers, their geometry helpers, tests and a render example. Register the package in the workspace and add the fovi extra. --- pyproject.toml | 7 + .../changelog.d/isaaclab-fovi.added.rst | 2 + .../changelog.d/isaaclab-fovi.minor | 0 source/isaaclab_fovi/docs/CHANGELOG.rst | 4 + source/isaaclab_fovi/docs/square_foveated.md | 42 ++ .../isaaclab_fovi/examples/compare_outputs.py | 36 + .../isaaclab_fovi/examples/render_foveated.py | 172 +++++ .../isaaclab_fovi/isaaclab_fovi/__init__.py | 11 + .../isaaclab_fovi/sensors/__init__.py | 77 +++ .../sensors/active_camera_geometry.py | 297 ++++++++ .../sensors/calibrated_camera.py | 162 +++++ .../sensors/calibrated_geometry.py | 176 +++++ .../sensors/dense_calibrated_geometry.py | 67 ++ .../sensors/fixed_software_fov.py | 247 +++++++ .../sensors/foveated_newton_tiled_camera.py | 595 ++++++++++++++++ .../isaaclab_fovi/sensors/foveated_rays.py | 156 +++++ .../sensors/foveated_rtx_tiled_camera.py | 647 ++++++++++++++++++ .../sensors/foveated_tiled_camera_cfg.py | 206 ++++++ .../sensors/generalized_projection.py | 424 ++++++++++++ .../isaaclab_fovi/sensors/native_grid.py | 219 ++++++ .../isaaclab_fovi/sensors/pooling.py | 154 +++++ .../isaaclab_fovi/sensors/virtual_gaze.py | 126 ++++ source/isaaclab_fovi/pyproject.toml | 39 ++ source/isaaclab_fovi/test/_check_imports.py | 52 ++ .../test/calibrated_camera_render_smoke.py | 458 +++++++++++++ .../test/test_backend_dispatch.py | 36 + .../test/test_calibrated_camera_batch.py | 30 + .../test/test_calibrated_camera_geometry.py | 230 +++++++ .../test/test_calibrated_gaze_fusion.py | 49 ++ .../test/test_dense_foveated_lens_parity.py | 39 ++ .../test/test_hybrid_geometry.py | 313 +++++++++ source/isaaclab_fovi/test/test_imports.py | 26 + source/isaaclab_fovi/test/test_lens_schema.py | 34 + source/isaaclab_fovi/test/test_native_grid.py | 154 +++++ .../isaaclab_fovi/test/test_newton_buffers.py | 138 ++++ source/isaaclab_fovi/test/test_pooling.py | 161 +++++ source/isaaclab_fovi/test/test_rays.py | 63 ++ source/isaaclab_fovi/test/test_rtx_layout.py | 29 + .../test/test_spherical_geometry.py | 294 ++++++++ .../test/test_square_native_grid.py | 133 ++++ 40 files changed, 6105 insertions(+) create mode 100644 source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst create mode 100644 source/isaaclab_fovi/changelog.d/isaaclab-fovi.minor create mode 100644 source/isaaclab_fovi/docs/CHANGELOG.rst create mode 100644 source/isaaclab_fovi/docs/square_foveated.md create mode 100644 source/isaaclab_fovi/examples/compare_outputs.py create mode 100644 source/isaaclab_fovi/examples/render_foveated.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/__init__.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/active_camera_geometry.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_camera.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/dense_calibrated_geometry.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/fixed_software_fov.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py create mode 100644 source/isaaclab_fovi/pyproject.toml create mode 100644 source/isaaclab_fovi/test/_check_imports.py create mode 100644 source/isaaclab_fovi/test/calibrated_camera_render_smoke.py create mode 100644 source/isaaclab_fovi/test/test_backend_dispatch.py create mode 100644 source/isaaclab_fovi/test/test_calibrated_camera_batch.py create mode 100644 source/isaaclab_fovi/test/test_calibrated_camera_geometry.py create mode 100644 source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py create mode 100644 source/isaaclab_fovi/test/test_dense_foveated_lens_parity.py create mode 100644 source/isaaclab_fovi/test/test_hybrid_geometry.py create mode 100644 source/isaaclab_fovi/test/test_imports.py create mode 100644 source/isaaclab_fovi/test/test_lens_schema.py create mode 100644 source/isaaclab_fovi/test/test_native_grid.py create mode 100644 source/isaaclab_fovi/test/test_newton_buffers.py create mode 100644 source/isaaclab_fovi/test/test_pooling.py create mode 100644 source/isaaclab_fovi/test/test_rays.py create mode 100644 source/isaaclab_fovi/test/test_rtx_layout.py create mode 100644 source/isaaclab_fovi/test/test_spherical_geometry.py create mode 100644 source/isaaclab_fovi/test/test_square_native_grid.py diff --git a/pyproject.toml b/pyproject.toml index 8f20b74dcc18..a6b6aba316e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -227,6 +227,12 @@ rlinf = [ leapp = [ "leapp==0.8.1", ] +# Foveated camera sensors. OpenEXR writes the RTX lens lookup textures. +fovi = [ + "isaaclab-fovi", + "fovi>=2.6", + "OpenEXR>=3", +] all = [ "isaaclab-dev[sb3,skrl,rl-games,rsl-rl,viser,rerun,ov]", ] @@ -467,6 +473,7 @@ isaaclab = { path = "source/isaaclab", editable = true } "isaaclab-assets" = { path = "source/isaaclab_assets", editable = true } "isaaclab-contrib" = { path = "source/isaaclab_contrib", editable = true } "isaaclab-experimental" = { path = "source/isaaclab_experimental", editable = true } +"isaaclab-fovi" = { path = "source/isaaclab_fovi", editable = true } "isaaclab-mimic" = { path = "source/isaaclab_mimic", editable = true } "isaaclab-newton" = { path = "source/isaaclab_newton", editable = true } "isaaclab-ov" = { path = "source/isaaclab_ov", editable = true } diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst new file mode 100644 index 000000000000..5ca30f7c3d96 --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst @@ -0,0 +1,2 @@ +* Introduced ``isaaclab_fovi`` and the ``fovi`` installation extra, providing a + foveated camera sensor for the Newton and RTX renderers. diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.minor b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_fovi/docs/CHANGELOG.rst b/source/isaaclab_fovi/docs/CHANGELOG.rst new file mode 100644 index 000000000000..9e3a308a2125 --- /dev/null +++ b/source/isaaclab_fovi/docs/CHANGELOG.rst @@ -0,0 +1,4 @@ +Changelog +========= + +.. towncrier release notes start diff --git a/source/isaaclab_fovi/docs/square_foveated.md b/source/isaaclab_fovi/docs/square_foveated.md new file mode 100644 index 000000000000..af7f029bf0f7 --- /dev/null +++ b/source/isaaclab_fovi/docs/square_foveated.md @@ -0,0 +1,42 @@ +# Square-foveated rendering + +Both RTX and Newton foveated cameras accept this configuration: + +```python +FoveatedTiledCameraCfg( + prim_path="/World/Camera", + foveated_style="warped_cartesian_as_grid", + radius_norm=float("inf"), + fov_type="square", + ndc_layout="native_grid", + foveated_res=64, + cmf_a=0.036021, +) +``` + +Fovi owns the concentric-square mapping and its analytic inverse. Direction +textures, exit textures, virtual gaze, and software retinalization use that +geometry. The public image is upright `(batch, height, width, channels)`; +RGB, depth, and segmentation retain their existing dtypes and buffer lifetimes. +There are no cells masked by the sensor footprint. Camera visibility and +out-of-frame software sampling can still invalidate pixels. + +The mode works with the existing planar and spherical chart conventions and +pinhole/equidistant ray projections. It retains a two-dimensional native +topology; the square footprint refers to the visual chart used by the projection. +The diagonal derivative seams remain relevant when assessing temporal filtering. + +Configure policy image preprocessing with the same field geometry, radius norm, +and sampling resolution as the camera. Checkpoints must use the sampling +configuration they were trained with. + +A bounded renderer example is: + +```bash +uv run --no-sync python source/isaaclab_fovi/examples/render_foveated.py \ + --backend rtx --style warped_cartesian_as_grid --radius-norm inf --fov-type square \ + --resolution 64 --steps 8 --visualizer none --device cuda:0 --output /tmp/square-foveated.pt +``` + +Install the pinned Fovi dependency through the repository's `fovi` extra. +The implementation uses Fovi's upright-grid and analytic native-mapping APIs. diff --git a/source/isaaclab_fovi/examples/compare_outputs.py b/source/isaaclab_fovi/examples/compare_outputs.py new file mode 100644 index 000000000000..015b6956fe51 --- /dev/null +++ b/source/isaaclab_fovi/examples/compare_outputs.py @@ -0,0 +1,36 @@ +# 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 + +"""Compare RGB snapshots saved by render_foveated.py across installations.""" + +import argparse +import statistics + +import torch + + +def main() -> None: + """Report image differences and observed frame times without setting thresholds.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("reference") + parser.add_argument("candidate") + args = parser.parse_args() + reference = torch.load(args.reference, map_location="cpu", weights_only=True) + candidate = torch.load(args.candidate, map_location="cpu", weights_only=True) + if reference["rgb"].shape != candidate["rgb"].shape: + raise ValueError("RGB shapes differ") + if reference["rgb"].dtype != candidate["rgb"].dtype: + raise ValueError("RGB dtypes differ") + torch.testing.assert_close(reference["sampling_coordinates"], candidate["sampling_coordinates"]) + difference = (reference["rgb"].float() - candidate["rgb"].float()).abs() + print(f"RGB absolute error: mean={difference.mean().item()}, max={difference.max().item()}") + for label, snapshot in (("reference", reference), ("candidate", candidate)): + durations = snapshot["frame_seconds"] + if durations: + print(f"{label} median warm frame seconds: {statistics.median(durations)}") + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py new file mode 100644 index 000000000000..a73dd9cbaa72 --- /dev/null +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -0,0 +1,172 @@ +# 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 + +"""Render a small scene with a foveated camera. + +Run with ``--backend newton`` or ``--backend rtx``; add ``--pool`` for +photoreceptor-to-output pooling. ``--steps`` bounds the simulation run. +With ``--virtual-gaze`` the camera stays fixed and the fixation moves inside +its calibrated field of view. +""" + +from __future__ import annotations + +import argparse +import time +import traceback +from pathlib import Path + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--backend", choices=("newton", "rtx"), required=True) +parser.add_argument("--pool", action="store_true") +parser.add_argument("--field-geometry", choices=("planar", "spherical"), default="planar") +parser.add_argument( + "--style", + choices=("isotropic", "warped_cartesian_as_grid"), + default="isotropic", +) +parser.add_argument("--fov-type", choices=("circular", "square", "wang"), default="circular") +parser.add_argument("--radius-norm", type=float, choices=(2.0, float("inf")), default=2.0) +parser.add_argument( + "--virtual-gaze", + action="store_true", + help="Move the fixation inside the fixed camera's calibrated field of view.", +) +parser.add_argument("--lens", choices=("pinhole", "fisheye"), default="pinhole") +parser.add_argument("--steps", type=int, default=8) +parser.add_argument("--resolution", type=int, default=16) +parser.add_argument("--output", type=Path, help="Save final RGB tensor and warm frame timings.") +AppLauncher.add_app_launcher_args(parser) +args = parser.parse_args() +if args.steps <= 0: + parser.error("--steps must be positive") +if args.resolution <= 0: + parser.error("--resolution must be positive") +if args.virtual_gaze and args.field_geometry != "spherical": + parser.error("--virtual-gaze requires --field-geometry spherical") +args.enable_cameras = True +launcher = AppLauncher(args) + + +def main() -> None: + """Render RGB of a static cube, optionally moving the fixation.""" + # Isaac Sim plugins must be available before importing simulator-bound types. + import isaaclab.sim as sim_utils + import torch + import warp as wp + from isaaclab.utils.warp import ProxyArray + + from isaaclab_fovi.sensors import FoveatedTiledCamera, FoveatedTiledCameraCfg + + if args.backend == "newton": + from isaaclab_newton.physics.mjwarp_solver_cfg import MJWarpSolverCfg + from isaaclab_newton.physics.newton_manager_cfg import NewtonCfg + from isaaclab_newton.renderers import NewtonWarpRendererCfg + + physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) + renderer = NewtonWarpRendererCfg(render_order="pixel_priority") + elif args.backend == "rtx": + from isaaclab_physx.physics.physx_manager_cfg import PhysxCfg + from isaaclab_physx.renderers import IsaacRtxRendererCfg + + physics = PhysxCfg() + renderer = IsaacRtxRendererCfg() + else: + raise ValueError(f"Unsupported backend: {args.backend}") + + sim_utils.create_new_stage() + sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(device=args.device, physics=physics)) + sim_utils.create_prim("/World/envs", "Xform") + sim_utils.create_prim("/World/envs/env_0", "Xform") + cube = sim_utils.CuboidCfg( + size=(0.5, 0.5, 0.5), + rigid_props=sim_utils.RigidBodyPropertiesCfg(disable_gravity=True), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=False), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.8, 0.2, 0.1)), + ) + cube.func("/World/envs/env_0/Cube", cube, translation=(0.0, 2.0, 0.0)) + light = sim_utils.DistantLightCfg(intensity=2000.0) + light.func("/World/Light", light) + calibration = None + if args.field_geometry == "spherical": + calibration = { + "model": args.lens, + "image_size": (480, 640), + "intrinsics": (550.0, 550.0, 319.5, 239.5), + "distortion": (0.02, -0.003, 0.0, 0.0), + } + cfg = FoveatedTiledCameraCfg( + prim_path="/World/envs/env_.*/Eye", + data_types=["rgb"], + renderer_cfg=renderer, + foveated_res=args.resolution, + foveated_style=args.style, + fov_type=args.fov_type, + radius_norm=args.radius_norm, + ndc_layout="native_grid" if args.style == "warped_cartesian_as_grid" else "cortical_disc", + cmf_a=0.1, + field_geometry=args.field_geometry, + camera_calibration=calibration, + fixed_software_fov=args.virtual_gaze, + software_fov_image_height=480, + software_fov_image_width=640, + retinal_window_reference_side="long", + pool_enabled=args.pool, + pool_res_mult=2.0, + pool_mode="avg", + camera_fov_deg=60.0, + spawn=sim_utils.PinholeCameraCfg(focal_length=24.0, horizontal_aperture=27.713), + # OpenGL camera looking along +Y with +Z up. + offset=FoveatedTiledCameraCfg.OffsetCfg(rot=(0.70710678, 0.0, 0.0, 0.70710678), convention="opengl"), + ) + camera = FoveatedTiledCamera(cfg) + sim.reset() + frame_seconds: list[float] = [] + frames: list[torch.Tensor] = [] + for step in range(args.steps): + if args.virtual_gaze: + fixation = torch.tensor([[0.5, (0.5, 0.58, 0.58, 0.5)[step % 4]]], device=sim.device) + camera.set_calibrated_fixation(fixation) + wp.synchronize_device(sim.device) + start = time.perf_counter() + sim.step() + camera.update(sim.get_physics_dt(), force_recompute=True) + wp.synchronize_device(sim.device) + if step > 0: + frame_seconds.append(time.perf_counter() - start) + frame = camera.data.output["rgb"] + frames.append((frame.torch if isinstance(frame, ProxyArray) else frame).clone()) + rgb = camera.data.output["rgb"] + rgb_tensor = rgb.torch if isinstance(rgb, ProxyArray) else rgb + print( + f"{args.backend}: pooled={args.pool}, RGB shape={tuple(rgb_tensor.shape)}, " + f"dtype={rgb_tensor.dtype}, warm frame seconds={frame_seconds}", + flush=True, + ) + if args.output is not None: + torch.save( + { + "rgb": rgb_tensor.cpu(), + "frames": torch.stack(frames).cpu(), + "sampling_coordinates": camera.sampling_coords.cartesian.cpu(), + "frame_seconds": frame_seconds, + }, + args.output, + ) + sim.stop() + + +if __name__ == "__main__": + try: + main() + except Exception: + # Kit shutdown can terminate before Python prints an uncaught exception. + traceback.print_exc() + raise + finally: + launcher.app.close() diff --git a/source/isaaclab_fovi/isaaclab_fovi/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/__init__.py new file mode 100644 index 000000000000..a351f217fcb2 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/__init__.py @@ -0,0 +1,11 @@ +# 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 + +"""Foveated rendering and binocular active cameras for Isaac Lab. + +Import camera implementations from :mod:`isaaclab_fovi.sensors` after starting +the selected simulator runtime. Geometry and fixation helpers are available +without starting a simulator. +""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py new file mode 100644 index 000000000000..188255bd927f --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py @@ -0,0 +1,77 @@ +# 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 + +"""Camera sensors and simulator-independent projection helpers. + +Backend classes are imported on demand so Newton and pure geometry callers +do not load the RTX runtime. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import warp as wp + + from .foveated_newton_tiled_camera import FoveatedNewtonTiledCamera + from .foveated_rays import compute_foveated_ray_array + from .foveated_rtx_tiled_camera import FoveatedRTXTiledCamera + from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + +__all__ = [ + "FoveatedNewtonTiledCamera", + "FoveatedRTXTiledCamera", + "FoveatedTiledCamera", + "FoveatedTiledCameraCfg", + "compute_foveated_ray_array", +] + + +def FoveatedTiledCamera( + cfg: FoveatedTiledCameraCfg, +) -> FoveatedNewtonTiledCamera | FoveatedRTXTiledCamera: + """Construct a foveated camera for the explicitly selected renderer. + + Args: + cfg: Camera configuration with a concrete renderer configuration. + + Raises: + ValueError: The renderer is not supported. + NotImplementedError: Non-tiled Isaac RTX rendering is requested. + """ + renderer_type = cfg.renderer_cfg.renderer_type + if renderer_type == "newton_warp": + from .foveated_newton_tiled_camera import FoveatedNewtonTiledCamera + + return FoveatedNewtonTiledCamera(cfg) + if renderer_type in ("isaac_rtx", "ovrtx"): + if not cfg.tiled: + raise NotImplementedError("Non-tiled foveated RTX rendering is not implemented. Use tiled=True.") + from .foveated_rtx_tiled_camera import FoveatedRTXTiledCamera + + return FoveatedRTXTiledCamera(cfg) + raise ValueError(f"Unsupported foveated renderer {renderer_type!r}; select 'newton_warp', 'isaac_rtx', or 'ovrtx'.") + + +def __getattr__(name: str) -> type | Callable[..., wp.array]: + if name == "FoveatedTiledCameraCfg": + from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + + return FoveatedTiledCameraCfg + if name == "FoveatedNewtonTiledCamera": + from .foveated_newton_tiled_camera import FoveatedNewtonTiledCamera + + return FoveatedNewtonTiledCamera + if name == "FoveatedRTXTiledCamera": + from .foveated_rtx_tiled_camera import FoveatedRTXTiledCamera + + return FoveatedRTXTiledCamera + if name == "compute_foveated_ray_array": + from .foveated_rays import compute_foveated_ray_array + + return compute_foveated_ray_array + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/active_camera_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/active_camera_geometry.py new file mode 100644 index 000000000000..3ec9465eeb09 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/active_camera_geometry.py @@ -0,0 +1,297 @@ +# 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 + +"""Shared active-camera stereo geometry helpers.""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +import numpy as np + +_CameraPose = tuple[ + tuple[float, float, float], + tuple[float, float, float, float], +] + + +@dataclass(frozen=True) +class PanTiltMountGeometry: + """Neutral root and camera-local poses for an image-aligned pan/tilt mount.""" + + base_pose: _CameraPose + camera_local_pose: _CameraPose + + +def stereo_baseline_fixation_axis( + left_quat_xyzw: tuple[float, float, float, float], + right_in_left: tuple[float, ...] | None, + *, + manual_stereo_horizontal_separation_m: float | None = None, + horizontal_axis_parent: tuple[float, float, float] = (1.0, 0.0, 0.0), +) -> tuple[float, float]: + """Project the stereo baseline into the mount's fixation controls. + + Canonical fixation commands are ``(tilt, pan)`` around the parent-frame + +X and +Z axes. The returned unit direction is the command whose neutral + optical-axis motion points along the left-to-right baseline projected into + the optical tangent plane. + """ + from scipy.spatial.transform import Rotation as R + + left_quat = np.asarray(left_quat_xyzw, dtype=np.float64) + if left_quat.shape != (4,) or not np.isfinite(left_quat).all(): + raise ValueError("left_quat_xyzw must contain four finite values.") + left_rot = R.from_quat(left_quat) + + if manual_stereo_horizontal_separation_m is not None: + separation = float(manual_stereo_horizontal_separation_m) + if not np.isfinite(separation) or separation <= 0.0: + raise ValueError( + "manual_stereo_horizontal_separation_m must be finite and > 0, " + f"got {manual_stereo_horizontal_separation_m!r}." + ) + axis_parent = np.asarray(horizontal_axis_parent, dtype=np.float64) + axis_norm = float(np.linalg.norm(axis_parent)) + if not np.isfinite(axis_parent).all() or axis_norm <= 1.0e-8: + raise ValueError("horizontal_axis_parent must be finite and non-zero.") + baseline_parent = separation * axis_parent / axis_norm + else: + if right_in_left is None: + raise ValueError("right_in_left is required to derive the calibrated vergence axis.") + transform = np.asarray(right_in_left, dtype=np.float64) + if transform.size != 16 or not np.isfinite(transform).all(): + raise ValueError("right_in_left must contain 16 finite transform values.") + baseline_left = transform.reshape(4, 4)[:3, 3] + baseline_parent = left_rot.apply(baseline_left) + + optical_axis_parent = left_rot.apply(np.asarray((0.0, 0.0, 1.0), dtype=np.float64)) + baseline_tangent = baseline_parent - (np.dot(baseline_parent, optical_axis_parent) * optical_axis_parent) + if float(np.linalg.norm(baseline_tangent)) <= 1.0e-8: + raise ValueError("Stereo baseline has no resolvable component in the fixation tangent plane.") + + control_jacobian = np.column_stack( + ( + np.cross((1.0, 0.0, 0.0), optical_axis_parent), + np.cross((0.0, 0.0, 1.0), optical_axis_parent), + ) + ) + control_axis, _, rank, _ = np.linalg.lstsq( + control_jacobian, + baseline_tangent, + rcond=None, + ) + if rank != 2: + raise ValueError("Camera optical axis is singular for the configured tilt/pan mount controls.") + control_norm = float(np.linalg.norm(control_axis)) + if control_norm <= 1.0e-8: + raise ValueError("Stereo baseline produces no resolvable tilt/pan command.") + unit = control_axis / control_norm + return float(unit[0]), float(unit[1]) + + +def optical_axis_offset( + camera_quat_xyzw: tuple[float, float, float, float], + offset_m: float, +) -> tuple[float, float, float]: + """Return a parent-frame offset along the ROS-camera optical axis.""" + offset_m = float(offset_m) + if offset_m == 0.0: + return (0.0, 0.0, 0.0) + + from scipy.spatial.transform import Rotation as R + + forward = R.from_quat(np.asarray(camera_quat_xyzw, dtype=np.float64)).apply( + np.asarray((0.0, 0.0, offset_m), dtype=np.float64) + ) + return tuple(float(v) for v in forward) + + +def centered_stereo_aperture_poses( + center_pos: tuple[float, float, float], + left_quat_xyzw: tuple[float, float, float, float], + right_in_left: tuple[float, ...] | None, + *, + use_stereo: bool, + manual_stereo_horizontal_separation_m: float | None = None, + horizontal_axis_parent: tuple[float, float, float] = (1.0, 0.0, 0.0), +) -> tuple[ + tuple[tuple[float, float, float], tuple[float, float, float, float]], + tuple[tuple[float, float, float], tuple[float, float, float, float]] | None, +]: + """Return centered left/right aperture poses in the parent frame. + + ``center_pos`` is the midpoint between the two camera aperture centers. + ``right_in_left`` is the calibrated right-camera transform expressed in + the left-camera aperture frame. ``manual_stereo_horizontal_separation_m`` + overrides that calibrated transform with a centered yoked baseline along + ``horizontal_axis_parent``. + """ + from scipy.spatial.transform import Rotation as R + + center = np.asarray(center_pos, dtype=np.float64) + left_quat = np.asarray(left_quat_xyzw, dtype=np.float64) + left_rot = R.from_quat(left_quat) + + if not use_stereo: + left_pose = ( + tuple(float(v) for v in center), + tuple(float(v) for v in left_quat), + ) + return left_pose, None + if right_in_left is None: + if manual_stereo_horizontal_separation_m is None: + raise ValueError("right_in_left is required when use_stereo=True.") + + if manual_stereo_horizontal_separation_m is not None: + separation = float(manual_stereo_horizontal_separation_m) + if separation <= 0.0: + raise ValueError( + "manual_stereo_horizontal_separation_m must be > 0 when set, " + f"got {manual_stereo_horizontal_separation_m!r}." + ) + axis = np.asarray(horizontal_axis_parent, dtype=np.float64) + axis_norm = float(np.linalg.norm(axis)) + if axis_norm <= 1.0e-8: + raise ValueError("horizontal_axis_parent must be non-zero when manual stereo separation is set.") + baseline_parent = separation * (axis / axis_norm) + left_pos = center - 0.5 * baseline_parent + right_pos = center + 0.5 * baseline_parent + left_pose = ( + tuple(float(v) for v in left_pos), + tuple(float(v) for v in left_quat), + ) + right_pose = ( + tuple(float(v) for v in right_pos), + tuple(float(v) for v in left_quat), + ) + return left_pose, right_pose + + right_in_left_tf = np.asarray(right_in_left, dtype=np.float64).reshape(4, 4) + baseline_parent = left_rot.apply(right_in_left_tf[:3, 3]) + left_pos = center - 0.5 * baseline_parent + + left_tf = np.eye(4) + left_tf[:3, :3] = left_rot.as_matrix() + left_tf[:3, 3] = left_pos + right_tf = left_tf @ right_in_left_tf + right_rot = R.from_matrix(right_tf[:3, :3]) + + left_pose = ( + tuple(float(v) for v in left_pos), + tuple(float(v) for v in left_quat), + ) + right_pose = ( + tuple(float(v) for v in right_tf[:3, 3]), + tuple(float(v) for v in right_rot.as_quat()), + ) + return left_pose, right_pose + + +def stereo_aperture_poses( + left_pos: tuple[float, float, float], + left_quat_xyzw: tuple[float, float, float, float], + right_in_left: tuple[float, ...] | None, + *, + use_stereo: bool, + manual_stereo_horizontal_separation_m: float | None = None, + horizontal_axis_parent: tuple[float, float, float] = (1.0, 0.0, 0.0), +) -> tuple[_CameraPose, _CameraPose | None]: + """Return the configured camera poses without recentering calibration. + + Calibrated camera configs define ``left_pos`` as the actual left aperture + position and ``right_in_left`` relative to it. A manual yoked pair instead + treats that position as its midpoint, matching the active-camera presets. + """ + if manual_stereo_horizontal_separation_m is not None: + return centered_stereo_aperture_poses( + left_pos, + left_quat_xyzw, + right_in_left, + use_stereo=use_stereo, + manual_stereo_horizontal_separation_m=manual_stereo_horizontal_separation_m, + horizontal_axis_parent=horizontal_axis_parent, + ) + + left_pose = (left_pos, left_quat_xyzw) + if not use_stereo: + return left_pose, None + if right_in_left is None: + raise ValueError("right_in_left is required when use_stereo=True.") + + from scipy.spatial.transform import Rotation as R + + left_transform = np.eye(4, dtype=np.float64) + left_transform[:3, :3] = R.from_quat(np.asarray(left_quat_xyzw, dtype=np.float64)).as_matrix() + left_transform[:3, 3] = np.asarray(left_pos, dtype=np.float64) + relative_transform = np.asarray(right_in_left, dtype=np.float64) + if relative_transform.size != 16 or not np.isfinite(relative_transform).all(): + raise ValueError("right_in_left must contain 16 finite transform values.") + right_transform = left_transform @ relative_transform.reshape(4, 4) + right_pose = ( + tuple(float(value) for value in right_transform[:3, 3]), + tuple(float(value) for value in R.from_matrix(right_transform[:3, :3]).as_quat()), + ) + return left_pose, right_pose + + +def pan_tilt_mount_geometry( + camera_pos: tuple[float, float, float], + camera_quat_xyzw: tuple[float, float, float, float], + *, + image_rotation_deg: float, + camera_forward_offset_m: float, + base_z_drop_m: float, +) -> PanTiltMountGeometry: + """Factor a calibrated camera pose into an image-aligned pan/tilt mount. + + The mount's X and Z axes become policy-image right and up. Its Y axis is + optical forward, matching the bundled pan/tilt asset. The returned local + camera pose exactly reconstructs the calibrated pose at zero joint angles. + """ + from scipy.spatial.transform import Rotation as R + + position = np.asarray(camera_pos, dtype=np.float64).copy() + quaternion = np.asarray(camera_quat_xyzw, dtype=np.float64) + rotation_deg = float(image_rotation_deg) + forward_offset = float(camera_forward_offset_m) + base_z_drop = float(base_z_drop_m) + if position.shape != (3,) or not np.isfinite(position).all(): + raise ValueError("camera_pos must contain three finite values.") + if quaternion.shape != (4,) or not np.isfinite(quaternion).all(): + raise ValueError("camera_quat_xyzw must contain four finite values.") + if not math.isfinite(rotation_deg): + raise ValueError("image_rotation_deg must be finite.") + if not math.isfinite(forward_offset): + raise ValueError("camera_forward_offset_m must be finite.") + if not math.isfinite(base_z_drop) or base_z_drop < 0.0: + raise ValueError("base_z_drop_m must be finite and non-negative.") + + camera_rotation = R.from_quat(quaternion) + camera_matrix = camera_rotation.as_matrix() + raw_right = camera_matrix[:, 0] + raw_up = -camera_matrix[:, 1] + optical_forward = camera_matrix[:, 2] + theta = math.radians(rotation_deg) + policy_right = math.cos(theta) * raw_right + math.sin(theta) * raw_up + policy_up = -math.sin(theta) * raw_right + math.cos(theta) * raw_up + mount_rotation = R.from_matrix(np.column_stack((policy_right, optical_forward, policy_up))) + camera_local_rotation = mount_rotation.inv() * camera_rotation + camera_local_position = mount_rotation.inv().apply(forward_offset * optical_forward) + base_position = position + base_position -= mount_rotation.apply((0.0, 0.0, base_z_drop)) + base_position -= forward_offset * optical_forward + + return PanTiltMountGeometry( + base_pose=( + tuple(float(value) for value in base_position), + tuple(float(value) for value in mount_rotation.as_quat()), + ), + camera_local_pose=( + tuple(float(value) for value in camera_local_position), + tuple(float(value) for value in camera_local_rotation.as_quat()), + ), + ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_camera.py new file mode 100644 index 000000000000..56e5ce784b35 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_camera.py @@ -0,0 +1,162 @@ +# 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 + +"""Dense calibrated cameras that render the physical lens's distorted raster.""" + +from __future__ import annotations + +import tempfile +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import numpy as np +import torch +import warp as wp +from fovi.sensing.projection import CameraCalibration, CameraModel +from isaaclab import sim as sim_utils +from isaaclab.renderers.base_renderer import BaseRenderer +from isaaclab.sensors import Camera, CameraCfg +from isaaclab.utils.configclass import configclass + +from .dense_calibrated_geometry import apply_lens_schema, dense_camera_rays +from .generalized_projection import ( + apply_generalized_projection_to_prim, + build_dense_calibrated_textures, + save_generalized_projection_textures, +) + +if TYPE_CHECKING: + from pxr import Usd + + +class CalibratedTiledCamera(Camera): + """Dense OpenCV pinhole/fisheye camera for Isaac RTX, OVRTX and Newton/Warp. + + Lens parameters describe the raw rendered orientation. The raster is never + rectified; each Newton ray and RTX primary ray follows the physical lens. + ``data.intrinsic_matrices`` contains K but cannot alone describe this lens. + """ + + @property + def supports_batch_update(self) -> bool: + return True + + @staticmethod + def _update_buffers_batch_impl(sensors: Sequence[CalibratedTiledCamera]) -> None: + Camera._update_buffers_batch_impl(sensors) + if sim_utils.SimulationContext.instance() is None: + return # The base implementation already invoked scalar capture. + for sensor in sensors: + sensor.process_rendered_frame() + + @property + def renderer(self) -> BaseRenderer: + """Renderer shared with task-owned visual animation bindings.""" + return self._renderer + + def __init__(self, cfg: CalibratedTiledCameraCfg) -> None: + if cfg.camera_calibration is None: + raise ValueError("CalibratedTiledCamera requires camera_calibration") + self.camera_model = CameraModel.from_config(cfg.camera_calibration).resized((cfg.height, cfg.width)) + self._calibrated_rays = None + self._invalid_pixels = None + self._lut_directory: tempfile.TemporaryDirectory[str] | None = None + if cfg.renderer_cfg.renderer_type not in ("isaac_rtx", "ovrtx", "newton_warp"): + raise ValueError("Calibrated cameras support isaac_rtx, ovrtx, and newton_warp") + super().__init__(cfg) + if cfg.renderer_cfg.renderer_type == "ovrtx": + self._author_lens() + + def _author_lens(self) -> None: + if self.cfg.renderer_cfg.renderer_type in ("isaac_rtx", "ovrtx"): + prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) + if self.camera_model.model == "fisheye": + # RTX's native OpenCV fisheye clips to an implicit image circle, + # even when the calibrated rectangular sensor has valid corners. + # Odd inverse dimensions put octahedral axis seams on texel centers. + direction, inverse = build_dense_calibrated_textures( + self.camera_model, exit_size=max(128, 4 * max(self.camera_model.image_size)) + 1 + ) + self._lut_directory = tempfile.TemporaryDirectory(prefix="rtx_calibrated_luts_") + direction_path, inverse_path = save_generalized_projection_textures( + direction, inverse, self._lut_directory.name, "calibrated" + ) + for prim in prims: + apply_generalized_projection_to_prim(prim, direction_path, inverse_path) + elif self.camera_model.model == "pinhole": + for prim in prims: + apply_lens_schema(prim, self.camera_model) + else: + raise ValueError(f"Unsupported lens model {self.camera_model.model!r}") + + def _initialize_impl(self) -> None: + if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": + self._author_lens() + super()._initialize_impl() + directions, valid = dense_camera_rays(self.camera_model, str(self._device)) + self._invalid_pixels = (~valid)[None, ..., None] + if self.cfg.renderer_cfg.renderer_type == "newton_warp": + height, width = self.camera_model.image_size + rays = torch.zeros((1, height, width, 2, 3), device=self._device) + rays[0, :, :, 1] = directions + self._calibrated_rays = wp.from_torch(rays, dtype=wp.vec3f) + self._render_data.camera_rays = self._calibrated_rays + + def _read_authored_opencv_intrinsics( + self, prim: Usd.Prim, width: int, height: int, env_id: int + ) -> tuple[float, float, float, float]: + # LUT schemas carry rays, not fx/fy/cx/cy attributes. The calibration + # remains the source of public K metadata, in OpenCV pixel centers. + return self.camera_model.intrinsics + + def _initialize_intrinsics(self) -> None: + super()._initialize_intrinsics() + # Newton's explicit-ray camera has no USD lens schema, so its base + # initialization otherwise reconstructs a nominal pinhole K. + fx, fy, cx, cy = self.camera_model.intrinsics + matrix = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float32) + matrices = wp.array( + np.repeat(matrix[None], self._view.count, axis=0), + dtype=wp.mat33f, + device=self._device, + ) + wp.copy(self._data.intrinsic_matrices.warp, matrices) + + def set_intrinsic_matrices( + self, + matrices: torch.Tensor, + focal_length: float = 1.0, + env_ids: Sequence[int] | None = None, + ) -> None: + raise NotImplementedError("Construct a new calibrated camera to change its lens; K alone is insufficient") + + def _update_buffers_impl(self, env_mask: wp.array) -> None: + if not self._env_mask_has_any(env_mask): + return + super()._update_buffers_impl(env_mask) + self.process_rendered_frame() + + def process_rendered_frame(self) -> None: + """Apply calibrated range and validity conventions after a render.""" + if not self._env_mask_has_any(self._is_outdated): + return + if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self._data.output: + # OVRTX measures range from the near-clipped ray origin. + self._data.output["distance_to_camera"].torch.add_(self.cfg.spawn.clipping_range[0]) + for name, output in self._data.output.items(): + fill = ( + self.cfg.spawn.clipping_range[1] + if name in ("depth", "distance_to_image_plane", "distance_to_camera") + else 0 + ) + output.torch.masked_fill_(self._invalid_pixels, fill) + + +@configclass +class CalibratedTiledCameraCfg(CameraCfg): + """Opt-in dense calibrated lens; existing CameraCfg remains pinhole.""" + + class_type: type = CalibratedTiledCamera + camera_calibration: CameraCalibration | None = None diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py new file mode 100644 index 000000000000..fd9af7783fae --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -0,0 +1,176 @@ +# 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 + +"""Shared calibrated retinal geometry for rendering and image sampling.""" + +from __future__ import annotations + +from typing import Literal, Protocol + +import torch +import warp as wp +from fovi.sensing.projection import ( + CameraCalibration, + CameraModel, + angular_directions, + gaze_rotation, +) + + +class SamplingGeometryConfig(Protocol): + field_geometry: str + camera_calibration: CameraCalibration | None + cmf_a: float + cmf_a_frac: float | None + retinal_window_reference_side: str + retinal_window_short_side_fraction: float + + +def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: + """Resolve normalized CMF against the selected camera axis in degrees.""" + fraction = cfg.cmf_a if cfg.cmf_a_frac is None else cfg.cmf_a_frac + if cfg.field_geometry in ("planar", "legacy"): + return 1.0, fraction + if cfg.field_geometry != "spherical": + raise ValueError(f"Unknown field geometry {cfg.field_geometry!r}") + if cfg.camera_calibration is None: + raise ValueError("Spherical sensing requires camera_calibration") + camera = CameraModel(**cfg.camera_calibration) + fov = camera.field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_short_side_fraction) + return fov, fraction * fov + + +def retinal_directions(cartesian: torch.Tensor, fov_deg: float, image_rotation_deg: float = 0.0) -> torch.Tensor: + """Return OpenGL-frame angular rays, including the sensor mount roll.""" + rays = angular_directions(cartesian, fov_deg) + rays = rays * rays.new_tensor((1, -1, -1)) + angle = rays.new_tensor(image_rotation_deg * torch.pi / 180) + x, y, z = rays.unbind(-1) + return torch.stack((angle.cos() * x - angle.sin() * y, angle.sin() * x + angle.cos() * y, z), -1) + + +def compose_rotations(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor: + """Compose small rotation matrices without TF32 tensor-core rounding. + + Camera transforms need orthonormal rotations even when the surrounding + training process enables reduced-precision matrix multiplication. + """ + return (left[..., :, :, None] * right[..., None, :, :]).sum(dim=-2) + + +def convert_camera_frame_quaternion( + orientation: torch.Tensor, + *, + origin: Literal["world", "opengl"], + target: Literal["world", "opengl", "ros"], +) -> torch.Tensor: + """Convert world/OpenGL or OpenGL/ROS poses without a matrix round trip. + + Args: + orientation: Camera quaternions in XYZW order, shape (..., 4). + origin: Input camera-frame convention. + target: Opposite world/OpenGL convention, or ROS for OpenGL input. + + Returns: + Normalized float32 quaternions, shape (..., 4). Quaternion sign may change. + """ + quat = orientation.float() + quat = quat / quat.norm(dim=-1, keepdim=True) + x, y, z, w = quat.unbind(-1) + # Right multiplication by exact fixed-basis quaternions, without allocating + # device constants or making the matrix round-trip sensitive to AMP/TF32. + if origin == "world" and target == "opengl": + components = (w + x - y + z, -w + x + y + z, -w - x - y + z, w - x + y + z) + elif origin == "opengl" and target == "world": + components = (-w + x + y - z, w - x + y - z, w + x + y + z, w + x - y - z) + elif origin == "opengl" and target == "ros": + # ROS flips the OpenGL Y/Z axes: right-multiply by a half-turn about X. + return torch.stack((w, z, -y, -x), dim=-1) + else: + raise ValueError(f"Unsupported camera conversion: {origin!r} to {target!r}") + return torch.stack(components, dim=-1) * 0.5 + + +def calibrated_fixation_rotation( + camera: CameraModel, fixation: torch.Tensor, convention: str = "pan_tilt" +) -> tuple[torch.Tensor, torch.Tensor]: + """Return source-camera rotation and validity for normalized image gaze.""" + if fixation.is_cuda: + return _compiled_fixation_rotation(camera, fixation, convention) + return _fixation_rotation(camera, fixation, convention) + + +def _fixation_rotation( + camera: CameraModel, fixation: torch.Tensor, convention: str +) -> tuple[torch.Tensor, torch.Tensor]: + h, w = camera.image_size + pixels = torch.stack((fixation[..., 1] * w - 0.5, fixation[..., 0] * h - 0.5), -1) + direction, valid = camera.unproject(pixels) + return gaze_rotation(direction, convention), valid + + +def calibrated_mount_angles(camera: CameraModel, fixation: torch.Tensor) -> torch.Tensor: + """Unproject normalized upright-image gaze to mount (tilt, pan) radians.""" + if fixation.is_cuda: + return _compiled_mount_angles(camera, fixation) + return _mount_angles(camera, fixation) + + +def _mount_angles(camera: CameraModel, fixation: torch.Tensor) -> torch.Tensor: + h, w = camera.image_size + pixels = torch.stack((fixation[..., 1] * w - 0.5, fixation[..., 0] * h - 0.5), -1) + direction, _ = camera.unproject(pixels) + x, y, z = direction.unbind(-1) + return torch.stack((-torch.atan2(y, torch.sqrt(x * x + z * z)), -torch.atan2(x, z)), -1) + + +# Fuse the lens inversion's iterative pointwise math instead of launching each +# small operation separately on every simulation tick. CPU callers stay eager. +_compiled_fixation_rotation = torch.compile(_fixation_rotation, fullgraph=True) +_compiled_mount_angles = torch.compile(_mount_angles, fullgraph=True) + + +@wp.kernel(enable_backward=False) +def _rotate_camera_rays( + rays: wp.array(dtype=wp.vec3), + rotations: wp.array(dtype=wp.mat33), + output: wp.array2d(dtype=wp.vec3), +): + batch, sample = wp.tid() + output[batch, sample] = rotations[batch] * rays[sample] + + +def rotate_camera_rays(canonical_rays: torch.Tensor, rotation: torch.Tensor) -> torch.Tensor: + """Rotate visibility rays with IEEE float32, independent of model TF32 settings.""" + if canonical_rays.is_cuda and canonical_rays.dtype == rotation.dtype == torch.float32: + wp.init() # stream_from_torch requires an initialized Warp runtime. + result = canonical_rays.new_empty((len(rotation), len(canonical_rays), 3)) + torch_stream = torch.cuda.current_stream(canonical_rays.device) + stream = wp.get_stream(wp.device_from_torch(canonical_rays.device)) + # Temporary aliases unregister even a live Warp-owned stream when destroyed. + if stream.cuda_stream != torch_stream.cuda_stream: + stream = wp.stream_from_torch(torch_stream) + with wp.ScopedStream( + stream, + sync_enter=False, + sync_exit=False, + ): + wp.launch( + _rotate_camera_rays, + dim=result.shape[:2], + inputs=[ + wp.from_torch(canonical_rays.contiguous(), dtype=wp.vec3), + wp.from_torch(rotation.contiguous(), dtype=wp.mat33), + ], + outputs=[wp.from_torch(result, dtype=wp.vec3)], + ) + return result + return canonical_rays @ rotation.transpose(-1, -2) + + +def calibrated_visibility(camera: CameraModel, canonical_rays: torch.Tensor, rotation: torch.Tensor) -> torch.Tensor: + """Mask OpenCV-frame canonical rays against the fixed physical sensor.""" + _, valid = camera.project(rotate_camera_rays(canonical_rays, rotation)) + return valid diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/dense_calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/dense_calibrated_geometry.py new file mode 100644 index 000000000000..2f50c7ea2555 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/dense_calibrated_geometry.py @@ -0,0 +1,67 @@ +# 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 + +"""Dense raster geometry using the same physical lens model as Fovi/Isaac Lab Fovi.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from fovi.sensing.projection import CameraModel + +if TYPE_CHECKING: + from pxr import Usd + + +def dense_camera_rays(camera: CameraModel, device: str = "cpu") -> tuple[torch.Tensor, torch.Tensor]: + """Return OpenGL unit rays (H,W,3) and usable-pixel mask (H,W). + + Integer pixel centers refer to the original distorted raster. Invalid + pixels receive a finite forward ray and are masked after rendering. + """ + height, width = camera.image_size + y, x = torch.meshgrid( + torch.arange(height, dtype=torch.float64, device=device), + torch.arange(width, dtype=torch.float64, device=device), + indexing="ij", + ) + directions, valid = camera.unproject(torch.stack((x, y), -1)) + directions = directions * directions.new_tensor((1, -1, -1)) + directions = torch.where(valid[..., None], directions, directions.new_tensor((0, 0, -1))) + return directions.float().contiguous(), valid + + +def lens_schema_values(camera: CameraModel) -> tuple[str, str, dict[str, float]]: + """Return the native RTX schema, model token, and OpenCV coefficient mapping.""" + fx, fy, cx, cy = camera.intrinsics + # RTX evaluates raster samples at half-integers; OpenCV centers are integers. + values = dict(fx=fx, fy=fy, cx=cx + 0.5, cy=cy + 0.5) + if camera.model == "fisheye": + schema, token = "OmniLensDistortionOpenCvFisheyeAPI", "opencvFisheye" + names = ("k1", "k2", "k3", "k4") + elif camera.model == "pinhole": + schema, token = "OmniLensDistortionOpenCvPinholeAPI", "opencvPinhole" + names = ("k1", "k2", "p1", "p2", "k3", "k4", "k5", "k6", "s1", "s2", "s3", "s4") + else: + raise ValueError(f"Unsupported lens model {camera.model!r}") + coefficients = (*camera.distortion, *((0.0,) * (len(names) - len(camera.distortion)))) + values.update(zip(names, coefficients, strict=True)) + return schema, token, values + + +def apply_lens_schema(prim: Usd.Prim, camera: CameraModel) -> None: + """Author native RTX distortion before render-product initialization.""" + from pxr import Gf, Sdf + + schema, token, values = lens_schema_values(camera) + # Explicit metadata and attributes work even when the USD schema is not registered. + prim.AddAppliedSchema(schema) + prim.CreateAttribute("omni:lensdistortion:model", Sdf.ValueTypeNames.Token).Set(token) + prefix = f"omni:lensdistortion:{token}:" + height, width = camera.image_size + prim.CreateAttribute(prefix + "imageSize", Sdf.ValueTypeNames.Int2).Set(Gf.Vec2i(width, height)) + for name, value in values.items(): + prim.CreateAttribute(prefix + name, Sdf.ValueTypeNames.Float).Set(float(value)) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/fixed_software_fov.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/fixed_software_fov.py new file mode 100644 index 000000000000..15eaa988b368 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/fixed_software_fov.py @@ -0,0 +1,247 @@ +# 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 + +"""Geometry helpers for direct foveation inside a fixed software-camera FOV.""" + +from __future__ import annotations + +import math + +import torch + +RETINAL_WINDOW_REFERENCE_SIDES = ("short", "long") +FIXED_FOV_ANGLE_MODELS = ("camera_xyz", "pan_tilt") + + +def retinal_window_reference_size( + *, + image_height: int, + image_width: int, + reference_side: str, +) -> int: + """Resolve the image dimension used as the circular retinal diameter.""" + if image_height <= 0 or image_width <= 0: + raise ValueError( + f"Retinal window reference requires positive image dimensions, got {image_height}x{image_width}." + ) + if reference_side == "short": + return min(image_height, image_width) + if reference_side == "long": + return max(image_height, image_width) + raise ValueError( + f"retinal_window_reference_side must be one of {RETINAL_WINDOW_REFERENCE_SIDES}, got {reference_side!r}." + ) + + +def validate_fixed_software_fov( + *, + image_height: int, + image_width: int, + focal_length_px: float, + principal_point: tuple[float, float], + retinal_window_short_side_fraction: float, + retinal_window_reference_side: str = "short", +) -> None: + """Validate a rectilinear dense-camera geometry.""" + if image_height <= 0 or image_width <= 0: + raise ValueError(f"fixed software FOV requires positive image dimensions, got {image_height}x{image_width}.") + if focal_length_px <= 0.0: + raise ValueError(f"fixed software FOV requires focal_length_px > 0, got {focal_length_px}.") + cx, cy = principal_point + if not 0.0 <= cx <= image_width or not 0.0 <= cy <= image_height: + raise ValueError( + "fixed software FOV principal point must lie inside the image, got " + f"{principal_point} for {image_height}x{image_width}." + ) + if not 0.0 < retinal_window_short_side_fraction <= 1.0: + raise ValueError( + f"retinal_window_short_side_fraction must be in (0, 1], got {retinal_window_short_side_fraction}." + ) + retinal_window_reference_size( + image_height=image_height, + image_width=image_width, + reference_side=retinal_window_reference_side, + ) + + +def retinal_ray_directions( + cartesian: torch.Tensor, + *, + image_height: int, + image_width: int, + focal_length_px: float, + retinal_window_short_side_fraction: float, + retinal_window_reference_side: str = "short", + image_rotation_deg: float = 0.0, +) -> torch.Tensor: + """Convert normalized retinal coordinates into camera-space pinhole rays.""" + validate_fixed_software_fov( + image_height=image_height, + image_width=image_width, + focal_length_px=focal_length_px, + principal_point=(image_width * 0.5, image_height * 0.5), + retinal_window_short_side_fraction=retinal_window_short_side_fraction, + retinal_window_reference_side=retinal_window_reference_side, + ) + rotated = cartesian + if image_rotation_deg: + theta = math.radians(float(image_rotation_deg)) + cosine = math.cos(theta) + sine = math.sin(theta) + rotation = cartesian.new_tensor(((cosine, -sine), (sine, cosine))) + rotated = cartesian @ rotation.T + reference_size = retinal_window_reference_size( + image_height=image_height, + image_width=image_width, + reference_side=retinal_window_reference_side, + ) + diameter_px = reference_size * retinal_window_short_side_fraction + tangent = rotated * (0.5 * diameter_px / focal_length_px) + directions = torch.cat( + (tangent, -torch.ones_like(tangent[:, :1])), + dim=-1, + ) + return torch.nn.functional.normalize(directions, dim=-1) + + +def _image_fixation_tangents( + fixation: torch.Tensor, + *, + image_height: int, + image_width: int, + focal_length_px: float, + principal_point: tuple[float, float], + image_rotation_deg: float = 0.0, +) -> tuple[torch.Tensor, torch.Tensor]: + validate_fixed_software_fov( + image_height=image_height, + image_width=image_width, + focal_length_px=focal_length_px, + principal_point=principal_point, + retinal_window_short_side_fraction=1.0, + ) + cx, cy = principal_point + tangent_x = (fixation[..., 1] * image_width - cx) / focal_length_px + tangent_y = (cy - fixation[..., 0] * image_height) / focal_length_px + if image_rotation_deg: + theta = math.radians(float(image_rotation_deg)) + cosine = math.cos(theta) + sine = math.sin(theta) + rotated_x = cosine * tangent_x - sine * tangent_y + tangent_y = sine * tangent_x + cosine * tangent_y + tangent_x = rotated_x + return tangent_x, tangent_y + + +def image_fixation_to_camera_angles( + fixation: torch.Tensor, + *, + image_height: int, + image_width: int, + focal_length_px: float, + principal_point: tuple[float, float], + image_rotation_deg: float = 0.0, +) -> torch.Tensor: + """Aim an XYZ-rotated virtual camera through an image fixation.""" + tangent_x, tangent_y = _image_fixation_tangents( + fixation, + image_height=image_height, + image_width=image_width, + focal_length_px=focal_length_px, + principal_point=principal_point, + image_rotation_deg=image_rotation_deg, + ) + roll = torch.atan(tangent_y) + pitch = torch.atan(-tangent_x * torch.cos(roll)) + return torch.stack((roll, pitch), dim=-1) + + +def image_fixation_to_pan_tilt_angles( + fixation: torch.Tensor, + *, + image_height: int, + image_width: int, + focal_length_px: float, + principal_point: tuple[float, float], +) -> torch.Tensor: + """Aim a +Y-forward, pan-then-tilt mount through an image fixation.""" + tangent_x, tangent_y = _image_fixation_tangents( + fixation, + image_height=image_height, + image_width=image_width, + focal_length_px=focal_length_px, + principal_point=principal_point, + ) + pan = torch.atan(-tangent_x) + tilt = torch.atan(tangent_y * torch.cos(pan)) + return torch.stack((tilt, pan), dim=-1) + + +def fixed_frustum_validity( + ray_directions: torch.Tensor, + fixation_angles: torch.Tensor, + *, + image_height: int, + image_width: int, + focal_length_px: float, + principal_point: tuple[float, float], + angle_model: str = "camera_xyz", + image_rotation_deg: float = 0.0, +) -> torch.Tensor: + """Return validity after applying the configured camera or mount rotation.""" + rays = ray_directions.unsqueeze(0) + x = rays[..., 0] + y = rays[..., 1] + z = rays[..., 2] + if angle_model == "camera_xyz": + roll = fixation_angles[:, 0:1] + pitch = fixation_angles[:, 1:2] + sin_r = torch.sin(roll) + cos_r = torch.cos(roll) + sin_p = torch.sin(pitch) + cos_p = torch.cos(pitch) + rotated_x = cos_p * x + sin_p * z + rotated_y = sin_r * sin_p * x + cos_r * y - sin_r * cos_p * z + rotated_z = -cos_r * sin_p * x + sin_r * y + cos_r * cos_p * z + elif angle_model == "pan_tilt": + if not math.isfinite(float(image_rotation_deg)): + raise ValueError(f"fixed-FOV image_rotation_deg must be finite, got {image_rotation_deg!r}.") + theta = math.radians(float(image_rotation_deg)) + cosine = math.cos(theta) + sine = math.sin(theta) + + policy_x = cosine * x + sine * y + policy_y = -sine * x + cosine * y + policy_z = z + mount_x = policy_x + mount_y = -policy_z + mount_z = policy_y + + tilt = fixation_angles[:, 0:1] + pan = fixation_angles[:, 1:2] + sin_tilt = torch.sin(tilt) + cos_tilt = torch.cos(tilt) + sin_pan = torch.sin(pan) + cos_pan = torch.cos(pan) + tilted_y = cos_tilt * mount_y - sin_tilt * mount_z + tilted_z = sin_tilt * mount_y + cos_tilt * mount_z + moved_mount_x = cos_pan * mount_x - sin_pan * tilted_y + moved_mount_y = sin_pan * mount_x + cos_pan * tilted_y + + moved_policy_x = moved_mount_x + moved_policy_y = tilted_z + moved_policy_z = -moved_mount_y + rotated_x = cosine * moved_policy_x - sine * moved_policy_y + rotated_y = sine * moved_policy_x + cosine * moved_policy_y + rotated_z = moved_policy_z + else: + raise ValueError(f"angle_model must be one of {FIXED_FOV_ANGLE_MODELS}, got {angle_model!r}.") + + forward = -rotated_z + safe_forward = forward.clamp_min(torch.finfo(ray_directions.dtype).eps) + cx, cy = principal_point + pixel_x = focal_length_px * rotated_x / safe_forward + cx + pixel_y = cy - focal_length_px * rotated_y / safe_forward + return (forward > 0.0) & (pixel_x >= 0.0) & (pixel_x < image_width) & (pixel_y >= 0.0) & (pixel_y < image_height) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py new file mode 100644 index 000000000000..22e12c1259bb --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py @@ -0,0 +1,595 @@ +# 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 + +"""Newton foveated tiled camera sensor. + +Subclasses :class:`isaaclab.sensors.Camera` to replace uniform pinhole +rays with CMF-distributed foveated rays computed from +:class:`fovi.sensing.coords.SamplingCoords`. Uses Newton's Warp renderer +to shoot custom ray arrays. +""" + +from __future__ import annotations + +import logging +import math +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp +from isaaclab.sensors.camera.camera import Camera +from isaaclab.utils.math import quat_from_euler_xyz, quat_mul +from isaaclab.utils.warp import ProxyArray + +from .calibrated_geometry import convert_camera_frame_quaternion, retinal_directions +from .fixed_software_fov import ( + FIXED_FOV_ANGLE_MODELS, + fixed_frustum_validity, + retinal_ray_directions, + validate_fixed_software_fov, +) +from .foveated_rays import compute_explicit_ray_array, compute_foveated_ray_array +from .native_grid import ( + GRID_STYLE, + allocate_grid_outputs, + copy_grid_outputs, + grid_output_shape, + grid_sample_indices, + mask_grid_samples, + native_grid_directions, +) +from .pooling import ( + build_highres_coords, + build_lowres_coords, + build_pooler, + is_segmentation_output, + pool_hwc_buffer, +) +from .virtual_gaze import CalibratedVirtualGaze + +if TYPE_CHECKING: + from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + +logger = logging.getLogger(__name__) + + +@wp.kernel(enable_backward=False) +def _pack_vector_rays( + source: wp.array2d(dtype=wp.vec3f), + target: wp.array2d(dtype=wp.vec3f), +) -> None: + i = wp.tid() + source_i = wp.min(i, source.shape[0] - 1) + target[i, 0] = source[source_i, 0] + target[i, 1] = source[source_i, 1] + + +class FoveatedNewtonTiledCamera(CalibratedVirtualGaze, Camera): + """Newton tiled camera that renders with foveated (CMF-distributed) rays. + + Instead of a uniform pixel grid, this sensor shoots *N* rays whose + directions are derived from :class:`fovi.sensing.coords.SamplingCoords` + and injected into Newton's Warp renderer. Vector sensors publish + ``(B, N, 1, C)``; native grid sensors publish upright ``(B, H, W, C)``. + + The camera's physical FOV (from the ``spawn`` optics) is used as the + ``SamplingCoords.fov`` parameter so that the foveated sampling covers the + full scene. Fixation is applied as a per-environment camera rotation. + """ + + cfg: FoveatedTiledCameraCfg + + def __init__(self, cfg: FoveatedTiledCameraCfg): + if cfg.field_geometry == "spherical": + cfg.update_latest_camera_pose = True + if cfg.camera_fov_deg is not None: + # Back-compute spawn optics from desired FOV for USD prim compat. + hfov_rad = math.radians(cfg.camera_fov_deg) + aperture = cfg.spawn.horizontal_aperture # keep default aperture + cfg.spawn.focal_length = aperture / (2.0 * math.tan(hfov_rad / 2.0)) + self._spawn_focal_length: float = cfg.spawn.focal_length + self._spawn_horizontal_aperture: float = cfg.spawn.horizontal_aperture + self._fixation: torch.Tensor | None = None + self._fixed_fov_fixation: torch.Tensor | None = None + self._fixed_fov_angle_model = "camera_xyz" + self._calibrated_rotation = None + super().__init__(cfg) + + # ------------------------------------------------------------------ + # Initialisation + # ------------------------------------------------------------------ + + def _initialize_impl(self): + # 1. Derive camera physical FOV for ray generation. + self._camera_hfov_rad = 2.0 * math.atan(self._spawn_horizontal_aperture / (2.0 * self._spawn_focal_length)) + + # 2. Build coords on CPU so we know N_lo (and N_hi when pooling) before + # the parent allocates buffers. The pooler is constructed later, + # after the sensor device is available, because its knn indices / + # distances / gaussian weights are plain tensor attributes that + # nn.Module.to() does not move. + # cfg.cmf_a is already cmf_a_frac after resolve_cmf_a_frac runs + self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") + self._native_grid = self.cfg.foveated_style == GRID_STYLE + self._sampling_coords_highres = build_highres_coords( + self.cfg, + matched_res, + device="cpu", + ) + self._num_valid_samples = len(self._sampling_coords) # public / RGC count + self._num_ray_samples = len(self._sampling_coords_highres or self._sampling_coords) + self._camera_hfov_deg = math.degrees(self._camera_hfov_rad) + self._fixed_fov_focal_length_px: float | None = None + self._fixed_fov_image_height: int | None = None + self._fixed_fov_image_width: int | None = None + if self.cfg.fixed_software_fov: + if self.cfg.projection != "pinhole" and self.cfg.field_geometry != "spherical": + raise ValueError( + f"fixed_software_fov currently requires projection='pinhole', got {self.cfg.projection!r}." + ) + image_height = self.cfg.software_fov_image_height + image_width = self.cfg.software_fov_image_width + if image_height is None or image_width is None: + raise ValueError( + "fixed_software_fov=True requires software_fov_image_height and software_fov_image_width." + ) + focal_length_px = image_width * self._spawn_focal_length / self._spawn_horizontal_aperture + validate_fixed_software_fov( + image_height=image_height, + image_width=image_width, + focal_length_px=focal_length_px, + principal_point=(image_width * 0.5, image_height * 0.5), + retinal_window_short_side_fraction=(self.cfg.retinal_window_short_side_fraction), + retinal_window_reference_side=self.cfg.retinal_window_reference_side, + ) + self._fixed_fov_focal_length_px = focal_length_px + self._fixed_fov_image_height = image_height + self._fixed_fov_image_width = image_width + pool_line = ( + f" Pool: mode={self.cfg.pool_mode} " + f"N_hi={self._num_ray_samples} -> N_lo={self._num_valid_samples}\n" + if self.cfg.pool_enabled + else "" + ) + print( + f"\n{'=' * 60}\n" + f" FoveatedNewtonTiledCamera\n" + f" HFOV: {self._camera_hfov_deg:.1f}°\n" + f" Projection: {self.cfg.projection}\n" + f" Samples: N={self._num_valid_samples}\n" + f" cmf_a_frac: {self.cfg.cmf_a}\n" + f" Style: {self.cfg.foveated_style}\n" + f"{pool_line}" + f"{'=' * 60}\n" + ) + + # 3. Size the parent's render buffers to the *rendered* ray count. + # When pooling is enabled this is N_hi; otherwise it equals N_lo. + ray_coords = self._sampling_coords_highres or self._sampling_coords + self.cfg.height, self.cfg.width = grid_output_shape(ray_coords) + renderer = self.cfg.renderer_cfg + if renderer.render_order == "tiled": + tile_width = renderer.tile_rendering_width + tile_height = renderer.tile_rendering_height + if tile_width <= 0 or tile_height <= 0: + raise ValueError("Newton render tile dimensions must be positive.") + if not self._native_grid: + # Pack consecutive vector rays into complete tiles. Padding is + # private renderer storage and never enters masking or pooling. + self.cfg.width = tile_width + self.cfg.height = ( + (self._num_ray_samples + tile_width * tile_height - 1) // (tile_width * tile_height) * tile_height + ) + + # 4. Run parent initialisation (creates renderer, buffers, etc.). + super()._initialize_impl() + if self._native_grid: + self._validate_native_render_layout() + + # 5. Move coords to the correct device. + self._sampling_coords = self._sampling_coords.to(device=self._device) + if self._sampling_coords_highres is not None: + self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) + ray_coords_device = self._sampling_coords_highres + else: + ray_coords_device = self._sampling_coords + self._ray_coords = ray_coords_device + self._initialize_calibrated_gaze() + + # 6. Build the pooler(s) on the sensor device. A second max-mode + # pooler is materialised lazily below if any integer-valued outputs + # are present (segmentation class IDs) and pool_int_mode differs + # from pool_mode. + self._pooler, self._pool_k = build_pooler( + self.cfg, + self._sampling_coords, + self._sampling_coords_highres, + device=str(self._device), + ) + self._pooler_int = None + + # 7. Pre-compute foveated rays from the highres (or lowres) cartesian. + # Apply optional image-space rotation by rotating the 2D cartesian + # coordinates around the optical axis BEFORE deriving rays. This + # keeps the per-sample index ordering identical to the canonical + # ``SamplingCoords`` (so the agent / foveated scatter visualization + # see upright samples) while undoing a physical mount rotation of + # the camera prim. Foveated analogue of a post-render + # ``torch.flip`` — but flip would shuffle the sample-to-coord + # mapping; this rotation does not. + ray_cart = ray_coords_device.cartesian + if self._native_grid: + tangent_scale = math.tan(self._camera_hfov_rad / 2) + if self.cfg.fixed_software_fov: + reference = ( + max(self._fixed_fov_image_height, self._fixed_fov_image_width) + if self.cfg.retinal_window_reference_side == "long" + else min(self._fixed_fov_image_height, self._fixed_fov_image_width) + ) + tangent_scale = ( + reference * self.cfg.retinal_window_short_side_fraction / (2 * self._fixed_fov_focal_length_px) + ) + self._fixed_fov_ray_directions = native_grid_directions( + ray_coords_device, + tangent_scale=tangent_scale, + image_rotation_deg=self.cfg.image_rotation_deg, + projection=self.cfg.projection, + camera_fov_rad=self._camera_hfov_rad, + ) + self._foveated_rays = compute_explicit_ray_array(self._fixed_fov_ray_directions, device=str(self._device)) + elif self.cfg.field_geometry == "spherical": + self._fixed_fov_ray_directions = retinal_directions( + ray_cart, self._sampling_coords.fov, self.cfg.image_rotation_deg + ) + self._foveated_rays = compute_explicit_ray_array(self._fixed_fov_ray_directions, device=str(self._device)) + elif self.cfg.fixed_software_fov: + self._fixed_fov_ray_directions = retinal_ray_directions( + ray_cart, + image_height=self._fixed_fov_image_height, + image_width=self._fixed_fov_image_width, + focal_length_px=self._fixed_fov_focal_length_px, + retinal_window_short_side_fraction=(self.cfg.retinal_window_short_side_fraction), + retinal_window_reference_side=self.cfg.retinal_window_reference_side, + image_rotation_deg=self.cfg.image_rotation_deg, + ) + self._foveated_rays = compute_explicit_ray_array( + self._fixed_fov_ray_directions, + device=str(self._device), + ) + elif self.cfg.image_rotation_deg: + theta = math.radians(float(self.cfg.image_rotation_deg)) + cos_t = math.cos(theta) + sin_t = math.sin(theta) + rot = torch.tensor( + [[cos_t, -sin_t], [sin_t, cos_t]], + device=ray_cart.device, + dtype=ray_cart.dtype, + ) + ray_cart = ray_cart @ rot.T + self._foveated_rays = compute_foveated_ray_array( + sampling_coords_cartesian=ray_cart, + camera_fov_rad=self._camera_hfov_rad, + device=str(self._device), + projection=self.cfg.projection, + ) + else: + self._foveated_rays = compute_foveated_ray_array( + sampling_coords_cartesian=ray_cart, + camera_fov_rad=self._camera_hfov_rad, + device=str(self._device), + projection=self.cfg.projection, + ) + + render_samples = self.cfg.height * self.cfg.width + if render_samples > self._num_ray_samples: + packed = wp.empty((render_samples, 2), dtype=wp.vec3f, device=self._device) + wp.launch( + _pack_vector_rays, + dim=render_samples, + inputs=[self._foveated_rays.reshape((self._num_ray_samples, 2)), packed], + device=self._device, + ) + self._foveated_rays = packed + self._foveated_rays = self._foveated_rays.reshape((1, self.cfg.height, self.cfg.width, 2)) + # Renderer buffers remain whole tiles; zero-copy canonical views hide + # trailing padding and preserve every output's dtype and sample order. + self._render_output = dict(self._data.output) + self._flat_render_output = {} + for name, value in self._render_output.items(): + tensor = value.torch + flat = tensor.view(tensor.shape[0], render_samples, 1, tensor.shape[-1]) + self._flat_render_output[name] = ProxyArray(wp.from_torch(flat[:, : self._num_ray_samples])) + self._data.output.clear() + self._data.output.update(self._flat_render_output) + + self._allocate_pooled_buffers() + if self._native_grid: + source = self._pooled_output if self._pooler is not None else self._flat_render_output + self._grid_output = allocate_grid_outputs(source, self._sampling_coords) + self._grid_indices = grid_sample_indices(self._sampling_coords) + self._data.output.clear() + self._data.output.update(self._grid_output) + + # 6. Inject foveated rays into render_data immediately. + self._render_data.camera_rays = self._foveated_rays + logger.info( + "FoveatedNewtonTiledCamera: injected foveated rays shape=%s onto render_data", + self._foveated_rays.shape, + ) + + def _validate_native_render_layout(self) -> None: + """Reject image dimensions that cannot be covered by Newton's tiles.""" + renderer = self._renderer.cfg + if renderer.render_order != "tiled": + return + tile_width = renderer.tile_rendering_width + tile_height = renderer.tile_rendering_height + if self.cfg.width % tile_width or self.cfg.height % tile_height: + raise ValueError( + f"Native-grid Newton render size {self.cfg.width}x{self.cfg.height} " + f"must be divisible by renderer tile size {tile_width}x{tile_height}. " + "Choose foveated_res and pool_res_mult so the rendered grid satisfies " + "these dimensions, or select a non-tiled Newton render_order." + ) + + def _allocate_pooled_buffers(self) -> None: + """Allocate output-grid tensors from renderer-owned high-resolution buffers.""" + if self._pooler is not None: + # Stash the parent-allocated highres buffers; the renderer will keep + # writing into these, and we pool into a separate lowres dict that + # becomes the public _data.output after each update. + self._highres_output: dict[str, ProxyArray] = dict(self._data.output) + self._pooled_output: dict[str, torch.Tensor] = {} + needs_int_pooler = False + for name, tex in self._highres_output.items(): + tensor = tex.torch + B, _, _, C = tensor.shape + self._pooled_output[name] = torch.zeros( + (B, self._num_valid_samples, 1, C), + dtype=tensor.dtype, + device=tensor.device, + ) + if is_segmentation_output(name) and self.cfg.pool_int_mode != self.cfg.pool_mode: + needs_int_pooler = True + if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: + # Re-alias rgb onto the first 3 channels of pooled rgba. + self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] + if needs_int_pooler: + self._pooler_int, _ = build_pooler( + self.cfg, + self._sampling_coords, + self._sampling_coords_highres, + device=str(self._device), + mode=self.cfg.pool_int_mode, + ) + dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} + print( + f"[FoveatedNewtonTiledCamera] pool outputs={dtypes_summary} " + f"pool_mode={self.cfg.pool_mode!r} int_mode={self.cfg.pool_int_mode!r} " + f"int_pooler_built={self._pooler_int is not None}" + ) + logger.info( + "FoveatedNewtonTiledCamera: KNN pooling enabled " + "(mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) " + "outputs=%s int_pooler=%s int_mode=%s", + self.cfg.pool_mode, + self._pool_k, + self.cfg.pool_sample_cortex, + self._num_ray_samples, + self._num_valid_samples, + dtypes_summary, + self._pooler_int is not None, + self.cfg.pool_int_mode, + ) + + # ------------------------------------------------------------------ + # Fixation + # ------------------------------------------------------------------ + + def set_fixation(self, fixation_angles: torch.Tensor): + """Set per-environment fixation as camera rotation angles. + + Args: + fixation_angles: ``(B, 2)`` tensor in radians. + ``[:, 0]`` = θ_x (X-axis rotation, positive = look up), + ``[:, 1]`` = θ_y (Y-axis rotation, positive = look left). + ``(0, 0)`` = center (no rotation). + """ + self._fixation = fixation_angles + + def set_fixed_fov_fixation( + self, + fixation_angles: torch.Tensor, + *, + angle_model: str, + ) -> None: + """Update fixed-frustum masking without rotating the camera twice.""" + if not self.cfg.fixed_software_fov: + raise RuntimeError("set_fixed_fov_fixation requires fixed_software_fov=True.") + if angle_model not in FIXED_FOV_ANGLE_MODELS: + raise ValueError(f"angle_model must be one of {FIXED_FOV_ANGLE_MODELS}, got {angle_model!r}.") + self._fixed_fov_fixation = fixation_angles + self._fixed_fov_angle_model = angle_model + + def _apply_fixation_rotation(self): + """Rotate camera orientations based on the current fixation angles. + + Composes fixation rotation (in angle-space) with the base camera + orientations in the OpenGL frame. + """ + fix = self._fixation.float() # (B, 2): [θ_x, θ_y] in radians + look_roll = fix[:, 0] # X-axis rotation (directly in radians) + look_pitch = fix[:, 1] # Y-axis rotation (directly in radians) + zeros = torch.zeros_like(look_roll) + + fix_quat = quat_from_euler_xyz(look_roll, look_pitch, zeros) # (B, 4) + + # Apply rotation in OpenGL camera frame: + # 1. Convert stored world-convention quaternions to OpenGL + quat_world = self._quat_w_world_torch() + quat_gl = convert_camera_frame_quaternion(quat_world, origin="world", target="opengl") + # 2. Compose: base rotation * fixation rotation (local frame) + quat_gl_rotated = quat_mul(quat_gl, fix_quat) + # 3. Convert back to world convention for storage + quat_world[:] = convert_camera_frame_quaternion(quat_gl_rotated, origin="opengl", target="world") + + def _quat_w_world_torch(self) -> torch.Tensor: + """Return the camera world quaternion as a Torch tensor view.""" + quat_world = self._data.quat_w_world + return quat_world.torch if hasattr(quat_world, "torch") else quat_world + + # ------------------------------------------------------------------ + # Per-frame overrides + # ------------------------------------------------------------------ + + def _update_poses( + self, + env_ids: Sequence[int] | wp.array | None = None, + env_mask: wp.array | None = None, + frame_op: int = 0, + ) -> None: + """Read base poses, apply fixation rotation, update renderer, inject rays. + + Read the scene pose even without a sensor-level fixation: the camera + may inherit motion from a parent articulation. + """ + # 1. Read base camera poses + apply fixation (only when fixation active) + Camera._update_poses(self, env_ids, env_mask=env_mask, frame_op=frame_op) + if self._fixation is not None: + self._apply_fixation_rotation() + + self._apply_calibrated_pose(env_ids, env_mask) + + # 2. Update camera_transforms + # The renderer maintains persistent transform buffers and updates + # them in place after the pose changes. + self._renderer.update_camera( + self._render_data, + self._data.pos_w, + self._data.quat_w_world, + self._data.intrinsic_matrices, + ) + + # 3. Ensure foveated rays (not pinhole) + if hasattr(self, "_foveated_rays"): + self._render_data.camera_rays = self._foveated_rays + + def _update_buffers_impl(self, env_mask: wp.array): + """Render, then (optionally) pool highres -> lowres foveated samples.""" + self._data.output.clear() + self._data.output.update(self._render_output) + if self._pooler is None: + super()._update_buffers_impl(env_mask) + output = self._flat_render_output + mask_grid_samples(output, self._ray_coords) + self._apply_fixed_fov_mask(output) + if self._native_grid: + copy_grid_outputs(output, self._grid_output, self._grid_indices) + self._data.output.clear() + self._data.output.update(self._grid_output if self._native_grid else output) + return + + # Ensure the renderer writes into the highres buffers, not the pooled ones. + self._data.output.clear() + self._data.output.update(self._render_output) + super()._update_buffers_impl(env_mask) + mask_grid_samples(self._highres_output, self._ray_coords) + self._apply_fixed_fov_mask(self._highres_output) + + # Pool each output channel (B, N_hi, 1, C) -> (B, N_lo, 1, C). + # Cast to float for pooling (KNN ops need real-valued NaN semantics), + # then restore the original dtype. Integer outputs (segmentation + # class IDs) use the separate max-mode pooler so pooled values remain + # valid class IDs rather than averaged floats. + for name, hi in self._highres_output.items(): + if name == "rgb": + continue # rgba alias, refreshed below + lo = self._pooled_output[name] + use_int_pool = self._pooler_int is not None and is_segmentation_output(name) + pooler = self._pooler_int if use_int_pool else self._pooler + pooled = pool_hwc_buffer(pooler, hi.torch.float()) + lo.copy_(pooled.to(lo.dtype)) + if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: + self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] + + # Expose pooled tensors as the public sensor output. + self._data.output.clear() + if self._native_grid: + copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) + self._data.output.update(self._grid_output) + else: + self._data.output.update(self._pooled_output) + + def _apply_fixed_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: + if not self.cfg.fixed_software_fov: + return + first_output = next(iter(outputs.values())) + first_tensor = first_output.torch if hasattr(first_output, "torch") else first_output + batch_size = first_tensor.shape[0] + fixation = self._fixed_fov_fixation + if fixation is None: + fixation = self._fixation + if fixation is None: + fixation = torch.zeros( + batch_size, + 2, + device=self._fixed_fov_ray_directions.device, + dtype=self._fixed_fov_ray_directions.dtype, + ) + if self.cfg.field_geometry == "spherical": + valid = self._calibrated_validity(batch_size) + else: + valid = fixed_frustum_validity( + self._fixed_fov_ray_directions, + fixation, + image_height=self._fixed_fov_image_height, + image_width=self._fixed_fov_image_width, + focal_length_px=self._fixed_fov_focal_length_px, + principal_point=( + self._fixed_fov_image_width * 0.5, + self._fixed_fov_image_height * 0.5, + ), + angle_model=self._fixed_fov_angle_model, + image_rotation_deg=self.cfg.image_rotation_deg, + ) + invalid = ~valid[:, :, None, None] + has_rgba_alias = "rgba" in outputs + for name, output in outputs.items(): + if name == "rgb" and has_rgba_alias: + continue + tensor = output.torch if hasattr(output, "torch") else output + tensor.masked_fill_(invalid, 0) + self._fixed_fov_valid_fraction = valid.float().mean(dim=1) + + # ------------------------------------------------------------------ + # Output helpers + # ------------------------------------------------------------------ + + @property + def hfov_rad(self) -> float: + """Horizontal field of view in radians.""" + return self._camera_hfov_rad + + @property + def sampling_coords(self): + """The :class:`SamplingCoords` used for ray generation.""" + return self._sampling_coords + + @property + def image_rotation_deg(self) -> float: + """Pre-render rotation (degrees, CCW around the optical axis) applied + to the per-ray sampling coordinates. ``0`` for the canonical mount.""" + return float(self.cfg.image_rotation_deg) + + @property + def num_valid_samples(self) -> int: + """Number of foveated sample points *N*.""" + return self._num_valid_samples + + @property + def fixed_fov_valid_fraction(self) -> torch.Tensor | None: + """Per-environment fraction of rays inside the fixed dense frustum.""" + return getattr(self, "_fixed_fov_valid_fraction", None) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py new file mode 100644 index 000000000000..28ac77911a91 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py @@ -0,0 +1,156 @@ +# 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 + +"""Foveated ray computation from SamplingCoords. + +Converts fovi's SamplingCoords.cartesian (N, 2) in [-1, 1] into a Warp ray +array suitable for Newton's SensorTiledCamera. The ray array has shape +(camera_count=1, height=N, width=1, 2) where [:, :, :, 0] is origin (always +zero) and [:, :, :, 1] is the normalized direction. + +Supports two projection models: +- ``"pinhole"``: rectilinear projection ``ray_xy = coord * tan(hfov/2)`` +- ``"fisheye_equidistant"``: equidistant fisheye ``θ = r * (hfov/2)`` +""" + +from __future__ import annotations + +import math + +import torch +import warp as wp + + +@wp.kernel(enable_backward=False) +def _fill_foveated_rays( + coords_x: wp.array(dtype=wp.float32), + coords_y: wp.array(dtype=wp.float32), + h_tan: wp.float32, + out_rays: wp.array(dtype=wp.vec3f, ndim=4), +): + """Warp kernel: map fovi (x, y) to OpenGL camera-space ray directions. + + Standard pinhole projection in OpenGL frame (+X=right, +Y=up, -Z=forward): + cart_x → ray_x (horizontal) + cart_y → ray_y (vertical) + """ + i = wp.tid() + x = coords_x[i] + y = coords_y[i] + direction = wp.normalize(wp.vec3f(x * h_tan, y * h_tan, -1.0)) + out_rays[0, i, 0, 0] = wp.vec3f(0.0, 0.0, 0.0) # origin + out_rays[0, i, 0, 1] = direction + + +@wp.kernel(enable_backward=False) +def _fill_foveated_rays_fisheye_equidistant( + coords_x: wp.array(dtype=wp.float32), + coords_y: wp.array(dtype=wp.float32), + half_fov: wp.float32, + out_rays: wp.array(dtype=wp.vec3f, ndim=4), +): + """Warp kernel: equidistant fisheye projection. + + Maps normalized coords to angles linearly: θ = r * half_fov, where + r = sqrt(x² + y²). Unlike pinhole, the z-component varies per ray + (-cos(θ)) and the lateral scaling is sin(θ)/r instead of constant h_tan. + """ + i = wp.tid() + x = coords_x[i] + y = coords_y[i] + r = wp.sqrt(x * x + y * y) + theta = r * half_fov + # sin(theta)/r → half_fov as r → 0 (L'Hôpital) + if r > 1.0e-7: + scale = wp.sin(theta) / r + else: + scale = half_fov + direction = wp.normalize(wp.vec3f(x * scale, y * scale, -wp.cos(theta))) + out_rays[0, i, 0, 0] = wp.vec3f(0.0, 0.0, 0.0) # origin + out_rays[0, i, 0, 1] = direction + + +@wp.kernel(enable_backward=False) +def _fill_explicit_rays( + directions: wp.array(dtype=wp.vec3f), + out_rays: wp.array(dtype=wp.vec3f, ndim=4), +): + i = wp.tid() + out_rays[0, i, 0, 0] = wp.vec3f(0.0, 0.0, 0.0) + out_rays[0, i, 0, 1] = directions[i] + + +def compute_explicit_ray_array( + ray_directions: torch.Tensor, + *, + device: str, +) -> wp.array: + """Build a Newton ray array from explicit normalized camera-space rays.""" + if ray_directions.ndim != 2 or ray_directions.shape[1] != 3: + raise ValueError(f"ray_directions must have shape (N, 3), got {tuple(ray_directions.shape)}.") + directions = wp.from_torch( + ray_directions.contiguous().float(), + dtype=wp.vec3f, + ) + num_rays = ray_directions.shape[0] + out_rays = wp.zeros((1, num_rays, 1, 2), dtype=wp.vec3f, device=device) + wp.launch( + kernel=_fill_explicit_rays, + dim=num_rays, + inputs=[directions, out_rays], + device=device, + ) + return out_rays + + +def compute_foveated_ray_array( + sampling_coords_cartesian: torch.Tensor, + camera_fov_rad: float, + device: str, + projection: str = "pinhole", +) -> wp.array: + """Build a ``(1, N, 1, 2)`` Warp ray array from foveated sample coordinates. + + Args: + sampling_coords_cartesian: ``(N, 2)`` tensor in ``[-1, 1]`` from + :class:`fovi.sensing.coords.SamplingCoords`. Column 0 is the + horizontal (x) coordinate, column 1 is vertical (y). + camera_fov_rad: Horizontal field-of-view of the camera in **radians** + (derived from spawn optics / intrinsic matrix). + device: Warp device string (e.g. ``"cuda:0"``). + projection: Projection model — ``"pinhole"`` (rectilinear) or + ``"fisheye_equidistant"`` (linear angle mapping). + + Returns: + ``wp.array(dtype=vec3f, ndim=4)`` of shape ``(1, N, 1, 2)``. + """ + N = sampling_coords_cartesian.shape[0] + + # Flatten coords to 1-D Warp arrays + coords_x = wp.from_torch(sampling_coords_cartesian[:, 0].contiguous().float(), dtype=wp.float32) + coords_y = wp.from_torch(sampling_coords_cartesian[:, 1].contiguous().float(), dtype=wp.float32) + + out_rays = wp.zeros((1, N, 1, 2), dtype=wp.vec3f, device=device) + + if projection == "pinhole": + h_tan = math.tan(camera_fov_rad / 2.0) + wp.launch( + kernel=_fill_foveated_rays, + dim=N, + inputs=[coords_x, coords_y, h_tan, out_rays], + device=device, + ) + elif projection == "fisheye_equidistant": + half_fov = camera_fov_rad / 2.0 + wp.launch( + kernel=_fill_foveated_rays_fisheye_equidistant, + dim=N, + inputs=[coords_x, coords_y, half_fov, out_rays], + device=device, + ) + else: + raise ValueError(f"Unknown projection {projection!r}. Supported: 'pinhole', 'fisheye_equidistant'.") + + return out_rays diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py new file mode 100644 index 000000000000..941c9c1b4032 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py @@ -0,0 +1,647 @@ +# 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 + +"""RTX foveated tiled camera sensor. + +Subclasses :class:`isaaclab.sensors.Camera` to render foveated images +via the RTX path tracer using ``OmniLensDistortionLutAPI`` textures. +Per-sample values are extracted from the rendered 2D texture to produce +vector ``(B, N, 1, C)`` or upright native-grid ``(B, H, W, C)`` output buffers, +identical to :class:`FoveatedNewtonTiledCamera`. +""" + +from __future__ import annotations + +import logging +import math +import tempfile +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch +import warp as wp +from isaaclab import sim as sim_utils +from isaaclab.sensors.camera.camera import Camera +from isaaclab.utils.math import matrix_from_quat, quat_from_matrix + +from . import generalized_projection as gp +from .calibrated_geometry import compose_rotations, retinal_directions +from .fixed_software_fov import ( + FIXED_FOV_ANGLE_MODELS, + fixed_frustum_validity, + retinal_ray_directions, + validate_fixed_software_fov, +) +from .native_grid import ( + GRID_STYLE, + allocate_grid_outputs, + copy_grid_outputs, + grid_sample_indices, + mask_grid_samples, + native_grid_directions, +) +from .pooling import ( + build_highres_coords, + build_lowres_coords, + build_pooler, + is_segmentation_output, + pool_hwc_buffer, +) +from .virtual_gaze import CalibratedVirtualGaze + +if TYPE_CHECKING: + from isaaclab.renderers.base_renderer import BaseRenderer + + from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + +logger = logging.getLogger(__name__) + + +class FoveatedRTXTiledCamera(CalibratedVirtualGaze, Camera): + """RTX tiled camera that renders with foveated (CMF-distributed) rays. + + Instead of Newton's Warp ray arrays, this sensor creates + ``OmniLensDistortionLutAPI`` Camera prims with LUT textures that define + per-texel ray directions. The RTX path tracer renders a 2D texture + which is then sampled at pre-computed UV positions to extract per-sample + values, producing ``(B, N, 1, C)`` output buffers. + + The cortical disc layout (default) ensures spatial coherence for DLSS + denoising. Camera motion comes from its parent articulation, using + a physical or idealized actuator. + """ + + cfg: FoveatedTiledCameraCfg + + @property + def supports_batch_update(self) -> bool: + return True + + @staticmethod + def _update_buffers_batch_impl(sensors: Sequence[FoveatedRTXTiledCamera]) -> None: + Camera._update_buffers_batch_impl(sensors) + if sim_utils.SimulationContext.instance() is None: + return # The base implementation already invoked scalar capture. + for sensor in sensors: + sensor.process_rendered_frame() + + @property + def renderer(self) -> BaseRenderer: + """Renderer shared with task-owned visual animation bindings.""" + return self._renderer + + def __init__(self, cfg: FoveatedTiledCameraCfg): + if cfg.field_geometry == "spherical": + cfg.update_latest_camera_pose = True + if cfg.camera_fov_deg is not None: + hfov_rad = math.radians(cfg.camera_fov_deg) + aperture = cfg.spawn.horizontal_aperture + cfg.spawn.focal_length = aperture / (2.0 * math.tan(hfov_rad / 2.0)) + self._spawn_focal_length: float = cfg.spawn.focal_length + self._spawn_horizontal_aperture: float = cfg.spawn.horizontal_aperture + self._fixed_fov_fixation: torch.Tensor | None = None + self._fixed_fov_angle_model = "pan_tilt" + self._calibrated_rotation = None + # Texture buffers are owned by the parent ``Camera`` (allocated in + # ``_create_buffers`` and bound to the renderer via ``set_outputs``). + # Foveated / pooled buffers are allocated in ``_initialize_impl`` + # once the texture buffers are known. + self._texture_output: dict[str, torch.Tensor] = {} + self._foveated_output: dict[str, torch.Tensor] = {} + self._pooled_output: dict[str, torch.Tensor] | None = None + if cfg.renderer_cfg.renderer_type == "ovrtx": + self.cfg = cfg + self._prepare_projection() + super().__init__(cfg) + if cfg.renderer_cfg.renderer_type == "ovrtx": + for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): + gp.apply_generalized_projection_to_prim(prim, self._dir_tex_path, self._exit_tex_path) + + # ------------------------------------------------------------------ + # Initialisation + # ------------------------------------------------------------------ + + def _prepare_projection(self) -> None: + # 1. Derive camera physical FOV. + self._camera_hfov_rad = 2.0 * math.atan(self._spawn_horizontal_aperture / (2.0 * self._spawn_focal_length)) + self._camera_hfov_deg = math.degrees(self._camera_hfov_rad) + self._fixed_fov_focal_length_px: float | None = None + self._fixed_fov_image_height: int | None = None + self._fixed_fov_image_width: int | None = None + if self.cfg.fixed_software_fov: + if self.cfg.projection != "pinhole" and self.cfg.field_geometry != "spherical": + raise ValueError( + f"fixed_software_fov currently requires projection='pinhole', got {self.cfg.projection!r}." + ) + image_height = self.cfg.software_fov_image_height + image_width = self.cfg.software_fov_image_width + if image_height is None or image_width is None: + raise ValueError( + "fixed_software_fov=True requires software_fov_image_height and software_fov_image_width." + ) + focal_length_px = image_width * self._spawn_focal_length / self._spawn_horizontal_aperture + validate_fixed_software_fov( + image_height=image_height, + image_width=image_width, + focal_length_px=focal_length_px, + principal_point=(image_width * 0.5, image_height * 0.5), + retinal_window_short_side_fraction=(self.cfg.retinal_window_short_side_fraction), + retinal_window_reference_side=self.cfg.retinal_window_reference_side, + ) + self._fixed_fov_focal_length_px = focal_length_px + self._fixed_fov_image_height = image_height + self._fixed_fov_image_width = image_width + + # 2. Build coords on CPU. The LUT textures + UV extraction use the + # *rendered* grid (highres when pooling, else lowres). The + # public `sampling_coords` property stays on the lowres / RGC grid. + self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") + self._sampling_coords_highres = build_highres_coords( + self.cfg, + matched_res, + device="cpu", + ) + ray_coords = self._sampling_coords_highres or self._sampling_coords + self._ray_coords = ray_coords + self._native_grid = self.cfg.foveated_style == GRID_STYLE + + self._num_valid_samples = len(self._sampling_coords) # public / RGC count + self._num_ray_samples = len(ray_coords) # rendered ray count + N = self._num_ray_samples + + # 3. Compute ray directions and UV mapping from the rendered grid. + # Apply optional image-space rotation (``cfg.image_rotation_deg``) by + # rotating the per-ray polar angle ``theta`` around the optical axis + # *before* computing the ray directions. This undoes a physical + # mount rotation of the camera prim while keeping the per-sample + # index ordering identical to the canonical ``SamplingCoords`` — so + # the agent's foveator (and the foveated scatter plot) read out the + # same upright scene at every sample position. A post-render + # ``torch.flip`` would reshuffle the sample order and corrupt the + # downstream visualization / KNN mapping; this rotation is the + # foveated-camera-native analogue of that flip. + theta_rad = ray_coords.polar[:, 1].to(torch.float64) + if self.cfg.image_rotation_deg: + theta_rad = theta_rad + math.radians(float(self.cfg.image_rotation_deg)) + if self._native_grid: + tangent_scale = math.tan(self._camera_hfov_rad / 2) + if self.cfg.fixed_software_fov: + reference = ( + max(self._fixed_fov_image_height, self._fixed_fov_image_width) + if self.cfg.retinal_window_reference_side == "long" + else min(self._fixed_fov_image_height, self._fixed_fov_image_width) + ) + tangent_scale = ( + reference * self.cfg.retinal_window_short_side_fraction / (2 * self._fixed_fov_focal_length_px) + ) + self._native_tangent_scale = tangent_scale + dirs = native_grid_directions( + ray_coords, + tangent_scale=tangent_scale, + image_rotation_deg=self.cfg.image_rotation_deg, + projection=self.cfg.projection, + camera_fov_rad=self._camera_hfov_rad, + ) + self._fixed_fov_ray_directions_cpu = dirs + elif self.cfg.field_geometry == "spherical": + dirs = retinal_directions(ray_coords.cartesian, ray_coords.fov, self.cfg.image_rotation_deg) + self._fixed_fov_ray_directions_cpu = dirs + elif self.cfg.fixed_software_fov: + dirs = retinal_ray_directions( + ray_coords.cartesian, + image_height=self._fixed_fov_image_height, + image_width=self._fixed_fov_image_width, + focal_length_px=self._fixed_fov_focal_length_px, + retinal_window_short_side_fraction=(self.cfg.retinal_window_short_side_fraction), + retinal_window_reference_side=self.cfg.retinal_window_reference_side, + image_rotation_deg=self.cfg.image_rotation_deg, + ) + self._fixed_fov_ray_directions_cpu = dirs + else: + r_deg = ray_coords.polar[:, 0].to(torch.float64) * (self._camera_hfov_deg / 2.0) + dirs = gp.ray_directions_rectilinear(r_deg, theta_rad, device="cpu") + + # 4. Texture dimensions and UV layout. + # UV mapping uses fov=1 normalized space (matching the profiling + # script and SamplingCoords convention). Ray directions use + # physical degrees for correct pinhole projection. + if self.cfg.ndc_layout == "native_grid": + tw = th = ray_coords.resolution + axis = (torch.arange(tw, dtype=torch.float32) + 0.5) / tw + row, col = torch.meshgrid(axis, axis, indexing="ij") + uv = torch.stack((col, row), -1).reshape(-1, 2) + elif self.cfg.ndc_layout == "cortical_disc": + tw = th = max(64, math.ceil(math.sqrt(4 * N / math.pi))) + r_norm = ray_coords.polar[:, 0].to(torch.float64) * 0.5 + uv = gp.samples_uv_cortical_disc( + r_norm, + theta_rad, + 1.0, + self.cfg.cmf_a, + device="cpu", + ) + else: + raise ValueError(f"Unknown ndc_layout: {self.cfg.ndc_layout!r}") + + self._texture_width = tw + self._texture_height = th + self._sample_uv = uv # (N, 2) float32 + + # 5. Build and save LUT textures. + # The exit texture is an octahedral inverse map (ray direction → sensor NDC). + # It covers the full hemisphere, but only the fraction within the camera + # FOV is populated. The resolution must be high enough that each foveated + # sample maps to a distinct exit texel within that fraction. Scaling as + # 4× the direction texture dimension gives ~16× the texel count, which + # provides sufficient angular oversampling for the NN lookup. + if self.cfg.exit_texture_size is not None: + EW = EH = self.cfg.exit_texture_size + else: + EW = EH = max(128, 4 * max(tw, th)) + if self._native_grid: + dir_tex, exit_tex = gp.build_native_grid_textures( + ray_coords, + tangent_scale=self._native_tangent_scale, + image_rotation_deg=self.cfg.image_rotation_deg, + exit_size=EW, + projection=self.cfg.projection, + camera_fov_rad=self._camera_hfov_rad, + ) + else: + dir_tex, exit_tex = gp.build_generalized_projection_textures( + uv, + dirs, + tw, + th, + EW, + EH, + device="cpu", + ) + self._lut_tmpdir = tempfile.mkdtemp(prefix="rtx_foveated_luts_") + self._dir_tex_path, self._exit_tex_path = gp.save_generalized_projection_textures( + dir_tex, + exit_tex, + self._lut_tmpdir, + "foveated", + ) + + pool_line = ( + f" Pool: mode={self.cfg.pool_mode} " + f"N_hi={self._num_ray_samples} -> N_lo={self._num_valid_samples}\n" + if self.cfg.pool_enabled + else "" + ) + print( + f"\n{'=' * 60}\n" + f" FoveatedRTXTiledCamera\n" + f" HFOV: {self._camera_hfov_deg:.1f}°\n" + f" Samples: N={self._num_valid_samples}\n" + f" Texture: {tw}x{th}\n" + f" Exit LUT: {EW}x{EH}\n" + f" Layout: {self.cfg.ndc_layout}\n" + f" cmf_a_frac: {self.cfg.cmf_a}\n" + f" Style: {self.cfg.foveated_style}\n" + f"{pool_line}" + f" LUT dir: {self._lut_tmpdir}\n" + f"{'=' * 60}\n" + ) + + # 6. Set texture dimensions so parent allocates (B, th, tw, C) buffers. + self.cfg.height = th + self.cfg.width = tw + + def _initialize_impl(self) -> None: + if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": + self._prepare_projection() + tw, th = self._texture_width, self._texture_height + # Author the lens before Camera prepares the renderer's stage. OVRTX + # snapshots a detached stage, so later USD edits would miss its cameras. + for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): + gp.apply_generalized_projection_to_prim( + prim, + direction_texture_path=self._dir_tex_path, + exit_texture_path=self._exit_tex_path, + ) + + # 8. Run parent initialisation (creates renderer, buffers, etc.). + super()._initialize_impl() + + # OVRTX owns its runtime; Kit extensions belong only to Isaac RTX. + if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": + try: + import omni.kit.app + + ext_manager = omni.kit.app.get_app().get_extension_manager() + for ext_name in ("omni.sensors.nv.common", "omni.sensors.nv.camera"): + try: + ext_manager.set_extension_enabled_immediate(ext_name, True) + except Exception: + pass + except ImportError: + pass + + # Moving-gaze DLSS quality still needs validation with native LUTs; + # geometry smoke tests disable temporal accumulation. + + # 10. Pre-compute extraction indices and build the pooler. The + # parent ``Camera._create_buffers`` (called from super + # ``_initialize_impl``) has already allocated the per-data-type + # ``(B, H, W, C)`` texture tensors as ``self._data.output`` and + # bound them to the renderer via ``set_outputs``. We snapshot + # them as ``_texture_output`` (same dict reference, so the + # renderer keeps writing to it across frames) and allocate the + # foveated / pooled output buffers from those shapes. Then we + # point ``self._data.output`` at the foveated/pooled dict so + # downstream consumers see the per-sample buffers. + self._sampling_coords = self._sampling_coords.to(device=self._device) + if self.cfg.fixed_software_fov: + self._fixed_fov_ray_directions = self._fixed_fov_ray_directions_cpu.to(self._device) + if self._sampling_coords_highres is not None: + self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) + self._ray_coords = self._sampling_coords_highres or self._sampling_coords + self._initialize_calibrated_gaze() + if self.cfg.field_geometry == "spherical": + _, local_orientation = self._view.get_local_poses() + self._calibrated_base_local_orientation = matrix_from_quat(local_orientation.torch).clone() + + # Build the pooler on the sensor device (so knn tensors live there). + # A second max-mode pooler is built inside ``_allocate_foveated_buffers`` + # if any integer-valued output buffers are present (segmentation IDs). + self._pooler, self._pool_k = build_pooler( + self.cfg, + self._sampling_coords, + self._sampling_coords_highres, + device=str(self._device), + ) + self._pooler_int = None + + uv_gpu = self._sample_uv.to(self._device) + self._extract_px = (uv_gpu[:, 0] * tw).long().clamp(0, tw - 1) + self._extract_py = (uv_gpu[:, 1] * th).long().clamp(0, th - 1) + + # Capture the renderer-bound texture dict and allocate foveated / + # pooled output buffers. + self._texture_output = self._data.output + self._allocate_foveated_buffers() + # Expose foveated (or pooled) buffers as the public output. + # IsaacLab 3.0 made ``CameraData.output`` a read-only property; set + # the private ``_output`` backing field directly. Downstream + # readers (``CameraNode._read_rgb_raw`` etc.) just dict-index + # ``camera.data.output[name]`` and pass the value through + # ``_camera_output_to_torch``, which handles plain torch tensors + # natively — the renderer still writes to the original + # ProxyArray-backed buffers via the ``set_outputs`` binding done + # by the parent ``_create_buffers``. + new_output = self._pooled_output if self._pooled_output is not None else self._foveated_output + if self._native_grid: + self._grid_output = allocate_grid_outputs(new_output, self._sampling_coords) + self._grid_indices = grid_sample_indices(self._sampling_coords) + new_output = self._grid_output + try: + self._data._output = new_output + except AttributeError: + # Older IsaacLab where ``output`` was a writable attribute. + self._data.output = new_output + + logger.info( + "FoveatedRTXTiledCamera: %d samples, %dx%d texture, layout=%s", + self._num_ray_samples, + tw, + th, + self.cfg.ndc_layout, + ) + + def _allocate_foveated_buffers(self): + """Allocate ``(B, N_hi, 1, C)`` (and optionally ``(B, N_lo, 1, C)``) + per-data-type buffers from the captured ``_texture_output`` shapes. + + Called once from :meth:`_initialize_impl` after the parent ``Camera`` + has allocated the texture buffers. + """ + N = self._num_ray_samples + has_rgba_alias = "rgba" in self._texture_output + self._foveated_output = {} + for name, buf in self._texture_output.items(): + if name == "rgb" and has_rgba_alias: + continue # handled via rgba alias below + # IsaacLab 3.0: ``_data.output[name]`` is a ``ProxyArray`` + # wrapping a Warp array, not a torch tensor. ``buf.dtype`` is + # a Warp dtype (a Python class), incompatible with + # ``torch.zeros(dtype=...)``. Go through ``.torch`` to get + # a torch view whose dtype / device are torch-native. + buf_t = buf.torch if hasattr(buf, "torch") else buf + C = buf_t.shape[-1] + self._foveated_output[name] = torch.zeros( + (self._view.count, N, 1, C), + device=buf_t.device, + dtype=buf_t.dtype, + ).contiguous() + if "rgba" in self._foveated_output and "rgb" in self.cfg.data_types: + self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] + + if self._pooler is not None: + self._pooled_output = {} + needs_int_pooler = False + for name, buf in self._foveated_output.items(): + if name == "rgb" and has_rgba_alias: + continue + self._pooled_output[name] = torch.zeros( + (self._view.count, self._num_valid_samples, 1, buf.shape[-1]), + device=self._device, + dtype=buf.dtype, + ).contiguous() + if is_segmentation_output(name) and self.cfg.pool_int_mode != self.cfg.pool_mode: + needs_int_pooler = True + if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: + self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] + if needs_int_pooler: + self._pooler_int, _ = build_pooler( + self.cfg, + self._sampling_coords, + self._sampling_coords_highres, + device=str(self._device), + mode=self.cfg.pool_int_mode, + ) + logger.info( + "FoveatedRTXTiledCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", + self.cfg.pool_mode, + self._pool_k, + self.cfg.pool_sample_cortex, + self._num_ray_samples, + self._num_valid_samples, + ) + else: + self._pooled_output = None + + # ------------------------------------------------------------------ + # Per-frame overrides + # ------------------------------------------------------------------ + + def set_calibrated_fixation(self, fixation: torch.Tensor, env_ids: torch.Tensor | None = None) -> None: + super().set_calibrated_fixation(fixation, env_ids=env_ids) + self._write_calibrated_local_pose(env_ids) + + def set_calibrated_angles(self, angles: torch.Tensor) -> None: + super().set_calibrated_angles(angles) + self._write_calibrated_local_pose() + + def _write_calibrated_local_pose(self, env_ids: torch.Tensor | None = None) -> None: + # Replicator reads camera prims, not update_camera's pose arguments. + # Write when the command arrives, before a visualizer can render the step. + # The saved local base prevents accumulation and preserves parent motion. + basis = self._calibrated_basis + with torch.autocast(basis.device.type, enabled=False): + relative = compose_rotations(compose_rotations(basis, self._calibrated_rotation), basis.T) + local_orientation = quat_from_matrix(compose_rotations(self._calibrated_base_local_orientation, relative)) + if env_ids is None: + self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f)) + else: + self._view.set_local_poses( + orientations=wp.from_torch(local_orientation[env_ids].contiguous(), dtype=wp.vec4f), + indices=wp.from_torch(env_ids.to(dtype=torch.int32).contiguous()), + ) + + def set_fixed_fov_fixation( + self, + fixation_angles: torch.Tensor, + *, + angle_model: str, + ) -> None: + """Update fixed-frustum masking without changing the camera pose.""" + if not self.cfg.fixed_software_fov: + raise RuntimeError("set_fixed_fov_fixation requires fixed_software_fov=True.") + if angle_model not in FIXED_FOV_ANGLE_MODELS: + raise ValueError(f"angle_model must be one of {FIXED_FOV_ANGLE_MODELS}, got {angle_model!r}.") + self._fixed_fov_fixation = fixation_angles + self._fixed_fov_angle_model = angle_model + + def _update_buffers_impl(self, env_mask: wp.array): + if not self._env_mask_has_any(env_mask): + return + + # The renderer was bound to ``self._texture_output`` at create time + # via ``set_outputs`` and continues to write per-env pixel data into + # that dict regardless of what ``self._data.output`` currently + # references. ``self._data.output`` already points at the foveated + # (or pooled) buffer dict; the parent's ``render_into_camera`` only + # uses ``camera_data`` to populate ``camera_data.info`` (now a flat + # ``dict[str, Any]``), so we don't need to swap anything. + super()._update_buffers_impl(env_mask) + self.process_rendered_frame() + + def process_rendered_frame(self) -> None: + """Extract, mask and pool the frame written by scalar or batched rendering.""" + if not self._env_mask_has_any(self._is_outdated): + return + # Extract per-sample values from the per-env texture buffer. + self._extract_foveated_samples() + if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self._foveated_output: + # OVRTX's LUT range AOV measures from the near-clipped ray origin. + self._foveated_output["distance_to_camera"].add_(self.cfg.spawn.clipping_range[0]) + mask_grid_samples(self._foveated_output, self._ray_coords) + self._apply_fixed_fov_mask() + + # Optionally KNN-pool highres -> lowres samples. Integer-dtype + # outputs (segmentation class IDs) use the dedicated max-mode + # pooler so pooled values stay valid IDs. + if self._pooler is not None and self._pooled_output is not None: + has_rgba_alias = "rgba" in self._foveated_output + for name, hi in self._foveated_output.items(): + if name == "rgb" and has_rgba_alias: + continue # alias — refreshed below + lo = self._pooled_output[name] + use_int_pool = self._pooler_int is not None and is_segmentation_output(name) + pooler = self._pooler_int if use_int_pool else self._pooler + pooled = pool_hwc_buffer(pooler, hi.float()) + lo.copy_(pooled.to(lo.dtype)) + if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: + self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] + if self._native_grid: + source = self._pooled_output if self._pooled_output is not None else self._foveated_output + copy_grid_outputs(source, self._grid_output, self._grid_indices) + + def _extract_foveated_samples(self): + """Extract per-sample values from rendered 2D textures into (B, N, 1, C) buffers.""" + px = self._extract_px + py = self._extract_py + has_rgba_alias = "rgba" in self._texture_output + for name in self._texture_output: + if name == "rgb" and has_rgba_alias: + continue # handled via rgba alias below + tex = self._texture_output[name] # (B, th, tw, C) + fov = self._foveated_output[name] # (B, N, 1, C) + if self._native_grid: + tensor = tex.torch if hasattr(tex, "torch") else tex + fov.copy_(tensor.reshape_as(fov)) + else: + fov[:, :, 0, :] = tex[:, py, px, :] + if "rgba" in self._foveated_output and "rgb" in self.cfg.data_types: + self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] + + def _apply_fixed_fov_mask(self) -> None: + if not self.cfg.fixed_software_fov: + return + batch_size = next(iter(self._foveated_output.values())).shape[0] + fixation = self._fixed_fov_fixation + if fixation is None: + fixation = torch.zeros( + batch_size, + 2, + device=self._fixed_fov_ray_directions.device, + dtype=self._fixed_fov_ray_directions.dtype, + ) + if self.cfg.field_geometry == "spherical": + valid = self._calibrated_validity(batch_size) + else: + valid = fixed_frustum_validity( + self._fixed_fov_ray_directions, + fixation, + image_height=self._fixed_fov_image_height, + image_width=self._fixed_fov_image_width, + focal_length_px=self._fixed_fov_focal_length_px, + principal_point=( + self._fixed_fov_image_width * 0.5, + self._fixed_fov_image_height * 0.5, + ), + angle_model=self._fixed_fov_angle_model, + image_rotation_deg=self.cfg.image_rotation_deg, + ) + invalid = ~valid[:, :, None, None] + has_rgba_alias = "rgba" in self._foveated_output + for name, output in self._foveated_output.items(): + if name == "rgb" and has_rgba_alias: + continue + output.masked_fill_(invalid, 0) + self._fixed_fov_valid_fraction = valid.float().mean(dim=1) + + # ------------------------------------------------------------------ + # Output helpers + # ------------------------------------------------------------------ + + @property + def hfov_rad(self) -> float: + """Horizontal field of view in radians.""" + return self._camera_hfov_rad + + @property + def sampling_coords(self): + """The :class:`SamplingCoords` used for ray generation.""" + return self._sampling_coords + + @property + def image_rotation_deg(self) -> float: + """Pre-render rotation (degrees, CCW around the optical axis) applied + to the per-ray sampling coordinates. ``0`` for the canonical mount.""" + return float(self.cfg.image_rotation_deg) + + @property + def num_valid_samples(self) -> int: + """Number of foveated sample points *N*.""" + return self._num_valid_samples + + @property + def fixed_fov_valid_fraction(self) -> torch.Tensor | None: + """Per-environment fraction of rays inside the fixed dense frustum.""" + return getattr(self, "_fixed_fov_valid_fraction", None) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py new file mode 100644 index 000000000000..6e50a75b9222 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py @@ -0,0 +1,206 @@ +# 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 + +"""Configuration for the FoveatedTiledCamera sensor.""" + +from __future__ import annotations + +from fovi.sensing.projection import CameraCalibration +from isaaclab.sensors.camera.camera_cfg import CameraCfg +from isaaclab.utils.configclass import configclass + +from isaaclab_fovi.sensors.native_grid import validate_radius_norm + + +@configclass +class FoveatedTiledCameraCfg(CameraCfg): + """Configuration for a foveated tiled camera sensor. + + Extends :class:`CameraCfg` with CMF-based foveation parameters. + The sensor generates non-uniform foveated rays from + :class:`fovi.sensing.coords.SamplingCoords`. ``height`` and ``width`` + are auto-computed from the number of sampling coordinates. + + The actual camera class (Newton or RTX) is resolved at runtime by the + :func:`isaaclab_fovi.sensors.FoveatedTiledCamera` factory based on + ``renderer_cfg.renderer_type``. + """ + + class_type: type | str = "isaaclab_fovi.sensors:FoveatedTiledCamera" + + # -- Foveation parameters (no img_height/img_width/fixation_size) -------- + + cmf_a: float = 0.1 + """Normalized CMF parameter relative to the selected field diameter. + Smaller values give stronger foveation. The public fovi API instead takes + an angular cmf_a; sampling_geometry performs that conversion once.""" + + cmf_a_frac: float | None = None + """Normalized CMF parameter (= cmf_a / fov). If set, ``cmf_a`` is + ignored. Planar sampling uses fov=1; spherical sampling resolves degrees + from the calibrated retinal window before scaling this fraction.""" + + field_geometry: str = "planar" + camera_calibration: CameraCalibration | None = None + """CameraModel fields for the physical source image; required for spherical geometry.""" + + foveated_res: int = 60 + """Resolution parameter passed to :class:`SamplingCoords`. For isotropic + sampling this is the number of radial rings; the total sample count *N* + depends on ``(fov, cmf_a, foveated_res)``.""" + + foveated_style: str = "isotropic" + """Sampling style passed to :class:`SamplingCoords`. Supported values + include ``"isotropic"``, ``"logpolar"``, ``"uniform"``, etc.""" + + fov_type: str = "circular" + """Visual footprint; circular is the default for native warped grids.""" + + radius_norm: float = 2.0 + """Warped-Cartesian shell norm: 2.0 for circular shells, infinity for square shells.""" + + isotropic_plotting_type: str = "v1like" + """Plotting-space mapping passed to :class:`SamplingCoords` for isotropic + sampling. Must match the resolved retinal transform so the camera rays + and policy-side coordinate grids agree on cortical-space geometry. Supported values: + ``"v1like"`` (default in :class:`SamplingCoords`), ``"schwartz"``, ``"warp"``. + Ignored for non-isotropic ``foveated_style``.""" + + image_rotation_deg: float = 0.0 + """Rotation (degrees, counter-clockwise) applied to the foveated ray + directions around the optical axis BEFORE rendering. Used to undo a + physical camera mount rotation (e.g. an upside-down right-eye sensor) + so that the per-ray samples land in the canonical + :class:`SamplingCoords` order — i.e. sample ``i`` always corresponds to + visual-field position ``rel_cart_coords[i]`` regardless of how the + camera prim is oriented in world. General-purpose alternative to + post-render ``torch.flip`` (which would shuffle the sample order and + misalign with retinal scatter and KNN processing). + + Common values: + * ``0.0`` — no rotation (default; right-side-up sensor). + * ``180.0`` — flip vertically + horizontally (upside-down sensor). + * Other angles work in principle but are untested.""" + + projection: str = "pinhole" + """Projection model for mapping normalized coords to ray directions. + ``"pinhole"`` (rectilinear) or ``"fisheye_equidistant"`` (linear angle + mapping, suitable for wide FOV).""" + + camera_fov_deg: float | None = None + """If set, use this as the camera HFOV (in degrees) instead of deriving + from ``spawn.focal_length`` and ``spawn.horizontal_aperture``. When this + is not None, ``spawn.focal_length`` and ``spawn.horizontal_aperture`` + must be left at their defaults (they will be back-computed automatically + for USD prim compatibility).""" + + fixed_software_fov: bool = False + """Mask pose-steered rays against a fixed dense pinhole camera frustum.""" + + software_fov_image_height: int | None = None + """Dense camera image height used by the deployment software sampler.""" + + software_fov_image_width: int | None = None + """Dense camera image width used by the deployment software sampler.""" + + retinal_window_short_side_fraction: float = 1.0 + """Diameter scale applied to the selected image reference side.""" + + retinal_window_reference_side: str = "short" + """Image side defining the circular retinal diameter: ``short`` or ``long``.""" + + # -- Optional retinal pooling (photoreceptor -> RGC two-layer sampling) -- + + pool_enabled: bool = False + """If True, the sensor fires a *highres* (photoreceptor) ray grid and + pools it down to the regular foveated grid. Default False keeps the single- + layer behaviour unchanged.""" + + pool_res_mult: float = 2 + """Resolution multiplier for the highres photoreceptor ray grid. The + highres :class:`SamplingCoords` uses + ``res = round(pool_res_mult * matched_res)`` with the **same** ``cmf_a`` + as the lowres (output) grid so both layers share the same cortical + magnification profile. Fractional values are allowed — e.g. + ``pool_res_mult = sqrt(2)`` gives ~2× input-to-output sample ratio, since + total sample count scales with ``res²`` in isotropic sampling.""" + + pool_k: int | None = None + """Pooling neighborhood size. ``_as_grid`` sensors use 2D pooling, where + ``pool_k`` is the squared kernel side (a perfect square) and None uses the + squared high/low resolution ratio. Sample-set sensors use KNN, where None + uses the rounded sample-count ratio.""" + + pool_mode: str = "avg" + """Retinal pooling mode. ``"avg"`` or ``"gaussian"``.""" + + pool_sample_cortex: bool | str = "geodesic" + """Space in which KNN neighbours are selected. ``True`` = Euclidean on + cortical manifold, ``False`` = visual field, ``"geodesic"`` = exact + geodesic cortical distances (slower at init, most faithful).""" + + pool_gauss_sigma: float = 10.0 + """Gaussian sigma for ``pool_mode="gaussian"``. Unused otherwise.""" + + pool_int_mode: str = "max" + """Pool mode used for outputs whose key name contains ``"segmentation"`` + (``semantic_segmentation``, ``instance_segmentation_fast``, + ``instance_id_segmentation_fast``). Averaging segmentation values blurs + class labels and breaks downstream integer/equality checks, so these + outputs get a separate pooler with this mode. Set equal to ``pool_mode`` + to disable this behaviour.""" + + # -- RTX-specific parameters (ignored by Newton backend) ---------------- + + tiled: bool = True + """Use a shared tiled RTX render product across environments. + + Non-tiled foveated RTX rendering is not implemented and selecting it + raises :class:`NotImplementedError`. Ignored by Newton backend. + """ + + ndc_layout: str = "cortical_disc" + """RTX texture layout: ``cortical_disc`` or warped Cartesian ``native_grid``. + + Row-major packing breaks spatial filtering and is no longer accepted. + Newton does not use a texture layout. + """ + + exit_texture_size: int | None = None + """Dimension of the exit (inverse) LUT texture (EW = EH) for RTX rendering. + If ``None`` (default), computed as ``max(128, 4 * tw)`` where ``tw`` is the + direction texture dimension — this ensures the octahedral inverse map has + sufficient angular resolution to distinguish individual foveated samples. + Ignored by Newton backend.""" + + # height / width are set automatically in _initialize_impl before the + # parent allocates buffers. We default them to 1 here so the MISSING + # sentinel from CameraCfg is satisfied at config-validation time. + width: int = 1 + height: int = 1 + + # Enable per-frame pose updates so fixation rotation is applied each step. + update_latest_camera_pose: bool = True + + def __post_init__(self): + if self.ndc_layout not in ("cortical_disc", "native_grid"): + raise ValueError( + f"Unsupported ndc_layout={self.ndc_layout!r}; use 'cortical_disc' or 'native_grid'. " + "Row-major packing is no longer supported because it breaks spatial filtering." + ) + if self.ndc_layout == "native_grid" and self.foveated_style != "warped_cartesian_as_grid": + raise ValueError("native_grid requires a Cartesian grid foveated_style.") + if self.foveated_style == "warped_cartesian_as_grid" and self.ndc_layout != "native_grid": + raise ValueError(f"{self.foveated_style} requires ndc_layout='native_grid'.") + validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) + # ``spawn`` is a ``PinholeCameraCfg`` / ``FisheyeCameraCfg`` whose + # ``lock_camera`` field defaults to True. That writes + # ``omni:kit:cameraLock=True`` on every spawned prim, which the RTX + # renderer can interpret as "static camera" and use to skip motion- + # vector synthesis — breaking DLSS-RR temporal reprojection on dynamic + # geometry. Foveated cameras always have a moving fixation pose, so + # we force the lock off here. + if self.spawn is not None and getattr(self.spawn, "lock_camera", None): + self.spawn = self.spawn.replace(lock_camera=False) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py new file mode 100644 index 000000000000..e80332b1904b --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py @@ -0,0 +1,424 @@ +# 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 + +# Copyright (c) 2024-2026, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + +""" +Utilities for building generalised-projection (LUT-based) foveated camera +models compatible with OmniLensDistortionLutAPI (Omniverse / Isaac Sim). + +A generalised-projection sensor is defined by two HDR textures attached to a +camera prim: + +* **rayEnterDirectionTexture** ``(H × W, RGB float32)`` + Maps each sensor texel NDC ``(u, v)`` → unit ray direction in camera space. + +* **rayExitPositionTexture** ``(EW × EH, RG float32)`` + Inverse map: given a ray direction (octahedral-encoded over ``[0,1]²``), + returns the sensor NDC ``(u, v)`` of the nearest sample. + +Ported from ``fovi-rtx/generalized_projection.py`` — contains only the +subset of functions required by :class:`FoveatedRTXTiledCamera`. + +Coordinate conventions: + +* **Camera space**: X right, Y up, −Z forward (OpenGL / USD). + Spherical grid padding may extend behind the optical hemisphere. +* **NDC**: ``u ∈ [0,1]`` = column (left → right), + ``v ∈ [0,1]`` = row (top → bottom). +""" + +from __future__ import annotations + +import math +import os +from typing import Tuple + +# Must be set before cv2 is first imported anywhere in the process. +os.environ.setdefault("OPENCV_IO_ENABLE_OPENEXR", "1") + +import numpy as np +import torch +from fovi.sensing.coords import SamplingCoords +from fovi.sensing.projection import CameraModel + +from .dense_calibrated_geometry import dense_camera_rays +from .native_grid import native_grid_directions, native_grid_exit_uv + +# ── Optional dependencies ──────────────────────────────────────────────────── +try: + import Imath + import OpenEXR +except ImportError: + OpenEXR = Imath = None # type: ignore + +try: + from pxr import Sdf, Usd, UsdGeom +except ImportError: + Sdf = Usd = UsdGeom = None # type: ignore + + +# ============================================================================= +# Internal helpers +# ============================================================================= + + +def _t(x, dtype: torch.dtype, device) -> torch.Tensor: + """Convert array-like or tensor *x* to a ``torch.Tensor`` on *device*.""" + if isinstance(x, torch.Tensor): + return x.to(dtype=dtype, device=device) + return torch.as_tensor(np.asarray(x), dtype=dtype, device=device) + + +# ============================================================================= +# EXR I/O +# ============================================================================= + + +def save_exr(path: str, data: torch.Tensor) -> None: + """Save a ``(H, W, C)`` float32 tensor to an EXR file (C ∈ {2, 3}). + + Uses **OpenEXR** when available; falls back to **OpenCV** otherwise. + """ + arr = np.ascontiguousarray(data.detach().cpu().numpy(), dtype=np.float32) + h, w, c = arr.shape + if c not in (2, 3): + raise ValueError(f"save_exr: expected 2 or 3 channels, got {c}") + + if OpenEXR is not None and Imath is not None: + names = ("R", "G") if c == 2 else ("R", "G", "B") + ch_t = Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT)) + hdr = OpenEXR.Header(w, h) + hdr["Compression"] = Imath.Compression.ZIP_COMPRESSION + hdr["channels"] = {n: ch_t for n in names} + exr = OpenEXR.OutputFile(path, hdr) + exr.writePixels({n: arr[:, :, i].tobytes() for i, n in enumerate(names)}) + exr.close() + return + + try: + import cv2 + + flags = [cv2.IMWRITE_EXR_TYPE, cv2.IMWRITE_EXR_TYPE_FLOAT] + if c == 2: + img = np.concatenate([np.zeros((h, w, 1), dtype=np.float32), arr[:, :, ::-1]], axis=2) + else: + img = arr[:, :, ::-1] + if not cv2.imwrite(path, img, flags): + raise RuntimeError(f"OpenCV failed to write EXR: {path}") + return + except ImportError: + pass + + raise RuntimeError( + "Neither OpenEXR nor OpenCV is installed. " + "Install one: conda install -c conda-forge openexr or pip install opencv-python" + ) + + +# ============================================================================= +# Octahedral decoding (internal) +# ============================================================================= + + +def _octahedral_decode( + width: int, + height: int, + device="cuda", +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Decode octahedral-LUT texel centres to unit directions (camera −Z convention). + + Returns: + Three ``(height, width)`` float64 tensors ``(dx, dy, dz)``. + """ + u = (torch.arange(width, dtype=torch.float64, device=device) + 0.5) / width + v = (torch.arange(height, dtype=torch.float64, device=device) + 0.5) / height + px = u.unsqueeze(0).expand(height, width) * 2.0 - 1.0 + py = v.unsqueeze(1).expand(height, width) * 2.0 - 1.0 + dz = 1.0 - px.abs() - py.abs() + sx = torch.sign(px) + sy = torch.sign(py) + dx = torch.where(dz <= 0.0, (1.0 - py.abs()) * sx, px) + dy = torch.where(dz <= 0.0, (1.0 - px.abs()) * sy, py) + n = torch.clamp((dx**2 + dy**2 + dz**2).sqrt(), min=1e-20) + return dx / n, dy / n, -dz / n + + +# ============================================================================= +# Nearest-neighbour search +# ============================================================================= + + +def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tensor: + """Chunked nearest-neighbour search via ``torch.cdist``. + + Chunk size is capped so the float32 distance matrix stays within 2 GiB. + + Returns: + ``(M,)`` int64 index of the closest key for each query row. + """ + N = keys.shape[0] + safe_chunk = max(1, (2 << 30) // (4 * max(N, 1))) + effective = min(chunk, safe_chunk) + M = query.shape[0] + idx = torch.empty(M, dtype=torch.long, device=query.device) + for s in range(0, M, effective): + e = min(s + effective, M) + idx[s:e] = torch.cdist(query[s:e], keys).argmin(dim=1) + return idx + + +# ============================================================================= +# Core LUT tensor builders +# ============================================================================= + + +def build_dense_calibrated_textures(camera: CameraModel, *, exit_size: int) -> tuple[torch.Tensor, torch.Tensor]: + """Build physical-lens direction texels and an analytic octahedral inverse map. + + Direction texels use OpenCV integer pixel centers. The inverse map converts + those coordinates to half-integer normalized texture coordinates; rays + outside the calibrated raster, image circle, or angular domain map to -1. + """ + directions, _ = dense_camera_rays(camera) + decoded = torch.stack(_octahedral_decode(exit_size, exit_size, device="cpu"), -1) + pixels, valid = camera.project(decoded * decoded.new_tensor((1, -1, -1))) + height, width = camera.image_size + uv = ((pixels + 0.5) / pixels.new_tensor((width, height))).float() + exit_texture = torch.where(valid[..., None], uv, torch.full_like(uv, -1)) + return directions, exit_texture + + +def build_native_grid_textures( + coords: SamplingCoords, + *, + tangent_scale: float, + image_rotation_deg: float, + exit_size: int, + projection: str = "pinhole", + camera_fov_rad: float | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Build native direction texels and an analytic octahedral inverse map.""" + directions = native_grid_directions( + coords, + tangent_scale=tangent_scale, + image_rotation_deg=image_rotation_deg, + projection=projection, + camera_fov_rad=camera_fov_rad, + ).reshape(coords.resolution, coords.resolution, 3) + decoded = torch.stack(_octahedral_decode(exit_size, exit_size, device=coords.device), -1) + uv, valid = native_grid_exit_uv( + decoded, + coords, + tangent_scale=tangent_scale, + image_rotation_deg=image_rotation_deg, + projection=projection, + camera_fov_rad=camera_fov_rad, + ) + # Out-of-sensor rays must not be projected into the fovea by the inverse LUT. + exit_texture = torch.where(valid[..., None], uv, torch.full_like(uv, -1)) + return directions, exit_texture + + +def build_generalized_projection_textures( + samples_uv: torch.Tensor, + ray_directions: torch.Tensor, + texture_width: int, + texture_height: int, + exit_width: int, + exit_height: int, + chunk: int = 8192, + device="cuda", +) -> Tuple[torch.Tensor, torch.Tensor]: + """Build direction and exit LUT tensors from a labelled set of sensor samples. + + Both tensors are filled by **nearest-neighbour assignment**. + + Args: + samples_uv: ``(N, 2)`` float32. NDC ``(u, v)`` per sample. + ray_directions: ``(N, 3)`` float32. Unit ray direction per sample. + texture_width, texture_height: Direction LUT dimensions. + exit_width, exit_height: Exit LUT dimensions. + chunk: NN search batch size. + device: Torch device. + + Returns: + ``(direction_texture, exit_texture)`` — + ``(H, W, 3)`` and ``(EH, EW, 2)`` float32 tensors. + """ + uv_t = _t(samples_uv, torch.float32, device) + dirs_t = _t(ray_directions, torch.float32, device) + N = uv_t.shape[0] + Q = texture_width * texture_height + + # ── Direction texture ───────────────────────────────────────────────────── + dir_out = torch.zeros(texture_height, texture_width, 3, dtype=torch.float32, device=device) + dir_out[:, :, 2] = -1.0 + + if N > 0: + if N == Q: + dir_out.reshape(-1, 3)[:] = dirs_t + else: + u_t = (torch.arange(texture_width, dtype=torch.float32, device=device) + 0.5) / texture_width + v_t = (torch.arange(texture_height, dtype=torch.float32, device=device) + 0.5) / texture_height + U = u_t.unsqueeze(0).expand(texture_height, texture_width) + V = v_t.unsqueeze(1).expand(texture_height, texture_width) + texel_uv = torch.stack([U.reshape(-1), V.reshape(-1)], dim=1) + k_nn = _nn_chunk(texel_uv, uv_t, chunk) + dir_out.reshape(-1, 3)[:] = dirs_t[k_nn] + + # ── Exit texture ────────────────────────────────────────────────────────── + # The exit texture is an octahedral inverse map: given a ray direction + # (encoded over [0,1]² via octahedral projection), it returns the sensor + # NDC (u, v) of the nearest foveated sample. The octahedral grid covers + # the full hemisphere, but only texels whose decoded direction falls within + # the camera's FOV (r ≤ max_r) are populated; the rest default to (0.5, 0.5). + # Resolution (exit_width × exit_height) should be large enough to resolve + # individual samples — typically 4× the direction texture dimension. + d = dirs_t.to(torch.float64) + r_s = (torch.atan2((d[:, 0] ** 2 + d[:, 1] ** 2).sqrt(), (-d[:, 2]).clamp(min=1e-20)) * (180.0 / math.pi)).float() + th_s = torch.atan2(d[:, 1], d[:, 0]).float() + xs = r_s * th_s.cos() + ys = r_s * th_s.sin() + max_r = float(r_s.max().item()) if N > 0 else 0.0 + + oct_x, oct_y, oct_z = _octahedral_decode(exit_width, exit_height, device=device) + r_q = (torch.atan2((oct_x**2 + oct_y**2).sqrt(), (-oct_z).clamp(min=1e-20)) * (180.0 / math.pi)).float() + th_q = torch.atan2(oct_y.float(), oct_x.float()) + xq = r_q * th_q.cos() + yq = r_q * th_q.sin() + + odz_f = oct_z.float() + valid = (r_q <= max_r) & (odz_f < -1e-9) + + exit_u = torch.full((exit_height, exit_width), 0.5, dtype=torch.float32, device=device) + exit_v = torch.full((exit_height, exit_width), 0.5, dtype=torch.float32, device=device) + + if N > 0 and valid.any(): + sample_cart = torch.stack([xs, ys], dim=1) + vf = valid.reshape(-1) + query_cart = torch.stack([xq.reshape(-1)[vf], yq.reshape(-1)[vf]], dim=1) + k_exit = _nn_chunk(query_cart, sample_cart, chunk) + eu_flat = exit_u.reshape(-1) + ev_flat = exit_v.reshape(-1) + eu_flat[vf] = uv_t[k_exit, 0] + ev_flat[vf] = uv_t[k_exit, 1] + + return dir_out, torch.stack([exit_u, exit_v], dim=2) + + +# ============================================================================= +# EXR save helpers +# ============================================================================= + + +def save_generalized_projection_textures( + direction_texture: torch.Tensor, + exit_texture: torch.Tensor, + output_dir: str, + basename: str, +) -> Tuple[str, str]: + """Save direction and exit LUT tensors as EXR files. + + Returns: + ``(direction_path, exit_path)`` — absolute paths to the written files. + """ + os.makedirs(output_dir, exist_ok=True) + dir_path = os.path.join(output_dir, f"{basename}_ray_enter_direction.exr") + exit_path = os.path.join(output_dir, f"{basename}_ray_exit_position.exr") + save_exr(dir_path, direction_texture) + save_exr(exit_path, exit_texture) + return os.path.abspath(dir_path), os.path.abspath(exit_path) + + +# ============================================================================= +# USD prim authoring +# ============================================================================= + + +def apply_generalized_projection_to_prim( + prim: Usd.Prim, + direction_texture_path: str, + exit_texture_path: str, +) -> None: + """Apply native OmniLensDistortion LUT textures to an existing USD Camera.""" + if Sdf is None: + raise RuntimeError("pxr.Sdf required — run inside Omniverse Kit / Isaac Sim.") + # RTX reads explicitly authored metadata and attributes without USD schema registration. + prim.AddAppliedSchema("OmniLensDistortionLutAPI") + prim.CreateAttribute("omni:lensdistortion:model", Sdf.ValueTypeNames.Token).Set("lut") + prim.CreateAttribute("omni:lensdistortion:lut:rayEnterDirectionTexture", Sdf.ValueTypeNames.Asset).Set( + direction_texture_path + ) + prim.CreateAttribute("omni:lensdistortion:lut:rayExitPositionTexture", Sdf.ValueTypeNames.Asset).Set( + exit_texture_path + ) + + +# ============================================================================= +# Ray direction models +# ============================================================================= + + +def ray_directions_rectilinear( + r_deg, + theta_rad, + device="cuda", +) -> torch.Tensor: + """Unit ray directions for the rectilinear (pinhole) projection model. + + ``d = normalize(tan(r°)·cosθ, tan(r°)·sinθ, -1)`` + + Args: + r_deg: ``(N,)`` eccentricities in degrees. + theta_rad: ``(N,)`` polar angles in radians. + device: Torch device. + + Returns: + ``(N, 3)`` float32 unit directions, ``dz < 0``. + """ + r = _t(r_deg, torch.float64, device) + th = _t(theta_rad, torch.float64, device) + t = torch.tan(r * (math.pi / 180.0)) + dx = t * th.cos() + dy = t * th.sin() + dz = torch.full_like(dx, -1.0) + n = (dx**2 + dy**2 + dz**2).sqrt().clamp(min=1e-20) + return torch.stack([dx / n, dy / n, dz / n], dim=-1).float() + + +# ============================================================================= +# NDC layout functions +# ============================================================================= + + +def samples_uv_cortical_disc( + r_deg, + theta_rad, + fov_deg: float, + cmf_a: float, + device="cuda", +) -> torch.Tensor: + """Map samples to NDC using the cortical polar disc layout. + + ``ρ = log((r + a) / a)``, mapped to a centered disc. + Foveal centre ``r=0`` → disc centre ``(0.5, 0.5)``. + + Returns: + ``(N, 2)`` float32 NDC tensor. + """ + rho_max = math.log((fov_deg / 2.0 + cmf_a) / cmf_a) + r = _t(r_deg, torch.float64, device) + th = _t(theta_rad, torch.float64, device) + rho = ((r + cmf_a) / cmf_a).clamp(min=1e-30).log() + u = (rho * th.cos() / (2.0 * rho_max) + 0.5).float() + v = (-rho * th.sin() / (2.0 * rho_max) + 0.5).float() + return torch.stack([u, v], dim=1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py new file mode 100644 index 000000000000..a9aac12b96c4 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py @@ -0,0 +1,219 @@ +# 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 + +"""Native warped-grid rendering geometry and public image layout.""" + +from __future__ import annotations + +import math +from collections.abc import Mapping +from typing import Protocol + +import torch +from fovi.sensing.coords import RADIUS_NORMS, WARPED_CARTESIAN_STYLES, SamplingCoords + +GRID_STYLE = "warped_cartesian_as_grid" + + +def validate_radius_norm(radius_norm: float, style: str, fov_type: str) -> None: + """Reject unsupported warp configurations before renderer startup.""" + if radius_norm not in RADIUS_NORMS: + raise ValueError(f"radius_norm must be one of {RADIUS_NORMS}, got {radius_norm!r}.") + if radius_norm != 2.0 and style not in WARPED_CARTESIAN_STYLES: + raise ValueError("Non-default radius_norm requires a warped_cartesian style.") + if radius_norm == math.inf and fov_type == "wang": + raise ValueError("radius_norm=inf does not support fov_type='wang'.") + + +class TorchBuffer(Protocol): + """Renderer buffer exposing a Torch view.""" + + @property + def torch(self) -> torch.Tensor: ... + + +def buffer_tensor(value: torch.Tensor | TorchBuffer) -> torch.Tensor: + """Get a renderer or public tensor without copying.""" + return value if isinstance(value, torch.Tensor) else value.torch + + +def _angular_padding_boundary(coords: SamplingCoords, camera_fov_rad: float | None = None) -> tuple[float, float]: + if coords.fov_type == "circular": + radius = 1.0 + elif coords.fov_type == "square": + radius = math.sqrt(2) + elif coords.fov_type == "wang": + corner = coords.cartesian.new_tensor([[1.0, 1.0]]) + radius = float(torch.linalg.vector_norm(coords.native_to_visual(corner)).item()) + else: + raise ValueError(f"Unsupported native grid footprint {coords.fov_type!r}.") + fov_rad = math.radians(coords.fov) if camera_fov_rad is None else camera_fov_rad + angle = radius * fov_rad / 2 + if angle >= math.pi: + raise ValueError("Spherical native grid footprint reaches the antipode; reduce FoV or use circular coverage.") + return radius, angle + + +def bounded_angular_radius(radius: torch.Tensor, half_fov_rad: float) -> torch.Tensor: + """Continue angular padding monotonically toward the antipode. + + The nominal visual disc is unchanged. Outside it, the continuation has + matching value and derivative at the rim and never wraps around the sphere. + """ + if not 0 < half_fov_rad < math.pi: + raise ValueError("Spherical grid half FoV must lie strictly between zero and pi.") + remaining = math.pi - half_fov_rad + excess = (radius - 1).clamp_min(0) * half_fov_rad + padding = half_fov_rad + remaining * excess / (remaining + excess) + return torch.where(radius <= 1, radius * half_fov_rad, padding) + + +def unbounded_angular_radius(angle: torch.Tensor, half_fov_rad: float) -> torch.Tensor: + """Invert :func:`bounded_angular_radius` for angles below the antipode.""" + remaining = math.pi - half_fov_rad + fraction = ((angle - half_fov_rad) / remaining).clamp(0, 1 - torch.finfo(angle.dtype).eps) + padding = 1 + remaining * fraction / ((1 - fraction) * half_fov_rad) + return torch.where(angle <= half_fov_rad, angle / half_fov_rad, padding) + + +def native_grid_directions( + coords: SamplingCoords, + *, + tangent_scale: float, + image_rotation_deg: float = 0.0, + projection: str = "pinhole", + camera_fov_rad: float | None = None, +) -> torch.Tensor: + """Return canonical ordered OpenGL rays for a warped Cartesian grid.""" + cartesian = coords.cartesian.to(torch.float64) + radius = torch.linalg.vector_norm(cartesian, dim=-1) + if projection not in ("pinhole", "fisheye_equidistant"): + raise ValueError(f"Unsupported native grid projection {projection!r}.") + if coords.field_geometry == "spherical" or projection == "fisheye_equidistant": + if coords.field_geometry != "spherical" and camera_fov_rad is None: + raise ValueError("Planar equidistant rendering requires camera_fov_rad.") + boundary_radius, boundary_angle = _angular_padding_boundary( + coords, None if coords.field_geometry == "spherical" else camera_fov_rad + ) + angle = bounded_angular_radius(radius / boundary_radius, boundary_angle) + scale = torch.where(radius > 0, angle.sin() / radius.clamp_min(1e-30), angle.new_zeros(())) + xy = cartesian * scale[:, None] + z = -angle.cos() + elif coords.field_geometry in ("planar", "legacy"): + xy = cartesian * tangent_scale + z = -torch.ones_like(radius) + else: + raise ValueError(f"Unknown field geometry {coords.field_geometry!r}.") + angle = math.radians(image_rotation_deg) + x, y = xy.unbind(-1) + rays = torch.stack( + (math.cos(angle) * x - math.sin(angle) * y, math.sin(angle) * x + math.cos(angle) * y, z), + -1, + ) + return torch.nn.functional.normalize(rays, dim=-1).float() + + +def native_grid_exit_uv( + directions: torch.Tensor, + coords: SamplingCoords, + *, + tangent_scale: float, + image_rotation_deg: float = 0.0, + projection: str = "pinhole", + camera_fov_rad: float | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Analytically map OpenGL rays to native texture UV and visibility. + + Texture rows and columns follow canonical vector order: native x then y. + The public image applies Fovi's upright grid permutation after rendering. + """ + angle = math.radians(image_rotation_deg) + x, y, z = directions.to(torch.float64).unbind(-1) + xy = torch.stack((math.cos(angle) * x + math.sin(angle) * y, -math.sin(angle) * x + math.cos(angle) * y), -1) + lateral = torch.linalg.vector_norm(xy, dim=-1) + if projection not in ("pinhole", "fisheye_equidistant"): + raise ValueError(f"Unsupported native grid projection {projection!r}.") + if coords.field_geometry == "spherical" or projection == "fisheye_equidistant": + if coords.field_geometry != "spherical" and camera_fov_rad is None: + raise ValueError("Planar equidistant rendering requires camera_fov_rad.") + theta = torch.atan2(lateral, -z) + boundary_radius, boundary_angle = _angular_padding_boundary( + coords, None if coords.field_geometry == "spherical" else camera_fov_rad + ) + radius = unbounded_angular_radius(theta, boundary_angle) * boundary_radius + cartesian = xy * (radius / lateral.clamp_min(1e-30))[..., None] + visible = theta < math.pi - 1e-8 + elif coords.field_geometry in ("planar", "legacy"): + cartesian = xy / ((-z).clamp_min(1e-30) * tangent_scale)[..., None] + visible = z < 0 + else: + raise ValueError(f"Unknown field geometry {coords.field_geometry!r}.") + native = coords.visual_to_native(cartesian) + uv = (native.flip(-1) + 1) / 2 + visible = visible & (uv >= 0).all(-1) & (uv <= 1).all(-1) + return uv.float(), visible + + +def grid_output_shape(coords: SamplingCoords) -> tuple[int, int]: + """Resolve public image dimensions, preserving vector cameras' shape.""" + if coords.style == GRID_STYLE: + return coords.resolution, coords.resolution + return len(coords), 1 + + +def canonical_to_grid(value: torch.Tensor, coords: SamplingCoords) -> torch.Tensor: + """Convert canonical BNC or BN1C values into upright BHWC values.""" + if value.ndim == 4: + value = value.squeeze(2) + if value.ndim != 3 or value.shape[1] != len(coords): + raise ValueError(f"Expected canonical (B, {len(coords)}, C), got {tuple(value.shape)}.") + return coords.as_grid(value, sample_dim=1) + + +def mask_grid_samples(outputs: Mapping[str, torch.Tensor | TorchBuffer], coords: SamplingCoords) -> None: + """Zero samples outside the configured footprint before pooling or publication.""" + if coords.style != GRID_STYLE: + return + invalid = ~coords.valid_mask[None, :, None, None] + for name, value in outputs.items(): + if name == "rgb" and "rgba" in outputs: + continue + tensor = buffer_tensor(value) + tensor.masked_fill_(invalid, 0) + + +def allocate_grid_outputs( + outputs: Mapping[str, torch.Tensor | TorchBuffer], coords: SamplingCoords +) -> dict[str, torch.Tensor]: + """Allocate stable public BHWC buffers from flat renderer outputs.""" + result: dict[str, torch.Tensor] = {} + for name, value in outputs.items(): + if name == "rgb" and "rgba" in outputs: + continue + tensor = buffer_tensor(value) + result[name] = tensor.new_zeros((tensor.shape[0], coords.resolution, coords.resolution, tensor.shape[-1])) + if "rgb" in outputs and "rgba" in result: + result["rgb"] = result["rgba"][..., :3] + return result + + +def grid_sample_indices(coords: SamplingCoords) -> torch.Tensor: + """Resolve the public image permutation once, outside rendering updates.""" + return coords.as_grid(torch.arange(len(coords), device=coords.device)).reshape(-1) + + +def copy_grid_outputs( + source: Mapping[str, torch.Tensor | TorchBuffer], + target: dict[str, torch.Tensor], + indices: torch.Tensor, +) -> None: + """Update stable public image buffers without changing sample ordering.""" + for name, value in source.items(): + if name == "rgb" and "rgba" in source: + continue + tensor = buffer_tensor(value) + flat_source = tensor.reshape(tensor.shape[0], -1, tensor.shape[-1]) + flat_target = target[name].view(tensor.shape[0], -1, tensor.shape[-1]) + torch.index_select(flat_source, 1, indices, out=flat_target) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py new file mode 100644 index 000000000000..a9b07b1589e6 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -0,0 +1,154 @@ +# 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 + +"""Shared retinal-pooling helpers for FoveatedTiledCamera backends. + +Builds a pair of (lowres, highres) :class:`SamplingCoords` and a retinal +pooler analogous to :class:`fovi.sensing.samplers.PoolingGridSampler`, but driven by a +:class:`FoveatedTiledCameraCfg` and operating on rays rather than images. + +Key deviation from ``PoolingGridSampler``: the highres grid shares ``cmf_a`` with +the lowres grid (no ``cmf_a_mult``). Only ``res`` is scaled by +``pool_res_mult`` so the photoreceptor and RGC layers represent the same +visual-field geometry at different densities. + +Construction happens in two stages to accommodate Isaac's sensor init order: +1. ``build_lowres_coords`` + ``build_highres_coords`` run *before* + ``super()._initialize_impl()`` (CPU) so the backend can size its render + buffers from the highres sample count. +2. ``build_pooler`` runs *after* coords have been moved to the sensor's + device, so the KNN indices/distances/Gaussian weights materialise on the + correct device (they are plain tensor attributes and are not moved by + ``nn.Module.to``). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from .calibrated_geometry import sampling_geometry + +if TYPE_CHECKING: + from fovi.arch.knn import KNNPoolingLayer + from fovi.arch.pooling import GridPoolingLayer + from fovi.sensing.coords import SamplingCoords + + from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + + +def build_lowres_coords(cfg: "FoveatedTiledCameraCfg", device: str) -> tuple["SamplingCoords", int]: + """Build the lowres (RGC / public output) SamplingCoords. + + Returns ``(lowres_coords, matched_res)`` where ``matched_res`` is the + auto-matched radial resolution also needed for the highres grid. + """ + from fovi.sensing.coords import SamplingCoords, auto_match_num_coords + + fov, cmf_a = sampling_geometry(cfg) + + matched_res, _ = auto_match_num_coords( + fov, + cmf_a, + cfg.foveated_res, + cfg.foveated_style, + 1, + device, + quiet=False, + fov_type=cfg.fov_type, + radius_norm=cfg.radius_norm, + field_geometry=cfg.field_geometry, + ) + lowres = SamplingCoords( + fov=fov, + cmf_a=cmf_a, + res=matched_res, + device=device, + style=cfg.foveated_style, + isotropic_plotting_type=cfg.isotropic_plotting_type, + fov_type=cfg.fov_type, + radius_norm=cfg.radius_norm, + field_geometry=cfg.field_geometry, + ) + return lowres, matched_res + + +def build_highres_coords(cfg: "FoveatedTiledCameraCfg", matched_res: int, device: str) -> "SamplingCoords | None": + """Build the highres (photoreceptor) SamplingCoords when pooling is on.""" + if not cfg.pool_enabled: + return None + from fovi.sensing.coords import SamplingCoords + + fov, cmf_a = sampling_geometry(cfg) + + # pool_res_mult is a float to support fractional ratios (e.g. sqrt(2) for + # a 2× N_hi/N_lo ratio). SamplingCoords requires an integer radial res. + highres_res = int(round(cfg.pool_res_mult * matched_res)) + return SamplingCoords( + fov=fov, + cmf_a=cmf_a, + res=highres_res, + device=device, + style=cfg.foveated_style, + isotropic_plotting_type=cfg.isotropic_plotting_type, + fov_type=cfg.fov_type, + radius_norm=cfg.radius_norm, + field_geometry=cfg.field_geometry, + ) + + +def build_pooler( + cfg: "FoveatedTiledCameraCfg", + lowres: "SamplingCoords", + highres: "SamplingCoords | None", + device: str, + mode: str | None = None, +) -> tuple["KNNPoolingLayer | GridPoolingLayer | None", int | None]: + """Build a retinal pooling layer. Both coord sets must already be on ``device``. + + If ``mode`` is None, uses ``cfg.pool_mode`` — the standard pooler for + floating-point outputs. Pass ``mode="max"`` (or similar) to build a + separate pooler for integer segmentation outputs. + """ + if highres is None: + return None, None + + from fovi.arch.pooling import build_retinal_pooler + + return build_retinal_pooler( + highres, + lowres, + k=cfg.pool_k, + mode=mode if mode is not None else cfg.pool_mode, + device=device, + sample_cortex=cfg.pool_sample_cortex, + gauss_sigma=cfg.pool_gauss_sigma, + ) + + +def is_segmentation_output(name: str) -> bool: + """Whether a sensor output key should be pooled with ``pool_int_mode``. + + Uses a key-name heuristic (``"segmentation" in name``) rather than dtype, + since all IsaacLab segmentation variants — ``semantic_segmentation``, + ``instance_segmentation_fast``, ``instance_id_segmentation_fast`` — + produce class-like values whose per-pixel semantics are broken by + averaging, regardless of whether they're stored as int32 class IDs or + uint8 colorized RGBA. + """ + return "segmentation" in name + + +def pool_hwc_buffer(pooler: "KNNPoolingLayer | GridPoolingLayer", buf: torch.Tensor) -> torch.Tensor: + """Pool a ``(B, N_hi, 1, C)`` sensor buffer into ``(B, N_lo, 1, C)``. + + Both poolers expect ``(B, C, N)`` inputs, so we permute in and out. + """ + B, N_hi, one, C = buf.shape + assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}" + x = buf[:, :, 0, :].transpose(1, 2).contiguous() # (B, C, N_hi) + y = pooler(x) # (B, C, N_lo) + return y.transpose(1, 2).unsqueeze(2).contiguous() # (B, N_lo, 1, C) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py new file mode 100644 index 000000000000..b9451d36745c --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -0,0 +1,126 @@ +# 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 + +"""Virtual gaze with a static physical camera and a static rendering ray bundle.""" + +from __future__ import annotations + +import math +from collections.abc import Sequence + +import torch +import warp as wp +from fovi.sensing.projection import CameraModel, angular_directions, gaze_rotation +from isaaclab.utils.math import matrix_from_quat, quat_from_matrix + +from .calibrated_geometry import ( + calibrated_fixation_rotation, + calibrated_mount_angles, + calibrated_visibility, + compose_rotations, + convert_camera_frame_quaternion, +) +from .native_grid import GRID_STYLE, native_grid_directions + + +class CalibratedVirtualGaze: + """Calibrated virtual-gaze operations shared by tiled-camera backends.""" + + def get_world_positions(self) -> torch.Tensor: + """Read live camera origins without capturing RGB or changing image metadata. + + Unlike ``data``, this only queries the camera's FrameView and never + refreshes lazy image buffers. Hybrid virtual gaze leaves origins unchanged. + """ + position, _ = self.get_world_poses() + return position + + def get_world_poses(self) -> tuple[torch.Tensor, torch.Tensor]: + """Read live scene-frame poses without refreshing images or their metadata. + + Returns: + World positions (B, 3), in meters, and OpenGL orientations (B, 4), + as XYZW quaternions. The tensors borrow the sensor view's buffers. + RTX gaze writes are included; Warp's renderer-only gaze is not. + """ + position, orientation = self._view.get_world_poses() + return position.torch, orientation.torch + + def calibrated_fov_sample_mask(self) -> torch.Tensor: + """Return the physical-sensor visibility mask in canonical ray order (B,N).""" + if self._calibrated_rotation is None: + raise RuntimeError("Set calibrated gaze before requesting its physical-FoV mask") + return self._calibrated_validity(len(self._calibrated_rotation)) + + def set_calibrated_fixation(self, fixation: torch.Tensor, env_ids: torch.Tensor | None = None) -> None: + """Set full-batch image fixation, optionally changing only selected environments.""" + with torch.autocast(fixation.device.type, enabled=False): + rotation, _ = calibrated_fixation_rotation(self._calibrated_camera, fixation.float()) + if env_ids is None: + self._calibrated_rotation = rotation + else: + if self._calibrated_rotation is None: + self._calibrated_rotation = self._calibrated_identity.expand_as(rotation).clone() + self._calibrated_rotation[env_ids] = rotation[env_ids] + + def calibrated_mount_angles(self, fixation: torch.Tensor) -> torch.Tensor: + """Convert upright image gaze to mount (tilt, pan) radians.""" + with torch.autocast(fixation.device.type, enabled=False): + return calibrated_mount_angles(self._calibrated_camera, fixation.float()) + + def set_calibrated_angles(self, angles: torch.Tensor) -> None: + """Set virtual gaze from the mount's (tilt, pan) radians.""" + # Geometry must remain float32 even when the policy runs under AMP. + with torch.autocast(angles.device.type, enabled=False): + tilt, pan = angles.float().unbind(-1) + direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + self._calibrated_rotation = gaze_rotation(direction, "pan_tilt") + + def _apply_calibrated_pose( + self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None + ) -> None: + if self._calibrated_rotation is None: + return + stored = self._data.quat_w_world + quat = stored.torch if hasattr(stored, "torch") else stored + with torch.autocast(quat.device.type, enabled=False): + base = convert_camera_frame_quaternion(quat, origin="world", target="opengl") + # Calibration uses the upright image frame; rays include mount roll. + basis = self._calibrated_basis + relative = compose_rotations(compose_rotations(basis, self._calibrated_rotation), basis.T) + composed = quat_from_matrix(compose_rotations(matrix_from_quat(base), relative)) + updated = convert_camera_frame_quaternion(composed, origin="opengl", target="world") + if env_mask is not None: + quat.copy_(torch.where(wp.to_torch(env_mask)[:, None], updated, quat)) + elif env_ids is not None: + indices = wp.to_torch(env_ids) if isinstance(env_ids, wp.array) else env_ids + quat[indices] = updated[indices] + else: + quat.copy_(updated) + + def _calibrated_validity(self, batch_size: int) -> torch.Tensor: + rays = self._calibrated_rays + with torch.autocast(rays.device.type, enabled=False): + rotation = self._calibrated_rotation + if rotation is None: + rotation = self._calibrated_identity.expand(batch_size, -1, -1) + # A receptive field can overlap the sensor even when its center is outside it. + return calibrated_visibility(self._calibrated_camera, rays, rotation) + + def _initialize_calibrated_gaze(self) -> None: + if self.cfg.field_geometry != "spherical": + return + self._calibrated_camera = CameraModel(**self.cfg.camera_calibration) + coords = self._sampling_coords_highres or self._sampling_coords + if coords.style == GRID_STYLE: + self._calibrated_rays = native_grid_directions(coords, tangent_scale=1.0) * coords.cartesian.new_tensor( + (1, -1, -1) + ) + else: + self._calibrated_rays = angular_directions(coords.cartesian, coords.fov) + self._calibrated_identity = torch.eye(3, device=coords.device) + angle = math.radians(self.cfg.image_rotation_deg) + c, s = math.cos(angle), math.sin(angle) + self._calibrated_basis = self._calibrated_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) diff --git a/source/isaaclab_fovi/pyproject.toml b/source/isaaclab_fovi/pyproject.toml new file mode 100644 index 000000000000..1f8c7bcac8ad --- /dev/null +++ b/source/isaaclab_fovi/pyproject.toml @@ -0,0 +1,39 @@ +# 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 + +[build-system] +requires = ["setuptools>=70.0,<82.0.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "isaaclab_fovi" +version = "0.1.0" +description = "Extension providing foveated camera sensors for the Newton and RTX renderers." +license = {text = "BSD-3-Clause"} +authors = [{name = "Isaac Lab Project Developers"}] +maintainers = [{name = "Isaac Lab Project Developers"}] +keywords = ["robotics", "simulation", "rendering", "camera", "foveation"] +requires-python = ">=3.12" +# Only interpackage dependencies should go here. +dependencies = [ + "isaaclab", +] + +[tool.uv.sources] +isaaclab = { path = "../isaaclab", editable = true } + +[project.urls] +Homepage = "https://github.com/isaac-sim/IsaacLab" +Repository = "https://github.com/isaac-sim/IsaacLab" + +[tool.setuptools] +include-package-data = true + +[tool.setuptools.packages.find] +where = ["."] +include = ["isaaclab_fovi", "isaaclab_fovi.*"] + +[tool.setuptools.package-data] +"*" = ["*.pyi"] diff --git a/source/isaaclab_fovi/test/_check_imports.py b/source/isaaclab_fovi/test/_check_imports.py new file mode 100644 index 000000000000..8a84b341bac2 --- /dev/null +++ b/source/isaaclab_fovi/test/_check_imports.py @@ -0,0 +1,52 @@ +# 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 + +"""Executed in a fresh process to reject accidental research/runtime imports.""" + +import importlib +import importlib.abc +import sys +from types import ModuleType + +BLOCKED = ( + "ffcv", + "wandb", + "lightning", + "pytorch_lightning", + "timm", + "fovi.models", + "fovi.training", + "isaacsim", + "omni", +) + + +class BlockResearchImports(importlib.abc.MetaPathFinder): + """Fail at the import boundary even when research packages are installed.""" + + def find_spec( + self, + fullname: str, + path: list[str] | None = None, + target: ModuleType | None = None, + ) -> None: + if any(fullname == prefix or fullname.startswith(prefix + ".") for prefix in BLOCKED): + raise AssertionError(f"Standalone geometry imported forbidden dependency {fullname}") + return None + + +sys.meta_path.insert(0, BlockResearchImports()) +for module in ( + "isaaclab_fovi", + "isaaclab_fovi.sensors", + "isaaclab_fovi.sensors.fixed_software_fov", + "isaaclab_fovi.sensors.active_camera_geometry", + "isaaclab_fovi.sensors.foveated_rays", + "isaaclab_fovi.sensors.pooling", + "fovi.sensing.coords", + "fovi.arch.knn", +): + importlib.import_module(module) +print("Standalone import boundary passed") diff --git a/source/isaaclab_fovi/test/calibrated_camera_render_smoke.py b/source/isaaclab_fovi/test/calibrated_camera_render_smoke.py new file mode 100644 index 000000000000..ee7a2baf4f51 --- /dev/null +++ b/source/isaaclab_fovi/test/calibrated_camera_render_smoke.py @@ -0,0 +1,458 @@ +# 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 + +"""Bounded GPU check of calibrated dense/Isaac Lab Fovi rendering against analytic geometry. + +Run separately for each --backend {rtx,newton} and --sampling {dense,foveated} +with --visualizer none --device cuda:0. Both sampling modes are provided by Isaac Lab Fovi. +The reference uses OpenCV and analytic ray/box intersections, not renderer rays. +""" + +from __future__ import annotations + +import argparse +import faulthandler +import json +import traceback +from contextlib import ExitStack +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np +from isaaclab.app import AppLauncher + +if TYPE_CHECKING: + from fovi.sensing.projection import CameraCalibration + from isaaclab.sensors import Camera + +HEIGHT, WIDTH = 120, 192 +FAR = 500.0 +NEAR = 0.01 +BOXES = ( + ((0.0, 0.0, -4.05), (200.0, 200.0, 0.1)), + ((0.8, 0.3, -2.15), (0.6, 0.8, 0.3)), +) + + +def audit_projection(cameras: dict[str, Camera], output: Path) -> None: + """Record and verify the camera properties actually seen by the renderer.""" + import isaaclab.sim as sim_utils + import omni.kit.app + from pxr import Usd + + records = {} + for name, camera in cameras.items(): + prim = sim_utils.get_current_stage().GetPrimAtPath(camera.cfg.prim_path) + schemas = list(prim.GetMetadata("apiSchemas").GetAppliedItems()) + properties = { + attr.GetName(): str(attr.Get()) + for attr in prim.GetAuthoredAttributes() + if "Projection" in attr.GetName() or attr.GetName().startswith("omni:lensdistortion:") + } + assert "OmniLensDistortionLutAPI" in schemas, (name, schemas) + assert properties["omni:lensdistortion:model"] == "lut", (name, properties) + assert properties.get("cameraProjectionType") != "generalizedProjection", (name, properties) + assert not any("generalizedProjection" in key for key in properties), (name, properties) + for texture in ("rayEnterDirectionTexture", "rayExitPositionTexture"): + assert properties[f"omni:lensdistortion:lut:{texture}"], (name, properties) + records[name] = {"schemas": schemas, "properties": properties} + runtime = { + "schema_registered": bool(Usd.SchemaRegistry.GetTypeFromSchemaTypeName("OmniLensDistortionLutAPI")), + "extension_enabled": omni.kit.app.get_app() + .get_extension_manager() + .is_extension_enabled("omni.usd.schema.omni_lens_distortion"), + } + output.write_text(json.dumps({"runtime": runtime, "cameras": records}, indent=2) + "\n") + + +def video_maps(cameras: dict[str, Camera], size: int) -> dict[str, np.ndarray]: + """Nearest-sample visual-field reconstruction; the periphery stays coarse.""" + from scipy.spatial import cKDTree + + y, x = np.mgrid[:size, :size] + points = np.stack((2 * (x + 0.5) / size - 1, 1 - 2 * (y + 0.5) / size), axis=-1) + maps = {} + for name, camera in cameras.items(): + coords = camera.sampling_coords.cartesian.cpu().numpy() + indices = cKDTree(coords).query(points.reshape(-1, 2))[1].reshape(size, size) + indices[np.linalg.norm(points, axis=-1) > 1] = -1 + maps[name] = indices + return maps + + +def video_frame( + frames: dict[str, dict[str, np.ndarray]], + maps: dict[str, np.ndarray], + phase: int, + mode: str, + fixation: tuple[float, float], +) -> np.ndarray: + """Pair measured RGB with analytic foreground/mask reference for every lens.""" + import cv2 + + size = next(iter(maps.values())).shape[0] + tile_width, tile_height = size * 2 + 16, size + 32 + canvas = np.full((tile_height * 3 + 64, tile_width * 2, 3), 24, dtype=np.uint8) + cv2.putText(canvas, f"Foveated | {mode} | frame {phase - 4}", (12, 24), 0, 0.6, (240,) * 3, 1) + cv2.putText( + canvas, + f"Fixation y,x: {fixation[0]:.3f}, {fixation[1]:.3f} | RGB / analytic reference", + (12, 48), + 0, + 0.5, + (240,) * 3, + 1, + ) + for index, (name, lookup) in enumerate(maps.items()): + frame = frames[f"{name}_{phase}"] + actual = frame["rgb"].reshape(-1, 3).astype(np.uint8) + reference = np.zeros_like(actual) + reference[:, 2] = 200 + reference[frame["expected"] < 3] = (200, 0, 0) + reference[~frame["valid"]] = 0 + top, left = 64 + (index // 2) * tile_height, (index % 2) * tile_width + cv2.putText(canvas, name, (left + 8, top + 22), 0, 0.5, (240,) * 3, 1) + for column, samples in enumerate((actual, reference)): + image = samples[lookup].copy() + image[lookup < 0] = 0 + x = left + 4 + column * (size + 8) + canvas[top + 32 : top + 32 + size, x : x + size] = image[:, :, ::-1] + return canvas + + +def unproject(pixels: np.ndarray, calibration: CameraCalibration) -> np.ndarray: + """Independent OpenCV reference, returning unit OpenCV-frame directions.""" + import cv2 + + fx, fy, cx, cy = calibration["intrinsics"] + matrix = np.array(((fx, 0, cx), (0, fy, cy), (0, 0, 1)), dtype=np.float64) + coefficients = np.array(calibration["distortion"], dtype=np.float64) + points = np.asarray(pixels, dtype=np.float64).reshape(-1, 1, 2) + if calibration["model"] == "fisheye": + xy = cv2.fisheye.undistortPoints(points, matrix, coefficients)[:, 0] + else: + xy = cv2.undistortPointsIter( + points, + matrix, + coefficients, + None, + None, + (cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 100, 1e-12), + )[:, 0] + rays = np.column_stack((xy, np.ones(len(xy)))) + return rays / np.linalg.norm(rays, axis=-1, keepdims=True) + + +def ray_depth(rays: np.ndarray, origin: np.ndarray) -> np.ndarray: + """First intersection distance [m] with the two axis-aligned scene boxes.""" + result = np.full(len(rays), FAR) + for center, size in BOXES: + lo = np.array(center) - np.array(size) / 2 + hi = np.array(center) + np.array(size) / 2 + with np.errstate(divide="ignore", invalid="ignore"): + a, b = (lo - origin) / rays, (hi - origin) / rays + near = np.minimum(a, b).max(axis=-1) + far = np.maximum(a, b).min(axis=-1) + hit = (far >= near) & (near > 0) + result = np.minimum(result, np.where(hit, near, FAR)) + return result + + +def reference_rays( + camera: Camera, calibration: CameraCalibration, sampling: str, fixation: tuple[float, float] +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Return physical GL-frame rays and lens validity for the public sample grid.""" + import cv2 + + y, x = np.mgrid[:HEIGHT, :WIDTH] + pixels = np.stack((x, y), -1).reshape(-1, 2) + if sampling == "dense": + rays = unproject(pixels, calibration) + forward_cosine = rays[:, 2].copy() + else: + coords = camera.sampling_coords.cartesian.cpu().numpy().astype(np.float64) + # The short-side retinal diameter is the angle between these image rays. + edges = np.array((((WIDTH - 1) / 2, -0.5), ((WIDTH - 1) / 2, HEIGHT - 0.5))) + edge_rays = unproject(edges, calibration) + half_angle = np.arccos(np.clip(edge_rays[0] @ edge_rays[1], -1, 1)) / 2 + xy = coords * (1, -1) + radius = np.linalg.norm(xy, axis=-1) + scale = half_angle * np.sinc(radius * half_angle / np.pi) + rays = np.column_stack((xy * scale[:, None], np.cos(radius * half_angle))) + forward_cosine = rays[:, 2].copy() + target = unproject(np.array(((fixation[1] * WIDTH - 0.5, fixation[0] * HEIGHT - 0.5),)), calibration)[0] + pan = np.arctan2(target[0], target[2]) + tilt = np.arctan2(-target[1], np.hypot(target[0], target[2])) + rx, _ = cv2.Rodrigues(np.array((tilt, 0, 0))) + ry, _ = cv2.Rodrigues(np.array((0, pan, 0))) + rays = rays @ (ry @ rx).T + fx, fy, cx, cy = calibration["intrinsics"] + matrix = np.array(((fx, 0, cx), (0, fy, cy), (0, 0, 1))) + project = cv2.fisheye.projectPoints if calibration["model"] == "fisheye" else cv2.projectPoints + pixels = project(rays[:, None], np.zeros(3), np.zeros(3), matrix, np.array(calibration["distortion"]))[0][:, 0] + valid = ( + (pixels[:, 0] >= -0.5) & (pixels[:, 0] < WIDTH - 0.5) & (pixels[:, 1] >= -0.5) & (pixels[:, 1] < HEIGHT - 0.5) + ) + if "image_circle" in calibration: + cx, cy, radius = calibration["image_circle"] + valid &= np.linalg.norm(pixels - (cx, cy), axis=-1) <= radius + if sampling == "foveated": + target_pixel = np.array((fixation[1] * WIDTH - 0.5, fixation[0] * HEIGHT - 0.5)) + # An invalid fixation disables the whole calibrated view, including + # rays that would otherwise land inside the lens's usable circle. + valid &= np.linalg.norm(target_pixel - (cx, cy)) <= radius + return rays * (1, -1, -1), valid, forward_cosine + + +def main(args: argparse.Namespace) -> None: + import isaaclab.sim as sim_utils + import torch + from isaaclab.utils.warp import ProxyArray + + from isaaclab_fovi.sensors.calibrated_camera import CalibratedTiledCamera, CalibratedTiledCameraCfg + + if args.backend in ("newton", "ovrtx"): + from isaaclab_newton.physics.mjwarp_solver_cfg import MJWarpSolverCfg + from isaaclab_newton.physics.newton_manager_cfg import NewtonCfg + from isaaclab_newton.renderers import NewtonWarpRendererCfg + + physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) + if args.backend == "newton": + renderer = NewtonWarpRendererCfg(render_order="pixel_priority") + else: + from isaaclab_ov.renderers.ovrtx_renderer_cfg import OVRTXRendererCfg + + renderer = OVRTXRendererCfg(log_level="warn") + else: + from isaaclab_physx.physics.physx_manager_cfg import PhysxCfg + from isaaclab_physx.renderers import IsaacRtxRendererCfg + from isaaclab_physx.renderers.isaac_rtx_renderer_cfg import ( + IsaacRtxRendererGlobalSettingsCfg, + ) + + physics, renderer = ( + PhysxCfg(), + IsaacRtxRendererCfg( + global_settings=IsaacRtxRendererGlobalSettingsCfg( + antialiasing_mode="Off", + enable_dl_denoiser=False, + enable_global_illumination=False, + enable_reflections=False, + enable_ambient_occlusion=False, + enable_shadows=False, + ) + ), + ) + sim_utils.create_new_stage() + sim = sim_utils.SimulationContext( + sim_utils.SimulationCfg(device=args.device, physics=physics, gravity=(0.0, 0.0, 0.0)) + ) + sim_utils.create_prim("/World/envs/env_0", "Xform") + for i, (center, size) in enumerate(BOXES): + cfg = sim_utils.CuboidCfg( + size=size, + rigid_props=sim_utils.RigidBodyPropertiesCfg(disable_gravity=True), + mass_props=sim_utils.MassPropertiesCfg(mass=1.0), + collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=False), + visual_material=sim_utils.PreviewSurfaceCfg( + diffuse_color=(0.8, 0.0, 0.0) if i else (0.0, 0.0, 0.8), + emissive_color=(0.8, 0.0, 0.0) if i else (0.0, 0.0, 0.8), + ), + ) + cfg.func(f"/World/envs/env_0/Box{i}", cfg, translation=center) + light = sim_utils.DistantLightCfg(intensity=2000) + light.func("/World/Light", light) + base = dict( + model="fisheye", + image_size=(HEIGHT, WIDTH), + intrinsics=(80.0, 85.0, 88.0, 63.0), + distortion=(0.0,) * 4, + ) + cases = { + "equidistant": base, + "intrinsics": dict(base, intrinsics=(105.0, 95.0, 102.0, 53.0)), + "distortion": dict(base, distortion=(0.14, -0.025, 0.004, -0.0002)), + "mask": dict(base, image_circle=(88.0, 63.0, 68.0)), + "pinhole": dict(base, model="pinhole"), + "brown": dict(base, model="pinhole", distortion=(0.12, -0.01, 0.005, -0.003)), + } + cameras = {} + for name, calibration in cases.items(): + common = dict( + prim_path=f"/World/envs/env_0/{name}", + data_types=["rgb", "distance_to_camera", "depth"], + camera_calibration=calibration, + renderer_cfg=renderer, + spawn=sim_utils.PinholeCameraCfg(clipping_range=(NEAR, FAR), lock_camera=False), + offset=CalibratedTiledCameraCfg.OffsetCfg(rot=(0.0, 0.0, 0.0, 1.0), convention="opengl"), + update_latest_camera_pose=True, + ) + if args.sampling == "dense": + camera = CalibratedTiledCamera(CalibratedTiledCameraCfg(height=HEIGHT, width=WIDTH, **common)) + else: + from isaaclab_fovi.sensors import FoveatedTiledCamera, FoveatedTiledCameraCfg + + camera = FoveatedTiledCamera( + FoveatedTiledCameraCfg( + field_geometry="spherical", + foveated_res=24, + cmf_a=0.1, + fixed_software_fov=True, + software_fov_image_height=HEIGHT, + software_fov_image_width=WIDTH, + **common, + ) + ) + cameras[name] = camera + if args.backend == "ovrtx": + from isaaclab.cloner import ClonePlan + + sim.set_clone_plan( + ClonePlan( + sources=("/World/envs/env_0",), + destinations=("/World/envs/env_{}",), + clone_mask=np.ones((1, 1), dtype=bool), + env_ids=np.array([0]), + positions=np.zeros((1, 3)), + ) + ) + sim.reset() + args.output.parent.mkdir(parents=True, exist_ok=True) + if args.backend == "rtx" and args.sampling == "foveated": + audit_projection(cameras, args.output.with_suffix(".projection.json")) + records, frames = [], {} + fixations = [(0.5, 0.5), (0.4, 0.65), (0.4, 0.65), (0.5, 0.5)] + maps = {} + if args.video_frames: + maps = video_maps(cameras, 224) + for angle in np.linspace(0, 2 * np.pi, args.video_frames): + fixations.append((0.5 + 0.2 * np.sin(angle), 0.5 + 0.3 * np.sin(2 * angle))) + with ExitStack() as resources: + video = None + if args.video_frames: + import imageio.v2 as imageio + + video = resources.enter_context( + imageio.get_writer( + args.output.with_suffix(".mp4"), + fps=24, + codec="libx264", + macro_block_size=1, + ffmpeg_params=["-crf", "18", "-preset", "medium"], + ) + ) + # Repeated fixation and return exercise pose updates without accumulated rotation. + for phase, fixation in enumerate(fixations): + origin = np.array((0.15, -0.1, 0.0)) if phase in (1, 2) else np.zeros(3) + for camera in cameras.values(): + camera.set_world_poses(positions=torch.tensor(origin[None], device=sim.device, dtype=torch.float32)) + if args.sampling == "foveated": + camera.set_calibrated_fixation(torch.tensor((fixation,), device=sim.device, dtype=torch.float32)) + for _ in range(8): + sim.step() + if args.backend == "ovrtx": + from isaaclab.sensors import SensorBase + + SensorBase.update_batch(list(cameras.values()), sim.get_physics_dt()) + else: + for camera in cameras.values(): + camera.update(sim.get_physics_dt(), force_recompute=True) + for name, camera in cameras.items(): + rays, valid, forward_cosine = reference_rays(camera, cases[name], args.sampling, fixation) + expected = ray_depth(rays, origin) + output = camera.data.output["distance_to_camera"] + measured = (output.torch if isinstance(output, ProxyArray) else output).cpu().numpy().reshape(-1) + depth = camera.data.output["depth"] + depth = (depth.torch if isinstance(depth, ProxyArray) else depth).cpu().numpy().reshape(-1) + # Native RTX annotators measure ray range after advancing by near clip. + # Forward-axis depth still measures from the optical center. + expected_range = expected - NEAR if args.backend == "rtx" else expected + error = np.abs(measured[valid] - expected_range[valid]) + depth_error = np.abs(depth[valid] - expected[valid] * forward_cosine[valid]) + record = dict( + case=name, + phase=phase, + median_error_m=float(np.median(error)) if valid.any() else None, + p95_error_m=float(np.quantile(error, 0.95)) if valid.any() else None, + p99_error_m=float(np.quantile(error, 0.99)) if valid.any() else None, + max_error_m=float(error.max()) if valid.any() else None, + depth_p99_error_m=float(np.quantile(depth_error, 0.99)) if valid.any() else None, + valid_samples=int(valid.sum()), + ) + records.append(record) + print(json.dumps(record), flush=True) + rgb = camera.data.output["rgb"] + rgb = (rgb.torch if isinstance(rgb, ProxyArray) else rgb).cpu().numpy() + rgb_flat = rgb.reshape(-1, 3) + foreground = rgb_flat[:, 0] > rgb_flat[:, 2] + record["rgb_foreground_agreement"] = ( + float(np.mean(foreground[valid] == (expected[valid] < 3))) if valid.any() else None + ) + frames[f"{name}_{phase}"] = dict(distance=measured.copy(), expected=expected, valid=valid, rgb=rgb) + if not valid.all(): + assert np.all(rgb.reshape(-1, 3)[~valid] == 0), (name, phase, "color mask") + masked_depth = FAR if args.sampling == "dense" else 0 + assert np.all(measured[~valid] == masked_depth), (name, phase, "distance mask") + assert np.all(depth[~valid] == masked_depth), (name, phase, "depth mask") + if video is not None and phase >= 4: + frame = video_frame(frames, maps, phase, args.backend, fixation) + video.append_data(frame[:, :, ::-1]) + if args.video_frames: + import imageio_ffmpeg + + video_frames, _ = imageio_ffmpeg.count_frames_and_secs(str(args.output.with_suffix(".mp4"))) + if video_frames != args.video_frames: + raise AssertionError(f"Expected {args.video_frames} video frames, decoded {video_frames}") + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(records, indent=2) + "\n") + np.savez_compressed( + args.output.with_suffix(".npz"), + **{f"{key}_{channel}": value for key, frame in frames.items() for channel, value in frame.items()}, + ) + sim.stop() + for record in records: + if record["valid_samples"] == 0: + # RGB, range, and depth were required to be entirely zero above. + continue + assert record["p95_error_m"] < 0.01, record + assert record["p99_error_m"] < 0.03, record + assert record["depth_p99_error_m"] < 0.03, record + assert record["rgb_foreground_agreement"] > 0.99, record + for name in cases: + np.testing.assert_allclose(frames[f"{name}_0"]["distance"], frames[f"{name}_3"]["distance"], atol=0.001) + np.testing.assert_allclose(frames[f"{name}_1"]["distance"], frames[f"{name}_2"]["distance"], atol=0.001) + for name in ("intrinsics", "distortion", "pinhole", "brown"): + frame, baseline = frames[f"{name}_0"], frames["equidistant_0"] + assert abs(frame["distance"][frame["valid"]].mean() - baseline["distance"][baseline["valid"]].mean()) > 0.01, ( + name + ) + print("CALIBRATED RENDER CHECK PASSED", flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--backend", choices=("rtx", "newton", "ovrtx"), required=True) + parser.add_argument("--sampling", choices=("dense", "foveated"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--video_frames", type=int, default=0) + parser.add_argument("--near", type=float, default=NEAR) + AppLauncher.add_app_launcher_args(parser) + args = parser.parse_args() + NEAR = args.near + if args.video_frames < 0 or (args.video_frames and args.sampling != "foveated"): + parser.error("--video_frames must be nonnegative and requires --sampling foveated") + args.enable_cameras = True + faulthandler.dump_traceback_later(60, repeat=True) + launcher = None if args.backend == "ovrtx" else AppLauncher(args) + exit_code = 0 + try: + main(args) + except Exception: + exit_code = 1 + traceback.print_exc() + raise + finally: + if launcher is not None: + launcher.app.close(exit_code=exit_code) diff --git a/source/isaaclab_fovi/test/test_backend_dispatch.py b/source/isaaclab_fovi/test/test_backend_dispatch.py new file mode 100644 index 000000000000..daa65c511d95 --- /dev/null +++ b/source/isaaclab_fovi/test/test_backend_dispatch.py @@ -0,0 +1,36 @@ +# 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 + +"""Unsupported renderers fail before importing simulator backends.""" + +from dataclasses import dataclass + +import pytest + +from isaaclab_fovi.sensors import FoveatedTiledCamera + + +@dataclass +class RendererSelection: + renderer_type: str + + +@dataclass +class CameraSelection: + renderer_cfg: RendererSelection + tiled: bool + + +def test_unknown_backend_fails_explicitly() -> None: + cfg = CameraSelection(RendererSelection("unknown"), True) + with pytest.raises(ValueError, match="Unsupported foveated renderer"): + FoveatedTiledCamera(cfg) + + +@pytest.mark.parametrize("renderer_type", ["isaac_rtx", "ovrtx"]) +def test_non_tiled_rtx_fails_explicitly(renderer_type: str) -> None: + cfg = CameraSelection(RendererSelection(renderer_type), False) + with pytest.raises(NotImplementedError, match="Non-tiled.*not implemented"): + FoveatedTiledCamera(cfg) diff --git a/source/isaaclab_fovi/test/test_calibrated_camera_batch.py b/source/isaaclab_fovi/test/test_calibrated_camera_batch.py new file mode 100644 index 000000000000..28a1ea8f2fc7 --- /dev/null +++ b/source/isaaclab_fovi/test/test_calibrated_camera_batch.py @@ -0,0 +1,30 @@ +# 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 + +"""Batched captures preserve corrected ranges while the camera is not due.""" + +from types import SimpleNamespace + +import torch + +from isaaclab_fovi.sensors.calibrated_camera import CalibratedTiledCamera + + +def test_held_frame_does_not_accumulate_near_distance() -> None: + camera = SimpleNamespace() + camera.cfg = SimpleNamespace( + renderer_cfg=SimpleNamespace(renderer_type="ovrtx"), + spawn=SimpleNamespace(clipping_range=(0.04, 20.0)), + ) + camera._is_outdated = [True] + camera._env_mask_has_any = lambda mask: mask[0] + ranges = torch.tensor([[[[1.0], [2.0]]]]) + camera._data = SimpleNamespace(output={"distance_to_camera": SimpleNamespace(torch=ranges)}) + camera._invalid_pixels = torch.tensor([[[[False], [True]]]]) + CalibratedTiledCamera.process_rendered_frame(camera) + torch.testing.assert_close(ranges, torch.tensor([[[[1.04], [20.0]]]])) + camera._is_outdated[0] = False + CalibratedTiledCamera.process_rendered_frame(camera) + torch.testing.assert_close(ranges, torch.tensor([[[[1.04], [20.0]]]])) diff --git a/source/isaaclab_fovi/test/test_calibrated_camera_geometry.py b/source/isaaclab_fovi/test/test_calibrated_camera_geometry.py new file mode 100644 index 000000000000..ac9a96b86538 --- /dev/null +++ b/source/isaaclab_fovi/test/test_calibrated_camera_geometry.py @@ -0,0 +1,230 @@ +# 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 + +"""Physical-lens raster rays checked against independent OpenCV projections.""" + +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +# OpenCV provides the independent projection reference for these checks. +cv2 = pytest.importorskip("cv2") +CameraModel = pytest.importorskip("fovi.sensing.projection").CameraModel + +from isaaclab_fovi.sensors.dense_calibrated_geometry import ( # noqa: E402 + apply_lens_schema, + dense_camera_rays, + lens_schema_values, +) +from isaaclab_fovi.sensors.generalized_projection import ( # noqa: E402 + build_dense_calibrated_textures, +) + + +@pytest.mark.parametrize( + "model,distortion", + [ + ("pinhole", (-0.1, 0.02, 0.001, -0.002, 0.003)), + ("fisheye", (0.01, -0.003, 0.0002, -0.00001)), + ], +) +def test_dense_rays_reproject_to_original_pixel_centers(model: str, distortion: tuple[float, ...]) -> None: + camera = CameraModel(model, (120, 192), (72.5, 74, 93.2, 61.7), distortion) + rays, valid = dense_camera_rays(camera) + cv_rays = rays.double() * torch.tensor((1, -1, -1)) + points = cv_rays[valid].numpy().reshape(-1, 1, 3) + fx, fy, cx, cy = camera.intrinsics + matrix = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + project = cv2.fisheye.projectPoints if model == "fisheye" else cv2.projectPoints + pixels, _ = project(points, np.zeros(3), np.zeros(3), matrix, np.array(distortion)) + expected = valid.nonzero()[:, [1, 0]].numpy() + np.testing.assert_allclose(pixels[:, 0], expected, atol=5e-5) + assert valid.float().mean() > 0.9 + + +def test_image_circle_and_angular_domain_mask_dense_pixels() -> None: + camera = CameraModel("fisheye", (80, 120), (40, 40, 59.5, 39.5), image_circle=(59.5, 39.5, 35), max_angle_deg=40) + rays, valid = dense_camera_rays(camera) + assert valid[40, 60] and not valid[0, 0] + assert not valid[40, 95] # Inside raster but beyond angular domain. + assert torch.isfinite(rays).all() + torch.testing.assert_close(rays[~valid], torch.tensor([0.0, 0.0, -1.0]).expand((~valid).sum(), 3)) + + +def test_native_schema_keeps_brown_and_fisheye_coefficient_order() -> None: + camera = CameraModel("pinhole", (80, 120), (55, 58, 57, 42), (1, 2, 3, 4, 5)) + schema, token, attrs = lens_schema_values(camera) + assert schema == "OmniLensDistortionOpenCvPinholeAPI" and token == "opencvPinhole" + assert (attrs["p1"], attrs["p2"], attrs["k3"], attrs["k4"]) == (3, 4, 5, 0) + schema, token, attrs = lens_schema_values(CameraModel("fisheye", (80, 120), (55, 58, 57, 42))) + assert schema == "OmniLensDistortionOpenCvFisheyeAPI" and token == "opencvFisheye" + assert [attrs[f"k{i}"] for i in range(1, 5)] == [0, 0, 0, 0] + + +def test_native_schema_converts_integer_centers_to_pixel_edge_coordinates() -> None: + for model in ("pinhole", "fisheye"): + camera = CameraModel(model, (80, 120), (55, 58, 57, 42)) + _, _, attrs = lens_schema_values(camera) + assert (attrs["cx"], attrs["cy"]) == (57.5, 42.5) + + +@pytest.mark.parametrize("model", ["pinhole", "fisheye"]) +def test_native_usd_calibration_survives_stage_roundtrip(model: str) -> None: + Usd = pytest.importorskip("pxr.Usd") + from pxr import UsdGeom + + camera = CameraModel(model, (80, 120), (55, 58, 57, 42), (0.01, -0.002, 0.0001, 0.0)) + schema, token, attrs = lens_schema_values(camera) + stage = Usd.Stage.CreateInMemory() + prim = UsdGeom.Camera.Define(stage, "/Camera").GetPrim() + apply_lens_schema(prim, camera) + text = stage.GetRootLayer().ExportToString() + restored = Usd.Stage.CreateInMemory() + restored.GetRootLayer().ImportFromString(text) + prim = restored.GetPrimAtPath("/Camera") + assert schema in prim.GetMetadata("apiSchemas").GetAppliedItems() + assert prim.GetAttribute("omni:lensdistortion:model").Get() == token + assert tuple(prim.GetAttribute(f"omni:lensdistortion:{token}:imageSize").Get()) == (120, 80) + for key, value in attrs.items(): + assert prim.GetAttribute(f"omni:lensdistortion:{token}:{key}").Get() == pytest.approx(value) + + +def test_dense_fisheye_rtx_uses_lut_for_valid_rectangular_corners( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from isaaclab.sensors import Camera + from pxr import Usd, UsdGeom + + from isaaclab_fovi.sensors.calibrated_camera import CalibratedTiledCamera + + class InitializationOnlyCamera(CalibratedTiledCamera): + def __init__(self) -> None: + self.camera_model = CameraModel("fisheye", (24, 40), (18, 19, 18, 12)) + self.cfg = SimpleNamespace(prim_path="/Camera", renderer_cfg=SimpleNamespace(renderer_type="isaac_rtx")) + self.stage = Usd.Stage.CreateInMemory() + self._device = "cpu" + + def __del__(self) -> None: + pass + + camera = InitializationOnlyCamera() + prim = UsdGeom.Camera.Define(camera.stage, "/Camera").GetPrim() + monkeypatch.setattr(Camera, "_initialize_impl", lambda self: None) + camera._initialize_impl() + + assert not camera._invalid_pixels.any() + assert prim.GetAttribute("omni:lensdistortion:model").Get() == "lut" + assert "OmniLensDistortionLutAPI" in prim.GetMetadata("apiSchemas").GetAppliedItems() + paths = [ + Path(prim.GetAttribute(f"omni:lensdistortion:lut:{name}").Get().path) + for name in ("rayEnterDirectionTexture", "rayExitPositionTexture") + ] + assert all(path.is_file() for path in paths) + rays_bgr = cv2.imread(str(paths[0]), cv2.IMREAD_UNCHANGED) + expected, _ = dense_camera_rays(camera.camera_model) + np.testing.assert_array_equal(rays_bgr[..., ::-1], expected.numpy()) + + +@pytest.mark.parametrize("renderer", ["isaac_rtx", "ovrtx", "newton_warp"]) +def test_calibrated_metadata_initialization_preserves_measured_intrinsics( + renderer: str, caplog: pytest.LogCaptureFixture +) -> None: + from isaaclab.sensors.camera.camera_data import CameraData + from pxr import Sdf, Usd, UsdGeom + + from isaaclab_fovi.sensors.calibrated_camera import CalibratedTiledCamera + + class MetadataOnlyCamera(CalibratedTiledCamera): + def __init__(self) -> None: + self.camera_model = CameraModel("fisheye", (80, 120), (55, 58, 57, 42)).resized((40, 60)) + self.cfg = SimpleNamespace(height=40, width=60) + self._device = "cpu" + self._view = SimpleNamespace(count=2) + self._data_generation = self._data_generation_last_update = 0 + self._data_dirty = False + self.stage = Usd.Stage.CreateInMemory() + self._sensor_prims = [UsdGeom.Camera.Define(self.stage, f"/Camera{i}") for i in range(2)] + for camera in self._sensor_prims: + camera.GetFocalLengthAttr().Set(20) + camera.GetHorizontalApertureAttr().Set(10) + if renderer != "newton_warp": + camera.GetPrim().CreateAttribute("omni:lensdistortion:model", Sdf.ValueTypeNames.Token).Set("lut") + self._data = CameraData() + self._data.create_buffers(2, "cpu") + + def __del__(self) -> None: + pass + + camera = MetadataOnlyCamera() + camera._initialize_intrinsics() + # Half-pixel-aware resize of the original integer-center calibration. + expected = np.array(((27.5, 0, 28.25), (0, 29, 20.75), (0, 0, 1))) + np.testing.assert_array_equal(camera.data.intrinsic_matrices.torch.numpy(), np.repeat(expected[None], 2, axis=0)) + assert "falling back" not in caplog.text + assert camera._sensor_prims[0].GetFocalLengthAttr().Get() == 20 + + +@pytest.mark.parametrize("distortion", [(), (0.01, -0.003, 0.0002, -0.00001)]) +def test_dense_lut_inverse_preserves_pixel_centers_and_depth_directions( + distortion: tuple[float, ...], +) -> None: + height, width = 24, 40 + camera = CameraModel("fisheye", (height, width), (18, 19, 18, 12), distortion) + directions, inverse = build_dense_calibrated_textures(camera, exit_size=4 * width + 1) + # These physically valid corners lie outside the native RTX fisheye circle. + assert all( + torch.isfinite(directions[row, col]).all() + for row, col in ((0, 0), (0, width - 1), (height - 1, 0), (height - 1, width - 1)) + ) + cv_directions = directions.numpy() * (1, -1, -1) + matrix = np.array(((18, 0, 18), (0, 19, 12), (0, 0, 1)), dtype=np.float64) + pixels, _ = cv2.fisheye.projectPoints( + cv_directions.reshape(-1, 1, 3), + np.zeros(3), + np.zeros(3), + matrix, + np.asarray(distortion or (0, 0, 0, 0), dtype=np.float64), + ) + row, col = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij") + expected_pixels = torch.stack((col, row), -1).numpy() + np.testing.assert_allclose(pixels.reshape(height, width, 2), expected_pixels, atol=5e-5) + torch.testing.assert_close(directions.norm(dim=-1), torch.ones(height, width)) + + # For front-hemisphere rays, octahedral texture coordinates are the signed + # XY components divided by the L1 norm, then mapped from [-1, 1] to [0, 1]. + octahedral_xy = directions[..., :2] / directions.abs().sum(-1, keepdim=True) + recovered_uv = torch.nn.functional.grid_sample( + inverse.permute(2, 0, 1)[None], + octahedral_xy[None], + mode="bilinear", + align_corners=False, + )[0].permute(1, 2, 0) + recovered_pixels = recovered_uv * torch.tensor((width, height)) - 0.5 + # Bilinear interpolation across octahedral axis seams has finite-table error; + # keep it below a tenth pixel, well below a half-pixel convention mismatch. + # Exclude raster boundaries where interpolation includes the invalid sentinel. + torch.testing.assert_close( + recovered_pixels[1:-1, 1:-1], + torch.stack((col, row), -1).float()[1:-1, 1:-1], + rtol=0, + atol=0.1, + ) + torch.testing.assert_close(recovered_pixels[12, 18], torch.tensor((18.0, 12.0)), rtol=0, atol=2e-6) + + +def test_dense_lut_inverse_keeps_declared_image_circle_and_angle_mask() -> None: + camera = CameraModel("fisheye", (24, 40), (18, 19, 18, 12), image_circle=(18, 12, 7), max_angle_deg=15) + _, inverse = build_dense_calibrated_textures(camera, exit_size=128) + valid = (inverse >= 0).all(-1) + assert valid.any() and not valid.all() + pixels = inverse[valid].double() * torch.tensor((40, 24)) - 0.5 + rays, pixel_valid = camera.unproject(pixels) + assert pixel_valid.all() + assert torch.linalg.vector_norm(pixels - pixels.new_tensor((18, 12)), dim=-1).max() <= 7 + assert torch.acos(rays[:, 2]).rad2deg().max() <= 15 + assert torch.all(inverse[~valid] == -1) diff --git a/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py b/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py new file mode 100644 index 000000000000..bd6a5d12f807 --- /dev/null +++ b/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py @@ -0,0 +1,49 @@ +# 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 + +"""CUDA gaze fusion agrees with eager geometry and reads live replay inputs.""" + +import pytest +import torch +from fovi.sensing.projection import CameraModel, gaze_rotation + +from isaaclab_fovi.sensors.calibrated_geometry import ( + calibrated_fixation_rotation, + calibrated_mount_angles, +) + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA") + + +@pytest.mark.parametrize("projection", ["pinhole", "fisheye"]) +def test_calibrated_gaze_fusion_replay(projection: str) -> None: + distortion = (0.01, -0.003, 0.0002, -0.00001) + if projection == "pinhole": + distortion = (0.01, -0.003, 0.0002, -0.00001, 0.0001) + camera = CameraModel(projection, (120, 192), (72, 71, 96, 60), distortion) + axis = torch.linspace(-0.1, 1.1, 32, device="cuda") + fixation = torch.stack(torch.meshgrid(axis, axis, indexing="ij"), -1).reshape(-1, 2) + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + calibrated_fixation_rotation(camera, fixation) + calibrated_mount_angles(camera, fixation) + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + rotation, valid = calibrated_fixation_rotation(camera, fixation) + angles = calibrated_mount_angles(camera, fixation) + + for delta in (0.0, 0.01, -0.02): + fixation.add_(delta) + graph.replay() + pixels = torch.stack((fixation[:, 1] * 192 - 0.5, fixation[:, 0] * 120 - 0.5), -1) + direction, expected_valid = camera.unproject(pixels) + x, y, z = direction.unbind(-1) + expected_angles = torch.stack((-torch.atan2(y, (x * x + z * z).sqrt()), -torch.atan2(x, z)), -1) + torch.testing.assert_close(rotation, gaze_rotation(direction, "pan_tilt"), atol=2e-6, rtol=2e-6) + torch.testing.assert_close(angles, expected_angles, atol=2e-6, rtol=2e-6) + assert torch.equal(valid, expected_valid) diff --git a/source/isaaclab_fovi/test/test_dense_foveated_lens_parity.py b/source/isaaclab_fovi/test/test_dense_foveated_lens_parity.py new file mode 100644 index 000000000000..97d82f824a61 --- /dev/null +++ b/source/isaaclab_fovi/test/test_dense_foveated_lens_parity.py @@ -0,0 +1,39 @@ +# 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 + +"""Dense raster and foveated renderers must use the same physical lens rays.""" + +import pytest +import torch +from fovi.sensing.projection import CameraModel, gaze_rotation + +from isaaclab_fovi.sensors.calibrated_geometry import calibrated_visibility, retinal_directions +from isaaclab_fovi.sensors.dense_calibrated_geometry import dense_camera_rays + + +@pytest.mark.parametrize( + "model,distortion", + [ + ("pinhole", (-0.06, 0.01, 0.001, -0.002, 0.0)), + ("fisheye", (0.01, -0.003, 0.0001, 0.0)), + ], +) +def test_dense_and_foveated_rays_agree_under_off_axis_gaze(model: str, distortion: tuple[float, ...]) -> None: + camera = CameraModel(model, (120, 192), (100, 103, 93.4, 61.2), distortion) + dense, valid = dense_camera_rays(camera) + pixels = torch.tensor([[50, 40], [100, 60], [140, 80]]) + assert valid[pixels[:, 1], pixels[:, 0]].all() + source_rays = dense[pixels[:, 1], pixels[:, 0]].double() * torch.tensor([1, -1, -1]) + rotation = gaze_rotation(torch.tensor([[0.2, -0.1, 1.0]], dtype=torch.float64), "pan_tilt")[0] + retinal = source_rays @ rotation + theta = torch.atan2(torch.linalg.vector_norm(retinal[:, :2], dim=-1), retinal[:, 2]) + xy = torch.nn.functional.normalize(retinal[:, :2], dim=-1) * theta[:, None] + cartesian = xy * torch.tensor([1, -1]) / torch.deg2rad(torch.tensor(60.0)) + rendered = retinal_directions(cartesian, 120) * torch.tensor([1, -1, -1]) + torch.testing.assert_close(rendered @ rotation.T, source_rays, atol=1e-7, rtol=1e-7) + recovered, projected_valid = camera.project(rendered @ rotation.T) + torch.testing.assert_close(recovered, pixels.double(), atol=2e-5, rtol=0) + assert projected_valid.all() + torch.testing.assert_close(calibrated_visibility(camera, rendered, rotation[None])[0], projected_valid) diff --git a/source/isaaclab_fovi/test/test_hybrid_geometry.py b/source/isaaclab_fovi/test/test_hybrid_geometry.py new file mode 100644 index 000000000000..bcf5f3883070 --- /dev/null +++ b/source/isaaclab_fovi/test/test_hybrid_geometry.py @@ -0,0 +1,313 @@ +# 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 + +import math + +import numpy as np +import pytest +import torch +from scipy.spatial.transform import Rotation as R + +from isaaclab_fovi.sensors.fixed_software_fov import ( + fixed_frustum_validity, + image_fixation_to_camera_angles, + image_fixation_to_pan_tilt_angles, + retinal_ray_directions, +) + + +def test_center_image_fixation_preserves_camera_axis() -> None: + angles = image_fixation_to_camera_angles( + torch.tensor([[0.5, 0.5]]), + image_height=120, + image_width=160, + focal_length_px=100.0, + principal_point=(80.0, 60.0), + ) + + torch.testing.assert_close(angles, torch.zeros_like(angles)) + + +def test_image_rotation_rotates_normalized_fixation_before_steering() -> None: + fixation = torch.tensor([[0.5, 0.75]]) + unrotated = image_fixation_to_camera_angles( + fixation, + image_height=100, + image_width=100, + focal_length_px=100.0, + principal_point=(50.0, 50.0), + ) + rotated = image_fixation_to_camera_angles( + fixation, + image_height=100, + image_width=100, + focal_length_px=100.0, + principal_point=(50.0, 50.0), + image_rotation_deg=90.0, + ) + + assert unrotated[0, 0].abs() < 1.0e-7 + assert unrotated[0, 1] < 0.0 + assert rotated[0, 0] > 0.0 + assert rotated[0, 1].abs() < 1.0e-7 + + +@pytest.mark.parametrize( + "fixation", + [ + (0.2, 0.8), + (0.75, 0.15), + (0.1, 0.3), + ], +) +def test_pan_tilt_image_conversion_centers_off_axis_rays( + fixation: tuple[float, float], +) -> None: + image_height = 160 + image_width = 120 + focal_length_px = 180.0 + command = image_fixation_to_pan_tilt_angles( + torch.tensor([fixation]), + image_height=image_height, + image_width=image_width, + focal_length_px=focal_length_px, + principal_point=(image_width * 0.5, image_height * 0.5), + )[0] + tilt, pan = command.tolist() + + # The mount is +Y-forward with pan about +Z followed by tilt about the + # panned +X axis. Compare the resulting optical axis against the pinhole + # ray independently of the implementation under test. + optical_axis = torch.tensor( + [ + -math.sin(pan) * math.cos(tilt), + math.cos(pan) * math.cos(tilt), + math.sin(tilt), + ] + ) + expected_tangent = torch.tensor( + [ + (fixation[1] * image_width - image_width * 0.5) / focal_length_px, + (image_height * 0.5 - fixation[0] * image_height) / focal_length_px, + ] + ) + actual_tangent = optical_axis[[0, 2]] / optical_axis[1] + + torch.testing.assert_close(actual_tangent, expected_tangent) + + +def test_fixed_frustum_masks_direct_rays_after_off_center_steering() -> None: + cartesian = torch.tensor( + [ + [0.0, 0.0], + [-0.9, 0.0], + [0.9, 0.0], + ] + ) + directions = retinal_ray_directions( + cartesian, + image_height=120, + image_width=160, + focal_length_px=100.0, + retinal_window_short_side_fraction=1.0, + ) + fixation = image_fixation_to_camera_angles( + torch.tensor([[0.5, 0.9]]), + image_height=120, + image_width=160, + focal_length_px=100.0, + principal_point=(80.0, 60.0), + ) + + valid = fixed_frustum_validity( + directions, + fixation, + image_height=120, + image_width=160, + focal_length_px=100.0, + principal_point=(80.0, 60.0), + ) + + assert valid.shape == (1, 3) + assert valid[0, 0] + assert valid[0].sum() < valid.shape[1] + + +@pytest.mark.parametrize("image_rotation_deg", [-90.0, 0.0, 90.0, 180.0]) +def test_fixed_frustum_pan_tilt_matches_physical_mount_kinematics( + image_rotation_deg: float, +) -> None: + raw_height = 120 + raw_width = 160 + focal_length_px = 100.0 + if round(image_rotation_deg / 90.0) % 2: + policy_height, policy_width = raw_width, raw_height + else: + policy_height, policy_width = raw_height, raw_width + cartesian = torch.tensor( + [ + [0.0, 0.0], + [-1.0, -0.7], + [-0.4, 0.8], + [0.6, -0.5], + [1.0, 0.9], + ], + dtype=torch.float64, + ) + rays = retinal_ray_directions( + cartesian, + image_height=raw_height, + image_width=raw_width, + focal_length_px=focal_length_px, + retinal_window_short_side_fraction=1.0, + retinal_window_reference_side="long", + image_rotation_deg=image_rotation_deg, + ) + mount_angles = image_fixation_to_pan_tilt_angles( + torch.tensor([[0.18, 0.81]], dtype=torch.float64), + image_height=policy_height, + image_width=policy_width, + focal_length_px=focal_length_px, + principal_point=(policy_width * 0.5, policy_height * 0.5), + ) + + actual = fixed_frustum_validity( + rays, + mount_angles, + image_height=raw_height, + image_width=raw_width, + focal_length_px=focal_length_px, + principal_point=(raw_width * 0.5, raw_height * 0.5), + angle_model="pan_tilt", + image_rotation_deg=image_rotation_deg, + ) + + tilt, pan = mount_angles[0].tolist() + camera_to_policy = R.from_euler("z", -image_rotation_deg, degrees=True) + policy_to_camera = camera_to_policy.inv() + policy_rays = camera_to_policy.apply(rays.numpy()) + mount_rays = np.column_stack((policy_rays[:, 0], -policy_rays[:, 2], policy_rays[:, 1])) + mount_motion = R.from_euler("z", pan) * R.from_euler("x", tilt) + moved_mount_rays = mount_motion.apply(mount_rays) + moved_policy_rays = np.column_stack((moved_mount_rays[:, 0], moved_mount_rays[:, 2], -moved_mount_rays[:, 1])) + moved_camera_rays = policy_to_camera.apply(moved_policy_rays) + forward = -moved_camera_rays[:, 2] + pixel_x = focal_length_px * moved_camera_rays[:, 0] / forward + raw_width * 0.5 + pixel_y = raw_height * 0.5 - focal_length_px * moved_camera_rays[:, 1] / forward + expected = (forward > 0.0) & (pixel_x >= 0.0) & (pixel_x < raw_width) & (pixel_y >= 0.0) & (pixel_y < raw_height) + + assert torch.equal(actual[0], torch.from_numpy(expected)) + + +@pytest.mark.parametrize( + ("reference_side", "expected_tangent"), + (("short", 0.6), ("long", 0.8)), +) +def test_retinal_ray_directions_select_reference_side( + reference_side: str, + expected_tangent: float, +) -> None: + directions = retinal_ray_directions( + torch.tensor([[1.0, 0.0]]), + image_height=120, + image_width=160, + focal_length_px=100.0, + retinal_window_short_side_fraction=1.0, + retinal_window_reference_side=reference_side, + ) + + tangent = directions[0, 0] / -directions[0, 2] + assert tangent.item() == pytest.approx(expected_tangent) + + +def test_retinal_ray_directions_reject_invalid_reference_side() -> None: + with pytest.raises(ValueError, match="retinal_window_reference_side"): + retinal_ray_directions( + torch.tensor([[0.0, 0.0]]), + image_height=120, + image_width=160, + focal_length_px=100.0, + retinal_window_short_side_fraction=1.0, + retinal_window_reference_side="diagonal", + ) + + +def test_fixed_fov_ray_and_mask_geometry_is_scale_invariant() -> None: + cartesian = torch.tensor([[0.0, 0.0], [-0.8, 0.1], [0.9, -0.2]]) + fixation = torch.tensor([[0.3, 0.85]]) + reference_directions = None + reference_validity = None + + for scale in (1, 4, 8): + height = 120 * scale + width = 160 * scale + focal_length_px = 100.0 * scale + directions = retinal_ray_directions( + cartesian, + image_height=height, + image_width=width, + focal_length_px=focal_length_px, + retinal_window_short_side_fraction=1.0, + ) + fixation_angles = image_fixation_to_camera_angles( + fixation, + image_height=height, + image_width=width, + focal_length_px=focal_length_px, + principal_point=(width * 0.5, height * 0.5), + ) + validity = fixed_frustum_validity( + directions, + fixation_angles, + image_height=height, + image_width=width, + focal_length_px=focal_length_px, + principal_point=(width * 0.5, height * 0.5), + ) + + if reference_directions is None: + reference_directions = directions + reference_validity = validity + else: + torch.testing.assert_close(directions, reference_directions) + assert torch.equal(validity, reference_validity) + + +def test_fixed_frustum_matches_half_open_image_boundaries() -> None: + directions = torch.tensor( + [[-0.6, 0.0, -0.8], [0.6, 0.0, -0.8], [0.0, 0.6, -0.8], [0.0, -0.6, -0.8], [0.0, 0.0, 1.0]], + dtype=torch.float64, + ) + valid = fixed_frustum_validity( + directions, + torch.zeros(1, 2, dtype=torch.float64), + image_height=150, + image_width=150, + focal_length_px=100.0, + principal_point=(75.0, 75.0), + ) + assert valid.tolist() == [[True, False, True, False, False]] + + +@pytest.mark.parametrize("principal_point", [(70.0, 45.0), (95.0, 75.0)]) +def test_fixation_optical_axis_projects_to_calibrated_image_location( + principal_point: tuple[float, float], +) -> None: + fixation = torch.tensor([[0.25, 0.7]], dtype=torch.float64) + angles = image_fixation_to_camera_angles( + fixation, + image_height=120, + image_width=160, + focal_length_px=100.0, + principal_point=principal_point, + ) + roll, pitch = angles[0].tolist() + # Independent rotations project the steered central ray into the dense image. + motion = R.from_euler("x", roll) * R.from_euler("y", pitch) + direction = motion.apply(np.array([0.0, 0.0, -1.0])) + pixel_x = 100.0 * direction[0] / -direction[2] + principal_point[0] + pixel_y = principal_point[1] - 100.0 * direction[1] / -direction[2] + assert pixel_x == pytest.approx(0.7 * 160) + assert pixel_y == pytest.approx(0.25 * 120) diff --git a/source/isaaclab_fovi/test/test_imports.py b/source/isaaclab_fovi/test/test_imports.py new file mode 100644 index 000000000000..0e2e69bcb379 --- /dev/null +++ b/source/isaaclab_fovi/test/test_imports.py @@ -0,0 +1,26 @@ +# 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 + +"""Verify package import boundaries in a fresh interpreter.""" + +import subprocess +import sys +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.kitless + + +def test_geometry_imports_without_research_or_rtx_runtime() -> None: + result = subprocess.run( + [sys.executable, str(Path(__file__).with_name("_check_imports.py"))], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + assert "Standalone import boundary passed" in result.stdout diff --git a/source/isaaclab_fovi/test/test_lens_schema.py b/source/isaaclab_fovi/test/test_lens_schema.py new file mode 100644 index 000000000000..27c34198e1a5 --- /dev/null +++ b/source/isaaclab_fovi/test/test_lens_schema.py @@ -0,0 +1,34 @@ +# 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 + +"""Native LUT metadata and assets survive USD export without schema registration.""" + +import pytest + +Usd = pytest.importorskip("pxr.Usd") +from pxr import UsdGeom # noqa: E402 + +from isaaclab_fovi.sensors.generalized_projection import ( # noqa: E402 + apply_generalized_projection_to_prim, +) + + +def test_lut_schema_has_explicit_model_and_assets_after_export() -> None: + stage = Usd.Stage.CreateInMemory() + prim = UsdGeom.Camera.Define(stage, "/Camera").GetPrim() + apply_generalized_projection_to_prim(prim, "/tmp/direction.exr", "/tmp/exit.exr") + restored = Usd.Stage.CreateInMemory() + restored.GetRootLayer().ImportFromString(stage.GetRootLayer().ExportToString()) + prim = restored.GetPrimAtPath("/Camera") + assert "OmniLensDistortionLutAPI" in prim.GetMetadata("apiSchemas").GetAppliedItems() + assert prim.GetAttribute("omni:lensdistortion:model").Get() == "lut" + assert prim.GetAttribute("omni:lensdistortion:lut:rayEnterDirectionTexture").Get().path == "/tmp/direction.exr" + assert prim.GetAttribute("omni:lensdistortion:lut:rayExitPositionTexture").Get().path == "/tmp/exit.exr" + for name in ( + "cameraProjectionType", + "generalizedProjectionDirectionTexturePath", + "generalizedProjectionNDCTexturePath", + ): + assert not prim.HasProperty(name), name diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py new file mode 100644 index 000000000000..9defbc80a83c --- /dev/null +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -0,0 +1,154 @@ +# 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 + +"""Native sensor texture geometry agrees with Fovi's ordered samples.""" + +import math + +import pytest +import torch +from fovi.sensing.coords import SamplingCoords + +from isaaclab_fovi.sensors.generalized_projection import build_native_grid_textures +from isaaclab_fovi.sensors.native_grid import ( + allocate_grid_outputs, + bounded_angular_radius, + canonical_to_grid, + copy_grid_outputs, + grid_sample_indices, + mask_grid_samples, + native_grid_directions, + native_grid_exit_uv, + unbounded_angular_radius, +) + + +def make_coords(field: str, resolution: int = 64, coverage: str = "circular") -> SamplingCoords: + fov = (80.0 if coverage == "wang" else 170.0) if field == "spherical" else 1.0 + return SamplingCoords( + fov=fov, + cmf_a=0.036021 * fov, + res=resolution, + style="warped_cartesian_as_grid", + fov_type=coverage, + field_geometry=field, + device="cpu", + ) + + +@pytest.mark.parametrize("field", ["planar", "spherical"]) +@pytest.mark.parametrize("resolution", [64, 128]) +@pytest.mark.parametrize("rotation", [0.0, 180.0, 37.0]) +@pytest.mark.parametrize("coverage", ["circular", "square", "wang"]) +def test_analytic_inverse_returns_every_native_texel(field, resolution, rotation, coverage): + coords = make_coords(field, resolution, coverage) + rays = native_grid_directions(coords, tangent_scale=0.7, image_rotation_deg=rotation) + uv, valid = native_grid_exit_uv(rays, coords, tangent_scale=0.7, image_rotation_deg=rotation) + axis = (torch.arange(resolution) + 0.5) / resolution + row, col = torch.meshgrid(axis, axis, indexing="ij") + expected = torch.stack((col, row), -1).reshape(-1, 2) + assert valid.all() + torch.testing.assert_close(uv, expected, atol=2e-6, rtol=0) + torch.testing.assert_close(rays.norm(dim=-1), torch.ones(len(coords)), atol=1e-6, rtol=0) + + +@pytest.mark.parametrize("coverage", ["circular", "square", "wang"]) +def test_spherical_valid_samples_match_calibrated_software_rays(coverage): + from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions + + coords = make_coords("spherical", coverage=coverage) + actual = native_grid_directions(coords, tangent_scale=0.7) + expected = retinal_directions(coords.cartesian[coords.valid_mask], coords.fov) + torch.testing.assert_close(actual[coords.valid_mask], expected, atol=3e-7, rtol=0) + + +def test_planar_equidistant_preserves_lens_projection(): + from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions + + coords = make_coords("planar") + rays = native_grid_directions( + coords, + tangent_scale=0.7, + projection="fisheye_equidistant", + camera_fov_rad=math.radians(150), + ) + expected = retinal_directions(coords.cartesian[coords.valid_mask], 150) + torch.testing.assert_close(rays[coords.valid_mask], expected, atol=3e-7, rtol=0) + uv, valid = native_grid_exit_uv( + rays, + coords, + tangent_scale=0.7, + projection="fisheye_equidistant", + camera_fov_rad=math.radians(150), + ) + torch.testing.assert_close(uv, (coords.cortical.flip(-1) + 1) / 2, atol=2e-6, rtol=0) + assert valid.all() + + +def test_spherical_padding_matches_rim_slope_and_does_not_wrap(): + radius = torch.tensor([0.0, 0.99999, 1.0, 1.00001, 2.0, 10.0], dtype=torch.float64) + half_fov = math.radians(170) / 2 + angles = bounded_angular_radius(radius, half_fov) + assert (angles[1:] > angles[:-1]).all() + assert (angles < math.pi).all() + left = (angles[2] - angles[1]) / (radius[2] - radius[1]) + right = (angles[3] - angles[2]) / (radius[3] - radius[2]) + torch.testing.assert_close(left, right, atol=2e-5, rtol=0) + torch.testing.assert_close(unbounded_angular_radius(angles, half_fov), radius, atol=1e-10, rtol=0) + + +@pytest.mark.parametrize("field", ["planar", "spherical"]) +def test_direction_texture_is_native_rays_without_assignment(field): + coords = make_coords(field, 64) + direction, inverse = build_native_grid_textures(coords, tangent_scale=0.7, image_rotation_deg=0, exit_size=256) + expected = native_grid_directions(coords, tangent_scale=0.7) + torch.testing.assert_close(direction.reshape(-1, 3), expected, atol=0, rtol=0) + assert direction.shape == (64, 64, 3) + assert inverse.shape == (256, 256, 2) + assert torch.isfinite(inverse).all() + assert (inverse == -1).any() + + +def test_upright_grid_masks_and_channel_aliases(): + coords = make_coords("planar", 16) + # Coordinate channels make rotation/transposition failures observable. + values = torch.cat((coords.cartesian, torch.ones(len(coords), 2)), -1)[None, :, None] + source = {"rgba": values.clone(), "rgb": values[..., :3]} + source["rgb"] = source["rgba"][..., :3] + mask_grid_samples(source, coords) + target = allocate_grid_outputs(source, coords) + copy_grid_outputs(source, target, grid_sample_indices(coords)) + expected = coords.as_grid(source["rgba"][:, :, 0], sample_dim=1) + torch.testing.assert_close(target["rgba"], expected) + assert target["rgb"].untyped_storage().data_ptr() == target["rgba"].untyped_storage().data_ptr() + assert target["rgba"][0, :, :, 0][8, 4] < target["rgba"][0, :, :, 0][8, 11] + assert target["rgba"][0, :, :, 1][4, 8] > target["rgba"][0, :, :, 1][11, 8] + assert (target["rgba"][0][~coords.as_grid(coords.valid_mask)] == 0).all() + torch.testing.assert_close(canonical_to_grid(source["rgba"], coords), expected) + + +@pytest.mark.parametrize("dtype,channels", [(torch.uint8, 4), (torch.float32, 1), (torch.int32, 1)]) +@pytest.mark.parametrize("device", ["cpu", "cuda"]) +def test_output_permutation_preserves_dtype_and_captures(dtype, channels, device): + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA required") + coords = make_coords("planar", 16).to(device=device) + source = { + "value": torch.arange(3 * len(coords) * channels, device=device).to(dtype).reshape(3, len(coords), 1, channels) + } + target = allocate_grid_outputs(source, coords) + indices = grid_sample_indices(coords) + copy_grid_outputs(source, target, indices) + expected = canonical_to_grid(source["value"], coords) + torch.testing.assert_close(target["value"], expected, atol=0, rtol=0) + if device == "cuda": + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + copy_grid_outputs(source, target, indices) + source["value"].zero_() + graph.replay() + torch.cuda.synchronize() + assert torch.count_nonzero(target["value"]) == 0 diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py new file mode 100644 index 000000000000..c793857167a8 --- /dev/null +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -0,0 +1,138 @@ +# 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 + +"""Newton anti-aliasing consumes IsaacLab's public renderer-buffer views.""" + +from types import SimpleNamespace + +import pytest +import torch +import warp as wp +from fovi.sensing.coords import SamplingCoords +from isaaclab.renderers.output_contract import RenderBufferKind, RenderBufferSpec +from isaaclab.sensors.camera.camera_data import CameraData +from isaaclab.utils.warp import ProxyArray + +from isaaclab_fovi.sensors import foveated_newton_tiled_camera as newton_camera +from isaaclab_fovi.sensors.foveated_newton_tiled_camera import FoveatedNewtonTiledCamera + + +def test_pooled_allocation_accepts_proxy_arrays_and_preserves_render_buffers() -> None: + rgba = torch.zeros((1, 8, 1, 4), dtype=torch.uint8) + rgba_proxy = ProxyArray(wp.from_torch(rgba)) + data = CameraData.allocate( + ["rgba"], + 8, + 1, + 1, + "cpu", + {RenderBufferKind.RGBA: RenderBufferSpec(channels=4, dtype=wp.uint8)}, + ) + data.output["rgba"] = rgba_proxy + camera = SimpleNamespace() + camera._data = data + camera._pooler = torch.nn.Identity() + camera._pooler_int = None + camera._num_valid_samples = 4 + camera._num_ray_samples = 8 + camera._pool_k = 2 + camera.cfg = SimpleNamespace(data_types=["rgba"], pool_int_mode="max", pool_mode="avg", pool_sample_cortex=False) + + FoveatedNewtonTiledCamera._allocate_pooled_buffers(camera) + + assert camera._pooled_output["rgba"].shape == (1, 4, 1, 4) + assert camera._pooled_output["rgba"].dtype == torch.uint8 + assert camera._highres_output["rgba"] is rgba_proxy + assert camera._highres_output is not data.output + + +@pytest.mark.parametrize("pooled", [False, True]) +def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatch, pooled) -> None: + coords = SamplingCoords(1.0, 0.036021, 16, style="warped_cartesian_as_grid", device="cpu") + highres = coords.clone(resolution=32) if pooled else None + ray_coords = highres if pooled else coords + pooler = torch.nn.AdaptiveAvgPool1d(len(coords)) if pooled else None + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (pooler, 4)) + monkeypatch.setattr(FoveatedNewtonTiledCamera, "_initialize_calibrated_gaze", lambda self: None) + + def initialize_renderer(camera): + # Newton launches image tiles; a vector-shaped width of one is not valid. + assert camera.cfg.height == camera.cfg.width == ray_coords.resolution + rgba = torch.zeros((2, camera.cfg.height, camera.cfg.width, 4), dtype=torch.uint8) + camera._data = SimpleNamespace( + output={ + "rgba": ProxyArray(wp.from_torch(rgba)), + "rgb": ProxyArray(wp.from_torch(rgba[..., :3])), + } + ) + camera._render_data = SimpleNamespace(camera_rays=None) + camera._renderer = SimpleNamespace( + cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + cleanup=lambda render_data: None, + ) + camera.renderer_rgba = rgba + + def render(camera, env_mask): + assert camera._data.output["rgba"].torch.shape == camera.renderer_rgba.shape + values = torch.arange(camera.renderer_rgba.numel()).reshape(camera.renderer_rgba.shape) + camera.renderer_rgba.copy_(values.to(torch.uint8)) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) + camera = object.__new__(FoveatedNewtonTiledCamera) + camera._initialize_handle = None + camera._invalidate_initialize_handle = None + camera._prim_deletion_handle = None + camera._view = None + camera._renderer = None + camera._device = "cpu" + camera._spawn_horizontal_aperture = 1.0 + camera._spawn_focal_length = 1.0 + camera.cfg = SimpleNamespace( + foveated_style="warped_cartesian_as_grid", + fixed_software_fov=False, + cmf_a=0.036021, + pool_enabled=pooled, + pool_mode="avg", + pool_int_mode="avg", + pool_sample_cortex=False, + projection="pinhole", + field_geometry="planar", + image_rotation_deg=0, + data_types=["rgba", "rgb"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + + rays = wp.to_torch(camera._foveated_rays) + assert rays.shape == (1, ray_coords.resolution, ray_coords.resolution, 2, 3) + torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], camera._fixed_fov_ray_directions) + public_rgba = camera._data.output["rgba"] + camera._update_buffers_impl(None) + expected = camera.renderer_rgba.reshape(2, len(ray_coords), 1, 4).clone() + expected[:, ~ray_coords.valid_mask] = 0 + if pooled: + expected = newton_camera.pool_hwc_buffer(pooler, expected.float()).to(torch.uint8) + expected = coords.as_grid(expected.squeeze(2), sample_dim=1) + torch.testing.assert_close(camera._data.output["rgba"], expected, rtol=0, atol=0) + assert camera._data.output["rgba"] is public_rgba + assert camera._data.output["rgb"].untyped_storage().data_ptr() == public_rgba.untyped_storage().data_ptr() + + +@pytest.mark.parametrize("render_order", ["tiled", "pixel_priority", "view_priority"]) +def test_native_grid_fractional_pool_resolution_validates_newton_tiles(render_order) -> None: + camera = SimpleNamespace( + cfg=SimpleNamespace(width=83, height=83), + _renderer=SimpleNamespace( + cfg=SimpleNamespace(render_order=render_order, tile_rendering_width=16, tile_rendering_height=8) + ), + ) + if render_order == "tiled": + with pytest.raises(ValueError, match="83x83.*16x8"): + FoveatedNewtonTiledCamera._validate_native_render_layout(camera) + else: + FoveatedNewtonTiledCamera._validate_native_render_layout(camera) diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py new file mode 100644 index 000000000000..56265ddcd180 --- /dev/null +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -0,0 +1,161 @@ +# 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 + +"""Dual-grid geometry and modality-specific pooling without a simulator.""" + +from dataclasses import dataclass + +import pytest +import torch +from fovi.arch.knn import KNNPoolingLayer +from fovi.arch.pooling import GridPoolingLayer + +from isaaclab_fovi.sensors.pooling import ( + build_highres_coords, + build_lowres_coords, + build_pooler, + is_segmentation_output, + pool_hwc_buffer, +) + + +@dataclass +class SamplingConfig: + """Sampling fields consumed by the shared pooling helpers.""" + + cmf_a: float = 0.1 + cmf_a_frac: float | None = None + field_geometry: str = "planar" + camera_calibration: dict[str, str | tuple[int, int] | tuple[float, ...]] | None = None + retinal_window_reference_side: str = "short" + retinal_window_short_side_fraction: float = 1.0 + foveated_res: int = 8 + foveated_style: str = "isotropic" + fov_type: str = "circular" + radius_norm: float = 2.0 + isotropic_plotting_type: str = "v1like" + pool_enabled: bool = True + pool_res_mult: float = 2.0 + pool_k: int | None = 3 + pool_mode: str = "avg" + pool_sample_cortex: bool = False + pool_gauss_sigma: float = 10.0 + + +@pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) +def test_dual_grid_preserves_constant_channels_and_batch_order(mode: str) -> None: + cfg = SamplingConfig(pool_mode=mode) + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + assert highres is not None + assert len(highres) > len(lowres) + assert highres.cmf_a == lowres.cmf_a + pooler, neighbors = build_pooler(cfg, lowres, highres, "cpu") + assert pooler is not None + assert neighbors == 3 + constants = torch.tensor([[0.25, 0.5, 0.75], [3.0, 6.0, 9.0]]) + rendered = constants[:, None, None, :].expand(2, len(highres), 1, 3).clone() + actual = pool_hwc_buffer(pooler, rendered) + expected = constants[:, None, None, :].expand(2, len(lowres), 1, 3) + assert actual.dtype == rendered.dtype + torch.testing.assert_close(actual, expected) + + +def test_disabled_pooling_uses_only_output_grid() -> None: + cfg = SamplingConfig(pool_enabled=False) + lowres, matched = build_lowres_coords(cfg, "cpu") + assert build_highres_coords(cfg, matched, "cpu") is None + assert build_pooler(cfg, lowres, None, "cpu") == (None, None) + + +def test_segmentation_pooler_override_preserves_discrete_label_values() -> None: + cfg = SamplingConfig(pool_mode="avg") + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + assert highres is not None + pooler, _ = build_pooler(cfg, lowres, highres, "cpu", mode="max") + assert pooler is not None + labels = torch.tensor([2.0, 7.0, 19.0]) + rendered = labels[torch.arange(len(highres)) % len(labels)].reshape(1, -1, 1, 1) + pooled = pool_hwc_buffer(pooler, rendered) + assert pooled.shape == (1, len(lowres), 1, 1) + assert torch.isin(pooled, labels).all() + + +@pytest.mark.parametrize( + ("name", "expected"), + [ + ("rgb", False), + ("distance_to_camera", False), + ("semantic_segmentation", True), + ("instance_segmentation_fast", True), + ("instance_id_segmentation_fast", True), + ], +) +def test_segmentation_dispatch_uses_semantics(name: str, expected: bool) -> None: + assert is_segmentation_output(name) is expected + + +@pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) +@pytest.mark.parametrize("sample_cortex", [False, True, "geodesic"]) +@pytest.mark.parametrize("style", ["warped_cartesian_as_grid", "warped_cartesian"]) +def test_native_grid_pooling_excludes_invalid_photoreceptors(mode, sample_cortex, style) -> None: + cfg = SamplingConfig( + foveated_style=style, + pool_mode=mode, + pool_sample_cortex=sample_cortex, + # 3x3 grid windows; KNN keeps the default neighbor count. + pool_k=9 if style.endswith("_as_grid") else 3, + ) + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + assert highres is not None + pooler, _ = build_pooler(cfg, lowres, highres, "cpu") + values = torch.ones(1, len(highres), 1, 1) + values[:, ~highres.valid_mask] = 1e6 + result = pool_hwc_buffer(pooler, values)[0, :, 0, 0] + assert (result[~lowres.valid_mask] == 0).all() + assert (result[lowres.valid_mask] <= 1).all() + assert (result[lowres.valid_mask] > 0).all() + + +@pytest.mark.parametrize( + "style,expected", + [ + ("warped_cartesian_as_grid", GridPoolingLayer), + ("logpolar_as_grid", GridPoolingLayer), + ("warped_cartesian", KNNPoolingLayer), + ], +) +def test_native_grid_default_kernel_matches_deployment(style: str, expected: type) -> None: + cfg = SamplingConfig( + foveated_style=style, + pool_k=None, + pool_sample_cortex=True, + ) + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + pooler, resolved_k = build_pooler(cfg, lowres, highres, "cpu") + assert resolved_k == 4 + assert isinstance(pooler, expected) + + +def test_logpolar_grid_pooling_wraps_the_angular_boundary() -> None: + cfg = SamplingConfig(foveated_style="logpolar_as_grid", pool_k=9) + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + pooler, _ = build_pooler(cfg, lowres, highres, "cpu") + assert highres.valid_mask.all() + # Log-polar grids are angle x eccentricity; light only the last angle row. + values = torch.zeros(highres.resolution, highres.resolution) + values[-1] = 1.0 + result = pool_hwc_buffer(pooler, values.reshape(1, -1, 1, 1))[0, :, 0, 0] + pooled = lowres.as_grid(result) + # 3x3 windows centered on high-res angles 2i span 2i-1..2i+1, so the last + # row reaches output angle 0 only by wrapping, and the last output angle. + expected = torch.zeros_like(pooled) + expected[0] = 1 / 3 + expected[-1] = 1 / 3 + torch.testing.assert_close(pooled, expected) diff --git a/source/isaaclab_fovi/test/test_rays.py b/source/isaaclab_fovi/test/test_rays.py new file mode 100644 index 000000000000..84f6950bf9b5 --- /dev/null +++ b/source/isaaclab_fovi/test/test_rays.py @@ -0,0 +1,63 @@ +# 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 + +"""CPU tests of sensor ray layout and the fixed optical center.""" + +import math + +import pytest +import torch +import warp as wp + +from isaaclab_fovi.sensors.foveated_rays import ( + compute_explicit_ray_array, + compute_foveated_ray_array, +) + + +@pytest.fixture(scope="module", autouse=True) +def initialize_warp() -> None: + wp.init() + + +@pytest.mark.parametrize("projection", ["pinhole", "fisheye_equidistant"]) +def test_ray_layout_and_projection(projection: str) -> None: + coordinates = torch.tensor([[0.0, 0.0], [1.0, 0.0], [0.0, -0.5], [-0.4, 0.3]]) + field_of_view = math.radians(90.0) + rays = compute_foveated_ray_array(coordinates, field_of_view, "cpu", projection) + actual = wp.to_torch(rays)[0, :, 0] + + assert rays.shape == (1, 4, 1, 2) + assert rays.dtype == wp.vec3f + torch.testing.assert_close(actual[:, 0], torch.zeros(4, 3)) + torch.testing.assert_close(actual[:, 1].norm(dim=-1), torch.ones(4)) + torch.testing.assert_close(actual[0, 1], torch.tensor([0.0, 0.0, -1.0])) + if projection == "pinhole": + expected = torch.cat((coordinates, -torch.ones(4, 1)), dim=-1) + expected = torch.nn.functional.normalize(expected, dim=-1) + torch.testing.assert_close(actual[:, 1], expected) + else: + # Equidistant projection maps eccentricity linearly to optical-axis angle. + actual_angle = torch.acos(-actual[:, 1, 2]) + torch.testing.assert_close(actual_angle, coordinates.norm(dim=-1) * field_of_view / 2) + + +def test_explicit_rays_preserve_sample_order_and_optical_center() -> None: + directions = torch.nn.functional.normalize( + torch.tensor([[0.7, 0.3, -1.0], [-0.2, 0.6, -1.0], [0.0, 0.0, -1.0]]), dim=-1 + ) + rays = wp.to_torch(compute_explicit_ray_array(directions, device="cpu"))[0, :, 0] + torch.testing.assert_close(rays[:, 0], torch.zeros_like(directions)) + torch.testing.assert_close(rays[:, 1], directions) + + +def test_explicit_rays_reject_invalid_dimensions() -> None: + with pytest.raises(ValueError, match="shape"): + compute_explicit_ray_array(torch.zeros(3, 2), device="cpu") + + +def test_unknown_projection_fails() -> None: + with pytest.raises(ValueError, match="Unknown projection"): + compute_foveated_ray_array(torch.zeros(1, 2), 1.0, "cpu", "unknown") diff --git a/source/isaaclab_fovi/test/test_rtx_layout.py b/source/isaaclab_fovi/test/test_rtx_layout.py new file mode 100644 index 000000000000..44762d97c60a --- /dev/null +++ b/source/isaaclab_fovi/test/test_rtx_layout.py @@ -0,0 +1,29 @@ +# 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 + +"""Reject atlas layouts that destroy spatial neighborhoods before rendering.""" + +import pytest + +from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + + +@pytest.mark.parametrize("layout", ["row_major", "unknown"]) +def test_unsupported_layout_rejected_at_configuration(layout: str) -> None: + with pytest.raises(ValueError, match="ndc_layout.*cortical_disc"): + FoveatedTiledCameraCfg(ndc_layout=layout) + + +def test_cortical_disc_remains_default() -> None: + assert FoveatedTiledCameraCfg().ndc_layout == "cortical_disc" + + +def test_native_grid_requires_matching_sensor() -> None: + with pytest.raises(ValueError, match="native_grid requires"): + FoveatedTiledCameraCfg(ndc_layout="native_grid") + with pytest.raises(ValueError, match="requires ndc_layout"): + FoveatedTiledCameraCfg(foveated_style="warped_cartesian_as_grid") + cfg = FoveatedTiledCameraCfg(ndc_layout="native_grid", foveated_style="warped_cartesian_as_grid") + assert cfg.fov_type == "circular" diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py new file mode 100644 index 000000000000..56be04218cfb --- /dev/null +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -0,0 +1,294 @@ +# 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 + +"""Shared rendering and software calibration contracts without launching a simulator.""" + +from dataclasses import asdict +from types import SimpleNamespace + +import pytest +import torch +import warp as wp +from fovi.sensing.projection import CameraModel, angular_directions +from fovi.sensing.retina import RetinalTransform +from isaaclab.utils.math import matrix_from_quat, quat_apply, quat_from_euler_xyz, quat_from_matrix + +from isaaclab_fovi.sensors.calibrated_geometry import ( + retinal_directions, + rotate_camera_rays, + sampling_geometry, +) +from isaaclab_fovi.sensors.foveated_newton_tiled_camera import FoveatedNewtonTiledCamera +from isaaclab_fovi.sensors.foveated_rtx_tiled_camera import FoveatedRTXTiledCamera +from isaaclab_fovi.sensors.pooling import build_lowres_coords +from isaaclab_fovi.sensors.virtual_gaze import CalibratedVirtualGaze + + +@pytest.fixture +def tf32_enabled(): + previous = torch.get_float32_matmul_precision() + torch.set_float32_matmul_precision("high") + try: + yield + finally: + torch.set_float32_matmul_precision(previous) + + +def camera_config() -> SimpleNamespace: + camera = CameraModel("fisheye", (80, 120), (55, 55, 59.5, 39.5), (0.02, -0.003, 0, 0)) + return SimpleNamespace( + field_geometry="spherical", + camera_calibration=asdict(camera), + cmf_a=0.03, + cmf_a_frac=None, + retinal_window_reference_side="long", + retinal_window_short_side_fraction=0.75, + foveated_res=12, + foveated_style="isotropic", + fov_type="circular", + radius_norm=2.0, + isotropic_plotting_type="v1like", + image_rotation_deg=0.0, + ) + + +def test_rendering_and_software_sampling_share_window_and_nodes() -> None: + cfg = camera_config() + fov, a = sampling_geometry(cfg) + camera = CameraModel(**cfg.camera_calibration) + assert fov == pytest.approx(camera.field_of_view("long", 0.75)) + assert a / fov == pytest.approx(0.03) + coords, _ = build_lowres_coords(cfg, "cpu") + retina = RetinalTransform( + fov=fov, + cmf_a=a, + resolution=12, + device="cpu", + field_geometry="spherical", + camera_model=camera, + gaze_convention="pan_tilt", + ) + torch.testing.assert_close(coords.cartesian, retina.sampler.coords.cartesian) + actual = retina(torch.ones(2, 3, 80, 120), torch.tensor([[0.5, 0.5], [0.3, 0.8]])) + assert actual.shape == (2, 3, len(coords)) + assert torch.isfinite(actual).all() + + +class GazeHarness(CalibratedVirtualGaze): + def __init__(self) -> None: + self.cfg = camera_config() + self._sampling_coords, _ = build_lowres_coords(self.cfg, "cpu") + self._sampling_coords_highres = None + self._calibrated_rotation = None + self._data = SimpleNamespace( + quat_w_world=torch.tensor([[0.0, 0.0, 0.0, 1.0]]).repeat(2, 1), pos_w=torch.zeros(2, 3) + ) + self._initialize_calibrated_gaze() + + +@pytest.mark.parametrize("command", ["fixation", "angles"]) +@pytest.mark.parametrize("fixation", [(0.5, 1.0), (1.0, 0.5), (0.5, 1.01), (-0.01, 0.5)]) +def test_edge_gaze_preserves_visible_rays(command: str, fixation: tuple[float, float]) -> None: + camera = GazeHarness() + target = torch.tensor([fixation]) + if command == "fixation": + camera.set_calibrated_fixation(target) + else: + camera.set_calibrated_angles(camera.calibrated_mount_angles(target)) + + # An edge-centered receptive field straddles the physical sensor boundary. + # Its visible part must survive even when the center lies outside the image. + valid = camera._calibrated_validity(1) + assert valid.any() + assert not valid.all() + + +def test_gaze_away_from_sensor_masks_all_rays() -> None: + camera = GazeHarness() + camera.set_calibrated_angles(torch.tensor([[0.0, torch.pi]])) + assert not camera._calibrated_validity(1).any() + + +@pytest.mark.parametrize("device", ["cpu", "cuda"]) +@pytest.mark.parametrize("batch_size", [48, 256]) +@pytest.mark.parametrize("autocast", [False, True]) +@pytest.mark.parametrize("mode", ["planar", "spherical", "spherical_ids", "spherical_mask"]) +def test_newton_fixation_preserves_camera_rotation_with_tf32( + device: str, batch_size: int, autocast: bool, mode: str, tf32_enabled +) -> None: + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA unavailable") + source_gl = torch.tensor([[0.4625, 0.4940, -0.5341, 0.5067]], device=device).repeat(batch_size, 1) + conversion = source_gl.new_tensor([[0, 0, -1], [-1, 0, 0], [0, 1, 0]]).double() + source = quat_from_matrix(matrix_from_quat(source_gl.double()) @ conversion.T).float() + original = source.clone() + angles = torch.tensor([[0.13, -0.21]], device=device).repeat(batch_size, 1) + angles[1::2] = 0 + expected = matrix_from_quat(source.double()) @ conversion + if mode == "planar": + camera = object.__new__(FoveatedNewtonTiledCamera) + camera._data = SimpleNamespace(quat_w_world=SimpleNamespace(torch=source)) + camera._fixation = angles + camera._renderer = None + camera._view = None + camera._initialize_handle = None + camera._invalidate_initialize_handle = None + camera._prim_deletion_handle = None + camera._debug_vis_handle = None + expected = ( + expected + @ matrix_from_quat( + quat_from_euler_xyz(angles[:, 0].double(), angles[:, 1].double(), angles[:, 0].double() * 0) + ) + @ conversion.T + ) + with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast): + camera._apply_fixation_rotation() + else: + camera = GazeHarness() + camera._data.quat_w_world = source + camera._calibrated_basis = camera._calibrated_basis.to(device) + camera.set_calibrated_angles(angles) + basis = camera._calibrated_basis.double() + expected = expected @ basis @ camera._calibrated_rotation.double() @ basis.T @ conversion.T + selected = torch.arange(batch_size, device=device) % 2 == 0 + with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast): + if mode == "spherical_ids": + camera._apply_calibrated_pose(torch.nonzero(selected).flatten()) + elif mode == "spherical_mask": + camera._apply_calibrated_pose(env_mask=wp.from_torch(selected)) + else: + camera._apply_calibrated_pose() + if mode in ("spherical_ids", "spherical_mask"): + torch.testing.assert_close(source[~selected], original[~selected], atol=0, rtol=0) + source = source[selected] + expected = expected[selected] + assert source.dtype == torch.float32 + assert torch.isfinite(source).all() + torch.testing.assert_close(source.norm(dim=-1), torch.ones(len(source), device=device), atol=1e-6, rtol=0) + torch.testing.assert_close(matrix_from_quat(source.double()), expected, atol=1e-6, rtol=0) + assert torch.get_float32_matmul_precision() == "high" + + +def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pose() -> None: + camera = GazeHarness() + fixation = torch.tensor([[0.4, 0.7], [0.6, 0.3]]) + camera.set_calibrated_fixation(fixation) + camera._apply_calibrated_pose() + forward = quat_apply(camera._data.quat_w_world, torch.tensor([[1.0, 0.0, 0.0]]).expand(2, -1)) + source = CameraModel(**camera.cfg.camera_calibration) + pixels = torch.stack((fixation[:, 1] * 120 - 0.5, fixation[:, 0] * 80 - 0.5), -1) + directions, _ = source.unproject(pixels) + expected = torch.stack((directions[:, 2], -directions[:, 0], -directions[:, 1]), -1) + torch.testing.assert_close(forward, expected, atol=1e-6, rtol=1e-6) + assert torch.count_nonzero(camera._data.pos_w) == 0 + untouched = camera._data.quat_w_world[1].clone() + camera._data.quat_w_world[0] = torch.tensor([0.0, 0.0, 0.0, 1.0]) + camera._apply_calibrated_pose([0]) + torch.testing.assert_close(camera._data.quat_w_world[1], untouched) + torch.testing.assert_close( + camera._calibrated_validity(2), + source.project( + angular_directions(camera._sampling_coords.cartesian, camera._sampling_coords.fov) + @ camera._calibrated_rotation.transpose(-1, -2) + )[1], + ) + + +def test_renderer_ray_frame_matches_cv_frame() -> None: + coords = torch.tensor([[0.0, 0.0], [0.3, -0.4], [-1.0, 0.0]]) + rendered = retinal_directions(coords, 120) + cv = angular_directions(coords, 120) + torch.testing.assert_close(rendered, cv * torch.tensor([1, -1, -1])) + + +@pytest.mark.parametrize("command", ["angles", "fixation"]) +@pytest.mark.parametrize("device", ["cpu", "cuda"]) +def test_calibrated_pose_is_stable_inside_model_autocast(command: str, device: str) -> None: + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA unavailable") + cameras = [GazeHarness(), GazeHarness()] + for camera in cameras: + camera._data.quat_w_world = torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(2, 1) + camera._calibrated_basis = camera._calibrated_basis.to(device) + camera._calibrated_rays = camera._calibrated_rays.to(device) + camera._calibrated_identity = camera._calibrated_identity.to(device) + target = torch.tensor([[0.002, 0.003], [-0.1, 0.2]], device=device) + if command == "fixation": + target = target + 0.5 + for camera, enabled in zip(cameras, [False, True], strict=True): + with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled): + getattr(camera, f"set_calibrated_{command}")(target) + camera._apply_calibrated_pose() + camera._test_validity = camera._calibrated_validity(2) + assert torch.isfinite(cameras[1]._data.quat_w_world).all() + torch.testing.assert_close(cameras[1]._data.quat_w_world, cameras[0]._data.quat_w_world) + torch.testing.assert_close(cameras[1]._calibrated_rotation, cameras[0]._calibrated_rotation) + + torch.testing.assert_close(cameras[1]._data.quat_w_world.norm(dim=-1), torch.ones(2, device=device)) + torch.testing.assert_close(cameras[1]._test_validity, cameras[0]._test_validity) + + +@pytest.mark.parametrize("device", ["cpu", "cuda"]) +def test_rtx_calibrated_pose_writer_is_stable_inside_model_autocast(device: str, tf32_enabled) -> None: + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA unavailable") + camera = GazeHarness() + camera._calibrated_basis = camera._calibrated_basis.to(device) + camera._calibrated_base_local_orientation = matrix_from_quat( + torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(48, 1) + ) + written = [] + camera._view = SimpleNamespace( + set_local_poses=lambda *, orientations: written.append(torch.utils.dlpack.from_dlpack(orientations).clone()) + ) + # Policy outputs may themselves be BF16; both paths use the same input values. + angles = torch.tensor([[-0.006677, -0.010717]], device=device, dtype=torch.bfloat16).repeat(48, 1) + for enabled in [False, True]: + with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled): + camera.set_calibrated_angles(angles) + FoveatedRTXTiledCamera._write_calibrated_local_pose(camera) + assert torch.isfinite(written[1]).all() + assert written[1].dtype == torch.float32 + torch.testing.assert_close(written[1].norm(dim=-1), torch.ones(48, device=device)) + torch.testing.assert_close(written[1], written[0]) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable") +def test_visibility_ray_rotation_preserves_precision_and_cuda_capture(tf32_enabled) -> None: + device = "cuda" + generator = torch.Generator(device=device).manual_seed(42) + rays = torch.randn(16384, 3, device=device, generator=generator) + rays = rays / rays.norm(dim=-1, keepdim=True) + rotations = matrix_from_quat(torch.randn(48, 4, device=device, generator=generator)) + expected = (rays.double() @ rotations.double().transpose(-1, -2)).float() + for _ in range(3): + actual = rotate_camera_rays(rays, rotations) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + actual = rotate_camera_rays(rays, rotations) + graph.replay() + torch.testing.assert_close(actual, expected, atol=2e-7, rtol=1e-6) + assert torch.get_float32_matmul_precision() == "high" + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable") +def test_visibility_ray_rotation_preserves_shared_stream_for_warp_capture() -> None: + wp.init() + stream = wp.Stream("cuda:0") + with wp.ScopedStream(stream), torch.cuda.stream(wp.stream_to_torch(stream)): + rays = torch.tensor([[1.0, 2.0, 3.0], [-2.0, 4.0, 1.0]], device="cuda:0") + rotation = torch.tensor([[[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]], device="cuda:0") + target = wp.zeros((1, 2), dtype=wp.vec3, device="cuda:0") + actual = rotate_camera_rays(rays, rotation) + source = wp.from_torch(actual, dtype=wp.vec3) + # Physics must still be able to capture after the camera's temporary scope exits. + with wp.ScopedCapture(stream=stream) as capture: + wp.copy(target, source) + wp.capture_launch(capture.graph) + torch.testing.assert_close( + wp.to_torch(target), + torch.tensor([[[-2.0, 1.0, 3.0], [-4.0, -2.0, 1.0]]], device="cuda:0"), + ) diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py new file mode 100644 index 000000000000..10d3fa7db909 --- /dev/null +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -0,0 +1,133 @@ +# 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 + +"""Square-shell sensing uses every renderer texel with an analytic inverse.""" + +import math + +import pytest +import torch +from fovi.sensing.coords import SamplingCoords + +from isaaclab_fovi.sensors.generalized_projection import build_native_grid_textures +from isaaclab_fovi.sensors.native_grid import ( + allocate_grid_outputs, + copy_grid_outputs, + grid_output_shape, + grid_sample_indices, + mask_grid_samples, + native_grid_directions, + native_grid_exit_uv, +) + + +def make_coords(field: str, res: int = 16) -> SamplingCoords: + fov = 170.0 if field == "spherical" else 1.0 + return SamplingCoords( + fov, + 0.036021 * fov, + res, + style="warped_cartesian_as_grid", + fov_type="square", + radius_norm=math.inf, + field_geometry=field, + ) + + +@pytest.mark.parametrize("field", ["planar", "spherical"]) +@pytest.mark.parametrize("projection", ["pinhole", "fisheye_equidistant"]) +@pytest.mark.parametrize("rotation", [0.0, 37.0, 180.0]) +@pytest.mark.parametrize("res", [1, 15, 64]) +def test_every_texel_roundtrips(field: str, projection: str, rotation: float, res: int) -> None: + coords = make_coords(field, res) + kwargs = dict( + tangent_scale=0.7, + image_rotation_deg=rotation, + projection=projection, + camera_fov_rad=math.radians(150), + ) + rays = native_grid_directions(coords, **kwargs) + uv, visible = native_grid_exit_uv(rays, coords, **kwargs) + axis = (torch.arange(res) + 0.5) / res + row, col = torch.meshgrid(axis, axis, indexing="ij") + expected = torch.stack((col, row), -1).reshape(-1, 2) + assert visible.all() and coords.valid_mask.all() + torch.testing.assert_close(uv, expected, atol=2e-6, rtol=0) + torch.testing.assert_close(rays.norm(dim=-1), torch.ones(len(coords)), atol=1e-6, rtol=0) + + +@pytest.mark.parametrize("field", ["planar", "spherical"]) +def test_textures_and_public_modalities(field: str) -> None: + coords = make_coords(field) + directions, inverse = build_native_grid_textures(coords, tangent_scale=0.7, image_rotation_deg=0, exit_size=64) + torch.testing.assert_close(directions.reshape(-1, 3), native_grid_directions(coords, tangent_scale=0.7)) + assert torch.isfinite(inverse).all() + assert (inverse == -1).any() + assert grid_output_shape(coords) == (16, 16) + source = { + "rgba": torch.ones(2, len(coords), 1, 4, dtype=torch.uint8), + "depth": torch.arange(len(coords), dtype=torch.float32)[None, :, None, None], + "segmentation": torch.arange(len(coords), dtype=torch.int32)[None, :, None, None], + } + source["rgb"] = source["rgba"][..., :3] + mask_grid_samples(source, coords) + assert source["rgba"].all() + target = allocate_grid_outputs(source, coords) + pointers = {name: tensor.data_ptr() for name, tensor in target.items()} + copy_grid_outputs(source, target, grid_sample_indices(coords)) + for name in source: + torch.testing.assert_close(target[name], coords.as_grid(source[name][:, :, 0], sample_dim=1)) + assert target[name].data_ptr() == pointers[name] + assert target["rgb"].untyped_storage().data_ptr() == target["rgba"].untyped_storage().data_ptr() + + +def test_camera_config_rejects_wang_and_requires_native_layout() -> None: + from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + + kwargs = dict(prim_path="/World/Camera", foveated_style="warped_cartesian_as_grid", radius_norm=math.inf) + with pytest.raises(ValueError, match="native_grid"): + FoveatedTiledCameraCfg(**kwargs, fov_type="square") + with pytest.raises(ValueError, match="wang"): + FoveatedTiledCameraCfg(**kwargs, ndc_layout="native_grid", fov_type="wang") + cfg = FoveatedTiledCameraCfg(**kwargs, ndc_layout="native_grid", fov_type="square") + assert cfg.ndc_layout == "native_grid" + + +@pytest.mark.parametrize("coverage", ["square", "circular"]) +def test_camera_pooling_preserves_square_shells(coverage: str) -> None: + from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + from isaaclab_fovi.sensors.pooling import build_highres_coords, build_lowres_coords + + cfg = FoveatedTiledCameraCfg( + prim_path="/World/Camera", + foveated_style="warped_cartesian_as_grid", + fov_type=coverage, + radius_norm=math.inf, + ndc_layout="native_grid", + foveated_res=16, + pool_enabled=True, + pool_res_mult=2.0, + ) + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + assert lowres.radius_norm == highres.radius_norm == math.inf + for coords in (lowres, highres): + assert coords.fov_type == coverage + boundary = torch.tensor([[1.0, 1.0], [1.0, 0.0]]) + torch.testing.assert_close(coords.native_to_visual(boundary), boundary) + + +@pytest.mark.parametrize( + "kwargs", + [ + dict(radius_norm=1.0, foveated_style="warped_cartesian_as_grid", ndc_layout="native_grid"), + dict(radius_norm=math.inf, foveated_style="isotropic"), + ], +) +def test_camera_rejects_unsupported_radius_norm(kwargs: dict[str, float | str]) -> None: + from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + + with pytest.raises(ValueError, match="radius_norm"): + FoveatedTiledCameraCfg(prim_path="/World/Camera", **kwargs) From b5da2025054228916bfdc9bbf3ee2536a1645bab Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:28:38 -0800 Subject: [PATCH 02/81] Remove calibrated dense camera and unused stereo geometry Dense calibrated rendering is covered by the lens distortion support on the core camera spawn configuration. The stereo aperture geometry module had no callers. --- .../sensors/active_camera_geometry.py | 297 ------------ .../sensors/calibrated_camera.py | 162 ------- .../sensors/dense_calibrated_geometry.py | 67 --- .../sensors/generalized_projection.py | 18 - source/isaaclab_fovi/test/_check_imports.py | 1 - .../test/calibrated_camera_render_smoke.py | 458 ------------------ .../test/test_calibrated_camera_batch.py | 30 -- .../test/test_calibrated_camera_geometry.py | 230 --------- .../test/test_dense_foveated_lens_parity.py | 39 -- 9 files changed, 1302 deletions(-) delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/active_camera_geometry.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_camera.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/dense_calibrated_geometry.py delete mode 100644 source/isaaclab_fovi/test/calibrated_camera_render_smoke.py delete mode 100644 source/isaaclab_fovi/test/test_calibrated_camera_batch.py delete mode 100644 source/isaaclab_fovi/test/test_calibrated_camera_geometry.py delete mode 100644 source/isaaclab_fovi/test/test_dense_foveated_lens_parity.py diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/active_camera_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/active_camera_geometry.py deleted file mode 100644 index 3ec9465eeb09..000000000000 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/active_camera_geometry.py +++ /dev/null @@ -1,297 +0,0 @@ -# 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 - -"""Shared active-camera stereo geometry helpers.""" - -from __future__ import annotations - -import math -from dataclasses import dataclass - -import numpy as np - -_CameraPose = tuple[ - tuple[float, float, float], - tuple[float, float, float, float], -] - - -@dataclass(frozen=True) -class PanTiltMountGeometry: - """Neutral root and camera-local poses for an image-aligned pan/tilt mount.""" - - base_pose: _CameraPose - camera_local_pose: _CameraPose - - -def stereo_baseline_fixation_axis( - left_quat_xyzw: tuple[float, float, float, float], - right_in_left: tuple[float, ...] | None, - *, - manual_stereo_horizontal_separation_m: float | None = None, - horizontal_axis_parent: tuple[float, float, float] = (1.0, 0.0, 0.0), -) -> tuple[float, float]: - """Project the stereo baseline into the mount's fixation controls. - - Canonical fixation commands are ``(tilt, pan)`` around the parent-frame - +X and +Z axes. The returned unit direction is the command whose neutral - optical-axis motion points along the left-to-right baseline projected into - the optical tangent plane. - """ - from scipy.spatial.transform import Rotation as R - - left_quat = np.asarray(left_quat_xyzw, dtype=np.float64) - if left_quat.shape != (4,) or not np.isfinite(left_quat).all(): - raise ValueError("left_quat_xyzw must contain four finite values.") - left_rot = R.from_quat(left_quat) - - if manual_stereo_horizontal_separation_m is not None: - separation = float(manual_stereo_horizontal_separation_m) - if not np.isfinite(separation) or separation <= 0.0: - raise ValueError( - "manual_stereo_horizontal_separation_m must be finite and > 0, " - f"got {manual_stereo_horizontal_separation_m!r}." - ) - axis_parent = np.asarray(horizontal_axis_parent, dtype=np.float64) - axis_norm = float(np.linalg.norm(axis_parent)) - if not np.isfinite(axis_parent).all() or axis_norm <= 1.0e-8: - raise ValueError("horizontal_axis_parent must be finite and non-zero.") - baseline_parent = separation * axis_parent / axis_norm - else: - if right_in_left is None: - raise ValueError("right_in_left is required to derive the calibrated vergence axis.") - transform = np.asarray(right_in_left, dtype=np.float64) - if transform.size != 16 or not np.isfinite(transform).all(): - raise ValueError("right_in_left must contain 16 finite transform values.") - baseline_left = transform.reshape(4, 4)[:3, 3] - baseline_parent = left_rot.apply(baseline_left) - - optical_axis_parent = left_rot.apply(np.asarray((0.0, 0.0, 1.0), dtype=np.float64)) - baseline_tangent = baseline_parent - (np.dot(baseline_parent, optical_axis_parent) * optical_axis_parent) - if float(np.linalg.norm(baseline_tangent)) <= 1.0e-8: - raise ValueError("Stereo baseline has no resolvable component in the fixation tangent plane.") - - control_jacobian = np.column_stack( - ( - np.cross((1.0, 0.0, 0.0), optical_axis_parent), - np.cross((0.0, 0.0, 1.0), optical_axis_parent), - ) - ) - control_axis, _, rank, _ = np.linalg.lstsq( - control_jacobian, - baseline_tangent, - rcond=None, - ) - if rank != 2: - raise ValueError("Camera optical axis is singular for the configured tilt/pan mount controls.") - control_norm = float(np.linalg.norm(control_axis)) - if control_norm <= 1.0e-8: - raise ValueError("Stereo baseline produces no resolvable tilt/pan command.") - unit = control_axis / control_norm - return float(unit[0]), float(unit[1]) - - -def optical_axis_offset( - camera_quat_xyzw: tuple[float, float, float, float], - offset_m: float, -) -> tuple[float, float, float]: - """Return a parent-frame offset along the ROS-camera optical axis.""" - offset_m = float(offset_m) - if offset_m == 0.0: - return (0.0, 0.0, 0.0) - - from scipy.spatial.transform import Rotation as R - - forward = R.from_quat(np.asarray(camera_quat_xyzw, dtype=np.float64)).apply( - np.asarray((0.0, 0.0, offset_m), dtype=np.float64) - ) - return tuple(float(v) for v in forward) - - -def centered_stereo_aperture_poses( - center_pos: tuple[float, float, float], - left_quat_xyzw: tuple[float, float, float, float], - right_in_left: tuple[float, ...] | None, - *, - use_stereo: bool, - manual_stereo_horizontal_separation_m: float | None = None, - horizontal_axis_parent: tuple[float, float, float] = (1.0, 0.0, 0.0), -) -> tuple[ - tuple[tuple[float, float, float], tuple[float, float, float, float]], - tuple[tuple[float, float, float], tuple[float, float, float, float]] | None, -]: - """Return centered left/right aperture poses in the parent frame. - - ``center_pos`` is the midpoint between the two camera aperture centers. - ``right_in_left`` is the calibrated right-camera transform expressed in - the left-camera aperture frame. ``manual_stereo_horizontal_separation_m`` - overrides that calibrated transform with a centered yoked baseline along - ``horizontal_axis_parent``. - """ - from scipy.spatial.transform import Rotation as R - - center = np.asarray(center_pos, dtype=np.float64) - left_quat = np.asarray(left_quat_xyzw, dtype=np.float64) - left_rot = R.from_quat(left_quat) - - if not use_stereo: - left_pose = ( - tuple(float(v) for v in center), - tuple(float(v) for v in left_quat), - ) - return left_pose, None - if right_in_left is None: - if manual_stereo_horizontal_separation_m is None: - raise ValueError("right_in_left is required when use_stereo=True.") - - if manual_stereo_horizontal_separation_m is not None: - separation = float(manual_stereo_horizontal_separation_m) - if separation <= 0.0: - raise ValueError( - "manual_stereo_horizontal_separation_m must be > 0 when set, " - f"got {manual_stereo_horizontal_separation_m!r}." - ) - axis = np.asarray(horizontal_axis_parent, dtype=np.float64) - axis_norm = float(np.linalg.norm(axis)) - if axis_norm <= 1.0e-8: - raise ValueError("horizontal_axis_parent must be non-zero when manual stereo separation is set.") - baseline_parent = separation * (axis / axis_norm) - left_pos = center - 0.5 * baseline_parent - right_pos = center + 0.5 * baseline_parent - left_pose = ( - tuple(float(v) for v in left_pos), - tuple(float(v) for v in left_quat), - ) - right_pose = ( - tuple(float(v) for v in right_pos), - tuple(float(v) for v in left_quat), - ) - return left_pose, right_pose - - right_in_left_tf = np.asarray(right_in_left, dtype=np.float64).reshape(4, 4) - baseline_parent = left_rot.apply(right_in_left_tf[:3, 3]) - left_pos = center - 0.5 * baseline_parent - - left_tf = np.eye(4) - left_tf[:3, :3] = left_rot.as_matrix() - left_tf[:3, 3] = left_pos - right_tf = left_tf @ right_in_left_tf - right_rot = R.from_matrix(right_tf[:3, :3]) - - left_pose = ( - tuple(float(v) for v in left_pos), - tuple(float(v) for v in left_quat), - ) - right_pose = ( - tuple(float(v) for v in right_tf[:3, 3]), - tuple(float(v) for v in right_rot.as_quat()), - ) - return left_pose, right_pose - - -def stereo_aperture_poses( - left_pos: tuple[float, float, float], - left_quat_xyzw: tuple[float, float, float, float], - right_in_left: tuple[float, ...] | None, - *, - use_stereo: bool, - manual_stereo_horizontal_separation_m: float | None = None, - horizontal_axis_parent: tuple[float, float, float] = (1.0, 0.0, 0.0), -) -> tuple[_CameraPose, _CameraPose | None]: - """Return the configured camera poses without recentering calibration. - - Calibrated camera configs define ``left_pos`` as the actual left aperture - position and ``right_in_left`` relative to it. A manual yoked pair instead - treats that position as its midpoint, matching the active-camera presets. - """ - if manual_stereo_horizontal_separation_m is not None: - return centered_stereo_aperture_poses( - left_pos, - left_quat_xyzw, - right_in_left, - use_stereo=use_stereo, - manual_stereo_horizontal_separation_m=manual_stereo_horizontal_separation_m, - horizontal_axis_parent=horizontal_axis_parent, - ) - - left_pose = (left_pos, left_quat_xyzw) - if not use_stereo: - return left_pose, None - if right_in_left is None: - raise ValueError("right_in_left is required when use_stereo=True.") - - from scipy.spatial.transform import Rotation as R - - left_transform = np.eye(4, dtype=np.float64) - left_transform[:3, :3] = R.from_quat(np.asarray(left_quat_xyzw, dtype=np.float64)).as_matrix() - left_transform[:3, 3] = np.asarray(left_pos, dtype=np.float64) - relative_transform = np.asarray(right_in_left, dtype=np.float64) - if relative_transform.size != 16 or not np.isfinite(relative_transform).all(): - raise ValueError("right_in_left must contain 16 finite transform values.") - right_transform = left_transform @ relative_transform.reshape(4, 4) - right_pose = ( - tuple(float(value) for value in right_transform[:3, 3]), - tuple(float(value) for value in R.from_matrix(right_transform[:3, :3]).as_quat()), - ) - return left_pose, right_pose - - -def pan_tilt_mount_geometry( - camera_pos: tuple[float, float, float], - camera_quat_xyzw: tuple[float, float, float, float], - *, - image_rotation_deg: float, - camera_forward_offset_m: float, - base_z_drop_m: float, -) -> PanTiltMountGeometry: - """Factor a calibrated camera pose into an image-aligned pan/tilt mount. - - The mount's X and Z axes become policy-image right and up. Its Y axis is - optical forward, matching the bundled pan/tilt asset. The returned local - camera pose exactly reconstructs the calibrated pose at zero joint angles. - """ - from scipy.spatial.transform import Rotation as R - - position = np.asarray(camera_pos, dtype=np.float64).copy() - quaternion = np.asarray(camera_quat_xyzw, dtype=np.float64) - rotation_deg = float(image_rotation_deg) - forward_offset = float(camera_forward_offset_m) - base_z_drop = float(base_z_drop_m) - if position.shape != (3,) or not np.isfinite(position).all(): - raise ValueError("camera_pos must contain three finite values.") - if quaternion.shape != (4,) or not np.isfinite(quaternion).all(): - raise ValueError("camera_quat_xyzw must contain four finite values.") - if not math.isfinite(rotation_deg): - raise ValueError("image_rotation_deg must be finite.") - if not math.isfinite(forward_offset): - raise ValueError("camera_forward_offset_m must be finite.") - if not math.isfinite(base_z_drop) or base_z_drop < 0.0: - raise ValueError("base_z_drop_m must be finite and non-negative.") - - camera_rotation = R.from_quat(quaternion) - camera_matrix = camera_rotation.as_matrix() - raw_right = camera_matrix[:, 0] - raw_up = -camera_matrix[:, 1] - optical_forward = camera_matrix[:, 2] - theta = math.radians(rotation_deg) - policy_right = math.cos(theta) * raw_right + math.sin(theta) * raw_up - policy_up = -math.sin(theta) * raw_right + math.cos(theta) * raw_up - mount_rotation = R.from_matrix(np.column_stack((policy_right, optical_forward, policy_up))) - camera_local_rotation = mount_rotation.inv() * camera_rotation - camera_local_position = mount_rotation.inv().apply(forward_offset * optical_forward) - base_position = position - base_position -= mount_rotation.apply((0.0, 0.0, base_z_drop)) - base_position -= forward_offset * optical_forward - - return PanTiltMountGeometry( - base_pose=( - tuple(float(value) for value in base_position), - tuple(float(value) for value in mount_rotation.as_quat()), - ), - camera_local_pose=( - tuple(float(value) for value in camera_local_position), - tuple(float(value) for value in camera_local_rotation.as_quat()), - ), - ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_camera.py deleted file mode 100644 index 56e5ce784b35..000000000000 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_camera.py +++ /dev/null @@ -1,162 +0,0 @@ -# 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 - -"""Dense calibrated cameras that render the physical lens's distorted raster.""" - -from __future__ import annotations - -import tempfile -from collections.abc import Sequence -from typing import TYPE_CHECKING - -import numpy as np -import torch -import warp as wp -from fovi.sensing.projection import CameraCalibration, CameraModel -from isaaclab import sim as sim_utils -from isaaclab.renderers.base_renderer import BaseRenderer -from isaaclab.sensors import Camera, CameraCfg -from isaaclab.utils.configclass import configclass - -from .dense_calibrated_geometry import apply_lens_schema, dense_camera_rays -from .generalized_projection import ( - apply_generalized_projection_to_prim, - build_dense_calibrated_textures, - save_generalized_projection_textures, -) - -if TYPE_CHECKING: - from pxr import Usd - - -class CalibratedTiledCamera(Camera): - """Dense OpenCV pinhole/fisheye camera for Isaac RTX, OVRTX and Newton/Warp. - - Lens parameters describe the raw rendered orientation. The raster is never - rectified; each Newton ray and RTX primary ray follows the physical lens. - ``data.intrinsic_matrices`` contains K but cannot alone describe this lens. - """ - - @property - def supports_batch_update(self) -> bool: - return True - - @staticmethod - def _update_buffers_batch_impl(sensors: Sequence[CalibratedTiledCamera]) -> None: - Camera._update_buffers_batch_impl(sensors) - if sim_utils.SimulationContext.instance() is None: - return # The base implementation already invoked scalar capture. - for sensor in sensors: - sensor.process_rendered_frame() - - @property - def renderer(self) -> BaseRenderer: - """Renderer shared with task-owned visual animation bindings.""" - return self._renderer - - def __init__(self, cfg: CalibratedTiledCameraCfg) -> None: - if cfg.camera_calibration is None: - raise ValueError("CalibratedTiledCamera requires camera_calibration") - self.camera_model = CameraModel.from_config(cfg.camera_calibration).resized((cfg.height, cfg.width)) - self._calibrated_rays = None - self._invalid_pixels = None - self._lut_directory: tempfile.TemporaryDirectory[str] | None = None - if cfg.renderer_cfg.renderer_type not in ("isaac_rtx", "ovrtx", "newton_warp"): - raise ValueError("Calibrated cameras support isaac_rtx, ovrtx, and newton_warp") - super().__init__(cfg) - if cfg.renderer_cfg.renderer_type == "ovrtx": - self._author_lens() - - def _author_lens(self) -> None: - if self.cfg.renderer_cfg.renderer_type in ("isaac_rtx", "ovrtx"): - prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) - if self.camera_model.model == "fisheye": - # RTX's native OpenCV fisheye clips to an implicit image circle, - # even when the calibrated rectangular sensor has valid corners. - # Odd inverse dimensions put octahedral axis seams on texel centers. - direction, inverse = build_dense_calibrated_textures( - self.camera_model, exit_size=max(128, 4 * max(self.camera_model.image_size)) + 1 - ) - self._lut_directory = tempfile.TemporaryDirectory(prefix="rtx_calibrated_luts_") - direction_path, inverse_path = save_generalized_projection_textures( - direction, inverse, self._lut_directory.name, "calibrated" - ) - for prim in prims: - apply_generalized_projection_to_prim(prim, direction_path, inverse_path) - elif self.camera_model.model == "pinhole": - for prim in prims: - apply_lens_schema(prim, self.camera_model) - else: - raise ValueError(f"Unsupported lens model {self.camera_model.model!r}") - - def _initialize_impl(self) -> None: - if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": - self._author_lens() - super()._initialize_impl() - directions, valid = dense_camera_rays(self.camera_model, str(self._device)) - self._invalid_pixels = (~valid)[None, ..., None] - if self.cfg.renderer_cfg.renderer_type == "newton_warp": - height, width = self.camera_model.image_size - rays = torch.zeros((1, height, width, 2, 3), device=self._device) - rays[0, :, :, 1] = directions - self._calibrated_rays = wp.from_torch(rays, dtype=wp.vec3f) - self._render_data.camera_rays = self._calibrated_rays - - def _read_authored_opencv_intrinsics( - self, prim: Usd.Prim, width: int, height: int, env_id: int - ) -> tuple[float, float, float, float]: - # LUT schemas carry rays, not fx/fy/cx/cy attributes. The calibration - # remains the source of public K metadata, in OpenCV pixel centers. - return self.camera_model.intrinsics - - def _initialize_intrinsics(self) -> None: - super()._initialize_intrinsics() - # Newton's explicit-ray camera has no USD lens schema, so its base - # initialization otherwise reconstructs a nominal pinhole K. - fx, fy, cx, cy = self.camera_model.intrinsics - matrix = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float32) - matrices = wp.array( - np.repeat(matrix[None], self._view.count, axis=0), - dtype=wp.mat33f, - device=self._device, - ) - wp.copy(self._data.intrinsic_matrices.warp, matrices) - - def set_intrinsic_matrices( - self, - matrices: torch.Tensor, - focal_length: float = 1.0, - env_ids: Sequence[int] | None = None, - ) -> None: - raise NotImplementedError("Construct a new calibrated camera to change its lens; K alone is insufficient") - - def _update_buffers_impl(self, env_mask: wp.array) -> None: - if not self._env_mask_has_any(env_mask): - return - super()._update_buffers_impl(env_mask) - self.process_rendered_frame() - - def process_rendered_frame(self) -> None: - """Apply calibrated range and validity conventions after a render.""" - if not self._env_mask_has_any(self._is_outdated): - return - if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self._data.output: - # OVRTX measures range from the near-clipped ray origin. - self._data.output["distance_to_camera"].torch.add_(self.cfg.spawn.clipping_range[0]) - for name, output in self._data.output.items(): - fill = ( - self.cfg.spawn.clipping_range[1] - if name in ("depth", "distance_to_image_plane", "distance_to_camera") - else 0 - ) - output.torch.masked_fill_(self._invalid_pixels, fill) - - -@configclass -class CalibratedTiledCameraCfg(CameraCfg): - """Opt-in dense calibrated lens; existing CameraCfg remains pinhole.""" - - class_type: type = CalibratedTiledCamera - camera_calibration: CameraCalibration | None = None diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/dense_calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/dense_calibrated_geometry.py deleted file mode 100644 index 2f50c7ea2555..000000000000 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/dense_calibrated_geometry.py +++ /dev/null @@ -1,67 +0,0 @@ -# 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 - -"""Dense raster geometry using the same physical lens model as Fovi/Isaac Lab Fovi.""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -import torch -from fovi.sensing.projection import CameraModel - -if TYPE_CHECKING: - from pxr import Usd - - -def dense_camera_rays(camera: CameraModel, device: str = "cpu") -> tuple[torch.Tensor, torch.Tensor]: - """Return OpenGL unit rays (H,W,3) and usable-pixel mask (H,W). - - Integer pixel centers refer to the original distorted raster. Invalid - pixels receive a finite forward ray and are masked after rendering. - """ - height, width = camera.image_size - y, x = torch.meshgrid( - torch.arange(height, dtype=torch.float64, device=device), - torch.arange(width, dtype=torch.float64, device=device), - indexing="ij", - ) - directions, valid = camera.unproject(torch.stack((x, y), -1)) - directions = directions * directions.new_tensor((1, -1, -1)) - directions = torch.where(valid[..., None], directions, directions.new_tensor((0, 0, -1))) - return directions.float().contiguous(), valid - - -def lens_schema_values(camera: CameraModel) -> tuple[str, str, dict[str, float]]: - """Return the native RTX schema, model token, and OpenCV coefficient mapping.""" - fx, fy, cx, cy = camera.intrinsics - # RTX evaluates raster samples at half-integers; OpenCV centers are integers. - values = dict(fx=fx, fy=fy, cx=cx + 0.5, cy=cy + 0.5) - if camera.model == "fisheye": - schema, token = "OmniLensDistortionOpenCvFisheyeAPI", "opencvFisheye" - names = ("k1", "k2", "k3", "k4") - elif camera.model == "pinhole": - schema, token = "OmniLensDistortionOpenCvPinholeAPI", "opencvPinhole" - names = ("k1", "k2", "p1", "p2", "k3", "k4", "k5", "k6", "s1", "s2", "s3", "s4") - else: - raise ValueError(f"Unsupported lens model {camera.model!r}") - coefficients = (*camera.distortion, *((0.0,) * (len(names) - len(camera.distortion)))) - values.update(zip(names, coefficients, strict=True)) - return schema, token, values - - -def apply_lens_schema(prim: Usd.Prim, camera: CameraModel) -> None: - """Author native RTX distortion before render-product initialization.""" - from pxr import Gf, Sdf - - schema, token, values = lens_schema_values(camera) - # Explicit metadata and attributes work even when the USD schema is not registered. - prim.AddAppliedSchema(schema) - prim.CreateAttribute("omni:lensdistortion:model", Sdf.ValueTypeNames.Token).Set(token) - prefix = f"omni:lensdistortion:{token}:" - height, width = camera.image_size - prim.CreateAttribute(prefix + "imageSize", Sdf.ValueTypeNames.Int2).Set(Gf.Vec2i(width, height)) - for name, value in values.items(): - prim.CreateAttribute(prefix + name, Sdf.ValueTypeNames.Float).Set(float(value)) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py index e80332b1904b..dc8ede0d31bb 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py @@ -48,9 +48,7 @@ import numpy as np import torch from fovi.sensing.coords import SamplingCoords -from fovi.sensing.projection import CameraModel -from .dense_calibrated_geometry import dense_camera_rays from .native_grid import native_grid_directions, native_grid_exit_uv # ── Optional dependencies ──────────────────────────────────────────────────── @@ -181,22 +179,6 @@ def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tens # ============================================================================= -def build_dense_calibrated_textures(camera: CameraModel, *, exit_size: int) -> tuple[torch.Tensor, torch.Tensor]: - """Build physical-lens direction texels and an analytic octahedral inverse map. - - Direction texels use OpenCV integer pixel centers. The inverse map converts - those coordinates to half-integer normalized texture coordinates; rays - outside the calibrated raster, image circle, or angular domain map to -1. - """ - directions, _ = dense_camera_rays(camera) - decoded = torch.stack(_octahedral_decode(exit_size, exit_size, device="cpu"), -1) - pixels, valid = camera.project(decoded * decoded.new_tensor((1, -1, -1))) - height, width = camera.image_size - uv = ((pixels + 0.5) / pixels.new_tensor((width, height))).float() - exit_texture = torch.where(valid[..., None], uv, torch.full_like(uv, -1)) - return directions, exit_texture - - def build_native_grid_textures( coords: SamplingCoords, *, diff --git a/source/isaaclab_fovi/test/_check_imports.py b/source/isaaclab_fovi/test/_check_imports.py index 8a84b341bac2..4bc16248f541 100644 --- a/source/isaaclab_fovi/test/_check_imports.py +++ b/source/isaaclab_fovi/test/_check_imports.py @@ -42,7 +42,6 @@ def find_spec( "isaaclab_fovi", "isaaclab_fovi.sensors", "isaaclab_fovi.sensors.fixed_software_fov", - "isaaclab_fovi.sensors.active_camera_geometry", "isaaclab_fovi.sensors.foveated_rays", "isaaclab_fovi.sensors.pooling", "fovi.sensing.coords", diff --git a/source/isaaclab_fovi/test/calibrated_camera_render_smoke.py b/source/isaaclab_fovi/test/calibrated_camera_render_smoke.py deleted file mode 100644 index ee7a2baf4f51..000000000000 --- a/source/isaaclab_fovi/test/calibrated_camera_render_smoke.py +++ /dev/null @@ -1,458 +0,0 @@ -# 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 - -"""Bounded GPU check of calibrated dense/Isaac Lab Fovi rendering against analytic geometry. - -Run separately for each --backend {rtx,newton} and --sampling {dense,foveated} -with --visualizer none --device cuda:0. Both sampling modes are provided by Isaac Lab Fovi. -The reference uses OpenCV and analytic ray/box intersections, not renderer rays. -""" - -from __future__ import annotations - -import argparse -import faulthandler -import json -import traceback -from contextlib import ExitStack -from pathlib import Path -from typing import TYPE_CHECKING - -import numpy as np -from isaaclab.app import AppLauncher - -if TYPE_CHECKING: - from fovi.sensing.projection import CameraCalibration - from isaaclab.sensors import Camera - -HEIGHT, WIDTH = 120, 192 -FAR = 500.0 -NEAR = 0.01 -BOXES = ( - ((0.0, 0.0, -4.05), (200.0, 200.0, 0.1)), - ((0.8, 0.3, -2.15), (0.6, 0.8, 0.3)), -) - - -def audit_projection(cameras: dict[str, Camera], output: Path) -> None: - """Record and verify the camera properties actually seen by the renderer.""" - import isaaclab.sim as sim_utils - import omni.kit.app - from pxr import Usd - - records = {} - for name, camera in cameras.items(): - prim = sim_utils.get_current_stage().GetPrimAtPath(camera.cfg.prim_path) - schemas = list(prim.GetMetadata("apiSchemas").GetAppliedItems()) - properties = { - attr.GetName(): str(attr.Get()) - for attr in prim.GetAuthoredAttributes() - if "Projection" in attr.GetName() or attr.GetName().startswith("omni:lensdistortion:") - } - assert "OmniLensDistortionLutAPI" in schemas, (name, schemas) - assert properties["omni:lensdistortion:model"] == "lut", (name, properties) - assert properties.get("cameraProjectionType") != "generalizedProjection", (name, properties) - assert not any("generalizedProjection" in key for key in properties), (name, properties) - for texture in ("rayEnterDirectionTexture", "rayExitPositionTexture"): - assert properties[f"omni:lensdistortion:lut:{texture}"], (name, properties) - records[name] = {"schemas": schemas, "properties": properties} - runtime = { - "schema_registered": bool(Usd.SchemaRegistry.GetTypeFromSchemaTypeName("OmniLensDistortionLutAPI")), - "extension_enabled": omni.kit.app.get_app() - .get_extension_manager() - .is_extension_enabled("omni.usd.schema.omni_lens_distortion"), - } - output.write_text(json.dumps({"runtime": runtime, "cameras": records}, indent=2) + "\n") - - -def video_maps(cameras: dict[str, Camera], size: int) -> dict[str, np.ndarray]: - """Nearest-sample visual-field reconstruction; the periphery stays coarse.""" - from scipy.spatial import cKDTree - - y, x = np.mgrid[:size, :size] - points = np.stack((2 * (x + 0.5) / size - 1, 1 - 2 * (y + 0.5) / size), axis=-1) - maps = {} - for name, camera in cameras.items(): - coords = camera.sampling_coords.cartesian.cpu().numpy() - indices = cKDTree(coords).query(points.reshape(-1, 2))[1].reshape(size, size) - indices[np.linalg.norm(points, axis=-1) > 1] = -1 - maps[name] = indices - return maps - - -def video_frame( - frames: dict[str, dict[str, np.ndarray]], - maps: dict[str, np.ndarray], - phase: int, - mode: str, - fixation: tuple[float, float], -) -> np.ndarray: - """Pair measured RGB with analytic foreground/mask reference for every lens.""" - import cv2 - - size = next(iter(maps.values())).shape[0] - tile_width, tile_height = size * 2 + 16, size + 32 - canvas = np.full((tile_height * 3 + 64, tile_width * 2, 3), 24, dtype=np.uint8) - cv2.putText(canvas, f"Foveated | {mode} | frame {phase - 4}", (12, 24), 0, 0.6, (240,) * 3, 1) - cv2.putText( - canvas, - f"Fixation y,x: {fixation[0]:.3f}, {fixation[1]:.3f} | RGB / analytic reference", - (12, 48), - 0, - 0.5, - (240,) * 3, - 1, - ) - for index, (name, lookup) in enumerate(maps.items()): - frame = frames[f"{name}_{phase}"] - actual = frame["rgb"].reshape(-1, 3).astype(np.uint8) - reference = np.zeros_like(actual) - reference[:, 2] = 200 - reference[frame["expected"] < 3] = (200, 0, 0) - reference[~frame["valid"]] = 0 - top, left = 64 + (index // 2) * tile_height, (index % 2) * tile_width - cv2.putText(canvas, name, (left + 8, top + 22), 0, 0.5, (240,) * 3, 1) - for column, samples in enumerate((actual, reference)): - image = samples[lookup].copy() - image[lookup < 0] = 0 - x = left + 4 + column * (size + 8) - canvas[top + 32 : top + 32 + size, x : x + size] = image[:, :, ::-1] - return canvas - - -def unproject(pixels: np.ndarray, calibration: CameraCalibration) -> np.ndarray: - """Independent OpenCV reference, returning unit OpenCV-frame directions.""" - import cv2 - - fx, fy, cx, cy = calibration["intrinsics"] - matrix = np.array(((fx, 0, cx), (0, fy, cy), (0, 0, 1)), dtype=np.float64) - coefficients = np.array(calibration["distortion"], dtype=np.float64) - points = np.asarray(pixels, dtype=np.float64).reshape(-1, 1, 2) - if calibration["model"] == "fisheye": - xy = cv2.fisheye.undistortPoints(points, matrix, coefficients)[:, 0] - else: - xy = cv2.undistortPointsIter( - points, - matrix, - coefficients, - None, - None, - (cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 100, 1e-12), - )[:, 0] - rays = np.column_stack((xy, np.ones(len(xy)))) - return rays / np.linalg.norm(rays, axis=-1, keepdims=True) - - -def ray_depth(rays: np.ndarray, origin: np.ndarray) -> np.ndarray: - """First intersection distance [m] with the two axis-aligned scene boxes.""" - result = np.full(len(rays), FAR) - for center, size in BOXES: - lo = np.array(center) - np.array(size) / 2 - hi = np.array(center) + np.array(size) / 2 - with np.errstate(divide="ignore", invalid="ignore"): - a, b = (lo - origin) / rays, (hi - origin) / rays - near = np.minimum(a, b).max(axis=-1) - far = np.maximum(a, b).min(axis=-1) - hit = (far >= near) & (near > 0) - result = np.minimum(result, np.where(hit, near, FAR)) - return result - - -def reference_rays( - camera: Camera, calibration: CameraCalibration, sampling: str, fixation: tuple[float, float] -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Return physical GL-frame rays and lens validity for the public sample grid.""" - import cv2 - - y, x = np.mgrid[:HEIGHT, :WIDTH] - pixels = np.stack((x, y), -1).reshape(-1, 2) - if sampling == "dense": - rays = unproject(pixels, calibration) - forward_cosine = rays[:, 2].copy() - else: - coords = camera.sampling_coords.cartesian.cpu().numpy().astype(np.float64) - # The short-side retinal diameter is the angle between these image rays. - edges = np.array((((WIDTH - 1) / 2, -0.5), ((WIDTH - 1) / 2, HEIGHT - 0.5))) - edge_rays = unproject(edges, calibration) - half_angle = np.arccos(np.clip(edge_rays[0] @ edge_rays[1], -1, 1)) / 2 - xy = coords * (1, -1) - radius = np.linalg.norm(xy, axis=-1) - scale = half_angle * np.sinc(radius * half_angle / np.pi) - rays = np.column_stack((xy * scale[:, None], np.cos(radius * half_angle))) - forward_cosine = rays[:, 2].copy() - target = unproject(np.array(((fixation[1] * WIDTH - 0.5, fixation[0] * HEIGHT - 0.5),)), calibration)[0] - pan = np.arctan2(target[0], target[2]) - tilt = np.arctan2(-target[1], np.hypot(target[0], target[2])) - rx, _ = cv2.Rodrigues(np.array((tilt, 0, 0))) - ry, _ = cv2.Rodrigues(np.array((0, pan, 0))) - rays = rays @ (ry @ rx).T - fx, fy, cx, cy = calibration["intrinsics"] - matrix = np.array(((fx, 0, cx), (0, fy, cy), (0, 0, 1))) - project = cv2.fisheye.projectPoints if calibration["model"] == "fisheye" else cv2.projectPoints - pixels = project(rays[:, None], np.zeros(3), np.zeros(3), matrix, np.array(calibration["distortion"]))[0][:, 0] - valid = ( - (pixels[:, 0] >= -0.5) & (pixels[:, 0] < WIDTH - 0.5) & (pixels[:, 1] >= -0.5) & (pixels[:, 1] < HEIGHT - 0.5) - ) - if "image_circle" in calibration: - cx, cy, radius = calibration["image_circle"] - valid &= np.linalg.norm(pixels - (cx, cy), axis=-1) <= radius - if sampling == "foveated": - target_pixel = np.array((fixation[1] * WIDTH - 0.5, fixation[0] * HEIGHT - 0.5)) - # An invalid fixation disables the whole calibrated view, including - # rays that would otherwise land inside the lens's usable circle. - valid &= np.linalg.norm(target_pixel - (cx, cy)) <= radius - return rays * (1, -1, -1), valid, forward_cosine - - -def main(args: argparse.Namespace) -> None: - import isaaclab.sim as sim_utils - import torch - from isaaclab.utils.warp import ProxyArray - - from isaaclab_fovi.sensors.calibrated_camera import CalibratedTiledCamera, CalibratedTiledCameraCfg - - if args.backend in ("newton", "ovrtx"): - from isaaclab_newton.physics.mjwarp_solver_cfg import MJWarpSolverCfg - from isaaclab_newton.physics.newton_manager_cfg import NewtonCfg - from isaaclab_newton.renderers import NewtonWarpRendererCfg - - physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) - if args.backend == "newton": - renderer = NewtonWarpRendererCfg(render_order="pixel_priority") - else: - from isaaclab_ov.renderers.ovrtx_renderer_cfg import OVRTXRendererCfg - - renderer = OVRTXRendererCfg(log_level="warn") - else: - from isaaclab_physx.physics.physx_manager_cfg import PhysxCfg - from isaaclab_physx.renderers import IsaacRtxRendererCfg - from isaaclab_physx.renderers.isaac_rtx_renderer_cfg import ( - IsaacRtxRendererGlobalSettingsCfg, - ) - - physics, renderer = ( - PhysxCfg(), - IsaacRtxRendererCfg( - global_settings=IsaacRtxRendererGlobalSettingsCfg( - antialiasing_mode="Off", - enable_dl_denoiser=False, - enable_global_illumination=False, - enable_reflections=False, - enable_ambient_occlusion=False, - enable_shadows=False, - ) - ), - ) - sim_utils.create_new_stage() - sim = sim_utils.SimulationContext( - sim_utils.SimulationCfg(device=args.device, physics=physics, gravity=(0.0, 0.0, 0.0)) - ) - sim_utils.create_prim("/World/envs/env_0", "Xform") - for i, (center, size) in enumerate(BOXES): - cfg = sim_utils.CuboidCfg( - size=size, - rigid_props=sim_utils.RigidBodyPropertiesCfg(disable_gravity=True), - mass_props=sim_utils.MassPropertiesCfg(mass=1.0), - collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=False), - visual_material=sim_utils.PreviewSurfaceCfg( - diffuse_color=(0.8, 0.0, 0.0) if i else (0.0, 0.0, 0.8), - emissive_color=(0.8, 0.0, 0.0) if i else (0.0, 0.0, 0.8), - ), - ) - cfg.func(f"/World/envs/env_0/Box{i}", cfg, translation=center) - light = sim_utils.DistantLightCfg(intensity=2000) - light.func("/World/Light", light) - base = dict( - model="fisheye", - image_size=(HEIGHT, WIDTH), - intrinsics=(80.0, 85.0, 88.0, 63.0), - distortion=(0.0,) * 4, - ) - cases = { - "equidistant": base, - "intrinsics": dict(base, intrinsics=(105.0, 95.0, 102.0, 53.0)), - "distortion": dict(base, distortion=(0.14, -0.025, 0.004, -0.0002)), - "mask": dict(base, image_circle=(88.0, 63.0, 68.0)), - "pinhole": dict(base, model="pinhole"), - "brown": dict(base, model="pinhole", distortion=(0.12, -0.01, 0.005, -0.003)), - } - cameras = {} - for name, calibration in cases.items(): - common = dict( - prim_path=f"/World/envs/env_0/{name}", - data_types=["rgb", "distance_to_camera", "depth"], - camera_calibration=calibration, - renderer_cfg=renderer, - spawn=sim_utils.PinholeCameraCfg(clipping_range=(NEAR, FAR), lock_camera=False), - offset=CalibratedTiledCameraCfg.OffsetCfg(rot=(0.0, 0.0, 0.0, 1.0), convention="opengl"), - update_latest_camera_pose=True, - ) - if args.sampling == "dense": - camera = CalibratedTiledCamera(CalibratedTiledCameraCfg(height=HEIGHT, width=WIDTH, **common)) - else: - from isaaclab_fovi.sensors import FoveatedTiledCamera, FoveatedTiledCameraCfg - - camera = FoveatedTiledCamera( - FoveatedTiledCameraCfg( - field_geometry="spherical", - foveated_res=24, - cmf_a=0.1, - fixed_software_fov=True, - software_fov_image_height=HEIGHT, - software_fov_image_width=WIDTH, - **common, - ) - ) - cameras[name] = camera - if args.backend == "ovrtx": - from isaaclab.cloner import ClonePlan - - sim.set_clone_plan( - ClonePlan( - sources=("/World/envs/env_0",), - destinations=("/World/envs/env_{}",), - clone_mask=np.ones((1, 1), dtype=bool), - env_ids=np.array([0]), - positions=np.zeros((1, 3)), - ) - ) - sim.reset() - args.output.parent.mkdir(parents=True, exist_ok=True) - if args.backend == "rtx" and args.sampling == "foveated": - audit_projection(cameras, args.output.with_suffix(".projection.json")) - records, frames = [], {} - fixations = [(0.5, 0.5), (0.4, 0.65), (0.4, 0.65), (0.5, 0.5)] - maps = {} - if args.video_frames: - maps = video_maps(cameras, 224) - for angle in np.linspace(0, 2 * np.pi, args.video_frames): - fixations.append((0.5 + 0.2 * np.sin(angle), 0.5 + 0.3 * np.sin(2 * angle))) - with ExitStack() as resources: - video = None - if args.video_frames: - import imageio.v2 as imageio - - video = resources.enter_context( - imageio.get_writer( - args.output.with_suffix(".mp4"), - fps=24, - codec="libx264", - macro_block_size=1, - ffmpeg_params=["-crf", "18", "-preset", "medium"], - ) - ) - # Repeated fixation and return exercise pose updates without accumulated rotation. - for phase, fixation in enumerate(fixations): - origin = np.array((0.15, -0.1, 0.0)) if phase in (1, 2) else np.zeros(3) - for camera in cameras.values(): - camera.set_world_poses(positions=torch.tensor(origin[None], device=sim.device, dtype=torch.float32)) - if args.sampling == "foveated": - camera.set_calibrated_fixation(torch.tensor((fixation,), device=sim.device, dtype=torch.float32)) - for _ in range(8): - sim.step() - if args.backend == "ovrtx": - from isaaclab.sensors import SensorBase - - SensorBase.update_batch(list(cameras.values()), sim.get_physics_dt()) - else: - for camera in cameras.values(): - camera.update(sim.get_physics_dt(), force_recompute=True) - for name, camera in cameras.items(): - rays, valid, forward_cosine = reference_rays(camera, cases[name], args.sampling, fixation) - expected = ray_depth(rays, origin) - output = camera.data.output["distance_to_camera"] - measured = (output.torch if isinstance(output, ProxyArray) else output).cpu().numpy().reshape(-1) - depth = camera.data.output["depth"] - depth = (depth.torch if isinstance(depth, ProxyArray) else depth).cpu().numpy().reshape(-1) - # Native RTX annotators measure ray range after advancing by near clip. - # Forward-axis depth still measures from the optical center. - expected_range = expected - NEAR if args.backend == "rtx" else expected - error = np.abs(measured[valid] - expected_range[valid]) - depth_error = np.abs(depth[valid] - expected[valid] * forward_cosine[valid]) - record = dict( - case=name, - phase=phase, - median_error_m=float(np.median(error)) if valid.any() else None, - p95_error_m=float(np.quantile(error, 0.95)) if valid.any() else None, - p99_error_m=float(np.quantile(error, 0.99)) if valid.any() else None, - max_error_m=float(error.max()) if valid.any() else None, - depth_p99_error_m=float(np.quantile(depth_error, 0.99)) if valid.any() else None, - valid_samples=int(valid.sum()), - ) - records.append(record) - print(json.dumps(record), flush=True) - rgb = camera.data.output["rgb"] - rgb = (rgb.torch if isinstance(rgb, ProxyArray) else rgb).cpu().numpy() - rgb_flat = rgb.reshape(-1, 3) - foreground = rgb_flat[:, 0] > rgb_flat[:, 2] - record["rgb_foreground_agreement"] = ( - float(np.mean(foreground[valid] == (expected[valid] < 3))) if valid.any() else None - ) - frames[f"{name}_{phase}"] = dict(distance=measured.copy(), expected=expected, valid=valid, rgb=rgb) - if not valid.all(): - assert np.all(rgb.reshape(-1, 3)[~valid] == 0), (name, phase, "color mask") - masked_depth = FAR if args.sampling == "dense" else 0 - assert np.all(measured[~valid] == masked_depth), (name, phase, "distance mask") - assert np.all(depth[~valid] == masked_depth), (name, phase, "depth mask") - if video is not None and phase >= 4: - frame = video_frame(frames, maps, phase, args.backend, fixation) - video.append_data(frame[:, :, ::-1]) - if args.video_frames: - import imageio_ffmpeg - - video_frames, _ = imageio_ffmpeg.count_frames_and_secs(str(args.output.with_suffix(".mp4"))) - if video_frames != args.video_frames: - raise AssertionError(f"Expected {args.video_frames} video frames, decoded {video_frames}") - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(json.dumps(records, indent=2) + "\n") - np.savez_compressed( - args.output.with_suffix(".npz"), - **{f"{key}_{channel}": value for key, frame in frames.items() for channel, value in frame.items()}, - ) - sim.stop() - for record in records: - if record["valid_samples"] == 0: - # RGB, range, and depth were required to be entirely zero above. - continue - assert record["p95_error_m"] < 0.01, record - assert record["p99_error_m"] < 0.03, record - assert record["depth_p99_error_m"] < 0.03, record - assert record["rgb_foreground_agreement"] > 0.99, record - for name in cases: - np.testing.assert_allclose(frames[f"{name}_0"]["distance"], frames[f"{name}_3"]["distance"], atol=0.001) - np.testing.assert_allclose(frames[f"{name}_1"]["distance"], frames[f"{name}_2"]["distance"], atol=0.001) - for name in ("intrinsics", "distortion", "pinhole", "brown"): - frame, baseline = frames[f"{name}_0"], frames["equidistant_0"] - assert abs(frame["distance"][frame["valid"]].mean() - baseline["distance"][baseline["valid"]].mean()) > 0.01, ( - name - ) - print("CALIBRATED RENDER CHECK PASSED", flush=True) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--backend", choices=("rtx", "newton", "ovrtx"), required=True) - parser.add_argument("--sampling", choices=("dense", "foveated"), required=True) - parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--video_frames", type=int, default=0) - parser.add_argument("--near", type=float, default=NEAR) - AppLauncher.add_app_launcher_args(parser) - args = parser.parse_args() - NEAR = args.near - if args.video_frames < 0 or (args.video_frames and args.sampling != "foveated"): - parser.error("--video_frames must be nonnegative and requires --sampling foveated") - args.enable_cameras = True - faulthandler.dump_traceback_later(60, repeat=True) - launcher = None if args.backend == "ovrtx" else AppLauncher(args) - exit_code = 0 - try: - main(args) - except Exception: - exit_code = 1 - traceback.print_exc() - raise - finally: - if launcher is not None: - launcher.app.close(exit_code=exit_code) diff --git a/source/isaaclab_fovi/test/test_calibrated_camera_batch.py b/source/isaaclab_fovi/test/test_calibrated_camera_batch.py deleted file mode 100644 index 28a1ea8f2fc7..000000000000 --- a/source/isaaclab_fovi/test/test_calibrated_camera_batch.py +++ /dev/null @@ -1,30 +0,0 @@ -# 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 - -"""Batched captures preserve corrected ranges while the camera is not due.""" - -from types import SimpleNamespace - -import torch - -from isaaclab_fovi.sensors.calibrated_camera import CalibratedTiledCamera - - -def test_held_frame_does_not_accumulate_near_distance() -> None: - camera = SimpleNamespace() - camera.cfg = SimpleNamespace( - renderer_cfg=SimpleNamespace(renderer_type="ovrtx"), - spawn=SimpleNamespace(clipping_range=(0.04, 20.0)), - ) - camera._is_outdated = [True] - camera._env_mask_has_any = lambda mask: mask[0] - ranges = torch.tensor([[[[1.0], [2.0]]]]) - camera._data = SimpleNamespace(output={"distance_to_camera": SimpleNamespace(torch=ranges)}) - camera._invalid_pixels = torch.tensor([[[[False], [True]]]]) - CalibratedTiledCamera.process_rendered_frame(camera) - torch.testing.assert_close(ranges, torch.tensor([[[[1.04], [20.0]]]])) - camera._is_outdated[0] = False - CalibratedTiledCamera.process_rendered_frame(camera) - torch.testing.assert_close(ranges, torch.tensor([[[[1.04], [20.0]]]])) diff --git a/source/isaaclab_fovi/test/test_calibrated_camera_geometry.py b/source/isaaclab_fovi/test/test_calibrated_camera_geometry.py deleted file mode 100644 index ac9a96b86538..000000000000 --- a/source/isaaclab_fovi/test/test_calibrated_camera_geometry.py +++ /dev/null @@ -1,230 +0,0 @@ -# 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 - -"""Physical-lens raster rays checked against independent OpenCV projections.""" - -from pathlib import Path -from types import SimpleNamespace - -import numpy as np -import pytest -import torch - -# OpenCV provides the independent projection reference for these checks. -cv2 = pytest.importorskip("cv2") -CameraModel = pytest.importorskip("fovi.sensing.projection").CameraModel - -from isaaclab_fovi.sensors.dense_calibrated_geometry import ( # noqa: E402 - apply_lens_schema, - dense_camera_rays, - lens_schema_values, -) -from isaaclab_fovi.sensors.generalized_projection import ( # noqa: E402 - build_dense_calibrated_textures, -) - - -@pytest.mark.parametrize( - "model,distortion", - [ - ("pinhole", (-0.1, 0.02, 0.001, -0.002, 0.003)), - ("fisheye", (0.01, -0.003, 0.0002, -0.00001)), - ], -) -def test_dense_rays_reproject_to_original_pixel_centers(model: str, distortion: tuple[float, ...]) -> None: - camera = CameraModel(model, (120, 192), (72.5, 74, 93.2, 61.7), distortion) - rays, valid = dense_camera_rays(camera) - cv_rays = rays.double() * torch.tensor((1, -1, -1)) - points = cv_rays[valid].numpy().reshape(-1, 1, 3) - fx, fy, cx, cy = camera.intrinsics - matrix = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) - project = cv2.fisheye.projectPoints if model == "fisheye" else cv2.projectPoints - pixels, _ = project(points, np.zeros(3), np.zeros(3), matrix, np.array(distortion)) - expected = valid.nonzero()[:, [1, 0]].numpy() - np.testing.assert_allclose(pixels[:, 0], expected, atol=5e-5) - assert valid.float().mean() > 0.9 - - -def test_image_circle_and_angular_domain_mask_dense_pixels() -> None: - camera = CameraModel("fisheye", (80, 120), (40, 40, 59.5, 39.5), image_circle=(59.5, 39.5, 35), max_angle_deg=40) - rays, valid = dense_camera_rays(camera) - assert valid[40, 60] and not valid[0, 0] - assert not valid[40, 95] # Inside raster but beyond angular domain. - assert torch.isfinite(rays).all() - torch.testing.assert_close(rays[~valid], torch.tensor([0.0, 0.0, -1.0]).expand((~valid).sum(), 3)) - - -def test_native_schema_keeps_brown_and_fisheye_coefficient_order() -> None: - camera = CameraModel("pinhole", (80, 120), (55, 58, 57, 42), (1, 2, 3, 4, 5)) - schema, token, attrs = lens_schema_values(camera) - assert schema == "OmniLensDistortionOpenCvPinholeAPI" and token == "opencvPinhole" - assert (attrs["p1"], attrs["p2"], attrs["k3"], attrs["k4"]) == (3, 4, 5, 0) - schema, token, attrs = lens_schema_values(CameraModel("fisheye", (80, 120), (55, 58, 57, 42))) - assert schema == "OmniLensDistortionOpenCvFisheyeAPI" and token == "opencvFisheye" - assert [attrs[f"k{i}"] for i in range(1, 5)] == [0, 0, 0, 0] - - -def test_native_schema_converts_integer_centers_to_pixel_edge_coordinates() -> None: - for model in ("pinhole", "fisheye"): - camera = CameraModel(model, (80, 120), (55, 58, 57, 42)) - _, _, attrs = lens_schema_values(camera) - assert (attrs["cx"], attrs["cy"]) == (57.5, 42.5) - - -@pytest.mark.parametrize("model", ["pinhole", "fisheye"]) -def test_native_usd_calibration_survives_stage_roundtrip(model: str) -> None: - Usd = pytest.importorskip("pxr.Usd") - from pxr import UsdGeom - - camera = CameraModel(model, (80, 120), (55, 58, 57, 42), (0.01, -0.002, 0.0001, 0.0)) - schema, token, attrs = lens_schema_values(camera) - stage = Usd.Stage.CreateInMemory() - prim = UsdGeom.Camera.Define(stage, "/Camera").GetPrim() - apply_lens_schema(prim, camera) - text = stage.GetRootLayer().ExportToString() - restored = Usd.Stage.CreateInMemory() - restored.GetRootLayer().ImportFromString(text) - prim = restored.GetPrimAtPath("/Camera") - assert schema in prim.GetMetadata("apiSchemas").GetAppliedItems() - assert prim.GetAttribute("omni:lensdistortion:model").Get() == token - assert tuple(prim.GetAttribute(f"omni:lensdistortion:{token}:imageSize").Get()) == (120, 80) - for key, value in attrs.items(): - assert prim.GetAttribute(f"omni:lensdistortion:{token}:{key}").Get() == pytest.approx(value) - - -def test_dense_fisheye_rtx_uses_lut_for_valid_rectangular_corners( - monkeypatch: pytest.MonkeyPatch, -) -> None: - from isaaclab.sensors import Camera - from pxr import Usd, UsdGeom - - from isaaclab_fovi.sensors.calibrated_camera import CalibratedTiledCamera - - class InitializationOnlyCamera(CalibratedTiledCamera): - def __init__(self) -> None: - self.camera_model = CameraModel("fisheye", (24, 40), (18, 19, 18, 12)) - self.cfg = SimpleNamespace(prim_path="/Camera", renderer_cfg=SimpleNamespace(renderer_type="isaac_rtx")) - self.stage = Usd.Stage.CreateInMemory() - self._device = "cpu" - - def __del__(self) -> None: - pass - - camera = InitializationOnlyCamera() - prim = UsdGeom.Camera.Define(camera.stage, "/Camera").GetPrim() - monkeypatch.setattr(Camera, "_initialize_impl", lambda self: None) - camera._initialize_impl() - - assert not camera._invalid_pixels.any() - assert prim.GetAttribute("omni:lensdistortion:model").Get() == "lut" - assert "OmniLensDistortionLutAPI" in prim.GetMetadata("apiSchemas").GetAppliedItems() - paths = [ - Path(prim.GetAttribute(f"omni:lensdistortion:lut:{name}").Get().path) - for name in ("rayEnterDirectionTexture", "rayExitPositionTexture") - ] - assert all(path.is_file() for path in paths) - rays_bgr = cv2.imread(str(paths[0]), cv2.IMREAD_UNCHANGED) - expected, _ = dense_camera_rays(camera.camera_model) - np.testing.assert_array_equal(rays_bgr[..., ::-1], expected.numpy()) - - -@pytest.mark.parametrize("renderer", ["isaac_rtx", "ovrtx", "newton_warp"]) -def test_calibrated_metadata_initialization_preserves_measured_intrinsics( - renderer: str, caplog: pytest.LogCaptureFixture -) -> None: - from isaaclab.sensors.camera.camera_data import CameraData - from pxr import Sdf, Usd, UsdGeom - - from isaaclab_fovi.sensors.calibrated_camera import CalibratedTiledCamera - - class MetadataOnlyCamera(CalibratedTiledCamera): - def __init__(self) -> None: - self.camera_model = CameraModel("fisheye", (80, 120), (55, 58, 57, 42)).resized((40, 60)) - self.cfg = SimpleNamespace(height=40, width=60) - self._device = "cpu" - self._view = SimpleNamespace(count=2) - self._data_generation = self._data_generation_last_update = 0 - self._data_dirty = False - self.stage = Usd.Stage.CreateInMemory() - self._sensor_prims = [UsdGeom.Camera.Define(self.stage, f"/Camera{i}") for i in range(2)] - for camera in self._sensor_prims: - camera.GetFocalLengthAttr().Set(20) - camera.GetHorizontalApertureAttr().Set(10) - if renderer != "newton_warp": - camera.GetPrim().CreateAttribute("omni:lensdistortion:model", Sdf.ValueTypeNames.Token).Set("lut") - self._data = CameraData() - self._data.create_buffers(2, "cpu") - - def __del__(self) -> None: - pass - - camera = MetadataOnlyCamera() - camera._initialize_intrinsics() - # Half-pixel-aware resize of the original integer-center calibration. - expected = np.array(((27.5, 0, 28.25), (0, 29, 20.75), (0, 0, 1))) - np.testing.assert_array_equal(camera.data.intrinsic_matrices.torch.numpy(), np.repeat(expected[None], 2, axis=0)) - assert "falling back" not in caplog.text - assert camera._sensor_prims[0].GetFocalLengthAttr().Get() == 20 - - -@pytest.mark.parametrize("distortion", [(), (0.01, -0.003, 0.0002, -0.00001)]) -def test_dense_lut_inverse_preserves_pixel_centers_and_depth_directions( - distortion: tuple[float, ...], -) -> None: - height, width = 24, 40 - camera = CameraModel("fisheye", (height, width), (18, 19, 18, 12), distortion) - directions, inverse = build_dense_calibrated_textures(camera, exit_size=4 * width + 1) - # These physically valid corners lie outside the native RTX fisheye circle. - assert all( - torch.isfinite(directions[row, col]).all() - for row, col in ((0, 0), (0, width - 1), (height - 1, 0), (height - 1, width - 1)) - ) - cv_directions = directions.numpy() * (1, -1, -1) - matrix = np.array(((18, 0, 18), (0, 19, 12), (0, 0, 1)), dtype=np.float64) - pixels, _ = cv2.fisheye.projectPoints( - cv_directions.reshape(-1, 1, 3), - np.zeros(3), - np.zeros(3), - matrix, - np.asarray(distortion or (0, 0, 0, 0), dtype=np.float64), - ) - row, col = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij") - expected_pixels = torch.stack((col, row), -1).numpy() - np.testing.assert_allclose(pixels.reshape(height, width, 2), expected_pixels, atol=5e-5) - torch.testing.assert_close(directions.norm(dim=-1), torch.ones(height, width)) - - # For front-hemisphere rays, octahedral texture coordinates are the signed - # XY components divided by the L1 norm, then mapped from [-1, 1] to [0, 1]. - octahedral_xy = directions[..., :2] / directions.abs().sum(-1, keepdim=True) - recovered_uv = torch.nn.functional.grid_sample( - inverse.permute(2, 0, 1)[None], - octahedral_xy[None], - mode="bilinear", - align_corners=False, - )[0].permute(1, 2, 0) - recovered_pixels = recovered_uv * torch.tensor((width, height)) - 0.5 - # Bilinear interpolation across octahedral axis seams has finite-table error; - # keep it below a tenth pixel, well below a half-pixel convention mismatch. - # Exclude raster boundaries where interpolation includes the invalid sentinel. - torch.testing.assert_close( - recovered_pixels[1:-1, 1:-1], - torch.stack((col, row), -1).float()[1:-1, 1:-1], - rtol=0, - atol=0.1, - ) - torch.testing.assert_close(recovered_pixels[12, 18], torch.tensor((18.0, 12.0)), rtol=0, atol=2e-6) - - -def test_dense_lut_inverse_keeps_declared_image_circle_and_angle_mask() -> None: - camera = CameraModel("fisheye", (24, 40), (18, 19, 18, 12), image_circle=(18, 12, 7), max_angle_deg=15) - _, inverse = build_dense_calibrated_textures(camera, exit_size=128) - valid = (inverse >= 0).all(-1) - assert valid.any() and not valid.all() - pixels = inverse[valid].double() * torch.tensor((40, 24)) - 0.5 - rays, pixel_valid = camera.unproject(pixels) - assert pixel_valid.all() - assert torch.linalg.vector_norm(pixels - pixels.new_tensor((18, 12)), dim=-1).max() <= 7 - assert torch.acos(rays[:, 2]).rad2deg().max() <= 15 - assert torch.all(inverse[~valid] == -1) diff --git a/source/isaaclab_fovi/test/test_dense_foveated_lens_parity.py b/source/isaaclab_fovi/test/test_dense_foveated_lens_parity.py deleted file mode 100644 index 97d82f824a61..000000000000 --- a/source/isaaclab_fovi/test/test_dense_foveated_lens_parity.py +++ /dev/null @@ -1,39 +0,0 @@ -# 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 - -"""Dense raster and foveated renderers must use the same physical lens rays.""" - -import pytest -import torch -from fovi.sensing.projection import CameraModel, gaze_rotation - -from isaaclab_fovi.sensors.calibrated_geometry import calibrated_visibility, retinal_directions -from isaaclab_fovi.sensors.dense_calibrated_geometry import dense_camera_rays - - -@pytest.mark.parametrize( - "model,distortion", - [ - ("pinhole", (-0.06, 0.01, 0.001, -0.002, 0.0)), - ("fisheye", (0.01, -0.003, 0.0001, 0.0)), - ], -) -def test_dense_and_foveated_rays_agree_under_off_axis_gaze(model: str, distortion: tuple[float, ...]) -> None: - camera = CameraModel(model, (120, 192), (100, 103, 93.4, 61.2), distortion) - dense, valid = dense_camera_rays(camera) - pixels = torch.tensor([[50, 40], [100, 60], [140, 80]]) - assert valid[pixels[:, 1], pixels[:, 0]].all() - source_rays = dense[pixels[:, 1], pixels[:, 0]].double() * torch.tensor([1, -1, -1]) - rotation = gaze_rotation(torch.tensor([[0.2, -0.1, 1.0]], dtype=torch.float64), "pan_tilt")[0] - retinal = source_rays @ rotation - theta = torch.atan2(torch.linalg.vector_norm(retinal[:, :2], dim=-1), retinal[:, 2]) - xy = torch.nn.functional.normalize(retinal[:, :2], dim=-1) * theta[:, None] - cartesian = xy * torch.tensor([1, -1]) / torch.deg2rad(torch.tensor(60.0)) - rendered = retinal_directions(cartesian, 120) * torch.tensor([1, -1, -1]) - torch.testing.assert_close(rendered @ rotation.T, source_rays, atol=1e-7, rtol=1e-7) - recovered, projected_valid = camera.project(rendered @ rotation.T) - torch.testing.assert_close(recovered, pixels.double(), atol=2e-5, rtol=0) - assert projected_valid.all() - torch.testing.assert_close(calibrated_visibility(camera, rendered, rotation[None])[0], projected_valid) From a72041a7e6db7f33c2105a88ba7ac307278c7cdf Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:29:50 -0800 Subject: [PATCH 03/81] Apply repository lint rules to isaaclab_fovi Sort imports and modernize annotations under the root ruff configuration, and log a warning when a Kit sensor extension cannot be enabled instead of ignoring the failure. --- .../isaaclab_fovi/examples/render_foveated.py | 6 +++--- .../sensors/foveated_newton_tiled_camera.py | 1 + .../sensors/foveated_rtx_tiled_camera.py | 18 +++++++----------- .../sensors/foveated_tiled_camera_cfg.py | 1 + .../sensors/generalized_projection.py | 7 +++---- .../isaaclab_fovi/sensors/pooling.py | 14 +++++++------- .../isaaclab_fovi/sensors/virtual_gaze.py | 1 + .../test/test_backend_dispatch.py | 1 - .../test/test_calibrated_gaze_fusion.py | 1 - .../isaaclab_fovi/test/test_hybrid_geometry.py | 3 +-- source/isaaclab_fovi/test/test_lens_schema.py | 4 ++-- source/isaaclab_fovi/test/test_native_grid.py | 1 - .../isaaclab_fovi/test/test_newton_buffers.py | 6 +++--- source/isaaclab_fovi/test/test_pooling.py | 1 - source/isaaclab_fovi/test/test_rays.py | 1 - source/isaaclab_fovi/test/test_rtx_layout.py | 1 - .../test/test_spherical_geometry.py | 4 ++-- .../test/test_square_native_grid.py | 1 - 18 files changed, 31 insertions(+), 41 deletions(-) diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index a73dd9cbaa72..6d8e186bc799 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -55,13 +55,13 @@ def main() -> None: """Render RGB of a static cube, optionally moving the fixation.""" # Isaac Sim plugins must be available before importing simulator-bound types. - import isaaclab.sim as sim_utils import torch import warp as wp - from isaaclab.utils.warp import ProxyArray - from isaaclab_fovi.sensors import FoveatedTiledCamera, FoveatedTiledCameraCfg + import isaaclab.sim as sim_utils + from isaaclab.utils.warp import ProxyArray + if args.backend == "newton": from isaaclab_newton.physics.mjwarp_solver_cfg import MJWarpSolverCfg from isaaclab_newton.physics.newton_manager_cfg import NewtonCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py index 22e12c1259bb..63820fd5a97f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py @@ -20,6 +20,7 @@ import torch import warp as wp + from isaaclab.sensors.camera.camera import Camera from isaaclab.utils.math import quat_from_euler_xyz, quat_mul from isaaclab.utils.warp import ProxyArray diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py index 941c9c1b4032..5c5b9a4b4a0e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py @@ -22,6 +22,7 @@ import torch import warp as wp + from isaaclab import sim as sim_utils from isaaclab.sensors.camera.camera import Camera from isaaclab.utils.math import matrix_from_quat, quat_from_matrix @@ -330,17 +331,12 @@ def _initialize_impl(self) -> None: # OVRTX owns its runtime; Kit extensions belong only to Isaac RTX. if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": - try: - import omni.kit.app - - ext_manager = omni.kit.app.get_app().get_extension_manager() - for ext_name in ("omni.sensors.nv.common", "omni.sensors.nv.camera"): - try: - ext_manager.set_extension_enabled_immediate(ext_name, True) - except Exception: - pass - except ImportError: - pass + import omni.kit.app + + ext_manager = omni.kit.app.get_app().get_extension_manager() + for ext_name in ("omni.sensors.nv.common", "omni.sensors.nv.camera"): + if not ext_manager.set_extension_enabled_immediate(ext_name, True): + logger.warning("Could not enable Kit extension '%s'; the lens lookup may not render.", ext_name) # Moving-gaze DLSS quality still needs validation with native LUTs; # geometry smoke tests disable temporal accumulation. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py index 6e50a75b9222..5382d6355a48 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py @@ -8,6 +8,7 @@ from __future__ import annotations from fovi.sensing.projection import CameraCalibration + from isaaclab.sensors.camera.camera_cfg import CameraCfg from isaaclab.utils.configclass import configclass diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py index dc8ede0d31bb..812e4083b574 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py @@ -40,7 +40,6 @@ import math import os -from typing import Tuple # Must be set before cv2 is first imported anywhere in the process. os.environ.setdefault("OPENCV_IO_ENABLE_OPENEXR", "1") @@ -131,7 +130,7 @@ def _octahedral_decode( width: int, height: int, device="cuda", -) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Decode octahedral-LUT texel centres to unit directions (camera −Z convention). Returns: @@ -219,7 +218,7 @@ def build_generalized_projection_textures( exit_height: int, chunk: int = 8192, device="cuda", -) -> Tuple[torch.Tensor, torch.Tensor]: +) -> tuple[torch.Tensor, torch.Tensor]: """Build direction and exit LUT tensors from a labelled set of sensor samples. Both tensors are filled by **nearest-neighbour assignment**. @@ -307,7 +306,7 @@ def save_generalized_projection_textures( exit_texture: torch.Tensor, output_dir: str, basename: str, -) -> Tuple[str, str]: +) -> tuple[str, str]: """Save direction and exit LUT tensors as EXR files. Returns: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index a9b07b1589e6..d3b63abd0f00 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -40,7 +40,7 @@ from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg -def build_lowres_coords(cfg: "FoveatedTiledCameraCfg", device: str) -> tuple["SamplingCoords", int]: +def build_lowres_coords(cfg: FoveatedTiledCameraCfg, device: str) -> tuple[SamplingCoords, int]: """Build the lowres (RGC / public output) SamplingCoords. Returns ``(lowres_coords, matched_res)`` where ``matched_res`` is the @@ -76,7 +76,7 @@ def build_lowres_coords(cfg: "FoveatedTiledCameraCfg", device: str) -> tuple["Sa return lowres, matched_res -def build_highres_coords(cfg: "FoveatedTiledCameraCfg", matched_res: int, device: str) -> "SamplingCoords | None": +def build_highres_coords(cfg: FoveatedTiledCameraCfg, matched_res: int, device: str) -> SamplingCoords | None: """Build the highres (photoreceptor) SamplingCoords when pooling is on.""" if not cfg.pool_enabled: return None @@ -101,12 +101,12 @@ def build_highres_coords(cfg: "FoveatedTiledCameraCfg", matched_res: int, device def build_pooler( - cfg: "FoveatedTiledCameraCfg", - lowres: "SamplingCoords", - highres: "SamplingCoords | None", + cfg: FoveatedTiledCameraCfg, + lowres: SamplingCoords, + highres: SamplingCoords | None, device: str, mode: str | None = None, -) -> tuple["KNNPoolingLayer | GridPoolingLayer | None", int | None]: +) -> tuple[KNNPoolingLayer | GridPoolingLayer | None, int | None]: """Build a retinal pooling layer. Both coord sets must already be on ``device``. If ``mode`` is None, uses ``cfg.pool_mode`` — the standard pooler for @@ -142,7 +142,7 @@ def is_segmentation_output(name: str) -> bool: return "segmentation" in name -def pool_hwc_buffer(pooler: "KNNPoolingLayer | GridPoolingLayer", buf: torch.Tensor) -> torch.Tensor: +def pool_hwc_buffer(pooler: KNNPoolingLayer | GridPoolingLayer, buf: torch.Tensor) -> torch.Tensor: """Pool a ``(B, N_hi, 1, C)`` sensor buffer into ``(B, N_lo, 1, C)``. Both poolers expect ``(B, C, N)`` inputs, so we permute in and out. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index b9451d36745c..f0ada54e402d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -13,6 +13,7 @@ import torch import warp as wp from fovi.sensing.projection import CameraModel, angular_directions, gaze_rotation + from isaaclab.utils.math import matrix_from_quat, quat_from_matrix from .calibrated_geometry import ( diff --git a/source/isaaclab_fovi/test/test_backend_dispatch.py b/source/isaaclab_fovi/test/test_backend_dispatch.py index daa65c511d95..28d783b63ef6 100644 --- a/source/isaaclab_fovi/test/test_backend_dispatch.py +++ b/source/isaaclab_fovi/test/test_backend_dispatch.py @@ -8,7 +8,6 @@ from dataclasses import dataclass import pytest - from isaaclab_fovi.sensors import FoveatedTiledCamera diff --git a/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py b/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py index bd6a5d12f807..80485813465f 100644 --- a/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py +++ b/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py @@ -8,7 +8,6 @@ import pytest import torch from fovi.sensing.projection import CameraModel, gaze_rotation - from isaaclab_fovi.sensors.calibrated_geometry import ( calibrated_fixation_rotation, calibrated_mount_angles, diff --git a/source/isaaclab_fovi/test/test_hybrid_geometry.py b/source/isaaclab_fovi/test/test_hybrid_geometry.py index bcf5f3883070..cf2d3140905e 100644 --- a/source/isaaclab_fovi/test/test_hybrid_geometry.py +++ b/source/isaaclab_fovi/test/test_hybrid_geometry.py @@ -8,14 +8,13 @@ import numpy as np import pytest import torch -from scipy.spatial.transform import Rotation as R - from isaaclab_fovi.sensors.fixed_software_fov import ( fixed_frustum_validity, image_fixation_to_camera_angles, image_fixation_to_pan_tilt_angles, retinal_ray_directions, ) +from scipy.spatial.transform import Rotation as R def test_center_image_fixation_preserves_camera_axis() -> None: diff --git a/source/isaaclab_fovi/test/test_lens_schema.py b/source/isaaclab_fovi/test/test_lens_schema.py index 27c34198e1a5..3dc0b748ccef 100644 --- a/source/isaaclab_fovi/test/test_lens_schema.py +++ b/source/isaaclab_fovi/test/test_lens_schema.py @@ -8,12 +8,12 @@ import pytest Usd = pytest.importorskip("pxr.Usd") -from pxr import UsdGeom # noqa: E402 - from isaaclab_fovi.sensors.generalized_projection import ( # noqa: E402 apply_generalized_projection_to_prim, ) +from pxr import UsdGeom # noqa: E402 + def test_lut_schema_has_explicit_model_and_assets_after_export() -> None: stage = Usd.Stage.CreateInMemory() diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py index 9defbc80a83c..2a9faae9d3a9 100644 --- a/source/isaaclab_fovi/test/test_native_grid.py +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -10,7 +10,6 @@ import pytest import torch from fovi.sensing.coords import SamplingCoords - from isaaclab_fovi.sensors.generalized_projection import build_native_grid_textures from isaaclab_fovi.sensors.native_grid import ( allocate_grid_outputs, diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index c793857167a8..40c0a0437869 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -11,13 +11,13 @@ import torch import warp as wp from fovi.sensing.coords import SamplingCoords +from isaaclab_fovi.sensors import foveated_newton_tiled_camera as newton_camera +from isaaclab_fovi.sensors.foveated_newton_tiled_camera import FoveatedNewtonTiledCamera + from isaaclab.renderers.output_contract import RenderBufferKind, RenderBufferSpec from isaaclab.sensors.camera.camera_data import CameraData from isaaclab.utils.warp import ProxyArray -from isaaclab_fovi.sensors import foveated_newton_tiled_camera as newton_camera -from isaaclab_fovi.sensors.foveated_newton_tiled_camera import FoveatedNewtonTiledCamera - def test_pooled_allocation_accepts_proxy_arrays_and_preserves_render_buffers() -> None: rgba = torch.zeros((1, 8, 1, 4), dtype=torch.uint8) diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 56265ddcd180..0f0b19d133fb 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -11,7 +11,6 @@ import torch from fovi.arch.knn import KNNPoolingLayer from fovi.arch.pooling import GridPoolingLayer - from isaaclab_fovi.sensors.pooling import ( build_highres_coords, build_lowres_coords, diff --git a/source/isaaclab_fovi/test/test_rays.py b/source/isaaclab_fovi/test/test_rays.py index 84f6950bf9b5..af5e3fe55bdf 100644 --- a/source/isaaclab_fovi/test/test_rays.py +++ b/source/isaaclab_fovi/test/test_rays.py @@ -10,7 +10,6 @@ import pytest import torch import warp as wp - from isaaclab_fovi.sensors.foveated_rays import ( compute_explicit_ray_array, compute_foveated_ray_array, diff --git a/source/isaaclab_fovi/test/test_rtx_layout.py b/source/isaaclab_fovi/test/test_rtx_layout.py index 44762d97c60a..4172f48702af 100644 --- a/source/isaaclab_fovi/test/test_rtx_layout.py +++ b/source/isaaclab_fovi/test/test_rtx_layout.py @@ -6,7 +6,6 @@ """Reject atlas layouts that destroy spatial neighborhoods before rendering.""" import pytest - from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 56be04218cfb..f56ec3be0661 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -13,8 +13,6 @@ import warp as wp from fovi.sensing.projection import CameraModel, angular_directions from fovi.sensing.retina import RetinalTransform -from isaaclab.utils.math import matrix_from_quat, quat_apply, quat_from_euler_xyz, quat_from_matrix - from isaaclab_fovi.sensors.calibrated_geometry import ( retinal_directions, rotate_camera_rays, @@ -25,6 +23,8 @@ from isaaclab_fovi.sensors.pooling import build_lowres_coords from isaaclab_fovi.sensors.virtual_gaze import CalibratedVirtualGaze +from isaaclab.utils.math import matrix_from_quat, quat_apply, quat_from_euler_xyz, quat_from_matrix + @pytest.fixture def tf32_enabled(): diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 10d3fa7db909..2bfcbf627d4f 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -10,7 +10,6 @@ import pytest import torch from fovi.sensing.coords import SamplingCoords - from isaaclab_fovi.sensors.generalized_projection import build_native_grid_textures from isaaclab_fovi.sensors.native_grid import ( allocate_grid_outputs, From 2a313d2df31315fc8cec601c2ab0c7f353240be8 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:36:48 -0800 Subject: [PATCH 04/81] Make FoveatedCamera a class and drop Tiled from names FoveatedCamera is now the base class of the Newton and RTX implementations and returns the one matching the configured renderer. The configuration resolves the default renderer like CameraCfg does. Remove the gaze helper's pose getters, which shadowed Camera.get_world_poses with a different signature. --- source/isaaclab_fovi/docs/square_foveated.md | 2 +- .../isaaclab_fovi/examples/render_foveated.py | 8 +- .../isaaclab_fovi/sensors/__init__.py | 81 +++++-------------- .../isaaclab_fovi/sensors/foveated_camera.py | 59 ++++++++++++++ ...d_camera_cfg.py => foveated_camera_cfg.py} | 22 ++--- ...ed_camera.py => foveated_newton_camera.py} | 20 ++--- ...tiled_camera.py => foveated_rtx_camera.py} | 22 ++--- .../sensors/generalized_projection.py | 2 +- .../isaaclab_fovi/sensors/pooling.py | 12 +-- .../isaaclab_fovi/sensors/virtual_gaze.py | 22 +---- .../test/test_backend_dispatch.py | 29 ++++--- .../isaaclab_fovi/test/test_newton_buffers.py | 14 ++-- source/isaaclab_fovi/test/test_rtx_layout.py | 12 +-- .../test/test_spherical_geometry.py | 8 +- .../test/test_square_native_grid.py | 16 ++-- 15 files changed, 162 insertions(+), 167 deletions(-) create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py rename source/isaaclab_fovi/isaaclab_fovi/sensors/{foveated_tiled_camera_cfg.py => foveated_camera_cfg.py} (93%) rename source/isaaclab_fovi/isaaclab_fovi/sensors/{foveated_newton_tiled_camera.py => foveated_newton_camera.py} (97%) rename source/isaaclab_fovi/isaaclab_fovi/sensors/{foveated_rtx_tiled_camera.py => foveated_rtx_camera.py} (97%) diff --git a/source/isaaclab_fovi/docs/square_foveated.md b/source/isaaclab_fovi/docs/square_foveated.md index af7f029bf0f7..bd418ae88573 100644 --- a/source/isaaclab_fovi/docs/square_foveated.md +++ b/source/isaaclab_fovi/docs/square_foveated.md @@ -3,7 +3,7 @@ Both RTX and Newton foveated cameras accept this configuration: ```python -FoveatedTiledCameraCfg( +FoveatedCameraCfg( prim_path="/World/Camera", foveated_style="warped_cartesian_as_grid", radius_norm=float("inf"), diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index 6d8e186bc799..2d6d72eca213 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -57,7 +57,7 @@ def main() -> None: # Isaac Sim plugins must be available before importing simulator-bound types. import torch import warp as wp - from isaaclab_fovi.sensors import FoveatedTiledCamera, FoveatedTiledCameraCfg + from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg import isaaclab.sim as sim_utils from isaaclab.utils.warp import ProxyArray @@ -100,7 +100,7 @@ def main() -> None: "intrinsics": (550.0, 550.0, 319.5, 239.5), "distortion": (0.02, -0.003, 0.0, 0.0), } - cfg = FoveatedTiledCameraCfg( + cfg = FoveatedCameraCfg( prim_path="/World/envs/env_.*/Eye", data_types=["rgb"], renderer_cfg=renderer, @@ -122,9 +122,9 @@ def main() -> None: camera_fov_deg=60.0, spawn=sim_utils.PinholeCameraCfg(focal_length=24.0, horizontal_aperture=27.713), # OpenGL camera looking along +Y with +Z up. - offset=FoveatedTiledCameraCfg.OffsetCfg(rot=(0.70710678, 0.0, 0.0, 0.70710678), convention="opengl"), + offset=FoveatedCameraCfg.OffsetCfg(rot=(0.70710678, 0.0, 0.0, 0.70710678), convention="opengl"), ) - camera = FoveatedTiledCamera(cfg) + camera = FoveatedCamera(cfg) sim.reset() frame_seconds: list[float] = [] frames: list[torch.Tensor] = [] diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py index 188255bd927f..a09878b8285a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py @@ -3,75 +3,30 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Camera sensors and simulator-independent projection helpers. +"""Foveated camera sensors and simulator-independent projection helpers. -Backend classes are imported on demand so Newton and pure geometry callers -do not load the RTX runtime. +Names are imported on first access, so reading the configuration or the geometry +helpers does not load a renderer runtime. """ from __future__ import annotations -from collections.abc import Callable -from typing import TYPE_CHECKING +import importlib +from typing import Any -if TYPE_CHECKING: - import warp as wp +_LAZY_EXPORTS = { + "FoveatedCamera": "foveated_camera", + "FoveatedCameraCfg": "foveated_camera_cfg", + "FoveatedNewtonCamera": "foveated_newton_camera", + "FoveatedRTXCamera": "foveated_rtx_camera", + "compute_foveated_ray_array": "foveated_rays", +} - from .foveated_newton_tiled_camera import FoveatedNewtonTiledCamera - from .foveated_rays import compute_foveated_ray_array - from .foveated_rtx_tiled_camera import FoveatedRTXTiledCamera - from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg +__all__ = list(_LAZY_EXPORTS) -__all__ = [ - "FoveatedNewtonTiledCamera", - "FoveatedRTXTiledCamera", - "FoveatedTiledCamera", - "FoveatedTiledCameraCfg", - "compute_foveated_ray_array", -] - -def FoveatedTiledCamera( - cfg: FoveatedTiledCameraCfg, -) -> FoveatedNewtonTiledCamera | FoveatedRTXTiledCamera: - """Construct a foveated camera for the explicitly selected renderer. - - Args: - cfg: Camera configuration with a concrete renderer configuration. - - Raises: - ValueError: The renderer is not supported. - NotImplementedError: Non-tiled Isaac RTX rendering is requested. - """ - renderer_type = cfg.renderer_cfg.renderer_type - if renderer_type == "newton_warp": - from .foveated_newton_tiled_camera import FoveatedNewtonTiledCamera - - return FoveatedNewtonTiledCamera(cfg) - if renderer_type in ("isaac_rtx", "ovrtx"): - if not cfg.tiled: - raise NotImplementedError("Non-tiled foveated RTX rendering is not implemented. Use tiled=True.") - from .foveated_rtx_tiled_camera import FoveatedRTXTiledCamera - - return FoveatedRTXTiledCamera(cfg) - raise ValueError(f"Unsupported foveated renderer {renderer_type!r}; select 'newton_warp', 'isaac_rtx', or 'ovrtx'.") - - -def __getattr__(name: str) -> type | Callable[..., wp.array]: - if name == "FoveatedTiledCameraCfg": - from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg - - return FoveatedTiledCameraCfg - if name == "FoveatedNewtonTiledCamera": - from .foveated_newton_tiled_camera import FoveatedNewtonTiledCamera - - return FoveatedNewtonTiledCamera - if name == "FoveatedRTXTiledCamera": - from .foveated_rtx_tiled_camera import FoveatedRTXTiledCamera - - return FoveatedRTXTiledCamera - if name == "compute_foveated_ray_array": - from .foveated_rays import compute_foveated_ray_array - - return compute_foveated_ray_array - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") +def __getattr__(name: str) -> Any: + module = _LAZY_EXPORTS.get(name) + if module is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + return getattr(importlib.import_module(f"{__name__}.{module}"), name) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py new file mode 100644 index 000000000000..5630a64748aa --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -0,0 +1,59 @@ +# 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 + +"""Foveated camera sensor.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.sensors.camera.camera import Camera + +from .virtual_gaze import CalibratedVirtualGaze + +if TYPE_CHECKING: + from .foveated_camera_cfg import FoveatedCameraCfg + + +class FoveatedCamera(CalibratedVirtualGaze, Camera): + """Camera that samples the scene on a foveated retina instead of a uniform pixel grid. + + The sample layout comes from :class:`fovi.sensing.coords.SamplingCoords`. Constructing this class returns the + implementation for the renderer selected by :attr:`FoveatedCameraCfg.renderer_cfg`: + + * ``newton_warp``: :class:`~isaaclab_fovi.sensors.foveated_newton_camera.FoveatedNewtonCamera`, which injects + the foveated rays into the Newton Warp renderer. + * ``isaac_rtx`` and ``ovrtx``: :class:`~isaaclab_fovi.sensors.foveated_rtx_camera.FoveatedRTXCamera`, which + authors a lens lookup table on the camera prim. + + Both are subclasses of this class and are imported on first use, so selecting one renderer does not load the + other's runtime. + """ + + cfg: FoveatedCameraCfg + + def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): + """Create the implementation that matches the configured renderer. + + Args: + cfg: Camera configuration with a concrete renderer configuration. + + Raises: + ValueError: The configured renderer has no foveated implementation. + """ + if cls is not FoveatedCamera: + return super().__new__(cls) + renderer_type = cfg.renderer_cfg.renderer_type + if renderer_type == "newton_warp": + from .foveated_newton_camera import FoveatedNewtonCamera + + return super().__new__(FoveatedNewtonCamera) + if renderer_type in ("isaac_rtx", "ovrtx"): + from .foveated_rtx_camera import FoveatedRTXCamera + + return super().__new__(FoveatedRTXCamera) + raise ValueError( + f"Unsupported foveated renderer {renderer_type!r}; select 'newton_warp', 'isaac_rtx', or 'ovrtx'." + ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py similarity index 93% rename from source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py rename to source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 5382d6355a48..fd7bd22674c3 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_tiled_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Configuration for the FoveatedTiledCamera sensor.""" +"""Configuration for the FoveatedCamera sensor.""" from __future__ import annotations @@ -16,20 +16,19 @@ @configclass -class FoveatedTiledCameraCfg(CameraCfg): - """Configuration for a foveated tiled camera sensor. +class FoveatedCameraCfg(CameraCfg): + """Configuration for a foveated camera sensor. Extends :class:`CameraCfg` with CMF-based foveation parameters. The sensor generates non-uniform foveated rays from :class:`fovi.sensing.coords.SamplingCoords`. ``height`` and ``width`` are auto-computed from the number of sampling coordinates. - The actual camera class (Newton or RTX) is resolved at runtime by the - :func:`isaaclab_fovi.sensors.FoveatedTiledCamera` factory based on - ``renderer_cfg.renderer_type``. + :class:`~isaaclab_fovi.sensors.FoveatedCamera` selects its Newton or RTX + implementation from ``renderer_cfg.renderer_type``. """ - class_type: type | str = "isaaclab_fovi.sensors:FoveatedTiledCamera" + class_type: type | str = "isaaclab_fovi.sensors:FoveatedCamera" # -- Foveation parameters (no img_height/img_width/fixation_size) -------- @@ -155,13 +154,6 @@ class labels and breaks downstream integer/equality checks, so these # -- RTX-specific parameters (ignored by Newton backend) ---------------- - tiled: bool = True - """Use a shared tiled RTX render product across environments. - - Non-tiled foveated RTX rendering is not implemented and selecting it - raises :class:`NotImplementedError`. Ignored by Newton backend. - """ - ndc_layout: str = "cortical_disc" """RTX texture layout: ``cortical_disc`` or warped Cartesian ``native_grid``. @@ -186,6 +178,8 @@ class labels and breaks downstream integer/equality checks, so these update_latest_camera_pose: bool = True def __post_init__(self): + # Resolves the default renderer and forwards deprecated renderer fields. + super().__post_init__() if self.ndc_layout not in ("cortical_disc", "native_grid"): raise ValueError( f"Unsupported ndc_layout={self.ndc_layout!r}; use 'cortical_disc' or 'native_grid'. " diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py similarity index 97% rename from source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py rename to source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 63820fd5a97f..300f987766b3 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_tiled_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -32,6 +32,7 @@ retinal_ray_directions, validate_fixed_software_fov, ) +from .foveated_camera import FoveatedCamera from .foveated_rays import compute_explicit_ray_array, compute_foveated_ray_array from .native_grid import ( GRID_STYLE, @@ -49,10 +50,9 @@ is_segmentation_output, pool_hwc_buffer, ) -from .virtual_gaze import CalibratedVirtualGaze if TYPE_CHECKING: - from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + from .foveated_camera_cfg import FoveatedCameraCfg logger = logging.getLogger(__name__) @@ -68,8 +68,8 @@ def _pack_vector_rays( target[i, 1] = source[source_i, 1] -class FoveatedNewtonTiledCamera(CalibratedVirtualGaze, Camera): - """Newton tiled camera that renders with foveated (CMF-distributed) rays. +class FoveatedNewtonCamera(FoveatedCamera): + """Newton camera that renders with foveated (CMF-distributed) rays. Instead of a uniform pixel grid, this sensor shoots *N* rays whose directions are derived from :class:`fovi.sensing.coords.SamplingCoords` @@ -81,9 +81,9 @@ class FoveatedNewtonTiledCamera(CalibratedVirtualGaze, Camera): full scene. Fixation is applied as a per-environment camera rotation. """ - cfg: FoveatedTiledCameraCfg + cfg: FoveatedCameraCfg - def __init__(self, cfg: FoveatedTiledCameraCfg): + def __init__(self, cfg: FoveatedCameraCfg): if cfg.field_geometry == "spherical": cfg.update_latest_camera_pose = True if cfg.camera_fov_deg is not None: @@ -157,7 +157,7 @@ def _initialize_impl(self): ) print( f"\n{'=' * 60}\n" - f" FoveatedNewtonTiledCamera\n" + f" FoveatedNewtonCamera\n" f" HFOV: {self._camera_hfov_deg:.1f}°\n" f" Projection: {self.cfg.projection}\n" f" Samples: N={self._num_valid_samples}\n" @@ -317,7 +317,7 @@ def _initialize_impl(self): # 6. Inject foveated rays into render_data immediately. self._render_data.camera_rays = self._foveated_rays logger.info( - "FoveatedNewtonTiledCamera: injected foveated rays shape=%s onto render_data", + "FoveatedNewtonCamera: injected foveated rays shape=%s onto render_data", self._foveated_rays.shape, ) @@ -368,12 +368,12 @@ def _allocate_pooled_buffers(self) -> None: ) dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} print( - f"[FoveatedNewtonTiledCamera] pool outputs={dtypes_summary} " + f"[FoveatedNewtonCamera] pool outputs={dtypes_summary} " f"pool_mode={self.cfg.pool_mode!r} int_mode={self.cfg.pool_int_mode!r} " f"int_pooler_built={self._pooler_int is not None}" ) logger.info( - "FoveatedNewtonTiledCamera: KNN pooling enabled " + "FoveatedNewtonCamera: KNN pooling enabled " "(mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) " "outputs=%s int_pooler=%s int_mode=%s", self.cfg.pool_mode, diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py similarity index 97% rename from source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py rename to source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 5c5b9a4b4a0e..2d4ce977c88e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_tiled_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -9,7 +9,7 @@ via the RTX path tracer using ``OmniLensDistortionLutAPI`` textures. Per-sample values are extracted from the rendered 2D texture to produce vector ``(B, N, 1, C)`` or upright native-grid ``(B, H, W, C)`` output buffers, -identical to :class:`FoveatedNewtonTiledCamera`. +identical to :class:`FoveatedNewtonCamera`. """ from __future__ import annotations @@ -35,6 +35,7 @@ retinal_ray_directions, validate_fixed_software_fov, ) +from .foveated_camera import FoveatedCamera from .native_grid import ( GRID_STYLE, allocate_grid_outputs, @@ -50,18 +51,17 @@ is_segmentation_output, pool_hwc_buffer, ) -from .virtual_gaze import CalibratedVirtualGaze if TYPE_CHECKING: from isaaclab.renderers.base_renderer import BaseRenderer - from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + from .foveated_camera_cfg import FoveatedCameraCfg logger = logging.getLogger(__name__) -class FoveatedRTXTiledCamera(CalibratedVirtualGaze, Camera): - """RTX tiled camera that renders with foveated (CMF-distributed) rays. +class FoveatedRTXCamera(FoveatedCamera): + """RTX camera that renders with foveated (CMF-distributed) rays. Instead of Newton's Warp ray arrays, this sensor creates ``OmniLensDistortionLutAPI`` Camera prims with LUT textures that define @@ -74,14 +74,14 @@ class FoveatedRTXTiledCamera(CalibratedVirtualGaze, Camera): a physical or idealized actuator. """ - cfg: FoveatedTiledCameraCfg + cfg: FoveatedCameraCfg @property def supports_batch_update(self) -> bool: return True @staticmethod - def _update_buffers_batch_impl(sensors: Sequence[FoveatedRTXTiledCamera]) -> None: + def _update_buffers_batch_impl(sensors: Sequence[FoveatedRTXCamera]) -> None: Camera._update_buffers_batch_impl(sensors) if sim_utils.SimulationContext.instance() is None: return # The base implementation already invoked scalar capture. @@ -93,7 +93,7 @@ def renderer(self) -> BaseRenderer: """Renderer shared with task-owned visual animation bindings.""" return self._renderer - def __init__(self, cfg: FoveatedTiledCameraCfg): + def __init__(self, cfg: FoveatedCameraCfg): if cfg.field_geometry == "spherical": cfg.update_latest_camera_pose = True if cfg.camera_fov_deg is not None: @@ -296,7 +296,7 @@ def _prepare_projection(self) -> None: ) print( f"\n{'=' * 60}\n" - f" FoveatedRTXTiledCamera\n" + f" FoveatedRTXCamera\n" f" HFOV: {self._camera_hfov_deg:.1f}°\n" f" Samples: N={self._num_valid_samples}\n" f" Texture: {tw}x{th}\n" @@ -402,7 +402,7 @@ def _initialize_impl(self) -> None: self._data.output = new_output logger.info( - "FoveatedRTXTiledCamera: %d samples, %dx%d texture, layout=%s", + "FoveatedRTXCamera: %d samples, %dx%d texture, layout=%s", self._num_ray_samples, tw, th, @@ -461,7 +461,7 @@ def _allocate_foveated_buffers(self): mode=self.cfg.pool_int_mode, ) logger.info( - "FoveatedRTXTiledCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", + "FoveatedRTXCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", self.cfg.pool_mode, self._pool_k, self.cfg.pool_sample_cortex, diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py index 812e4083b574..191853d6ab1f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py @@ -26,7 +26,7 @@ returns the sensor NDC ``(u, v)`` of the nearest sample. Ported from ``fovi-rtx/generalized_projection.py`` — contains only the -subset of functions required by :class:`FoveatedRTXTiledCamera`. +subset of functions required by :class:`FoveatedRTXCamera`. Coordinate conventions: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index d3b63abd0f00..9149f780a274 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -3,11 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Shared retinal-pooling helpers for FoveatedTiledCamera backends. +"""Shared retinal-pooling helpers for FoveatedCamera backends. Builds a pair of (lowres, highres) :class:`SamplingCoords` and a retinal pooler analogous to :class:`fovi.sensing.samplers.PoolingGridSampler`, but driven by a -:class:`FoveatedTiledCameraCfg` and operating on rays rather than images. +:class:`FoveatedCameraCfg` and operating on rays rather than images. Key deviation from ``PoolingGridSampler``: the highres grid shares ``cmf_a`` with the lowres grid (no ``cmf_a_mult``). Only ``res`` is scaled by @@ -37,10 +37,10 @@ from fovi.arch.pooling import GridPoolingLayer from fovi.sensing.coords import SamplingCoords - from .foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + from .foveated_camera_cfg import FoveatedCameraCfg -def build_lowres_coords(cfg: FoveatedTiledCameraCfg, device: str) -> tuple[SamplingCoords, int]: +def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCoords, int]: """Build the lowres (RGC / public output) SamplingCoords. Returns ``(lowres_coords, matched_res)`` where ``matched_res`` is the @@ -76,7 +76,7 @@ def build_lowres_coords(cfg: FoveatedTiledCameraCfg, device: str) -> tuple[Sampl return lowres, matched_res -def build_highres_coords(cfg: FoveatedTiledCameraCfg, matched_res: int, device: str) -> SamplingCoords | None: +def build_highres_coords(cfg: FoveatedCameraCfg, matched_res: int, device: str) -> SamplingCoords | None: """Build the highres (photoreceptor) SamplingCoords when pooling is on.""" if not cfg.pool_enabled: return None @@ -101,7 +101,7 @@ def build_highres_coords(cfg: FoveatedTiledCameraCfg, matched_res: int, device: def build_pooler( - cfg: FoveatedTiledCameraCfg, + cfg: FoveatedCameraCfg, lowres: SamplingCoords, highres: SamplingCoords | None, device: str, diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index f0ada54e402d..73b02432cec8 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -27,27 +27,7 @@ class CalibratedVirtualGaze: - """Calibrated virtual-gaze operations shared by tiled-camera backends.""" - - def get_world_positions(self) -> torch.Tensor: - """Read live camera origins without capturing RGB or changing image metadata. - - Unlike ``data``, this only queries the camera's FrameView and never - refreshes lazy image buffers. Hybrid virtual gaze leaves origins unchanged. - """ - position, _ = self.get_world_poses() - return position - - def get_world_poses(self) -> tuple[torch.Tensor, torch.Tensor]: - """Read live scene-frame poses without refreshing images or their metadata. - - Returns: - World positions (B, 3), in meters, and OpenGL orientations (B, 4), - as XYZW quaternions. The tensors borrow the sensor view's buffers. - RTX gaze writes are included; Warp's renderer-only gaze is not. - """ - position, orientation = self._view.get_world_poses() - return position.torch, orientation.torch + """Calibrated virtual-gaze operations shared by the foveated camera backends.""" def calibrated_fov_sample_mask(self) -> torch.Tensor: """Return the physical-sensor visibility mask in canonical ray order (B,N).""" diff --git a/source/isaaclab_fovi/test/test_backend_dispatch.py b/source/isaaclab_fovi/test/test_backend_dispatch.py index 28d783b63ef6..a72ef8a19d51 100644 --- a/source/isaaclab_fovi/test/test_backend_dispatch.py +++ b/source/isaaclab_fovi/test/test_backend_dispatch.py @@ -3,12 +3,12 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Unsupported renderers fail before importing simulator backends.""" +"""The foveated camera class selects its implementation from the renderer.""" from dataclasses import dataclass import pytest -from isaaclab_fovi.sensors import FoveatedTiledCamera +from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg, FoveatedNewtonCamera, FoveatedRTXCamera @dataclass @@ -19,17 +19,24 @@ class RendererSelection: @dataclass class CameraSelection: renderer_cfg: RendererSelection - tiled: bool -def test_unknown_backend_fails_explicitly() -> None: - cfg = CameraSelection(RendererSelection("unknown"), True) +def test_default_renderer_is_resolved_to_a_concrete_one() -> None: + cfg = FoveatedCameraCfg(prim_path="/World/Camera") + assert cfg.renderer_cfg.renderer_type != "default" + + +def test_unknown_renderer_fails_explicitly() -> None: + cfg = CameraSelection(RendererSelection("unknown")) with pytest.raises(ValueError, match="Unsupported foveated renderer"): - FoveatedTiledCamera(cfg) + FoveatedCamera(cfg) -@pytest.mark.parametrize("renderer_type", ["isaac_rtx", "ovrtx"]) -def test_non_tiled_rtx_fails_explicitly(renderer_type: str) -> None: - cfg = CameraSelection(RendererSelection(renderer_type), False) - with pytest.raises(NotImplementedError, match="Non-tiled.*not implemented"): - FoveatedTiledCamera(cfg) +@pytest.mark.parametrize( + ("renderer_type", "implementation"), + [("newton_warp", FoveatedNewtonCamera), ("isaac_rtx", FoveatedRTXCamera), ("ovrtx", FoveatedRTXCamera)], +) +def test_renderer_selects_implementation(renderer_type: str, implementation: type) -> None: + camera = FoveatedCamera.__new__(FoveatedCamera, CameraSelection(RendererSelection(renderer_type))) + assert type(camera) is implementation + assert isinstance(camera, FoveatedCamera) diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 40c0a0437869..577592e720c4 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -11,8 +11,8 @@ import torch import warp as wp from fovi.sensing.coords import SamplingCoords -from isaaclab_fovi.sensors import foveated_newton_tiled_camera as newton_camera -from isaaclab_fovi.sensors.foveated_newton_tiled_camera import FoveatedNewtonTiledCamera +from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera +from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera from isaaclab.renderers.output_contract import RenderBufferKind, RenderBufferSpec from isaaclab.sensors.camera.camera_data import CameraData @@ -40,7 +40,7 @@ def test_pooled_allocation_accepts_proxy_arrays_and_preserves_render_buffers() - camera._pool_k = 2 camera.cfg = SimpleNamespace(data_types=["rgba"], pool_int_mode="max", pool_mode="avg", pool_sample_cortex=False) - FoveatedNewtonTiledCamera._allocate_pooled_buffers(camera) + FoveatedNewtonCamera._allocate_pooled_buffers(camera) assert camera._pooled_output["rgba"].shape == (1, 4, 1, 4) assert camera._pooled_output["rgba"].dtype == torch.uint8 @@ -57,7 +57,7 @@ def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatc monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (pooler, 4)) - monkeypatch.setattr(FoveatedNewtonTiledCamera, "_initialize_calibrated_gaze", lambda self: None) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_calibrated_gaze", lambda self: None) def initialize_renderer(camera): # Newton launches image tiles; a vector-shaped width of one is not valid. @@ -83,7 +83,7 @@ def render(camera, env_mask): monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) - camera = object.__new__(FoveatedNewtonTiledCamera) + camera = object.__new__(FoveatedNewtonCamera) camera._initialize_handle = None camera._invalidate_initialize_handle = None camera._prim_deletion_handle = None @@ -133,6 +133,6 @@ def test_native_grid_fractional_pool_resolution_validates_newton_tiles(render_or ) if render_order == "tiled": with pytest.raises(ValueError, match="83x83.*16x8"): - FoveatedNewtonTiledCamera._validate_native_render_layout(camera) + FoveatedNewtonCamera._validate_native_render_layout(camera) else: - FoveatedNewtonTiledCamera._validate_native_render_layout(camera) + FoveatedNewtonCamera._validate_native_render_layout(camera) diff --git a/source/isaaclab_fovi/test/test_rtx_layout.py b/source/isaaclab_fovi/test/test_rtx_layout.py index 4172f48702af..0502cadcec40 100644 --- a/source/isaaclab_fovi/test/test_rtx_layout.py +++ b/source/isaaclab_fovi/test/test_rtx_layout.py @@ -6,23 +6,23 @@ """Reject atlas layouts that destroy spatial neighborhoods before rendering.""" import pytest -from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg +from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg @pytest.mark.parametrize("layout", ["row_major", "unknown"]) def test_unsupported_layout_rejected_at_configuration(layout: str) -> None: with pytest.raises(ValueError, match="ndc_layout.*cortical_disc"): - FoveatedTiledCameraCfg(ndc_layout=layout) + FoveatedCameraCfg(ndc_layout=layout) def test_cortical_disc_remains_default() -> None: - assert FoveatedTiledCameraCfg().ndc_layout == "cortical_disc" + assert FoveatedCameraCfg().ndc_layout == "cortical_disc" def test_native_grid_requires_matching_sensor() -> None: with pytest.raises(ValueError, match="native_grid requires"): - FoveatedTiledCameraCfg(ndc_layout="native_grid") + FoveatedCameraCfg(ndc_layout="native_grid") with pytest.raises(ValueError, match="requires ndc_layout"): - FoveatedTiledCameraCfg(foveated_style="warped_cartesian_as_grid") - cfg = FoveatedTiledCameraCfg(ndc_layout="native_grid", foveated_style="warped_cartesian_as_grid") + FoveatedCameraCfg(foveated_style="warped_cartesian_as_grid") + cfg = FoveatedCameraCfg(ndc_layout="native_grid", foveated_style="warped_cartesian_as_grid") assert cfg.fov_type == "circular" diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index f56ec3be0661..e27ee7d83dbb 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -18,8 +18,8 @@ rotate_camera_rays, sampling_geometry, ) -from isaaclab_fovi.sensors.foveated_newton_tiled_camera import FoveatedNewtonTiledCamera -from isaaclab_fovi.sensors.foveated_rtx_tiled_camera import FoveatedRTXTiledCamera +from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera +from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.pooling import build_lowres_coords from isaaclab_fovi.sensors.virtual_gaze import CalibratedVirtualGaze @@ -128,7 +128,7 @@ def test_newton_fixation_preserves_camera_rotation_with_tf32( angles[1::2] = 0 expected = matrix_from_quat(source.double()) @ conversion if mode == "planar": - camera = object.__new__(FoveatedNewtonTiledCamera) + camera = object.__new__(FoveatedNewtonCamera) camera._data = SimpleNamespace(quat_w_world=SimpleNamespace(torch=source)) camera._fixation = angles camera._renderer = None @@ -249,7 +249,7 @@ def test_rtx_calibrated_pose_writer_is_stable_inside_model_autocast(device: str, for enabled in [False, True]: with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled): camera.set_calibrated_angles(angles) - FoveatedRTXTiledCamera._write_calibrated_local_pose(camera) + FoveatedRTXCamera._write_calibrated_local_pose(camera) assert torch.isfinite(written[1]).all() assert written[1].dtype == torch.float32 torch.testing.assert_close(written[1].norm(dim=-1), torch.ones(48, device=device)) diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 2bfcbf627d4f..25335767913f 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -83,23 +83,23 @@ def test_textures_and_public_modalities(field: str) -> None: def test_camera_config_rejects_wang_and_requires_native_layout() -> None: - from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg kwargs = dict(prim_path="/World/Camera", foveated_style="warped_cartesian_as_grid", radius_norm=math.inf) with pytest.raises(ValueError, match="native_grid"): - FoveatedTiledCameraCfg(**kwargs, fov_type="square") + FoveatedCameraCfg(**kwargs, fov_type="square") with pytest.raises(ValueError, match="wang"): - FoveatedTiledCameraCfg(**kwargs, ndc_layout="native_grid", fov_type="wang") - cfg = FoveatedTiledCameraCfg(**kwargs, ndc_layout="native_grid", fov_type="square") + FoveatedCameraCfg(**kwargs, ndc_layout="native_grid", fov_type="wang") + cfg = FoveatedCameraCfg(**kwargs, ndc_layout="native_grid", fov_type="square") assert cfg.ndc_layout == "native_grid" @pytest.mark.parametrize("coverage", ["square", "circular"]) def test_camera_pooling_preserves_square_shells(coverage: str) -> None: - from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab_fovi.sensors.pooling import build_highres_coords, build_lowres_coords - cfg = FoveatedTiledCameraCfg( + cfg = FoveatedCameraCfg( prim_path="/World/Camera", foveated_style="warped_cartesian_as_grid", fov_type=coverage, @@ -126,7 +126,7 @@ def test_camera_pooling_preserves_square_shells(coverage: str) -> None: ], ) def test_camera_rejects_unsupported_radius_norm(kwargs: dict[str, float | str]) -> None: - from isaaclab_fovi.sensors.foveated_tiled_camera_cfg import FoveatedTiledCameraCfg + from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg with pytest.raises(ValueError, match="radius_norm"): - FoveatedTiledCameraCfg(prim_path="/World/Camera", **kwargs) + FoveatedCameraCfg(prim_path="/World/Camera", **kwargs) From ba3a2fc787881276810e58cee9d356f5244b1055 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:40:43 -0800 Subject: [PATCH 05/81] Specify cmf_a in degrees with a 0.591 degree default Replace the normalized cmf_a and cmf_a_frac fields with cmf_a_deg, passed to fovi unchanged together with the field of view in degrees for both field geometries. The RTX cortical disc layout now uses the field of view and CMF constant of the generated samples. Log the camera summary instead of printing it. --- source/isaaclab_fovi/docs/square_foveated.md | 1 - .../isaaclab_fovi/examples/render_foveated.py | 1 - .../sensors/calibrated_geometry.py | 42 +++++++++++------ .../sensors/foveated_camera_cfg.py | 16 +++---- .../sensors/foveated_newton_camera.py | 24 +++------- .../sensors/foveated_rtx_camera.py | 46 ++++++++----------- .../isaaclab_fovi/test/test_newton_buffers.py | 2 +- source/isaaclab_fovi/test/test_pooling.py | 8 ++-- .../test/test_spherical_geometry.py | 6 +-- .../test/test_square_native_grid.py | 4 ++ 10 files changed, 75 insertions(+), 75 deletions(-) diff --git a/source/isaaclab_fovi/docs/square_foveated.md b/source/isaaclab_fovi/docs/square_foveated.md index bd418ae88573..2efa7ab968f5 100644 --- a/source/isaaclab_fovi/docs/square_foveated.md +++ b/source/isaaclab_fovi/docs/square_foveated.md @@ -10,7 +10,6 @@ FoveatedCameraCfg( fov_type="square", ndc_layout="native_grid", foveated_res=64, - cmf_a=0.036021, ) ``` diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index 2d6d72eca213..3c2ea4792466 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -109,7 +109,6 @@ def main() -> None: fov_type=args.fov_type, radius_norm=args.radius_norm, ndc_layout="native_grid" if args.style == "warped_cartesian_as_grid" else "cortical_disc", - cmf_a=0.1, field_geometry=args.field_geometry, camera_calibration=calibration, fixed_software_fov=args.virtual_gaze, diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index fd9af7783fae..003172fc14c3 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -7,7 +7,8 @@ from __future__ import annotations -from typing import Literal, Protocol +import math +from typing import Any, Literal, Protocol import torch import warp as wp @@ -22,24 +23,37 @@ class SamplingGeometryConfig(Protocol): field_geometry: str camera_calibration: CameraCalibration | None - cmf_a: float - cmf_a_frac: float | None + cmf_a_deg: float retinal_window_reference_side: str retinal_window_short_side_fraction: float + spawn: Any def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: - """Resolve normalized CMF against the selected camera axis in degrees.""" - fraction = cfg.cmf_a if cfg.cmf_a_frac is None else cfg.cmf_a_frac - if cfg.field_geometry in ("planar", "legacy"): - return 1.0, fraction - if cfg.field_geometry != "spherical": - raise ValueError(f"Unknown field geometry {cfg.field_geometry!r}") - if cfg.camera_calibration is None: - raise ValueError("Spherical sensing requires camera_calibration") - camera = CameraModel(**cfg.camera_calibration) - fov = camera.field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_short_side_fraction) - return fov, fraction * fov + """Return the retinal field of view and the CMF constant, both in degrees. + + These are the units :class:`fovi.sensing.coords.SamplingCoords` takes in either + field geometry, so neither value is converted here. + + * Spherical: the field of view is the calibrated retinal window. + * Planar: the field of view is the horizontal field of view of the spawn optics. + + Raises: + ValueError: The geometry is unknown, or the configuration lacks the + calibration (spherical) or spawn optics (planar) that define the window. + """ + if cfg.field_geometry == "spherical": + if cfg.camera_calibration is None: + raise ValueError("Spherical sensing requires camera_calibration") + camera = CameraModel(**cfg.camera_calibration) + fov = camera.field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_short_side_fraction) + return fov, cfg.cmf_a_deg + if cfg.field_geometry == "planar": + if cfg.spawn is None: + raise ValueError("Planar sensing requires spawn optics to define its field of view") + fov = math.degrees(2.0 * math.atan(cfg.spawn.horizontal_aperture / (2.0 * cfg.spawn.focal_length))) + return fov, cfg.cmf_a_deg + raise ValueError(f"Unknown field geometry {cfg.field_geometry!r}; use 'spherical' or 'planar'.") def retinal_directions(cartesian: torch.Tensor, fov_deg: float, image_rotation_deg: float = 0.0) -> torch.Tensor: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index fd7bd22674c3..cc26906a149d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -32,15 +32,13 @@ class FoveatedCameraCfg(CameraCfg): # -- Foveation parameters (no img_height/img_width/fixation_size) -------- - cmf_a: float = 0.1 - """Normalized CMF parameter relative to the selected field diameter. - Smaller values give stronger foveation. The public fovi API instead takes - an angular cmf_a; sampling_geometry performs that conversion once.""" - - cmf_a_frac: float | None = None - """Normalized CMF parameter (= cmf_a / fov). If set, ``cmf_a`` is - ignored. Planar sampling uses fov=1; spherical sampling resolves degrees - from the calibrated retinal window before scaling this fraction.""" + cmf_a_deg: float = 0.591 + """Cortical magnification constant *a* of ``M(e) = 1 / (e + a)`` [deg]. + + Smaller values give stronger foveation; a value much larger than the field + of view gives nearly uniform sampling. The default is an estimate from human + data. It is passed to :class:`fovi.sensing.coords.SamplingCoords` unchanged + in both field geometries.""" field_geometry: str = "planar" camera_calibration: CameraCalibration | None = None diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 300f987766b3..6f47bc2dc340 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -112,7 +112,6 @@ def _initialize_impl(self): # after the sensor device is available, because its knn indices / # distances / gaussian weights are plain tensor attributes that # nn.Module.to() does not move. - # cfg.cmf_a is already cmf_a_frac after resolve_cmf_a_frac runs self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") self._native_grid = self.cfg.foveated_style == GRID_STYLE self._sampling_coords_highres = build_highres_coords( @@ -149,22 +148,13 @@ def _initialize_impl(self): self._fixed_fov_focal_length_px = focal_length_px self._fixed_fov_image_height = image_height self._fixed_fov_image_width = image_width - pool_line = ( - f" Pool: mode={self.cfg.pool_mode} " - f"N_hi={self._num_ray_samples} -> N_lo={self._num_valid_samples}\n" - if self.cfg.pool_enabled - else "" - ) - print( - f"\n{'=' * 60}\n" - f" FoveatedNewtonCamera\n" - f" HFOV: {self._camera_hfov_deg:.1f}°\n" - f" Projection: {self.cfg.projection}\n" - f" Samples: N={self._num_valid_samples}\n" - f" cmf_a_frac: {self.cfg.cmf_a}\n" - f" Style: {self.cfg.foveated_style}\n" - f"{pool_line}" - f"{'=' * 60}\n" + logger.info( + "FoveatedNewtonCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg", + self._num_valid_samples, + self._num_ray_samples, + self.cfg.foveated_style, + self._sampling_coords.cmf_a, + self._sampling_coords.fov, ) # 3. Size the parent's render buffers to the *rendered* ray count. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 2d4ce977c88e..a479d8c99221 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -225,9 +225,6 @@ def _prepare_projection(self) -> None: dirs = gp.ray_directions_rectilinear(r_deg, theta_rad, device="cpu") # 4. Texture dimensions and UV layout. - # UV mapping uses fov=1 normalized space (matching the profiling - # script and SamplingCoords convention). Ray directions use - # physical degrees for correct pinhole projection. if self.cfg.ndc_layout == "native_grid": tw = th = ray_coords.resolution axis = (torch.arange(tw, dtype=torch.float32) + 0.5) / tw @@ -235,12 +232,14 @@ def _prepare_projection(self) -> None: uv = torch.stack((col, row), -1).reshape(-1, 2) elif self.cfg.ndc_layout == "cortical_disc": tw = th = max(64, math.ceil(math.sqrt(4 * N / math.pi))) - r_norm = ray_coords.polar[:, 0].to(torch.float64) * 0.5 + # Eccentricity [deg] of each sample; the disc is laid out with the same + # field of view and CMF constant the samples were generated with. + eccentricity = ray_coords.polar[:, 0].to(torch.float64) * (ray_coords.fov / 2.0) uv = gp.samples_uv_cortical_disc( - r_norm, + eccentricity, theta_rad, - 1.0, - self.cfg.cmf_a, + ray_coords.fov, + ray_coords.cmf_a, device="cpu", ) else: @@ -288,25 +287,20 @@ def _prepare_projection(self) -> None: "foveated", ) - pool_line = ( - f" Pool: mode={self.cfg.pool_mode} " - f"N_hi={self._num_ray_samples} -> N_lo={self._num_valid_samples}\n" - if self.cfg.pool_enabled - else "" - ) - print( - f"\n{'=' * 60}\n" - f" FoveatedRTXCamera\n" - f" HFOV: {self._camera_hfov_deg:.1f}°\n" - f" Samples: N={self._num_valid_samples}\n" - f" Texture: {tw}x{th}\n" - f" Exit LUT: {EW}x{EH}\n" - f" Layout: {self.cfg.ndc_layout}\n" - f" cmf_a_frac: {self.cfg.cmf_a}\n" - f" Style: {self.cfg.foveated_style}\n" - f"{pool_line}" - f" LUT dir: {self._lut_tmpdir}\n" - f"{'=' * 60}\n" + logger.info( + "FoveatedRTXCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg, " + "texture %dx%d, exit lookup %dx%d, layout=%s, lookup textures in %s", + self._num_valid_samples, + self._num_ray_samples, + self.cfg.foveated_style, + ray_coords.cmf_a, + ray_coords.fov, + tw, + th, + EW, + EH, + self.cfg.ndc_layout, + self._lut_tmpdir, ) # 6. Set texture dimensions so parent allocates (B, th, tw, C) buffers. diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 577592e720c4..1c37531a9afe 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -95,7 +95,7 @@ def render(camera, env_mask): camera.cfg = SimpleNamespace( foveated_style="warped_cartesian_as_grid", fixed_software_fov=False, - cmf_a=0.036021, + cmf_a_deg=0.591, pool_enabled=pooled, pool_mode="avg", pool_int_mode="avg", diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 0f0b19d133fb..b8f56722af30 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -5,7 +5,8 @@ """Dual-grid geometry and modality-specific pooling without a simulator.""" -from dataclasses import dataclass +from dataclasses import dataclass, field +from types import SimpleNamespace import pytest import torch @@ -24,8 +25,9 @@ class SamplingConfig: """Sampling fields consumed by the shared pooling helpers.""" - cmf_a: float = 0.1 - cmf_a_frac: float | None = None + # A 90 degree planar window (focal length 1, aperture 2) with a CMF constant of a tenth of it. + cmf_a_deg: float = 9.0 + spawn: SimpleNamespace = field(default_factory=lambda: SimpleNamespace(focal_length=1.0, horizontal_aperture=2.0)) field_geometry: str = "planar" camera_calibration: dict[str, str | tuple[int, int] | tuple[float, ...]] | None = None retinal_window_reference_side: str = "short" diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index e27ee7d83dbb..4a4de073eaba 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -41,8 +41,8 @@ def camera_config() -> SimpleNamespace: return SimpleNamespace( field_geometry="spherical", camera_calibration=asdict(camera), - cmf_a=0.03, - cmf_a_frac=None, + cmf_a_deg=2.5, + spawn=None, retinal_window_reference_side="long", retinal_window_short_side_fraction=0.75, foveated_res=12, @@ -59,7 +59,7 @@ def test_rendering_and_software_sampling_share_window_and_nodes() -> None: fov, a = sampling_geometry(cfg) camera = CameraModel(**cfg.camera_calibration) assert fov == pytest.approx(camera.field_of_view("long", 0.75)) - assert a / fov == pytest.approx(0.03) + assert a == 2.5 coords, _ = build_lowres_coords(cfg, "cpu") retina = RetinalTransform( fov=fov, diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 25335767913f..2d534fb3f6fa 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -99,8 +99,12 @@ def test_camera_pooling_preserves_square_shells(coverage: str) -> None: from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab_fovi.sensors.pooling import build_highres_coords, build_lowres_coords + from isaaclab.sim import PinholeCameraCfg + cfg = FoveatedCameraCfg( prim_path="/World/Camera", + spawn=PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0), + cmf_a_deg=9.0, foveated_style="warped_cartesian_as_grid", fov_type=coverage, radius_norm=math.inf, From dfb5301a5ec03436fe3fd8900f196407329ba1cc Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:42:21 -0800 Subject: [PATCH 06/81] Default to spherical grid sampling and derive the RTX layout The foveated camera now defaults to spherical coordinates and the warped Cartesian grid style. The RTX texture layout follows from the style, so the ndc_layout field is removed, and unknown field geometries are rejected when the configuration is built. --- source/isaaclab_fovi/docs/square_foveated.md | 1 - .../isaaclab_fovi/examples/render_foveated.py | 1 - .../sensors/foveated_camera_cfg.py | 35 ++++++++----------- .../sensors/foveated_rtx_camera.py | 21 ++++------- source/isaaclab_fovi/test/test_rtx_layout.py | 25 +++++-------- .../test/test_square_native_grid.py | 14 ++++---- 6 files changed, 36 insertions(+), 61 deletions(-) diff --git a/source/isaaclab_fovi/docs/square_foveated.md b/source/isaaclab_fovi/docs/square_foveated.md index 2efa7ab968f5..e79e272ee969 100644 --- a/source/isaaclab_fovi/docs/square_foveated.md +++ b/source/isaaclab_fovi/docs/square_foveated.md @@ -8,7 +8,6 @@ FoveatedCameraCfg( foveated_style="warped_cartesian_as_grid", radius_norm=float("inf"), fov_type="square", - ndc_layout="native_grid", foveated_res=64, ) ``` diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index 3c2ea4792466..bbc069337298 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -108,7 +108,6 @@ def main() -> None: foveated_style=args.style, fov_type=args.fov_type, radius_norm=args.radius_norm, - ndc_layout="native_grid" if args.style == "warped_cartesian_as_grid" else "cortical_disc", field_geometry=args.field_geometry, camera_calibration=calibration, fixed_software_fov=args.virtual_gaze, diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index cc26906a149d..5a79c7dbdca9 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -40,7 +40,13 @@ class FoveatedCameraCfg(CameraCfg): data. It is passed to :class:`fovi.sensing.coords.SamplingCoords` unchanged in both field geometries.""" - field_geometry: str = "planar" + field_geometry: str = "spherical" + """Coordinates the samples are laid out in: ``"spherical"`` or ``"planar"``. + + Spherical sampling places samples by visual angle inside the calibrated + camera's field of view and needs :attr:`camera_calibration`. Planar sampling + places them on the image plane of the spawn optics.""" + camera_calibration: CameraCalibration | None = None """CameraModel fields for the physical source image; required for spherical geometry.""" @@ -49,9 +55,12 @@ class FoveatedCameraCfg(CameraCfg): sampling this is the number of radial rings; the total sample count *N* depends on ``(fov, cmf_a, foveated_res)``.""" - foveated_style: str = "isotropic" - """Sampling style passed to :class:`SamplingCoords`. Supported values - include ``"isotropic"``, ``"logpolar"``, ``"uniform"``, etc.""" + foveated_style: str = "warped_cartesian_as_grid" + """Sampling style passed to :class:`SamplingCoords`. + + The default ``"warped_cartesian_as_grid"`` publishes an upright image of + shape ``(B, H, W, C)``. Sample-set styles such as ``"isotropic"`` are an + advanced option and publish ``(B, N, 1, C)``.""" fov_type: str = "circular" """Visual footprint; circular is the default for native warped grids.""" @@ -152,13 +161,6 @@ class labels and breaks downstream integer/equality checks, so these # -- RTX-specific parameters (ignored by Newton backend) ---------------- - ndc_layout: str = "cortical_disc" - """RTX texture layout: ``cortical_disc`` or warped Cartesian ``native_grid``. - - Row-major packing breaks spatial filtering and is no longer accepted. - Newton does not use a texture layout. - """ - exit_texture_size: int | None = None """Dimension of the exit (inverse) LUT texture (EW = EH) for RTX rendering. If ``None`` (default), computed as ``max(128, 4 * tw)`` where ``tw`` is the @@ -178,15 +180,8 @@ class labels and breaks downstream integer/equality checks, so these def __post_init__(self): # Resolves the default renderer and forwards deprecated renderer fields. super().__post_init__() - if self.ndc_layout not in ("cortical_disc", "native_grid"): - raise ValueError( - f"Unsupported ndc_layout={self.ndc_layout!r}; use 'cortical_disc' or 'native_grid'. " - "Row-major packing is no longer supported because it breaks spatial filtering." - ) - if self.ndc_layout == "native_grid" and self.foveated_style != "warped_cartesian_as_grid": - raise ValueError("native_grid requires a Cartesian grid foveated_style.") - if self.foveated_style == "warped_cartesian_as_grid" and self.ndc_layout != "native_grid": - raise ValueError(f"{self.foveated_style} requires ndc_layout='native_grid'.") + if self.field_geometry not in ("spherical", "planar"): + raise ValueError(f"Unknown field_geometry={self.field_geometry!r}; use 'spherical' or 'planar'.") validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) # ``spawn`` is a ``PinholeCameraCfg`` / ``FisheyeCameraCfg`` whose # ``lock_camera`` field defaults to True. That writes diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index a479d8c99221..651820d05ecf 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -224,13 +224,15 @@ def _prepare_projection(self) -> None: r_deg = ray_coords.polar[:, 0].to(torch.float64) * (self._camera_hfov_deg / 2.0) dirs = gp.ray_directions_rectilinear(r_deg, theta_rad, device="cpu") - # 4. Texture dimensions and UV layout. - if self.cfg.ndc_layout == "native_grid": + # 4. Texture dimensions and UV layout. Grid styles render straight into their + # native grid; sample-set styles are packed onto a cortical disc, which keeps + # neighbouring samples adjacent for the renderer's spatial filtering. + if self._native_grid: tw = th = ray_coords.resolution axis = (torch.arange(tw, dtype=torch.float32) + 0.5) / tw row, col = torch.meshgrid(axis, axis, indexing="ij") uv = torch.stack((col, row), -1).reshape(-1, 2) - elif self.cfg.ndc_layout == "cortical_disc": + else: tw = th = max(64, math.ceil(math.sqrt(4 * N / math.pi))) # Eccentricity [deg] of each sample; the disc is laid out with the same # field of view and CMF constant the samples were generated with. @@ -242,8 +244,6 @@ def _prepare_projection(self) -> None: ray_coords.cmf_a, device="cpu", ) - else: - raise ValueError(f"Unknown ndc_layout: {self.cfg.ndc_layout!r}") self._texture_width = tw self._texture_height = th @@ -289,7 +289,7 @@ def _prepare_projection(self) -> None: logger.info( "FoveatedRTXCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg, " - "texture %dx%d, exit lookup %dx%d, layout=%s, lookup textures in %s", + "texture %dx%d, exit lookup %dx%d, lookup textures in %s", self._num_valid_samples, self._num_ray_samples, self.cfg.foveated_style, @@ -299,7 +299,6 @@ def _prepare_projection(self) -> None: th, EW, EH, - self.cfg.ndc_layout, self._lut_tmpdir, ) @@ -395,14 +394,6 @@ def _initialize_impl(self) -> None: # Older IsaacLab where ``output`` was a writable attribute. self._data.output = new_output - logger.info( - "FoveatedRTXCamera: %d samples, %dx%d texture, layout=%s", - self._num_ray_samples, - tw, - th, - self.cfg.ndc_layout, - ) - def _allocate_foveated_buffers(self): """Allocate ``(B, N_hi, 1, C)`` (and optionally ``(B, N_lo, 1, C)``) per-data-type buffers from the captured ``_texture_output`` shapes. diff --git a/source/isaaclab_fovi/test/test_rtx_layout.py b/source/isaaclab_fovi/test/test_rtx_layout.py index 0502cadcec40..61d0644e867d 100644 --- a/source/isaaclab_fovi/test/test_rtx_layout.py +++ b/source/isaaclab_fovi/test/test_rtx_layout.py @@ -3,26 +3,19 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Reject atlas layouts that destroy spatial neighborhoods before rendering.""" +"""Configuration defaults and validation of the foveated camera.""" import pytest from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg -@pytest.mark.parametrize("layout", ["row_major", "unknown"]) -def test_unsupported_layout_rejected_at_configuration(layout: str) -> None: - with pytest.raises(ValueError, match="ndc_layout.*cortical_disc"): - FoveatedCameraCfg(ndc_layout=layout) +def test_defaults_are_spherical_grid_sampling_at_the_human_cmf_estimate() -> None: + cfg = FoveatedCameraCfg() + assert cfg.field_geometry == "spherical" + assert cfg.foveated_style == "warped_cartesian_as_grid" + assert cfg.cmf_a_deg == 0.591 -def test_cortical_disc_remains_default() -> None: - assert FoveatedCameraCfg().ndc_layout == "cortical_disc" - - -def test_native_grid_requires_matching_sensor() -> None: - with pytest.raises(ValueError, match="native_grid requires"): - FoveatedCameraCfg(ndc_layout="native_grid") - with pytest.raises(ValueError, match="requires ndc_layout"): - FoveatedCameraCfg(foveated_style="warped_cartesian_as_grid") - cfg = FoveatedCameraCfg(ndc_layout="native_grid", foveated_style="warped_cartesian_as_grid") - assert cfg.fov_type == "circular" +def test_unknown_field_geometry_is_rejected() -> None: + with pytest.raises(ValueError, match="field_geometry"): + FoveatedCameraCfg(field_geometry="legacy") diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 2d534fb3f6fa..93eb5481d4fa 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -82,16 +82,14 @@ def test_textures_and_public_modalities(field: str) -> None: assert target["rgb"].untyped_storage().data_ptr() == target["rgba"].untyped_storage().data_ptr() -def test_camera_config_rejects_wang_and_requires_native_layout() -> None: +def test_camera_config_rejects_wang_with_square_shells() -> None: from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg kwargs = dict(prim_path="/World/Camera", foveated_style="warped_cartesian_as_grid", radius_norm=math.inf) - with pytest.raises(ValueError, match="native_grid"): - FoveatedCameraCfg(**kwargs, fov_type="square") with pytest.raises(ValueError, match="wang"): - FoveatedCameraCfg(**kwargs, ndc_layout="native_grid", fov_type="wang") - cfg = FoveatedCameraCfg(**kwargs, ndc_layout="native_grid", fov_type="square") - assert cfg.ndc_layout == "native_grid" + FoveatedCameraCfg(**kwargs, fov_type="wang") + cfg = FoveatedCameraCfg(**kwargs, fov_type="square") + assert cfg.fov_type == "square" @pytest.mark.parametrize("coverage", ["square", "circular"]) @@ -105,10 +103,10 @@ def test_camera_pooling_preserves_square_shells(coverage: str) -> None: prim_path="/World/Camera", spawn=PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0), cmf_a_deg=9.0, + field_geometry="planar", foveated_style="warped_cartesian_as_grid", fov_type=coverage, radius_norm=math.inf, - ndc_layout="native_grid", foveated_res=16, pool_enabled=True, pool_res_mult=2.0, @@ -125,7 +123,7 @@ def test_camera_pooling_preserves_square_shells(coverage: str) -> None: @pytest.mark.parametrize( "kwargs", [ - dict(radius_norm=1.0, foveated_style="warped_cartesian_as_grid", ndc_layout="native_grid"), + dict(radius_norm=1.0, foveated_style="warped_cartesian_as_grid"), dict(radius_norm=math.inf, foveated_style="isotropic"), ], ) From cc746ab5d72bd3907e5f1698ad8b725989162adf Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:47:10 -0800 Subject: [PATCH 07/81] Remove the projection option and unused gaze paths Drop the projection and camera_fov_deg fields, the fixed-frustum gaze setters and their geometry module. Sensor masking is now one option, mask_to_sensor_fov, that uses the calibrated camera in spherical geometry. The cameras no longer modify the caller's configuration and accept an existing camera prim without spawn optics. --- .../isaaclab_fovi/examples/render_foveated.py | 87 ++--- .../sensors/fixed_software_fov.py | 247 -------------- .../sensors/foveated_camera_cfg.py | 30 +- .../sensors/foveated_newton_camera.py | 217 ++---------- .../sensors/foveated_rtx_camera.py | 146 ++------ source/isaaclab_fovi/test/_check_imports.py | 1 - .../test/test_hybrid_geometry.py | 312 ------------------ .../isaaclab_fovi/test/test_newton_buffers.py | 5 +- .../test/test_spherical_geometry.py | 63 ++-- 9 files changed, 117 insertions(+), 991 deletions(-) delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/fixed_software_fov.py delete mode 100644 source/isaaclab_fovi/test/test_hybrid_geometry.py diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index bbc069337298..a85fb3cac518 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -5,10 +5,10 @@ """Render a small scene with a foveated camera. -Run with ``--backend newton`` or ``--backend rtx``; add ``--pool`` for -photoreceptor-to-output pooling. ``--steps`` bounds the simulation run. -With ``--virtual-gaze`` the camera stays fixed and the fixation moves inside -its calibrated field of view. +Run with ``--backend newton`` or ``--backend rtx``. By default the fixation +moves inside the fixed camera's calibrated field of view; ``--planar`` samples +the image plane of the spawn optics instead, with no gaze. ``--pool`` renders a +denser photoreceptor grid and pools it to the output grid. """ from __future__ import annotations @@ -22,45 +22,30 @@ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--backend", choices=("newton", "rtx"), required=True) -parser.add_argument("--pool", action="store_true") -parser.add_argument("--field-geometry", choices=("planar", "spherical"), default="planar") -parser.add_argument( - "--style", - choices=("isotropic", "warped_cartesian_as_grid"), - default="isotropic", -) -parser.add_argument("--fov-type", choices=("circular", "square", "wang"), default="circular") -parser.add_argument("--radius-norm", type=float, choices=(2.0, float("inf")), default=2.0) -parser.add_argument( - "--virtual-gaze", - action="store_true", - help="Move the fixation inside the fixed camera's calibrated field of view.", -) -parser.add_argument("--lens", choices=("pinhole", "fisheye"), default="pinhole") +parser.add_argument("--planar", action="store_true", help="Sample the image plane of the spawn optics.") +parser.add_argument("--pool", action="store_true", help="Pool a denser photoreceptor grid to the output grid.") +parser.add_argument("--resolution", type=int, default=64, help="Side length of the output grid.") +parser.add_argument("--cmf-a-deg", type=float, default=None, help="CMF constant [deg]; a large value is non-foveated.") parser.add_argument("--steps", type=int, default=8) -parser.add_argument("--resolution", type=int, default=16) -parser.add_argument("--output", type=Path, help="Save final RGB tensor and warm frame timings.") +parser.add_argument("--output", type=Path, help="Save the RGB frames and warm frame timings.") AppLauncher.add_app_launcher_args(parser) args = parser.parse_args() if args.steps <= 0: parser.error("--steps must be positive") if args.resolution <= 0: parser.error("--resolution must be positive") -if args.virtual_gaze and args.field_geometry != "spherical": - parser.error("--virtual-gaze requires --field-geometry spherical") args.enable_cameras = True launcher = AppLauncher(args) def main() -> None: - """Render RGB of a static cube, optionally moving the fixation.""" + """Render RGB of a static cube while the fixation moves.""" # Isaac Sim plugins must be available before importing simulator-bound types. import torch import warp as wp from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg import isaaclab.sim as sim_utils - from isaaclab.utils.warp import ProxyArray if args.backend == "newton": from isaaclab_newton.physics.mjwarp_solver_cfg import MJWarpSolverCfg @@ -69,14 +54,12 @@ def main() -> None: physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) renderer = NewtonWarpRendererCfg(render_order="pixel_priority") - elif args.backend == "rtx": + else: from isaaclab_physx.physics.physx_manager_cfg import PhysxCfg from isaaclab_physx.renderers import IsaacRtxRendererCfg physics = PhysxCfg() renderer = IsaacRtxRendererCfg() - else: - raise ValueError(f"Unsupported backend: {args.backend}") sim_utils.create_new_stage() sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(device=args.device, physics=physics)) @@ -92,42 +75,38 @@ def main() -> None: cube.func("/World/envs/env_0/Cube", cube, translation=(0.0, 2.0, 0.0)) light = sim_utils.DistantLightCfg(intensity=2000.0) light.func("/World/Light", light) - calibration = None - if args.field_geometry == "spherical": - calibration = { - "model": args.lens, - "image_size": (480, 640), - "intrinsics": (550.0, 550.0, 319.5, 239.5), - "distortion": (0.02, -0.003, 0.0, 0.0), - } + cfg = FoveatedCameraCfg( prim_path="/World/envs/env_.*/Eye", data_types=["rgb"], renderer_cfg=renderer, foveated_res=args.resolution, - foveated_style=args.style, - fov_type=args.fov_type, - radius_norm=args.radius_norm, - field_geometry=args.field_geometry, - camera_calibration=calibration, - fixed_software_fov=args.virtual_gaze, - software_fov_image_height=480, - software_fov_image_width=640, - retinal_window_reference_side="long", pool_enabled=args.pool, - pool_res_mult=2.0, - pool_mode="avg", - camera_fov_deg=60.0, + # A 60 degree horizontal field of view, used by planar sampling. spawn=sim_utils.PinholeCameraCfg(focal_length=24.0, horizontal_aperture=27.713), # OpenGL camera looking along +Y with +Z up. offset=FoveatedCameraCfg.OffsetCfg(rot=(0.70710678, 0.0, 0.0, 0.70710678), convention="opengl"), ) + if args.planar: + cfg.field_geometry = "planar" + else: + # The physical camera the retina looks through: a 640x480 pinhole. + cfg.camera_calibration = { + "model": "pinhole", + "image_size": (480, 640), + "intrinsics": (550.0, 550.0, 319.5, 239.5), + } + cfg.mask_to_sensor_fov = True + if args.cmf_a_deg is not None: + cfg.cmf_a_deg = args.cmf_a_deg camera = FoveatedCamera(cfg) sim.reset() + frame_seconds: list[float] = [] frames: list[torch.Tensor] = [] for step in range(args.steps): - if args.virtual_gaze: + if not args.planar: + # Fixation in normalized image coordinates (row, column) of the calibrated camera. fixation = torch.tensor([[0.5, (0.5, 0.58, 0.58, 0.5)[step % 4]]], device=sim.device) camera.set_calibrated_fixation(fixation) wp.synchronize_device(sim.device) @@ -137,19 +116,15 @@ def main() -> None: wp.synchronize_device(sim.device) if step > 0: frame_seconds.append(time.perf_counter() - start) - frame = camera.data.output["rgb"] - frames.append((frame.torch if isinstance(frame, ProxyArray) else frame).clone()) - rgb = camera.data.output["rgb"] - rgb_tensor = rgb.torch if isinstance(rgb, ProxyArray) else rgb + frames.append(camera.data.output["rgb"].torch.clone()) print( - f"{args.backend}: pooled={args.pool}, RGB shape={tuple(rgb_tensor.shape)}, " - f"dtype={rgb_tensor.dtype}, warm frame seconds={frame_seconds}", + f"{args.backend}: RGB shape={tuple(frames[-1].shape)}, dtype={frames[-1].dtype}, " + f"warm frame seconds={frame_seconds}", flush=True, ) if args.output is not None: torch.save( { - "rgb": rgb_tensor.cpu(), "frames": torch.stack(frames).cpu(), "sampling_coordinates": camera.sampling_coords.cartesian.cpu(), "frame_seconds": frame_seconds, diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/fixed_software_fov.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/fixed_software_fov.py deleted file mode 100644 index 15eaa988b368..000000000000 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/fixed_software_fov.py +++ /dev/null @@ -1,247 +0,0 @@ -# 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 - -"""Geometry helpers for direct foveation inside a fixed software-camera FOV.""" - -from __future__ import annotations - -import math - -import torch - -RETINAL_WINDOW_REFERENCE_SIDES = ("short", "long") -FIXED_FOV_ANGLE_MODELS = ("camera_xyz", "pan_tilt") - - -def retinal_window_reference_size( - *, - image_height: int, - image_width: int, - reference_side: str, -) -> int: - """Resolve the image dimension used as the circular retinal diameter.""" - if image_height <= 0 or image_width <= 0: - raise ValueError( - f"Retinal window reference requires positive image dimensions, got {image_height}x{image_width}." - ) - if reference_side == "short": - return min(image_height, image_width) - if reference_side == "long": - return max(image_height, image_width) - raise ValueError( - f"retinal_window_reference_side must be one of {RETINAL_WINDOW_REFERENCE_SIDES}, got {reference_side!r}." - ) - - -def validate_fixed_software_fov( - *, - image_height: int, - image_width: int, - focal_length_px: float, - principal_point: tuple[float, float], - retinal_window_short_side_fraction: float, - retinal_window_reference_side: str = "short", -) -> None: - """Validate a rectilinear dense-camera geometry.""" - if image_height <= 0 or image_width <= 0: - raise ValueError(f"fixed software FOV requires positive image dimensions, got {image_height}x{image_width}.") - if focal_length_px <= 0.0: - raise ValueError(f"fixed software FOV requires focal_length_px > 0, got {focal_length_px}.") - cx, cy = principal_point - if not 0.0 <= cx <= image_width or not 0.0 <= cy <= image_height: - raise ValueError( - "fixed software FOV principal point must lie inside the image, got " - f"{principal_point} for {image_height}x{image_width}." - ) - if not 0.0 < retinal_window_short_side_fraction <= 1.0: - raise ValueError( - f"retinal_window_short_side_fraction must be in (0, 1], got {retinal_window_short_side_fraction}." - ) - retinal_window_reference_size( - image_height=image_height, - image_width=image_width, - reference_side=retinal_window_reference_side, - ) - - -def retinal_ray_directions( - cartesian: torch.Tensor, - *, - image_height: int, - image_width: int, - focal_length_px: float, - retinal_window_short_side_fraction: float, - retinal_window_reference_side: str = "short", - image_rotation_deg: float = 0.0, -) -> torch.Tensor: - """Convert normalized retinal coordinates into camera-space pinhole rays.""" - validate_fixed_software_fov( - image_height=image_height, - image_width=image_width, - focal_length_px=focal_length_px, - principal_point=(image_width * 0.5, image_height * 0.5), - retinal_window_short_side_fraction=retinal_window_short_side_fraction, - retinal_window_reference_side=retinal_window_reference_side, - ) - rotated = cartesian - if image_rotation_deg: - theta = math.radians(float(image_rotation_deg)) - cosine = math.cos(theta) - sine = math.sin(theta) - rotation = cartesian.new_tensor(((cosine, -sine), (sine, cosine))) - rotated = cartesian @ rotation.T - reference_size = retinal_window_reference_size( - image_height=image_height, - image_width=image_width, - reference_side=retinal_window_reference_side, - ) - diameter_px = reference_size * retinal_window_short_side_fraction - tangent = rotated * (0.5 * diameter_px / focal_length_px) - directions = torch.cat( - (tangent, -torch.ones_like(tangent[:, :1])), - dim=-1, - ) - return torch.nn.functional.normalize(directions, dim=-1) - - -def _image_fixation_tangents( - fixation: torch.Tensor, - *, - image_height: int, - image_width: int, - focal_length_px: float, - principal_point: tuple[float, float], - image_rotation_deg: float = 0.0, -) -> tuple[torch.Tensor, torch.Tensor]: - validate_fixed_software_fov( - image_height=image_height, - image_width=image_width, - focal_length_px=focal_length_px, - principal_point=principal_point, - retinal_window_short_side_fraction=1.0, - ) - cx, cy = principal_point - tangent_x = (fixation[..., 1] * image_width - cx) / focal_length_px - tangent_y = (cy - fixation[..., 0] * image_height) / focal_length_px - if image_rotation_deg: - theta = math.radians(float(image_rotation_deg)) - cosine = math.cos(theta) - sine = math.sin(theta) - rotated_x = cosine * tangent_x - sine * tangent_y - tangent_y = sine * tangent_x + cosine * tangent_y - tangent_x = rotated_x - return tangent_x, tangent_y - - -def image_fixation_to_camera_angles( - fixation: torch.Tensor, - *, - image_height: int, - image_width: int, - focal_length_px: float, - principal_point: tuple[float, float], - image_rotation_deg: float = 0.0, -) -> torch.Tensor: - """Aim an XYZ-rotated virtual camera through an image fixation.""" - tangent_x, tangent_y = _image_fixation_tangents( - fixation, - image_height=image_height, - image_width=image_width, - focal_length_px=focal_length_px, - principal_point=principal_point, - image_rotation_deg=image_rotation_deg, - ) - roll = torch.atan(tangent_y) - pitch = torch.atan(-tangent_x * torch.cos(roll)) - return torch.stack((roll, pitch), dim=-1) - - -def image_fixation_to_pan_tilt_angles( - fixation: torch.Tensor, - *, - image_height: int, - image_width: int, - focal_length_px: float, - principal_point: tuple[float, float], -) -> torch.Tensor: - """Aim a +Y-forward, pan-then-tilt mount through an image fixation.""" - tangent_x, tangent_y = _image_fixation_tangents( - fixation, - image_height=image_height, - image_width=image_width, - focal_length_px=focal_length_px, - principal_point=principal_point, - ) - pan = torch.atan(-tangent_x) - tilt = torch.atan(tangent_y * torch.cos(pan)) - return torch.stack((tilt, pan), dim=-1) - - -def fixed_frustum_validity( - ray_directions: torch.Tensor, - fixation_angles: torch.Tensor, - *, - image_height: int, - image_width: int, - focal_length_px: float, - principal_point: tuple[float, float], - angle_model: str = "camera_xyz", - image_rotation_deg: float = 0.0, -) -> torch.Tensor: - """Return validity after applying the configured camera or mount rotation.""" - rays = ray_directions.unsqueeze(0) - x = rays[..., 0] - y = rays[..., 1] - z = rays[..., 2] - if angle_model == "camera_xyz": - roll = fixation_angles[:, 0:1] - pitch = fixation_angles[:, 1:2] - sin_r = torch.sin(roll) - cos_r = torch.cos(roll) - sin_p = torch.sin(pitch) - cos_p = torch.cos(pitch) - rotated_x = cos_p * x + sin_p * z - rotated_y = sin_r * sin_p * x + cos_r * y - sin_r * cos_p * z - rotated_z = -cos_r * sin_p * x + sin_r * y + cos_r * cos_p * z - elif angle_model == "pan_tilt": - if not math.isfinite(float(image_rotation_deg)): - raise ValueError(f"fixed-FOV image_rotation_deg must be finite, got {image_rotation_deg!r}.") - theta = math.radians(float(image_rotation_deg)) - cosine = math.cos(theta) - sine = math.sin(theta) - - policy_x = cosine * x + sine * y - policy_y = -sine * x + cosine * y - policy_z = z - mount_x = policy_x - mount_y = -policy_z - mount_z = policy_y - - tilt = fixation_angles[:, 0:1] - pan = fixation_angles[:, 1:2] - sin_tilt = torch.sin(tilt) - cos_tilt = torch.cos(tilt) - sin_pan = torch.sin(pan) - cos_pan = torch.cos(pan) - tilted_y = cos_tilt * mount_y - sin_tilt * mount_z - tilted_z = sin_tilt * mount_y + cos_tilt * mount_z - moved_mount_x = cos_pan * mount_x - sin_pan * tilted_y - moved_mount_y = sin_pan * mount_x + cos_pan * tilted_y - - moved_policy_x = moved_mount_x - moved_policy_y = tilted_z - moved_policy_z = -moved_mount_y - rotated_x = cosine * moved_policy_x - sine * moved_policy_y - rotated_y = sine * moved_policy_x + cosine * moved_policy_y - rotated_z = moved_policy_z - else: - raise ValueError(f"angle_model must be one of {FIXED_FOV_ANGLE_MODELS}, got {angle_model!r}.") - - forward = -rotated_z - safe_forward = forward.clamp_min(torch.finfo(ray_directions.dtype).eps) - cx, cy = principal_point - pixel_x = focal_length_px * rotated_x / safe_forward + cx - pixel_y = cy - focal_length_px * rotated_y / safe_forward - return (forward > 0.0) & (pixel_x >= 0.0) & (pixel_x < image_width) & (pixel_y >= 0.0) & (pixel_y < image_height) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 5a79c7dbdca9..9d26a55ebf3f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -91,32 +91,18 @@ class FoveatedCameraCfg(CameraCfg): * ``180.0`` — flip vertically + horizontally (upside-down sensor). * Other angles work in principle but are untested.""" - projection: str = "pinhole" - """Projection model for mapping normalized coords to ray directions. - ``"pinhole"`` (rectilinear) or ``"fisheye_equidistant"`` (linear angle - mapping, suitable for wide FOV).""" + mask_to_sensor_fov: bool = False + """Zero the samples that fall outside the calibrated camera's image at the current gaze. - camera_fov_deg: float | None = None - """If set, use this as the camera HFOV (in degrees) instead of deriving - from ``spawn.focal_length`` and ``spawn.horizontal_aperture``. When this - is not None, ``spawn.focal_length`` and ``spawn.horizontal_aperture`` - must be left at their defaults (they will be back-computed automatically - for USD prim compatibility).""" - - fixed_software_fov: bool = False - """Mask pose-steered rays against a fixed dense pinhole camera frustum.""" - - software_fov_image_height: int | None = None - """Dense camera image height used by the deployment software sampler.""" - - software_fov_image_width: int | None = None - """Dense camera image width used by the deployment software sampler.""" + With calibrated gaze the retina can look past the edge of the physical + camera; this keeps what the sensor reports to what that camera could have + seen. Requires spherical geometry.""" retinal_window_short_side_fraction: float = 1.0 - """Diameter scale applied to the selected image reference side.""" + """Diameter of the retinal window as a fraction of the reference image side. Spherical geometry only.""" retinal_window_reference_side: str = "short" - """Image side defining the circular retinal diameter: ``short`` or ``long``.""" + """Image side defining the retinal window diameter: ``short`` or ``long``. Spherical geometry only.""" # -- Optional retinal pooling (photoreceptor -> RGC two-layer sampling) -- @@ -182,6 +168,8 @@ def __post_init__(self): super().__post_init__() if self.field_geometry not in ("spherical", "planar"): raise ValueError(f"Unknown field_geometry={self.field_geometry!r}; use 'spherical' or 'planar'.") + if self.mask_to_sensor_fov and self.field_geometry != "spherical": + raise ValueError("mask_to_sensor_fov requires field_geometry='spherical'.") validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) # ``spawn`` is a ``PinholeCameraCfg`` / ``FisheyeCameraCfg`` whose # ``lock_camera`` field defaults to True. That writes diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 6f47bc2dc340..91d0c22a3903 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -22,16 +22,9 @@ import warp as wp from isaaclab.sensors.camera.camera import Camera -from isaaclab.utils.math import quat_from_euler_xyz, quat_mul from isaaclab.utils.warp import ProxyArray -from .calibrated_geometry import convert_camera_frame_quaternion, retinal_directions -from .fixed_software_fov import ( - FIXED_FOV_ANGLE_MODELS, - fixed_frustum_validity, - retinal_ray_directions, - validate_fixed_software_fov, -) +from .calibrated_geometry import retinal_directions from .foveated_camera import FoveatedCamera from .foveated_rays import compute_explicit_ray_array, compute_foveated_ray_array from .native_grid import ( @@ -76,26 +69,17 @@ class FoveatedNewtonCamera(FoveatedCamera): and injected into Newton's Warp renderer. Vector sensors publish ``(B, N, 1, C)``; native grid sensors publish upright ``(B, H, W, C)``. - The camera's physical FOV (from the ``spawn`` optics) is used as the - ``SamplingCoords.fov`` parameter so that the foveated sampling covers the - full scene. Fixation is applied as a per-environment camera rotation. + In planar geometry the samples cover the horizontal field of view of the + ``spawn`` optics. In spherical geometry they cover the calibrated retinal + window, and gaze is applied as a per-environment rotation of the rays. """ cfg: FoveatedCameraCfg def __init__(self, cfg: FoveatedCameraCfg): - if cfg.field_geometry == "spherical": - cfg.update_latest_camera_pose = True - if cfg.camera_fov_deg is not None: - # Back-compute spawn optics from desired FOV for USD prim compat. - hfov_rad = math.radians(cfg.camera_fov_deg) - aperture = cfg.spawn.horizontal_aperture # keep default aperture - cfg.spawn.focal_length = aperture / (2.0 * math.tan(hfov_rad / 2.0)) - self._spawn_focal_length: float = cfg.spawn.focal_length - self._spawn_horizontal_aperture: float = cfg.spawn.horizontal_aperture - self._fixation: torch.Tensor | None = None - self._fixed_fov_fixation: torch.Tensor | None = None - self._fixed_fov_angle_model = "camera_xyz" + # Spawn optics are only needed for planar geometry; an existing prim has none. + self._spawn_focal_length: float | None = None if cfg.spawn is None else cfg.spawn.focal_length + self._spawn_horizontal_aperture: float | None = None if cfg.spawn is None else cfg.spawn.horizontal_aperture self._calibrated_rotation = None super().__init__(cfg) @@ -105,7 +89,9 @@ def __init__(self, cfg: FoveatedCameraCfg): def _initialize_impl(self): # 1. Derive camera physical FOV for ray generation. - self._camera_hfov_rad = 2.0 * math.atan(self._spawn_horizontal_aperture / (2.0 * self._spawn_focal_length)) + self._camera_hfov_rad: float | None = None + if self._spawn_focal_length is not None: + self._camera_hfov_rad = 2.0 * math.atan(self._spawn_horizontal_aperture / (2.0 * self._spawn_focal_length)) # 2. Build coords on CPU so we know N_lo (and N_hi when pooling) before # the parent allocates buffers. The pooler is constructed later, @@ -121,33 +107,6 @@ def _initialize_impl(self): ) self._num_valid_samples = len(self._sampling_coords) # public / RGC count self._num_ray_samples = len(self._sampling_coords_highres or self._sampling_coords) - self._camera_hfov_deg = math.degrees(self._camera_hfov_rad) - self._fixed_fov_focal_length_px: float | None = None - self._fixed_fov_image_height: int | None = None - self._fixed_fov_image_width: int | None = None - if self.cfg.fixed_software_fov: - if self.cfg.projection != "pinhole" and self.cfg.field_geometry != "spherical": - raise ValueError( - f"fixed_software_fov currently requires projection='pinhole', got {self.cfg.projection!r}." - ) - image_height = self.cfg.software_fov_image_height - image_width = self.cfg.software_fov_image_width - if image_height is None or image_width is None: - raise ValueError( - "fixed_software_fov=True requires software_fov_image_height and software_fov_image_width." - ) - focal_length_px = image_width * self._spawn_focal_length / self._spawn_horizontal_aperture - validate_fixed_software_fov( - image_height=image_height, - image_width=image_width, - focal_length_px=focal_length_px, - principal_point=(image_width * 0.5, image_height * 0.5), - retinal_window_short_side_fraction=(self.cfg.retinal_window_short_side_fraction), - retinal_window_reference_side=self.cfg.retinal_window_reference_side, - ) - self._fixed_fov_focal_length_px = focal_length_px - self._fixed_fov_image_height = image_height - self._fixed_fov_image_width = image_width logger.info( "FoveatedNewtonCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg", self._num_valid_samples, @@ -213,43 +172,18 @@ def _initialize_impl(self): # mapping; this rotation does not. ray_cart = ray_coords_device.cartesian if self._native_grid: - tangent_scale = math.tan(self._camera_hfov_rad / 2) - if self.cfg.fixed_software_fov: - reference = ( - max(self._fixed_fov_image_height, self._fixed_fov_image_width) - if self.cfg.retinal_window_reference_side == "long" - else min(self._fixed_fov_image_height, self._fixed_fov_image_width) - ) - tangent_scale = ( - reference * self.cfg.retinal_window_short_side_fraction / (2 * self._fixed_fov_focal_length_px) - ) - self._fixed_fov_ray_directions = native_grid_directions( + # Spherical grids take their extent from the sampling coordinates and ignore the tangent scale. + tangent_scale = 1.0 if self._camera_hfov_rad is None else math.tan(self._camera_hfov_rad / 2) + self._ray_directions = native_grid_directions( ray_coords_device, tangent_scale=tangent_scale, image_rotation_deg=self.cfg.image_rotation_deg, - projection=self.cfg.projection, camera_fov_rad=self._camera_hfov_rad, ) - self._foveated_rays = compute_explicit_ray_array(self._fixed_fov_ray_directions, device=str(self._device)) + self._foveated_rays = compute_explicit_ray_array(self._ray_directions, device=str(self._device)) elif self.cfg.field_geometry == "spherical": - self._fixed_fov_ray_directions = retinal_directions( - ray_cart, self._sampling_coords.fov, self.cfg.image_rotation_deg - ) - self._foveated_rays = compute_explicit_ray_array(self._fixed_fov_ray_directions, device=str(self._device)) - elif self.cfg.fixed_software_fov: - self._fixed_fov_ray_directions = retinal_ray_directions( - ray_cart, - image_height=self._fixed_fov_image_height, - image_width=self._fixed_fov_image_width, - focal_length_px=self._fixed_fov_focal_length_px, - retinal_window_short_side_fraction=(self.cfg.retinal_window_short_side_fraction), - retinal_window_reference_side=self.cfg.retinal_window_reference_side, - image_rotation_deg=self.cfg.image_rotation_deg, - ) - self._foveated_rays = compute_explicit_ray_array( - self._fixed_fov_ray_directions, - device=str(self._device), - ) + self._ray_directions = retinal_directions(ray_cart, ray_coords_device.fov, self.cfg.image_rotation_deg) + self._foveated_rays = compute_explicit_ray_array(self._ray_directions, device=str(self._device)) elif self.cfg.image_rotation_deg: theta = math.radians(float(self.cfg.image_rotation_deg)) cos_t = math.cos(theta) @@ -264,14 +198,12 @@ def _initialize_impl(self): sampling_coords_cartesian=ray_cart, camera_fov_rad=self._camera_hfov_rad, device=str(self._device), - projection=self.cfg.projection, ) else: self._foveated_rays = compute_foveated_ray_array( sampling_coords_cartesian=ray_cart, camera_fov_rad=self._camera_hfov_rad, device=str(self._device), - projection=self.cfg.projection, ) render_samples = self.cfg.height * self.cfg.width @@ -357,11 +289,6 @@ def _allocate_pooled_buffers(self) -> None: mode=self.cfg.pool_int_mode, ) dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} - print( - f"[FoveatedNewtonCamera] pool outputs={dtypes_summary} " - f"pool_mode={self.cfg.pool_mode!r} int_mode={self.cfg.pool_int_mode!r} " - f"int_pooler_built={self._pooler_int is not None}" - ) logger.info( "FoveatedNewtonCamera: KNN pooling enabled " "(mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) " @@ -376,62 +303,6 @@ def _allocate_pooled_buffers(self) -> None: self.cfg.pool_int_mode, ) - # ------------------------------------------------------------------ - # Fixation - # ------------------------------------------------------------------ - - def set_fixation(self, fixation_angles: torch.Tensor): - """Set per-environment fixation as camera rotation angles. - - Args: - fixation_angles: ``(B, 2)`` tensor in radians. - ``[:, 0]`` = θ_x (X-axis rotation, positive = look up), - ``[:, 1]`` = θ_y (Y-axis rotation, positive = look left). - ``(0, 0)`` = center (no rotation). - """ - self._fixation = fixation_angles - - def set_fixed_fov_fixation( - self, - fixation_angles: torch.Tensor, - *, - angle_model: str, - ) -> None: - """Update fixed-frustum masking without rotating the camera twice.""" - if not self.cfg.fixed_software_fov: - raise RuntimeError("set_fixed_fov_fixation requires fixed_software_fov=True.") - if angle_model not in FIXED_FOV_ANGLE_MODELS: - raise ValueError(f"angle_model must be one of {FIXED_FOV_ANGLE_MODELS}, got {angle_model!r}.") - self._fixed_fov_fixation = fixation_angles - self._fixed_fov_angle_model = angle_model - - def _apply_fixation_rotation(self): - """Rotate camera orientations based on the current fixation angles. - - Composes fixation rotation (in angle-space) with the base camera - orientations in the OpenGL frame. - """ - fix = self._fixation.float() # (B, 2): [θ_x, θ_y] in radians - look_roll = fix[:, 0] # X-axis rotation (directly in radians) - look_pitch = fix[:, 1] # Y-axis rotation (directly in radians) - zeros = torch.zeros_like(look_roll) - - fix_quat = quat_from_euler_xyz(look_roll, look_pitch, zeros) # (B, 4) - - # Apply rotation in OpenGL camera frame: - # 1. Convert stored world-convention quaternions to OpenGL - quat_world = self._quat_w_world_torch() - quat_gl = convert_camera_frame_quaternion(quat_world, origin="world", target="opengl") - # 2. Compose: base rotation * fixation rotation (local frame) - quat_gl_rotated = quat_mul(quat_gl, fix_quat) - # 3. Convert back to world convention for storage - quat_world[:] = convert_camera_frame_quaternion(quat_gl_rotated, origin="opengl", target="world") - - def _quat_w_world_torch(self) -> torch.Tensor: - """Return the camera world quaternion as a Torch tensor view.""" - quat_world = self._data.quat_w_world - return quat_world.torch if hasattr(quat_world, "torch") else quat_world - # ------------------------------------------------------------------ # Per-frame overrides # ------------------------------------------------------------------ @@ -442,16 +313,13 @@ def _update_poses( env_mask: wp.array | None = None, frame_op: int = 0, ) -> None: - """Read base poses, apply fixation rotation, update renderer, inject rays. + """Read base poses, apply the calibrated gaze, update renderer, inject rays. - Read the scene pose even without a sensor-level fixation: the camera - may inherit motion from a parent articulation. + The scene pose is read even without a gaze: the camera may inherit + motion from a parent body. """ - # 1. Read base camera poses + apply fixation (only when fixation active) + # 1. Read base camera poses, then rotate them by the calibrated gaze if one is set. Camera._update_poses(self, env_ids, env_mask=env_mask, frame_op=frame_op) - if self._fixation is not None: - self._apply_fixation_rotation() - self._apply_calibrated_pose(env_ids, env_mask) # 2. Update camera_transforms @@ -476,7 +344,7 @@ def _update_buffers_impl(self, env_mask: wp.array): super()._update_buffers_impl(env_mask) output = self._flat_render_output mask_grid_samples(output, self._ray_coords) - self._apply_fixed_fov_mask(output) + self._apply_sensor_fov_mask(output) if self._native_grid: copy_grid_outputs(output, self._grid_output, self._grid_indices) self._data.output.clear() @@ -488,7 +356,7 @@ def _update_buffers_impl(self, env_mask: wp.array): self._data.output.update(self._render_output) super()._update_buffers_impl(env_mask) mask_grid_samples(self._highres_output, self._ray_coords) - self._apply_fixed_fov_mask(self._highres_output) + self._apply_sensor_fov_mask(self._highres_output) # Pool each output channel (B, N_hi, 1, C) -> (B, N_lo, 1, C). # Cast to float for pooling (KNN ops need real-valued NaN semantics), @@ -514,38 +382,13 @@ def _update_buffers_impl(self, env_mask: wp.array): else: self._data.output.update(self._pooled_output) - def _apply_fixed_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: - if not self.cfg.fixed_software_fov: + def _apply_sensor_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: + """Zero the samples that fall outside the calibrated camera at the current gaze.""" + if not self.cfg.mask_to_sensor_fov: return first_output = next(iter(outputs.values())) first_tensor = first_output.torch if hasattr(first_output, "torch") else first_output - batch_size = first_tensor.shape[0] - fixation = self._fixed_fov_fixation - if fixation is None: - fixation = self._fixation - if fixation is None: - fixation = torch.zeros( - batch_size, - 2, - device=self._fixed_fov_ray_directions.device, - dtype=self._fixed_fov_ray_directions.dtype, - ) - if self.cfg.field_geometry == "spherical": - valid = self._calibrated_validity(batch_size) - else: - valid = fixed_frustum_validity( - self._fixed_fov_ray_directions, - fixation, - image_height=self._fixed_fov_image_height, - image_width=self._fixed_fov_image_width, - focal_length_px=self._fixed_fov_focal_length_px, - principal_point=( - self._fixed_fov_image_width * 0.5, - self._fixed_fov_image_height * 0.5, - ), - angle_model=self._fixed_fov_angle_model, - image_rotation_deg=self.cfg.image_rotation_deg, - ) + valid = self._calibrated_validity(first_tensor.shape[0]) invalid = ~valid[:, :, None, None] has_rgba_alias = "rgba" in outputs for name, output in outputs.items(): @@ -553,7 +396,7 @@ def _apply_fixed_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: continue tensor = output.torch if hasattr(output, "torch") else output tensor.masked_fill_(invalid, 0) - self._fixed_fov_valid_fraction = valid.float().mean(dim=1) + self._sensor_fov_valid_fraction = valid.float().mean(dim=1) # ------------------------------------------------------------------ # Output helpers @@ -581,6 +424,6 @@ def num_valid_samples(self) -> int: return self._num_valid_samples @property - def fixed_fov_valid_fraction(self) -> torch.Tensor | None: - """Per-environment fraction of rays inside the fixed dense frustum.""" - return getattr(self, "_fixed_fov_valid_fraction", None) + def sensor_fov_valid_fraction(self) -> torch.Tensor | None: + """Per-environment fraction of samples inside the calibrated camera, or None before the first masked frame.""" + return getattr(self, "_sensor_fov_valid_fraction", None) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 651820d05ecf..8aee189b3337 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -29,12 +29,6 @@ from . import generalized_projection as gp from .calibrated_geometry import compose_rotations, retinal_directions -from .fixed_software_fov import ( - FIXED_FOV_ANGLE_MODELS, - fixed_frustum_validity, - retinal_ray_directions, - validate_fixed_software_fov, -) from .foveated_camera import FoveatedCamera from .native_grid import ( GRID_STYLE, @@ -69,9 +63,10 @@ class FoveatedRTXCamera(FoveatedCamera): which is then sampled at pre-computed UV positions to extract per-sample values, producing ``(B, N, 1, C)`` output buffers. - The cortical disc layout (default) ensures spatial coherence for DLSS - denoising. Camera motion comes from its parent articulation, using - a physical or idealized actuator. + Grid styles render straight into their native grid. Sample-set styles are + packed onto a cortical disc, which keeps neighbouring samples adjacent for + DLSS denoising. Camera motion comes from the prim's parent, and in spherical + geometry from the calibrated gaze. """ cfg: FoveatedCameraCfg @@ -94,16 +89,9 @@ def renderer(self) -> BaseRenderer: return self._renderer def __init__(self, cfg: FoveatedCameraCfg): - if cfg.field_geometry == "spherical": - cfg.update_latest_camera_pose = True - if cfg.camera_fov_deg is not None: - hfov_rad = math.radians(cfg.camera_fov_deg) - aperture = cfg.spawn.horizontal_aperture - cfg.spawn.focal_length = aperture / (2.0 * math.tan(hfov_rad / 2.0)) - self._spawn_focal_length: float = cfg.spawn.focal_length - self._spawn_horizontal_aperture: float = cfg.spawn.horizontal_aperture - self._fixed_fov_fixation: torch.Tensor | None = None - self._fixed_fov_angle_model = "pan_tilt" + # Spawn optics are only needed for planar geometry; an existing prim has none. + self._spawn_focal_length: float | None = None if cfg.spawn is None else cfg.spawn.focal_length + self._spawn_horizontal_aperture: float | None = None if cfg.spawn is None else cfg.spawn.horizontal_aperture self._calibrated_rotation = None # Texture buffers are owned by the parent ``Camera`` (allocated in # ``_create_buffers`` and bound to the renderer via ``set_outputs``). @@ -126,34 +114,9 @@ def __init__(self, cfg: FoveatedCameraCfg): def _prepare_projection(self) -> None: # 1. Derive camera physical FOV. - self._camera_hfov_rad = 2.0 * math.atan(self._spawn_horizontal_aperture / (2.0 * self._spawn_focal_length)) - self._camera_hfov_deg = math.degrees(self._camera_hfov_rad) - self._fixed_fov_focal_length_px: float | None = None - self._fixed_fov_image_height: int | None = None - self._fixed_fov_image_width: int | None = None - if self.cfg.fixed_software_fov: - if self.cfg.projection != "pinhole" and self.cfg.field_geometry != "spherical": - raise ValueError( - f"fixed_software_fov currently requires projection='pinhole', got {self.cfg.projection!r}." - ) - image_height = self.cfg.software_fov_image_height - image_width = self.cfg.software_fov_image_width - if image_height is None or image_width is None: - raise ValueError( - "fixed_software_fov=True requires software_fov_image_height and software_fov_image_width." - ) - focal_length_px = image_width * self._spawn_focal_length / self._spawn_horizontal_aperture - validate_fixed_software_fov( - image_height=image_height, - image_width=image_width, - focal_length_px=focal_length_px, - principal_point=(image_width * 0.5, image_height * 0.5), - retinal_window_short_side_fraction=(self.cfg.retinal_window_short_side_fraction), - retinal_window_reference_side=self.cfg.retinal_window_reference_side, - ) - self._fixed_fov_focal_length_px = focal_length_px - self._fixed_fov_image_height = image_height - self._fixed_fov_image_width = image_width + self._camera_hfov_rad: float | None = None + if self._spawn_focal_length is not None: + self._camera_hfov_rad = 2.0 * math.atan(self._spawn_horizontal_aperture / (2.0 * self._spawn_focal_length)) # 2. Build coords on CPU. The LUT textures + UV extraction use the # *rendered* grid (highres when pooling, else lowres). The @@ -187,41 +150,19 @@ def _prepare_projection(self) -> None: if self.cfg.image_rotation_deg: theta_rad = theta_rad + math.radians(float(self.cfg.image_rotation_deg)) if self._native_grid: - tangent_scale = math.tan(self._camera_hfov_rad / 2) - if self.cfg.fixed_software_fov: - reference = ( - max(self._fixed_fov_image_height, self._fixed_fov_image_width) - if self.cfg.retinal_window_reference_side == "long" - else min(self._fixed_fov_image_height, self._fixed_fov_image_width) - ) - tangent_scale = ( - reference * self.cfg.retinal_window_short_side_fraction / (2 * self._fixed_fov_focal_length_px) - ) + # Spherical grids take their extent from the sampling coordinates and ignore the tangent scale. + tangent_scale = 1.0 if self._camera_hfov_rad is None else math.tan(self._camera_hfov_rad / 2) self._native_tangent_scale = tangent_scale dirs = native_grid_directions( ray_coords, tangent_scale=tangent_scale, image_rotation_deg=self.cfg.image_rotation_deg, - projection=self.cfg.projection, camera_fov_rad=self._camera_hfov_rad, ) - self._fixed_fov_ray_directions_cpu = dirs elif self.cfg.field_geometry == "spherical": dirs = retinal_directions(ray_coords.cartesian, ray_coords.fov, self.cfg.image_rotation_deg) - self._fixed_fov_ray_directions_cpu = dirs - elif self.cfg.fixed_software_fov: - dirs = retinal_ray_directions( - ray_coords.cartesian, - image_height=self._fixed_fov_image_height, - image_width=self._fixed_fov_image_width, - focal_length_px=self._fixed_fov_focal_length_px, - retinal_window_short_side_fraction=(self.cfg.retinal_window_short_side_fraction), - retinal_window_reference_side=self.cfg.retinal_window_reference_side, - image_rotation_deg=self.cfg.image_rotation_deg, - ) - self._fixed_fov_ray_directions_cpu = dirs else: - r_deg = ray_coords.polar[:, 0].to(torch.float64) * (self._camera_hfov_deg / 2.0) + r_deg = ray_coords.polar[:, 0].to(torch.float64) * (ray_coords.fov / 2.0) dirs = gp.ray_directions_rectilinear(r_deg, theta_rad, device="cpu") # 4. Texture dimensions and UV layout. Grid styles render straight into their @@ -266,7 +207,6 @@ def _prepare_projection(self) -> None: tangent_scale=self._native_tangent_scale, image_rotation_deg=self.cfg.image_rotation_deg, exit_size=EW, - projection=self.cfg.projection, camera_fov_rad=self._camera_hfov_rad, ) else: @@ -345,8 +285,6 @@ def _initialize_impl(self) -> None: # point ``self._data.output`` at the foveated/pooled dict so # downstream consumers see the per-sample buffers. self._sampling_coords = self._sampling_coords.to(device=self._device) - if self.cfg.fixed_software_fov: - self._fixed_fov_ray_directions = self._fixed_fov_ray_directions_cpu.to(self._device) if self._sampling_coords_highres is not None: self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) self._ray_coords = self._sampling_coords_highres or self._sampling_coords @@ -484,20 +422,6 @@ def _write_calibrated_local_pose(self, env_ids: torch.Tensor | None = None) -> N indices=wp.from_torch(env_ids.to(dtype=torch.int32).contiguous()), ) - def set_fixed_fov_fixation( - self, - fixation_angles: torch.Tensor, - *, - angle_model: str, - ) -> None: - """Update fixed-frustum masking without changing the camera pose.""" - if not self.cfg.fixed_software_fov: - raise RuntimeError("set_fixed_fov_fixation requires fixed_software_fov=True.") - if angle_model not in FIXED_FOV_ANGLE_MODELS: - raise ValueError(f"angle_model must be one of {FIXED_FOV_ANGLE_MODELS}, got {angle_model!r}.") - self._fixed_fov_fixation = fixation_angles - self._fixed_fov_angle_model = angle_model - def _update_buffers_impl(self, env_mask: wp.array): if not self._env_mask_has_any(env_mask): return @@ -522,7 +446,7 @@ def process_rendered_frame(self) -> None: # OVRTX's LUT range AOV measures from the near-clipped ray origin. self._foveated_output["distance_to_camera"].add_(self.cfg.spawn.clipping_range[0]) mask_grid_samples(self._foveated_output, self._ray_coords) - self._apply_fixed_fov_mask() + self._apply_sensor_fov_mask() # Optionally KNN-pool highres -> lowres samples. Integer-dtype # outputs (segmentation class IDs) use the dedicated max-mode @@ -553,49 +477,27 @@ def _extract_foveated_samples(self): continue # handled via rgba alias below tex = self._texture_output[name] # (B, th, tw, C) fov = self._foveated_output[name] # (B, N, 1, C) + tensor = tex.torch if hasattr(tex, "torch") else tex if self._native_grid: - tensor = tex.torch if hasattr(tex, "torch") else tex fov.copy_(tensor.reshape_as(fov)) else: - fov[:, :, 0, :] = tex[:, py, px, :] + fov[:, :, 0, :] = tensor[:, py, px, :] if "rgba" in self._foveated_output and "rgb" in self.cfg.data_types: self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] - def _apply_fixed_fov_mask(self) -> None: - if not self.cfg.fixed_software_fov: + def _apply_sensor_fov_mask(self) -> None: + """Zero the samples that fall outside the calibrated camera at the current gaze.""" + if not self.cfg.mask_to_sensor_fov: return batch_size = next(iter(self._foveated_output.values())).shape[0] - fixation = self._fixed_fov_fixation - if fixation is None: - fixation = torch.zeros( - batch_size, - 2, - device=self._fixed_fov_ray_directions.device, - dtype=self._fixed_fov_ray_directions.dtype, - ) - if self.cfg.field_geometry == "spherical": - valid = self._calibrated_validity(batch_size) - else: - valid = fixed_frustum_validity( - self._fixed_fov_ray_directions, - fixation, - image_height=self._fixed_fov_image_height, - image_width=self._fixed_fov_image_width, - focal_length_px=self._fixed_fov_focal_length_px, - principal_point=( - self._fixed_fov_image_width * 0.5, - self._fixed_fov_image_height * 0.5, - ), - angle_model=self._fixed_fov_angle_model, - image_rotation_deg=self.cfg.image_rotation_deg, - ) + valid = self._calibrated_validity(batch_size) invalid = ~valid[:, :, None, None] has_rgba_alias = "rgba" in self._foveated_output for name, output in self._foveated_output.items(): if name == "rgb" and has_rgba_alias: continue output.masked_fill_(invalid, 0) - self._fixed_fov_valid_fraction = valid.float().mean(dim=1) + self._sensor_fov_valid_fraction = valid.float().mean(dim=1) # ------------------------------------------------------------------ # Output helpers @@ -623,6 +525,6 @@ def num_valid_samples(self) -> int: return self._num_valid_samples @property - def fixed_fov_valid_fraction(self) -> torch.Tensor | None: - """Per-environment fraction of rays inside the fixed dense frustum.""" - return getattr(self, "_fixed_fov_valid_fraction", None) + def sensor_fov_valid_fraction(self) -> torch.Tensor | None: + """Per-environment fraction of samples inside the calibrated camera, or None before the first masked frame.""" + return getattr(self, "_sensor_fov_valid_fraction", None) diff --git a/source/isaaclab_fovi/test/_check_imports.py b/source/isaaclab_fovi/test/_check_imports.py index 4bc16248f541..f1c4a68024d9 100644 --- a/source/isaaclab_fovi/test/_check_imports.py +++ b/source/isaaclab_fovi/test/_check_imports.py @@ -41,7 +41,6 @@ def find_spec( for module in ( "isaaclab_fovi", "isaaclab_fovi.sensors", - "isaaclab_fovi.sensors.fixed_software_fov", "isaaclab_fovi.sensors.foveated_rays", "isaaclab_fovi.sensors.pooling", "fovi.sensing.coords", diff --git a/source/isaaclab_fovi/test/test_hybrid_geometry.py b/source/isaaclab_fovi/test/test_hybrid_geometry.py deleted file mode 100644 index cf2d3140905e..000000000000 --- a/source/isaaclab_fovi/test/test_hybrid_geometry.py +++ /dev/null @@ -1,312 +0,0 @@ -# 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 - -import math - -import numpy as np -import pytest -import torch -from isaaclab_fovi.sensors.fixed_software_fov import ( - fixed_frustum_validity, - image_fixation_to_camera_angles, - image_fixation_to_pan_tilt_angles, - retinal_ray_directions, -) -from scipy.spatial.transform import Rotation as R - - -def test_center_image_fixation_preserves_camera_axis() -> None: - angles = image_fixation_to_camera_angles( - torch.tensor([[0.5, 0.5]]), - image_height=120, - image_width=160, - focal_length_px=100.0, - principal_point=(80.0, 60.0), - ) - - torch.testing.assert_close(angles, torch.zeros_like(angles)) - - -def test_image_rotation_rotates_normalized_fixation_before_steering() -> None: - fixation = torch.tensor([[0.5, 0.75]]) - unrotated = image_fixation_to_camera_angles( - fixation, - image_height=100, - image_width=100, - focal_length_px=100.0, - principal_point=(50.0, 50.0), - ) - rotated = image_fixation_to_camera_angles( - fixation, - image_height=100, - image_width=100, - focal_length_px=100.0, - principal_point=(50.0, 50.0), - image_rotation_deg=90.0, - ) - - assert unrotated[0, 0].abs() < 1.0e-7 - assert unrotated[0, 1] < 0.0 - assert rotated[0, 0] > 0.0 - assert rotated[0, 1].abs() < 1.0e-7 - - -@pytest.mark.parametrize( - "fixation", - [ - (0.2, 0.8), - (0.75, 0.15), - (0.1, 0.3), - ], -) -def test_pan_tilt_image_conversion_centers_off_axis_rays( - fixation: tuple[float, float], -) -> None: - image_height = 160 - image_width = 120 - focal_length_px = 180.0 - command = image_fixation_to_pan_tilt_angles( - torch.tensor([fixation]), - image_height=image_height, - image_width=image_width, - focal_length_px=focal_length_px, - principal_point=(image_width * 0.5, image_height * 0.5), - )[0] - tilt, pan = command.tolist() - - # The mount is +Y-forward with pan about +Z followed by tilt about the - # panned +X axis. Compare the resulting optical axis against the pinhole - # ray independently of the implementation under test. - optical_axis = torch.tensor( - [ - -math.sin(pan) * math.cos(tilt), - math.cos(pan) * math.cos(tilt), - math.sin(tilt), - ] - ) - expected_tangent = torch.tensor( - [ - (fixation[1] * image_width - image_width * 0.5) / focal_length_px, - (image_height * 0.5 - fixation[0] * image_height) / focal_length_px, - ] - ) - actual_tangent = optical_axis[[0, 2]] / optical_axis[1] - - torch.testing.assert_close(actual_tangent, expected_tangent) - - -def test_fixed_frustum_masks_direct_rays_after_off_center_steering() -> None: - cartesian = torch.tensor( - [ - [0.0, 0.0], - [-0.9, 0.0], - [0.9, 0.0], - ] - ) - directions = retinal_ray_directions( - cartesian, - image_height=120, - image_width=160, - focal_length_px=100.0, - retinal_window_short_side_fraction=1.0, - ) - fixation = image_fixation_to_camera_angles( - torch.tensor([[0.5, 0.9]]), - image_height=120, - image_width=160, - focal_length_px=100.0, - principal_point=(80.0, 60.0), - ) - - valid = fixed_frustum_validity( - directions, - fixation, - image_height=120, - image_width=160, - focal_length_px=100.0, - principal_point=(80.0, 60.0), - ) - - assert valid.shape == (1, 3) - assert valid[0, 0] - assert valid[0].sum() < valid.shape[1] - - -@pytest.mark.parametrize("image_rotation_deg", [-90.0, 0.0, 90.0, 180.0]) -def test_fixed_frustum_pan_tilt_matches_physical_mount_kinematics( - image_rotation_deg: float, -) -> None: - raw_height = 120 - raw_width = 160 - focal_length_px = 100.0 - if round(image_rotation_deg / 90.0) % 2: - policy_height, policy_width = raw_width, raw_height - else: - policy_height, policy_width = raw_height, raw_width - cartesian = torch.tensor( - [ - [0.0, 0.0], - [-1.0, -0.7], - [-0.4, 0.8], - [0.6, -0.5], - [1.0, 0.9], - ], - dtype=torch.float64, - ) - rays = retinal_ray_directions( - cartesian, - image_height=raw_height, - image_width=raw_width, - focal_length_px=focal_length_px, - retinal_window_short_side_fraction=1.0, - retinal_window_reference_side="long", - image_rotation_deg=image_rotation_deg, - ) - mount_angles = image_fixation_to_pan_tilt_angles( - torch.tensor([[0.18, 0.81]], dtype=torch.float64), - image_height=policy_height, - image_width=policy_width, - focal_length_px=focal_length_px, - principal_point=(policy_width * 0.5, policy_height * 0.5), - ) - - actual = fixed_frustum_validity( - rays, - mount_angles, - image_height=raw_height, - image_width=raw_width, - focal_length_px=focal_length_px, - principal_point=(raw_width * 0.5, raw_height * 0.5), - angle_model="pan_tilt", - image_rotation_deg=image_rotation_deg, - ) - - tilt, pan = mount_angles[0].tolist() - camera_to_policy = R.from_euler("z", -image_rotation_deg, degrees=True) - policy_to_camera = camera_to_policy.inv() - policy_rays = camera_to_policy.apply(rays.numpy()) - mount_rays = np.column_stack((policy_rays[:, 0], -policy_rays[:, 2], policy_rays[:, 1])) - mount_motion = R.from_euler("z", pan) * R.from_euler("x", tilt) - moved_mount_rays = mount_motion.apply(mount_rays) - moved_policy_rays = np.column_stack((moved_mount_rays[:, 0], moved_mount_rays[:, 2], -moved_mount_rays[:, 1])) - moved_camera_rays = policy_to_camera.apply(moved_policy_rays) - forward = -moved_camera_rays[:, 2] - pixel_x = focal_length_px * moved_camera_rays[:, 0] / forward + raw_width * 0.5 - pixel_y = raw_height * 0.5 - focal_length_px * moved_camera_rays[:, 1] / forward - expected = (forward > 0.0) & (pixel_x >= 0.0) & (pixel_x < raw_width) & (pixel_y >= 0.0) & (pixel_y < raw_height) - - assert torch.equal(actual[0], torch.from_numpy(expected)) - - -@pytest.mark.parametrize( - ("reference_side", "expected_tangent"), - (("short", 0.6), ("long", 0.8)), -) -def test_retinal_ray_directions_select_reference_side( - reference_side: str, - expected_tangent: float, -) -> None: - directions = retinal_ray_directions( - torch.tensor([[1.0, 0.0]]), - image_height=120, - image_width=160, - focal_length_px=100.0, - retinal_window_short_side_fraction=1.0, - retinal_window_reference_side=reference_side, - ) - - tangent = directions[0, 0] / -directions[0, 2] - assert tangent.item() == pytest.approx(expected_tangent) - - -def test_retinal_ray_directions_reject_invalid_reference_side() -> None: - with pytest.raises(ValueError, match="retinal_window_reference_side"): - retinal_ray_directions( - torch.tensor([[0.0, 0.0]]), - image_height=120, - image_width=160, - focal_length_px=100.0, - retinal_window_short_side_fraction=1.0, - retinal_window_reference_side="diagonal", - ) - - -def test_fixed_fov_ray_and_mask_geometry_is_scale_invariant() -> None: - cartesian = torch.tensor([[0.0, 0.0], [-0.8, 0.1], [0.9, -0.2]]) - fixation = torch.tensor([[0.3, 0.85]]) - reference_directions = None - reference_validity = None - - for scale in (1, 4, 8): - height = 120 * scale - width = 160 * scale - focal_length_px = 100.0 * scale - directions = retinal_ray_directions( - cartesian, - image_height=height, - image_width=width, - focal_length_px=focal_length_px, - retinal_window_short_side_fraction=1.0, - ) - fixation_angles = image_fixation_to_camera_angles( - fixation, - image_height=height, - image_width=width, - focal_length_px=focal_length_px, - principal_point=(width * 0.5, height * 0.5), - ) - validity = fixed_frustum_validity( - directions, - fixation_angles, - image_height=height, - image_width=width, - focal_length_px=focal_length_px, - principal_point=(width * 0.5, height * 0.5), - ) - - if reference_directions is None: - reference_directions = directions - reference_validity = validity - else: - torch.testing.assert_close(directions, reference_directions) - assert torch.equal(validity, reference_validity) - - -def test_fixed_frustum_matches_half_open_image_boundaries() -> None: - directions = torch.tensor( - [[-0.6, 0.0, -0.8], [0.6, 0.0, -0.8], [0.0, 0.6, -0.8], [0.0, -0.6, -0.8], [0.0, 0.0, 1.0]], - dtype=torch.float64, - ) - valid = fixed_frustum_validity( - directions, - torch.zeros(1, 2, dtype=torch.float64), - image_height=150, - image_width=150, - focal_length_px=100.0, - principal_point=(75.0, 75.0), - ) - assert valid.tolist() == [[True, False, True, False, False]] - - -@pytest.mark.parametrize("principal_point", [(70.0, 45.0), (95.0, 75.0)]) -def test_fixation_optical_axis_projects_to_calibrated_image_location( - principal_point: tuple[float, float], -) -> None: - fixation = torch.tensor([[0.25, 0.7]], dtype=torch.float64) - angles = image_fixation_to_camera_angles( - fixation, - image_height=120, - image_width=160, - focal_length_px=100.0, - principal_point=principal_point, - ) - roll, pitch = angles[0].tolist() - # Independent rotations project the steered central ray into the dense image. - motion = R.from_euler("x", roll) * R.from_euler("y", pitch) - direction = motion.apply(np.array([0.0, 0.0, -1.0])) - pixel_x = 100.0 * direction[0] / -direction[2] + principal_point[0] - pixel_y = principal_point[1] - 100.0 * direction[1] / -direction[2] - assert pixel_x == pytest.approx(0.7 * 160) - assert pixel_y == pytest.approx(0.25 * 120) diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 1c37531a9afe..304bce99be2e 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -94,13 +94,12 @@ def render(camera, env_mask): camera._spawn_focal_length = 1.0 camera.cfg = SimpleNamespace( foveated_style="warped_cartesian_as_grid", - fixed_software_fov=False, + mask_to_sensor_fov=False, cmf_a_deg=0.591, pool_enabled=pooled, pool_mode="avg", pool_int_mode="avg", pool_sample_cortex=False, - projection="pinhole", field_geometry="planar", image_rotation_deg=0, data_types=["rgba", "rgb"], @@ -110,7 +109,7 @@ def render(camera, env_mask): rays = wp.to_torch(camera._foveated_rays) assert rays.shape == (1, ray_coords.resolution, ray_coords.resolution, 2, 3) - torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], camera._fixed_fov_ray_directions) + torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], camera._ray_directions) public_rgba = camera._data.output["rgba"] camera._update_buffers_impl(None) expected = camera.renderer_rgba.reshape(2, len(ray_coords), 1, 4).clone() diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 4a4de073eaba..9e2222d7140c 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -18,12 +18,11 @@ rotate_camera_rays, sampling_geometry, ) -from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.pooling import build_lowres_coords from isaaclab_fovi.sensors.virtual_gaze import CalibratedVirtualGaze -from isaaclab.utils.math import matrix_from_quat, quat_apply, quat_from_euler_xyz, quat_from_matrix +from isaaclab.utils.math import matrix_from_quat, quat_apply, quat_from_matrix @pytest.fixture @@ -114,8 +113,8 @@ def test_gaze_away_from_sensor_masks_all_rays() -> None: @pytest.mark.parametrize("device", ["cpu", "cuda"]) @pytest.mark.parametrize("batch_size", [48, 256]) @pytest.mark.parametrize("autocast", [False, True]) -@pytest.mark.parametrize("mode", ["planar", "spherical", "spherical_ids", "spherical_mask"]) -def test_newton_fixation_preserves_camera_rotation_with_tf32( +@pytest.mark.parametrize("mode", ["spherical", "spherical_ids", "spherical_mask"]) +def test_calibrated_gaze_preserves_camera_rotation_with_tf32( device: str, batch_size: int, autocast: bool, mode: str, tf32_enabled ) -> None: if device == "cuda" and not torch.cuda.is_available(): @@ -127,44 +126,24 @@ def test_newton_fixation_preserves_camera_rotation_with_tf32( angles = torch.tensor([[0.13, -0.21]], device=device).repeat(batch_size, 1) angles[1::2] = 0 expected = matrix_from_quat(source.double()) @ conversion - if mode == "planar": - camera = object.__new__(FoveatedNewtonCamera) - camera._data = SimpleNamespace(quat_w_world=SimpleNamespace(torch=source)) - camera._fixation = angles - camera._renderer = None - camera._view = None - camera._initialize_handle = None - camera._invalidate_initialize_handle = None - camera._prim_deletion_handle = None - camera._debug_vis_handle = None - expected = ( - expected - @ matrix_from_quat( - quat_from_euler_xyz(angles[:, 0].double(), angles[:, 1].double(), angles[:, 0].double() * 0) - ) - @ conversion.T - ) - with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast): - camera._apply_fixation_rotation() - else: - camera = GazeHarness() - camera._data.quat_w_world = source - camera._calibrated_basis = camera._calibrated_basis.to(device) - camera.set_calibrated_angles(angles) - basis = camera._calibrated_basis.double() - expected = expected @ basis @ camera._calibrated_rotation.double() @ basis.T @ conversion.T - selected = torch.arange(batch_size, device=device) % 2 == 0 - with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast): - if mode == "spherical_ids": - camera._apply_calibrated_pose(torch.nonzero(selected).flatten()) - elif mode == "spherical_mask": - camera._apply_calibrated_pose(env_mask=wp.from_torch(selected)) - else: - camera._apply_calibrated_pose() - if mode in ("spherical_ids", "spherical_mask"): - torch.testing.assert_close(source[~selected], original[~selected], atol=0, rtol=0) - source = source[selected] - expected = expected[selected] + camera = GazeHarness() + camera._data.quat_w_world = source + camera._calibrated_basis = camera._calibrated_basis.to(device) + camera.set_calibrated_angles(angles) + basis = camera._calibrated_basis.double() + expected = expected @ basis @ camera._calibrated_rotation.double() @ basis.T @ conversion.T + selected = torch.arange(batch_size, device=device) % 2 == 0 + with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast): + if mode == "spherical_ids": + camera._apply_calibrated_pose(torch.nonzero(selected).flatten()) + elif mode == "spherical_mask": + camera._apply_calibrated_pose(env_mask=wp.from_torch(selected)) + else: + camera._apply_calibrated_pose() + if mode in ("spherical_ids", "spherical_mask"): + torch.testing.assert_close(source[~selected], original[~selected], atol=0, rtol=0) + source = source[selected] + expected = expected[selected] assert source.dtype == torch.float32 assert torch.isfinite(source).all() torch.testing.assert_close(source.norm(dim=-1), torch.ones(len(source), device=device), atol=1e-6, rtol=0) From 51621c53a65d664cc7b8b423c6a02a565d1acbee Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:47:38 -0800 Subject: [PATCH 08/81] Document the foveated camera Add a package README covering installation, configuration, foveation strength, field geometry and gaze, and update the square-field guide for the current options. --- source/isaaclab_fovi/docs/README.md | 97 ++++++++++++++++++++ source/isaaclab_fovi/docs/square_foveated.md | 39 +++----- 2 files changed, 112 insertions(+), 24 deletions(-) create mode 100644 source/isaaclab_fovi/docs/README.md diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md new file mode 100644 index 000000000000..b1a97f74872a --- /dev/null +++ b/source/isaaclab_fovi/docs/README.md @@ -0,0 +1,97 @@ +# Isaac Lab Fovi + +Foveated camera sensors for Isaac Lab. A foveated camera samples the scene densely +at the point of fixation and sparsely in the periphery, instead of on a uniform +pixel grid. The sample layout comes from the [fovi](https://pypi.org/project/fovi/) +library. + +## Installation + +From the Isaac Lab repository root: + +```bash +uv sync --extra fovi +``` + +The `fovi` extra installs this package, the `fovi` library and OpenEXR, which the +RTX renderers use to write lens lookup textures. + +## Usage + +Add a `FoveatedCameraCfg` to a scene like any other camera. `FoveatedCamera` +picks its implementation from the renderer: it supports `newton_warp`, +`isaac_rtx` and `ovrtx`. + +```python +import isaaclab.sim as sim_utils +from isaaclab_fovi.sensors import FoveatedCameraCfg +from isaaclab_newton.renderers import NewtonWarpRendererCfg + +camera = FoveatedCameraCfg( + prim_path="{ENV_REGEX_NS}/Eye", + data_types=["rgb"], + renderer_cfg=NewtonWarpRendererCfg(), + spawn=sim_utils.PinholeCameraCfg(), + # The physical camera the retina looks through. + camera_calibration={ + "model": "pinhole", + "image_size": (480, 640), # (height, width) + "intrinsics": (550.0, 550.0, 319.5, 239.5), # fx, fy, cx, cy [px] + }, + foveated_res=64, +) +``` + +With the default grid style the sensor publishes an upright image of shape +`(num_envs, foveated_res, foveated_res, channels)` in `camera.data.output`. + +### Foveation strength + +`cmf_a_deg` is the cortical magnification constant in degrees. Smaller values +concentrate more samples at the fixation. The default, 0.591, is an estimate +from human data. A value much larger than the field of view gives nearly +uniform sampling, which is a matched non-foveated baseline with the same +resolution, field of view and gaze: + +```bash +env.scene.eye.cmf_a_deg=1000 +``` + +### Field geometry + +- `field_geometry="spherical"` (default) places samples by visual angle inside + the calibrated camera's field of view. It needs `camera_calibration`. +- `field_geometry="planar"` places samples on the image plane of the spawn + optics. It needs no calibration and has no gaze. + +### Gaze + +In spherical geometry the fixation can move while the camera prim stays in +place: + +```python +# Normalized (row, column) position in the calibrated image, shape (num_envs, 2). +camera.set_calibrated_fixation(fixation) +# Or mount angles (tilt, pan) in radians, shape (num_envs, 2). +camera.set_calibrated_angles(angles) +``` + +Set `mask_to_sensor_fov=True` to zero the samples that fall outside the +calibrated camera's image at the current gaze. + +### Advanced options + +- Sample-set styles such as `foveated_style="isotropic"` publish + `(num_envs, num_samples, 1, channels)`. +- `fov_type` and `radius_norm` select circular or square coverage. See + [square-foveated rendering](square_foveated.md). +- `pool_enabled=True` renders a denser grid and pools it to the output grid. + +## Example + +```bash +uv run python source/isaaclab_fovi/examples/render_foveated.py --backend newton --steps 8 +``` + +Add `--backend rtx` for the RTX renderer, `--planar` for planar sampling, or +`--cmf-a-deg 1000` for the non-foveated baseline. diff --git a/source/isaaclab_fovi/docs/square_foveated.md b/source/isaaclab_fovi/docs/square_foveated.md index e79e272ee969..a3d9bb9f0977 100644 --- a/source/isaaclab_fovi/docs/square_foveated.md +++ b/source/isaaclab_fovi/docs/square_foveated.md @@ -1,6 +1,8 @@ # Square-foveated rendering -Both RTX and Newton foveated cameras accept this configuration: +By default the foveated grid covers a circular field: cells outside the circle +are masked. A square field uses every cell. Both the RTX and Newton foveated +cameras accept this configuration: ```python FoveatedCameraCfg( @@ -12,29 +14,18 @@ FoveatedCameraCfg( ) ``` -Fovi owns the concentric-square mapping and its analytic inverse. Direction -textures, exit textures, virtual gaze, and software retinalization use that -geometry. The public image is upright `(batch, height, width, channels)`; -RGB, depth, and segmentation retain their existing dtypes and buffer lifetimes. -There are no cells masked by the sensor footprint. Camera visibility and -out-of-frame software sampling can still invalidate pixels. +`fovi` owns the concentric-square mapping and its analytic inverse. The lens +lookup textures and the calibrated gaze use that geometry. The published image +is upright, `(num_envs, height, width, channels)`, and RGB, depth and +segmentation keep their usual dtypes. -The mode works with the existing planar and spherical chart conventions and -pinhole/equidistant ray projections. It retains a two-dimensional native -topology; the square footprint refers to the visual chart used by the projection. -The diagonal derivative seams remain relevant when assessing temporal filtering. +No cell is masked by the sensor footprint. With `mask_to_sensor_fov=True`, +samples outside the calibrated camera's image are still zeroed. -Configure policy image preprocessing with the same field geometry, radius norm, -and sampling resolution as the camera. Checkpoints must use the sampling -configuration they were trained with. +The mode works in both field geometries. The grid keeps its two-dimensional +topology; "square" refers to the region of the visual field the grid covers. +The mapping is not smooth across the diagonals of the square, which matters +when a temporal filter such as DLSS is applied to the rendered grid. -A bounded renderer example is: - -```bash -uv run --no-sync python source/isaaclab_fovi/examples/render_foveated.py \ - --backend rtx --style warped_cartesian_as_grid --radius-norm inf --fov-type square \ - --resolution 64 --steps 8 --visualizer none --device cuda:0 --output /tmp/square-foveated.pt -``` - -Install the pinned Fovi dependency through the repository's `fovi` extra. -The implementation uses Fovi's upright-grid and analytic native-mapping APIs. +A policy that consumes the image has to be configured with the same field +geometry, `radius_norm` and resolution as the camera. From 22e713d7bee8a0741b0adf4b19d55893d39764df Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 13:48:36 -0800 Subject: [PATCH 09/81] Silence the sample-count search during camera setup --- source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index 9149f780a274..50b994b9d9e6 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -57,7 +57,7 @@ def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCo cfg.foveated_style, 1, device, - quiet=False, + quiet=True, fov_type=cfg.fov_type, radius_norm=cfg.radius_norm, field_geometry=cfg.field_geometry, From 13f6d5d90480fbaa3fb5d0f6b4e6ebcfc526131f Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 14:13:38 -0800 Subject: [PATCH 10/81] Lock the fovi extra --- uv.lock | 176 ++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 160 insertions(+), 16 deletions(-) diff --git a/uv.lock b/uv.lock index 15161ac8e229..1c15ce2e3c66 100644 --- a/uv.lock +++ b/uv.lock @@ -421,6 +421,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" }, ] +[[package]] +name = "beartype" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/79/34/c0cfdaee9c796c8381439fed0fcab62810753b8b0adb1ec88fa7f41eaa5d/beartype-0.23.1.tar.gz", hash = "sha256:8b805f246b32931c74f2b321ea0939fe5bb2ff43c12a3eff19cc4c854b832e1d", size = 1993714, upload-time = "2026-10-11T05:36:55.251Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1c/cb/2f6aa982e2860c1156830db3da7f823b71784ed7d533ca289ea9b6c6347a/beartype-0.23.1-py3-none-any.whl", hash = "sha256:4461b4dc57e3fdd6c8a8464b22cf118002eea107c33e9fef651c69068ab3cce3", size = 1582101, upload-time = "2026-10-11T05:36:52.431Z" }, +] + [[package]] name = "beautifulsoup4" version = "4.15.0" @@ -891,6 +900,7 @@ dependencies = [ wheels = [ { url = "https://files.pythonhosted.org/packages/d3/8c/5fe3f6719c2d4560c79c62ef6d9b7d6c34d145879ddc0c1a41f8153ad0a6/cupy_cuda12x-14.2.0-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:b74340aa7271f0f081f77e2e5107bac75af19b86df29213db7ada90e14428efe", size = 147490427, upload-time = "2026-08-20T02:40:00.196Z" }, { url = "https://files.pythonhosted.org/packages/7c/5b/65124de2dbaf2e85109f611a41947e39acd6dd938751c04b4c4d7bf6fc82/cupy_cuda12x-14.2.0-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:f82141761f2c81905d49387464ae29438887956d99063381c93a1d5d1b7d32e8", size = 136111459, upload-time = "2026-08-20T02:40:04.909Z" }, + { url = "https://files.pythonhosted.org/packages/e9/18/ddea819204701024bef7fa748730702245d803847c841b737723b94fd091/cupy_cuda12x-14.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:c9571d3b5f2e65758137e210f7fb3c3b34767f0af6b6ca04035a244b6141ee12", size = 98780018, upload-time = "2026-08-20T02:40:09.465Z" }, ] [[package]] @@ -1171,6 +1181,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5f/c7/cb03251d9dfb177246a9809a76f189d21df32dbd4a845951881d11323b7f/fastapi-0.139.2-py3-none-any.whl", hash = "sha256:b9ad015a835173d59865e2f5d8296fbc2b317bf56a2ba1a5bfbdd03de2fd4b1c", size = 130234, upload-time = "2026-07-16T15:06:19.557Z" }, ] +[[package]] +name = "fastcore" +version = "2.2.44" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ff/3e/4922745d9221efe50bbc3c4e9a8e23879305ac512b89d248e9d7cb2dd86c/fastcore-2.2.44.tar.gz", hash = "sha256:65503dc894e0c75e37fd22ccfdebd2a708f911cb20bcb22983f1516e23b75850", size = 144872, upload-time = "2026-11-16T05:10:47.345Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ac/3f/2f21fb6b00d41fdcb173d10cc9c651e6d70dc3815ae34dc468e870f2fa38/fastcore-2.2.44-py3-none-any.whl", hash = "sha256:978eda3ecbdffb7b4b83b4cfaef54391b5497343138d22d6f11cf3711015222c", size = 151666, upload-time = "2026-11-16T05:10:45.813Z" }, +] + [[package]] name = "fastjsonschema" version = "2.22.1" @@ -1286,6 +1305,32 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c7/4e/ce75a57ff3aebf6fc1f4e9d508b8e5810618a33d900ad6c19eb30b290b97/fonttools-4.61.1-py3-none-any.whl", hash = "sha256:17d2bf5d541add43822bcf0c43d7d847b160c9bb01d15d5007d84e2217aaa371", size = 1148996, upload-time = "2025-12-12T17:31:21.03Z" }, ] +[[package]] +name = "fovi" +version = "2.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cupy-cuda12x" }, + { name = "einops" }, + { name = "fastcore" }, + { name = "ipython" }, + { name = "numpy" }, + { name = "pillow" }, + { name = "plum-dispatch" }, + { name = "pygeodesic" }, + { name = "scikit-image" }, + { name = "scipy" }, + { name = "torch" }, + { name = "torchvision" }, + { name = "tqdm" }, + { name = "trimesh" }, + { name = "warp-lang" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9f/bc/14afdf090c412a543a939051f83a26fa50e46f407100d20707b5d34f8316/fovi-2.6.0.tar.gz", hash = "sha256:9bda8baedbd28e29c679e545dd1813e911667d3dd2c6fb1802c4a92c564d3625", size = 67577289, upload-time = "2026-11-14T18:14:09.39Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/6c/45b6d1948a23ee352ec63612e0b94a76e7dfa5427b6ff8ddc72b8864b297/fovi-2.6.0-py3-none-any.whl", hash = "sha256:d39b88f4654832b875e4197906e23043edb3dbedbb4a07798e59fd852ce0c42e", size = 312591, upload-time = "2026-11-14T18:14:07.165Z" }, +] + [[package]] name = "frozenlist" version = "1.5.0" @@ -1795,16 +1840,16 @@ source = { editable = "source/isaaclab_assets" } dependencies = [ { name = "isaaclab" }, { name = "isaaclab-contrib" }, - { name = "isaaclab-newton" }, { name = "isaaclab-isaacsim" }, + { name = "isaaclab-newton" }, ] [package.metadata] requires-dist = [ { name = "isaaclab", editable = "source/isaaclab" }, { name = "isaaclab-contrib", editable = "source/isaaclab_contrib" }, - { name = "isaaclab-newton", editable = "source/isaaclab_newton" }, { name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" }, + { name = "isaaclab-newton", editable = "source/isaaclab_newton" }, ] [[package]] @@ -1840,9 +1885,9 @@ dependencies = [ { name = "isaaclab-assets" }, { name = "isaaclab-contrib" }, { name = "isaaclab-experimental" }, + { name = "isaaclab-isaacsim" }, { name = "isaaclab-newton" }, { name = "isaaclab-ov" }, - { name = "isaaclab-isaacsim" }, { name = "isaaclab-ppisp" }, { name = "isaaclab-rl" }, { name = "isaaclab-tasks" }, @@ -1926,6 +1971,11 @@ dev = [ { name = "sphinxcontrib-bibtex" }, { name = "sphinxemoji" }, ] +fovi = [ + { name = "fovi" }, + { name = "isaaclab-fovi" }, + { name = "openexr" }, +] importers = [ { name = "isaacsim-asset-isolated" }, { name = "tinyobjloader" }, @@ -2058,6 +2108,7 @@ requires-dist = [ { name = "fast-simplification", specifier = ">=0.1.11" }, { name = "filelock" }, { name = "flaky", marker = "extra == 'test'" }, + { name = "fovi", marker = "extra == 'fovi'", specifier = ">=2.6" }, { name = "gitpython", specifier = ">=3.1.60" }, { name = "gym", marker = "extra == 'rl-games'" }, { name = "gymnasium", specifier = ">=1.2.0" }, @@ -2075,11 +2126,12 @@ requires-dist = [ { name = "isaaclab-dev", extras = ["sb3", "skrl", "rl-games", "rsl-rl", "viser", "rerun", "ov"], marker = "extra == 'all'" }, { name = "isaaclab-dev", extras = ["test"], marker = "extra == 'dev'" }, { name = "isaaclab-experimental", editable = "source/isaaclab_experimental" }, + { name = "isaaclab-fovi", marker = "extra == 'fovi'", editable = "source/isaaclab_fovi" }, + { name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" }, { name = "isaaclab-mimic", marker = "extra == 'mimic'", editable = "source/isaaclab_mimic" }, { name = "isaaclab-mimic", marker = "extra == 'teleop'", editable = "source/isaaclab_mimic" }, { name = "isaaclab-newton", editable = "source/isaaclab_newton" }, { name = "isaaclab-ov", editable = "source/isaaclab_ov" }, - { name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" }, { name = "isaaclab-ppisp", editable = "source/isaaclab_ppisp" }, { name = "isaaclab-rl", editable = "source/isaaclab_rl" }, { name = "isaaclab-tasks", editable = "source/isaaclab_tasks" }, @@ -2106,6 +2158,7 @@ requires-dist = [ { name = "numpydantic", marker = "extra == 'rlinf'", specifier = ">=1.7.0" }, { name = "onnx", specifier = ">=1.18.0" }, { name = "open3d", marker = "(python_full_version < '3.13' and platform_machine != 'aarch64') or (python_full_version < '3.13' and sys_platform != 'linux')", specifier = ">=0.19.0" }, + { name = "openexr", marker = "extra == 'fovi'", specifier = ">=3" }, { name = "ovphysx", marker = "extra == 'ov'", specifier = "==0.8.0.43443703471", index = "https://pypi.org/simple" }, { name = "ovphysx", marker = "extra == 'ovphysx'", specifier = "==0.8.0.43443703471", index = "https://pypi.org/simple" }, { name = "ovrtx", marker = "extra == 'ov'", specifier = "==0.7.0.1794596436", index = "https://pypi.org/simple" }, @@ -2178,7 +2231,7 @@ requires-dist = [ { name = "wandb", marker = "extra == 'wandb'", specifier = ">=0.13.11" }, { name = "warp-lang", specifier = "==1.17.0" }, ] -provides-extras = ["tetrahedralization", "video", "optix", "importers", "test", "dev", "sb3", "skrl", "skrl-jax", "rl-games", "wandb", "rsl-rl", "torchrl", "viser", "rerun", "isaacsim", "ov", "ovphysx", "ovrtx", "mimic", "teleop", "ovxr", "rlinf", "leapp", "all"] +provides-extras = ["tetrahedralization", "video", "optix", "importers", "test", "dev", "sb3", "skrl", "skrl-jax", "rl-games", "wandb", "rsl-rl", "torchrl", "viser", "rerun", "isaacsim", "ov", "ovphysx", "ovrtx", "mimic", "teleop", "ovxr", "rlinf", "leapp", "fovi", "all"] [[package]] name = "isaaclab-experimental" @@ -2195,6 +2248,28 @@ requires-dist = [ { name = "isaaclab-newton", editable = "source/isaaclab_newton" }, ] +[[package]] +name = "isaaclab-fovi" +version = "0.1.0" +source = { editable = "source/isaaclab_fovi" } +dependencies = [ + { name = "isaaclab" }, +] + +[package.metadata] +requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }] + +[[package]] +name = "isaaclab-isaacsim" +version = "13.2.0" +source = { editable = "source/isaaclab_isaacsim" } +dependencies = [ + { name = "isaaclab" }, +] + +[package.metadata] +requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }] + [[package]] name = "isaaclab-mimic" version = "2.1.7" @@ -2238,17 +2313,6 @@ requires-dist = [ { name = "ovstage", specifier = "==0.4.0.1794520352" }, ] -[[package]] -name = "isaaclab-isaacsim" -version = "13.2.0" -source = { editable = "source/isaaclab_isaacsim" } -dependencies = [ - { name = "isaaclab" }, -] - -[package.metadata] -requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }] - [[package]] name = "isaaclab-ppisp" version = "0.3.2" @@ -3935,6 +3999,22 @@ wheels = [ { url = "https://pypi.nvidia.com/opencv-python-headless-noffmpeg/opencv_python_headless_noffmpeg-4.14.0.94rc3-cp312-cp312-win_amd64.whl", hash = "sha256:a158d4182618fd1d2029647b65435757d6a01468c3ea6618f6caceaa139de4c7" }, ] +[[package]] +name = "openexr" +version = "3.5.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5f/c0/422dd868e5f94f7885bd9c12f2dc6fabbeb4a8cd0b002bc097024dae861d/openexr-3.5.4.tar.gz", hash = "sha256:8b5b06f08b05d512fe52fa18c5c2f27c2141938149da23d056094bc392f15db8", size = 26300935, upload-time = "2026-11-12T16:45:00.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/b9/c9e228497d81cb810c277116ab4cbeb3d3d1826b1b21fcc2f8aafa771ec6/openexr-3.5.4-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:116adcc66a9601048d0ffa7387990bb9d510d1dd0e8cb0ab999b825c1e717277", size = 1593447, upload-time = "2026-11-12T16:44:02.944Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3e/4b08275770fffcb57202762e2f023bfac39754290ba4727198b02d76bf74/openexr-3.5.4-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6f9644dd8b96eb314498c9849684f57adf67bde72f8b0193929bf29adff03b70", size = 1786567, upload-time = "2026-11-12T16:44:05.014Z" }, + { url = "https://files.pythonhosted.org/packages/17/b3/4a25166ed8bc29aee9d01f2d9f007ef15f9d3ea4075b19667879c149e30b/openexr-3.5.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b1c2658516cc199fb31baf0565e422dfa6df8077ba2336c3acc170c45e251a08", size = 2607932, upload-time = "2026-11-12T16:44:06.641Z" }, + { url = "https://files.pythonhosted.org/packages/76/37/a0e9a6a8a1cf7ec7efcb2cb7fbdaf55cd2a4349a26343a75fb7ac83e3e54/openexr-3.5.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a586a32ebb01fd87a54286ec9f29f5583a5176c019ebbbe6fd832a7188cefcd1", size = 2825749, upload-time = "2026-11-12T16:44:08.373Z" }, + { url = "https://files.pythonhosted.org/packages/68/15/7ff3e6a17444d70669085e21487e546fd6fe298b2eb653eccbd4e0c3b6a1/openexr-3.5.4-cp312-cp312-win_amd64.whl", hash = "sha256:d55fe6b60e923917bc5104808df2d515a82b0fb053b0e038788626f0fd2b780f", size = 1186933, upload-time = "2026-11-12T16:44:10.017Z" }, +] + [[package]] name = "opentelemetry-api" version = "1.44.0" @@ -4300,6 +4380,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] +[[package]] +name = "plum-dispatch" +version = "2.10.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "beartype" }, + { name = "rich" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/dc/75/807b02f339906867de07baaecd3519fe8704df013a27ae0a57250ed461d3/plum_dispatch-2.10.1.tar.gz", hash = "sha256:93aa1ec5c4683c0777b9d7d1ccc0b31e0e82f38399116345b4ed8d0fb67cc66e", size = 250842, upload-time = "2026-09-07T17:38:44.9Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/c3/d8793642ce7d29ea15cc39c10185ef126a27fcb8ea230154978221deb4b2/plum_dispatch-2.10.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5b6a2474f53b23cd07254c2ad286fc8371a3c4ed17dee72794eac9c3a6873db", size = 334557, upload-time = "2026-09-07T17:38:34.857Z" }, + { url = "https://files.pythonhosted.org/packages/41/c7/3544b2bf05aa9e1a1b45981d21da5e5d5c135fcc2da0ee1040f73512662f/plum_dispatch-2.10.1-cp312-cp312-win_amd64.whl", hash = "sha256:ae2f76ce97bcbf1d7038e7c352180cbb35c90c23ea0848e2924f35133fb0f223", size = 245830, upload-time = "2026-09-07T17:38:36.228Z" }, + { url = "https://files.pythonhosted.org/packages/55/9f/0adfb5a90d65233b764cb1b07244b72ded1db7cfc66955418544d0da2e38/plum_dispatch-2.10.1-py3-none-any.whl", hash = "sha256:dac63fd5ada8ae8045aefed127dacda0ba02db2635876b12f4e1dfaf6db73f39", size = 49430, upload-time = "2026-09-07T17:38:43.589Z" }, +] + [[package]] name = "pooch" version = "1.9.0" @@ -4622,6 +4718,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/32/a7125fb28c4261a627f999d5fb4afff25b523800faed2c30979949d6facd/pydot-4.0.1-py3-none-any.whl", hash = "sha256:869c0efadd2708c0be1f916eb669f3d664ca684bc57ffb7ecc08e70d5e93fee6", size = 37087, upload-time = "2025-06-17T20:09:55.25Z" }, ] +[[package]] +name = "pygeodesic" +version = "0.1.11" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/33/174106049bdea633e537f14fc39ebc68f2f97994591911b4e64e4870803c/pygeodesic-0.1.11.tar.gz", hash = "sha256:a9b54eb20d57f5499d8b2a4a67ece675a44c6fc8d00b11e8c14c8c99edeee5ed", size = 36275, upload-time = "2024-11-26T20:54:23.088Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/3d/972e2207d5845b6129f553376010b0bddecc2b1b74799e186d97e0f326d6/pygeodesic-0.1.11-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:495101cd634df7afe108a63419a864c77098c490608934c642b9d6eabc946ec1", size = 1016926, upload-time = "2024-11-26T20:54:10.904Z" }, + { url = "https://files.pythonhosted.org/packages/e6/0b/03af381ad00eaf56dde8156d48c0c4b7c5b928dd128221619d8b3cfea901/pygeodesic-0.1.11-cp312-cp312-win_amd64.whl", hash = "sha256:585e6fd35babbda2fa9b87f23d05e0ec26e1e416e069997ed137ac04b94f05b9", size = 1335932, upload-time = "2024-11-26T20:54:12.072Z" }, +] + [[package]] name = "pyglet" version = "2.1.15" @@ -5217,6 +5326,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, ] +[[package]] +name = "scikit-image" +version = "0.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "imageio" }, + { name = "lazy-loader" }, + { name = "networkx" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "scipy" }, + { name = "tifffile" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/b4/2528bb43c67d48053a7a649a9666432dc307d66ba02e3a6d5c40f46655df/scikit_image-0.26.0.tar.gz", hash = "sha256:f5f970ab04efad85c24714321fcc91613fcb64ef2a892a13167df2f3e59199fa", size = 22729739, upload-time = "2025-12-20T17:12:21.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/2b/c70120a6880579fb42b91567ad79feb4772f7be72e8d52fec403a3dde0c6/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4c717490cec9e276afb0438dd165b7c3072d6c416709cc0f9f5a4c1070d23a44", size = 13084214, upload-time = "2025-12-20T17:10:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/f4/a2/70401a107d6d7466d64b466927e6b96fcefa99d57494b972608e2f8be50f/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7df650e79031634ac90b11e64a9eedaf5a5e06fcd09bcd03a34be01745744466", size = 13561683, upload-time = "2025-12-20T17:10:59.49Z" }, + { url = "https://files.pythonhosted.org/packages/13/a5/48bdfd92794c5002d664e0910a349d0a1504671ef5ad358150f21643c79a/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cefd85033e66d4ea35b525bb0937d7f42d4cdcfed2d1888e1570d5ce450d3932", size = 14112147, upload-time = "2025-12-20T17:11:02.083Z" }, + { url = "https://files.pythonhosted.org/packages/ee/b5/ac71694da92f5def5953ca99f18a10fe98eac2dd0a34079389b70b4d0394/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3f5bf622d7c0435884e1e141ebbe4b2804e16b2dd23ae4c6183e2ea99233be70", size = 14661625, upload-time = "2025-12-20T17:11:04.528Z" }, + { url = "https://files.pythonhosted.org/packages/23/4d/a3cc1e96f080e253dad2251bfae7587cf2b7912bcd76fd43fd366ff35a87/scikit_image-0.26.0-cp312-cp312-win_amd64.whl", hash = "sha256:abed017474593cd3056ae0fe948d07d0747b27a085e92df5474f4955dd65aec0", size = 11911059, upload-time = "2025-12-20T17:11:06.61Z" }, +] + [[package]] name = "scikit-learn" version = "1.9.0" @@ -5794,6 +5926,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl", hash = "sha256:43a0b8fd5a2928500110039e43a5eed8480b918967083ea48dc3ab9f13c4a7fb", size = 18638, upload-time = "2025-03-13T13:49:21.846Z" }, ] +[[package]] +name = "tifffile" +version = "2026.11.16" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/e1/f09384869bcf78bae3a794a86d8a90753fb2a6f4646c07ec941ff629cd33/tifffile-2026.11.16.tar.gz", hash = "sha256:d9c246d464f1c3ca9ab62c5225b3ff45578f33629029dbbd9f62f4e901702726", size = 462802, upload-time = "2026-11-17T03:35:19.648Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cf/3a/483491be6f7eb070d1c22b1182bbbc0243e85bf5903fafe3f80b6aeb3dba/tifffile-2026.11.16-py3-none-any.whl", hash = "sha256:d2103c2537f185868f0a880eceba590b316aa1981bd76d91028e5f2eb0e1a6e6", size = 279737, upload-time = "2026-11-17T03:35:18.375Z" }, +] + [[package]] name = "timm" version = "1.0.28" From 41883046d28798d129507c3c74eef371f124bb73 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 14:13:54 -0800 Subject: [PATCH 11/81] Publish foveated camera outputs as ProxyArray Core Camera publishes ProxyArray values in camera.data.output. The foveated cameras published plain tensors for their grid and pooled buffers, so camera.data.output[name].torch failed. --- .../sensors/foveated_newton_camera.py | 20 +++++++++---------- .../sensors/foveated_rtx_camera.py | 19 +++++------------- .../isaaclab_fovi/sensors/native_grid.py | 11 ++++++++++ .../isaaclab_fovi/test/test_newton_buffers.py | 6 ++++-- 4 files changed, 30 insertions(+), 26 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 91d0c22a3903..45a1b89c93f9 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -35,6 +35,7 @@ grid_sample_indices, mask_grid_samples, native_grid_directions, + proxy_outputs, ) from .pooling import ( build_highres_coords, @@ -229,12 +230,15 @@ def _initialize_impl(self): self._data.output.update(self._flat_render_output) self._allocate_pooled_buffers() + source = self._pooled_output if self._pooler is not None else self._flat_render_output if self._native_grid: - source = self._pooled_output if self._pooler is not None else self._flat_render_output self._grid_output = allocate_grid_outputs(source, self._sampling_coords) self._grid_indices = grid_sample_indices(self._sampling_coords) - self._data.output.clear() - self._data.output.update(self._grid_output) + source = self._grid_output + # The buffers the camera publishes: stable for the camera's lifetime and refilled each frame. + self._public_output = proxy_outputs(source) + self._data.output.clear() + self._data.output.update(self._public_output) # 6. Inject foveated rays into render_data immediately. self._render_data.camera_rays = self._foveated_rays @@ -348,7 +352,7 @@ def _update_buffers_impl(self, env_mask: wp.array): if self._native_grid: copy_grid_outputs(output, self._grid_output, self._grid_indices) self._data.output.clear() - self._data.output.update(self._grid_output if self._native_grid else output) + self._data.output.update(self._public_output) return # Ensure the renderer writes into the highres buffers, not the pooled ones. @@ -371,16 +375,12 @@ def _update_buffers_impl(self, env_mask: wp.array): pooler = self._pooler_int if use_int_pool else self._pooler pooled = pool_hwc_buffer(pooler, hi.torch.float()) lo.copy_(pooled.to(lo.dtype)) - if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: - self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] # Expose pooled tensors as the public sensor output. - self._data.output.clear() if self._native_grid: copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) - self._data.output.update(self._grid_output) - else: - self._data.output.update(self._pooled_output) + self._data.output.clear() + self._data.output.update(self._public_output) def _apply_sensor_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: """Zero the samples that fall outside the calibrated camera at the current gaze.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 8aee189b3337..9de46c05329e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -37,6 +37,7 @@ grid_sample_indices, mask_grid_samples, native_grid_directions, + proxy_outputs, ) from .pooling import ( build_highres_coords, @@ -312,25 +313,15 @@ def _initialize_impl(self) -> None: # pooled output buffers. self._texture_output = self._data.output self._allocate_foveated_buffers() - # Expose foveated (or pooled) buffers as the public output. - # IsaacLab 3.0 made ``CameraData.output`` a read-only property; set - # the private ``_output`` backing field directly. Downstream - # readers (``CameraNode._read_rgb_raw`` etc.) just dict-index - # ``camera.data.output[name]`` and pass the value through - # ``_camera_output_to_torch``, which handles plain torch tensors - # natively — the renderer still writes to the original - # ProxyArray-backed buffers via the ``set_outputs`` binding done - # by the parent ``_create_buffers``. + # Publish the foveated (or pooled) buffers. ``CameraData.output`` is read-only, so the + # backing field is replaced; the renderer keeps writing to the texture buffers it was + # bound to by the parent ``_create_buffers``. new_output = self._pooled_output if self._pooled_output is not None else self._foveated_output if self._native_grid: self._grid_output = allocate_grid_outputs(new_output, self._sampling_coords) self._grid_indices = grid_sample_indices(self._sampling_coords) new_output = self._grid_output - try: - self._data._output = new_output - except AttributeError: - # Older IsaacLab where ``output`` was a writable attribute. - self._data.output = new_output + self._data._output = proxy_outputs(new_output) def _allocate_foveated_buffers(self): """Allocate ``(B, N_hi, 1, C)`` (and optionally ``(B, N_lo, 1, C)``) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py index a9aac12b96c4..6f7cb6a0c45e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py @@ -12,8 +12,11 @@ from typing import Protocol import torch +import warp as wp from fovi.sensing.coords import RADIUS_NORMS, WARPED_CARTESIAN_STYLES, SamplingCoords +from isaaclab.utils.warp import ProxyArray + GRID_STYLE = "warped_cartesian_as_grid" @@ -39,6 +42,14 @@ def buffer_tensor(value: torch.Tensor | TorchBuffer) -> torch.Tensor: return value if isinstance(value, torch.Tensor) else value.torch +def proxy_outputs(outputs: Mapping[str, torch.Tensor | ProxyArray]) -> dict[str, ProxyArray]: + """Wrap output buffers as zero-copy :class:`ProxyArray` values, as :class:`CameraData` publishes them.""" + return { + name: ProxyArray(wp.from_torch(value)) if isinstance(value, torch.Tensor) else value + for name, value in outputs.items() + } + + def _angular_padding_boundary(coords: SamplingCoords, camera_fov_rad: float | None = None) -> tuple[float, float]: if coords.fov_type == "circular": radius = 1.0 diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 304bce99be2e..0e4696de5d00 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -117,9 +117,11 @@ def render(camera, env_mask): if pooled: expected = newton_camera.pool_hwc_buffer(pooler, expected.float()).to(torch.uint8) expected = coords.as_grid(expected.squeeze(2), sample_dim=1) - torch.testing.assert_close(camera._data.output["rgba"], expected, rtol=0, atol=0) + torch.testing.assert_close(camera._data.output["rgba"].torch, expected, rtol=0, atol=0) + # The published buffers are stable across frames, and rgb shares rgba's memory. assert camera._data.output["rgba"] is public_rgba - assert camera._data.output["rgb"].untyped_storage().data_ptr() == public_rgba.untyped_storage().data_ptr() + torch.testing.assert_close(camera._data.output["rgb"].torch, expected[..., :3], rtol=0, atol=0) + assert camera._data.output["rgb"].warp.ptr == public_rgba.warp.ptr @pytest.mark.parametrize("render_order", ["tiled", "pixel_priority", "view_priority"]) From 2919ee181eedd1e9529a099a62d7ddb1784cb21d Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 14:13:54 -0800 Subject: [PATCH 12/81] Add render tests for the foveated camera Render ground distance on the Newton Warp and Isaac RTX renderers and compare the retina's centre with the analytic pinhole ray through the fixated pixel. --- .../test/test_backend_dispatch.py | 6 +- .../test/test_foveated_camera_render.py | 186 ++++++++++++++++++ 2 files changed, 191 insertions(+), 1 deletion(-) create mode 100644 source/isaaclab_fovi/test/test_foveated_camera_render.py diff --git a/source/isaaclab_fovi/test/test_backend_dispatch.py b/source/isaaclab_fovi/test/test_backend_dispatch.py index a72ef8a19d51..e91fa39b2b02 100644 --- a/source/isaaclab_fovi/test/test_backend_dispatch.py +++ b/source/isaaclab_fovi/test/test_backend_dispatch.py @@ -10,6 +10,8 @@ import pytest from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg, FoveatedNewtonCamera, FoveatedRTXCamera +from isaaclab.sensors.camera import Camera + @dataclass class RendererSelection: @@ -36,7 +38,9 @@ def test_unknown_renderer_fails_explicitly() -> None: ("renderer_type", "implementation"), [("newton_warp", FoveatedNewtonCamera), ("isaac_rtx", FoveatedRTXCamera), ("ovrtx", FoveatedRTXCamera)], ) -def test_renderer_selects_implementation(renderer_type: str, implementation: type) -> None: +def test_renderer_selects_implementation(renderer_type: str, implementation: type, monkeypatch) -> None: + # The camera is allocated but never initialized, so it has nothing to release. + monkeypatch.setattr(Camera, "__del__", lambda self: None) camera = FoveatedCamera.__new__(FoveatedCamera, CameraSelection(RendererSelection(renderer_type))) assert type(camera) is implementation assert isinstance(camera, FoveatedCamera) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py new file mode 100644 index 000000000000..1745ecff0150 --- /dev/null +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -0,0 +1,186 @@ +# 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 + +"""Render tests for the foveated camera on the Newton Warp and Isaac RTX renderers. + +A camera looks down at the ground plane and renders distance. The ground distance along any camera +ray is known in closed form, so the images check the sampling geometry without reference images. +""" + +from isaaclab.test.utils import launch_test_simulation + +launch_test_simulation(enable_cameras=True) + +import numpy as np +import pytest +import torch +from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg, FoveatedNewtonCamera, FoveatedRTXCamera +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.renderers import NewtonWarpRendererCfg +from isaaclab_physx.physics import PhysxCfg +from isaaclab_physx.renderers import IsaacRtxRendererCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg, RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationCfg, build_simulation_context +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils.configclass import configclass +from isaaclab.utils.math import create_rotation_matrix_from_view, quat_from_matrix + +pytestmark = [pytest.mark.integration, pytest.mark.rendering, pytest.mark.isaacsim_ci] + +# Each backend pairs a physics engine with the renderer under test and the implementation it selects. +BACKENDS = { + "newton_warp": (NewtonCfg(solver_cfg=MJWarpSolverCfg()), NewtonWarpRendererCfg, FoveatedNewtonCamera), + "isaac_rtx": (PhysxCfg(), IsaacRtxRendererCfg, FoveatedRTXCamera), +} + +DEVICE = "cuda:0" +WARMUP_STEPS = 4 +RESOLUTION = 32 + +# The physical camera the retina looks through: a 640x480 pinhole. +WIDTH, HEIGHT = 640, 480 +FOCAL, CX, CY = 550.0, 319.5, 239.5 +CALIBRATION = {"model": "pinhole", "image_size": (HEIGHT, WIDTH), "intrinsics": (FOCAL, FOCAL, CX, CY)} + +# The camera looks down at the ground plane; its optical axis meets the ground at the target. +CAM_EYE = (0.0, 0.0, 2.5) +CAM_TARGET = (1.75, 0.0, 0.0) + + +@configclass +class _GroundSceneCfg(InteractiveSceneCfg): + """A ground plane, a foveated camera, and an off-screen body; Newton cannot build an empty model.""" + + ground = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + dome_light = AssetBaseCfg( + prim_path="/World/DomeLight", + spawn=sim_utils.DomeLightCfg(intensity=2000.0, color=(0.9, 0.9, 0.9)), + ) + anchor = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Anchor", + spawn=sim_utils.CuboidCfg( + size=(0.01, 0.01, 0.01), + rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), + mass_props=sim_utils.MassCfg(mass=0.001), + collision_props=sim_utils.UsdPhysicsCollisionCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, -100.0)), + ) + camera = FoveatedCameraCfg( + prim_path="{ENV_REGEX_NS}/Camera", + update_period=0.0, + data_types=["distance_to_camera"], + spawn=sim_utils.PinholeCameraCfg(clipping_range=(0.001, 20.0)), + camera_calibration=CALIBRATION, + foveated_res=RESOLUTION, + mask_to_sensor_fov=True, + ) + + +def _ground_distance_through_pixel(u: float, v: float) -> float: + """Distance [m] from the camera to the ground along the pinhole ray through calibrated pixel ``(u, v)``.""" + ray_camera = np.array(((u - CX) / FOCAL, -(v - CY) / FOCAL, -1.0)) + ray_camera /= np.linalg.norm(ray_camera) + eye = np.asarray(CAM_EYE) + forward = np.asarray(CAM_TARGET) - eye + z_axis = -forward / np.linalg.norm(forward) + x_axis = np.cross(np.array((0.0, 0.0, 1.0)), z_axis) + x_axis /= np.linalg.norm(x_axis) + y_axis = np.cross(z_axis, x_axis) + ray_world = np.column_stack((x_axis, y_axis, z_axis)) @ ray_camera + return float(-eye[2] / ray_world[2]) + + +def _render(backend: str, fixation: torch.Tensor, **camera_overrides) -> tuple[torch.Tensor, torch.Tensor]: + """Render ground distance for one environment per fixation row. + + Returns: + The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid + cell, shape (H, W, 2). + """ + physics_cfg, renderer_cfg, camera_class = BACKENDS[backend] + sim_cfg = SimulationCfg(physics=physics_cfg, device=DEVICE) + with build_simulation_context(device=DEVICE, sim_cfg=sim_cfg) as sim: + sim._app_control_on_stop_handle = None + rot = tuple( + quat_from_matrix( + create_rotation_matrix_from_view(torch.tensor([CAM_EYE]), torch.tensor([CAM_TARGET]), up_axis="Z") + )[0].tolist() + ) + scene_cfg = _GroundSceneCfg(num_envs=len(fixation), env_spacing=20.0) + scene_cfg.camera.renderer_cfg = renderer_cfg() + scene_cfg.camera.offset = FoveatedCameraCfg.OffsetCfg(pos=CAM_EYE, rot=rot, convention="opengl") + for name, value in camera_overrides.items(): + setattr(scene_cfg.camera, name, value) + scene = InteractiveScene(scene_cfg) + camera: FoveatedCamera = scene["camera"] + assert isinstance(camera, camera_class) + sim.reset() + camera.set_calibrated_fixation(fixation.to(sim.device)) + for _ in range(WARMUP_STEPS): + sim.step() + camera.update(sim.get_physics_dt(), force_recompute=True) + distance = camera.data.output["distance_to_camera"].torch[..., 0].detach().cpu().float().clone() + coords = camera.sampling_coords + field = coords.as_grid(coords.cartesian, sample_dim=0).detach().cpu().float().clone() + return distance, field + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_foveated_camera_follows_calibrated_gaze(backend): + """The retina's centre sees the ground along the pinhole ray through the fixated pixel. + + One environment fixates the image centre and one a point to the right. The reference is the + analytic ground distance of the calibrated pinhole ray through each fixated pixel. + """ + # Fixations are normalized (row, column) positions in the calibrated image. + fixation = torch.tensor([[0.5, 0.5], [0.5, 0.75]]) + distance, field = _render(backend, fixation) + + assert distance.shape == (2, RESOLUTION, RESOLUTION) + assert torch.isfinite(distance).all() + + # The grid cell closest to the centre of the visual field. + row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) + for env, (row_fraction, column_fraction) in enumerate(fixation.tolist()): + expected = _ground_distance_through_pixel(column_fraction * WIDTH - 0.5, row_fraction * HEIGHT - 0.5) + assert float(distance[env, row, column]) == pytest.approx(expected, rel=0.01) + + # The image is upright: the top looks farther along the ground than the bottom. + centred = distance[0] + seen = centred > 0 + top = centred[: RESOLUTION // 2][seen[: RESOLUTION // 2]].mean() + bottom = centred[RESOLUTION // 2 :][seen[RESOLUTION // 2 :]].mean() + assert top > bottom + 0.25 + # The camera has no roll, so the left and right halves see the same distances. + left = centred[:, : RESOLUTION // 2][seen[:, : RESOLUTION // 2]].mean() + right = centred[:, RESOLUTION // 2 :][seen[:, RESOLUTION // 2 :]].mean() + assert float(left) == pytest.approx(float(right), rel=0.01) + + # Looking right moves part of the retina past the edge of the calibrated camera, and those samples are zeroed. + assert (distance[1] == 0).sum() > (distance[0] == 0).sum() + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_foveated_camera_samples_densest_at_the_fixation(backend): + """Neighbouring samples are closer together at the fixation, and nearly even without foveation.""" + + def central_to_edge_spacing(field: torch.Tensor) -> float: + steps = field[RESOLUTION // 2, :, 0].diff() + return float(steps[len(steps) // 2] / steps[-1]) + + fixation = torch.tensor([[0.5, 0.5]]) + foveated_distance, foveated_field = _render(backend, fixation) + uniform_distance, uniform_field = _render(backend, fixation, cmf_a_deg=1000.0) + + assert central_to_edge_spacing(foveated_field) < 0.2 + assert central_to_edge_spacing(uniform_field) > 0.9 + # Both cover the same field of view, so they see the same range of ground distances. + for distance in (foveated_distance, uniform_distance): + assert torch.isfinite(distance).all() + assert float(foveated_distance.max()) == pytest.approx(float(uniform_distance.max()), rel=0.05) From 41bac53480fd7d7d9107cca9cdf026a5ded10c34 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 14:13:55 -0800 Subject: [PATCH 13/81] Run the isaaclab_fovi tests in CI Install the fovi extra in the CI image and add the package to the combined package test job. --- .github/workflows/build.yaml | 2 +- docker/Dockerfile.base | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 700903b0fcec..c96f199e2b1d 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -624,7 +624,7 @@ jobs: image-tag: ${{ needs.config.outputs.ci_image_tag }} isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }} isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }} - filter-pattern: "isaaclab_assets,isaaclab_contrib,isaaclab_teleop,isaaclab_mimic,isaaclab_experimental" + filter-pattern: "isaaclab_assets,isaaclab_contrib,isaaclab_teleop,isaaclab_mimic,isaaclab_experimental,isaaclab_fovi" warp-cache: restore ovrtx-shader-cache: restore test-jobs: "4" diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index 8d7b15aaee64..6722e33489a7 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -138,7 +138,7 @@ COPY --parents source/*/pyproject.toml ${ISAACLAB_PATH}/ # The image's package set. Kit ships in the base image, so the teleop stack comes without the # ``isaacsim`` wheel; ``teleop`` itself is left exactly as tuned. -ARG IMAGE_EXTRAS="--extra sb3 --extra skrl --extra rl-games --extra rsl-rl --extra viser --extra rerun --extra mimic --extra teleop --extra test --extra tetrahedralization --extra ov" +ARG IMAGE_EXTRAS="--extra sb3 --extra skrl --extra rl-games --extra rsl-rl --extra viser --extra rerun --extra mimic --extra teleop --extra test --extra tetrahedralization --extra ov --extra fovi" RUN --mount=type=cache,target=/root/.cache/uv \ cd ${ISAACLAB_PATH} && \ From 697241ad83941e5b46e37401fdae3e42fa8ffc96 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 14:18:50 -0800 Subject: [PATCH 14/81] Build the render example scene with InteractiveScene The hand-built scene had no body for Newton to attach the camera frame to, so the example failed on the Newton backend. --- .../isaaclab_fovi/examples/render_foveated.py | 62 ++++++++++++------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index a85fb3cac518..7c65eac362cd 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -46,6 +46,10 @@ def main() -> None: from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg import isaaclab.sim as sim_utils + from isaaclab.assets import AssetBaseCfg, RigidObjectCfg + from isaaclab.scene import InteractiveScene, InteractiveSceneCfg + from isaaclab.terrains import TerrainImporterCfg + from isaaclab.utils.configclass import configclass if args.backend == "newton": from isaaclab_newton.physics.mjwarp_solver_cfg import MJWarpSolverCfg @@ -61,45 +65,55 @@ def main() -> None: physics = PhysxCfg() renderer = IsaacRtxRendererCfg() - sim_utils.create_new_stage() - sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(device=args.device, physics=physics)) - sim_utils.create_prim("/World/envs", "Xform") - sim_utils.create_prim("/World/envs/env_0", "Xform") - cube = sim_utils.CuboidCfg( - size=(0.5, 0.5, 0.5), - rigid_props=sim_utils.RigidBodyPropertiesCfg(disable_gravity=True), - mass_props=sim_utils.MassPropertiesCfg(mass=1.0), - collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=False), - visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.8, 0.2, 0.1)), - ) - cube.func("/World/envs/env_0/Cube", cube, translation=(0.0, 2.0, 0.0)) - light = sim_utils.DistantLightCfg(intensity=2000.0) - light.func("/World/Light", light) - - cfg = FoveatedCameraCfg( - prim_path="/World/envs/env_.*/Eye", + camera_cfg = FoveatedCameraCfg( + prim_path="{ENV_REGEX_NS}/Eye", data_types=["rgb"], renderer_cfg=renderer, foveated_res=args.resolution, pool_enabled=args.pool, # A 60 degree horizontal field of view, used by planar sampling. spawn=sim_utils.PinholeCameraCfg(focal_length=24.0, horizontal_aperture=27.713), - # OpenGL camera looking along +Y with +Z up. - offset=FoveatedCameraCfg.OffsetCfg(rot=(0.70710678, 0.0, 0.0, 0.70710678), convention="opengl"), + # OpenGL camera half a metre above the ground, looking along +Y with +Z up. + offset=FoveatedCameraCfg.OffsetCfg( + pos=(0.0, 0.0, 0.5), rot=(0.70710678, 0.0, 0.0, 0.70710678), convention="opengl" + ), ) if args.planar: - cfg.field_geometry = "planar" + camera_cfg.field_geometry = "planar" else: # The physical camera the retina looks through: a 640x480 pinhole. - cfg.camera_calibration = { + camera_cfg.camera_calibration = { "model": "pinhole", "image_size": (480, 640), "intrinsics": (550.0, 550.0, 319.5, 239.5), } - cfg.mask_to_sensor_fov = True + camera_cfg.mask_to_sensor_fov = True if args.cmf_a_deg is not None: - cfg.cmf_a_deg = args.cmf_a_deg - camera = FoveatedCamera(cfg) + camera_cfg.cmf_a_deg = args.cmf_a_deg + + @configclass + class SceneCfg(InteractiveSceneCfg): + """A red cube on the ground in front of the camera.""" + + ground = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + light = AssetBaseCfg(prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=500.0)) + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.5, 0.5, 0.5), + rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), + mass_props=sim_utils.MassCfg(mass=1.0), + collision_props=sim_utils.UsdPhysicsCollisionCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.8, 0.2, 0.1)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 2.0, 0.25)), + ) + eye = camera_cfg + + sim_utils.create_new_stage() + sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(device=args.device, physics=physics)) + scene = InteractiveScene(SceneCfg(num_envs=1, env_spacing=4.0)) + camera: FoveatedCamera = scene["eye"] sim.reset() frame_seconds: list[float] = [] From c8864d1d7b0c8c9c0ff377c7d5a5b89ff84b41d4 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 14:47:12 -0800 Subject: [PATCH 15/81] Sample in spherical coordinates and derive the camera from spawn optics The retina always places its samples by visual angle inside the physical camera it looks through. The field_geometry option, the planar ray paths and their helpers are removed; log-polar styles go with them, because fovi does not support them in spherical coordinates. Without camera_calibration, the physical camera is the one spawn creates: an ideal pinhole from PinholeCameraCfg optics, or the OpenCV model in spawn.distortion. An OpenCV fisheye with zero coefficients is an ideal equidistant fisheye. Gaze and edge masking now work for every camera. --- source/isaaclab_fovi/docs/README.md | 63 +++++++--- .../isaaclab_fovi/examples/render_foveated.py | 44 +++---- .../isaaclab_fovi/sensors/__init__.py | 7 +- .../sensors/calibrated_geometry.py | 93 ++++++++++---- .../sensors/foveated_camera_cfg.py | 44 ++++--- .../sensors/foveated_newton_camera.py | 57 ++------- .../isaaclab_fovi/sensors/foveated_rays.py | 116 +---------------- .../sensors/foveated_rtx_camera.py | 52 ++------ .../sensors/generalized_projection.py | 59 +-------- .../isaaclab_fovi/sensors/native_grid.py | 79 ++++-------- .../isaaclab_fovi/sensors/pooling.py | 6 +- .../isaaclab_fovi/sensors/virtual_gaze.py | 11 +- source/isaaclab_fovi/test/test_camera_cfg.py | 117 ++++++++++++++++++ .../test/test_foveated_camera_render.py | 23 +++- source/isaaclab_fovi/test/test_native_grid.py | 57 +++------ .../isaaclab_fovi/test/test_newton_buffers.py | 5 +- source/isaaclab_fovi/test/test_pooling.py | 28 +---- source/isaaclab_fovi/test/test_rays.py | 39 +----- source/isaaclab_fovi/test/test_rtx_layout.py | 21 ---- .../test/test_spherical_geometry.py | 1 - .../test/test_square_native_grid.py | 32 ++--- 21 files changed, 401 insertions(+), 553 deletions(-) create mode 100644 source/isaaclab_fovi/test/test_camera_cfg.py delete mode 100644 source/isaaclab_fovi/test/test_rtx_layout.py diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index b1a97f74872a..e4033fb82796 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -32,12 +32,6 @@ camera = FoveatedCameraCfg( data_types=["rgb"], renderer_cfg=NewtonWarpRendererCfg(), spawn=sim_utils.PinholeCameraCfg(), - # The physical camera the retina looks through. - camera_calibration={ - "model": "pinhole", - "image_size": (480, 640), # (height, width) - "intrinsics": (550.0, 550.0, 319.5, 239.5), # fx, fy, cx, cy [px] - }, foveated_res=64, ) ``` @@ -45,6 +39,42 @@ camera = FoveatedCameraCfg( With the default grid style the sensor publishes an upright image of shape `(num_envs, foveated_res, foveated_res, channels)` in `camera.data.output`. +### The physical camera + +The retina looks through a physical camera. It places its samples by visual +angle inside that camera's field of view, and its rays are cast directly at +those angles, so no pinhole image is resampled. The physical camera sets the +retinal window, the image that fixations are given in, and the edge that +`mask_to_sensor_fov` masks against. + +By default it is the camera that `spawn` creates: + +- `PinholeCameraCfg` optics give an ideal pinhole. Without a vertical + aperture the image is square. +- An OpenCV model in `spawn.distortion` gives that calibrated camera. + `OpenCvFisheyeDistortionCfg` with zero coefficients is an ideal equidistant + fisheye: + + ```python + spawn=sim_utils.PinholeCameraCfg( + distortion=sim_utils.OpenCvFisheyeDistortionCfg( + fx=229.2, fy=229.2, cx=319.5, cy=319.5, image_size=(640, 640) # 160 degrees across + ) + ) + ``` + +To describe any other calibrated camera, or a prim without spawn +configuration, set `camera_calibration` to +[`fovi.sensing.projection.CameraModel`](https://pypi.org/project/fovi/) fields: + +```python +camera_calibration={ + "model": "pinhole", # or "fisheye" + "image_size": (480, 640), # (height, width) + "intrinsics": (550.0, 550.0, 319.5, 239.5), # fx, fy, cx, cy [px] +} +``` + ### Foveation strength `cmf_a_deg` is the cortical magnification constant in degrees. Smaller values @@ -57,32 +87,25 @@ resolution, field of view and gaze: env.scene.eye.cmf_a_deg=1000 ``` -### Field geometry - -- `field_geometry="spherical"` (default) places samples by visual angle inside - the calibrated camera's field of view. It needs `camera_calibration`. -- `field_geometry="planar"` places samples on the image plane of the spawn - optics. It needs no calibration and has no gaze. - ### Gaze -In spherical geometry the fixation can move while the camera prim stays in -place: +The fixation can move while the camera prim stays in place: ```python -# Normalized (row, column) position in the calibrated image, shape (num_envs, 2). +# Normalized (row, column) position in the physical camera's image, shape (num_envs, 2). camera.set_calibrated_fixation(fixation) # Or mount angles (tilt, pan) in radians, shape (num_envs, 2). camera.set_calibrated_angles(angles) ``` Set `mask_to_sensor_fov=True` to zero the samples that fall outside the -calibrated camera's image at the current gaze. +physical camera's image at the current gaze. ### Advanced options - Sample-set styles such as `foveated_style="isotropic"` publish - `(num_envs, num_samples, 1, channels)`. + `(num_envs, num_samples, 1, channels)`. Log-polar styles are not available, + because fovi does not support them in spherical coordinates. - `fov_type` and `radius_norm` select circular or square coverage. See [square-foveated rendering](square_foveated.md). - `pool_enabled=True` renders a denser grid and pools it to the output grid. @@ -93,5 +116,5 @@ calibrated camera's image at the current gaze. uv run python source/isaaclab_fovi/examples/render_foveated.py --backend newton --steps 8 ``` -Add `--backend rtx` for the RTX renderer, `--planar` for planar sampling, or -`--cmf-a-deg 1000` for the non-foveated baseline. +Add `--backend rtx` for the RTX renderer, `--lens fisheye` for an ideal +equidistant fisheye, or `--cmf-a-deg 1000` for the non-foveated baseline. diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index 7c65eac362cd..b60dfb4d00c9 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -5,15 +5,16 @@ """Render a small scene with a foveated camera. -Run with ``--backend newton`` or ``--backend rtx``. By default the fixation -moves inside the fixed camera's calibrated field of view; ``--planar`` samples -the image plane of the spawn optics instead, with no gaze. ``--pool`` renders a -denser photoreceptor grid and pools it to the output grid. +Run with ``--backend newton`` or ``--backend rtx``. The retina looks through +the spawned camera, an ideal pinhole or, with ``--lens fisheye``, an ideal +equidistant fisheye, and its fixation moves inside that camera's field of view. +``--pool`` renders a denser photoreceptor grid and pools it to the output grid. """ from __future__ import annotations import argparse +import math import time import traceback from pathlib import Path @@ -22,7 +23,7 @@ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--backend", choices=("newton", "rtx"), required=True) -parser.add_argument("--planar", action="store_true", help="Sample the image plane of the spawn optics.") +parser.add_argument("--lens", choices=("pinhole", "fisheye"), default="pinhole", help="The camera the retina uses.") parser.add_argument("--pool", action="store_true", help="Pool a denser photoreceptor grid to the output grid.") parser.add_argument("--resolution", type=int, default=64, help="Side length of the output grid.") parser.add_argument("--cmf-a-deg", type=float, default=None, help="CMF constant [deg]; a large value is non-foveated.") @@ -65,29 +66,31 @@ def main() -> None: physics = PhysxCfg() renderer = IsaacRtxRendererCfg() + if args.lens == "pinhole": + # An ideal pinhole with a 60 degree field of view. + spawn = sim_utils.PinholeCameraCfg(focal_length=24.0, horizontal_aperture=27.713) + else: + # An ideal equidistant fisheye: a 640 px image circle spanning 160 degrees. + focal = 320.0 / math.radians(80.0) + spawn = sim_utils.PinholeCameraCfg( + distortion=sim_utils.OpenCvFisheyeDistortionCfg( + fx=focal, fy=focal, cx=319.5, cy=319.5, image_size=(640, 640) + ) + ) camera_cfg = FoveatedCameraCfg( prim_path="{ENV_REGEX_NS}/Eye", data_types=["rgb"], renderer_cfg=renderer, foveated_res=args.resolution, pool_enabled=args.pool, - # A 60 degree horizontal field of view, used by planar sampling. - spawn=sim_utils.PinholeCameraCfg(focal_length=24.0, horizontal_aperture=27.713), + spawn=spawn, + # The retina sees only what the spawned camera can see at the current gaze. + mask_to_sensor_fov=True, # OpenGL camera half a metre above the ground, looking along +Y with +Z up. offset=FoveatedCameraCfg.OffsetCfg( pos=(0.0, 0.0, 0.5), rot=(0.70710678, 0.0, 0.0, 0.70710678), convention="opengl" ), ) - if args.planar: - camera_cfg.field_geometry = "planar" - else: - # The physical camera the retina looks through: a 640x480 pinhole. - camera_cfg.camera_calibration = { - "model": "pinhole", - "image_size": (480, 640), - "intrinsics": (550.0, 550.0, 319.5, 239.5), - } - camera_cfg.mask_to_sensor_fov = True if args.cmf_a_deg is not None: camera_cfg.cmf_a_deg = args.cmf_a_deg @@ -119,10 +122,9 @@ class SceneCfg(InteractiveSceneCfg): frame_seconds: list[float] = [] frames: list[torch.Tensor] = [] for step in range(args.steps): - if not args.planar: - # Fixation in normalized image coordinates (row, column) of the calibrated camera. - fixation = torch.tensor([[0.5, (0.5, 0.58, 0.58, 0.5)[step % 4]]], device=sim.device) - camera.set_calibrated_fixation(fixation) + # Fixation in normalized image coordinates (row, column) of the spawned camera. + fixation = torch.tensor([[0.5, (0.5, 0.58, 0.58, 0.5)[step % 4]]], device=sim.device) + camera.set_calibrated_fixation(fixation) wp.synchronize_device(sim.device) start = time.perf_counter() sim.step() diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py index a09878b8285a..2ef23d9f3f3a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py @@ -3,10 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Foveated camera sensors and simulator-independent projection helpers. +"""Foveated camera sensors. -Names are imported on first access, so reading the configuration or the geometry -helpers does not load a renderer runtime. +Names are imported on first access, so reading the configuration does not load +a renderer runtime. """ from __future__ import annotations @@ -19,7 +19,6 @@ "FoveatedCameraCfg": "foveated_camera_cfg", "FoveatedNewtonCamera": "foveated_newton_camera", "FoveatedRTXCamera": "foveated_rtx_camera", - "compute_foveated_ray_array": "foveated_rays", } __all__ = list(_LAZY_EXPORTS) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index 003172fc14c3..53c3614164b4 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -19,9 +19,14 @@ gaze_rotation, ) +IDEAL_IMAGE_WIDTH = 1024 +"""Pixel width [px] of the image assigned to a camera derived from ideal spawn optics. + +The scale is arbitrary: fixations are normalized image positions and the retinal +window is an angle, so neither depends on it.""" + class SamplingGeometryConfig(Protocol): - field_geometry: str camera_calibration: CameraCalibration | None cmf_a_deg: float retinal_window_reference_side: str @@ -29,31 +34,77 @@ class SamplingGeometryConfig(Protocol): spawn: Any -def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: - """Return the retinal field of view and the CMF constant, both in degrees. +def calibration_from_spawn(spawn: Any) -> CameraCalibration: + """Describe the camera that the spawn configuration creates as a fovi calibration. - These are the units :class:`fovi.sensing.coords.SamplingCoords` takes in either - field geometry, so neither value is converted here. + * An OpenCV model in ``spawn.distortion`` gives that calibrated camera. A fisheye + model with zero coefficients is an ideal equidistant fisheye. + * Plain pinhole optics give an ideal pinhole with the same field of view. Without + a vertical aperture, the image is square. - * Spherical: the field of view is the calibrated retinal window. - * Planar: the field of view is the horizontal field of view of the spawn optics. + Raises: + ValueError: The spawn configuration describes a camera fovi cannot model: a USD + fisheye projection, thin-prism distortion, or an aperture offset. + """ + distortion = getattr(spawn, "distortion", None) + if distortion is not None: + width, height = distortion.image_size + intrinsics = (distortion.fx, distortion.fy, distortion.cx, distortion.cy) + if distortion.model == "opencvFisheye": + calibration = CameraCalibration(model="fisheye", max_angle_deg=math.degrees(distortion.max_fov) / 2) + coefficients = (distortion.k1, distortion.k2, distortion.k3, distortion.k4) + elif distortion.model == "opencvPinhole": + calibration = CameraCalibration(model="pinhole") + coefficients = tuple(getattr(distortion, name) for name in ("k1", "k2", "p1", "p2", "k3", "k4", "k5", "k6")) + thin_prism = (distortion.s1, distortion.s2, distortion.s3, distortion.s4) + if distortion.apply_lens_distortion and any(thin_prism): + raise ValueError("Thin-prism distortion (s1-s4) is not supported; set camera_calibration instead.") + else: + raise ValueError(f"Unsupported lens distortion model {distortion.model!r}.") + calibration.update(image_size=(height, width), intrinsics=tuple(float(value) for value in intrinsics)) + if distortion.apply_lens_distortion and any(coefficients): + calibration["distortion"] = tuple(float(value) for value in coefficients) + return calibration + if getattr(spawn, "projection_type", None) != "pinhole": + raise ValueError( + "Only pinhole spawn optics describe a camera; for a fisheye, set spawn.distortion to an " + "OpenCvFisheyeDistortionCfg or set camera_calibration." + ) + if spawn.horizontal_aperture_offset or spawn.vertical_aperture_offset: + raise ValueError("Aperture offsets are not supported; set camera_calibration instead.") + vertical_aperture = spawn.vertical_aperture or spawn.horizontal_aperture + width = IDEAL_IMAGE_WIDTH + height = round(width * vertical_aperture / spawn.horizontal_aperture) + focal = spawn.focal_length / spawn.horizontal_aperture * width + return CameraCalibration( + model="pinhole", image_size=(height, width), intrinsics=(focal, focal, (width - 1) / 2, (height - 1) / 2) + ) + + +def camera_model(cfg: SamplingGeometryConfig) -> CameraModel: + """Return the physical camera the retina looks through. + + This is ``cfg.camera_calibration`` when set, otherwise the camera that ``cfg.spawn`` + creates (see :func:`calibration_from_spawn`). Raises: - ValueError: The geometry is unknown, or the configuration lacks the - calibration (spherical) or spawn optics (planar) that define the window. + ValueError: Neither a calibration nor spawn optics describe the camera. + """ + if cfg.camera_calibration is not None: + return CameraModel(**cfg.camera_calibration) + if cfg.spawn is None: + raise ValueError("A foveated camera on an existing prim needs camera_calibration.") + return CameraModel(**calibration_from_spawn(cfg.spawn)) + + +def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: + """Return the retinal field of view and the CMF constant, both in degrees. + + The field of view is the angular span of the retinal window in the physical + camera. Both values are in the units :class:`fovi.sensing.coords.SamplingCoords` takes. """ - if cfg.field_geometry == "spherical": - if cfg.camera_calibration is None: - raise ValueError("Spherical sensing requires camera_calibration") - camera = CameraModel(**cfg.camera_calibration) - fov = camera.field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_short_side_fraction) - return fov, cfg.cmf_a_deg - if cfg.field_geometry == "planar": - if cfg.spawn is None: - raise ValueError("Planar sensing requires spawn optics to define its field of view") - fov = math.degrees(2.0 * math.atan(cfg.spawn.horizontal_aperture / (2.0 * cfg.spawn.focal_length))) - return fov, cfg.cmf_a_deg - raise ValueError(f"Unknown field geometry {cfg.field_geometry!r}; use 'spherical' or 'planar'.") + fov = camera_model(cfg).field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_short_side_fraction) + return fov, cfg.cmf_a_deg def retinal_directions(cartesian: torch.Tensor, fov_deg: float, image_rotation_deg: float = 0.0) -> torch.Tensor: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 9d26a55ebf3f..f058f01a450b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -19,10 +19,11 @@ class FoveatedCameraCfg(CameraCfg): """Configuration for a foveated camera sensor. - Extends :class:`CameraCfg` with CMF-based foveation parameters. - The sensor generates non-uniform foveated rays from - :class:`fovi.sensing.coords.SamplingCoords`. ``height`` and ``width`` - are auto-computed from the number of sampling coordinates. + Extends :class:`CameraCfg` with CMF-based foveation parameters. The retina + looks through a physical camera and places its samples by visual angle + inside that camera's field of view, densest at the fixation. The rays come + from :class:`fovi.sensing.coords.SamplingCoords`; ``height`` and ``width`` + are computed from the number of samples. :class:`~isaaclab_fovi.sensors.FoveatedCamera` selects its Newton or RTX implementation from ``renderer_cfg.renderer_type``. @@ -37,18 +38,20 @@ class FoveatedCameraCfg(CameraCfg): Smaller values give stronger foveation; a value much larger than the field of view gives nearly uniform sampling. The default is an estimate from human - data. It is passed to :class:`fovi.sensing.coords.SamplingCoords` unchanged - in both field geometries.""" + data. It is passed to :class:`fovi.sensing.coords.SamplingCoords` unchanged.""" - field_geometry: str = "spherical" - """Coordinates the samples are laid out in: ``"spherical"`` or ``"planar"``. + camera_calibration: CameraCalibration | None = None + """The physical camera the retina looks through, as :class:`fovi.sensing.projection.CameraModel` fields. - Spherical sampling places samples by visual angle inside the calibrated - camera's field of view and needs :attr:`camera_calibration`. Planar sampling - places them on the image plane of the spawn optics.""" + It defines the retinal window, the image that fixations are given in, and + the edge that :attr:`mask_to_sensor_fov` masks against. Any calibrated + pinhole or fisheye camera works. - camera_calibration: CameraCalibration | None = None - """CameraModel fields for the physical source image; required for spherical geometry.""" + If None, the camera that :attr:`spawn` creates is used: an OpenCV model in + ``spawn.distortion`` (an :class:`~isaaclab.sim.OpenCvFisheyeDistortionCfg` with + zero coefficients is an ideal equidistant fisheye), otherwise an ideal pinhole + with the spawn's focal length and apertures. A prim without spawn + configuration needs a calibration.""" foveated_res: int = 60 """Resolution parameter passed to :class:`SamplingCoords`. For isotropic @@ -92,17 +95,16 @@ class FoveatedCameraCfg(CameraCfg): * Other angles work in principle but are untested.""" mask_to_sensor_fov: bool = False - """Zero the samples that fall outside the calibrated camera's image at the current gaze. + """Zero the samples that fall outside the physical camera's image at the current gaze. - With calibrated gaze the retina can look past the edge of the physical - camera; this keeps what the sensor reports to what that camera could have - seen. Requires spherical geometry.""" + With gaze the retina can look past the edge of the physical camera; this + keeps what the sensor reports to what that camera could have seen.""" retinal_window_short_side_fraction: float = 1.0 - """Diameter of the retinal window as a fraction of the reference image side. Spherical geometry only.""" + """Diameter of the retinal window as a fraction of the reference image side.""" retinal_window_reference_side: str = "short" - """Image side defining the retinal window diameter: ``short`` or ``long``. Spherical geometry only.""" + """Image side defining the retinal window diameter: ``short`` or ``long``.""" # -- Optional retinal pooling (photoreceptor -> RGC two-layer sampling) -- @@ -166,10 +168,6 @@ class labels and breaks downstream integer/equality checks, so these def __post_init__(self): # Resolves the default renderer and forwards deprecated renderer fields. super().__post_init__() - if self.field_geometry not in ("spherical", "planar"): - raise ValueError(f"Unknown field_geometry={self.field_geometry!r}; use 'spherical' or 'planar'.") - if self.mask_to_sensor_fov and self.field_geometry != "spherical": - raise ValueError("mask_to_sensor_fov requires field_geometry='spherical'.") validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) # ``spawn`` is a ``PinholeCameraCfg`` / ``FisheyeCameraCfg`` whose # ``lock_camera`` field defaults to True. That writes diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 45a1b89c93f9..cb11da5e819e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -14,7 +14,6 @@ from __future__ import annotations import logging -import math from collections.abc import Sequence from typing import TYPE_CHECKING @@ -26,7 +25,7 @@ from .calibrated_geometry import retinal_directions from .foveated_camera import FoveatedCamera -from .foveated_rays import compute_explicit_ray_array, compute_foveated_ray_array +from .foveated_rays import compute_explicit_ray_array from .native_grid import ( GRID_STYLE, allocate_grid_outputs, @@ -70,17 +69,13 @@ class FoveatedNewtonCamera(FoveatedCamera): and injected into Newton's Warp renderer. Vector sensors publish ``(B, N, 1, C)``; native grid sensors publish upright ``(B, H, W, C)``. - In planar geometry the samples cover the horizontal field of view of the - ``spawn`` optics. In spherical geometry they cover the calibrated retinal - window, and gaze is applied as a per-environment rotation of the rays. + The samples cover the retinal window of the physical camera, and gaze is + applied as a per-environment rotation of the rays. """ cfg: FoveatedCameraCfg def __init__(self, cfg: FoveatedCameraCfg): - # Spawn optics are only needed for planar geometry; an existing prim has none. - self._spawn_focal_length: float | None = None if cfg.spawn is None else cfg.spawn.focal_length - self._spawn_horizontal_aperture: float | None = None if cfg.spawn is None else cfg.spawn.horizontal_aperture self._calibrated_rotation = None super().__init__(cfg) @@ -89,12 +84,7 @@ def __init__(self, cfg: FoveatedCameraCfg): # ------------------------------------------------------------------ def _initialize_impl(self): - # 1. Derive camera physical FOV for ray generation. - self._camera_hfov_rad: float | None = None - if self._spawn_focal_length is not None: - self._camera_hfov_rad = 2.0 * math.atan(self._spawn_horizontal_aperture / (2.0 * self._spawn_focal_length)) - - # 2. Build coords on CPU so we know N_lo (and N_hi when pooling) before + # 1. Build coords on CPU so we know N_lo (and N_hi when pooling) before # the parent allocates buffers. The pooler is constructed later, # after the sensor device is available, because its knn indices / # distances / gaussian weights are plain tensor attributes that @@ -171,41 +161,15 @@ def _initialize_impl(self): # the camera prim. Foveated analogue of a post-render # ``torch.flip`` — but flip would shuffle the sample-to-coord # mapping; this rotation does not. - ray_cart = ray_coords_device.cartesian if self._native_grid: - # Spherical grids take their extent from the sampling coordinates and ignore the tangent scale. - tangent_scale = 1.0 if self._camera_hfov_rad is None else math.tan(self._camera_hfov_rad / 2) self._ray_directions = native_grid_directions( - ray_coords_device, - tangent_scale=tangent_scale, - image_rotation_deg=self.cfg.image_rotation_deg, - camera_fov_rad=self._camera_hfov_rad, - ) - self._foveated_rays = compute_explicit_ray_array(self._ray_directions, device=str(self._device)) - elif self.cfg.field_geometry == "spherical": - self._ray_directions = retinal_directions(ray_cart, ray_coords_device.fov, self.cfg.image_rotation_deg) - self._foveated_rays = compute_explicit_ray_array(self._ray_directions, device=str(self._device)) - elif self.cfg.image_rotation_deg: - theta = math.radians(float(self.cfg.image_rotation_deg)) - cos_t = math.cos(theta) - sin_t = math.sin(theta) - rot = torch.tensor( - [[cos_t, -sin_t], [sin_t, cos_t]], - device=ray_cart.device, - dtype=ray_cart.dtype, - ) - ray_cart = ray_cart @ rot.T - self._foveated_rays = compute_foveated_ray_array( - sampling_coords_cartesian=ray_cart, - camera_fov_rad=self._camera_hfov_rad, - device=str(self._device), + ray_coords_device, image_rotation_deg=self.cfg.image_rotation_deg ) else: - self._foveated_rays = compute_foveated_ray_array( - sampling_coords_cartesian=ray_cart, - camera_fov_rad=self._camera_hfov_rad, - device=str(self._device), + self._ray_directions = retinal_directions( + ray_coords_device.cartesian, ray_coords_device.fov, self.cfg.image_rotation_deg ) + self._foveated_rays = compute_explicit_ray_array(self._ray_directions, device=str(self._device)) render_samples = self.cfg.height * self.cfg.width if render_samples > self._num_ray_samples: @@ -402,11 +366,6 @@ def _apply_sensor_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: # Output helpers # ------------------------------------------------------------------ - @property - def hfov_rad(self) -> float: - """Horizontal field of view in radians.""" - return self._camera_hfov_rad - @property def sampling_coords(self): """The :class:`SamplingCoords` used for ray generation.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py index 28ac77911a91..e94c3995eb33 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py @@ -3,75 +3,18 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Foveated ray computation from SamplingCoords. +"""Newton ray arrays for foveated cameras. -Converts fovi's SamplingCoords.cartesian (N, 2) in [-1, 1] into a Warp ray -array suitable for Newton's SensorTiledCamera. The ray array has shape -(camera_count=1, height=N, width=1, 2) where [:, :, :, 0] is origin (always -zero) and [:, :, :, 1] is the normalized direction. - -Supports two projection models: -- ``"pinhole"``: rectilinear projection ``ray_xy = coord * tan(hfov/2)`` -- ``"fisheye_equidistant"``: equidistant fisheye ``θ = r * (hfov/2)`` +Newton's Warp renderer takes a ray array of shape (camera_count=1, height, width, 2), +where [..., 0] is the ray origin (always zero) and [..., 1] its unit direction. """ from __future__ import annotations -import math - import torch import warp as wp -@wp.kernel(enable_backward=False) -def _fill_foveated_rays( - coords_x: wp.array(dtype=wp.float32), - coords_y: wp.array(dtype=wp.float32), - h_tan: wp.float32, - out_rays: wp.array(dtype=wp.vec3f, ndim=4), -): - """Warp kernel: map fovi (x, y) to OpenGL camera-space ray directions. - - Standard pinhole projection in OpenGL frame (+X=right, +Y=up, -Z=forward): - cart_x → ray_x (horizontal) - cart_y → ray_y (vertical) - """ - i = wp.tid() - x = coords_x[i] - y = coords_y[i] - direction = wp.normalize(wp.vec3f(x * h_tan, y * h_tan, -1.0)) - out_rays[0, i, 0, 0] = wp.vec3f(0.0, 0.0, 0.0) # origin - out_rays[0, i, 0, 1] = direction - - -@wp.kernel(enable_backward=False) -def _fill_foveated_rays_fisheye_equidistant( - coords_x: wp.array(dtype=wp.float32), - coords_y: wp.array(dtype=wp.float32), - half_fov: wp.float32, - out_rays: wp.array(dtype=wp.vec3f, ndim=4), -): - """Warp kernel: equidistant fisheye projection. - - Maps normalized coords to angles linearly: θ = r * half_fov, where - r = sqrt(x² + y²). Unlike pinhole, the z-component varies per ray - (-cos(θ)) and the lateral scaling is sin(θ)/r instead of constant h_tan. - """ - i = wp.tid() - x = coords_x[i] - y = coords_y[i] - r = wp.sqrt(x * x + y * y) - theta = r * half_fov - # sin(theta)/r → half_fov as r → 0 (L'Hôpital) - if r > 1.0e-7: - scale = wp.sin(theta) / r - else: - scale = half_fov - direction = wp.normalize(wp.vec3f(x * scale, y * scale, -wp.cos(theta))) - out_rays[0, i, 0, 0] = wp.vec3f(0.0, 0.0, 0.0) # origin - out_rays[0, i, 0, 1] = direction - - @wp.kernel(enable_backward=False) def _fill_explicit_rays( directions: wp.array(dtype=wp.vec3f), @@ -87,7 +30,7 @@ def compute_explicit_ray_array( *, device: str, ) -> wp.array: - """Build a Newton ray array from explicit normalized camera-space rays.""" + """Build a ``(1, N, 1, 2)`` Newton ray array from unit OpenGL camera-frame directions, shape (N, 3).""" if ray_directions.ndim != 2 or ray_directions.shape[1] != 3: raise ValueError(f"ray_directions must have shape (N, 3), got {tuple(ray_directions.shape)}.") directions = wp.from_torch( @@ -103,54 +46,3 @@ def compute_explicit_ray_array( device=device, ) return out_rays - - -def compute_foveated_ray_array( - sampling_coords_cartesian: torch.Tensor, - camera_fov_rad: float, - device: str, - projection: str = "pinhole", -) -> wp.array: - """Build a ``(1, N, 1, 2)`` Warp ray array from foveated sample coordinates. - - Args: - sampling_coords_cartesian: ``(N, 2)`` tensor in ``[-1, 1]`` from - :class:`fovi.sensing.coords.SamplingCoords`. Column 0 is the - horizontal (x) coordinate, column 1 is vertical (y). - camera_fov_rad: Horizontal field-of-view of the camera in **radians** - (derived from spawn optics / intrinsic matrix). - device: Warp device string (e.g. ``"cuda:0"``). - projection: Projection model — ``"pinhole"`` (rectilinear) or - ``"fisheye_equidistant"`` (linear angle mapping). - - Returns: - ``wp.array(dtype=vec3f, ndim=4)`` of shape ``(1, N, 1, 2)``. - """ - N = sampling_coords_cartesian.shape[0] - - # Flatten coords to 1-D Warp arrays - coords_x = wp.from_torch(sampling_coords_cartesian[:, 0].contiguous().float(), dtype=wp.float32) - coords_y = wp.from_torch(sampling_coords_cartesian[:, 1].contiguous().float(), dtype=wp.float32) - - out_rays = wp.zeros((1, N, 1, 2), dtype=wp.vec3f, device=device) - - if projection == "pinhole": - h_tan = math.tan(camera_fov_rad / 2.0) - wp.launch( - kernel=_fill_foveated_rays, - dim=N, - inputs=[coords_x, coords_y, h_tan, out_rays], - device=device, - ) - elif projection == "fisheye_equidistant": - half_fov = camera_fov_rad / 2.0 - wp.launch( - kernel=_fill_foveated_rays_fisheye_equidistant, - dim=N, - inputs=[coords_x, coords_y, half_fov, out_rays], - device=device, - ) - else: - raise ValueError(f"Unknown projection {projection!r}. Supported: 'pinhole', 'fisheye_equidistant'.") - - return out_rays diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 9de46c05329e..d897ae196215 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -66,8 +66,7 @@ class FoveatedRTXCamera(FoveatedCamera): Grid styles render straight into their native grid. Sample-set styles are packed onto a cortical disc, which keeps neighbouring samples adjacent for - DLSS denoising. Camera motion comes from the prim's parent, and in spherical - geometry from the calibrated gaze. + DLSS denoising. Camera motion comes from the prim's parent and from the gaze. """ cfg: FoveatedCameraCfg @@ -90,9 +89,6 @@ def renderer(self) -> BaseRenderer: return self._renderer def __init__(self, cfg: FoveatedCameraCfg): - # Spawn optics are only needed for planar geometry; an existing prim has none. - self._spawn_focal_length: float | None = None if cfg.spawn is None else cfg.spawn.focal_length - self._spawn_horizontal_aperture: float | None = None if cfg.spawn is None else cfg.spawn.horizontal_aperture self._calibrated_rotation = None # Texture buffers are owned by the parent ``Camera`` (allocated in # ``_create_buffers`` and bound to the renderer via ``set_outputs``). @@ -114,12 +110,7 @@ def __init__(self, cfg: FoveatedCameraCfg): # ------------------------------------------------------------------ def _prepare_projection(self) -> None: - # 1. Derive camera physical FOV. - self._camera_hfov_rad: float | None = None - if self._spawn_focal_length is not None: - self._camera_hfov_rad = 2.0 * math.atan(self._spawn_horizontal_aperture / (2.0 * self._spawn_focal_length)) - - # 2. Build coords on CPU. The LUT textures + UV extraction use the + # 1. Build coords on CPU. The LUT textures + UV extraction use the # *rendered* grid (highres when pooling, else lowres). The # public `sampling_coords` property stays on the lowres / RGC grid. self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") @@ -136,7 +127,7 @@ def _prepare_projection(self) -> None: self._num_ray_samples = len(ray_coords) # rendered ray count N = self._num_ray_samples - # 3. Compute ray directions and UV mapping from the rendered grid. + # 2. Compute ray directions and UV mapping from the rendered grid. # Apply optional image-space rotation (``cfg.image_rotation_deg``) by # rotating the per-ray polar angle ``theta`` around the optical axis # *before* computing the ray directions. This undoes a physical @@ -151,22 +142,11 @@ def _prepare_projection(self) -> None: if self.cfg.image_rotation_deg: theta_rad = theta_rad + math.radians(float(self.cfg.image_rotation_deg)) if self._native_grid: - # Spherical grids take their extent from the sampling coordinates and ignore the tangent scale. - tangent_scale = 1.0 if self._camera_hfov_rad is None else math.tan(self._camera_hfov_rad / 2) - self._native_tangent_scale = tangent_scale - dirs = native_grid_directions( - ray_coords, - tangent_scale=tangent_scale, - image_rotation_deg=self.cfg.image_rotation_deg, - camera_fov_rad=self._camera_hfov_rad, - ) - elif self.cfg.field_geometry == "spherical": - dirs = retinal_directions(ray_coords.cartesian, ray_coords.fov, self.cfg.image_rotation_deg) + dirs = native_grid_directions(ray_coords, image_rotation_deg=self.cfg.image_rotation_deg) else: - r_deg = ray_coords.polar[:, 0].to(torch.float64) * (ray_coords.fov / 2.0) - dirs = gp.ray_directions_rectilinear(r_deg, theta_rad, device="cpu") + dirs = retinal_directions(ray_coords.cartesian, ray_coords.fov, self.cfg.image_rotation_deg) - # 4. Texture dimensions and UV layout. Grid styles render straight into their + # 3. Texture dimensions and UV layout. Grid styles render straight into their # native grid; sample-set styles are packed onto a cortical disc, which keeps # neighbouring samples adjacent for the renderer's spatial filtering. if self._native_grid: @@ -191,7 +171,7 @@ def _prepare_projection(self) -> None: self._texture_height = th self._sample_uv = uv # (N, 2) float32 - # 5. Build and save LUT textures. + # 4. Build and save LUT textures. # The exit texture is an octahedral inverse map (ray direction → sensor NDC). # It covers the full hemisphere, but only the fraction within the camera # FOV is populated. The resolution must be high enough that each foveated @@ -204,11 +184,7 @@ def _prepare_projection(self) -> None: EW = EH = max(128, 4 * max(tw, th)) if self._native_grid: dir_tex, exit_tex = gp.build_native_grid_textures( - ray_coords, - tangent_scale=self._native_tangent_scale, - image_rotation_deg=self.cfg.image_rotation_deg, - exit_size=EW, - camera_fov_rad=self._camera_hfov_rad, + ray_coords, image_rotation_deg=self.cfg.image_rotation_deg, exit_size=EW ) else: dir_tex, exit_tex = gp.build_generalized_projection_textures( @@ -243,7 +219,7 @@ def _prepare_projection(self) -> None: self._lut_tmpdir, ) - # 6. Set texture dimensions so parent allocates (B, th, tw, C) buffers. + # 5. Set texture dimensions so parent allocates (B, th, tw, C) buffers. self.cfg.height = th self.cfg.width = tw @@ -290,9 +266,8 @@ def _initialize_impl(self) -> None: self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) self._ray_coords = self._sampling_coords_highres or self._sampling_coords self._initialize_calibrated_gaze() - if self.cfg.field_geometry == "spherical": - _, local_orientation = self._view.get_local_poses() - self._calibrated_base_local_orientation = matrix_from_quat(local_orientation.torch).clone() + _, local_orientation = self._view.get_local_poses() + self._calibrated_base_local_orientation = matrix_from_quat(local_orientation.torch).clone() # Build the pooler on the sensor device (so knn tensors live there). # A second max-mode pooler is built inside ``_allocate_foveated_buffers`` @@ -494,11 +469,6 @@ def _apply_sensor_fov_mask(self) -> None: # Output helpers # ------------------------------------------------------------------ - @property - def hfov_rad(self) -> float: - """Horizontal field of view in radians.""" - return self._camera_hfov_rad - @property def sampling_coords(self): """The :class:`SamplingCoords` used for ray generation.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py index 191853d6ab1f..8f1a4fbe4328 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py @@ -179,31 +179,14 @@ def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tens def build_native_grid_textures( - coords: SamplingCoords, - *, - tangent_scale: float, - image_rotation_deg: float, - exit_size: int, - projection: str = "pinhole", - camera_fov_rad: float | None = None, + coords: SamplingCoords, *, image_rotation_deg: float, exit_size: int ) -> tuple[torch.Tensor, torch.Tensor]: """Build native direction texels and an analytic octahedral inverse map.""" - directions = native_grid_directions( - coords, - tangent_scale=tangent_scale, - image_rotation_deg=image_rotation_deg, - projection=projection, - camera_fov_rad=camera_fov_rad, - ).reshape(coords.resolution, coords.resolution, 3) - decoded = torch.stack(_octahedral_decode(exit_size, exit_size, device=coords.device), -1) - uv, valid = native_grid_exit_uv( - decoded, - coords, - tangent_scale=tangent_scale, - image_rotation_deg=image_rotation_deg, - projection=projection, - camera_fov_rad=camera_fov_rad, + directions = native_grid_directions(coords, image_rotation_deg=image_rotation_deg).reshape( + coords.resolution, coords.resolution, 3 ) + decoded = torch.stack(_octahedral_decode(exit_size, exit_size, device=coords.device), -1) + uv, valid = native_grid_exit_uv(decoded, coords, image_rotation_deg=image_rotation_deg) # Out-of-sensor rays must not be projected into the fovea by the inverse LUT. exit_texture = torch.where(valid[..., None], uv, torch.full_like(uv, -1)) return directions, exit_texture @@ -344,38 +327,6 @@ def apply_generalized_projection_to_prim( ) -# ============================================================================= -# Ray direction models -# ============================================================================= - - -def ray_directions_rectilinear( - r_deg, - theta_rad, - device="cuda", -) -> torch.Tensor: - """Unit ray directions for the rectilinear (pinhole) projection model. - - ``d = normalize(tan(r°)·cosθ, tan(r°)·sinθ, -1)`` - - Args: - r_deg: ``(N,)`` eccentricities in degrees. - theta_rad: ``(N,)`` polar angles in radians. - device: Torch device. - - Returns: - ``(N, 3)`` float32 unit directions, ``dz < 0``. - """ - r = _t(r_deg, torch.float64, device) - th = _t(theta_rad, torch.float64, device) - t = torch.tan(r * (math.pi / 180.0)) - dx = t * th.cos() - dy = t * th.sin() - dz = torch.full_like(dx, -1.0) - n = (dx**2 + dy**2 + dz**2).sqrt().clamp(min=1e-20) - return torch.stack([dx / n, dy / n, dz / n], dim=-1).float() - - # ============================================================================= # NDC layout functions # ============================================================================= diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py index 6f7cb6a0c45e..8b8e57267cea 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py @@ -50,7 +50,12 @@ def proxy_outputs(outputs: Mapping[str, torch.Tensor | ProxyArray]) -> dict[str, } -def _angular_padding_boundary(coords: SamplingCoords, camera_fov_rad: float | None = None) -> tuple[float, float]: +def _require_spherical(coords: SamplingCoords) -> None: + if coords.field_geometry != "spherical": + raise ValueError(f"Foveated cameras sample spherical coordinates, got {coords.field_geometry!r}.") + + +def _angular_padding_boundary(coords: SamplingCoords) -> tuple[float, float]: if coords.fov_type == "circular": radius = 1.0 elif coords.fov_type == "square": @@ -60,8 +65,7 @@ def _angular_padding_boundary(coords: SamplingCoords, camera_fov_rad: float | No radius = float(torch.linalg.vector_norm(coords.native_to_visual(corner)).item()) else: raise ValueError(f"Unsupported native grid footprint {coords.fov_type!r}.") - fov_rad = math.radians(coords.fov) if camera_fov_rad is None else camera_fov_rad - angle = radius * fov_rad / 2 + angle = radius * math.radians(coords.fov) / 2 if angle >= math.pi: raise ValueError("Spherical native grid footprint reaches the antipode; reduce FoV or use circular coverage.") return radius, angle @@ -89,34 +93,20 @@ def unbounded_angular_radius(angle: torch.Tensor, half_fov_rad: float) -> torch. return torch.where(angle <= half_fov_rad, angle / half_fov_rad, padding) -def native_grid_directions( - coords: SamplingCoords, - *, - tangent_scale: float, - image_rotation_deg: float = 0.0, - projection: str = "pinhole", - camera_fov_rad: float | None = None, -) -> torch.Tensor: - """Return canonical ordered OpenGL rays for a warped Cartesian grid.""" +def native_grid_directions(coords: SamplingCoords, *, image_rotation_deg: float = 0.0) -> torch.Tensor: + """Return canonical ordered OpenGL rays for a warped Cartesian grid. + + Grid radius is proportional to visual angle, and the padding outside the + nominal field continues toward the antipode without wrapping. + """ + _require_spherical(coords) cartesian = coords.cartesian.to(torch.float64) radius = torch.linalg.vector_norm(cartesian, dim=-1) - if projection not in ("pinhole", "fisheye_equidistant"): - raise ValueError(f"Unsupported native grid projection {projection!r}.") - if coords.field_geometry == "spherical" or projection == "fisheye_equidistant": - if coords.field_geometry != "spherical" and camera_fov_rad is None: - raise ValueError("Planar equidistant rendering requires camera_fov_rad.") - boundary_radius, boundary_angle = _angular_padding_boundary( - coords, None if coords.field_geometry == "spherical" else camera_fov_rad - ) - angle = bounded_angular_radius(radius / boundary_radius, boundary_angle) - scale = torch.where(radius > 0, angle.sin() / radius.clamp_min(1e-30), angle.new_zeros(())) - xy = cartesian * scale[:, None] - z = -angle.cos() - elif coords.field_geometry in ("planar", "legacy"): - xy = cartesian * tangent_scale - z = -torch.ones_like(radius) - else: - raise ValueError(f"Unknown field geometry {coords.field_geometry!r}.") + boundary_radius, boundary_angle = _angular_padding_boundary(coords) + angle = bounded_angular_radius(radius / boundary_radius, boundary_angle) + scale = torch.where(radius > 0, angle.sin() / radius.clamp_min(1e-30), angle.new_zeros(())) + xy = cartesian * scale[:, None] + z = -angle.cos() angle = math.radians(image_rotation_deg) x, y = xy.unbind(-1) rays = torch.stack( @@ -127,40 +117,23 @@ def native_grid_directions( def native_grid_exit_uv( - directions: torch.Tensor, - coords: SamplingCoords, - *, - tangent_scale: float, - image_rotation_deg: float = 0.0, - projection: str = "pinhole", - camera_fov_rad: float | None = None, + directions: torch.Tensor, coords: SamplingCoords, *, image_rotation_deg: float = 0.0 ) -> tuple[torch.Tensor, torch.Tensor]: """Analytically map OpenGL rays to native texture UV and visibility. Texture rows and columns follow canonical vector order: native x then y. The public image applies Fovi's upright grid permutation after rendering. """ + _require_spherical(coords) angle = math.radians(image_rotation_deg) x, y, z = directions.to(torch.float64).unbind(-1) xy = torch.stack((math.cos(angle) * x + math.sin(angle) * y, -math.sin(angle) * x + math.cos(angle) * y), -1) lateral = torch.linalg.vector_norm(xy, dim=-1) - if projection not in ("pinhole", "fisheye_equidistant"): - raise ValueError(f"Unsupported native grid projection {projection!r}.") - if coords.field_geometry == "spherical" or projection == "fisheye_equidistant": - if coords.field_geometry != "spherical" and camera_fov_rad is None: - raise ValueError("Planar equidistant rendering requires camera_fov_rad.") - theta = torch.atan2(lateral, -z) - boundary_radius, boundary_angle = _angular_padding_boundary( - coords, None if coords.field_geometry == "spherical" else camera_fov_rad - ) - radius = unbounded_angular_radius(theta, boundary_angle) * boundary_radius - cartesian = xy * (radius / lateral.clamp_min(1e-30))[..., None] - visible = theta < math.pi - 1e-8 - elif coords.field_geometry in ("planar", "legacy"): - cartesian = xy / ((-z).clamp_min(1e-30) * tangent_scale)[..., None] - visible = z < 0 - else: - raise ValueError(f"Unknown field geometry {coords.field_geometry!r}.") + theta = torch.atan2(lateral, -z) + boundary_radius, boundary_angle = _angular_padding_boundary(coords) + radius = unbounded_angular_radius(theta, boundary_angle) * boundary_radius + cartesian = xy * (radius / lateral.clamp_min(1e-30))[..., None] + visible = theta < math.pi - 1e-8 native = coords.visual_to_native(cartesian) uv = (native.flip(-1) + 1) / 2 visible = visible & (uv >= 0).all(-1) & (uv <= 1).all(-1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index 50b994b9d9e6..c4daa1bc8d93 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -60,7 +60,7 @@ def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCo quiet=True, fov_type=cfg.fov_type, radius_norm=cfg.radius_norm, - field_geometry=cfg.field_geometry, + field_geometry="spherical", ) lowres = SamplingCoords( fov=fov, @@ -71,7 +71,7 @@ def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCo isotropic_plotting_type=cfg.isotropic_plotting_type, fov_type=cfg.fov_type, radius_norm=cfg.radius_norm, - field_geometry=cfg.field_geometry, + field_geometry="spherical", ) return lowres, matched_res @@ -96,7 +96,7 @@ def build_highres_coords(cfg: FoveatedCameraCfg, matched_res: int, device: str) isotropic_plotting_type=cfg.isotropic_plotting_type, fov_type=cfg.fov_type, radius_norm=cfg.radius_norm, - field_geometry=cfg.field_geometry, + field_geometry="spherical", ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index 73b02432cec8..49f922840539 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -12,7 +12,7 @@ import torch import warp as wp -from fovi.sensing.projection import CameraModel, angular_directions, gaze_rotation +from fovi.sensing.projection import angular_directions, gaze_rotation from isaaclab.utils.math import matrix_from_quat, quat_from_matrix @@ -20,6 +20,7 @@ calibrated_fixation_rotation, calibrated_mount_angles, calibrated_visibility, + camera_model, compose_rotations, convert_camera_frame_quaternion, ) @@ -91,14 +92,10 @@ def _calibrated_validity(self, batch_size: int) -> torch.Tensor: return calibrated_visibility(self._calibrated_camera, rays, rotation) def _initialize_calibrated_gaze(self) -> None: - if self.cfg.field_geometry != "spherical": - return - self._calibrated_camera = CameraModel(**self.cfg.camera_calibration) + self._calibrated_camera = camera_model(self.cfg) coords = self._sampling_coords_highres or self._sampling_coords if coords.style == GRID_STYLE: - self._calibrated_rays = native_grid_directions(coords, tangent_scale=1.0) * coords.cartesian.new_tensor( - (1, -1, -1) - ) + self._calibrated_rays = native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1)) else: self._calibrated_rays = angular_directions(coords.cartesian, coords.fov) self._calibrated_identity = torch.eye(3, device=coords.device) diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py new file mode 100644 index 000000000000..f08aef6ea5b0 --- /dev/null +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -0,0 +1,117 @@ +# 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 + +"""Configuration defaults of the foveated camera and the physical camera it looks through.""" + +import math + +import pytest +import torch +from isaaclab_fovi.sensors.calibrated_geometry import camera_model, sampling_geometry +from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg + +from isaaclab.sim import ( + FisheyeCameraCfg, + OpenCvFisheyeDistortionCfg, + OpenCvPinholeDistortionCfg, + PinholeCameraCfg, +) + +CALIBRATION = {"model": "pinhole", "image_size": (480, 640), "intrinsics": (550.0, 550.0, 319.5, 239.5)} + + +def make_cfg(**kwargs) -> FoveatedCameraCfg: + return FoveatedCameraCfg(prim_path="/World/Camera", **kwargs) + + +def ray_angle_deg(camera, pixel: tuple[float, float]) -> float: + """Angle [deg] between the optical axis and the ray through a source pixel (x, y).""" + direction, valid = camera.unproject(torch.tensor([pixel], dtype=torch.float64)) + assert valid.all() + return math.degrees(math.acos(float(direction[0, 2]))) + + +def test_defaults_are_grid_sampling_at_the_human_cmf_estimate() -> None: + cfg = FoveatedCameraCfg() + assert cfg.foveated_style == "warped_cartesian_as_grid" + assert cfg.cmf_a_deg == 0.591 + assert cfg.camera_calibration is None + + +def test_default_pinhole_spawn_describes_an_ideal_pinhole() -> None: + spawn = PinholeCameraCfg() + fov, cmf_a = sampling_geometry(make_cfg(spawn=spawn)) + expected = math.degrees(2 * math.atan(spawn.horizontal_aperture / (2 * spawn.focal_length))) + assert fov == pytest.approx(expected, rel=1e-6) + assert cmf_a == 0.591 + camera = camera_model(make_cfg(spawn=spawn)) + assert camera.model == "pinhole" + assert camera.distortion == () + # Without a vertical aperture the image is square. + assert camera.image_size[0] == camera.image_size[1] + + +def test_vertical_aperture_sets_the_short_side() -> None: + spawn = PinholeCameraCfg(focal_length=10.0, horizontal_aperture=20.0, vertical_aperture=10.0) + fov, _ = sampling_geometry(make_cfg(spawn=spawn)) + # The short side is vertical: 2 * atan(5 / 10). + assert fov == pytest.approx(math.degrees(2 * math.atan(0.5)), rel=1e-6) + + +def test_opencv_pinhole_spawn_gives_that_calibrated_camera() -> None: + distortion = OpenCvPinholeDistortionCfg( + fx=500.0, fy=510.0, cx=320.0, cy=240.0, image_size=(640, 480), k1=-0.1, k2=0.01, p1=0.001, k4=0.002 + ) + camera = camera_model(make_cfg(spawn=PinholeCameraCfg(distortion=distortion))) + assert camera.model == "pinhole" + # Isaac Lab sizes are (width, height); fovi's are (height, width). + assert camera.image_size == (480, 640) + assert camera.intrinsics == (500.0, 510.0, 320.0, 240.0) + assert camera.distortion == (-0.1, 0.01, 0.001, 0.0, 0.0, 0.002, 0.0, 0.0) + + distortion.apply_lens_distortion = False + assert camera_model(make_cfg(spawn=PinholeCameraCfg(distortion=distortion))).distortion == () + + +def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> None: + # The image edge is 320 / 250 rad (73 deg) off axis, inside the default 180 deg lens. + focal = 250.0 + distortion = OpenCvFisheyeDistortionCfg(fx=focal, fy=focal, cx=319.5, cy=319.5, image_size=(640, 640)) + cfg = make_cfg(spawn=PinholeCameraCfg(distortion=distortion)) + camera = camera_model(cfg) + assert camera.model == "fisheye" + assert camera.distortion == () + assert camera.max_angle_deg == pytest.approx(90.0) + # Equidistant: the angle off the optical axis grows linearly with image radius. + for radius in (50.0, 150.0, 310.0): + assert ray_angle_deg(camera, (319.5 + radius, 319.5)) == pytest.approx(math.degrees(radius / focal), rel=1e-6) + fov, _ = sampling_geometry(cfg) + assert fov == pytest.approx(math.degrees(640 / focal), rel=1e-6) + + +def test_explicit_calibration_wins_over_the_spawn() -> None: + cfg = make_cfg(spawn=PinholeCameraCfg(), camera_calibration=CALIBRATION) + assert camera_model(cfg).intrinsics == CALIBRATION["intrinsics"] + # A prim without spawn configuration needs a calibration. + assert camera_model(make_cfg(spawn=None, camera_calibration=CALIBRATION)).image_size == (480, 640) + + +@pytest.mark.parametrize( + ("spawn", "message"), + [ + (None, "camera_calibration"), + (FisheyeCameraCfg(), "OpenCvFisheyeDistortionCfg"), + (PinholeCameraCfg(horizontal_aperture_offset=1.0), "Aperture offsets"), + ( + PinholeCameraCfg( + distortion=OpenCvPinholeDistortionCfg(fx=1.0, fy=1.0, cx=1.0, cy=1.0, image_size=(4, 4), s1=0.1) + ), + "Thin-prism", + ), + ], +) +def test_cameras_fovi_cannot_model_are_rejected(spawn, message: str) -> None: + with pytest.raises(ValueError, match=message): + camera_model(make_cfg(spawn=spawn)) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index 1745ecff0150..efae8b4e8817 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -45,8 +45,24 @@ # The physical camera the retina looks through: a 640x480 pinhole. WIDTH, HEIGHT = 640, 480 FOCAL, CX, CY = 550.0, 319.5, 239.5 +CLIPPING_RANGE = (0.001, 20.0) CALIBRATION = {"model": "pinhole", "image_size": (HEIGHT, WIDTH), "intrinsics": (FOCAL, FOCAL, CX, CY)} +# The same camera given in either supported way: as a fovi calibration, or as the spawned camera's +# OpenCV model, from which the foveated camera derives its calibration. +CAMERA_SOURCES = { + "calibration": dict(camera_calibration=CALIBRATION), + "spawn": dict( + camera_calibration=None, + spawn=sim_utils.PinholeCameraCfg( + clipping_range=CLIPPING_RANGE, + distortion=sim_utils.OpenCvPinholeDistortionCfg( + fx=FOCAL, fy=FOCAL, cx=CX, cy=CY, image_size=(WIDTH, HEIGHT) + ), + ), + ), +} + # The camera looks down at the ground plane; its optical axis meets the ground at the target. CAM_EYE = (0.0, 0.0, 2.5) CAM_TARGET = (1.75, 0.0, 0.0) @@ -75,7 +91,7 @@ class _GroundSceneCfg(InteractiveSceneCfg): prim_path="{ENV_REGEX_NS}/Camera", update_period=0.0, data_types=["distance_to_camera"], - spawn=sim_utils.PinholeCameraCfg(clipping_range=(0.001, 20.0)), + spawn=sim_utils.PinholeCameraCfg(clipping_range=CLIPPING_RANGE), camera_calibration=CALIBRATION, foveated_res=RESOLUTION, mask_to_sensor_fov=True, @@ -131,8 +147,9 @@ def _render(backend: str, fixation: torch.Tensor, **camera_overrides) -> tuple[t return distance, field +@pytest.mark.parametrize("source", CAMERA_SOURCES) @pytest.mark.parametrize("backend", BACKENDS) -def test_foveated_camera_follows_calibrated_gaze(backend): +def test_foveated_camera_follows_calibrated_gaze(backend, source): """The retina's centre sees the ground along the pinhole ray through the fixated pixel. One environment fixates the image centre and one a point to the right. The reference is the @@ -140,7 +157,7 @@ def test_foveated_camera_follows_calibrated_gaze(backend): """ # Fixations are normalized (row, column) positions in the calibrated image. fixation = torch.tensor([[0.5, 0.5], [0.5, 0.75]]) - distance, field = _render(backend, fixation) + distance, field = _render(backend, fixation, **CAMERA_SOURCES[source]) assert distance.shape == (2, RESOLUTION, RESOLUTION) assert torch.isfinite(distance).all() diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py index 2a9faae9d3a9..83e669eae964 100644 --- a/source/isaaclab_fovi/test/test_native_grid.py +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -24,8 +24,8 @@ ) -def make_coords(field: str, resolution: int = 64, coverage: str = "circular") -> SamplingCoords: - fov = (80.0 if coverage == "wang" else 170.0) if field == "spherical" else 1.0 +def make_coords(resolution: int = 64, coverage: str = "circular", field: str = "spherical") -> SamplingCoords: + fov = 80.0 if coverage == "wang" else 170.0 return SamplingCoords( fov=fov, cmf_a=0.036021 * fov, @@ -37,14 +37,13 @@ def make_coords(field: str, resolution: int = 64, coverage: str = "circular") -> ) -@pytest.mark.parametrize("field", ["planar", "spherical"]) @pytest.mark.parametrize("resolution", [64, 128]) @pytest.mark.parametrize("rotation", [0.0, 180.0, 37.0]) @pytest.mark.parametrize("coverage", ["circular", "square", "wang"]) -def test_analytic_inverse_returns_every_native_texel(field, resolution, rotation, coverage): - coords = make_coords(field, resolution, coverage) - rays = native_grid_directions(coords, tangent_scale=0.7, image_rotation_deg=rotation) - uv, valid = native_grid_exit_uv(rays, coords, tangent_scale=0.7, image_rotation_deg=rotation) +def test_analytic_inverse_returns_every_native_texel(resolution, rotation, coverage): + coords = make_coords(resolution, coverage) + rays = native_grid_directions(coords, image_rotation_deg=rotation) + uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) axis = (torch.arange(resolution) + 0.5) / resolution row, col = torch.meshgrid(axis, axis, indexing="ij") expected = torch.stack((col, row), -1).reshape(-1, 2) @@ -57,33 +56,18 @@ def test_analytic_inverse_returns_every_native_texel(field, resolution, rotation def test_spherical_valid_samples_match_calibrated_software_rays(coverage): from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions - coords = make_coords("spherical", coverage=coverage) - actual = native_grid_directions(coords, tangent_scale=0.7) + coords = make_coords(coverage=coverage) + actual = native_grid_directions(coords) expected = retinal_directions(coords.cartesian[coords.valid_mask], coords.fov) torch.testing.assert_close(actual[coords.valid_mask], expected, atol=3e-7, rtol=0) -def test_planar_equidistant_preserves_lens_projection(): - from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions - - coords = make_coords("planar") - rays = native_grid_directions( - coords, - tangent_scale=0.7, - projection="fisheye_equidistant", - camera_fov_rad=math.radians(150), - ) - expected = retinal_directions(coords.cartesian[coords.valid_mask], 150) - torch.testing.assert_close(rays[coords.valid_mask], expected, atol=3e-7, rtol=0) - uv, valid = native_grid_exit_uv( - rays, - coords, - tangent_scale=0.7, - projection="fisheye_equidistant", - camera_fov_rad=math.radians(150), - ) - torch.testing.assert_close(uv, (coords.cortical.flip(-1) + 1) / 2, atol=2e-6, rtol=0) - assert valid.all() +def test_planar_coordinates_are_rejected(): + coords = make_coords(16, field="planar") + with pytest.raises(ValueError, match="spherical"): + native_grid_directions(coords) + with pytest.raises(ValueError, match="spherical"): + native_grid_exit_uv(torch.tensor([[0.0, 0.0, -1.0]]), coords) def test_spherical_padding_matches_rim_slope_and_does_not_wrap(): @@ -98,11 +82,10 @@ def test_spherical_padding_matches_rim_slope_and_does_not_wrap(): torch.testing.assert_close(unbounded_angular_radius(angles, half_fov), radius, atol=1e-10, rtol=0) -@pytest.mark.parametrize("field", ["planar", "spherical"]) -def test_direction_texture_is_native_rays_without_assignment(field): - coords = make_coords(field, 64) - direction, inverse = build_native_grid_textures(coords, tangent_scale=0.7, image_rotation_deg=0, exit_size=256) - expected = native_grid_directions(coords, tangent_scale=0.7) +def test_direction_texture_is_native_rays_without_assignment(): + coords = make_coords(64) + direction, inverse = build_native_grid_textures(coords, image_rotation_deg=0, exit_size=256) + expected = native_grid_directions(coords) torch.testing.assert_close(direction.reshape(-1, 3), expected, atol=0, rtol=0) assert direction.shape == (64, 64, 3) assert inverse.shape == (256, 256, 2) @@ -111,7 +94,7 @@ def test_direction_texture_is_native_rays_without_assignment(field): def test_upright_grid_masks_and_channel_aliases(): - coords = make_coords("planar", 16) + coords = make_coords(16) # Coordinate channels make rotation/transposition failures observable. values = torch.cat((coords.cartesian, torch.ones(len(coords), 2)), -1)[None, :, None] source = {"rgba": values.clone(), "rgb": values[..., :3]} @@ -133,7 +116,7 @@ def test_upright_grid_masks_and_channel_aliases(): def test_output_permutation_preserves_dtype_and_captures(dtype, channels, device): if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA required") - coords = make_coords("planar", 16).to(device=device) + coords = make_coords(16).to(device=device) source = { "value": torch.arange(3 * len(coords) * channels, device=device).to(dtype).reshape(3, len(coords), 1, channels) } diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 0e4696de5d00..f2fa4f52d246 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -50,7 +50,7 @@ def test_pooled_allocation_accepts_proxy_arrays_and_preserves_render_buffers() - @pytest.mark.parametrize("pooled", [False, True]) def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatch, pooled) -> None: - coords = SamplingCoords(1.0, 0.036021, 16, style="warped_cartesian_as_grid", device="cpu") + coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") highres = coords.clone(resolution=32) if pooled else None ray_coords = highres if pooled else coords pooler = torch.nn.AdaptiveAvgPool1d(len(coords)) if pooled else None @@ -90,8 +90,6 @@ def render(camera, env_mask): camera._view = None camera._renderer = None camera._device = "cpu" - camera._spawn_horizontal_aperture = 1.0 - camera._spawn_focal_length = 1.0 camera.cfg = SimpleNamespace( foveated_style="warped_cartesian_as_grid", mask_to_sensor_fov=False, @@ -100,7 +98,6 @@ def render(camera, env_mask): pool_mode="avg", pool_int_mode="avg", pool_sample_cortex=False, - field_geometry="planar", image_rotation_deg=0, data_types=["rgba", "rgb"], renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index b8f56722af30..c4560932f3ed 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -6,7 +6,6 @@ """Dual-grid geometry and modality-specific pooling without a simulator.""" from dataclasses import dataclass, field -from types import SimpleNamespace import pytest import torch @@ -20,15 +19,16 @@ pool_hwc_buffer, ) +from isaaclab.sim import PinholeCameraCfg + @dataclass class SamplingConfig: """Sampling fields consumed by the shared pooling helpers.""" - # A 90 degree planar window (focal length 1, aperture 2) with a CMF constant of a tenth of it. + # A 90 degree pinhole window (focal length 1, aperture 2) with a CMF constant of a tenth of it. cmf_a_deg: float = 9.0 - spawn: SimpleNamespace = field(default_factory=lambda: SimpleNamespace(focal_length=1.0, horizontal_aperture=2.0)) - field_geometry: str = "planar" + spawn: PinholeCameraCfg = field(default_factory=lambda: PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0)) camera_calibration: dict[str, str | tuple[int, int] | tuple[float, ...]] | None = None retinal_window_reference_side: str = "short" retinal_window_short_side_fraction: float = 1.0 @@ -126,7 +126,6 @@ def test_native_grid_pooling_excludes_invalid_photoreceptors(mode, sample_cortex "style,expected", [ ("warped_cartesian_as_grid", GridPoolingLayer), - ("logpolar_as_grid", GridPoolingLayer), ("warped_cartesian", KNNPoolingLayer), ], ) @@ -141,22 +140,3 @@ def test_native_grid_default_kernel_matches_deployment(style: str, expected: typ pooler, resolved_k = build_pooler(cfg, lowres, highres, "cpu") assert resolved_k == 4 assert isinstance(pooler, expected) - - -def test_logpolar_grid_pooling_wraps_the_angular_boundary() -> None: - cfg = SamplingConfig(foveated_style="logpolar_as_grid", pool_k=9) - lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") - pooler, _ = build_pooler(cfg, lowres, highres, "cpu") - assert highres.valid_mask.all() - # Log-polar grids are angle x eccentricity; light only the last angle row. - values = torch.zeros(highres.resolution, highres.resolution) - values[-1] = 1.0 - result = pool_hwc_buffer(pooler, values.reshape(1, -1, 1, 1))[0, :, 0, 0] - pooled = lowres.as_grid(result) - # 3x3 windows centered on high-res angles 2i span 2i-1..2i+1, so the last - # row reaches output angle 0 only by wrapping, and the last output angle. - expected = torch.zeros_like(pooled) - expected[0] = 1 / 3 - expected[-1] = 1 / 3 - torch.testing.assert_close(pooled, expected) diff --git a/source/isaaclab_fovi/test/test_rays.py b/source/isaaclab_fovi/test/test_rays.py index af5e3fe55bdf..76ea397bdff2 100644 --- a/source/isaaclab_fovi/test/test_rays.py +++ b/source/isaaclab_fovi/test/test_rays.py @@ -5,15 +5,10 @@ """CPU tests of sensor ray layout and the fixed optical center.""" -import math - import pytest import torch import warp as wp -from isaaclab_fovi.sensors.foveated_rays import ( - compute_explicit_ray_array, - compute_foveated_ray_array, -) +from isaaclab_fovi.sensors.foveated_rays import compute_explicit_ray_array @pytest.fixture(scope="module", autouse=True) @@ -21,33 +16,14 @@ def initialize_warp() -> None: wp.init() -@pytest.mark.parametrize("projection", ["pinhole", "fisheye_equidistant"]) -def test_ray_layout_and_projection(projection: str) -> None: - coordinates = torch.tensor([[0.0, 0.0], [1.0, 0.0], [0.0, -0.5], [-0.4, 0.3]]) - field_of_view = math.radians(90.0) - rays = compute_foveated_ray_array(coordinates, field_of_view, "cpu", projection) - actual = wp.to_torch(rays)[0, :, 0] - - assert rays.shape == (1, 4, 1, 2) - assert rays.dtype == wp.vec3f - torch.testing.assert_close(actual[:, 0], torch.zeros(4, 3)) - torch.testing.assert_close(actual[:, 1].norm(dim=-1), torch.ones(4)) - torch.testing.assert_close(actual[0, 1], torch.tensor([0.0, 0.0, -1.0])) - if projection == "pinhole": - expected = torch.cat((coordinates, -torch.ones(4, 1)), dim=-1) - expected = torch.nn.functional.normalize(expected, dim=-1) - torch.testing.assert_close(actual[:, 1], expected) - else: - # Equidistant projection maps eccentricity linearly to optical-axis angle. - actual_angle = torch.acos(-actual[:, 1, 2]) - torch.testing.assert_close(actual_angle, coordinates.norm(dim=-1) * field_of_view / 2) - - def test_explicit_rays_preserve_sample_order_and_optical_center() -> None: directions = torch.nn.functional.normalize( torch.tensor([[0.7, 0.3, -1.0], [-0.2, 0.6, -1.0], [0.0, 0.0, -1.0]]), dim=-1 ) - rays = wp.to_torch(compute_explicit_ray_array(directions, device="cpu"))[0, :, 0] + rays = compute_explicit_ray_array(directions, device="cpu") + assert rays.shape == (1, 3, 1, 2) + assert rays.dtype == wp.vec3f + rays = wp.to_torch(rays)[0, :, 0] torch.testing.assert_close(rays[:, 0], torch.zeros_like(directions)) torch.testing.assert_close(rays[:, 1], directions) @@ -55,8 +31,3 @@ def test_explicit_rays_preserve_sample_order_and_optical_center() -> None: def test_explicit_rays_reject_invalid_dimensions() -> None: with pytest.raises(ValueError, match="shape"): compute_explicit_ray_array(torch.zeros(3, 2), device="cpu") - - -def test_unknown_projection_fails() -> None: - with pytest.raises(ValueError, match="Unknown projection"): - compute_foveated_ray_array(torch.zeros(1, 2), 1.0, "cpu", "unknown") diff --git a/source/isaaclab_fovi/test/test_rtx_layout.py b/source/isaaclab_fovi/test/test_rtx_layout.py deleted file mode 100644 index 61d0644e867d..000000000000 --- a/source/isaaclab_fovi/test/test_rtx_layout.py +++ /dev/null @@ -1,21 +0,0 @@ -# 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 - -"""Configuration defaults and validation of the foveated camera.""" - -import pytest -from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg - - -def test_defaults_are_spherical_grid_sampling_at_the_human_cmf_estimate() -> None: - cfg = FoveatedCameraCfg() - assert cfg.field_geometry == "spherical" - assert cfg.foveated_style == "warped_cartesian_as_grid" - assert cfg.cmf_a_deg == 0.591 - - -def test_unknown_field_geometry_is_rejected() -> None: - with pytest.raises(ValueError, match="field_geometry"): - FoveatedCameraCfg(field_geometry="legacy") diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 9e2222d7140c..6643f3a401e9 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -38,7 +38,6 @@ def tf32_enabled(): def camera_config() -> SimpleNamespace: camera = CameraModel("fisheye", (80, 120), (55, 55, 59.5, 39.5), (0.02, -0.003, 0, 0)) return SimpleNamespace( - field_geometry="spherical", camera_calibration=asdict(camera), cmf_a_deg=2.5, spawn=None, diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 93eb5481d4fa..ff99dd39fe23 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -22,8 +22,8 @@ ) -def make_coords(field: str, res: int = 16) -> SamplingCoords: - fov = 170.0 if field == "spherical" else 1.0 +def make_coords(res: int = 16) -> SamplingCoords: + fov = 170.0 return SamplingCoords( fov, 0.036021 * fov, @@ -31,24 +31,16 @@ def make_coords(field: str, res: int = 16) -> SamplingCoords: style="warped_cartesian_as_grid", fov_type="square", radius_norm=math.inf, - field_geometry=field, + field_geometry="spherical", ) -@pytest.mark.parametrize("field", ["planar", "spherical"]) -@pytest.mark.parametrize("projection", ["pinhole", "fisheye_equidistant"]) @pytest.mark.parametrize("rotation", [0.0, 37.0, 180.0]) @pytest.mark.parametrize("res", [1, 15, 64]) -def test_every_texel_roundtrips(field: str, projection: str, rotation: float, res: int) -> None: - coords = make_coords(field, res) - kwargs = dict( - tangent_scale=0.7, - image_rotation_deg=rotation, - projection=projection, - camera_fov_rad=math.radians(150), - ) - rays = native_grid_directions(coords, **kwargs) - uv, visible = native_grid_exit_uv(rays, coords, **kwargs) +def test_every_texel_roundtrips(rotation: float, res: int) -> None: + coords = make_coords(res) + rays = native_grid_directions(coords, image_rotation_deg=rotation) + uv, visible = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) axis = (torch.arange(res) + 0.5) / res row, col = torch.meshgrid(axis, axis, indexing="ij") expected = torch.stack((col, row), -1).reshape(-1, 2) @@ -57,11 +49,10 @@ def test_every_texel_roundtrips(field: str, projection: str, rotation: float, re torch.testing.assert_close(rays.norm(dim=-1), torch.ones(len(coords)), atol=1e-6, rtol=0) -@pytest.mark.parametrize("field", ["planar", "spherical"]) -def test_textures_and_public_modalities(field: str) -> None: - coords = make_coords(field) - directions, inverse = build_native_grid_textures(coords, tangent_scale=0.7, image_rotation_deg=0, exit_size=64) - torch.testing.assert_close(directions.reshape(-1, 3), native_grid_directions(coords, tangent_scale=0.7)) +def test_textures_and_public_modalities() -> None: + coords = make_coords() + directions, inverse = build_native_grid_textures(coords, image_rotation_deg=0, exit_size=64) + torch.testing.assert_close(directions.reshape(-1, 3), native_grid_directions(coords)) assert torch.isfinite(inverse).all() assert (inverse == -1).any() assert grid_output_shape(coords) == (16, 16) @@ -103,7 +94,6 @@ def test_camera_pooling_preserves_square_shells(coverage: str) -> None: prim_path="/World/Camera", spawn=PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0), cmf_a_deg=9.0, - field_geometry="planar", foveated_style="warped_cartesian_as_grid", fov_type=coverage, radius_norm=math.inf, From 41d42efd89060add6517ce3a0f7627b0c137b09a Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:09:16 -0800 Subject: [PATCH 16/81] Reduce gaze to one angle setter and rename camera_calibration to camera_model Tasks drive the gaze through set_gaze_angles, (tilt, pan) in radians from the physical camera's optical axis; how a policy's actions map to those angles belongs to the task's action term. The image-position setter, the image-to-angle conversion and their compiled helpers had no callers outside tests and are removed. camera_model holds fovi CameraModel fields, the same ones fovi's software sampler takes on a real camera. The gaze mixin is now VirtualGaze, and internal names drop the calibrated prefix. --- source/isaaclab_fovi/docs/README.md | 22 ++-- source/isaaclab_fovi/docs/square_foveated.md | 4 +- .../isaaclab_fovi/examples/render_foveated.py | 10 +- .../isaaclab_fovi/isaaclab_fovi/__init__.py | 5 +- .../sensors/calibrated_geometry.py | 87 ++++---------- .../isaaclab_fovi/sensors/foveated_camera.py | 4 +- .../sensors/foveated_camera_cfg.py | 12 +- .../sensors/foveated_newton_camera.py | 16 +-- .../sensors/foveated_rtx_camera.py | 38 +++--- .../isaaclab_fovi/sensors/virtual_gaze.py | 78 ++++++------- .../test/test_calibrated_gaze_fusion.py | 48 -------- source/isaaclab_fovi/test/test_camera_cfg.py | 28 ++--- .../test/test_foveated_camera_render.py | 56 ++++----- .../isaaclab_fovi/test/test_newton_buffers.py | 2 +- source/isaaclab_fovi/test/test_pooling.py | 2 +- .../test/test_spherical_geometry.py | 108 +++++++++--------- 16 files changed, 207 insertions(+), 313 deletions(-) delete mode 100644 source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index e4033fb82796..c2022ab927de 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -43,9 +43,9 @@ With the default grid style the sensor publishes an upright image of shape The retina looks through a physical camera. It places its samples by visual angle inside that camera's field of view, and its rays are cast directly at -those angles, so no pinhole image is resampled. The physical camera sets the -retinal window, the image that fixations are given in, and the edge that -`mask_to_sensor_fov` masks against. +those angles, so no pinhole image is resampled. The retinal window spans the +physical camera's image, and `mask_to_sensor_fov` masks against its edge. On a +real camera, fovi's software sampler takes the same `camera_model` fields. By default it is the camera that `spawn` creates: @@ -64,11 +64,11 @@ By default it is the camera that `spawn` creates: ``` To describe any other calibrated camera, or a prim without spawn -configuration, set `camera_calibration` to +configuration, set `camera_model` to [`fovi.sensing.projection.CameraModel`](https://pypi.org/project/fovi/) fields: ```python -camera_calibration={ +camera_model={ "model": "pinhole", # or "fisheye" "image_size": (480, 640), # (height, width) "intrinsics": (550.0, 550.0, 319.5, 239.5), # fx, fy, cx, cy [px] @@ -89,15 +89,17 @@ env.scene.eye.cmf_a_deg=1000 ### Gaze -The fixation can move while the camera prim stays in place: +The retina can turn while the camera prim stays in place: ```python -# Normalized (row, column) position in the physical camera's image, shape (num_envs, 2). -camera.set_calibrated_fixation(fixation) -# Or mount angles (tilt, pan) in radians, shape (num_envs, 2). -camera.set_calibrated_angles(angles) +# (tilt, pan) [rad] from the physical camera's optical axis, shape (num_envs, 2). +# Positive tilt looks up and positive pan looks left. +camera.set_gaze_angles(angles) ``` +How a policy drives the gaze, for example as per-step changes normalized to +the retinal window, belongs to the task's action term. + Set `mask_to_sensor_fov=True` to zero the samples that fall outside the physical camera's image at the current gaze. diff --git a/source/isaaclab_fovi/docs/square_foveated.md b/source/isaaclab_fovi/docs/square_foveated.md index a3d9bb9f0977..41921e5f66d7 100644 --- a/source/isaaclab_fovi/docs/square_foveated.md +++ b/source/isaaclab_fovi/docs/square_foveated.md @@ -15,12 +15,12 @@ FoveatedCameraCfg( ``` `fovi` owns the concentric-square mapping and its analytic inverse. The lens -lookup textures and the calibrated gaze use that geometry. The published image +lookup textures and the gaze use that geometry. The published image is upright, `(num_envs, height, width, channels)`, and RGB, depth and segmentation keep their usual dtypes. No cell is masked by the sensor footprint. With `mask_to_sensor_fov=True`, -samples outside the calibrated camera's image are still zeroed. +samples outside the physical camera's image are still zeroed. The mode works in both field geometries. The grid keeps its two-dimensional topology; "square" refers to the region of the visual field the grid covers. diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index b60dfb4d00c9..1c1c03906b2f 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -7,7 +7,7 @@ Run with ``--backend newton`` or ``--backend rtx``. The retina looks through the spawned camera, an ideal pinhole or, with ``--lens fisheye``, an ideal -equidistant fisheye, and its fixation moves inside that camera's field of view. +equidistant fisheye, and its gaze moves inside that camera's field of view. ``--pool`` renders a denser photoreceptor grid and pools it to the output grid. """ @@ -40,7 +40,7 @@ def main() -> None: - """Render RGB of a static cube while the fixation moves.""" + """Render RGB of a static cube while the gaze moves.""" # Isaac Sim plugins must be available before importing simulator-bound types. import torch import warp as wp @@ -122,9 +122,9 @@ class SceneCfg(InteractiveSceneCfg): frame_seconds: list[float] = [] frames: list[torch.Tensor] = [] for step in range(args.steps): - # Fixation in normalized image coordinates (row, column) of the spawned camera. - fixation = torch.tensor([[0.5, (0.5, 0.58, 0.58, 0.5)[step % 4]]], device=sim.device) - camera.set_calibrated_fixation(fixation) + # Gaze (tilt, pan) [rad] from the optical axis: look ahead, then 8 degrees to the right. + pan = (0.0, -math.radians(8.0), -math.radians(8.0), 0.0)[step % 4] + camera.set_gaze_angles(torch.tensor([[0.0, pan]], device=sim.device)) wp.synchronize_device(sim.device) start = time.perf_counter() sim.step() diff --git a/source/isaaclab_fovi/isaaclab_fovi/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/__init__.py index a351f217fcb2..d2ea747c879c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/__init__.py +++ b/source/isaaclab_fovi/isaaclab_fovi/__init__.py @@ -3,9 +3,8 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Foveated rendering and binocular active cameras for Isaac Lab. +"""Foveated cameras for Isaac Lab. Import camera implementations from :mod:`isaaclab_fovi.sensors` after starting -the selected simulator runtime. Geometry and fixation helpers are available -without starting a simulator. +the selected simulator runtime. """ diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index 53c3614164b4..0eb4001d4c6c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Shared calibrated retinal geometry for rendering and image sampling.""" +"""Retinal geometry shared by rendering and image sampling: the physical camera and the gaze frame.""" from __future__ import annotations @@ -12,30 +12,24 @@ import torch import warp as wp -from fovi.sensing.projection import ( - CameraCalibration, - CameraModel, - angular_directions, - gaze_rotation, -) +from fovi.sensing.projection import CameraCalibration, CameraModel, angular_directions IDEAL_IMAGE_WIDTH = 1024 """Pixel width [px] of the image assigned to a camera derived from ideal spawn optics. -The scale is arbitrary: fixations are normalized image positions and the retinal -window is an angle, so neither depends on it.""" +The scale is arbitrary: the retinal window and the gaze are angles, so neither depends on it.""" class SamplingGeometryConfig(Protocol): - camera_calibration: CameraCalibration | None + camera_model: CameraCalibration | None cmf_a_deg: float retinal_window_reference_side: str retinal_window_short_side_fraction: float spawn: Any -def calibration_from_spawn(spawn: Any) -> CameraCalibration: - """Describe the camera that the spawn configuration creates as a fovi calibration. +def camera_model_from_spawn(spawn: Any) -> CameraCalibration: + """Describe the camera that the spawn configuration creates as :class:`CameraModel` fields. * An OpenCV model in ``spawn.distortion`` gives that calibrated camera. A fisheye model with zero coefficients is an ideal equidistant fisheye. @@ -58,7 +52,7 @@ def calibration_from_spawn(spawn: Any) -> CameraCalibration: coefficients = tuple(getattr(distortion, name) for name in ("k1", "k2", "p1", "p2", "k3", "k4", "k5", "k6")) thin_prism = (distortion.s1, distortion.s2, distortion.s3, distortion.s4) if distortion.apply_lens_distortion and any(thin_prism): - raise ValueError("Thin-prism distortion (s1-s4) is not supported; set camera_calibration instead.") + raise ValueError("Thin-prism distortion (s1-s4) is not supported; set camera_model instead.") else: raise ValueError(f"Unsupported lens distortion model {distortion.model!r}.") calibration.update(image_size=(height, width), intrinsics=tuple(float(value) for value in intrinsics)) @@ -68,10 +62,10 @@ def calibration_from_spawn(spawn: Any) -> CameraCalibration: if getattr(spawn, "projection_type", None) != "pinhole": raise ValueError( "Only pinhole spawn optics describe a camera; for a fisheye, set spawn.distortion to an " - "OpenCvFisheyeDistortionCfg or set camera_calibration." + "OpenCvFisheyeDistortionCfg or set camera_model." ) if spawn.horizontal_aperture_offset or spawn.vertical_aperture_offset: - raise ValueError("Aperture offsets are not supported; set camera_calibration instead.") + raise ValueError("Aperture offsets are not supported; set camera_model instead.") vertical_aperture = spawn.vertical_aperture or spawn.horizontal_aperture width = IDEAL_IMAGE_WIDTH height = round(width * vertical_aperture / spawn.horizontal_aperture) @@ -81,20 +75,20 @@ def calibration_from_spawn(spawn: Any) -> CameraCalibration: ) -def camera_model(cfg: SamplingGeometryConfig) -> CameraModel: +def resolve_camera_model(cfg: SamplingGeometryConfig) -> CameraModel: """Return the physical camera the retina looks through. - This is ``cfg.camera_calibration`` when set, otherwise the camera that ``cfg.spawn`` - creates (see :func:`calibration_from_spawn`). + This is ``cfg.camera_model`` when set, otherwise the camera that ``cfg.spawn`` + creates (see :func:`camera_model_from_spawn`). Raises: - ValueError: Neither a calibration nor spawn optics describe the camera. + ValueError: Neither ``cfg.camera_model`` nor ``cfg.spawn`` describes the camera. """ - if cfg.camera_calibration is not None: - return CameraModel(**cfg.camera_calibration) + if cfg.camera_model is not None: + return CameraModel(**cfg.camera_model) if cfg.spawn is None: - raise ValueError("A foveated camera on an existing prim needs camera_calibration.") - return CameraModel(**calibration_from_spawn(cfg.spawn)) + raise ValueError("A foveated camera on an existing prim needs camera_model.") + return CameraModel(**camera_model_from_spawn(cfg.spawn)) def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: @@ -103,7 +97,9 @@ def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: The field of view is the angular span of the retinal window in the physical camera. Both values are in the units :class:`fovi.sensing.coords.SamplingCoords` takes. """ - fov = camera_model(cfg).field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_short_side_fraction) + fov = resolve_camera_model(cfg).field_of_view( + cfg.retinal_window_reference_side, cfg.retinal_window_short_side_fraction + ) return fov, cfg.cmf_a_deg @@ -158,45 +154,6 @@ def convert_camera_frame_quaternion( return torch.stack(components, dim=-1) * 0.5 -def calibrated_fixation_rotation( - camera: CameraModel, fixation: torch.Tensor, convention: str = "pan_tilt" -) -> tuple[torch.Tensor, torch.Tensor]: - """Return source-camera rotation and validity for normalized image gaze.""" - if fixation.is_cuda: - return _compiled_fixation_rotation(camera, fixation, convention) - return _fixation_rotation(camera, fixation, convention) - - -def _fixation_rotation( - camera: CameraModel, fixation: torch.Tensor, convention: str -) -> tuple[torch.Tensor, torch.Tensor]: - h, w = camera.image_size - pixels = torch.stack((fixation[..., 1] * w - 0.5, fixation[..., 0] * h - 0.5), -1) - direction, valid = camera.unproject(pixels) - return gaze_rotation(direction, convention), valid - - -def calibrated_mount_angles(camera: CameraModel, fixation: torch.Tensor) -> torch.Tensor: - """Unproject normalized upright-image gaze to mount (tilt, pan) radians.""" - if fixation.is_cuda: - return _compiled_mount_angles(camera, fixation) - return _mount_angles(camera, fixation) - - -def _mount_angles(camera: CameraModel, fixation: torch.Tensor) -> torch.Tensor: - h, w = camera.image_size - pixels = torch.stack((fixation[..., 1] * w - 0.5, fixation[..., 0] * h - 0.5), -1) - direction, _ = camera.unproject(pixels) - x, y, z = direction.unbind(-1) - return torch.stack((-torch.atan2(y, torch.sqrt(x * x + z * z)), -torch.atan2(x, z)), -1) - - -# Fuse the lens inversion's iterative pointwise math instead of launching each -# small operation separately on every simulation tick. CPU callers stay eager. -_compiled_fixation_rotation = torch.compile(_fixation_rotation, fullgraph=True) -_compiled_mount_angles = torch.compile(_mount_angles, fullgraph=True) - - @wp.kernel(enable_backward=False) def _rotate_camera_rays( rays: wp.array(dtype=wp.vec3), @@ -235,7 +192,7 @@ def rotate_camera_rays(canonical_rays: torch.Tensor, rotation: torch.Tensor) -> return canonical_rays @ rotation.transpose(-1, -2) -def calibrated_visibility(camera: CameraModel, canonical_rays: torch.Tensor, rotation: torch.Tensor) -> torch.Tensor: - """Mask OpenCV-frame canonical rays against the fixed physical sensor.""" +def sensor_visibility(camera: CameraModel, canonical_rays: torch.Tensor, rotation: torch.Tensor) -> torch.Tensor: + """Mask OpenCV-frame canonical rays, turned by the gaze, against the fixed physical camera.""" _, valid = camera.project(rotate_camera_rays(canonical_rays, rotation)) return valid diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 5630a64748aa..fea0c639452b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -11,13 +11,13 @@ from isaaclab.sensors.camera.camera import Camera -from .virtual_gaze import CalibratedVirtualGaze +from .virtual_gaze import VirtualGaze if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg -class FoveatedCamera(CalibratedVirtualGaze, Camera): +class FoveatedCamera(VirtualGaze, Camera): """Camera that samples the scene on a foveated retina instead of a uniform pixel grid. The sample layout comes from :class:`fovi.sensing.coords.SamplingCoords`. Constructing this class returns the diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index f058f01a450b..75c1fbf86d74 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -40,18 +40,18 @@ class FoveatedCameraCfg(CameraCfg): of view gives nearly uniform sampling. The default is an estimate from human data. It is passed to :class:`fovi.sensing.coords.SamplingCoords` unchanged.""" - camera_calibration: CameraCalibration | None = None + camera_model: CameraCalibration | None = None """The physical camera the retina looks through, as :class:`fovi.sensing.projection.CameraModel` fields. - It defines the retinal window, the image that fixations are given in, and - the edge that :attr:`mask_to_sensor_fov` masks against. Any calibrated - pinhole or fisheye camera works. + The retinal window spans this camera's image, and :attr:`mask_to_sensor_fov` + masks against its edge. The same fields configure fovi's software sampler on + a real camera. If None, the camera that :attr:`spawn` creates is used: an OpenCV model in ``spawn.distortion`` (an :class:`~isaaclab.sim.OpenCvFisheyeDistortionCfg` with zero coefficients is an ideal equidistant fisheye), otherwise an ideal pinhole with the spawn's focal length and apertures. A prim without spawn - configuration needs a calibration.""" + configuration needs a camera model.""" foveated_res: int = 60 """Resolution parameter passed to :class:`SamplingCoords`. For isotropic @@ -162,7 +162,7 @@ class labels and breaks downstream integer/equality checks, so these width: int = 1 height: int = 1 - # Enable per-frame pose updates so fixation rotation is applied each step. + # Enable per-frame pose updates so the gaze rotation is applied each step. update_latest_camera_pose: bool = True def __post_init__(self): diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index cb11da5e819e..da39a6e9a933 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -76,7 +76,7 @@ class FoveatedNewtonCamera(FoveatedCamera): cfg: FoveatedCameraCfg def __init__(self, cfg: FoveatedCameraCfg): - self._calibrated_rotation = None + self._gaze_rotation = None super().__init__(cfg) # ------------------------------------------------------------------ @@ -138,7 +138,7 @@ def _initialize_impl(self): else: ray_coords_device = self._sampling_coords self._ray_coords = ray_coords_device - self._initialize_calibrated_gaze() + self._initialize_gaze() # 6. Build the pooler(s) on the sensor device. A second max-mode # pooler is materialised lazily below if any integer-valued outputs @@ -281,14 +281,14 @@ def _update_poses( env_mask: wp.array | None = None, frame_op: int = 0, ) -> None: - """Read base poses, apply the calibrated gaze, update renderer, inject rays. + """Read base poses, apply the gaze, update renderer, inject rays. The scene pose is read even without a gaze: the camera may inherit motion from a parent body. """ - # 1. Read base camera poses, then rotate them by the calibrated gaze if one is set. + # 1. Read base camera poses, then rotate them by the gaze if one is set. Camera._update_poses(self, env_ids, env_mask=env_mask, frame_op=frame_op) - self._apply_calibrated_pose(env_ids, env_mask) + self._apply_gaze_pose(env_ids, env_mask) # 2. Update camera_transforms # The renderer maintains persistent transform buffers and updates @@ -347,12 +347,12 @@ def _update_buffers_impl(self, env_mask: wp.array): self._data.output.update(self._public_output) def _apply_sensor_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: - """Zero the samples that fall outside the calibrated camera at the current gaze.""" + """Zero the samples that fall outside the physical camera at the current gaze.""" if not self.cfg.mask_to_sensor_fov: return first_output = next(iter(outputs.values())) first_tensor = first_output.torch if hasattr(first_output, "torch") else first_output - valid = self._calibrated_validity(first_tensor.shape[0]) + valid = self._gaze_validity(first_tensor.shape[0]) invalid = ~valid[:, :, None, None] has_rgba_alias = "rgba" in outputs for name, output in outputs.items(): @@ -384,5 +384,5 @@ def num_valid_samples(self) -> int: @property def sensor_fov_valid_fraction(self) -> torch.Tensor | None: - """Per-environment fraction of samples inside the calibrated camera, or None before the first masked frame.""" + """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" return getattr(self, "_sensor_fov_valid_fraction", None) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index d897ae196215..026633c0b849 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -89,7 +89,7 @@ def renderer(self) -> BaseRenderer: return self._renderer def __init__(self, cfg: FoveatedCameraCfg): - self._calibrated_rotation = None + self._gaze_rotation = None # Texture buffers are owned by the parent ``Camera`` (allocated in # ``_create_buffers`` and bound to the renderer via ``set_outputs``). # Foveated / pooled buffers are allocated in ``_initialize_impl`` @@ -265,9 +265,9 @@ def _initialize_impl(self) -> None: if self._sampling_coords_highres is not None: self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) self._ray_coords = self._sampling_coords_highres or self._sampling_coords - self._initialize_calibrated_gaze() + self._initialize_gaze() _, local_orientation = self._view.get_local_poses() - self._calibrated_base_local_orientation = matrix_from_quat(local_orientation.torch).clone() + self._base_local_orientation = matrix_from_quat(local_orientation.torch).clone() # Build the pooler on the sensor device (so knn tensors live there). # A second max-mode pooler is built inside ``_allocate_foveated_buffers`` @@ -364,29 +364,19 @@ def _allocate_foveated_buffers(self): # Per-frame overrides # ------------------------------------------------------------------ - def set_calibrated_fixation(self, fixation: torch.Tensor, env_ids: torch.Tensor | None = None) -> None: - super().set_calibrated_fixation(fixation, env_ids=env_ids) - self._write_calibrated_local_pose(env_ids) + def set_gaze_angles(self, angles: torch.Tensor) -> None: + super().set_gaze_angles(angles) + self._write_gaze_local_pose() - def set_calibrated_angles(self, angles: torch.Tensor) -> None: - super().set_calibrated_angles(angles) - self._write_calibrated_local_pose() - - def _write_calibrated_local_pose(self, env_ids: torch.Tensor | None = None) -> None: + def _write_gaze_local_pose(self) -> None: # Replicator reads camera prims, not update_camera's pose arguments. # Write when the command arrives, before a visualizer can render the step. # The saved local base prevents accumulation and preserves parent motion. - basis = self._calibrated_basis + basis = self._gaze_basis with torch.autocast(basis.device.type, enabled=False): - relative = compose_rotations(compose_rotations(basis, self._calibrated_rotation), basis.T) - local_orientation = quat_from_matrix(compose_rotations(self._calibrated_base_local_orientation, relative)) - if env_ids is None: - self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f)) - else: - self._view.set_local_poses( - orientations=wp.from_torch(local_orientation[env_ids].contiguous(), dtype=wp.vec4f), - indices=wp.from_torch(env_ids.to(dtype=torch.int32).contiguous()), - ) + relative = compose_rotations(compose_rotations(basis, self._gaze_rotation), basis.T) + local_orientation = quat_from_matrix(compose_rotations(self._base_local_orientation, relative)) + self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f)) def _update_buffers_impl(self, env_mask: wp.array): if not self._env_mask_has_any(env_mask): @@ -452,11 +442,11 @@ def _extract_foveated_samples(self): self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] def _apply_sensor_fov_mask(self) -> None: - """Zero the samples that fall outside the calibrated camera at the current gaze.""" + """Zero the samples that fall outside the physical camera at the current gaze.""" if not self.cfg.mask_to_sensor_fov: return batch_size = next(iter(self._foveated_output.values())).shape[0] - valid = self._calibrated_validity(batch_size) + valid = self._gaze_validity(batch_size) invalid = ~valid[:, :, None, None] has_rgba_alias = "rgba" in self._foveated_output for name, output in self._foveated_output.items(): @@ -487,5 +477,5 @@ def num_valid_samples(self) -> int: @property def sensor_fov_valid_fraction(self) -> torch.Tensor | None: - """Per-environment fraction of samples inside the calibrated camera, or None before the first masked frame.""" + """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" return getattr(self, "_sensor_fov_valid_fraction", None) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index 49f922840539..ad4bb8166e7b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Virtual gaze with a static physical camera and a static rendering ray bundle.""" +"""Virtual gaze: the retina turns inside a fixed physical camera.""" from __future__ import annotations @@ -17,61 +17,48 @@ from isaaclab.utils.math import matrix_from_quat, quat_from_matrix from .calibrated_geometry import ( - calibrated_fixation_rotation, - calibrated_mount_angles, - calibrated_visibility, - camera_model, compose_rotations, convert_camera_frame_quaternion, + resolve_camera_model, + sensor_visibility, ) from .native_grid import GRID_STYLE, native_grid_directions -class CalibratedVirtualGaze: - """Calibrated virtual-gaze operations shared by the foveated camera backends.""" +class VirtualGaze: + """Gaze shared by the foveated camera backends. - def calibrated_fov_sample_mask(self) -> torch.Tensor: - """Return the physical-sensor visibility mask in canonical ray order (B,N).""" - if self._calibrated_rotation is None: - raise RuntimeError("Set calibrated gaze before requesting its physical-FoV mask") - return self._calibrated_validity(len(self._calibrated_rotation)) + The camera prim stays where the scene puts it. Gaze turns the retina relative + to the optical axis of the physical camera it looks through. + """ - def set_calibrated_fixation(self, fixation: torch.Tensor, env_ids: torch.Tensor | None = None) -> None: - """Set full-batch image fixation, optionally changing only selected environments.""" - with torch.autocast(fixation.device.type, enabled=False): - rotation, _ = calibrated_fixation_rotation(self._calibrated_camera, fixation.float()) - if env_ids is None: - self._calibrated_rotation = rotation - else: - if self._calibrated_rotation is None: - self._calibrated_rotation = self._calibrated_identity.expand_as(rotation).clone() - self._calibrated_rotation[env_ids] = rotation[env_ids] + def set_gaze_angles(self, angles: torch.Tensor) -> None: + """Turn the retina to (tilt, pan) [rad] from the physical camera's optical axis. - def calibrated_mount_angles(self, fixation: torch.Tensor) -> torch.Tensor: - """Convert upright image gaze to mount (tilt, pan) radians.""" - with torch.autocast(fixation.device.type, enabled=False): - return calibrated_mount_angles(self._calibrated_camera, fixation.float()) + Positive tilt looks up and positive pan looks left. Zero looks along the + optical axis. - def set_calibrated_angles(self, angles: torch.Tensor) -> None: - """Set virtual gaze from the mount's (tilt, pan) radians.""" + Args: + angles: Gaze angles for every environment, shape (num_envs, 2). + """ # Geometry must remain float32 even when the policy runs under AMP. with torch.autocast(angles.device.type, enabled=False): tilt, pan = angles.float().unbind(-1) direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) - self._calibrated_rotation = gaze_rotation(direction, "pan_tilt") + self._gaze_rotation = gaze_rotation(direction, "pan_tilt") - def _apply_calibrated_pose( + def _apply_gaze_pose( self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None ) -> None: - if self._calibrated_rotation is None: + if self._gaze_rotation is None: return stored = self._data.quat_w_world quat = stored.torch if hasattr(stored, "torch") else stored with torch.autocast(quat.device.type, enabled=False): base = convert_camera_frame_quaternion(quat, origin="world", target="opengl") - # Calibration uses the upright image frame; rays include mount roll. - basis = self._calibrated_basis - relative = compose_rotations(compose_rotations(basis, self._calibrated_rotation), basis.T) + # Gaze is defined in the upright image frame; rays include mount roll. + basis = self._gaze_basis + relative = compose_rotations(compose_rotations(basis, self._gaze_rotation), basis.T) composed = quat_from_matrix(compose_rotations(matrix_from_quat(base), relative)) updated = convert_camera_frame_quaternion(composed, origin="opengl", target="world") if env_mask is not None: @@ -82,23 +69,24 @@ def _apply_calibrated_pose( else: quat.copy_(updated) - def _calibrated_validity(self, batch_size: int) -> torch.Tensor: - rays = self._calibrated_rays + def _gaze_validity(self, batch_size: int) -> torch.Tensor: + """Return which samples the physical camera sees at the current gaze, shape (batch_size, num_samples).""" + rays = self._gaze_rays with torch.autocast(rays.device.type, enabled=False): - rotation = self._calibrated_rotation + rotation = self._gaze_rotation if rotation is None: - rotation = self._calibrated_identity.expand(batch_size, -1, -1) + rotation = self._gaze_identity.expand(batch_size, -1, -1) # A receptive field can overlap the sensor even when its center is outside it. - return calibrated_visibility(self._calibrated_camera, rays, rotation) + return sensor_visibility(self._camera_model, rays, rotation) - def _initialize_calibrated_gaze(self) -> None: - self._calibrated_camera = camera_model(self.cfg) + def _initialize_gaze(self) -> None: + self._camera_model = resolve_camera_model(self.cfg) coords = self._sampling_coords_highres or self._sampling_coords if coords.style == GRID_STYLE: - self._calibrated_rays = native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1)) + self._gaze_rays = native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1)) else: - self._calibrated_rays = angular_directions(coords.cartesian, coords.fov) - self._calibrated_identity = torch.eye(3, device=coords.device) + self._gaze_rays = angular_directions(coords.cartesian, coords.fov) + self._gaze_identity = torch.eye(3, device=coords.device) angle = math.radians(self.cfg.image_rotation_deg) c, s = math.cos(angle), math.sin(angle) - self._calibrated_basis = self._calibrated_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) + self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) diff --git a/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py b/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py deleted file mode 100644 index 80485813465f..000000000000 --- a/source/isaaclab_fovi/test/test_calibrated_gaze_fusion.py +++ /dev/null @@ -1,48 +0,0 @@ -# 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 - -"""CUDA gaze fusion agrees with eager geometry and reads live replay inputs.""" - -import pytest -import torch -from fovi.sensing.projection import CameraModel, gaze_rotation -from isaaclab_fovi.sensors.calibrated_geometry import ( - calibrated_fixation_rotation, - calibrated_mount_angles, -) - -pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA") - - -@pytest.mark.parametrize("projection", ["pinhole", "fisheye"]) -def test_calibrated_gaze_fusion_replay(projection: str) -> None: - distortion = (0.01, -0.003, 0.0002, -0.00001) - if projection == "pinhole": - distortion = (0.01, -0.003, 0.0002, -0.00001, 0.0001) - camera = CameraModel(projection, (120, 192), (72, 71, 96, 60), distortion) - axis = torch.linspace(-0.1, 1.1, 32, device="cuda") - fixation = torch.stack(torch.meshgrid(axis, axis, indexing="ij"), -1).reshape(-1, 2) - stream = torch.cuda.Stream() - stream.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(stream): - for _ in range(3): - calibrated_fixation_rotation(camera, fixation) - calibrated_mount_angles(camera, fixation) - torch.cuda.current_stream().wait_stream(stream) - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph, stream=stream): - rotation, valid = calibrated_fixation_rotation(camera, fixation) - angles = calibrated_mount_angles(camera, fixation) - - for delta in (0.0, 0.01, -0.02): - fixation.add_(delta) - graph.replay() - pixels = torch.stack((fixation[:, 1] * 192 - 0.5, fixation[:, 0] * 120 - 0.5), -1) - direction, expected_valid = camera.unproject(pixels) - x, y, z = direction.unbind(-1) - expected_angles = torch.stack((-torch.atan2(y, (x * x + z * z).sqrt()), -torch.atan2(x, z)), -1) - torch.testing.assert_close(rotation, gaze_rotation(direction, "pan_tilt"), atol=2e-6, rtol=2e-6) - torch.testing.assert_close(angles, expected_angles, atol=2e-6, rtol=2e-6) - assert torch.equal(valid, expected_valid) diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py index f08aef6ea5b0..0051183504a9 100644 --- a/source/isaaclab_fovi/test/test_camera_cfg.py +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -9,7 +9,7 @@ import pytest import torch -from isaaclab_fovi.sensors.calibrated_geometry import camera_model, sampling_geometry +from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab.sim import ( @@ -19,7 +19,7 @@ PinholeCameraCfg, ) -CALIBRATION = {"model": "pinhole", "image_size": (480, 640), "intrinsics": (550.0, 550.0, 319.5, 239.5)} +CAMERA_MODEL = {"model": "pinhole", "image_size": (480, 640), "intrinsics": (550.0, 550.0, 319.5, 239.5)} def make_cfg(**kwargs) -> FoveatedCameraCfg: @@ -37,7 +37,7 @@ def test_defaults_are_grid_sampling_at_the_human_cmf_estimate() -> None: cfg = FoveatedCameraCfg() assert cfg.foveated_style == "warped_cartesian_as_grid" assert cfg.cmf_a_deg == 0.591 - assert cfg.camera_calibration is None + assert cfg.camera_model is None def test_default_pinhole_spawn_describes_an_ideal_pinhole() -> None: @@ -46,7 +46,7 @@ def test_default_pinhole_spawn_describes_an_ideal_pinhole() -> None: expected = math.degrees(2 * math.atan(spawn.horizontal_aperture / (2 * spawn.focal_length))) assert fov == pytest.approx(expected, rel=1e-6) assert cmf_a == 0.591 - camera = camera_model(make_cfg(spawn=spawn)) + camera = resolve_camera_model(make_cfg(spawn=spawn)) assert camera.model == "pinhole" assert camera.distortion == () # Without a vertical aperture the image is square. @@ -64,7 +64,7 @@ def test_opencv_pinhole_spawn_gives_that_calibrated_camera() -> None: distortion = OpenCvPinholeDistortionCfg( fx=500.0, fy=510.0, cx=320.0, cy=240.0, image_size=(640, 480), k1=-0.1, k2=0.01, p1=0.001, k4=0.002 ) - camera = camera_model(make_cfg(spawn=PinholeCameraCfg(distortion=distortion))) + camera = resolve_camera_model(make_cfg(spawn=PinholeCameraCfg(distortion=distortion))) assert camera.model == "pinhole" # Isaac Lab sizes are (width, height); fovi's are (height, width). assert camera.image_size == (480, 640) @@ -72,7 +72,7 @@ def test_opencv_pinhole_spawn_gives_that_calibrated_camera() -> None: assert camera.distortion == (-0.1, 0.01, 0.001, 0.0, 0.0, 0.002, 0.0, 0.0) distortion.apply_lens_distortion = False - assert camera_model(make_cfg(spawn=PinholeCameraCfg(distortion=distortion))).distortion == () + assert resolve_camera_model(make_cfg(spawn=PinholeCameraCfg(distortion=distortion))).distortion == () def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> None: @@ -80,7 +80,7 @@ def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> No focal = 250.0 distortion = OpenCvFisheyeDistortionCfg(fx=focal, fy=focal, cx=319.5, cy=319.5, image_size=(640, 640)) cfg = make_cfg(spawn=PinholeCameraCfg(distortion=distortion)) - camera = camera_model(cfg) + camera = resolve_camera_model(cfg) assert camera.model == "fisheye" assert camera.distortion == () assert camera.max_angle_deg == pytest.approx(90.0) @@ -91,17 +91,17 @@ def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> No assert fov == pytest.approx(math.degrees(640 / focal), rel=1e-6) -def test_explicit_calibration_wins_over_the_spawn() -> None: - cfg = make_cfg(spawn=PinholeCameraCfg(), camera_calibration=CALIBRATION) - assert camera_model(cfg).intrinsics == CALIBRATION["intrinsics"] - # A prim without spawn configuration needs a calibration. - assert camera_model(make_cfg(spawn=None, camera_calibration=CALIBRATION)).image_size == (480, 640) +def test_explicit_camera_model_wins_over_the_spawn() -> None: + cfg = make_cfg(spawn=PinholeCameraCfg(), camera_model=CAMERA_MODEL) + assert resolve_camera_model(cfg).intrinsics == CAMERA_MODEL["intrinsics"] + # A prim without spawn configuration needs a camera model. + assert resolve_camera_model(make_cfg(spawn=None, camera_model=CAMERA_MODEL)).image_size == (480, 640) @pytest.mark.parametrize( ("spawn", "message"), [ - (None, "camera_calibration"), + (None, "camera_model"), (FisheyeCameraCfg(), "OpenCvFisheyeDistortionCfg"), (PinholeCameraCfg(horizontal_aperture_offset=1.0), "Aperture offsets"), ( @@ -114,4 +114,4 @@ def test_explicit_calibration_wins_over_the_spawn() -> None: ) def test_cameras_fovi_cannot_model_are_rejected(spawn, message: str) -> None: with pytest.raises(ValueError, match=message): - camera_model(make_cfg(spawn=spawn)) + resolve_camera_model(make_cfg(spawn=spawn)) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index efae8b4e8817..7f1d14a5f3b1 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -13,6 +13,8 @@ launch_test_simulation(enable_cameras=True) +import math + import numpy as np import pytest import torch @@ -46,14 +48,14 @@ WIDTH, HEIGHT = 640, 480 FOCAL, CX, CY = 550.0, 319.5, 239.5 CLIPPING_RANGE = (0.001, 20.0) -CALIBRATION = {"model": "pinhole", "image_size": (HEIGHT, WIDTH), "intrinsics": (FOCAL, FOCAL, CX, CY)} +CAMERA_MODEL = {"model": "pinhole", "image_size": (HEIGHT, WIDTH), "intrinsics": (FOCAL, FOCAL, CX, CY)} -# The same camera given in either supported way: as a fovi calibration, or as the spawned camera's -# OpenCV model, from which the foveated camera derives its calibration. +# The same camera given in either supported way: as fovi camera-model fields, or as the spawned +# camera's OpenCV model, from which the foveated camera derives them. CAMERA_SOURCES = { - "calibration": dict(camera_calibration=CALIBRATION), + "camera_model": dict(camera_model=CAMERA_MODEL), "spawn": dict( - camera_calibration=None, + camera_model=None, spawn=sim_utils.PinholeCameraCfg( clipping_range=CLIPPING_RANGE, distortion=sim_utils.OpenCvPinholeDistortionCfg( @@ -92,16 +94,16 @@ class _GroundSceneCfg(InteractiveSceneCfg): update_period=0.0, data_types=["distance_to_camera"], spawn=sim_utils.PinholeCameraCfg(clipping_range=CLIPPING_RANGE), - camera_calibration=CALIBRATION, + camera_model=CAMERA_MODEL, foveated_res=RESOLUTION, mask_to_sensor_fov=True, ) -def _ground_distance_through_pixel(u: float, v: float) -> float: - """Distance [m] from the camera to the ground along the pinhole ray through calibrated pixel ``(u, v)``.""" - ray_camera = np.array(((u - CX) / FOCAL, -(v - CY) / FOCAL, -1.0)) - ray_camera /= np.linalg.norm(ray_camera) +def _ground_distance_along_gaze(tilt: float, pan: float) -> float: + """Distance [m] from the camera to the ground along the gaze (tilt, pan) [rad]; up and left are positive.""" + # OpenGL camera frame: +X right, +Y up, looking along -Z. + ray_camera = np.array((-math.cos(tilt) * math.sin(pan), math.sin(tilt), -math.cos(tilt) * math.cos(pan))) eye = np.asarray(CAM_EYE) forward = np.asarray(CAM_TARGET) - eye z_axis = -forward / np.linalg.norm(forward) @@ -112,8 +114,8 @@ def _ground_distance_through_pixel(u: float, v: float) -> float: return float(-eye[2] / ray_world[2]) -def _render(backend: str, fixation: torch.Tensor, **camera_overrides) -> tuple[torch.Tensor, torch.Tensor]: - """Render ground distance for one environment per fixation row. +def _render(backend: str, gaze: torch.Tensor, **camera_overrides) -> tuple[torch.Tensor, torch.Tensor]: + """Render ground distance for one environment per row of gaze angles (tilt, pan) [rad]. Returns: The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid @@ -128,7 +130,7 @@ def _render(backend: str, fixation: torch.Tensor, **camera_overrides) -> tuple[t create_rotation_matrix_from_view(torch.tensor([CAM_EYE]), torch.tensor([CAM_TARGET]), up_axis="Z") )[0].tolist() ) - scene_cfg = _GroundSceneCfg(num_envs=len(fixation), env_spacing=20.0) + scene_cfg = _GroundSceneCfg(num_envs=len(gaze), env_spacing=20.0) scene_cfg.camera.renderer_cfg = renderer_cfg() scene_cfg.camera.offset = FoveatedCameraCfg.OffsetCfg(pos=CAM_EYE, rot=rot, convention="opengl") for name, value in camera_overrides.items(): @@ -137,7 +139,7 @@ def _render(backend: str, fixation: torch.Tensor, **camera_overrides) -> tuple[t camera: FoveatedCamera = scene["camera"] assert isinstance(camera, camera_class) sim.reset() - camera.set_calibrated_fixation(fixation.to(sim.device)) + camera.set_gaze_angles(gaze.to(sim.device)) for _ in range(WARMUP_STEPS): sim.step() camera.update(sim.get_physics_dt(), force_recompute=True) @@ -149,24 +151,22 @@ def _render(backend: str, fixation: torch.Tensor, **camera_overrides) -> tuple[t @pytest.mark.parametrize("source", CAMERA_SOURCES) @pytest.mark.parametrize("backend", BACKENDS) -def test_foveated_camera_follows_calibrated_gaze(backend, source): - """The retina's centre sees the ground along the pinhole ray through the fixated pixel. +def test_foveated_camera_follows_gaze(backend, source): + """The retina's centre sees the ground along the gaze direction. - One environment fixates the image centre and one a point to the right. The reference is the - analytic ground distance of the calibrated pinhole ray through each fixated pixel. + One environment looks along the optical axis and one 16 degrees to the right. The reference is + the analytic ground distance along each gaze direction. """ - # Fixations are normalized (row, column) positions in the calibrated image. - fixation = torch.tensor([[0.5, 0.5], [0.5, 0.75]]) - distance, field = _render(backend, fixation, **CAMERA_SOURCES[source]) + gaze = torch.tensor([[0.0, 0.0], [0.0, -math.radians(16.0)]]) + distance, field = _render(backend, gaze, **CAMERA_SOURCES[source]) assert distance.shape == (2, RESOLUTION, RESOLUTION) assert torch.isfinite(distance).all() # The grid cell closest to the centre of the visual field. row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) - for env, (row_fraction, column_fraction) in enumerate(fixation.tolist()): - expected = _ground_distance_through_pixel(column_fraction * WIDTH - 0.5, row_fraction * HEIGHT - 0.5) - assert float(distance[env, row, column]) == pytest.approx(expected, rel=0.01) + for env, (tilt, pan) in enumerate(gaze.tolist()): + assert float(distance[env, row, column]) == pytest.approx(_ground_distance_along_gaze(tilt, pan), rel=0.01) # The image is upright: the top looks farther along the ground than the bottom. centred = distance[0] @@ -179,7 +179,7 @@ def test_foveated_camera_follows_calibrated_gaze(backend, source): right = centred[:, RESOLUTION // 2 :][seen[:, RESOLUTION // 2 :]].mean() assert float(left) == pytest.approx(float(right), rel=0.01) - # Looking right moves part of the retina past the edge of the calibrated camera, and those samples are zeroed. + # Looking right moves part of the retina past the edge of the physical camera, and those samples are zeroed. assert (distance[1] == 0).sum() > (distance[0] == 0).sum() @@ -191,9 +191,9 @@ def central_to_edge_spacing(field: torch.Tensor) -> float: steps = field[RESOLUTION // 2, :, 0].diff() return float(steps[len(steps) // 2] / steps[-1]) - fixation = torch.tensor([[0.5, 0.5]]) - foveated_distance, foveated_field = _render(backend, fixation) - uniform_distance, uniform_field = _render(backend, fixation, cmf_a_deg=1000.0) + gaze = torch.zeros(1, 2) + foveated_distance, foveated_field = _render(backend, gaze) + uniform_distance, uniform_field = _render(backend, gaze, cmf_a_deg=1000.0) assert central_to_edge_spacing(foveated_field) < 0.2 assert central_to_edge_spacing(uniform_field) > 0.9 diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index f2fa4f52d246..0bf7a4ecf263 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -57,7 +57,7 @@ def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatc monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (pooler, 4)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_calibrated_gaze", lambda self: None) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", lambda self: None) def initialize_renderer(camera): # Newton launches image tiles; a vector-shaped width of one is not valid. diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index c4560932f3ed..2d7ad72713ec 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -29,7 +29,7 @@ class SamplingConfig: # A 90 degree pinhole window (focal length 1, aperture 2) with a CMF constant of a tenth of it. cmf_a_deg: float = 9.0 spawn: PinholeCameraCfg = field(default_factory=lambda: PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0)) - camera_calibration: dict[str, str | tuple[int, int] | tuple[float, ...]] | None = None + camera_model: dict[str, str | tuple[int, int] | tuple[float, ...]] | None = None retinal_window_reference_side: str = "short" retinal_window_short_side_fraction: float = 1.0 foveated_res: int = 8 diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 6643f3a401e9..1c9a0bc67c4f 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Shared rendering and software calibration contracts without launching a simulator.""" +"""Rendering, gaze and software-sampling contracts, without launching a simulator.""" from dataclasses import asdict from types import SimpleNamespace @@ -20,7 +20,7 @@ ) from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.pooling import build_lowres_coords -from isaaclab_fovi.sensors.virtual_gaze import CalibratedVirtualGaze +from isaaclab_fovi.sensors.virtual_gaze import VirtualGaze from isaaclab.utils.math import matrix_from_quat, quat_apply, quat_from_matrix @@ -38,7 +38,7 @@ def tf32_enabled(): def camera_config() -> SimpleNamespace: camera = CameraModel("fisheye", (80, 120), (55, 55, 59.5, 39.5), (0.02, -0.003, 0, 0)) return SimpleNamespace( - camera_calibration=asdict(camera), + camera_model=asdict(camera), cmf_a_deg=2.5, spawn=None, retinal_window_reference_side="long", @@ -55,7 +55,7 @@ def camera_config() -> SimpleNamespace: def test_rendering_and_software_sampling_share_window_and_nodes() -> None: cfg = camera_config() fov, a = sampling_geometry(cfg) - camera = CameraModel(**cfg.camera_calibration) + camera = CameraModel(**cfg.camera_model) assert fov == pytest.approx(camera.field_of_view("long", 0.75)) assert a == 2.5 coords, _ = build_lowres_coords(cfg, "cpu") @@ -74,46 +74,55 @@ def test_rendering_and_software_sampling_share_window_and_nodes() -> None: assert torch.isfinite(actual).all() -class GazeHarness(CalibratedVirtualGaze): +class GazeHarness(VirtualGaze): def __init__(self) -> None: self.cfg = camera_config() self._sampling_coords, _ = build_lowres_coords(self.cfg, "cpu") self._sampling_coords_highres = None - self._calibrated_rotation = None + self._gaze_rotation = None self._data = SimpleNamespace( quat_w_world=torch.tensor([[0.0, 0.0, 0.0, 1.0]]).repeat(2, 1), pos_w=torch.zeros(2, 3) ) - self._initialize_calibrated_gaze() + self._initialize_gaze() -@pytest.mark.parametrize("command", ["fixation", "angles"]) -@pytest.mark.parametrize("fixation", [(0.5, 1.0), (1.0, 0.5), (0.5, 1.01), (-0.01, 0.5)]) -def test_edge_gaze_preserves_visible_rays(command: str, fixation: tuple[float, float]) -> None: +def gaze_direction(angles: torch.Tensor) -> torch.Tensor: + """OpenCV camera-frame unit direction of (tilt, pan) gaze angles [rad]: up and left are positive.""" + tilt, pan = angles.unbind(-1) + return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + + +def angles_toward(camera: CameraModel, pixel: tuple[float, float]) -> torch.Tensor: + """(tilt, pan) gaze angles [rad] that look along the ray through a source pixel (x, y).""" + direction, _ = camera.unproject(torch.tensor([pixel])) + x, y, z = direction.unbind(-1) + return torch.stack((-torch.atan2(y, torch.sqrt(x * x + z * z)), -torch.atan2(x, z)), -1) + + +@pytest.mark.parametrize("pixel", [(119.5, 39.5), (59.5, 79.5), (120.5, 39.5), (59.5, -1.3)]) +def test_edge_gaze_preserves_visible_rays(pixel: tuple[float, float]) -> None: + """Looking at, or just past, an image edge keeps the part of the retina the camera still sees.""" camera = GazeHarness() - target = torch.tensor([fixation]) - if command == "fixation": - camera.set_calibrated_fixation(target) - else: - camera.set_calibrated_angles(camera.calibrated_mount_angles(target)) + camera.set_gaze_angles(angles_toward(camera._camera_model, pixel)) # An edge-centered receptive field straddles the physical sensor boundary. # Its visible part must survive even when the center lies outside the image. - valid = camera._calibrated_validity(1) + valid = camera._gaze_validity(1) assert valid.any() assert not valid.all() def test_gaze_away_from_sensor_masks_all_rays() -> None: camera = GazeHarness() - camera.set_calibrated_angles(torch.tensor([[0.0, torch.pi]])) - assert not camera._calibrated_validity(1).any() + camera.set_gaze_angles(torch.tensor([[0.0, torch.pi]])) + assert not camera._gaze_validity(1).any() @pytest.mark.parametrize("device", ["cpu", "cuda"]) @pytest.mark.parametrize("batch_size", [48, 256]) @pytest.mark.parametrize("autocast", [False, True]) @pytest.mark.parametrize("mode", ["spherical", "spherical_ids", "spherical_mask"]) -def test_calibrated_gaze_preserves_camera_rotation_with_tf32( +def test_gaze_preserves_camera_rotation_with_tf32( device: str, batch_size: int, autocast: bool, mode: str, tf32_enabled ) -> None: if device == "cuda" and not torch.cuda.is_available(): @@ -127,18 +136,18 @@ def test_calibrated_gaze_preserves_camera_rotation_with_tf32( expected = matrix_from_quat(source.double()) @ conversion camera = GazeHarness() camera._data.quat_w_world = source - camera._calibrated_basis = camera._calibrated_basis.to(device) - camera.set_calibrated_angles(angles) - basis = camera._calibrated_basis.double() - expected = expected @ basis @ camera._calibrated_rotation.double() @ basis.T @ conversion.T + camera._gaze_basis = camera._gaze_basis.to(device) + camera.set_gaze_angles(angles) + basis = camera._gaze_basis.double() + expected = expected @ basis @ camera._gaze_rotation.double() @ basis.T @ conversion.T selected = torch.arange(batch_size, device=device) % 2 == 0 with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast): if mode == "spherical_ids": - camera._apply_calibrated_pose(torch.nonzero(selected).flatten()) + camera._apply_gaze_pose(torch.nonzero(selected).flatten()) elif mode == "spherical_mask": - camera._apply_calibrated_pose(env_mask=wp.from_torch(selected)) + camera._apply_gaze_pose(env_mask=wp.from_torch(selected)) else: - camera._apply_calibrated_pose() + camera._apply_gaze_pose() if mode in ("spherical_ids", "spherical_mask"): torch.testing.assert_close(source[~selected], original[~selected], atol=0, rtol=0) source = source[selected] @@ -152,25 +161,25 @@ def test_calibrated_gaze_preserves_camera_rotation_with_tf32( def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pose() -> None: camera = GazeHarness() - fixation = torch.tensor([[0.4, 0.7], [0.6, 0.3]]) - camera.set_calibrated_fixation(fixation) - camera._apply_calibrated_pose() + angles = torch.tensor([[0.1, -0.2], [-0.15, 0.3]]) + camera.set_gaze_angles(angles) + camera._apply_gaze_pose() forward = quat_apply(camera._data.quat_w_world, torch.tensor([[1.0, 0.0, 0.0]]).expand(2, -1)) - source = CameraModel(**camera.cfg.camera_calibration) - pixels = torch.stack((fixation[:, 1] * 120 - 0.5, fixation[:, 0] * 80 - 0.5), -1) - directions, _ = source.unproject(pixels) + source = CameraModel(**camera.cfg.camera_model) + # The world camera frame looks along +X with +Z up; OpenCV looks along +Z with +Y down. + directions = gaze_direction(angles) expected = torch.stack((directions[:, 2], -directions[:, 0], -directions[:, 1]), -1) torch.testing.assert_close(forward, expected, atol=1e-6, rtol=1e-6) assert torch.count_nonzero(camera._data.pos_w) == 0 untouched = camera._data.quat_w_world[1].clone() camera._data.quat_w_world[0] = torch.tensor([0.0, 0.0, 0.0, 1.0]) - camera._apply_calibrated_pose([0]) + camera._apply_gaze_pose([0]) torch.testing.assert_close(camera._data.quat_w_world[1], untouched) torch.testing.assert_close( - camera._calibrated_validity(2), + camera._gaze_validity(2), source.project( angular_directions(camera._sampling_coords.cartesian, camera._sampling_coords.fov) - @ camera._calibrated_rotation.transpose(-1, -2) + @ camera._gaze_rotation.transpose(-1, -2) )[1], ) @@ -182,40 +191,37 @@ def test_renderer_ray_frame_matches_cv_frame() -> None: torch.testing.assert_close(rendered, cv * torch.tensor([1, -1, -1])) -@pytest.mark.parametrize("command", ["angles", "fixation"]) @pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_calibrated_pose_is_stable_inside_model_autocast(command: str, device: str) -> None: +def test_gaze_pose_is_stable_inside_model_autocast(device: str) -> None: if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA unavailable") cameras = [GazeHarness(), GazeHarness()] for camera in cameras: camera._data.quat_w_world = torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(2, 1) - camera._calibrated_basis = camera._calibrated_basis.to(device) - camera._calibrated_rays = camera._calibrated_rays.to(device) - camera._calibrated_identity = camera._calibrated_identity.to(device) + camera._gaze_basis = camera._gaze_basis.to(device) + camera._gaze_rays = camera._gaze_rays.to(device) + camera._gaze_identity = camera._gaze_identity.to(device) target = torch.tensor([[0.002, 0.003], [-0.1, 0.2]], device=device) - if command == "fixation": - target = target + 0.5 for camera, enabled in zip(cameras, [False, True], strict=True): with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled): - getattr(camera, f"set_calibrated_{command}")(target) - camera._apply_calibrated_pose() - camera._test_validity = camera._calibrated_validity(2) + camera.set_gaze_angles(target) + camera._apply_gaze_pose() + camera._test_validity = camera._gaze_validity(2) assert torch.isfinite(cameras[1]._data.quat_w_world).all() torch.testing.assert_close(cameras[1]._data.quat_w_world, cameras[0]._data.quat_w_world) - torch.testing.assert_close(cameras[1]._calibrated_rotation, cameras[0]._calibrated_rotation) + torch.testing.assert_close(cameras[1]._gaze_rotation, cameras[0]._gaze_rotation) torch.testing.assert_close(cameras[1]._data.quat_w_world.norm(dim=-1), torch.ones(2, device=device)) torch.testing.assert_close(cameras[1]._test_validity, cameras[0]._test_validity) @pytest.mark.parametrize("device", ["cpu", "cuda"]) -def test_rtx_calibrated_pose_writer_is_stable_inside_model_autocast(device: str, tf32_enabled) -> None: +def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_enabled) -> None: if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA unavailable") camera = GazeHarness() - camera._calibrated_basis = camera._calibrated_basis.to(device) - camera._calibrated_base_local_orientation = matrix_from_quat( + camera._gaze_basis = camera._gaze_basis.to(device) + camera._base_local_orientation = matrix_from_quat( torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(48, 1) ) written = [] @@ -226,8 +232,8 @@ def test_rtx_calibrated_pose_writer_is_stable_inside_model_autocast(device: str, angles = torch.tensor([[-0.006677, -0.010717]], device=device, dtype=torch.bfloat16).repeat(48, 1) for enabled in [False, True]: with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled): - camera.set_calibrated_angles(angles) - FoveatedRTXCamera._write_calibrated_local_pose(camera) + camera.set_gaze_angles(angles) + FoveatedRTXCamera._write_gaze_local_pose(camera) assert torch.isfinite(written[1]).all() assert written[1].dtype == torch.float32 torch.testing.assert_close(written[1].norm(dim=-1), torch.ones(48, device=device)) From 24f105bc3f7eb7536c1ceeeef12f34b5d7d7e32e Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:41:59 -0800 Subject: [PATCH 17/81] Take gaze angles in degrees Every other angle the foveated camera takes is in degrees: the CMF constant, the image rotation and the fields of view. set_gaze_angles now matches them. --- source/isaaclab_fovi/docs/README.md | 2 +- source/isaaclab_fovi/examples/render_foveated.py | 4 ++-- .../isaaclab_fovi/sensors/foveated_rtx_camera.py | 4 ++-- .../isaaclab_fovi/sensors/virtual_gaze.py | 10 +++++----- .../test/test_foveated_camera_render.py | 9 +++++---- .../test/test_spherical_geometry.py | 16 ++++++++-------- 6 files changed, 23 insertions(+), 22 deletions(-) diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index c2022ab927de..12daa4c63569 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -92,7 +92,7 @@ env.scene.eye.cmf_a_deg=1000 The retina can turn while the camera prim stays in place: ```python -# (tilt, pan) [rad] from the physical camera's optical axis, shape (num_envs, 2). +# (tilt, pan) [deg] from the physical camera's optical axis, shape (num_envs, 2). # Positive tilt looks up and positive pan looks left. camera.set_gaze_angles(angles) ``` diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index 1c1c03906b2f..c3dab86a3369 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -122,8 +122,8 @@ class SceneCfg(InteractiveSceneCfg): frame_seconds: list[float] = [] frames: list[torch.Tensor] = [] for step in range(args.steps): - # Gaze (tilt, pan) [rad] from the optical axis: look ahead, then 8 degrees to the right. - pan = (0.0, -math.radians(8.0), -math.radians(8.0), 0.0)[step % 4] + # Gaze (tilt, pan) [deg] from the optical axis: look ahead, then 8 degrees to the right. + pan = (0.0, -8.0, -8.0, 0.0)[step % 4] camera.set_gaze_angles(torch.tensor([[0.0, pan]], device=sim.device)) wp.synchronize_device(sim.device) start = time.perf_counter() diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 026633c0b849..cfcf3cb7ae3f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -364,8 +364,8 @@ def _allocate_foveated_buffers(self): # Per-frame overrides # ------------------------------------------------------------------ - def set_gaze_angles(self, angles: torch.Tensor) -> None: - super().set_gaze_angles(angles) + def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: + super().set_gaze_angles(angles_deg) self._write_gaze_local_pose() def _write_gaze_local_pose(self) -> None: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index ad4bb8166e7b..c2dd3cd25dda 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -32,18 +32,18 @@ class VirtualGaze: to the optical axis of the physical camera it looks through. """ - def set_gaze_angles(self, angles: torch.Tensor) -> None: - """Turn the retina to (tilt, pan) [rad] from the physical camera's optical axis. + def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: + """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. Positive tilt looks up and positive pan looks left. Zero looks along the optical axis. Args: - angles: Gaze angles for every environment, shape (num_envs, 2). + angles_deg: Gaze angles for every environment [deg], shape (num_envs, 2). """ # Geometry must remain float32 even when the policy runs under AMP. - with torch.autocast(angles.device.type, enabled=False): - tilt, pan = angles.float().unbind(-1) + with torch.autocast(angles_deg.device.type, enabled=False): + tilt, pan = angles_deg.float().deg2rad().unbind(-1) direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) self._gaze_rotation = gaze_rotation(direction, "pan_tilt") diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index 7f1d14a5f3b1..1806bfb32947 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -100,8 +100,9 @@ class _GroundSceneCfg(InteractiveSceneCfg): ) -def _ground_distance_along_gaze(tilt: float, pan: float) -> float: - """Distance [m] from the camera to the ground along the gaze (tilt, pan) [rad]; up and left are positive.""" +def _ground_distance_along_gaze(tilt_deg: float, pan_deg: float) -> float: + """Distance [m] from the camera to the ground along the gaze (tilt, pan) [deg]; up and left are positive.""" + tilt, pan = math.radians(tilt_deg), math.radians(pan_deg) # OpenGL camera frame: +X right, +Y up, looking along -Z. ray_camera = np.array((-math.cos(tilt) * math.sin(pan), math.sin(tilt), -math.cos(tilt) * math.cos(pan))) eye = np.asarray(CAM_EYE) @@ -115,7 +116,7 @@ def _ground_distance_along_gaze(tilt: float, pan: float) -> float: def _render(backend: str, gaze: torch.Tensor, **camera_overrides) -> tuple[torch.Tensor, torch.Tensor]: - """Render ground distance for one environment per row of gaze angles (tilt, pan) [rad]. + """Render ground distance for one environment per row of gaze angles (tilt, pan) [deg]. Returns: The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid @@ -157,7 +158,7 @@ def test_foveated_camera_follows_gaze(backend, source): One environment looks along the optical axis and one 16 degrees to the right. The reference is the analytic ground distance along each gaze direction. """ - gaze = torch.tensor([[0.0, 0.0], [0.0, -math.radians(16.0)]]) + gaze = torch.tensor([[0.0, 0.0], [0.0, -16.0]]) distance, field = _render(backend, gaze, **CAMERA_SOURCES[source]) assert distance.shape == (2, RESOLUTION, RESOLUTION) diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 1c9a0bc67c4f..40a4de79d3d2 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -86,17 +86,17 @@ def __init__(self) -> None: self._initialize_gaze() -def gaze_direction(angles: torch.Tensor) -> torch.Tensor: - """OpenCV camera-frame unit direction of (tilt, pan) gaze angles [rad]: up and left are positive.""" - tilt, pan = angles.unbind(-1) +def gaze_direction(angles_deg: torch.Tensor) -> torch.Tensor: + """OpenCV camera-frame unit direction of (tilt, pan) gaze angles [deg]: up and left are positive.""" + tilt, pan = angles_deg.deg2rad().unbind(-1) return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) def angles_toward(camera: CameraModel, pixel: tuple[float, float]) -> torch.Tensor: - """(tilt, pan) gaze angles [rad] that look along the ray through a source pixel (x, y).""" + """(tilt, pan) gaze angles [deg] that look along the ray through a source pixel (x, y).""" direction, _ = camera.unproject(torch.tensor([pixel])) x, y, z = direction.unbind(-1) - return torch.stack((-torch.atan2(y, torch.sqrt(x * x + z * z)), -torch.atan2(x, z)), -1) + return torch.stack((-torch.atan2(y, torch.sqrt(x * x + z * z)), -torch.atan2(x, z)), -1).rad2deg() @pytest.mark.parametrize("pixel", [(119.5, 39.5), (59.5, 79.5), (120.5, 39.5), (59.5, -1.3)]) @@ -114,7 +114,7 @@ def test_edge_gaze_preserves_visible_rays(pixel: tuple[float, float]) -> None: def test_gaze_away_from_sensor_masks_all_rays() -> None: camera = GazeHarness() - camera.set_gaze_angles(torch.tensor([[0.0, torch.pi]])) + camera.set_gaze_angles(torch.tensor([[0.0, 180.0]])) assert not camera._gaze_validity(1).any() @@ -131,7 +131,7 @@ def test_gaze_preserves_camera_rotation_with_tf32( conversion = source_gl.new_tensor([[0, 0, -1], [-1, 0, 0], [0, 1, 0]]).double() source = quat_from_matrix(matrix_from_quat(source_gl.double()) @ conversion.T).float() original = source.clone() - angles = torch.tensor([[0.13, -0.21]], device=device).repeat(batch_size, 1) + angles = torch.tensor([[7.5, -12.0]], device=device).repeat(batch_size, 1) angles[1::2] = 0 expected = matrix_from_quat(source.double()) @ conversion camera = GazeHarness() @@ -161,7 +161,7 @@ def test_gaze_preserves_camera_rotation_with_tf32( def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pose() -> None: camera = GazeHarness() - angles = torch.tensor([[0.1, -0.2], [-0.15, 0.3]]) + angles = torch.tensor([[6.0, -11.0], [-9.0, 17.0]]) camera.set_gaze_angles(angles) camera._apply_gaze_pose() forward = quat_apply(camera._data.quat_w_world, torch.tensor([[1.0, 0.0, 0.0]]).expand(2, -1)) From 310b9356e0a925468b041b33c353d4ba6ea7f43e Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 15:48:59 -0800 Subject: [PATCH 18/81] Keep the gaze relative to the mount when an RTX foveated camera is moved The RTX camera writes the gaze into the camera prim on top of a mount orientation cached at startup, so moving the camera with set_world_poses was undone by the next gaze command. set_world_poses now refreshes the cached mount of the moved environments and re-applies their gaze. A render test moves one environment's camera after setting its gaze on both renderers. --- .../sensors/foveated_rtx_camera.py | 13 ++++++ .../test/test_foveated_camera_render.py | 44 +++++++++++++++---- 2 files changed, 48 insertions(+), 9 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index cfcf3cb7ae3f..4c5021567119 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -368,6 +368,19 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: super().set_gaze_angles(angles_deg) self._write_gaze_local_pose() + def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): + """Move the camera's mount; the gaze stays relative to the new mount. + + Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. + """ + super().set_world_poses(positions, orientations, env_ids, convention) + # The prims of the moved environments now hold the bare mount pose, which is their new base. + ids = slice(None) if env_ids is None else torch.as_tensor(env_ids, device=self._device, dtype=torch.long) + _, local_orientation = self._view.get_local_poses() + self._base_local_orientation[ids] = matrix_from_quat(local_orientation.torch[ids]) + if self._gaze_rotation is not None: + self._write_gaze_local_pose() + def _write_gaze_local_pose(self) -> None: # Replicator reads camera prims, not update_camera's pose arguments. # Write when the command arrives, before a visualizer can render the step. diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index 1806bfb32947..21062c673c98 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -100,13 +100,19 @@ class _GroundSceneCfg(InteractiveSceneCfg): ) -def _ground_distance_along_gaze(tilt_deg: float, pan_deg: float) -> float: +def _look_at(eye, target) -> tuple[float, float, float, float]: + """OpenGL camera orientation (x, y, z, w) at ``eye`` looking at ``target`` with world +Z up.""" + matrix = create_rotation_matrix_from_view(torch.tensor([eye]), torch.tensor([target]), up_axis="Z") + return tuple(quat_from_matrix(matrix)[0].tolist()) + + +def _ground_distance_along_gaze(tilt_deg: float, pan_deg: float, eye=CAM_EYE, target=CAM_TARGET) -> float: """Distance [m] from the camera to the ground along the gaze (tilt, pan) [deg]; up and left are positive.""" tilt, pan = math.radians(tilt_deg), math.radians(pan_deg) # OpenGL camera frame: +X right, +Y up, looking along -Z. ray_camera = np.array((-math.cos(tilt) * math.sin(pan), math.sin(tilt), -math.cos(tilt) * math.cos(pan))) - eye = np.asarray(CAM_EYE) - forward = np.asarray(CAM_TARGET) - eye + eye = np.asarray(eye) + forward = np.asarray(target) - eye z_axis = -forward / np.linalg.norm(forward) x_axis = np.cross(np.array((0.0, 0.0, 1.0)), z_axis) x_axis /= np.linalg.norm(x_axis) @@ -115,9 +121,13 @@ def _ground_distance_along_gaze(tilt_deg: float, pan_deg: float) -> float: return float(-eye[2] / ray_world[2]) -def _render(backend: str, gaze: torch.Tensor, **camera_overrides) -> tuple[torch.Tensor, torch.Tensor]: +def _render( + backend: str, gaze: torch.Tensor, moved_mount: tuple | None = None, **camera_overrides +) -> tuple[torch.Tensor, torch.Tensor]: """Render ground distance for one environment per row of gaze angles (tilt, pan) [deg]. + With ``moved_mount`` (eye, target), the last environment's camera is moved there after its gaze is set. + Returns: The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid cell, shape (H, W, 2). @@ -126,13 +136,9 @@ def _render(backend: str, gaze: torch.Tensor, **camera_overrides) -> tuple[torch sim_cfg = SimulationCfg(physics=physics_cfg, device=DEVICE) with build_simulation_context(device=DEVICE, sim_cfg=sim_cfg) as sim: sim._app_control_on_stop_handle = None - rot = tuple( - quat_from_matrix( - create_rotation_matrix_from_view(torch.tensor([CAM_EYE]), torch.tensor([CAM_TARGET]), up_axis="Z") - )[0].tolist() - ) scene_cfg = _GroundSceneCfg(num_envs=len(gaze), env_spacing=20.0) scene_cfg.camera.renderer_cfg = renderer_cfg() + rot = _look_at(CAM_EYE, CAM_TARGET) scene_cfg.camera.offset = FoveatedCameraCfg.OffsetCfg(pos=CAM_EYE, rot=rot, convention="opengl") for name, value in camera_overrides.items(): setattr(scene_cfg.camera, name, value) @@ -141,6 +147,12 @@ def _render(backend: str, gaze: torch.Tensor, **camera_overrides) -> tuple[torch assert isinstance(camera, camera_class) sim.reset() camera.set_gaze_angles(gaze.to(sim.device)) + if moved_mount is not None: + last = len(gaze) - 1 + eye, target = moved_mount + position = scene.env_origins[last : last + 1] + torch.tensor([eye], device=sim.device) + orientation = torch.tensor([_look_at(eye, target)], device=sim.device) + camera.set_world_poses(position, orientation, env_ids=[last], convention="opengl") for _ in range(WARMUP_STEPS): sim.step() camera.update(sim.get_physics_dt(), force_recompute=True) @@ -184,6 +196,20 @@ def test_foveated_camera_follows_gaze(backend, source): assert (distance[1] == 0).sum() > (distance[0] == 0).sum() +@pytest.mark.parametrize("backend", BACKENDS) +def test_gaze_stays_relative_to_a_moved_mount(backend): + """Moving one environment's camera keeps its gaze relative to the new mount and leaves the other alone.""" + gaze = torch.tensor([[0.0, -10.0], [0.0, -10.0]]) + eye, target = (0.3, -0.4, 3.2), (2.0, 0.3, 0.0) + distance, field = _render(backend, gaze, moved_mount=(eye, target)) + + row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) + assert float(distance[0, row, column]) == pytest.approx(_ground_distance_along_gaze(0.0, -10.0), rel=0.01) + assert float(distance[1, row, column]) == pytest.approx( + _ground_distance_along_gaze(0.0, -10.0, eye, target), rel=0.01 + ) + + @pytest.mark.parametrize("backend", BACKENDS) def test_foveated_camera_samples_densest_at_the_fixation(backend): """Neighbouring samples are closer together at the fixation, and nearly even without foveation.""" From c9c1d4484826c548a396f2e9e915527c0645f325 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 17:16:35 -0800 Subject: [PATCH 19/81] Test that a gaze set after the first frame is rendered Gaze actions change the gaze every step, after the camera has rendered. The test renders, turns the gaze and checks the retina's centre against the analytic ground distance on Newton and RTX. --- .../test/test_foveated_camera_render.py | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index 21062c673c98..0711eeee6a59 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -122,11 +122,16 @@ def _ground_distance_along_gaze(tilt_deg: float, pan_deg: float, eye=CAM_EYE, ta def _render( - backend: str, gaze: torch.Tensor, moved_mount: tuple | None = None, **camera_overrides + backend: str, + gaze: torch.Tensor, + moved_mount: tuple | None = None, + later_gaze: torch.Tensor | None = None, + **camera_overrides, ) -> tuple[torch.Tensor, torch.Tensor]: """Render ground distance for one environment per row of gaze angles (tilt, pan) [deg]. With ``moved_mount`` (eye, target), the last environment's camera is moved there after its gaze is set. + With ``later_gaze``, the gaze changes to it after the first frames, and the camera renders again. Returns: The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid @@ -156,6 +161,11 @@ def _render( for _ in range(WARMUP_STEPS): sim.step() camera.update(sim.get_physics_dt(), force_recompute=True) + if later_gaze is not None: + camera.set_gaze_angles(later_gaze.to(sim.device)) + for _ in range(WARMUP_STEPS): + sim.step() + camera.update(sim.get_physics_dt(), force_recompute=True) distance = camera.data.output["distance_to_camera"].torch[..., 0].detach().cpu().float().clone() coords = camera.sampling_coords field = coords.as_grid(coords.cartesian, sample_dim=0).detach().cpu().float().clone() @@ -196,6 +206,17 @@ def test_foveated_camera_follows_gaze(backend, source): assert (distance[1] == 0).sum() > (distance[0] == 0).sum() +@pytest.mark.parametrize("backend", BACKENDS) +def test_gaze_change_reaches_the_next_frame(backend): + """A gaze set after the camera has rendered moves the retina, as a gaze action does every step.""" + later = torch.tensor([[0.0, -16.0], [8.0, 10.0]]) + distance, field = _render(backend, torch.zeros(2, 2), later_gaze=later) + + row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) + for env, (tilt, pan) in enumerate(later.tolist()): + assert float(distance[env, row, column]) == pytest.approx(_ground_distance_along_gaze(tilt, pan), rel=0.01) + + @pytest.mark.parametrize("backend", BACKENDS) def test_gaze_stays_relative_to_a_moved_mount(backend): """Moving one environment's camera keeps its gaze relative to the new mount and leaves the other alone.""" From 0b713f30f387f8c8c40eb853429cf972c14b87a4 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 17:16:39 -0800 Subject: [PATCH 20/81] Add active-gaze camera tasks with gaze-supervised PPO isaaclab_fovi.mdp adds a gaze action in field radii with a radial limit, the gaze observation, a teacher's gaze labels toward a point on an asset, and an action penalty without the gaze. isaaclab_fovi.rsl_rl adds PPO whose loss also pulls the gaze means toward the teacher's. Isaac-Cartpole-Camera-Fovi, Isaac-Lift-KukaAllegro-Camera-Fovi and Isaac-Reorient-KukaAllegro-Camera-Fovi are the stock camera tasks with the camera foveated at the same mount, optics and resolution. They keep the stock vision model and PPO settings, and are registered through the isaaclab.tasks entry point. --- .../changelog.d/isaaclab-fovi.added.rst | 4 + source/isaaclab_fovi/docs/README.md | 43 +++- .../isaaclab_fovi/mdp/__init__.py | 34 +++ .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 234 ++++++++++++++++++ .../isaaclab_fovi/rsl_rl/__init__.py | 14 ++ .../rsl_rl/gaze_supervised_ppo.py | 131 ++++++++++ .../rsl_rl/gaze_supervised_ppo_cfg.py | 26 ++ .../isaaclab_fovi/tasks/__init__.py | 13 + .../isaaclab_fovi/tasks/active_gaze.py | 80 ++++++ .../isaaclab_fovi/tasks/agents.py | 18 ++ .../isaaclab_fovi/tasks/cartpole/__init__.py | 19 ++ .../isaaclab_fovi/tasks/cartpole/agents.py | 19 ++ .../isaaclab_fovi/tasks/cartpole/env_cfg.py | 80 ++++++ .../tasks/kuka_allegro/__init__.py | 20 ++ .../tasks/kuka_allegro/agents.py | 25 ++ .../tasks/kuka_allegro/env_cfg.py | 80 ++++++ source/isaaclab_fovi/pyproject.toml | 9 +- source/isaaclab_fovi/test/test_active_gaze.py | 77 ++++++ uv.lock | 8 +- 19 files changed, 929 insertions(+), 5 deletions(-) create mode 100644 source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo_cfg.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/__init__.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/__init__.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py create mode 100644 source/isaaclab_fovi/test/test_active_gaze.py diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst index 5ca30f7c3d96..9f78714e11f3 100644 --- a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst +++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst @@ -1,2 +1,6 @@ * Introduced ``isaaclab_fovi`` and the ``fovi`` installation extra, providing a foveated camera sensor for the Newton and RTX renderers. +* Added active-gaze manager terms in :mod:`isaaclab_fovi.mdp`, gaze-supervised PPO + for RSL-RL in :mod:`isaaclab_fovi.rsl_rl`, and the ``Isaac-Cartpole-Camera-Fovi``, + ``Isaac-Lift-KukaAllegro-Camera-Fovi`` and ``Isaac-Reorient-KukaAllegro-Camera-Fovi`` + tasks. diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index 12daa4c63569..67c0679d6298 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -97,12 +97,49 @@ The retina can turn while the camera prim stays in place: camera.set_gaze_angles(angles) ``` -How a policy drives the gaze, for example as per-step changes normalized to -the retinal window, belongs to the task's action term. - Set `mask_to_sensor_fov=True` to zero the samples that fall outside the physical camera's image at the current gaze. +## Active gaze + +`isaaclab_fovi.mdp` has the manager terms for a policy that moves the gaze: + +- `GazeActionCfg`: two actions that move the gaze by up to `step_size` field + radii (half the retina's field of view) per step, within `gaze_limit` field + radii of the optical axis. Make it the last action term. +- `gaze_state`: the gaze and its velocity, in field radii. +- `gaze_teacher_labels`: a teacher's gaze action toward a point fixed to an + asset, and whether that point is a valid target. `teacher_labels` takes any + world points, for a task whose target changes during an episode. +- `motor_action_l2`: the stock action penalty without the gaze. + +`isaaclab_fovi.rsl_rl.GazeSupervisedPPOCfg` trains PPO with an added loss that +pulls the means of the gaze actions toward the teacher's. The labels come from +an `oracle` observation group that the actor and critic never see. + +### Tasks + +Each task is its stock camera counterpart with the camera foveated at the same +mount, optics and resolution, two gaze actions, and gaze supervision. The vision +model and the PPO settings are the stock ones. + +| Task | Teacher looks at | +| --- | --- | +| `Isaac-Cartpole-Camera-Fovi` (`presets=depth` for depth) | the pole's tip | +| `Isaac-Lift-KukaAllegro-Camera-Fovi` | the object | +| `Isaac-Reorient-KukaAllegro-Camera-Fovi` | the object | + +The Kuka-Allegro tasks take the stock base-camera presets, such as +`presets=depth128`. Set the retina's resolution with, for example, +`env.scene.tiled_camera.foveated_res=48`. + +```bash +uv run isaaclab train --rl_library rsl_rl --task Isaac-Cartpole-Camera-Fovi +``` + +The tasks are registered through the `isaaclab.tasks` entry point of this +package, so they are available from a source checkout. + ### Advanced options - Sample-set styles such as `foveated_style="isotropic"` publish diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py new file mode 100644 index 000000000000..585edad12dae --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py @@ -0,0 +1,34 @@ +# 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 + +"""Manager terms for active gaze with a foveated camera.""" + +from .gaze import ( + GazeAction, + GazeActionCfg, + angles_to_direction, + clamp_gaze, + direction_to_angles, + entity_point, + gaze_state, + gaze_teacher_labels, + motor_action_l2, + random_gaze, + teacher_labels, +) + +__all__ = [ + "GazeAction", + "GazeActionCfg", + "angles_to_direction", + "clamp_gaze", + "direction_to_angles", + "entity_point", + "gaze_state", + "gaze_teacher_labels", + "motor_action_l2", + "random_gaze", + "teacher_labels", +] diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py new file mode 100644 index 000000000000..3494cc4c5a18 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -0,0 +1,234 @@ +# 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 + +"""Active gaze for a foveated camera: a gaze action, its observation, and a teacher's gaze labels. + +Gaze angles are (tilt, pan) [deg] from the physical camera's optical axis: positive tilt looks up and positive pan +looks left, as for :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles`. The policy moves and observes the +gaze in field radii, half the retina's field of view. Camera-frame directions follow the ROS (OpenCV) convention: +x right, y down, z forward. +""" + +from __future__ import annotations + +import math +from dataclasses import MISSING +from typing import TYPE_CHECKING + +import torch + +from isaaclab.managers import ActionTerm, ActionTermCfg, SceneEntityCfg +from isaaclab.utils import configclass +from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_apply, quat_apply_inverse + +from ..sensors.calibrated_geometry import resolve_camera_model, sampling_geometry + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv, ManagerBasedRLEnv + + +def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3).""" + tilt, pan = angles_deg.deg2rad().unbind(-1) + return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + + +def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: + """Gaze angles [deg] of camera-frame directions, shape (..., 3) to (..., 2).""" + x, y, z = direction.unbind(-1) + return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg() + + +def clamp_gaze(gaze: torch.Tensor, limit: float) -> torch.Tensor: + """Scale gazes back onto the circle of radius ``limit`` when they leave it, shape (..., 2).""" + return gaze * (limit / gaze.norm(dim=-1, keepdim=True).clamp_min(limit)) + + +def random_gaze(count: int, limit: float, device: torch.device | str | None = None) -> torch.Tensor: + """Gazes drawn uniformly over the disc of radius ``limit``, shape (count, 2).""" + radius = limit * torch.rand(count, device=device).sqrt() + angle = 2 * math.pi * torch.rand(count, device=device) + return torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1) + + +class GazeAction(ActionTerm): + """Moves a foveated camera's gaze by bounded steps in (tilt, pan) order. + + Actions, the limit and the observed gaze are in field radii. An action of 1 changes a coordinate by + ``step_size``, and the gaze stays within ``gaze_limit`` of the optical axis. The gaze starts each episode on the + optical axis, or anywhere the physical camera sees within the limit when ``random_reset`` is set. + + The camera must be mounted on the environment, so that its offset is its pose in the environment frame. + """ + + cfg: GazeActionCfg + + def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self.camera = self._asset + camera_cfg = self.camera.cfg + if camera_cfg.prim_path.rpartition("/")[0] not in ("{ENV_REGEX_NS}", env.scene.env_regex_ns): + raise ValueError(f"Gaze needs a camera mounted on the environment, got {camera_cfg.prim_path!r}.") + self.camera_model = resolve_camera_model(camera_cfg) + self.field_radius_deg = sampling_geometry(camera_cfg)[0] / 2 + """Half the retina's field of view [deg].""" + offset = camera_cfg.offset + rotation = torch.tensor(offset.rot, dtype=torch.float32, device=self.device)[None] + self.mount_rotation = convert_camera_frame_orientation_convention( + rotation, origin=offset.convention, target="ros" + )[0] + """Orientation (x, y, z, w) of the physical camera in the environment frame, ROS convention.""" + self._raw = torch.zeros(self.num_envs, 2, device=self.device) + self._gaze = torch.zeros_like(self._raw) + self._velocity = torch.zeros_like(self._raw) + + @property + def action_dim(self) -> int: + return 2 + + @property + def raw_actions(self) -> torch.Tensor: + return self._raw + + @property + def processed_actions(self) -> torch.Tensor: + return self._gaze + + @property + def gaze(self) -> torch.Tensor: + """Current gaze in field radii, shape (num_envs, 2).""" + return self._gaze + + @property + def velocity(self) -> torch.Tensor: + """Gaze velocity in field radii per second, shape (num_envs, 2).""" + return self._velocity + + @property + def angles_deg(self) -> torch.Tensor: + """Current gaze angles [deg], shape (num_envs, 2).""" + return self._gaze * self.field_radius_deg + + def process_actions(self, actions: torch.Tensor): + self._raw.copy_(actions) + previous = self._gaze.clone() + self._gaze.copy_(clamp_gaze(self._gaze + actions.clamp(-1, 1) * self.cfg.step_size, self.cfg.gaze_limit)) + self._velocity.copy_((self._gaze - previous) / self._env.step_dt) + self.camera.set_gaze_angles(self.angles_deg) + + def apply_actions(self): + pass + + def reset(self, env_ids=None): + ids = torch.arange(self.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] + self._raw[ids] = 0.0 + self._velocity[ids] = 0.0 + self._gaze[ids] = 0.0 + if self.cfg.random_reset and len(ids): + gaze = random_gaze(len(ids), self.cfg.gaze_limit, self.device) + visible = self.visible(angles_to_direction(gaze * self.field_radius_deg)) + self._gaze[ids] = torch.where(visible[:, None], gaze, 0.0) + self.camera.set_gaze_angles(self.angles_deg) + + def directions(self, points: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions from the camera to world points, shape (num_envs, 3).""" + position = self.camera.data.pos_w.torch + local = quat_apply_inverse(self.mount_rotation.expand(len(points), -1), points - position) + return torch.nn.functional.normalize(local, dim=-1) + + def visible(self, direction: torch.Tensor) -> torch.Tensor: + """Whether camera-frame directions fall inside the physical camera's image.""" + return self.camera_model.project(direction)[1] + + def teacher_action(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """The action that moves the gaze toward world points, and whether each point is a valid target. + + A point is valid when the physical camera sees it and the gaze can reach it within the limit. + """ + direction = self.directions(points) + desired = direction_to_angles(direction) / self.field_radius_deg + valid = self.visible(direction) & (desired.norm(dim=-1) <= self.cfg.gaze_limit) + action = ((desired - self._gaze) / self.cfg.step_size).clamp(-1, 1) + return torch.where(valid[:, None], action, 0.0), valid + + def fixation_error_deg(self, points: torch.Tensor) -> torch.Tensor: + """Angle [deg] between the gaze and the direction to world points, shape (num_envs,).""" + direction = self.directions(points) + gaze = angles_to_direction(self.angles_deg) + # atan2 stays accurate near perfect alignment, unlike acos of the dot product. + return torch.atan2(torch.cross(gaze, direction, dim=-1).norm(dim=-1), (gaze * direction).sum(-1)).rad2deg() + + +@configclass +class GazeActionCfg(ActionTermCfg): + """Configuration of :class:`GazeAction`.""" + + class_type: type = GazeAction + asset_name: str = MISSING + """Scene name of the foveated camera whose gaze the action moves.""" + step_size: float = 0.1 + """Change of each gaze coordinate per step at an action of 1, in field radii.""" + gaze_limit: float = 1.0 + """Largest distance of the gaze from the camera's optical axis, in field radii.""" + random_reset: bool = False + """Start episodes at a random gaze the camera sees; otherwise on the optical axis.""" + + +def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: + """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" + term: GazeAction = env.action_manager.get_term(action_name) + return torch.cat((term.gaze, term.velocity), dim=-1) + + +def entity_point( + env: ManagerBasedEnv, asset_cfg: SceneEntityCfg, offset: tuple[float, float, float] = (0.0, 0.0, 0.0) +) -> torch.Tensor: + """World position of a point fixed to an asset's root, or to its first selected body, shape (num_envs, 3). + + Args: + asset_cfg: The asset, and optionally one body by ``body_names``. + offset: The point in the root's or the body's frame [m]. + """ + data = env.scene[asset_cfg.name].data + if asset_cfg.body_names is None: + position, orientation = data.root_pos_w.torch, data.root_quat_w.torch + else: + body = asset_cfg.body_ids[0] + position, orientation = data.body_pos_w.torch[:, body], data.body_quat_w.torch[:, body] + return position + quat_apply(orientation, torch.tensor(offset, device=env.device).expand_as(position)) + + +def teacher_labels(env: ManagerBasedEnv, points: torch.Tensor, action_name: str = "gaze") -> torch.Tensor: + """The teacher's gaze action toward world points and its validity, shape (num_envs, 3). + + A training label, never a policy input. Tasks whose target changes, for example from an object to a goal once + the object is grasped, choose the points and call this. + """ + term: GazeAction = env.action_manager.get_term(action_name) + action, valid = term.teacher_action(points) + error = term.fixation_error_deg(points) + log = env.extras.setdefault("log", {}) + log["Gaze/target_error_deg"] = torch.where(valid, error, 0.0).sum() / valid.sum().clamp_min(1) + log["Gaze/valid_target_fraction"] = valid.float().mean() + return torch.cat((action, valid[:, None].float()), dim=-1) + + +def gaze_teacher_labels( + env: ManagerBasedEnv, + target_cfg: SceneEntityCfg, + offset: tuple[float, float, float] = (0.0, 0.0, 0.0), + action_name: str = "gaze", +) -> torch.Tensor: + """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3).""" + return teacher_labels(env, entity_point(env, target_cfg, offset), action_name) + + +def motor_action_l2(env: ManagerBasedRLEnv, gaze_action_name: str = "gaze") -> torch.Tensor: + """Squared L2 norm of the actions other than the gaze, shape (num_envs,). + + Matches :func:`isaaclab.envs.mdp.action_l2` on the task's own actions, so moving the gaze costs nothing. + """ + gaze = env.action_manager.get_term(gaze_action_name).raw_actions + return env.action_manager.action.square().sum(-1) - gaze.square().sum(-1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py new file mode 100644 index 000000000000..5377996dd684 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py @@ -0,0 +1,14 @@ +# 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 + +"""RSL-RL training with gaze supervision by a teacher. + +The algorithm is resolved by name from :attr:`GazeSupervisedPPOCfg.class_name`, so importing this package does not +import RSL-RL. +""" + +from .gaze_supervised_ppo_cfg import GazeSupervisedPPOCfg + +__all__ = ["GazeSupervisedPPOCfg"] diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py new file mode 100644 index 000000000000..3594b8f36f27 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py @@ -0,0 +1,131 @@ +# 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 + +"""PPO with gaze supervision by a teacher, for RSL-RL. + +The update follows :meth:`rsl_rl.algorithms.PPO.update` (BSD-3-Clause) for feedforward models without RND or +symmetry, and adds the teacher's gaze loss to the PPO loss. +""" + +from __future__ import annotations + +import math + +import torch +from rsl_rl.algorithms import PPO +from torch import nn + + +def gaze_loss(mean: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + """Mean distance between the policy's gaze-action means and the teacher's, over valid labels. + + Args: + mean: The policy's gaze-action means, shape (batch, 2). + labels: The teacher's gaze actions and their validity, shape (batch, 3). + """ + valid = labels[:, 2] > 0.5 + # Select valid rows before subtracting, so an invalid label cannot reach the gradients. + residual = torch.where(valid[:, None], mean - torch.nan_to_num(labels[:, :2]), 0.0) + return residual.norm(dim=-1).sum() / valid.sum().clamp_min(1) + + +class GazeSupervisedPPO(PPO): + """PPO whose loss also pulls the policy's gaze toward a teacher's. + + The gaze is the last two actions. The teacher's labels are the observation group ``oracle_group``, as + :func:`isaaclab_fovi.mdp.teacher_labels` computes them; they never enter the actor or the critic. Only the means + of the gaze actions are supervised; PPO tunes their standard deviations like any other action's. + + Args: + oracle_loss_coef: Weight of the gaze loss. Zero trains plain PPO. + oracle_group: Observation group of the teacher's labels. + """ + + def __init__( + self, + actor, + critic, + storage, + *, + oracle_loss_coef: float = 1.0, + oracle_group: str = "oracle", + **kwargs, + ): + if actor.is_recurrent or critic.is_recurrent or kwargs.get("rnd_cfg") or kwargs.get("symmetry_cfg"): + raise ValueError("GazeSupervisedPPO supports feedforward models without RND or symmetry.") + if not math.isfinite(oracle_loss_coef) or oracle_loss_coef < 0: + raise ValueError("oracle_loss_coef must be finite and nonnegative.") + super().__init__(actor, critic, storage, **kwargs) + self.oracle_loss_coef = oracle_loss_coef + self.oracle_group = oracle_group + + def update(self) -> dict[str, float]: + totals = torch.zeros(5, device=self.device) + generator = self.storage.mini_batch_generator(self.num_mini_batches, self.num_learning_epochs) + for batch in generator: + if self.normalize_advantage_per_mini_batch: + with torch.no_grad(): + batch.advantages = (batch.advantages - batch.advantages.mean()) / (batch.advantages.std() + 1e-8) + with torch.amp.autocast( + device_type=torch.device(self.device).type, enabled=self.use_mixed_precision, dtype=torch.bfloat16 + ): + self.actor(batch.observations, stochastic_output=True) + log_prob = self.actor.get_output_log_prob(batch.actions) + values = self.critic(batch.observations) + entropy = self.actor.output_entropy.mean() + if self.desired_kl is not None and self.schedule == "adaptive": + self._adapt_learning_rate(batch.old_distribution_params, self.actor.output_distribution_params) + ratio = torch.exp(log_prob - batch.old_actions_log_prob.squeeze(-1)) + advantages = batch.advantages.squeeze(-1) + surrogate = torch.max( + -advantages * ratio, -advantages * ratio.clamp(1.0 - self.clip_param, 1.0 + self.clip_param) + ).mean() + value_error = (values - batch.returns).pow(2) + if self.use_clipped_value_loss: + clipped = batch.values + (values - batch.values).clamp(-self.clip_param, self.clip_param) + value_error = torch.max(value_error, (clipped - batch.returns).pow(2)) + value_loss = value_error.mean() + labels = batch.observations[self.oracle_group].float() + oracle = gaze_loss(self.actor.output_mean[:, -2:].float(), labels) + loss = ( + surrogate + + self.value_loss_coef * value_loss + - self.entropy_coef * entropy + + self.oracle_loss_coef * oracle + ) + self.optimizer.zero_grad() + loss.backward() + if self.is_multi_gpu: + self.reduce_parameters() + nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm) + nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm) + self.optimizer.step() + valid = (labels[:, 2] > 0.5).float().mean() + totals += torch.stack((value_loss, surrogate, entropy, oracle, valid)).detach().float() + obs = self.storage.observations.flatten(0, 1) + self.actor.update_normalization(obs) + self.critic.update_normalization(obs) + self.storage.clear() + means = (totals / (self.num_learning_epochs * self.num_mini_batches)).tolist() + return dict(zip(("value", "surrogate", "entropy", "oracle", "oracle_valid"), means, strict=True)) + + def _adapt_learning_rate(self, old_params, new_params): + """Adapt the learning rate to the policy's KL divergence, as PPO's adaptive schedule does.""" + with torch.inference_mode(): + kl = self.actor.get_kl_divergence(old_params, new_params).mean() + if self.is_multi_gpu: + torch.distributed.all_reduce(kl, op=torch.distributed.ReduceOp.SUM) + kl /= self.gpu_world_size + if self.gpu_global_rank == 0: + if kl > self.desired_kl * 2.0: + self.learning_rate = max(1e-5, self.learning_rate / 1.5) + elif 0.0 < kl < self.desired_kl / 2.0: + self.learning_rate = min(1e-2, self.learning_rate * 1.5) + if self.is_multi_gpu: + rate = torch.tensor(self.learning_rate, device=self.device) + torch.distributed.broadcast(rate, src=0) + self.learning_rate = rate.item() + for group in self.optimizer.param_groups: + group["lr"] = self.learning_rate diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo_cfg.py new file mode 100644 index 000000000000..9a43363dc5f4 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo_cfg.py @@ -0,0 +1,26 @@ +# 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 + +"""Configuration of :class:`~isaaclab_fovi.rsl_rl.gaze_supervised_ppo.GazeSupervisedPPO`.""" + +from __future__ import annotations + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlPpoAlgorithmCfg + + +@configclass +class GazeSupervisedPPOCfg(RslRlPpoAlgorithmCfg): + """PPO whose loss also pulls the policy's gaze toward a teacher's. + + See :class:`~isaaclab_fovi.rsl_rl.gaze_supervised_ppo.GazeSupervisedPPO`. + """ + + class_name: str = "isaaclab_fovi.rsl_rl.gaze_supervised_ppo:GazeSupervisedPPO" + oracle_loss_coef: float = 1.0 + """Weight of the gaze loss. Zero trains plain PPO.""" + oracle_group: str = "oracle" + """Observation group of the teacher's labels.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py new file mode 100644 index 000000000000..ad14d15ea85c --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py @@ -0,0 +1,13 @@ +# 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 + +"""Camera tasks of Isaac Lab with a foveated camera whose gaze the policy moves. + +Each task keeps its stock counterpart's scene, rewards, vision model and PPO settings. The camera becomes a foveated +camera at the same mount, with the same optics and resolution, and the policy gets two gaze actions. A teacher's gaze +labels supervise those actions during training. +""" + +from . import cartpole, kuka_allegro # noqa: F401 (registers the tasks) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py new file mode 100644 index 000000000000..bce9161cbae8 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py @@ -0,0 +1,80 @@ +# 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 + +"""Shared pieces of the active-gaze camera tasks.""" + +from __future__ import annotations + +from dataclasses import MISSING, fields + +from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg +from isaaclab.sensors import CameraCfg +from isaaclab.utils import configclass + +from isaaclab_tasks.utils import PresetCfg, preset + +from isaaclab_fovi import mdp +from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg + + +def foveated_camera(camera: CameraCfg, foveated_res: int | None = None) -> FoveatedCameraCfg: + """A foveated camera at the camera's mount, with its optics, data types and renderer. + + The retina covers the camera's short side and is ``foveated_res`` samples across, by default the camera's width, + so the number of rendered rays stays close to the camera's pixels. Samples the camera does not see are zero. + The foveated camera keeps its own image size and per-frame pose updates, which render each new gaze. + """ + camera = camera.copy() + own = {"class_type", "width", "height", "update_latest_camera_pose"} + values = {field.name: getattr(camera, field.name) for field in fields(CameraCfg) if field.name not in own} + return FoveatedCameraCfg(**values, foveated_res=foveated_res or camera.width, mask_to_sensor_fov=True) + + +def foveated_presets(cameras: PresetCfg) -> PresetCfg: + """The foveated version of every camera preset, under the same names. Other sensors are left out.""" + options = {} + for name in cameras.__dataclass_fields__: + camera = getattr(cameras, name) + if not name.startswith("_") and isinstance(camera, CameraCfg): + options[name] = foveated_camera(camera) + return preset(**options) + + +def select_presets(options: PresetCfg, names) -> PresetCfg: + """The options of a preset whose names are in ``names``, plus its default.""" + return preset( + **{name: getattr(options, name) for name in options.__dataclass_fields__ if name in {*names, "default"}} + ) + + +@configclass +class GazeObservationsCfg(ObservationGroupCfg): + """The gaze and its velocity, in field radii.""" + + state = ObservationTermCfg(func=mdp.gaze_state) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + +@configclass +class OracleObservationsCfg(ObservationGroupCfg): + """The teacher's gaze labels. Training labels, never a policy input.""" + + labels: ObservationTermCfg = MISSING + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + +def oracle_observations( + target_cfg: SceneEntityCfg, offset: tuple[float, float, float] = (0.0, 0.0, 0.0) +) -> OracleObservationsCfg: + """The teacher's gaze labels toward a point fixed to an asset.""" + return OracleObservationsCfg( + labels=ObservationTermCfg(func=mdp.gaze_teacher_labels, params={"target_cfg": target_cfg, "offset": offset}) + ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py new file mode 100644 index 000000000000..b488d92c4bd8 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py @@ -0,0 +1,18 @@ +# 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 + +"""Shared agent configuration of the active-gaze camera tasks.""" + +from dataclasses import fields + +from isaaclab_rl.rsl_rl import RslRlPpoAlgorithmCfg + +from isaaclab_fovi.rsl_rl import GazeSupervisedPPOCfg + + +def gaze_supervised(algorithm: RslRlPpoAlgorithmCfg, **kwargs) -> GazeSupervisedPPOCfg: + """The PPO settings of ``algorithm`` with gaze supervision by the teacher.""" + values = {field.name: getattr(algorithm, field.name) for field in fields(algorithm) if field.name != "class_name"} + return GazeSupervisedPPOCfg(**values, **kwargs) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/__init__.py new file mode 100644 index 000000000000..76574dfc3cc4 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/__init__.py @@ -0,0 +1,19 @@ +# 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 + +"""Cartpole with a foveated camera.""" + +import gymnasium as gym + +gym.register( + id="Isaac-Cartpole-Camera-Fovi", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:CartpoleFoviEnvCfg", + "rsl_rl_cfg_entry_point": f"{__name__}.agents:CartpoleFoviPPORunnerCfg", + "default_agent": "rsl_rl", + }, +) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py new file mode 100644 index 000000000000..c9b931ba3a5a --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py @@ -0,0 +1,19 @@ +# 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 + +"""The stock camera PPO with gaze supervision; the actor and critic also see the gaze.""" + +from isaaclab.utils import configclass + +from isaaclab_tasks.core.cartpole.agents.rsl_rl_ppo_cfg import CartpoleCameraPPORunnerCfg + +from ..agents import gaze_supervised + + +@configclass +class CartpoleFoviPPORunnerCfg(CartpoleCameraPPORunnerCfg): + experiment_name = "cartpole_fovi" + obs_groups = {"actor": ["policy", "gaze"], "critic": ["critic", "gaze"]} + algorithm = gaze_supervised(CartpoleCameraPPORunnerCfg().algorithm) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py new file mode 100644 index 000000000000..97e2ec4922b4 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py @@ -0,0 +1,80 @@ +# 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 + +"""Cartpole with a foveated camera, in RGB or depth. + +The stock camera task with the camera foveated and two gaze actions. The teacher looks at the pole's tip. +""" + +from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg +from isaaclab.utils import configclass + +from isaaclab_tasks.core.cartpole import mdp as cartpole_mdp +from isaaclab_tasks.core.cartpole.cartpole_common import CartpoleTiledCameraCfg +from isaaclab_tasks.core.cartpole.cartpole_manager_camera_env_cfg import CartpoleCameraEnvCfg, CartpoleCameraSceneCfg +from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ActionsCfg as CartpoleActionsCfg +from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ObservationsCfg as CartpoleObservationsCfg +from isaaclab_tasks.utils import PresetCfg + +from isaaclab_fovi import mdp + +from ..active_gaze import GazeObservationsCfg, foveated_presets, oracle_observations, select_presets + +POLE_TIP = (0.0, 0.0, 1.0) +"""The pole's tip in the pole's frame [m].""" + + +@configclass +class SceneCfg(CartpoleCameraSceneCfg): + tiled_camera = select_presets(foveated_presets(CartpoleTiledCameraCfg()), ("rgb", "depth")) + + +@configclass +class ActionsCfg(CartpoleActionsCfg): + # The gaze must be the last action term. + gaze = mdp.GazeActionCfg(asset_name="tiled_camera") + + +def observations(data_type: str, image_term) -> object: + """The stock camera observations of ``data_type``, the gaze, and the teacher's labels.""" + + @configclass + class ObservationsCfg: + @configclass + class PolicyCfg(ObservationGroupCfg): + image = ObservationTermCfg( + func=image_term, + params={ + "sensor_cfg": SceneEntityCfg("tiled_camera"), + "data_type": data_type, + "channel_first": True, + "frame_stack": 2, + }, + ) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + policy: ObservationGroupCfg = PolicyCfg() + critic: ObservationGroupCfg = CartpoleObservationsCfg.PolicyCfg() + gaze: ObservationGroupCfg = GazeObservationsCfg() + oracle: ObservationGroupCfg = oracle_observations(SceneEntityCfg("robot", body_names="pole"), POLE_TIP) + + return ObservationsCfg() + + +@configclass +class CartpoleFoviEnvCfg(PresetCfg): + """Cartpole with a foveated camera; ``presets=depth`` selects depth images.""" + + @configclass + class BaseCfg(CartpoleCameraEnvCfg.BaseCartpoleCameraEnvCfg): + scene: SceneCfg = SceneCfg(num_envs=512, env_spacing=20.0) + actions: ActionsCfg = ActionsCfg() + + rgb = BaseCfg(observations=observations("rgb", cartpole_mdp.image_rgb)) + depth = BaseCfg(observations=observations("depth", cartpole_mdp.image_depth)) + default = rgb diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/__init__.py new file mode 100644 index 000000000000..2e377cd6d73e --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/__init__.py @@ -0,0 +1,20 @@ +# 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 + +"""Kuka-Allegro lift and reorientation with a foveated base camera.""" + +import gymnasium as gym + +for task, cfg in (("Lift", "KukaAllegroLiftFoviEnvCfg"), ("Reorient", "KukaAllegroReorientFoviEnvCfg")): + gym.register( + id=f"Isaac-{task}-KukaAllegro-Camera-Fovi", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:{cfg}", + "rsl_rl_cfg_entry_point": f"{__name__}.agents:KukaAllegroFoviPPORunnerCfg", + "default_agent": "rsl_rl", + }, + ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py new file mode 100644 index 000000000000..05b64dc0a4ea --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py @@ -0,0 +1,25 @@ +# 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 + +"""The stock single-camera PPO with gaze supervision; the actor and critic also see the gaze.""" + +from isaaclab.utils import configclass + +from isaaclab_tasks.core.lift.config.kuka_allegro.agents.rsl_rl_ppo_cfg import ( + CAMERA_ALGO_CFG, + KukaAllegroSingleCameraPPORunnerCfg, +) + +from ..agents import gaze_supervised + + +@configclass +class KukaAllegroFoviPPORunnerCfg(KukaAllegroSingleCameraPPORunnerCfg): + experiment_name = "kuka_allegro_fovi" + obs_groups = { + "actor": ["policy", "proprio", "base_image", "gaze"], + "critic": ["policy", "proprio", "perception", "gaze"], + } + algorithm = gaze_supervised(CAMERA_ALGO_CFG) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py new file mode 100644 index 000000000000..83c4812be710 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py @@ -0,0 +1,80 @@ +# 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 + +"""Kuka-Allegro lift and reorientation with a foveated base camera. + +The stock single-camera tasks with the base camera foveated and two gaze actions. The teacher looks at the object: +the goal is a commanded pose, given to the policy as state and not drawn in the image, so there is nothing else to +look at. +""" + +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils import configclass + +from isaaclab_tasks.core.lift.config.kuka_allegro.camera_cfg import BaseTiledCameraCfg, SingleCameraObservationsCfg +from isaaclab_tasks.core.lift.config.kuka_allegro.kuka_allegro_camera_env_cfg import SingleCameraSceneCfg +from isaaclab_tasks.core.lift.config.kuka_allegro.kuka_allegro_env_cfg import ( + KukaAllegroLiftEnvCfg, + KukaAllegroRelJointPosActionCfg, + KukaAllegroReorientEnvCfg, +) + +from isaaclab_fovi import mdp + +from ..active_gaze import GazeObservationsCfg, foveated_presets, oracle_observations, select_presets + +BASE_CAMERAS = foveated_presets(BaseTiledCameraCfg()) +"""The base camera presets that are cameras (not ray casters), foveated.""" + + +@configclass +class SceneCfg(SingleCameraSceneCfg): + base_camera = BASE_CAMERAS + + +@configclass +class ActionsCfg(KukaAllegroRelJointPosActionCfg): + # The gaze must be the last action term. + gaze = mdp.GazeActionCfg(asset_name="base_camera") + + +@configclass +class ObservationsCfg(SingleCameraObservationsCfg): + @configclass + class BaseImageObsCfg(SingleCameraObservationsCfg.BaseImageObsCfg): + object_observation_b = select_presets( + SingleCameraObservationsCfg.BaseImageObsCfg().object_observation_b, BASE_CAMERAS.__dataclass_fields__ + ) + + base_image = BaseImageObsCfg() + gaze = GazeObservationsCfg() + oracle = oracle_observations(SceneEntityCfg("object")) + + +def _foveate(env_cfg): + # Moving the gaze is free; the action penalty applies to the hand and arm only. + env_cfg.rewards.action_l2.func = mdp.motor_action_l2 + + +@configclass +class KukaAllegroLiftFoviEnvCfg(KukaAllegroLiftEnvCfg): + scene: SceneCfg = SceneCfg(num_envs=4096, env_spacing=3) + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + + def __post_init__(self): + super().__post_init__() + _foveate(self) + + +@configclass +class KukaAllegroReorientFoviEnvCfg(KukaAllegroReorientEnvCfg): + scene: SceneCfg = SceneCfg(num_envs=4096, env_spacing=3) + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + + def __post_init__(self): + super().__post_init__() + _foveate(self) diff --git a/source/isaaclab_fovi/pyproject.toml b/source/isaaclab_fovi/pyproject.toml index 1f8c7bcac8ad..b56ed7b86fcf 100644 --- a/source/isaaclab_fovi/pyproject.toml +++ b/source/isaaclab_fovi/pyproject.toml @@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta" [project] name = "isaaclab_fovi" version = "0.1.0" -description = "Extension providing foveated camera sensors for the Newton and RTX renderers." +description = "Foveated camera sensors for the Newton and RTX renderers, and active-gaze camera tasks." license = {text = "BSD-3-Clause"} authors = [{name = "Isaac Lab Project Developers"}] maintainers = [{name = "Isaac Lab Project Developers"}] @@ -19,10 +19,17 @@ requires-python = ">=3.12" # Only interpackage dependencies should go here. dependencies = [ "isaaclab", + "isaaclab_rl", + "isaaclab_tasks", ] +[project.entry-points."isaaclab.tasks"] +isaaclab_fovi = "isaaclab_fovi.tasks" + [tool.uv.sources] isaaclab = { path = "../isaaclab", editable = true } +isaaclab_rl = { path = "../isaaclab_rl", editable = true } +isaaclab_tasks = { path = "../isaaclab_tasks", editable = true } [project.urls] Homepage = "https://github.com/isaac-sim/IsaacLab" diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py new file mode 100644 index 000000000000..9190b553bb85 --- /dev/null +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -0,0 +1,77 @@ +# 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 + +"""Gaze geometry and gaze-supervised PPO, without a simulator.""" + +import pytest +import torch +from isaaclab_fovi.mdp import angles_to_direction, clamp_gaze, direction_to_angles +from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss +from rsl_rl.models import MLPModel +from rsl_rl.storage import RolloutStorage +from tensordict import TensorDict + +NUM_ENVS = 64 +STEPS = 8 + + +def test_gaze_angles_round_trip_and_follow_the_camera_convention(): + angles = torch.tensor([[0.0, 0.0], [10.0, 0.0], [0.0, 10.0], [-20.0, 35.0]]) + directions = angles_to_direction(angles) + torch.testing.assert_close(direction_to_angles(directions), angles, atol=1e-4, rtol=0) + # OpenCV camera frame: z forward, y down, x right; positive tilt looks up, positive pan looks left. + torch.testing.assert_close(directions[0], torch.tensor([0.0, 0.0, 1.0])) + assert directions[1, 1] < 0 and directions[2, 0] < 0 + + +def test_clamp_gaze_is_radial(): + gaze = torch.tensor([[0.3, 0.4], [3.0, 4.0]]) + torch.testing.assert_close(clamp_gaze(gaze, 1.0), torch.tensor([[0.3, 0.4], [0.6, 0.8]])) + + +def test_gaze_loss_ignores_invalid_labels(): + mean = torch.tensor([[0.0, 0.0], [1.0, 1.0]], requires_grad=True) + labels = torch.tensor([[0.3, 0.4, 1.0], [float("nan"), float("nan"), 0.0]]) + loss = gaze_loss(mean, labels) + loss.backward() + assert float(loss.detach()) == pytest.approx(0.5) + assert torch.isfinite(mean.grad).all() and not mean.grad[1].any() + + +def _algorithm() -> tuple[GazeSupervisedPPO, TensorDict]: + torch.manual_seed(0) + labels = torch.rand(NUM_ENVS, 3) * 2 - 1 + labels[:, 2] = (torch.arange(NUM_ENVS) % 4 != 0).float() + labels[labels[:, 2] == 0, :2] = float("nan") + obs = TensorDict({"policy": torch.randn(NUM_ENVS, 6), "oracle": labels}, batch_size=[NUM_ENVS]) + groups = {"actor": ["policy"], "critic": ["policy"]} + distribution = {"class_name": "GaussianDistribution", "init_std": 1.0} + actor = MLPModel(obs, groups, "actor", 3, hidden_dims=[32], distribution_cfg=distribution) + critic = MLPModel(obs, groups, "critic", 1, hidden_dims=[32]) + storage = RolloutStorage("rl", NUM_ENVS, STEPS, obs, [3], "cpu") + settings = dict(num_learning_epochs=4, num_mini_batches=4, learning_rate=3e-3, schedule="fixed", device="cpu") + return GazeSupervisedPPO(actor, critic, storage, **settings), obs + + +def test_update_pulls_the_gaze_toward_the_teacher(): + algorithm, obs = _algorithm() + valid = obs["oracle"][:, 2] > 0.5 + + def distance() -> float: + with torch.no_grad(): + mean = algorithm.actor(obs)[:, -2:] + return float((mean - obs["oracle"][:, :2])[valid].norm(dim=-1).mean()) + + before = distance() + for _ in range(40): + for _ in range(STEPS): + with torch.inference_mode(): + algorithm.act(obs) + algorithm.process_env_step(obs, torch.zeros(NUM_ENVS), torch.zeros(NUM_ENVS), {}) + algorithm.compute_returns(obs) + losses = algorithm.update() + assert losses["oracle_valid"] == pytest.approx(0.75) + assert all(torch.isfinite(p).all() for p in algorithm.actor.parameters()) + assert distance() < 0.7 * before diff --git a/uv.lock b/uv.lock index 1c15ce2e3c66..db210039482b 100644 --- a/uv.lock +++ b/uv.lock @@ -2254,10 +2254,16 @@ version = "0.1.0" source = { editable = "source/isaaclab_fovi" } dependencies = [ { name = "isaaclab" }, + { name = "isaaclab-rl" }, + { name = "isaaclab-tasks" }, ] [package.metadata] -requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }] +requires-dist = [ + { name = "isaaclab", editable = "source/isaaclab" }, + { name = "isaaclab-rl", editable = "source/isaaclab_rl" }, + { name = "isaaclab-tasks", editable = "source/isaaclab_tasks" }, +] [[package]] name = "isaaclab-isaacsim" From b81202024b99e88f94b724852f4c29deeaeb0cac Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 17:32:51 -0800 Subject: [PATCH 21/81] Give the foveated Cartpole task a 32-sample retina Seeing the pole needs little resolution: at 32 samples across, the policy trains as well as at the stock camera's 96 pixels, several times faster. The stock Cartpole camera task is unchanged. --- source/isaaclab_fovi/docs/README.md | 16 ++++++++-------- .../isaaclab_fovi/tasks/active_gaze.py | 9 ++++++--- .../isaaclab_fovi/tasks/cartpole/env_cfg.py | 8 ++++++-- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index 67c0679d6298..56b07783de5c 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -120,18 +120,18 @@ an `oracle` observation group that the actor and critic never see. ### Tasks Each task is its stock camera counterpart with the camera foveated at the same -mount, optics and resolution, two gaze actions, and gaze supervision. The vision -model and the PPO settings are the stock ones. +mount and optics, two gaze actions, and gaze supervision. The vision model and +the PPO settings are the stock ones. -| Task | Teacher looks at | -| --- | --- | -| `Isaac-Cartpole-Camera-Fovi` (`presets=depth` for depth) | the pole's tip | -| `Isaac-Lift-KukaAllegro-Camera-Fovi` | the object | -| `Isaac-Reorient-KukaAllegro-Camera-Fovi` | the object | +| Task | Retina | Teacher looks at | +| --- | --- | --- | +| `Isaac-Cartpole-Camera-Fovi` (`presets=depth` for depth) | 32 × 32 | the pole's tip | +| `Isaac-Lift-KukaAllegro-Camera-Fovi` | the camera preset's resolution | the object | +| `Isaac-Reorient-KukaAllegro-Camera-Fovi` | the camera preset's resolution | the object | The Kuka-Allegro tasks take the stock base-camera presets, such as `presets=depth128`. Set the retina's resolution with, for example, -`env.scene.tiled_camera.foveated_res=48`. +`env.scene.tiled_camera.foveated_res=96`. ```bash uv run isaaclab train --rl_library rsl_rl --task Isaac-Cartpole-Camera-Fovi diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py index bce9161cbae8..cd7ae031a24d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py @@ -32,13 +32,16 @@ def foveated_camera(camera: CameraCfg, foveated_res: int | None = None) -> Fovea return FoveatedCameraCfg(**values, foveated_res=foveated_res or camera.width, mask_to_sensor_fov=True) -def foveated_presets(cameras: PresetCfg) -> PresetCfg: - """The foveated version of every camera preset, under the same names. Other sensors are left out.""" +def foveated_presets(cameras: PresetCfg, foveated_res: int | None = None) -> PresetCfg: + """The foveated version of every camera preset, under the same names. Other sensors are left out. + + ``foveated_res`` applies to every preset; by default each keeps its camera's width. + """ options = {} for name in cameras.__dataclass_fields__: camera = getattr(cameras, name) if not name.startswith("_") and isinstance(camera, CameraCfg): - options[name] = foveated_camera(camera) + options[name] = foveated_camera(camera, foveated_res) return preset(**options) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py index 97e2ec4922b4..f0b5ae0723ec 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py @@ -5,7 +5,8 @@ """Cartpole with a foveated camera, in RGB or depth. -The stock camera task with the camera foveated and two gaze actions. The teacher looks at the pole's tip. +The stock camera task with the camera foveated and two gaze actions. The teacher looks at the pole's tip. The retina +is :data:`RETINA_RES` samples across, enough for a task that only needs to see a bar. """ from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg @@ -25,10 +26,13 @@ POLE_TIP = (0.0, 0.0, 1.0) """The pole's tip in the pole's frame [m].""" +RETINA_RES = 32 +"""Retina samples across. The stock camera's 96 pixels train no better on this task, at several times the cost.""" + @configclass class SceneCfg(CartpoleCameraSceneCfg): - tiled_camera = select_presets(foveated_presets(CartpoleTiledCameraCfg()), ("rgb", "depth")) + tiled_camera = select_presets(foveated_presets(CartpoleTiledCameraCfg(), RETINA_RES), ("rgb", "depth")) @configclass From 641a26df92f492079d97e74d479ebe203420f935 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 17:53:56 -0800 Subject: [PATCH 22/81] Compute the gaze, the sensor mask and the teacher in Warp kernels Each frame recomputed the gaze pose, the sensor mask and the teacher's labels from dozens of small torch operations. One kernel now sets the gaze, one applies it to the camera pose, one masks the samples the physical camera does not see, and one computes the teacher's action, validity and fixation error. The projection mirrors fovi's CameraModel.project and is tested against it for pinhole, distorted pinhole and fisheye cameras. On the 32-sample Cartpole task with 1024 environments, an environment step takes 1.8 ms instead of 3.3 ms. --- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 136 ++++++++--- .../sensors/calibrated_geometry.py | 45 ---- .../isaaclab_fovi/sensors/gaze_kernels.py | 217 ++++++++++++++++++ .../isaaclab_fovi/sensors/virtual_gaze.py | 102 +++++--- source/isaaclab_fovi/test/test_active_gaze.py | 52 +++++ .../isaaclab_fovi/test/test_gaze_kernels.py | 107 +++++++++ .../test/test_spherical_geometry.py | 46 +--- 7 files changed, 561 insertions(+), 144 deletions(-) create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py create mode 100644 source/isaaclab_fovi/test/test_gaze_kernels.py diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 3494cc4c5a18..3862fa0cd41d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -18,16 +18,63 @@ from typing import TYPE_CHECKING import torch +import warp as wp -from isaaclab.managers import ActionTerm, ActionTermCfg, SceneEntityCfg +from isaaclab.managers import ActionTerm, ActionTermCfg, ManagerTermBase, ObservationTermCfg, SceneEntityCfg from isaaclab.utils import configclass from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_apply, quat_apply_inverse from ..sensors.calibrated_geometry import resolve_camera_model, sampling_geometry +from ..sensors.gaze_kernels import ( + DEG_TO_RAD, + CameraParams, + camera_params, + project_direction, + project_directions, + torch_stream, +) if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv, ManagerBasedRLEnv +RAD_TO_DEG = 180.0 / math.pi + + +@wp.kernel(enable_backward=False) +def teacher_kernel( + points: wp.array(dtype=wp.vec3f), + positions: wp.array(dtype=wp.vec3f), + mount: wp.quatf, + gaze: wp.array(dtype=wp.vec2f), + field_radius_deg: wp.float32, + step_size: wp.float32, + gaze_limit: wp.float32, + camera: CameraParams, + action: wp.array(dtype=wp.vec2f), + valid: wp.array(dtype=wp.bool), + error_deg: wp.array(dtype=wp.float32), +): + """The teacher's action toward each point, whether the point is a valid target, and the gaze's error to it.""" + i = wp.tid() + d = wp.normalize(wp.quat_rotate_inv(mount, points[i] - positions[i])) + tilt = -wp.atan2(d[1], wp.sqrt(d[0] * d[0] + d[2] * d[2])) * wp.float32(RAD_TO_DEG) + pan = -wp.atan2(d[0], d[2]) * wp.float32(RAD_TO_DEG) + desired = wp.vec2f(tilt, pan) / field_radius_deg + g = gaze[i] + ok = project_direction(d, camera)[2] > 0.5 and wp.length(desired) <= gaze_limit + step = wp.vec2f(0.0, 0.0) + if ok: + step = wp.vec2f( + wp.clamp((desired[0] - g[0]) / step_size, -1.0, 1.0), wp.clamp((desired[1] - g[1]) / step_size, -1.0, 1.0) + ) + action[i] = step + valid[i] = ok + g_tilt = g[0] * field_radius_deg * wp.float32(DEG_TO_RAD) + g_pan = g[1] * field_radius_deg * wp.float32(DEG_TO_RAD) + looking = wp.vec3f(-wp.cos(g_tilt) * wp.sin(g_pan), -wp.sin(g_tilt), wp.cos(g_tilt) * wp.cos(g_pan)) + # atan2 stays accurate near perfect alignment, unlike acos of the dot product. + error_deg[i] = wp.atan2(wp.length(wp.cross(looking, d)), wp.dot(looking, d)) * wp.float32(RAD_TO_DEG) + def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3).""" @@ -72,6 +119,7 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): if camera_cfg.prim_path.rpartition("/")[0] not in ("{ENV_REGEX_NS}", env.scene.env_regex_ns): raise ValueError(f"Gaze needs a camera mounted on the environment, got {camera_cfg.prim_path!r}.") self.camera_model = resolve_camera_model(camera_cfg) + self._camera = camera_params(self.camera_model) self.field_radius_deg = sampling_geometry(camera_cfg)[0] / 2 """Half the retina's field of view [deg].""" offset = camera_cfg.offset @@ -80,6 +128,7 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): rotation, origin=offset.convention, target="ros" )[0] """Orientation (x, y, z, w) of the physical camera in the environment frame, ROS convention.""" + self._mount = wp.quatf(*self.mount_rotation.tolist()) self._raw = torch.zeros(self.num_envs, 2, device=self.device) self._gaze = torch.zeros_like(self._raw) self._velocity = torch.zeros_like(self._raw) @@ -140,25 +189,39 @@ def directions(self, points: torch.Tensor) -> torch.Tensor: def visible(self, direction: torch.Tensor) -> torch.Tensor: """Whether camera-frame directions fall inside the physical camera's image.""" - return self.camera_model.project(direction)[1] + return project_directions(direction, self._camera)[1] - def teacher_action(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """The action that moves the gaze toward world points, and whether each point is a valid target. + def teacher(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """The teacher's action toward one world point per environment, in one launch. - A point is valid when the physical camera sees it and the gaze can reach it within the limit. - """ - direction = self.directions(points) - desired = direction_to_angles(direction) / self.field_radius_deg - valid = self.visible(direction) & (desired.norm(dim=-1) <= self.cfg.gaze_limit) - action = ((desired - self._gaze) / self.cfg.step_size).clamp(-1, 1) - return torch.where(valid[:, None], action, 0.0), valid + A point is a valid target when the physical camera sees it and the gaze can reach it within the limit; the + action toward an invalid target is zero. - def fixation_error_deg(self, points: torch.Tensor) -> torch.Tensor: - """Angle [deg] between the gaze and the direction to world points, shape (num_envs,).""" - direction = self.directions(points) - gaze = angles_to_direction(self.angles_deg) - # atan2 stays accurate near perfect alignment, unlike acos of the dot product. - return torch.atan2(torch.cross(gaze, direction, dim=-1).norm(dim=-1), (gaze * direction).sum(-1)).rad2deg() + Returns: + The actions, shape (num_envs, 2); whether each point is a valid target, shape (num_envs,); and the angle + between the gaze and each point [deg], shape (num_envs,). + """ + points = points.float().contiguous() + action = torch.empty(len(points), 2, device=self.device) + valid = torch.empty(len(points), dtype=torch.bool, device=self.device) + error = torch.empty(len(points), device=self.device) + with torch_stream(self.device): + wp.launch( + teacher_kernel, + dim=len(points), + inputs=[ + wp.from_torch(points, dtype=wp.vec3f), + self.camera.data.pos_w.warp, + self._mount, + wp.from_torch(self._gaze, dtype=wp.vec2f), + self.field_radius_deg, + self.cfg.step_size, + self.cfg.gaze_limit, + self._camera, + ], + outputs=[wp.from_torch(action, dtype=wp.vec2f), wp.from_torch(valid), wp.from_torch(error)], + ) + return action, valid, error @configclass @@ -183,7 +246,9 @@ def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: def entity_point( - env: ManagerBasedEnv, asset_cfg: SceneEntityCfg, offset: tuple[float, float, float] = (0.0, 0.0, 0.0) + env: ManagerBasedEnv, + asset_cfg: SceneEntityCfg, + offset: tuple[float, float, float] | torch.Tensor = (0.0, 0.0, 0.0), ) -> torch.Tensor: """World position of a point fixed to an asset's root, or to its first selected body, shape (num_envs, 3). @@ -197,7 +262,8 @@ def entity_point( else: body = asset_cfg.body_ids[0] position, orientation = data.body_pos_w.torch[:, body], data.body_quat_w.torch[:, body] - return position + quat_apply(orientation, torch.tensor(offset, device=env.device).expand_as(position)) + offset = torch.as_tensor(offset, dtype=position.dtype, device=position.device) + return position + quat_apply(orientation, offset.expand_as(position)) def teacher_labels(env: ManagerBasedEnv, points: torch.Tensor, action_name: str = "gaze") -> torch.Tensor: @@ -207,22 +273,34 @@ def teacher_labels(env: ManagerBasedEnv, points: torch.Tensor, action_name: str the object is grasped, choose the points and call this. """ term: GazeAction = env.action_manager.get_term(action_name) - action, valid = term.teacher_action(points) - error = term.fixation_error_deg(points) + action, valid, error = term.teacher(points) log = env.extras.setdefault("log", {}) log["Gaze/target_error_deg"] = torch.where(valid, error, 0.0).sum() / valid.sum().clamp_min(1) log["Gaze/valid_target_fraction"] = valid.float().mean() return torch.cat((action, valid[:, None].float()), dim=-1) -def gaze_teacher_labels( - env: ManagerBasedEnv, - target_cfg: SceneEntityCfg, - offset: tuple[float, float, float] = (0.0, 0.0, 0.0), - action_name: str = "gaze", -) -> torch.Tensor: - """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3).""" - return teacher_labels(env, entity_point(env, target_cfg, offset), action_name) +class gaze_teacher_labels(ManagerTermBase): + """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3). + + Args: + target_cfg: The asset, and optionally one body by ``body_names``. + offset: The point in the root's or the body's frame [m]. + action_name: The gaze action term. + """ + + def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._offset = torch.tensor(cfg.params.get("offset", (0.0, 0.0, 0.0)), device=env.device) + + def __call__( + self, + env: ManagerBasedEnv, + target_cfg: SceneEntityCfg, + offset: tuple[float, float, float] = (0.0, 0.0, 0.0), + action_name: str = "gaze", + ) -> torch.Tensor: + return teacher_labels(env, entity_point(env, target_cfg, self._offset), action_name) def motor_action_l2(env: ManagerBasedRLEnv, gaze_action_name: str = "gaze") -> torch.Tensor: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index 0eb4001d4c6c..af930faf6fb8 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -11,7 +11,6 @@ from typing import Any, Literal, Protocol import torch -import warp as wp from fovi.sensing.projection import CameraCalibration, CameraModel, angular_directions IDEAL_IMAGE_WIDTH = 1024 @@ -152,47 +151,3 @@ def convert_camera_frame_quaternion( else: raise ValueError(f"Unsupported camera conversion: {origin!r} to {target!r}") return torch.stack(components, dim=-1) * 0.5 - - -@wp.kernel(enable_backward=False) -def _rotate_camera_rays( - rays: wp.array(dtype=wp.vec3), - rotations: wp.array(dtype=wp.mat33), - output: wp.array2d(dtype=wp.vec3), -): - batch, sample = wp.tid() - output[batch, sample] = rotations[batch] * rays[sample] - - -def rotate_camera_rays(canonical_rays: torch.Tensor, rotation: torch.Tensor) -> torch.Tensor: - """Rotate visibility rays with IEEE float32, independent of model TF32 settings.""" - if canonical_rays.is_cuda and canonical_rays.dtype == rotation.dtype == torch.float32: - wp.init() # stream_from_torch requires an initialized Warp runtime. - result = canonical_rays.new_empty((len(rotation), len(canonical_rays), 3)) - torch_stream = torch.cuda.current_stream(canonical_rays.device) - stream = wp.get_stream(wp.device_from_torch(canonical_rays.device)) - # Temporary aliases unregister even a live Warp-owned stream when destroyed. - if stream.cuda_stream != torch_stream.cuda_stream: - stream = wp.stream_from_torch(torch_stream) - with wp.ScopedStream( - stream, - sync_enter=False, - sync_exit=False, - ): - wp.launch( - _rotate_camera_rays, - dim=result.shape[:2], - inputs=[ - wp.from_torch(canonical_rays.contiguous(), dtype=wp.vec3), - wp.from_torch(rotation.contiguous(), dtype=wp.mat33), - ], - outputs=[wp.from_torch(result, dtype=wp.vec3)], - ) - return result - return canonical_rays @ rotation.transpose(-1, -2) - - -def sensor_visibility(camera: CameraModel, canonical_rays: torch.Tensor, rotation: torch.Tensor) -> torch.Tensor: - """Mask OpenCV-frame canonical rays, turned by the gaze, against the fixed physical camera.""" - _, valid = camera.project(rotate_camera_rays(canonical_rays, rotation)) - return valid diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py new file mode 100644 index 000000000000..22093fd0bb0e --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -0,0 +1,217 @@ +# 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 + +"""Warp kernels of the virtual gaze, one launch each per gaze change, camera pose update and sensor mask. + +:func:`project_direction` follows :meth:`fovi.sensing.projection.CameraModel.project` operation for operation, in +float32. Camera-frame directions follow the ROS (OpenCV) convention: x right, y down, z forward. +""" + +from __future__ import annotations + +import contextlib +import math + +import torch +import warp as wp +from fovi.sensing.projection import CameraModel + +vec8f = wp.types.vector(length=8, dtype=wp.float32) + +FLOAT32_EPS = float(torch.finfo(torch.float32).eps) +DEG_TO_RAD = math.pi / 180.0 + + +@contextlib.contextmanager +def torch_stream(device: torch.device | str): + """Launch Warp kernels on the tensors' device and, on CUDA, PyTorch's current stream.""" + device = torch.device(device) + wp.init() + if device.type != "cuda": + with wp.ScopedDevice(wp.device_from_torch(device)): + yield + return + torch_current = torch.cuda.current_stream(device) + stream = wp.get_stream(wp.device_from_torch(device)) + # A temporary alias of a live Warp-owned stream would unregister it when destroyed. + if stream.cuda_stream != torch_current.cuda_stream: + stream = wp.stream_from_torch(torch_current) + with wp.ScopedStream(stream, sync_enter=False, sync_exit=False): + yield + + +@wp.struct +class CameraParams: + """A :class:`~fovi.sensing.projection.CameraModel` for Warp kernels.""" + + fisheye: wp.int32 + focal: wp.vec2f + center: wp.vec2f + size: wp.vec2f + """Image width and height [px].""" + distortion: vec8f + """Pinhole (k1, k2, p1, p2, k3, k4, k5, k6) or fisheye (k1, k2, k3, k4), zero-padded.""" + has_circle: wp.int32 + circle: wp.vec3f + max_angle: wp.float32 + """Largest angle from the optical axis [rad].""" + + +def camera_params(model: CameraModel) -> CameraParams: + """The Warp form of a camera model.""" + params = CameraParams() + params.fisheye = int(model.model == "fisheye") + fx, fy, cx, cy = model.intrinsics + params.focal = wp.vec2f(fx, fy) + params.center = wp.vec2f(cx, cy) + height, width = model.image_size + params.size = wp.vec2f(width, height) + params.distortion = vec8f(*model.distortion, *([0.0] * (8 - len(model.distortion)))) + params.has_circle = int(model.image_circle is not None) + params.circle = wp.vec3f(*(model.image_circle or (0.0, 0.0, 1.0))) + # fovi compares float32 angles against the limit converted to float32. + params.max_angle = float(torch.tensor(math.radians(model.max_angle_deg), dtype=torch.float32)) + return params + + +@wp.func +def project_direction(d: wp.vec3f, camera: CameraParams) -> wp.vec3f: + """Pixel (x, y) of a camera-frame direction, and 1 where the camera sees it, else 0.""" + eps = wp.float32(FLOAT32_EPS) + z = d[2] + lateral = wp.sqrt(d[0] * d[0] + d[1] * d[1]) + theta = wp.atan2(lateral, z) + k = camera.distortion + x = wp.float32(0.0) + y = wp.float32(0.0) + if camera.fisheye == 0: + depth = wp.max(z, eps) + u = d[0] / depth + v = d[1] / depth + r2 = u * u + v * v + radial = (1.0 + r2 * (k[0] + r2 * (k[1] + r2 * k[4]))) / (1.0 + r2 * (k[5] + r2 * (k[6] + r2 * k[7]))) + x = u * radial + 2.0 * k[2] * u * v + k[3] * (r2 + 2.0 * u * u) + y = v * radial + k[2] * (r2 + 2.0 * v * v) + 2.0 * k[3] * u * v + else: + t2 = theta * theta + radius = theta * (1.0 + t2 * (k[0] + t2 * (k[1] + t2 * (k[2] + t2 * k[3])))) + scale = 1.0 / wp.max(z, eps) + if lateral > eps: + scale = radius / wp.max(lateral, eps) + x = d[0] * scale + y = d[1] * scale + px = x * camera.focal[0] + camera.center[0] + py = y * camera.focal[1] + camera.center[1] + valid = wp.isfinite(px) and wp.isfinite(py) + valid = valid and px >= -0.5 and px < camera.size[0] - 0.5 and py >= -0.5 and py < camera.size[1] - 0.5 + if camera.has_circle != 0: + dx = px - camera.circle[0] + dy = py - camera.circle[1] + valid = valid and dx * dx + dy * dy <= camera.circle[2] * camera.circle[2] + valid = valid and theta <= camera.max_angle + if camera.fisheye == 0: + valid = valid and z > 0.0 + return wp.vec3f(px, py, wp.where(valid, 1.0, 0.0)) + + +@wp.func +def gaze_rotation(angles_deg: wp.vec2f) -> wp.mat33f: + """Pan-then-tilt rotation of a gaze (tilt, pan) [deg], as :func:`fovi.sensing.projection.gaze_rotation`.""" + tilt = angles_deg[0] * wp.float32(DEG_TO_RAD) + pan = angles_deg[1] * wp.float32(DEG_TO_RAD) + x = -wp.cos(tilt) * wp.sin(pan) + y = -wp.sin(tilt) + z = wp.cos(tilt) * wp.cos(pan) + pitch = wp.atan2(x, z) + roll = wp.atan2(-y, wp.sqrt(x * x + z * z)) + cp = wp.cos(pitch) + sp = wp.sin(pitch) + cr = wp.cos(roll) + sr = wp.sin(roll) + return wp.mat33f(cp, sp * sr, sp * cr, 0.0, cr, -sr, -sp, cp * sr, cp * cr) + + +@wp.kernel(enable_backward=False) +def set_gaze_kernel( + angles_deg: wp.array(dtype=wp.vec2f), + basis: wp.mat33f, + to_opengl: wp.quatf, + to_world: wp.quatf, + rotation: wp.array(dtype=wp.mat33f), + pose_delta: wp.array(dtype=wp.quatf), +): + """The gaze rotation of each environment, and the change it makes to the camera's world orientation. + + A camera at world orientation ``q`` (world convention) looks along ``q * pose_delta``. + """ + i = wp.tid() + gaze = gaze_rotation(angles_deg[i]) + rotation[i] = gaze + relative = basis * gaze * wp.transpose(basis) + pose_delta[i] = to_opengl * wp.quat_from_matrix(relative) * to_world + + +@wp.kernel(enable_backward=False) +def apply_gaze_kernel(orientation: wp.array(dtype=wp.quatf), pose_delta: wp.array(dtype=wp.quatf)): + i = wp.tid() + orientation[i] = wp.normalize(orientation[i] * pose_delta[i]) + + +@wp.kernel(enable_backward=False) +def apply_gaze_masked_kernel( + orientation: wp.array(dtype=wp.quatf), pose_delta: wp.array(dtype=wp.quatf), mask: wp.array(dtype=wp.bool) +): + i = wp.tid() + if mask[i]: + orientation[i] = wp.normalize(orientation[i] * pose_delta[i]) + + +@wp.kernel(enable_backward=False) +def apply_gaze_indexed_kernel( + orientation: wp.array(dtype=wp.quatf), pose_delta: wp.array(dtype=wp.quatf), indices: wp.array(dtype=wp.int32) +): + i = indices[wp.tid()] + orientation[i] = wp.normalize(orientation[i] * pose_delta[i]) + + +@wp.kernel(enable_backward=False) +def sensor_visibility_kernel( + rays: wp.array(dtype=wp.vec3f), + rotation: wp.array(dtype=wp.mat33f), + camera: CameraParams, + valid: wp.array2d(dtype=wp.bool), +): + """Whether the physical camera sees each canonical ray turned by each environment's gaze.""" + env, sample = wp.tid() + valid[env, sample] = project_direction(rotation[env] * rays[sample], camera)[2] > 0.5 + + +@wp.kernel(enable_backward=False) +def project_directions_kernel( + directions: wp.array(dtype=wp.vec3f), + camera: CameraParams, + pixels: wp.array(dtype=wp.vec2f), + valid: wp.array(dtype=wp.bool), +): + i = wp.tid() + result = project_direction(directions[i], camera) + pixels[i] = wp.vec2f(result[0], result[1]) + valid[i] = result[2] > 0.5 + + +def project_directions(directions: torch.Tensor, camera: CameraParams) -> tuple[torch.Tensor, torch.Tensor]: + """Project (..., 3) camera-frame directions to (..., 2) pixels and (...,) validity, in one launch.""" + flat = directions.detach().reshape(-1, 3).float().contiguous() + pixels = torch.empty(len(flat), 2, dtype=torch.float32, device=flat.device) + valid = torch.empty(len(flat), dtype=torch.bool, device=flat.device) + if len(flat): + with torch_stream(flat.device): + wp.launch( + project_directions_kernel, + dim=len(flat), + inputs=[wp.from_torch(flat, dtype=wp.vec3f), camera], + outputs=[wp.from_torch(pixels, dtype=wp.vec2f), wp.from_torch(valid, dtype=wp.bool)], + ) + return pixels.reshape(*directions.shape[:-1], 2), valid.reshape(directions.shape[:-1]) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index c2dd3cd25dda..108cec65fe41 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -12,15 +12,17 @@ import torch import warp as wp -from fovi.sensing.projection import angular_directions, gaze_rotation +from fovi.sensing.projection import angular_directions -from isaaclab.utils.math import matrix_from_quat, quat_from_matrix - -from .calibrated_geometry import ( - compose_rotations, - convert_camera_frame_quaternion, - resolve_camera_model, - sensor_visibility, +from .calibrated_geometry import convert_camera_frame_quaternion, resolve_camera_model +from .gaze_kernels import ( + apply_gaze_indexed_kernel, + apply_gaze_kernel, + apply_gaze_masked_kernel, + camera_params, + sensor_visibility_kernel, + set_gaze_kernel, + torch_stream, ) from .native_grid import GRID_STYLE, native_grid_directions @@ -41,52 +43,82 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: Args: angles_deg: Gaze angles for every environment [deg], shape (num_envs, 2). """ - # Geometry must remain float32 even when the policy runs under AMP. - with torch.autocast(angles_deg.device.type, enabled=False): - tilt, pan = angles_deg.float().deg2rad().unbind(-1) - direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) - self._gaze_rotation = gaze_rotation(direction, "pan_tilt") + angles = angles_deg.detach().float().contiguous() + rotation = self._gaze_rotation + if rotation is None or rotation.shape[0] != len(angles) or rotation.device != angles.device: + self._gaze_rotation = torch.empty(len(angles), 3, 3, device=angles.device) + self._gaze_pose_delta = torch.empty(len(angles), 4, device=angles.device) + with torch_stream(angles.device): + wp.launch( + set_gaze_kernel, + dim=len(angles), + inputs=[wp.from_torch(angles, dtype=wp.vec2f), *self._gaze_frames], + outputs=[ + wp.from_torch(self._gaze_rotation, dtype=wp.mat33f), + wp.from_torch(self._gaze_pose_delta, dtype=wp.quatf), + ], + ) def _apply_gaze_pose( self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None ) -> None: if self._gaze_rotation is None: return - stored = self._data.quat_w_world - quat = stored.torch if hasattr(stored, "torch") else stored - with torch.autocast(quat.device.type, enabled=False): - base = convert_camera_frame_quaternion(quat, origin="world", target="opengl") - # Gaze is defined in the upright image frame; rays include mount roll. - basis = self._gaze_basis - relative = compose_rotations(compose_rotations(basis, self._gaze_rotation), basis.T) - composed = quat_from_matrix(compose_rotations(matrix_from_quat(base), relative)) - updated = convert_camera_frame_quaternion(composed, origin="opengl", target="world") + orientation = self._data.quat_w_world + orientation = orientation.warp if hasattr(orientation, "warp") else wp.from_torch(orientation, dtype=wp.quatf) + delta = wp.from_torch(self._gaze_pose_delta, dtype=wp.quatf) + with torch_stream(self._gaze_pose_delta.device): if env_mask is not None: - quat.copy_(torch.where(wp.to_torch(env_mask)[:, None], updated, quat)) - elif env_ids is not None: - indices = wp.to_torch(env_ids) if isinstance(env_ids, wp.array) else env_ids - quat[indices] = updated[indices] + wp.launch(apply_gaze_masked_kernel, dim=len(delta), inputs=[orientation, delta, env_mask]) + elif env_ids is None: + wp.launch(apply_gaze_kernel, dim=len(delta), inputs=[orientation, delta]) else: - quat.copy_(updated) + if not isinstance(env_ids, wp.array): + ids = torch.as_tensor(env_ids, dtype=torch.int32, device=self._gaze_pose_delta.device) + env_ids = wp.from_torch(ids.contiguous()) + wp.launch(apply_gaze_indexed_kernel, dim=len(env_ids), inputs=[orientation, delta, env_ids]) def _gaze_validity(self, batch_size: int) -> torch.Tensor: """Return which samples the physical camera sees at the current gaze, shape (batch_size, num_samples).""" - rays = self._gaze_rays - with torch.autocast(rays.device.type, enabled=False): - rotation = self._gaze_rotation - if rotation is None: - rotation = self._gaze_identity.expand(batch_size, -1, -1) - # A receptive field can overlap the sensor even when its center is outside it. - return sensor_visibility(self._camera_model, rays, rotation) + rotation = self._gaze_rotation + if rotation is None: + rotation = self._gaze_identity.expand(batch_size, -1, -1).contiguous() + rays = self._gaze_rays.to(rotation.device) + valid = torch.empty(batch_size, len(rays), dtype=torch.bool, device=rotation.device) + # A receptive field can overlap the sensor even when its center is outside it. + with torch_stream(rotation.device): + wp.launch( + sensor_visibility_kernel, + dim=valid.shape, + inputs=[ + wp.from_torch(rays, dtype=wp.vec3f), + wp.from_torch(rotation.contiguous(), dtype=wp.mat33f), + self._gaze_camera, + ], + outputs=[wp.from_torch(valid, dtype=wp.bool)], + ) + return valid def _initialize_gaze(self) -> None: self._camera_model = resolve_camera_model(self.cfg) + self._gaze_camera = camera_params(self._camera_model) coords = self._sampling_coords_highres or self._sampling_coords if coords.style == GRID_STYLE: self._gaze_rays = native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1)) else: self._gaze_rays = angular_directions(coords.cartesian, coords.fov) - self._gaze_identity = torch.eye(3, device=coords.device) + self._gaze_rays = self._gaze_rays.float().contiguous() + device = self._gaze_rays.device + self._gaze_identity = torch.eye(3, device=device) angle = math.radians(self.cfg.image_rotation_deg) c, s = math.cos(angle), math.sin(angle) + # Gaze is defined in the upright image frame; rays include mount roll. self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device) + to_opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl")[0].tolist() + to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0].tolist() + self._gaze_frames = ( + wp.mat33f(*self._gaze_basis.flatten().tolist()), + wp.quatf(*to_opengl), + wp.quatf(*to_world), + ) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 9190b553bb85..4e5ab454aac0 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -7,12 +7,18 @@ import pytest import torch +import warp as wp +from fovi.sensing.projection import CameraModel from isaaclab_fovi.mdp import angles_to_direction, clamp_gaze, direction_to_angles +from isaaclab_fovi.mdp.gaze import teacher_kernel from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss +from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream from rsl_rl.models import MLPModel from rsl_rl.storage import RolloutStorage from tensordict import TensorDict +from isaaclab.utils.math import quat_apply, quat_apply_inverse + NUM_ENVS = 64 STEPS = 8 @@ -31,6 +37,52 @@ def test_clamp_gaze_is_radial(): torch.testing.assert_close(clamp_gaze(gaze, 1.0), torch.tensor([[0.3, 0.4], [0.6, 0.8]])) +def test_teacher_kernel_matches_the_torch_teacher(): + camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5), distortion=(-0.1, 0.02, 0.0, 0.0)) + field_radius, step, limit = 30.0, 0.1, 1.0 + generator = torch.Generator().manual_seed(3) + count = 4096 + mount = torch.nn.functional.normalize(torch.randn(4, generator=generator), dim=0) + positions = torch.randn(count, 3, generator=generator) + # Points mostly in front of the camera, spread across and beyond its field of view. + lateral = torch.randn(count, 2, generator=generator) * 0.6 + local = torch.cat((lateral, torch.rand(count, 1, generator=generator) + 0.2), -1) + points = positions + quat_apply(mount.expand(count, -1), local) + gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.7 + + # The torch teacher the kernel replaces. + direction = torch.nn.functional.normalize(quat_apply_inverse(mount.expand(count, -1), points - positions), dim=-1) + desired = direction_to_angles(direction) / field_radius + expected_valid = camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) + expected_action = torch.where(expected_valid[:, None], ((desired - gaze) / step).clamp(-1, 1), 0.0) + looking = angles_to_direction(gaze * field_radius) + expected_error = torch.atan2(torch.cross(looking, direction, dim=-1).norm(dim=-1), (looking * direction).sum(-1)) + + action = torch.empty(count, 2) + valid = torch.empty(count, dtype=torch.bool) + error = torch.empty(count) + with torch_stream("cpu"): + wp.launch( + teacher_kernel, + dim=count, + inputs=[ + wp.from_torch(points.contiguous(), dtype=wp.vec3f), + wp.from_torch(positions.contiguous(), dtype=wp.vec3f), + wp.quatf(*mount.tolist()), + wp.from_torch(gaze.contiguous(), dtype=wp.vec2f), + field_radius, + step, + limit, + camera_params(camera), + ], + outputs=[wp.from_torch(action, dtype=wp.vec2f), wp.from_torch(valid), wp.from_torch(error)], + ) + agree = valid == expected_valid + assert agree.float().mean() > 0.999 and expected_valid.any() and (~expected_valid).any() + torch.testing.assert_close(action[agree], expected_action[agree], atol=1e-4, rtol=0) + torch.testing.assert_close(error, expected_error.rad2deg(), atol=1e-3, rtol=0) + + def test_gaze_loss_ignores_invalid_labels(): mean = torch.tensor([[0.0, 0.0], [1.0, 1.0]], requires_grad=True) labels = torch.tensor([[0.3, 0.4, 1.0], [float("nan"), float("nan"), 0.0]]) diff --git a/source/isaaclab_fovi/test/test_gaze_kernels.py b/source/isaaclab_fovi/test/test_gaze_kernels.py new file mode 100644 index 000000000000..0e61c109afef --- /dev/null +++ b/source/isaaclab_fovi/test/test_gaze_kernels.py @@ -0,0 +1,107 @@ +# 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 + +"""The gaze kernels agree with fovi's camera geometry and with the composition they replace.""" + +import pytest +import torch +import warp as wp +from fovi.sensing.projection import CameraModel, gaze_rotation +from isaaclab_fovi.sensors.calibrated_geometry import compose_rotations, convert_camera_frame_quaternion +from isaaclab_fovi.sensors.gaze_kernels import camera_params, project_directions, set_gaze_kernel, torch_stream + +from isaaclab.utils.math import matrix_from_quat, quat_from_matrix + +DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" +wp.init() + +CAMERAS = { + "ideal pinhole": CameraModel("pinhole", (480, 640), (500.0, 500.0, 319.5, 239.5)), + "distorted pinhole": CameraModel( + "pinhole", + (480, 640), + (520.0, 515.0, 322.0, 241.0), + distortion=(-0.28, 0.09, 0.001, -0.002, -0.01, 0.02, -0.01, 0.005), + ), + "fisheye with image circle": CameraModel( + "fisheye", + (800, 800), + (230.0, 230.0, 399.5, 399.5), + distortion=(0.02, -0.01, 0.003, -0.001), + image_circle=(399.5, 399.5, 380.0), + max_angle_deg=95.0, + ), +} + + +def _directions(count: int) -> torch.Tensor: + generator = torch.Generator().manual_seed(0) + directions = torch.randn(count, 3, generator=generator) + directions[:, 2] = directions[:, 2].abs() * 1.5 # mostly forward, some sideways and behind + directions[: count // 10, 2] *= -1 + return torch.nn.functional.normalize(directions, dim=-1).to(DEVICE) + + +@pytest.mark.parametrize("name", CAMERAS) +def test_projection_matches_fovi(name): + camera = CAMERAS[name] + directions = _directions(20000) + expected_pixels, expected_valid = camera.project(directions) + pixels, valid = project_directions(directions, camera_params(camera)) + agree = valid == expected_valid + # Float32 rounding may flip a sample that lies on the image edge, nothing more. + assert agree.float().mean() > 0.9995 + assert expected_valid.any() and (~expected_valid).any() + torch.testing.assert_close( + pixels[valid & expected_valid], expected_pixels[valid & expected_valid], rtol=1e-4, atol=1e-2 + ) + + +def _set_gaze(angles: torch.Tensor, basis: torch.Tensor): + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=DEVICE) + to_opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl")[0] + to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0] + rotation = torch.empty(len(angles), 3, 3, device=DEVICE) + delta = torch.empty(len(angles), 4, device=DEVICE) + with torch_stream(DEVICE): + wp.launch( + set_gaze_kernel, + dim=len(angles), + inputs=[ + wp.from_torch(angles.contiguous(), dtype=wp.vec2f), + wp.mat33f(*basis.flatten().tolist()), + wp.quatf(*to_opengl.tolist()), + wp.quatf(*to_world.tolist()), + ], + outputs=[wp.from_torch(rotation, dtype=wp.mat33f), wp.from_torch(delta, dtype=wp.quatf)], + ) + return rotation, delta + + +def test_gaze_kernel_matches_the_torch_composition(): + generator = torch.Generator().manual_seed(1) + angles = ((torch.rand(64, 2, generator=generator) * 2 - 1) * 40).to(DEVICE) + base = torch.nn.functional.normalize(torch.randn(64, 4, generator=generator), dim=-1).to(DEVICE) + angle = torch.tensor(0.3) + c, s = float(angle.cos()), float(angle.sin()) + basis = torch.tensor(((c, s, 0.0), (s, -c, 0.0), (0.0, 0.0, -1.0)), device=DEVICE) + + rotation, delta = _set_gaze(angles, basis) + tilt, pan = angles.deg2rad().unbind(-1) + direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + expected_rotation = gaze_rotation(direction, "pan_tilt") + torch.testing.assert_close(rotation, expected_rotation, atol=1e-5, rtol=0) + + # The torch composition the camera used per frame. + relative = compose_rotations(compose_rotations(basis, expected_rotation), basis.T) + opengl = convert_camera_frame_quaternion(base, origin="world", target="opengl") + composed = quat_from_matrix(compose_rotations(matrix_from_quat(opengl), relative)) + expected = convert_camera_frame_quaternion(composed, origin="opengl", target="world") + + result = torch.empty_like(base) + for i in range(len(base)): + product = wp.normalize(wp.quatf(*base[i].tolist()) * wp.quatf(*delta[i].tolist())) + result[i] = torch.tensor([product[0], product[1], product[2], product[3]]) + torch.testing.assert_close(matrix_from_quat(result), matrix_from_quat(expected), atol=1e-5, rtol=0) diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 40a4de79d3d2..dbcd4d8172fb 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -13,11 +13,7 @@ import warp as wp from fovi.sensing.projection import CameraModel, angular_directions from fovi.sensing.retina import RetinalTransform -from isaaclab_fovi.sensors.calibrated_geometry import ( - retinal_directions, - rotate_camera_rays, - sampling_geometry, -) +from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions, sampling_geometry from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.pooling import build_lowres_coords from isaaclab_fovi.sensors.virtual_gaze import VirtualGaze @@ -241,38 +237,18 @@ def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_ @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable") -def test_visibility_ray_rotation_preserves_precision_and_cuda_capture(tf32_enabled) -> None: - device = "cuda" - generator = torch.Generator(device=device).manual_seed(42) - rays = torch.randn(16384, 3, device=device, generator=generator) - rays = rays / rays.norm(dim=-1, keepdim=True) - rotations = matrix_from_quat(torch.randn(48, 4, device=device, generator=generator)) - expected = (rays.double() @ rotations.double().transpose(-1, -2)).float() - for _ in range(3): - actual = rotate_camera_rays(rays, rotations) - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - actual = rotate_camera_rays(rays, rotations) - graph.replay() - torch.testing.assert_close(actual, expected, atol=2e-7, rtol=1e-6) - assert torch.get_float32_matmul_precision() == "high" - - -@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable") -def test_visibility_ray_rotation_preserves_shared_stream_for_warp_capture() -> None: +def test_gaze_kernels_preserve_shared_stream_for_warp_capture() -> None: wp.init() stream = wp.Stream("cuda:0") with wp.ScopedStream(stream), torch.cuda.stream(wp.stream_to_torch(stream)): - rays = torch.tensor([[1.0, 2.0, 3.0], [-2.0, 4.0, 1.0]], device="cuda:0") - rotation = torch.tensor([[[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]], device="cuda:0") - target = wp.zeros((1, 2), dtype=wp.vec3, device="cuda:0") - actual = rotate_camera_rays(rays, rotation) - source = wp.from_torch(actual, dtype=wp.vec3) - # Physics must still be able to capture after the camera's temporary scope exits. + camera = GazeHarness() + camera._gaze_rays = camera._gaze_rays.to("cuda:0") + camera.set_gaze_angles(torch.tensor([[5.0, -8.0], [0.0, 0.0]], device="cuda:0")) + valid = camera._gaze_validity(2) + target = wp.zeros(valid.shape, dtype=wp.bool, device="cuda:0") + # Physics must still be able to capture after the camera's temporary stream scopes exit. with wp.ScopedCapture(stream=stream) as capture: - wp.copy(target, source) + wp.copy(target, wp.from_torch(valid)) wp.capture_launch(capture.graph) - torch.testing.assert_close( - wp.to_torch(target), - torch.tensor([[[-2.0, 1.0, 3.0], [-4.0, -2.0, 1.0]]], device="cuda:0"), - ) + torch.testing.assert_close(wp.to_torch(target), valid) + assert valid[1].any() From 8658451764b7a26ff32fcb5b118b601344c37de0 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 18:05:05 -0800 Subject: [PATCH 23/81] Cut the per-step launch overhead of the gaze Warp streams are cached per PyTorch stream, and Warp views of persistent buffers are wrapped once. The gaze action's step, limit, velocity and angles are one kernel, and the teacher's target point, labels and logged sums are another. The visible fraction is computed when read. Results are unchanged; the new kernels are tested against the torch code they replace. On the 32-sample Cartpole task with 1024 environments, an environment step takes 1.5 ms instead of 1.8 ms. --- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 204 +++++++++++++++--- .../sensors/foveated_newton_camera.py | 5 +- .../sensors/foveated_rtx_camera.py | 5 +- .../isaaclab_fovi/sensors/gaze_kernels.py | 33 +-- .../isaaclab_fovi/sensors/virtual_gaze.py | 39 ++-- source/isaaclab_fovi/test/test_active_gaze.py | 82 ++++++- 6 files changed, 305 insertions(+), 63 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 3862fa0cd41d..8d4ae6156ace 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -40,40 +40,109 @@ RAD_TO_DEG = 180.0 / math.pi -@wp.kernel(enable_backward=False) -def teacher_kernel( - points: wp.array(dtype=wp.vec3f), - positions: wp.array(dtype=wp.vec3f), +@wp.func +def teach( + point: wp.vec3f, + position: wp.vec3f, mount: wp.quatf, - gaze: wp.array(dtype=wp.vec2f), + g: wp.vec2f, field_radius_deg: wp.float32, step_size: wp.float32, gaze_limit: wp.float32, camera: CameraParams, - action: wp.array(dtype=wp.vec2f), - valid: wp.array(dtype=wp.bool), - error_deg: wp.array(dtype=wp.float32), -): - """The teacher's action toward each point, whether the point is a valid target, and the gaze's error to it.""" - i = wp.tid() - d = wp.normalize(wp.quat_rotate_inv(mount, points[i] - positions[i])) +) -> wp.vec4f: + """The teacher's action (x, y) toward a point, 1 for a valid target or else 0, and the gaze's error [deg].""" + d = wp.normalize(wp.quat_rotate_inv(mount, point - position)) tilt = -wp.atan2(d[1], wp.sqrt(d[0] * d[0] + d[2] * d[2])) * wp.float32(RAD_TO_DEG) pan = -wp.atan2(d[0], d[2]) * wp.float32(RAD_TO_DEG) desired = wp.vec2f(tilt, pan) / field_radius_deg - g = gaze[i] ok = project_direction(d, camera)[2] > 0.5 and wp.length(desired) <= gaze_limit step = wp.vec2f(0.0, 0.0) if ok: step = wp.vec2f( wp.clamp((desired[0] - g[0]) / step_size, -1.0, 1.0), wp.clamp((desired[1] - g[1]) / step_size, -1.0, 1.0) ) - action[i] = step - valid[i] = ok g_tilt = g[0] * field_radius_deg * wp.float32(DEG_TO_RAD) g_pan = g[1] * field_radius_deg * wp.float32(DEG_TO_RAD) looking = wp.vec3f(-wp.cos(g_tilt) * wp.sin(g_pan), -wp.sin(g_tilt), wp.cos(g_tilt) * wp.cos(g_pan)) # atan2 stays accurate near perfect alignment, unlike acos of the dot product. - error_deg[i] = wp.atan2(wp.length(wp.cross(looking, d)), wp.dot(looking, d)) * wp.float32(RAD_TO_DEG) + error = wp.atan2(wp.length(wp.cross(looking, d)), wp.dot(looking, d)) * wp.float32(RAD_TO_DEG) + return wp.vec4f(step[0], step[1], wp.where(ok, 1.0, 0.0), error) + + +@wp.kernel(enable_backward=False) +def teacher_kernel( + points: wp.array(dtype=wp.vec3f), + positions: wp.array(dtype=wp.vec3f), + mount: wp.quatf, + gaze: wp.array(dtype=wp.vec2f), + field_radius_deg: wp.float32, + step_size: wp.float32, + gaze_limit: wp.float32, + camera: CameraParams, + action: wp.array(dtype=wp.vec2f), + valid: wp.array(dtype=wp.bool), + error_deg: wp.array(dtype=wp.float32), +): + """The teacher's action toward each point, whether the point is a valid target, and the gaze's error to it.""" + i = wp.tid() + result = teach(points[i], positions[i], mount, gaze[i], field_radius_deg, step_size, gaze_limit, camera) + action[i] = wp.vec2f(result[0], result[1]) + valid[i] = result[2] > 0.5 + error_deg[i] = result[3] + + +@wp.kernel(enable_backward=False) +def teacher_labels_kernel( + targets: wp.array(dtype=wp.vec3f), + orientations: wp.array(dtype=wp.quatf), + offset: wp.vec3f, + rotate_offset: wp.int32, + positions: wp.array(dtype=wp.vec3f), + mount: wp.quatf, + gaze: wp.array(dtype=wp.vec2f), + field_radius_deg: wp.float32, + step_size: wp.float32, + gaze_limit: wp.float32, + camera: CameraParams, + labels: wp.array2d(dtype=wp.float32), + sums: wp.array(dtype=wp.float32), +): + """Labels (action x, action y, valid) toward a point fixed to each target, and the error and count sums of valid + targets.""" + i = wp.tid() + point = targets[i] + if rotate_offset != 0: + point = point + wp.quat_rotate(orientations[i], offset) + result = teach(point, positions[i], mount, gaze[i], field_radius_deg, step_size, gaze_limit, camera) + labels[i, 0] = result[0] + labels[i, 1] = result[1] + labels[i, 2] = result[2] + if result[2] > 0.5: + wp.atomic_add(sums, 0, result[3]) + wp.atomic_add(sums, 1, 1.0) + + +@wp.kernel(enable_backward=False) +def gaze_step_kernel( + actions: wp.array(dtype=wp.vec2f), + gaze: wp.array(dtype=wp.vec2f), + velocity: wp.array(dtype=wp.vec2f), + angles_deg: wp.array(dtype=wp.vec2f), + step_size: wp.float32, + gaze_limit: wp.float32, + step_dt: wp.float32, + field_radius_deg: wp.float32, +): + """Move each gaze by its clamped action, keep it within the limit, and record its velocity and angles.""" + i = wp.tid() + a = actions[i] + previous = gaze[i] + moved = previous + wp.vec2f(wp.clamp(a[0], -1.0, 1.0), wp.clamp(a[1], -1.0, 1.0)) * step_size + current = moved * (gaze_limit / wp.max(wp.length(moved), gaze_limit)) + gaze[i] = current + velocity[i] = (current - previous) / step_dt + angles_deg[i] = current * field_radius_deg def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: @@ -132,6 +201,14 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): self._raw = torch.zeros(self.num_envs, 2, device=self.device) self._gaze = torch.zeros_like(self._raw) self._velocity = torch.zeros_like(self._raw) + self._angles = torch.zeros_like(self._raw) + """Gaze angles [deg] of the last step, the buffer the camera reads.""" + self._raw_wp, self._gaze_wp, self._velocity_wp, self._angles_wp = ( + wp.from_torch(buffer, dtype=wp.vec2f) for buffer in (self._raw, self._gaze, self._velocity, self._angles) + ) + self._label_sums = torch.zeros(2, device=self.device) + self._label_sums_wp = wp.from_torch(self._label_sums) + self._no_orientations = wp.from_torch(torch.zeros(1, 4, device=self.device), dtype=wp.quatf) @property def action_dim(self) -> int: @@ -162,10 +239,22 @@ def angles_deg(self) -> torch.Tensor: def process_actions(self, actions: torch.Tensor): self._raw.copy_(actions) - previous = self._gaze.clone() - self._gaze.copy_(clamp_gaze(self._gaze + actions.clamp(-1, 1) * self.cfg.step_size, self.cfg.gaze_limit)) - self._velocity.copy_((self._gaze - previous) / self._env.step_dt) - self.camera.set_gaze_angles(self.angles_deg) + with torch_stream(self.device): + wp.launch( + gaze_step_kernel, + dim=self.num_envs, + inputs=[ + self._raw_wp, + self._gaze_wp, + self._velocity_wp, + self._angles_wp, + self.cfg.step_size, + self.cfg.gaze_limit, + self._env.step_dt, + self.field_radius_deg, + ], + ) + self.camera.set_gaze_angles(self._angles) def apply_actions(self): pass @@ -213,7 +302,7 @@ def teacher(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, tor wp.from_torch(points, dtype=wp.vec3f), self.camera.data.pos_w.warp, self._mount, - wp.from_torch(self._gaze, dtype=wp.vec2f), + self._gaze_wp, self.field_radius_deg, self.cfg.step_size, self.cfg.gaze_limit, @@ -223,6 +312,43 @@ def teacher(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, tor ) return action, valid, error + def _teacher_labels( + self, targets: wp.array, orientations: wp.array | None = None, offset: wp.vec3f | None = None + ) -> tuple[torch.Tensor, torch.Tensor]: + """Teacher labels toward a point fixed to each target, in one launch. + + Args: + targets: Target positions in the world frame, one per environment. + orientations: Target orientations (x, y, z, w), to place ``offset`` in each target's frame. + offset: The point in each target's frame [m]. + + Returns: + The labels (action x, action y, valid), shape (num_envs, 3); and the sum of the gaze's errors to valid + targets [deg] with their count, shape (2,), a buffer the next call overwrites. + """ + labels = torch.empty(self.num_envs, 3, device=self.device) + self._label_sums.zero_() + with torch_stream(self.device): + wp.launch( + teacher_labels_kernel, + dim=self.num_envs, + inputs=[ + targets, + self._no_orientations if orientations is None else orientations, + wp.vec3f(0.0, 0.0, 0.0) if offset is None else offset, + int(orientations is not None), + self.camera.data.pos_w.warp, + self._mount, + self._gaze_wp, + self.field_radius_deg, + self.cfg.step_size, + self.cfg.gaze_limit, + self._camera, + ], + outputs=[wp.from_torch(labels), self._label_sums_wp], + ) + return labels, self._label_sums + @configclass class GazeActionCfg(ActionTermCfg): @@ -273,11 +399,16 @@ def teacher_labels(env: ManagerBasedEnv, points: torch.Tensor, action_name: str the object is grasped, choose the points and call this. """ term: GazeAction = env.action_manager.get_term(action_name) - action, valid, error = term.teacher(points) + labels, sums = term._teacher_labels(wp.from_torch(points.float().contiguous(), dtype=wp.vec3f)) + _log_teacher(env, sums, len(labels)) + return labels + + +def _log_teacher(env: ManagerBasedEnv, sums: torch.Tensor, count: int) -> None: + """Log the mean gaze error to valid targets and the fraction of valid targets.""" log = env.extras.setdefault("log", {}) - log["Gaze/target_error_deg"] = torch.where(valid, error, 0.0).sum() / valid.sum().clamp_min(1) - log["Gaze/valid_target_fraction"] = valid.float().mean() - return torch.cat((action, valid[:, None].float()), dim=-1) + log["Gaze/target_error_deg"] = sums[0] / sums[1].clamp_min(1) + log["Gaze/valid_target_fraction"] = sums[1] / count class gaze_teacher_labels(ManagerTermBase): @@ -291,7 +422,9 @@ class gaze_teacher_labels(ManagerTermBase): def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv): super().__init__(cfg, env) - self._offset = torch.tensor(cfg.params.get("offset", (0.0, 0.0, 0.0)), device=env.device) + self._offset = wp.vec3f(*cfg.params.get("offset", (0.0, 0.0, 0.0))) + self._sources = None + self._targets = self._orientations = None def __call__( self, @@ -300,7 +433,24 @@ def __call__( offset: tuple[float, float, float] = (0.0, 0.0, 0.0), action_name: str = "gaze", ) -> torch.Tensor: - return teacher_labels(env, entity_point(env, target_cfg, self._offset), action_name) + data = env.scene[target_cfg.name].data + # Reading the properties refreshes the asset's pose buffers; their Warp views are wrapped once. + if target_cfg.body_names is None: + positions, orientations = data.root_pos_w, data.root_quat_w + else: + positions, orientations = data.body_pos_w, data.body_quat_w + if self._sources != (id(positions), id(orientations)): + self._sources = (id(positions), id(orientations)) + if target_cfg.body_names is None: + self._targets, self._orientations = positions.warp, orientations.warp + else: + body = target_cfg.body_ids[0] + self._targets = wp.from_torch(positions.torch[:, body], dtype=wp.vec3f) + self._orientations = wp.from_torch(orientations.torch[:, body], dtype=wp.quatf) + term: GazeAction = env.action_manager.get_term(action_name) + labels, sums = term._teacher_labels(self._targets, self._orientations, self._offset) + _log_teacher(env, sums, len(labels)) + return labels def motor_action_l2(env: ManagerBasedRLEnv, gaze_action_name: str = "gaze") -> torch.Tensor: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index da39a6e9a933..f0c22f5f7680 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -360,7 +360,7 @@ def _apply_sensor_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: continue tensor = output.torch if hasattr(output, "torch") else output tensor.masked_fill_(invalid, 0) - self._sensor_fov_valid_fraction = valid.float().mean(dim=1) + self._sensor_fov_valid = valid # ------------------------------------------------------------------ # Output helpers @@ -385,4 +385,5 @@ def num_valid_samples(self) -> int: @property def sensor_fov_valid_fraction(self) -> torch.Tensor | None: """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" - return getattr(self, "_sensor_fov_valid_fraction", None) + valid = getattr(self, "_sensor_fov_valid", None) + return None if valid is None else valid.float().mean(dim=1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 4c5021567119..22bbe2d85951 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -466,7 +466,7 @@ def _apply_sensor_fov_mask(self) -> None: if name == "rgb" and has_rgba_alias: continue output.masked_fill_(invalid, 0) - self._sensor_fov_valid_fraction = valid.float().mean(dim=1) + self._sensor_fov_valid = valid # ------------------------------------------------------------------ # Output helpers @@ -491,4 +491,5 @@ def num_valid_samples(self) -> int: @property def sensor_fov_valid_fraction(self) -> torch.Tensor | None: """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" - return getattr(self, "_sensor_fov_valid_fraction", None) + valid = getattr(self, "_sensor_fov_valid", None) + return None if valid is None else valid.float().mean(dim=1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py index 22093fd0bb0e..f805902f2ff8 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -11,7 +11,6 @@ from __future__ import annotations -import contextlib import math import torch @@ -24,22 +23,26 @@ DEG_TO_RAD = math.pi / 180.0 -@contextlib.contextmanager -def torch_stream(device: torch.device | str): - """Launch Warp kernels on the tensors' device and, on CUDA, PyTorch's current stream.""" +_WARP_STREAMS: dict[int, wp.Stream] = {} +"""Warp streams by the CUDA stream handle of the PyTorch stream they launch on.""" + + +def torch_stream(device: torch.device | str) -> wp.ScopedStream | wp.ScopedDevice: + """Scope that launches Warp kernels on the tensors' device and, on CUDA, PyTorch's current stream.""" device = torch.device(device) - wp.init() if device.type != "cuda": - with wp.ScopedDevice(wp.device_from_torch(device)): - yield - return - torch_current = torch.cuda.current_stream(device) - stream = wp.get_stream(wp.device_from_torch(device)) - # A temporary alias of a live Warp-owned stream would unregister it when destroyed. - if stream.cuda_stream != torch_current.cuda_stream: - stream = wp.stream_from_torch(torch_current) - with wp.ScopedStream(stream, sync_enter=False, sync_exit=False): - yield + wp.init() + return wp.ScopedDevice(wp.device_from_torch(device)) + handle = torch.cuda.current_stream(device).cuda_stream + stream = _WARP_STREAMS.get(handle) + if stream is None: + wp.init() + stream = wp.get_stream(wp.device_from_torch(device)) + # A temporary alias of a live Warp-owned stream would unregister it when destroyed; cached aliases persist. + if stream.cuda_stream != handle: + stream = wp.stream_from_torch(torch.cuda.current_stream(device)) + _WARP_STREAMS[handle] = stream + return wp.ScopedStream(stream, sync_enter=False, sync_exit=False) @wp.struct diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index 108cec65fe41..af587448b6fb 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -48,15 +48,19 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: if rotation is None or rotation.shape[0] != len(angles) or rotation.device != angles.device: self._gaze_rotation = torch.empty(len(angles), 3, 3, device=angles.device) self._gaze_pose_delta = torch.empty(len(angles), 4, device=angles.device) + self._gaze_rotation_wp = wp.from_torch(self._gaze_rotation, dtype=wp.mat33f) + self._gaze_pose_delta_wp = wp.from_torch(self._gaze_pose_delta, dtype=wp.quatf) + # Callers usually pass the same buffer every step; wrap it once. + key = (angles.data_ptr(), angles.shape, angles.device) + if key != self._gaze_angles_key: + self._gaze_angles_wp = wp.from_torch(angles, dtype=wp.vec2f) + self._gaze_angles_key = key with torch_stream(angles.device): wp.launch( set_gaze_kernel, dim=len(angles), - inputs=[wp.from_torch(angles, dtype=wp.vec2f), *self._gaze_frames], - outputs=[ - wp.from_torch(self._gaze_rotation, dtype=wp.mat33f), - wp.from_torch(self._gaze_pose_delta, dtype=wp.quatf), - ], + inputs=[self._gaze_angles_wp, *self._gaze_frames], + outputs=[self._gaze_rotation_wp, self._gaze_pose_delta_wp], ) def _apply_gaze_pose( @@ -66,7 +70,7 @@ def _apply_gaze_pose( return orientation = self._data.quat_w_world orientation = orientation.warp if hasattr(orientation, "warp") else wp.from_torch(orientation, dtype=wp.quatf) - delta = wp.from_torch(self._gaze_pose_delta, dtype=wp.quatf) + delta = self._gaze_pose_delta_wp with torch_stream(self._gaze_pose_delta.device): if env_mask is not None: wp.launch(apply_gaze_masked_kernel, dim=len(delta), inputs=[orientation, delta, env_mask]) @@ -80,21 +84,22 @@ def _apply_gaze_pose( def _gaze_validity(self, batch_size: int) -> torch.Tensor: """Return which samples the physical camera sees at the current gaze, shape (batch_size, num_samples).""" - rotation = self._gaze_rotation - if rotation is None: + if self._gaze_rotation is None: rotation = self._gaze_identity.expand(batch_size, -1, -1).contiguous() - rays = self._gaze_rays.to(rotation.device) - valid = torch.empty(batch_size, len(rays), dtype=torch.bool, device=rotation.device) + rotation_wp = wp.from_torch(rotation, dtype=wp.mat33f) + else: + rotation, rotation_wp = self._gaze_rotation, self._gaze_rotation_wp + device = rotation.device + rays_wp = self._gaze_rays_wp.get(device) + if rays_wp is None: + rays_wp = self._gaze_rays_wp[device] = wp.from_torch(self._gaze_rays.to(device), dtype=wp.vec3f) + valid = torch.empty(batch_size, len(self._gaze_rays), dtype=torch.bool, device=device) # A receptive field can overlap the sensor even when its center is outside it. - with torch_stream(rotation.device): + with torch_stream(device): wp.launch( sensor_visibility_kernel, dim=valid.shape, - inputs=[ - wp.from_torch(rays, dtype=wp.vec3f), - wp.from_torch(rotation.contiguous(), dtype=wp.mat33f), - self._gaze_camera, - ], + inputs=[rays_wp, rotation_wp, self._gaze_camera], outputs=[wp.from_torch(valid, dtype=wp.bool)], ) return valid @@ -108,6 +113,8 @@ def _initialize_gaze(self) -> None: else: self._gaze_rays = angular_directions(coords.cartesian, coords.fov) self._gaze_rays = self._gaze_rays.float().contiguous() + self._gaze_rays_wp: dict[torch.device, wp.array] = {} + self._gaze_angles_key = None device = self._gaze_rays.device self._gaze_identity = torch.eye(3, device=device) angle = math.radians(self.cfg.image_rotation_deg) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 4e5ab454aac0..ee230a312479 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -10,7 +10,7 @@ import warp as wp from fovi.sensing.projection import CameraModel from isaaclab_fovi.mdp import angles_to_direction, clamp_gaze, direction_to_angles -from isaaclab_fovi.mdp.gaze import teacher_kernel +from isaaclab_fovi.mdp.gaze import gaze_step_kernel, teacher_kernel, teacher_labels_kernel from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream from rsl_rl.models import MLPModel @@ -83,6 +83,86 @@ def test_teacher_kernel_matches_the_torch_teacher(): torch.testing.assert_close(error, expected_error.rad2deg(), atol=1e-3, rtol=0) +def test_gaze_step_kernel_matches_the_torch_update(): + generator = torch.Generator().manual_seed(4) + count, step, limit, dt, radius = 2048, 0.1, 1.0, 1 / 60, 23.6 + actions = torch.randn(count, 2, generator=generator) * 1.5 + gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.75 + expected = clamp_gaze(gaze + actions.clamp(-1, 1) * step, limit) + expected_velocity = (expected - gaze) / dt + + velocity, angles = torch.empty_like(gaze), torch.empty_like(gaze) + with torch_stream("cpu"): + wp.launch( + gaze_step_kernel, + dim=count, + inputs=[ + *(wp.from_torch(buffer, dtype=wp.vec2f) for buffer in (actions, gaze, velocity, angles)), + step, + limit, + dt, + radius, + ], + ) + torch.testing.assert_close(gaze, expected, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(velocity, expected_velocity, atol=1e-3, rtol=1e-5) + torch.testing.assert_close(angles, expected * radius, atol=1e-5, rtol=1e-6) + + +def test_teacher_labels_kernel_matches_the_torch_labels(): + camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5)) + field_radius, step, limit = 30.0, 0.1, 1.0 + generator = torch.Generator().manual_seed(5) + count = 4096 + mount = torch.nn.functional.normalize(torch.randn(4, generator=generator), dim=0) + positions = torch.randn(count, 3, generator=generator) + lateral = torch.randn(count, 2, generator=generator) * 0.6 + local = torch.cat((lateral, torch.rand(count, 1, generator=generator) + 0.2), -1) + targets = positions + quat_apply(mount.expand(count, -1), local) + orientations = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1) + offset = torch.tensor([0.0, 0.0, 0.3]) + gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.7 + + # The torch path the kernel replaces: entity_point, then the teacher, then the labels and logs. + points = targets + quat_apply(orientations, offset.expand(count, -1)) + direction = torch.nn.functional.normalize(quat_apply_inverse(mount.expand(count, -1), points - positions), dim=-1) + desired = direction_to_angles(direction) / field_radius + valid = camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) + action = torch.where(valid[:, None], ((desired - gaze) / step).clamp(-1, 1), 0.0) + looking = angles_to_direction(gaze * field_radius) + error = torch.atan2(torch.cross(looking, direction, dim=-1).norm(dim=-1), (looking * direction).sum(-1)).rad2deg() + expected = torch.cat((action, valid[:, None].float()), dim=-1) + + labels = torch.empty(count, 3) + sums = torch.zeros(2) + with torch_stream("cpu"): + wp.launch( + teacher_labels_kernel, + dim=count, + inputs=[ + wp.from_torch(targets, dtype=wp.vec3f), + wp.from_torch(orientations, dtype=wp.quatf), + wp.vec3f(*offset.tolist()), + 1, + wp.from_torch(positions, dtype=wp.vec3f), + wp.quatf(*mount.tolist()), + wp.from_torch(gaze, dtype=wp.vec2f), + field_radius, + step, + limit, + camera_params(camera), + ], + outputs=[wp.from_torch(labels), wp.from_torch(sums)], + ) + agree = (labels[:, 2] > 0.5) == valid + assert agree.float().mean() > 0.999 and valid.any() and (~valid).any() + torch.testing.assert_close(labels[agree], expected[agree], atol=1e-4, rtol=0) + both = agree & valid + assert float(sums[1]) == pytest.approx(float((labels[:, 2] > 0.5).sum())) + assert float(sums[0]) == pytest.approx(float(torch.where(labels[:, 2] > 0.5, error, 0.0).sum()), rel=1e-4) + assert both.sum() > 0 + + def test_gaze_loss_ignores_invalid_labels(): mean = torch.tensor([[0.0, 0.0], [1.0, 1.0]], requires_grad=True) labels = torch.tensor([[0.3, 0.4, 1.0], [float("nan"), float("nan"), 0.0]]) From a28080eb5236a07c149e3ffbd3d8a2b69ba6fc43 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 18:59:14 -0800 Subject: [PATCH 24/81] Let physics graph the gaze tasks' actions and record the gaze launches The gaze action term declares itself graphable: it moves the gaze once per step in process_actions and does nothing in apply_actions, so Newton again records the other action terms and the decimation loop into its CUDA graph. The Newton camera masks rendered samples and lays them out in the upright grid with one kernel per output. The per-step Warp launches are recorded once and replayed, and the gaze observation is a buffer the gaze step writes. Results are unchanged; the new kernels are tested against the code they replace. On the 32-sample Cartpole task with 1024 environments, an environment step takes 1.14 ms instead of 1.48 ms, against 0.93 ms for the stock camera task. --- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 87 ++++++++++++------- .../sensors/foveated_newton_camera.py | 80 +++++++++++++++-- .../isaaclab_fovi/sensors/gaze_kernels.py | 53 ++++++++++- .../isaaclab_fovi/sensors/virtual_gaze.py | 45 ++++++---- source/isaaclab_fovi/test/test_active_gaze.py | 3 + .../isaaclab_fovi/test/test_gaze_kernels.py | 75 +++++++++++++++- 6 files changed, 289 insertions(+), 54 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 8d4ae6156ace..8305f235b99c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -15,7 +15,7 @@ import math from dataclasses import MISSING -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar import torch import warp as wp @@ -31,7 +31,9 @@ camera_params, project_direction, project_directions, + record_launch, torch_stream, + warp_stream, ) if TYPE_CHECKING: @@ -129,20 +131,23 @@ def gaze_step_kernel( gaze: wp.array(dtype=wp.vec2f), velocity: wp.array(dtype=wp.vec2f), angles_deg: wp.array(dtype=wp.vec2f), + state: wp.array(dtype=wp.vec4f), step_size: wp.float32, gaze_limit: wp.float32, step_dt: wp.float32, field_radius_deg: wp.float32, ): - """Move each gaze by its clamped action, keep it within the limit, and record its velocity and angles.""" + """Move each gaze by its clamped action, keep it within the limit, and record its velocity, angles and state.""" i = wp.tid() a = actions[i] previous = gaze[i] moved = previous + wp.vec2f(wp.clamp(a[0], -1.0, 1.0), wp.clamp(a[1], -1.0, 1.0)) * step_size current = moved * (gaze_limit / wp.max(wp.length(moved), gaze_limit)) + rate = (current - previous) / step_dt gaze[i] = current - velocity[i] = (current - previous) / step_dt + velocity[i] = rate angles_deg[i] = current * field_radius_deg + state[i] = wp.vec4f(current[0], current[1], rate[0], rate[1]) def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: @@ -181,6 +186,10 @@ class GazeAction(ActionTerm): cfg: GazeActionCfg + is_graphable: ClassVar[bool] = True + """The gaze moves in :meth:`process_actions`, once per environment step; :meth:`apply_actions` does nothing, so + physics may record the other terms' actions and its decimation loop into a CUDA graph.""" + def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): super().__init__(cfg, env) self.camera = self._asset @@ -203,12 +212,32 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): self._velocity = torch.zeros_like(self._raw) self._angles = torch.zeros_like(self._raw) """Gaze angles [deg] of the last step, the buffer the camera reads.""" + self._state = torch.zeros(self.num_envs, 4, device=self.device) + """Gaze and its velocity, the gaze observation.""" self._raw_wp, self._gaze_wp, self._velocity_wp, self._angles_wp = ( wp.from_torch(buffer, dtype=wp.vec2f) for buffer in (self._raw, self._gaze, self._velocity, self._angles) ) + self._step_launch = record_launch( + gaze_step_kernel, + self.num_envs, + [ + self._raw_wp, + self._gaze_wp, + self._velocity_wp, + self._angles_wp, + wp.from_torch(self._state, dtype=wp.vec4f), + self.cfg.step_size, + self.cfg.gaze_limit, + self._env.step_dt, + self.field_radius_deg, + ], + device=self.device, + ) + self._labels = torch.zeros(self.num_envs, 3, device=self.device) self._label_sums = torch.zeros(2, device=self.device) self._label_sums_wp = wp.from_torch(self._label_sums) self._no_orientations = wp.from_torch(torch.zeros(1, 4, device=self.device), dtype=wp.quatf) + self._labels_launch = None @property def action_dim(self) -> int: @@ -232,6 +261,11 @@ def velocity(self) -> torch.Tensor: """Gaze velocity in field radii per second, shape (num_envs, 2).""" return self._velocity + @property + def state(self) -> torch.Tensor: + """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" + return self._state + @property def angles_deg(self) -> torch.Tensor: """Current gaze angles [deg], shape (num_envs, 2).""" @@ -239,21 +273,7 @@ def angles_deg(self) -> torch.Tensor: def process_actions(self, actions: torch.Tensor): self._raw.copy_(actions) - with torch_stream(self.device): - wp.launch( - gaze_step_kernel, - dim=self.num_envs, - inputs=[ - self._raw_wp, - self._gaze_wp, - self._velocity_wp, - self._angles_wp, - self.cfg.step_size, - self.cfg.gaze_limit, - self._env.step_dt, - self.field_radius_deg, - ], - ) + self._step_launch.launch(warp_stream(self.device)) self.camera.set_gaze_angles(self._angles) def apply_actions(self): @@ -268,7 +288,10 @@ def reset(self, env_ids=None): gaze = random_gaze(len(ids), self.cfg.gaze_limit, self.device) visible = self.visible(angles_to_direction(gaze * self.field_radius_deg)) self._gaze[ids] = torch.where(visible[:, None], gaze, 0.0) - self.camera.set_gaze_angles(self.angles_deg) + # The camera keeps reading the same buffer, which every other environment already holds. + self._angles[ids] = self._gaze[ids] * self.field_radius_deg + self._state[ids] = torch.cat((self._gaze[ids], self._velocity[ids]), dim=-1) + self.camera.set_gaze_angles(self._angles) def directions(self, points: torch.Tensor) -> torch.Tensor: """Camera-frame unit directions from the camera to world points, shape (num_envs, 3).""" @@ -324,20 +347,20 @@ def _teacher_labels( Returns: The labels (action x, action y, valid), shape (num_envs, 3); and the sum of the gaze's errors to valid - targets [deg] with their count, shape (2,), a buffer the next call overwrites. + targets [deg] with their count, shape (2,). Both are buffers the next call overwrites. """ - labels = torch.empty(self.num_envs, 3, device=self.device) - self._label_sums.zero_() - with torch_stream(self.device): - wp.launch( + positions = self.camera.data.pos_w.warp + sources = (targets, orientations, positions, offset) + if self._labels_launch is None or any(a is not b for a, b in zip(self._labels_launch[0], sources)): + launch = record_launch( teacher_labels_kernel, - dim=self.num_envs, - inputs=[ + self.num_envs, + [ targets, self._no_orientations if orientations is None else orientations, wp.vec3f(0.0, 0.0, 0.0) if offset is None else offset, int(orientations is not None), - self.camera.data.pos_w.warp, + positions, self._mount, self._gaze_wp, self.field_radius_deg, @@ -345,9 +368,13 @@ def _teacher_labels( self.cfg.gaze_limit, self._camera, ], - outputs=[wp.from_torch(labels), self._label_sums_wp], + [wp.from_torch(self._labels), self._label_sums_wp], + self.device, ) - return labels, self._label_sums + self._labels_launch = (sources, launch) + self._label_sums.zero_() + self._labels_launch[1].launch(warp_stream(self.device)) + return self._labels, self._label_sums @configclass @@ -368,7 +395,7 @@ class GazeActionCfg(ActionTermCfg): def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" term: GazeAction = env.action_manager.get_term(action_name) - return torch.cat((term.gaze, term.velocity), dim=-1) + return term.state def entity_point( diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index f0c22f5f7680..1af7b50b79f8 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -26,6 +26,7 @@ from .calibrated_geometry import retinal_directions from .foveated_camera import FoveatedCamera from .foveated_rays import compute_explicit_ray_array +from .gaze_kernels import CameraParams, publish_grid_kernel, record_launch, warp_stream from .native_grid import ( GRID_STYLE, allocate_grid_outputs, @@ -203,6 +204,8 @@ def _initialize_impl(self): self._public_output = proxy_outputs(source) self._data.output.clear() self._data.output.update(self._public_output) + self._grid_publish = self._prepare_grid_publish() if self._native_grid and self._pooler is None else None + self._grid_launches = None # 6. Inject foveated rays into render_data immediately. self._render_data.camera_rays = self._foveated_rays @@ -211,6 +214,72 @@ def _initialize_impl(self): self._foveated_rays.shape, ) + def _prepare_grid_publish(self) -> list[tuple[wp.array, wp.array]]: + """Byte views of each rendered output and its public grid, for :func:`publish_grid_kernel`.""" + views = [] + for name, value in self._flat_render_output.items(): + if name == "rgb" and "rgba" in self._flat_render_output: + continue + source = value.torch.squeeze(2) + target = self._grid_output[name].view(source.shape[0], -1, source.shape[-1]) + views.append((wp.from_torch(source.view(torch.uint8)), wp.from_torch(target.view(torch.uint8)))) + self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous()) + self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous()) + num_envs = views[0][1].shape[0] + if self.cfg.mask_to_sensor_fov: + identity = self._gaze_identity.expand(num_envs, -1, -1).contiguous() + self._sensor_fov_valid_buffer = torch.zeros( + num_envs, len(self._gaze_rays), dtype=torch.bool, device=self._device + ) + self._grid_sensor = ( + wp.from_torch(self._gaze_rays, dtype=wp.vec3f), + wp.from_torch(identity, dtype=wp.mat33f), + self._gaze_camera, + wp.from_torch(self._sensor_fov_valid_buffer), + ) + else: + # Placeholders: the kernel reads none of these without the sensor mask. + self._grid_sensor = ( + wp.zeros(1, dtype=wp.vec3f, device=self._device), + wp.zeros(1, dtype=wp.mat33f, device=self._device), + CameraParams(), + wp.zeros((1, 1), dtype=wp.bool, device=self._device), + ) + return views + + def _publish_grid(self) -> None: + """Mask and lay out every output in one launch each; the result equals masking, then copying to the grid.""" + mask = self.cfg.mask_to_sensor_fov + rays, identity, camera, visible = self._grid_sensor + rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation_wp + if self._grid_launches is None or self._grid_launches[0] is not rotation: + launches = [ + record_launch( + publish_grid_kernel, + (target.shape[0], target.shape[1]), + [ + source, + self._grid_indices_wp, + self._grid_footprint_wp, + rays, + rotation, + camera, + int(mask), + int(mask and index == 0), + visible, + ], + [target], + self._device, + ) + for index, (source, target) in enumerate(self._grid_publish) + ] + self._grid_launches = (rotation, launches) + stream = warp_stream(self._device) + for launch in self._grid_launches[1]: + launch.launch(stream) + if mask: + self._sensor_fov_valid = self._sensor_fov_valid_buffer + def _validate_native_render_layout(self) -> None: """Reject image dimensions that cannot be covered by Newton's tiles.""" renderer = self._renderer.cfg @@ -310,11 +379,12 @@ def _update_buffers_impl(self, env_mask: wp.array): self._data.output.update(self._render_output) if self._pooler is None: super()._update_buffers_impl(env_mask) - output = self._flat_render_output - mask_grid_samples(output, self._ray_coords) - self._apply_sensor_fov_mask(output) - if self._native_grid: - copy_grid_outputs(output, self._grid_output, self._grid_indices) + if self._grid_publish is not None: + self._publish_grid() + else: + output = self._flat_render_output + mask_grid_samples(output, self._ray_coords) + self._apply_sensor_fov_mask(output) self._data.output.clear() self._data.output.update(self._public_output) return diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py index f805902f2ff8..e5e58d1e8001 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -27,12 +27,12 @@ """Warp streams by the CUDA stream handle of the PyTorch stream they launch on.""" -def torch_stream(device: torch.device | str) -> wp.ScopedStream | wp.ScopedDevice: - """Scope that launches Warp kernels on the tensors' device and, on CUDA, PyTorch's current stream.""" +def warp_stream(device: torch.device | str) -> wp.Stream | None: + """The Warp stream of PyTorch's current stream on a CUDA device, or None on the CPU.""" device = torch.device(device) if device.type != "cuda": wp.init() - return wp.ScopedDevice(wp.device_from_torch(device)) + return None handle = torch.cuda.current_stream(device).cuda_stream stream = _WARP_STREAMS.get(handle) if stream is None: @@ -42,9 +42,23 @@ def torch_stream(device: torch.device | str) -> wp.ScopedStream | wp.ScopedDevic if stream.cuda_stream != handle: stream = wp.stream_from_torch(torch.cuda.current_stream(device)) _WARP_STREAMS[handle] = stream + return stream + + +def torch_stream(device: torch.device | str) -> wp.ScopedStream | wp.ScopedDevice: + """Scope that launches Warp kernels on the tensors' device and, on CUDA, PyTorch's current stream.""" + stream = warp_stream(device) + if stream is None: + return wp.ScopedDevice(wp.device_from_torch(torch.device(device))) return wp.ScopedStream(stream, sync_enter=False, sync_exit=False) +def record_launch(kernel, dim, inputs, outputs=(), device: torch.device | str = "cpu") -> wp.Launch: + """A launch recorded once and replayed each step with :meth:`warp.Launch.launch`, skipping argument packing.""" + wp.init() + return wp.launch(kernel, dim=dim, inputs=inputs, outputs=outputs, device=str(device), record_cmd=True) + + @wp.struct class CameraParams: """A :class:`~fovi.sensing.projection.CameraModel` for Warp kernels.""" @@ -191,6 +205,39 @@ def sensor_visibility_kernel( valid[env, sample] = project_direction(rotation[env] * rays[sample], camera)[2] > 0.5 +@wp.kernel(enable_backward=False) +def publish_grid_kernel( + source: wp.array3d(dtype=wp.uint8), + indices: wp.array(dtype=wp.int32), + footprint: wp.array(dtype=wp.bool), + rays: wp.array(dtype=wp.vec3f), + rotation: wp.array(dtype=wp.mat33f), + camera: CameraParams, + mask_to_sensor: wp.int32, + record_visible: wp.int32, + visible: wp.array2d(dtype=wp.bool), + target: wp.array3d(dtype=wp.uint8), +): + """Copy rendered samples into the upright grid, zeroing samples outside the footprint or, when masking, the + physical camera's view. + + ``source`` and ``target`` hold each sample's channels as raw bytes, so one kernel serves every output type. + """ + env, cell = wp.tid() + sample = indices[cell] + keep = footprint[sample] + if mask_to_sensor != 0: + seen = project_direction(rotation[env] * rays[sample], camera)[2] > 0.5 + if record_visible != 0: + visible[env, sample] = seen + keep = keep and seen + for k in range(target.shape[2]): + if keep: + target[env, cell, k] = source[env, sample, k] + else: + target[env, cell, k] = wp.uint8(0) + + @wp.kernel(enable_backward=False) def project_directions_kernel( directions: wp.array(dtype=wp.vec3f), diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index af587448b6fb..9a0641dc5137 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -20,9 +20,11 @@ apply_gaze_kernel, apply_gaze_masked_kernel, camera_params, + record_launch, sensor_visibility_kernel, set_gaze_kernel, torch_stream, + warp_stream, ) from .native_grid import GRID_STYLE, native_grid_directions @@ -50,18 +52,21 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: self._gaze_pose_delta = torch.empty(len(angles), 4, device=angles.device) self._gaze_rotation_wp = wp.from_torch(self._gaze_rotation, dtype=wp.mat33f) self._gaze_pose_delta_wp = wp.from_torch(self._gaze_pose_delta, dtype=wp.quatf) - # Callers usually pass the same buffer every step; wrap it once. + self._gaze_angles_key = None + self._gaze_pose_launches = {} + # Callers usually pass the same buffer every step; record its launch once. key = (angles.data_ptr(), angles.shape, angles.device) if key != self._gaze_angles_key: self._gaze_angles_wp = wp.from_torch(angles, dtype=wp.vec2f) self._gaze_angles_key = key - with torch_stream(angles.device): - wp.launch( + self._set_gaze_launch = record_launch( set_gaze_kernel, - dim=len(angles), - inputs=[self._gaze_angles_wp, *self._gaze_frames], - outputs=[self._gaze_rotation_wp, self._gaze_pose_delta_wp], + len(angles), + [self._gaze_angles_wp, *self._gaze_frames], + [self._gaze_rotation_wp, self._gaze_pose_delta_wp], + angles.device, ) + self._set_gaze_launch.launch(warp_stream(angles.device)) def _apply_gaze_pose( self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None @@ -71,16 +76,25 @@ def _apply_gaze_pose( orientation = self._data.quat_w_world orientation = orientation.warp if hasattr(orientation, "warp") else wp.from_torch(orientation, dtype=wp.quatf) delta = self._gaze_pose_delta_wp - with torch_stream(self._gaze_pose_delta.device): - if env_mask is not None: - wp.launch(apply_gaze_masked_kernel, dim=len(delta), inputs=[orientation, delta, env_mask]) - elif env_ids is None: - wp.launch(apply_gaze_kernel, dim=len(delta), inputs=[orientation, delta]) - else: - if not isinstance(env_ids, wp.array): - ids = torch.as_tensor(env_ids, dtype=torch.int32, device=self._gaze_pose_delta.device) - env_ids = wp.from_torch(ids.contiguous()) + device = self._gaze_pose_delta.device + if env_ids is not None and env_mask is None: + if not isinstance(env_ids, wp.array): + ids = torch.as_tensor(env_ids, dtype=torch.int32, device=device) + env_ids = wp.from_torch(ids.contiguous()) + with torch_stream(device): wp.launch(apply_gaze_indexed_kernel, dim=len(env_ids), inputs=[orientation, delta, env_ids]) + return + # Every frame updates the same pose buffer, for all environments or under the camera's update mask. + launch, sources = self._gaze_pose_launches.get(env_mask is None, (None, None)) + if sources is None or sources[0] is not orientation or sources[1] is not env_mask: + if env_mask is None: + launch = record_launch(apply_gaze_kernel, len(delta), [orientation, delta], device=device) + else: + launch = record_launch( + apply_gaze_masked_kernel, len(delta), [orientation, delta, env_mask], device=device + ) + self._gaze_pose_launches[env_mask is None] = (launch, (orientation, env_mask)) + launch.launch(warp_stream(device)) def _gaze_validity(self, batch_size: int) -> torch.Tensor: """Return which samples the physical camera sees at the current gaze, shape (batch_size, num_samples).""" @@ -115,6 +129,7 @@ def _initialize_gaze(self) -> None: self._gaze_rays = self._gaze_rays.float().contiguous() self._gaze_rays_wp: dict[torch.device, wp.array] = {} self._gaze_angles_key = None + self._gaze_pose_launches: dict[bool, tuple[wp.Launch, tuple]] = {} device = self._gaze_rays.device self._gaze_identity = torch.eye(3, device=device) angle = math.radians(self.cfg.image_rotation_deg) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index ee230a312479..ff8230154584 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -92,12 +92,14 @@ def test_gaze_step_kernel_matches_the_torch_update(): expected_velocity = (expected - gaze) / dt velocity, angles = torch.empty_like(gaze), torch.empty_like(gaze) + state = torch.empty(count, 4) with torch_stream("cpu"): wp.launch( gaze_step_kernel, dim=count, inputs=[ *(wp.from_torch(buffer, dtype=wp.vec2f) for buffer in (actions, gaze, velocity, angles)), + wp.from_torch(state, dtype=wp.vec4f), step, limit, dt, @@ -107,6 +109,7 @@ def test_gaze_step_kernel_matches_the_torch_update(): torch.testing.assert_close(gaze, expected, atol=1e-6, rtol=1e-6) torch.testing.assert_close(velocity, expected_velocity, atol=1e-3, rtol=1e-5) torch.testing.assert_close(angles, expected * radius, atol=1e-5, rtol=1e-6) + torch.testing.assert_close(state, torch.cat((gaze, velocity), dim=-1)) def test_teacher_labels_kernel_matches_the_torch_labels(): diff --git a/source/isaaclab_fovi/test/test_gaze_kernels.py b/source/isaaclab_fovi/test/test_gaze_kernels.py index 0e61c109afef..4ca9aeac084e 100644 --- a/source/isaaclab_fovi/test/test_gaze_kernels.py +++ b/source/isaaclab_fovi/test/test_gaze_kernels.py @@ -8,9 +8,24 @@ import pytest import torch import warp as wp +from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel, gaze_rotation from isaaclab_fovi.sensors.calibrated_geometry import compose_rotations, convert_camera_frame_quaternion -from isaaclab_fovi.sensors.gaze_kernels import camera_params, project_directions, set_gaze_kernel, torch_stream +from isaaclab_fovi.sensors.gaze_kernels import ( + camera_params, + project_directions, + publish_grid_kernel, + set_gaze_kernel, + torch_stream, +) +from isaaclab_fovi.sensors.native_grid import ( + GRID_STYLE, + allocate_grid_outputs, + copy_grid_outputs, + grid_sample_indices, + mask_grid_samples, + native_grid_directions, +) from isaaclab.utils.math import matrix_from_quat, quat_from_matrix @@ -105,3 +120,61 @@ def test_gaze_kernel_matches_the_torch_composition(): product = wp.normalize(wp.quatf(*base[i].tolist()) * wp.quatf(*delta[i].tolist())) result[i] = torch.tensor([product[0], product[1], product[2], product[3]]) torch.testing.assert_close(matrix_from_quat(result), matrix_from_quat(expected), atol=1e-5, rtol=0) + + +def test_publish_kernel_matches_masking_then_copying_to_the_grid(): + camera = CAMERAS["distorted pinhole"] + coords = SamplingCoords( + camera.field_of_view("short"), + 0.591, + 24, + style=GRID_STYLE, + field_geometry="spherical", + device=DEVICE, + ) + rays = (native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1))).float().contiguous() + generator = torch.Generator().manual_seed(2) + angles = ((torch.rand(6, 2, generator=generator) * 2 - 1) * 25).to(DEVICE) + rotation, _ = _set_gaze(angles, torch.eye(3, device=DEVICE)) + count = len(coords) + outputs = { + "rgba": torch.randint(1, 255, (6, count, 1, 4), generator=generator, dtype=torch.uint8).to(DEVICE), + "depth": (torch.rand(6, count, 1, 1, generator=generator) + 0.5).to(DEVICE), + } + indices = grid_sample_indices(coords) + valid = camera.project(rays @ rotation.transpose(-1, -2))[1] + + # The sequence the kernel replaces: footprint mask, sensor mask, then the grid layout. + expected = {name: value.clone() for name, value in outputs.items()} + mask_grid_samples(expected, coords) + for value in expected.values(): + value.masked_fill_(~valid[:, :, None, None], 0) + expected_grid = allocate_grid_outputs(expected, coords) + copy_grid_outputs(expected, expected_grid, indices) + + visible = torch.zeros(6, count, dtype=torch.bool, device=DEVICE) + for name, value in outputs.items(): + target = torch.zeros_like(expected_grid[name]) + source = value.squeeze(2) + with torch_stream(DEVICE): + wp.launch( + publish_grid_kernel, + dim=(6, count), + inputs=[ + wp.from_torch(source.view(torch.uint8)), + wp.from_torch(indices.to(torch.int32).contiguous()), + wp.from_torch(coords.valid_mask.contiguous()), + wp.from_torch(rays, dtype=wp.vec3f), + wp.from_torch(rotation, dtype=wp.mat33f), + camera_params(camera), + 1, + int(name == "rgba"), + wp.from_torch(visible), + ], + outputs=[wp.from_torch(target.view(6, count, -1).view(torch.uint8))], + ) + # Float32 rounding may flip a sample on the image edge, nothing more. + same = (target == expected_grid[name]).all(-1) + assert same.float().mean() > 0.999 + assert (visible == valid).float().mean() > 0.999 + assert valid.any() and (~valid).any() From 009f314fa9a9e1173a47454bb0949e8c53cc770a Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 19:40:03 -0800 Subject: [PATCH 25/81] Cut the gaze tasks' per-step launches The gaze step writes the camera's own angles buffer and reads the action manager's buffer, so a step needs no copy or set launch; the Newton pose kernel turns the gaze from the stored angles. The camera hands the renderer its pose once per update instead of twice. A gaze reset is one recorded kernel instead of thirteen torch ops, and the camera's reset pose update replays a recorded launch. The teacher's labels and logs come from one single-block kernel, without zeroed atomics. --- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 187 +++++++++++++----- .../sensors/foveated_newton_camera.py | 39 ++-- .../sensors/foveated_rtx_camera.py | 2 +- .../isaaclab_fovi/sensors/gaze_kernels.py | 73 ++++--- .../isaaclab_fovi/sensors/virtual_gaze.py | 104 +++++++--- source/isaaclab_fovi/test/test_active_gaze.py | 80 ++++++-- .../isaaclab_fovi/test/test_gaze_kernels.py | 69 ++++--- 7 files changed, 388 insertions(+), 166 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 8305f235b99c..d456aa9d27d1 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -108,21 +108,66 @@ def teacher_labels_kernel( gaze_limit: wp.float32, camera: CameraParams, labels: wp.array2d(dtype=wp.float32), - sums: wp.array(dtype=wp.float32), + log: wp.array(dtype=wp.float32), ): - """Labels (action x, action y, valid) toward a point fixed to each target, and the error and count sums of valid - targets.""" - i = wp.tid() - point = targets[i] - if rotate_offset != 0: - point = point + wp.quat_rotate(orientations[i], offset) - result = teach(point, positions[i], mount, gaze[i], field_radius_deg, step_size, gaze_limit, camera) - labels[i, 0] = result[0] - labels[i, 1] = result[1] - labels[i, 2] = result[2] - if result[2] > 0.5: - wp.atomic_add(sums, 0, result[3]) - wp.atomic_add(sums, 1, 1.0) + """Labels (action x, action y, valid) toward a point fixed to each target; and the mean gaze error to valid + targets [deg] with the fraction of valid targets. + + One block labels every environment and reduces the logs itself, so the launch needs no zeroed accumulators. + """ + _block, lane = wp.tid() + count = targets.shape[0] + error_sum = wp.float32(0.0) + valid_count = wp.float32(0.0) + i = lane + while i < count: + point = targets[i] + if rotate_offset != 0: + point = point + wp.quat_rotate(orientations[i], offset) + result = teach(point, positions[i], mount, gaze[i], field_radius_deg, step_size, gaze_limit, camera) + labels[i, 0] = result[0] + labels[i, 1] = result[1] + labels[i, 2] = result[2] + if result[2] > 0.5: + error_sum += result[3] + valid_count += 1.0 + i += wp.block_dim() + errors = wp.tile_sum(wp.tile(error_sum)) + valid = wp.tile_sum(wp.tile(valid_count)) + if lane == 0: + log[0] = errors[0] / wp.max(valid[0], 1.0) + log[1] = valid[0] / wp.float32(count) + + +def teacher_block_dim(device: torch.device | str) -> int: + """Threads of the one block that runs :func:`teacher_labels_kernel`; Warp runs CPU blocks as one thread.""" + return 1024 if torch.device(device).type == "cuda" else 1 + + +@wp.kernel(enable_backward=False) +def gaze_reset_kernel( + ids: wp.array(dtype=wp.int32), + use_ids: wp.int32, + start: wp.array(dtype=wp.vec2f), + use_start: wp.int32, + field_radius_deg: wp.float32, + gaze: wp.array(dtype=wp.vec2f), + velocity: wp.array(dtype=wp.vec2f), + angles_deg: wp.array(dtype=wp.vec2f), + state: wp.array(dtype=wp.vec4f), +): + """Put each reset environment's gaze at its start, or on the optical axis, at rest.""" + k = wp.tid() + i = k + if use_ids != 0: + i = ids[k] + g = wp.vec2f(0.0, 0.0) + if use_start != 0: + g = start[k] + gaze[i] = g + velocity[i] = wp.vec2f(0.0, 0.0) + angles_deg[i] = g * field_radius_deg + state[i] = wp.vec4f(g[0], g[1], 0.0, 0.0) @wp.kernel(enable_backward=False) @@ -208,24 +253,44 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): """Orientation (x, y, z, w) of the physical camera in the environment frame, ROS convention.""" self._mount = wp.quatf(*self.mount_rotation.tolist()) self._raw = torch.zeros(self.num_envs, 2, device=self.device) + """Gaze actions of the last step; once bound, a view of the action manager's buffer.""" self._gaze = torch.zeros_like(self._raw) self._velocity = torch.zeros_like(self._raw) - self._angles = torch.zeros_like(self._raw) - """Gaze angles [deg] of the last step, the buffer the camera reads.""" + self._angles = None + """Gaze angles [deg] of the last step; the camera's own buffer, bound on first use.""" self._state = torch.zeros(self.num_envs, 4, device=self.device) """Gaze and its velocity, the gaze observation.""" - self._raw_wp, self._gaze_wp, self._velocity_wp, self._angles_wp = ( - wp.from_torch(buffer, dtype=wp.vec2f) for buffer in (self._raw, self._gaze, self._velocity, self._angles) - ) + self._gaze_wp, self._velocity_wp = (wp.from_torch(b, dtype=wp.vec2f) for b in (self._gaze, self._velocity)) + self._state_wp = wp.from_torch(self._state, dtype=wp.vec4f) + self._step_launch = None + self._labels = torch.zeros(self.num_envs, 3, device=self.device) + self._log = torch.zeros(2, device=self.device) + """Mean gaze error to valid teacher targets [deg] and the fraction of valid targets.""" + self._no_orientations = wp.from_torch(torch.zeros(1, 4, device=self.device), dtype=wp.quatf) + self._labels_launch = None + # Each reset copies its environments, and their start gazes if random, into these and replays one launch. + self._reset_ids = torch.zeros(self.num_envs, dtype=torch.int32, device=self.device) + self._reset_start = torch.zeros(self.num_envs, 2, device=self.device) + self._reset_launches: dict[tuple[bool, bool], wp.Launch] = {} + + def _bind(self) -> None: + """Read actions from the action manager's buffer and write angles into the camera's, saving a copy each.""" + manager = self._env.action_manager + terms = [manager.get_term(name) for name in manager.active_terms] + start = sum(manager.action_term_dim[: terms.index(self)]) + # The manager stores each step's actions before handing this term its slice, so the values are the same. + self._raw = manager.action[:, start : start + self.action_dim] + self._angles = self.camera.gaze_angles_buffer() + self._angles_wp = wp.from_torch(self._angles, dtype=wp.vec2f) self._step_launch = record_launch( gaze_step_kernel, self.num_envs, [ - self._raw_wp, + wp.from_torch(self._raw, dtype=wp.vec2f), self._gaze_wp, self._velocity_wp, self._angles_wp, - wp.from_torch(self._state, dtype=wp.vec4f), + self._state_wp, self.cfg.step_size, self.cfg.gaze_limit, self._env.step_dt, @@ -233,11 +298,6 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): ], device=self.device, ) - self._labels = torch.zeros(self.num_envs, 3, device=self.device) - self._label_sums = torch.zeros(2, device=self.device) - self._label_sums_wp = wp.from_torch(self._label_sums) - self._no_orientations = wp.from_torch(torch.zeros(1, 4, device=self.device), dtype=wp.quatf) - self._labels_launch = None @property def action_dim(self) -> int: @@ -272,7 +332,9 @@ def angles_deg(self) -> torch.Tensor: return self._gaze * self.field_radius_deg def process_actions(self, actions: torch.Tensor): - self._raw.copy_(actions) + """Move the gaze by this step's actions, which the term reads from the action manager's buffer.""" + if self._step_launch is None: + self._bind() self._step_launch.launch(warp_stream(self.device)) self.camera.set_gaze_angles(self._angles) @@ -280,17 +342,41 @@ def apply_actions(self): pass def reset(self, env_ids=None): - ids = torch.arange(self.num_envs, device=self.device)[slice(None) if env_ids is None else env_ids] - self._raw[ids] = 0.0 - self._velocity[ids] = 0.0 - self._gaze[ids] = 0.0 - if self.cfg.random_reset and len(ids): - gaze = random_gaze(len(ids), self.cfg.gaze_limit, self.device) + # The action manager zeroes the reset environments' actions itself. + if self._step_launch is None: + self._bind() + indexed = env_ids is not None + count = self.num_envs + if indexed: + if isinstance(env_ids, slice): + env_ids = torch.arange(self.num_envs, device=self.device)[env_ids] + count = len(env_ids) + if count == 0: + return + self._reset_ids[:count] = torch.as_tensor(env_ids, device=self.device) + random_start = self.cfg.random_reset + if random_start: + gaze = random_gaze(count, self.cfg.gaze_limit, self.device) visible = self.visible(angles_to_direction(gaze * self.field_radius_deg)) - self._gaze[ids] = torch.where(visible[:, None], gaze, 0.0) + self._reset_start[:count] = torch.where(visible[:, None], gaze, 0.0) + launch = self._reset_launches.get((indexed, random_start)) + if launch is None: + launch = self._reset_launches[(indexed, random_start)] = record_launch( + gaze_reset_kernel, + self.num_envs, + [ + wp.from_torch(self._reset_ids), + int(indexed), + wp.from_torch(self._reset_start, dtype=wp.vec2f), + int(random_start), + self.field_radius_deg, + ], + [self._gaze_wp, self._velocity_wp, self._angles_wp, self._state_wp], + self.device, + ) + launch.set_dim(count) + launch.launch(warp_stream(self.device)) # The camera keeps reading the same buffer, which every other environment already holds. - self._angles[ids] = self._gaze[ids] * self.field_radius_deg - self._state[ids] = torch.cat((self._gaze[ids], self._velocity[ids]), dim=-1) self.camera.set_gaze_angles(self._angles) def directions(self, points: torch.Tensor) -> torch.Tensor: @@ -346,15 +432,16 @@ def _teacher_labels( offset: The point in each target's frame [m]. Returns: - The labels (action x, action y, valid), shape (num_envs, 3); and the sum of the gaze's errors to valid - targets [deg] with their count, shape (2,). Both are buffers the next call overwrites. + The labels (action x, action y, valid), shape (num_envs, 3); and the mean gaze error to valid targets + [deg] with the fraction of valid targets, shape (2,). Both are buffers the next call overwrites. """ positions = self.camera.data.pos_w.warp sources = (targets, orientations, positions, offset) if self._labels_launch is None or any(a is not b for a, b in zip(self._labels_launch[0], sources)): + block = teacher_block_dim(self.device) launch = record_launch( teacher_labels_kernel, - self.num_envs, + (1, block), [ targets, self._no_orientations if orientations is None else orientations, @@ -368,13 +455,13 @@ def _teacher_labels( self.cfg.gaze_limit, self._camera, ], - [wp.from_torch(self._labels), self._label_sums_wp], + [wp.from_torch(self._labels), wp.from_torch(self._log)], self.device, + block_dim=block, ) self._labels_launch = (sources, launch) - self._label_sums.zero_() self._labels_launch[1].launch(warp_stream(self.device)) - return self._labels, self._label_sums + return self._labels, self._log @configclass @@ -426,16 +513,18 @@ def teacher_labels(env: ManagerBasedEnv, points: torch.Tensor, action_name: str the object is grasped, choose the points and call this. """ term: GazeAction = env.action_manager.get_term(action_name) - labels, sums = term._teacher_labels(wp.from_torch(points.float().contiguous(), dtype=wp.vec3f)) - _log_teacher(env, sums, len(labels)) + labels, values = term._teacher_labels(wp.from_torch(points.float().contiguous(), dtype=wp.vec3f)) + _log_teacher(env, values) return labels -def _log_teacher(env: ManagerBasedEnv, sums: torch.Tensor, count: int) -> None: +def _log_teacher(env: ManagerBasedEnv, values: torch.Tensor) -> None: """Log the mean gaze error to valid targets and the fraction of valid targets.""" + # Loggers keep each step's entries, so they get a copy rather than the buffer the next step overwrites. + error, fraction = values.clone() log = env.extras.setdefault("log", {}) - log["Gaze/target_error_deg"] = sums[0] / sums[1].clamp_min(1) - log["Gaze/valid_target_fraction"] = sums[1] / count + log["Gaze/target_error_deg"] = error + log["Gaze/valid_target_fraction"] = fraction class gaze_teacher_labels(ManagerTermBase): @@ -475,8 +564,8 @@ def __call__( self._targets = wp.from_torch(positions.torch[:, body], dtype=wp.vec3f) self._orientations = wp.from_torch(orientations.torch[:, body], dtype=wp.quatf) term: GazeAction = env.action_manager.get_term(action_name) - labels, sums = term._teacher_labels(self._targets, self._orientations, self._offset) - _log_teacher(env, sums, len(labels)) + labels, values = term._teacher_labels(self._targets, self._orientations, self._offset) + _log_teacher(env, values) return labels diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 1af7b50b79f8..d5f2d1aaf4a5 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -15,7 +15,7 @@ import logging from collections.abc import Sequence -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar import torch import warp as wp @@ -76,8 +76,11 @@ class FoveatedNewtonCamera(FoveatedCamera): cfg: FoveatedCameraCfg + _gaze_pose_reads_angles: ClassVar[bool] = True + def __init__(self, cfg: FoveatedCameraCfg): - self._gaze_rotation = None + # The parent's initialisation updates poses before the gaze exists. + self._gaze_angles = self._gaze_rotation = None super().__init__(cfg) # ------------------------------------------------------------------ @@ -350,29 +353,31 @@ def _update_poses( env_mask: wp.array | None = None, frame_op: int = 0, ) -> None: - """Read base poses, apply the gaze, update renderer, inject rays. + """Read base poses, turn them by the gaze, update the renderer once, and inject the foveated rays. The scene pose is read even without a gaze: the camera may inherit motion from a parent body. """ - # 1. Read base camera poses, then rotate them by the gaze if one is set. + # The base update turns the poses by the gaze in _update_camera_state, then hands them to the renderer. Camera._update_poses(self, env_ids, env_mask=env_mask, frame_op=frame_op) - self._apply_gaze_pose(env_ids, env_mask) - - # 2. Update camera_transforms - # The renderer maintains persistent transform buffers and updates - # them in place after the pose changes. - self._renderer.update_camera( - self._render_data, - self._data.pos_w, - self._data.quat_w_world, - self._data.intrinsic_matrices, - ) - - # 3. Ensure foveated rays (not pinhole) + # Ensure foveated rays (not pinhole) if hasattr(self, "_foveated_rays"): self._render_data.camera_rays = self._foveated_rays + def _update_camera_state( + self, + env_ids: wp.array | None = None, + env_mask: wp.array | None = None, + pos_src: wp.array | None = None, + quat_src: wp.array | None = None, + update_pose: bool = False, + frame_op: int = 0, + ): + """Update the camera state, then turn freshly read poses by the gaze before the renderer sees them.""" + super()._update_camera_state(env_ids, env_mask, pos_src, quat_src, update_pose, frame_op) + if update_pose: + self._apply_gaze_pose(env_ids, env_mask) + def _update_buffers_impl(self, env_mask: wp.array): """Render, then (optionally) pool highres -> lowres foveated samples.""" self._data.output.clear() diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 22bbe2d85951..83d455f25543 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -89,7 +89,7 @@ def renderer(self) -> BaseRenderer: return self._renderer def __init__(self, cfg: FoveatedCameraCfg): - self._gaze_rotation = None + self._gaze_angles = self._gaze_rotation = None # Texture buffers are owned by the parent ``Camera`` (allocated in # ``_create_buffers`` and bound to the renderer via ``set_outputs``). # Foveated / pooled buffers are allocated in ``_initialize_impl`` diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py index e5e58d1e8001..da3441d1f829 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Warp kernels of the virtual gaze, one launch each per gaze change, camera pose update and sensor mask. +"""Warp kernels of the virtual gaze, one launch each per camera pose update and published output. :func:`project_direction` follows :meth:`fovi.sensing.projection.CameraModel.project` operation for operation, in float32. Camera-frame directions follow the ROS (OpenCV) convention: x right, y down, z forward. @@ -53,10 +53,14 @@ def torch_stream(device: torch.device | str) -> wp.ScopedStream | wp.ScopedDevic return wp.ScopedStream(stream, sync_enter=False, sync_exit=False) -def record_launch(kernel, dim, inputs, outputs=(), device: torch.device | str = "cpu") -> wp.Launch: +def record_launch( + kernel, dim, inputs, outputs=(), device: torch.device | str = "cpu", block_dim: int = 256 +) -> wp.Launch: """A launch recorded once and replayed each step with :meth:`warp.Launch.launch`, skipping argument packing.""" wp.init() - return wp.launch(kernel, dim=dim, inputs=inputs, outputs=outputs, device=str(device), record_cmd=True) + return wp.launch( + kernel, dim=dim, inputs=inputs, outputs=outputs, device=str(device), block_dim=block_dim, record_cmd=True + ) @wp.struct @@ -150,47 +154,62 @@ def gaze_rotation(angles_deg: wp.vec2f) -> wp.mat33f: return wp.mat33f(cp, sp * sr, sp * cr, 0.0, cr, -sr, -sp, cp * sr, cp * cr) +@wp.func +def gaze_pose( + orientation: wp.quatf, gaze: wp.mat33f, basis: wp.mat33f, to_opengl: wp.quatf, to_world: wp.quatf +) -> wp.quatf: + """The world orientation (world convention) of a camera at ``orientation`` turned by a gaze rotation.""" + relative = basis * gaze * wp.transpose(basis) + return wp.normalize(orientation * (to_opengl * wp.quat_from_matrix(relative) * to_world)) + + @wp.kernel(enable_backward=False) def set_gaze_kernel( angles_deg: wp.array(dtype=wp.vec2f), - basis: wp.mat33f, - to_opengl: wp.quatf, - to_world: wp.quatf, + stored_angles: wp.array(dtype=wp.vec2f), rotation: wp.array(dtype=wp.mat33f), - pose_delta: wp.array(dtype=wp.quatf), ): - """The gaze rotation of each environment, and the change it makes to the camera's world orientation. - - A camera at world orientation ``q`` (world convention) looks along ``q * pose_delta``. - """ - i = wp.tid() - gaze = gaze_rotation(angles_deg[i]) - rotation[i] = gaze - relative = basis * gaze * wp.transpose(basis) - pose_delta[i] = to_opengl * wp.quat_from_matrix(relative) * to_world - - -@wp.kernel(enable_backward=False) -def apply_gaze_kernel(orientation: wp.array(dtype=wp.quatf), pose_delta: wp.array(dtype=wp.quatf)): + """Store each environment's gaze angles and their gaze rotation.""" i = wp.tid() - orientation[i] = wp.normalize(orientation[i] * pose_delta[i]) + angles = angles_deg[i] + stored_angles[i] = angles + rotation[i] = gaze_rotation(angles) @wp.kernel(enable_backward=False) -def apply_gaze_masked_kernel( - orientation: wp.array(dtype=wp.quatf), pose_delta: wp.array(dtype=wp.quatf), mask: wp.array(dtype=wp.bool) +def apply_gaze_kernel( + angles_deg: wp.array(dtype=wp.vec2f), + basis: wp.mat33f, + to_opengl: wp.quatf, + to_world: wp.quatf, + mask: wp.array(dtype=wp.bool), + use_mask: wp.int32, + orientation: wp.array(dtype=wp.quatf), + rotation: wp.array(dtype=wp.mat33f), ): + """Turn each camera's world orientation by its gaze, or only the masked ones, and record every gaze rotation.""" i = wp.tid() - if mask[i]: - orientation[i] = wp.normalize(orientation[i] * pose_delta[i]) + gaze = gaze_rotation(angles_deg[i]) + rotation[i] = gaze + if use_mask == 0 or mask[i]: + orientation[i] = gaze_pose(orientation[i], gaze, basis, to_opengl, to_world) @wp.kernel(enable_backward=False) def apply_gaze_indexed_kernel( - orientation: wp.array(dtype=wp.quatf), pose_delta: wp.array(dtype=wp.quatf), indices: wp.array(dtype=wp.int32) + angles_deg: wp.array(dtype=wp.vec2f), + basis: wp.mat33f, + to_opengl: wp.quatf, + to_world: wp.quatf, + indices: wp.array(dtype=wp.int32), + orientation: wp.array(dtype=wp.quatf), + rotation: wp.array(dtype=wp.mat33f), ): + """Turn the indexed cameras' world orientations by their gaze, and record their gaze rotations.""" i = indices[wp.tid()] - orientation[i] = wp.normalize(orientation[i] * pose_delta[i]) + gaze = gaze_rotation(angles_deg[i]) + rotation[i] = gaze + orientation[i] = gaze_pose(orientation[i], gaze, basis, to_opengl, to_world) @wp.kernel(enable_backward=False) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index 9a0641dc5137..f417cfc09380 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -9,6 +9,7 @@ import math from collections.abc import Sequence +from typing import ClassVar import torch import warp as wp @@ -18,7 +19,6 @@ from .gaze_kernels import ( apply_gaze_indexed_kernel, apply_gaze_kernel, - apply_gaze_masked_kernel, camera_params, record_launch, sensor_visibility_kernel, @@ -36,6 +36,20 @@ class VirtualGaze: to the optical axis of the physical camera it looks through. """ + _gaze_pose_reads_angles: ClassVar[bool] = False + """Whether the camera's per-frame pose update turns the gaze from its stored angles, so that a writer of + :meth:`gaze_angles_buffer` needs no other launch.""" + + def gaze_angles_buffer(self) -> torch.Tensor: + """The camera's stored gaze angles [deg], shape (num_envs, 2). + + A writer that moves the gaze every step can update this buffer in place and pass it to + :meth:`set_gaze_angles`, which then copies nothing. Writes take effect when :meth:`set_gaze_angles` is called. + """ + if self._gaze_angles is None: + self._allocate_gaze(self._view.count, torch.device(self._device)) + return self._gaze_angles + def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. @@ -45,55 +59,80 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: Args: angles_deg: Gaze angles for every environment [deg], shape (num_envs, 2). """ - angles = angles_deg.detach().float().contiguous() - rotation = self._gaze_rotation - if rotation is None or rotation.shape[0] != len(angles) or rotation.device != angles.device: - self._gaze_rotation = torch.empty(len(angles), 3, 3, device=angles.device) - self._gaze_pose_delta = torch.empty(len(angles), 4, device=angles.device) - self._gaze_rotation_wp = wp.from_torch(self._gaze_rotation, dtype=wp.mat33f) - self._gaze_pose_delta_wp = wp.from_torch(self._gaze_pose_delta, dtype=wp.quatf) - self._gaze_angles_key = None - self._gaze_pose_launches = {} + stored = angles_deg is self._gaze_angles and angles_deg is not None + if stored and self._gaze_pose_reads_angles and self.cfg.update_latest_camera_pose: + # The next pose update reads the stored angles; nothing has to happen now. + return + angles = angles_deg if stored else angles_deg.detach().float().contiguous() + if ( + self._gaze_angles is None + or len(self._gaze_angles) != len(angles) + or self._gaze_angles.device != angles.device + ): + self._allocate_gaze(len(angles), angles.device) # Callers usually pass the same buffer every step; record its launch once. key = (angles.data_ptr(), angles.shape, angles.device) if key != self._gaze_angles_key: - self._gaze_angles_wp = wp.from_torch(angles, dtype=wp.vec2f) self._gaze_angles_key = key self._set_gaze_launch = record_launch( set_gaze_kernel, len(angles), - [self._gaze_angles_wp, *self._gaze_frames], - [self._gaze_rotation_wp, self._gaze_pose_delta_wp], + [wp.from_torch(angles, dtype=wp.vec2f)], + [self._gaze_angles_wp, self._gaze_rotation_wp], angles.device, ) self._set_gaze_launch.launch(warp_stream(angles.device)) + def _allocate_gaze(self, count: int, device: torch.device) -> None: + """Allocate the stored gaze, on the optical axis, and its rotation.""" + self._gaze_angles = torch.zeros(count, 2, device=device) + self._gaze_rotation = torch.eye(3, device=device).repeat(count, 1, 1) + self._gaze_angles_wp = wp.from_torch(self._gaze_angles, dtype=wp.vec2f) + self._gaze_rotation_wp = wp.from_torch(self._gaze_rotation, dtype=wp.mat33f) + self._gaze_angles_key = None + self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} + self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=str(device)) + def _apply_gaze_pose( self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None ) -> None: - if self._gaze_rotation is None: + """Turn the camera's world orientation by the stored gaze, and record the gaze rotations it uses.""" + if self._gaze_angles is None: return orientation = self._data.quat_w_world orientation = orientation.warp if hasattr(orientation, "warp") else wp.from_torch(orientation, dtype=wp.quatf) - delta = self._gaze_pose_delta_wp - device = self._gaze_pose_delta.device - if env_ids is not None and env_mask is None: - if not isinstance(env_ids, wp.array): - ids = torch.as_tensor(env_ids, dtype=torch.int32, device=device) - env_ids = wp.from_torch(ids.contiguous()) - with torch_stream(device): - wp.launch(apply_gaze_indexed_kernel, dim=len(env_ids), inputs=[orientation, delta, env_ids]) - return - # Every frame updates the same pose buffer, for all environments or under the camera's update mask. - launch, sources = self._gaze_pose_launches.get(env_mask is None, (None, None)) - if sources is None or sources[0] is not orientation or sources[1] is not env_mask: - if env_mask is None: - launch = record_launch(apply_gaze_kernel, len(delta), [orientation, delta], device=device) + device = self._gaze_angles.device + frames = (self._gaze_angles_wp, *self._gaze_frames) + indexed = env_ids is not None and env_mask is None + if indexed and not isinstance(env_ids, wp.array): + env_ids = wp.from_torch(torch.as_tensor(env_ids, dtype=torch.int32, device=device).contiguous()) + # Every pose update writes the same pose buffer: for all environments, under the camera's update mask, or + # for the indexed ones, whose indices each call swaps in. + mode = "ids" if indexed else ("all" if env_mask is None else "mask") + launch, sources = self._gaze_pose_launches.get(mode, (None, None)) + if sources is None or sources[0] is not orientation or (mode == "mask" and sources[1] is not env_mask): + if indexed: + launch = record_launch( + apply_gaze_indexed_kernel, + len(env_ids), + [*frames, env_ids], + [orientation, self._gaze_rotation_wp], + device, + ) else: launch = record_launch( - apply_gaze_masked_kernel, len(delta), [orientation, delta, env_mask], device=device + apply_gaze_kernel, + len(self._gaze_angles), + [*frames, self._gaze_no_mask if env_mask is None else env_mask, int(env_mask is not None)], + [orientation, self._gaze_rotation_wp], + device, ) - self._gaze_pose_launches[env_mask is None] = (launch, (orientation, env_mask)) + self._gaze_pose_launches[mode] = (launch, (orientation, env_mask)) + if indexed: + if len(env_ids) == 0: + return + launch.set_param_by_name("indices", env_ids) + launch.set_dim(len(env_ids)) launch.launch(warp_stream(device)) def _gaze_validity(self, batch_size: int) -> torch.Tensor: @@ -128,8 +167,9 @@ def _initialize_gaze(self) -> None: self._gaze_rays = angular_directions(coords.cartesian, coords.fov) self._gaze_rays = self._gaze_rays.float().contiguous() self._gaze_rays_wp: dict[torch.device, wp.array] = {} - self._gaze_angles_key = None - self._gaze_pose_launches: dict[bool, tuple[wp.Launch, tuple]] = {} + # No gaze until one is set: the camera looks along its optical axis untouched. + self._gaze_angles = None + self._gaze_rotation = None device = self._gaze_rays.device self._gaze_identity = torch.eye(3, device=device) angle = math.radians(self.cfg.image_rotation_deg) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index ff8230154584..069d9cfcbfce 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -10,7 +10,13 @@ import warp as wp from fovi.sensing.projection import CameraModel from isaaclab_fovi.mdp import angles_to_direction, clamp_gaze, direction_to_angles -from isaaclab_fovi.mdp.gaze import gaze_step_kernel, teacher_kernel, teacher_labels_kernel +from isaaclab_fovi.mdp.gaze import ( + gaze_reset_kernel, + gaze_step_kernel, + teacher_block_dim, + teacher_kernel, + teacher_labels_kernel, +) from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream from rsl_rl.models import MLPModel @@ -21,6 +27,7 @@ NUM_ENVS = 64 STEPS = 8 +DEVICES = ["cpu", "cuda:0"] if torch.cuda.is_available() else ["cpu"] def test_gaze_angles_round_trip_and_follow_the_camera_convention(): @@ -112,11 +119,12 @@ def test_gaze_step_kernel_matches_the_torch_update(): torch.testing.assert_close(state, torch.cat((gaze, velocity), dim=-1)) -def test_teacher_labels_kernel_matches_the_torch_labels(): +@pytest.mark.parametrize("device", DEVICES) +def test_teacher_labels_kernel_matches_the_torch_labels(device): camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5)) field_radius, step, limit = 30.0, 0.1, 1.0 generator = torch.Generator().manual_seed(5) - count = 4096 + count = 4099 mount = torch.nn.functional.normalize(torch.randn(4, generator=generator), dim=0) positions = torch.randn(count, 3, generator=generator) lateral = torch.randn(count, 2, generator=generator) * 0.6 @@ -136,34 +144,74 @@ def test_teacher_labels_kernel_matches_the_torch_labels(): error = torch.atan2(torch.cross(looking, direction, dim=-1).norm(dim=-1), (looking * direction).sum(-1)).rad2deg() expected = torch.cat((action, valid[:, None].float()), dim=-1) - labels = torch.empty(count, 3) - sums = torch.zeros(2) - with torch_stream("cpu"): + labels = torch.empty(count, 3, device=device) + log = torch.full((2,), float("nan"), device=device) + block = teacher_block_dim(device) + with torch_stream(device): wp.launch( teacher_labels_kernel, - dim=count, + dim=(1, block), inputs=[ - wp.from_torch(targets, dtype=wp.vec3f), - wp.from_torch(orientations, dtype=wp.quatf), + wp.from_torch(targets.to(device), dtype=wp.vec3f), + wp.from_torch(orientations.to(device), dtype=wp.quatf), wp.vec3f(*offset.tolist()), 1, - wp.from_torch(positions, dtype=wp.vec3f), + wp.from_torch(positions.to(device), dtype=wp.vec3f), wp.quatf(*mount.tolist()), - wp.from_torch(gaze, dtype=wp.vec2f), + wp.from_torch(gaze.to(device), dtype=wp.vec2f), field_radius, step, limit, camera_params(camera), ], - outputs=[wp.from_torch(labels), wp.from_torch(sums)], + outputs=[wp.from_torch(labels), wp.from_torch(log)], + block_dim=block, ) + labels, log = labels.cpu(), log.cpu() agree = (labels[:, 2] > 0.5) == valid assert agree.float().mean() > 0.999 and valid.any() and (~valid).any() torch.testing.assert_close(labels[agree], expected[agree], atol=1e-4, rtol=0) - both = agree & valid - assert float(sums[1]) == pytest.approx(float((labels[:, 2] > 0.5).sum())) - assert float(sums[0]) == pytest.approx(float(torch.where(labels[:, 2] > 0.5, error, 0.0).sum()), rel=1e-4) - assert both.sum() > 0 + labelled = labels[:, 2] > 0.5 + assert float(log[1]) == pytest.approx(float(labelled.float().mean())) + assert float(log[0]) == pytest.approx(float(error[labelled].mean()), rel=1e-4) + + +@pytest.mark.parametrize("ids", [None, [3, 0, 7]]) +@pytest.mark.parametrize("random_start", [False, True]) +def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): + count, radius = 10, 23.6 + generator = torch.Generator().manual_seed(6) + gaze, velocity, angles, state = (torch.randn(count, size, generator=generator) for size in (2, 2, 2, 4)) + selected = torch.arange(count) if ids is None else torch.tensor(ids) + start = torch.randn(len(selected), 2, generator=generator) if random_start else torch.zeros(len(selected), 2) + expected_gaze, expected_velocity = gaze.clone(), velocity.clone() + expected_angles, expected_state = angles.clone(), state.clone() + # The torch reset the kernel replaces. + expected_gaze[selected] = start + expected_velocity[selected] = 0.0 + expected_angles[selected] = expected_gaze[selected] * radius + expected_state[selected] = torch.cat((expected_gaze[selected], expected_velocity[selected]), dim=-1) + + with torch_stream("cpu"): + wp.launch( + gaze_reset_kernel, + dim=len(selected), + inputs=[ + wp.from_torch(selected.to(torch.int32)) if ids is not None else wp.zeros(1, dtype=wp.int32), + int(ids is not None), + wp.from_torch(start, dtype=wp.vec2f) if random_start else wp.zeros(1, dtype=wp.vec2f), + int(random_start), + radius, + ], + outputs=[ + *(wp.from_torch(buffer, dtype=wp.vec2f) for buffer in (gaze, velocity, angles)), + wp.from_torch(state, dtype=wp.vec4f), + ], + ) + for actual, expected in zip( + (gaze, velocity, angles, state), (expected_gaze, expected_velocity, expected_angles, expected_state) + ): + torch.testing.assert_close(actual, expected, atol=0, rtol=0) def test_gaze_loss_ignores_invalid_labels(): diff --git a/source/isaaclab_fovi/test/test_gaze_kernels.py b/source/isaaclab_fovi/test/test_gaze_kernels.py index 4ca9aeac084e..6f485091b91c 100644 --- a/source/isaaclab_fovi/test/test_gaze_kernels.py +++ b/source/isaaclab_fovi/test/test_gaze_kernels.py @@ -12,6 +12,8 @@ from fovi.sensing.projection import CameraModel, gaze_rotation from isaaclab_fovi.sensors.calibrated_geometry import compose_rotations, convert_camera_frame_quaternion from isaaclab_fovi.sensors.gaze_kernels import ( + apply_gaze_indexed_kernel, + apply_gaze_kernel, camera_params, project_directions, publish_grid_kernel, @@ -74,40 +76,43 @@ def test_projection_matches_fovi(name): ) -def _set_gaze(angles: torch.Tensor, basis: torch.Tensor): - identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=DEVICE) - to_opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl")[0] - to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0] +def _set_gaze(angles: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """The stored angles and gaze rotations :func:`set_gaze_kernel` writes.""" + stored = torch.empty_like(angles) rotation = torch.empty(len(angles), 3, 3, device=DEVICE) - delta = torch.empty(len(angles), 4, device=DEVICE) with torch_stream(DEVICE): wp.launch( set_gaze_kernel, dim=len(angles), - inputs=[ - wp.from_torch(angles.contiguous(), dtype=wp.vec2f), - wp.mat33f(*basis.flatten().tolist()), - wp.quatf(*to_opengl.tolist()), - wp.quatf(*to_world.tolist()), - ], - outputs=[wp.from_torch(rotation, dtype=wp.mat33f), wp.from_torch(delta, dtype=wp.quatf)], + inputs=[wp.from_torch(angles.contiguous(), dtype=wp.vec2f)], + outputs=[wp.from_torch(stored, dtype=wp.vec2f), wp.from_torch(rotation, dtype=wp.mat33f)], ) - return rotation, delta + return stored, rotation -def test_gaze_kernel_matches_the_torch_composition(): +def _gaze_frames(basis: torch.Tensor) -> list: + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=DEVICE) + to_opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl")[0] + to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0] + return [wp.mat33f(*basis.flatten().tolist()), wp.quatf(*to_opengl.tolist()), wp.quatf(*to_world.tolist())] + + +@pytest.mark.parametrize("selection", ["all", "mask", "indices"]) +def test_gaze_kernels_match_the_torch_composition(selection): generator = torch.Generator().manual_seed(1) - angles = ((torch.rand(64, 2, generator=generator) * 2 - 1) * 40).to(DEVICE) - base = torch.nn.functional.normalize(torch.randn(64, 4, generator=generator), dim=-1).to(DEVICE) + count = 64 + angles = ((torch.rand(count, 2, generator=generator) * 2 - 1) * 40).to(DEVICE) + base = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1).to(DEVICE) angle = torch.tensor(0.3) c, s = float(angle.cos()), float(angle.sin()) basis = torch.tensor(((c, s, 0.0), (s, -c, 0.0), (0.0, 0.0, -1.0)), device=DEVICE) - rotation, delta = _set_gaze(angles, basis) + stored, set_rotation = _set_gaze(angles) tilt, pan = angles.deg2rad().unbind(-1) direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) expected_rotation = gaze_rotation(direction, "pan_tilt") - torch.testing.assert_close(rotation, expected_rotation, atol=1e-5, rtol=0) + torch.testing.assert_close(stored, angles, atol=0, rtol=0) + torch.testing.assert_close(set_rotation, expected_rotation, atol=1e-5, rtol=0) # The torch composition the camera used per frame. relative = compose_rotations(compose_rotations(basis, expected_rotation), basis.T) @@ -115,11 +120,27 @@ def test_gaze_kernel_matches_the_torch_composition(): composed = quat_from_matrix(compose_rotations(matrix_from_quat(opengl), relative)) expected = convert_camera_frame_quaternion(composed, origin="opengl", target="world") - result = torch.empty_like(base) - for i in range(len(base)): - product = wp.normalize(wp.quatf(*base[i].tolist()) * wp.quatf(*delta[i].tolist())) - result[i] = torch.tensor([product[0], product[1], product[2], product[3]]) - torch.testing.assert_close(matrix_from_quat(result), matrix_from_quat(expected), atol=1e-5, rtol=0) + selected = torch.arange(count, device=DEVICE) % 3 == 0 + orientation = base.clone() + rotation = torch.zeros(count, 3, 3, device=DEVICE) + inputs = [wp.from_torch(angles, dtype=wp.vec2f), *_gaze_frames(basis)] + outputs = [wp.from_torch(orientation, dtype=wp.quatf), wp.from_torch(rotation, dtype=wp.mat33f)] + with torch_stream(DEVICE): + if selection == "indices": + ids = wp.from_torch(torch.nonzero(selected).flatten().to(torch.int32)) + wp.launch(apply_gaze_indexed_kernel, dim=len(ids), inputs=[*inputs, ids], outputs=outputs) + else: + mask = wp.from_torch(selected) if selection == "mask" else wp.zeros(1, dtype=wp.bool, device=DEVICE) + wp.launch(apply_gaze_kernel, dim=count, inputs=[*inputs, mask, int(selection == "mask")], outputs=outputs) + turned = torch.ones(count, dtype=torch.bool, device=DEVICE) if selection == "all" else selected + torch.testing.assert_close( + matrix_from_quat(orientation[turned]), matrix_from_quat(expected[turned]), atol=1e-5, rtol=0 + ) + torch.testing.assert_close(orientation[~turned], base[~turned], atol=0, rtol=0) + # Every environment's rotation is recorded, except that the indexed kernel touches only its own. + recorded = selected if selection == "indices" else torch.ones_like(selected) + torch.testing.assert_close(rotation[recorded], set_rotation[recorded], atol=0, rtol=0) + assert not rotation[~recorded].any() def test_publish_kernel_matches_masking_then_copying_to_the_grid(): @@ -135,7 +156,7 @@ def test_publish_kernel_matches_masking_then_copying_to_the_grid(): rays = (native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1))).float().contiguous() generator = torch.Generator().manual_seed(2) angles = ((torch.rand(6, 2, generator=generator) * 2 - 1) * 25).to(DEVICE) - rotation, _ = _set_gaze(angles, torch.eye(3, device=DEVICE)) + _, rotation = _set_gaze(angles) count = len(coords) outputs = { "rgba": torch.randint(1, 255, (6, count, 1, 4), generator=generator, dtype=torch.uint8).to(DEVICE), From f262c9e3dfd199ea50e9fb9ccb3d0742d548e91b Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 20:12:47 -0800 Subject: [PATCH 26/81] Turn the OVRTX gaze in the pose update and publish its grid in one kernel OVRTX renders the poses the camera hands it, so the foveated RTX camera on OVRTX turns the gaze in the pose kernel, as on Newton, instead of writing prim poses on every gaze change (about 0.5 ms each). Isaac RTX keeps the prim writes that Replicator reads. Native-grid RTX frames go through the same fused publish kernel as Newton's, which moves from the Newton camera into VirtualGaze. The render cases move into a shared module so OVRTX runs them without Kit, which cannot load beside it. --- .../sensors/foveated_newton_camera.py | 94 +------ .../sensors/foveated_rtx_camera.py | 21 +- .../isaaclab_fovi/sensors/virtual_gaze.py | 93 ++++++- .../test/foveated_render_cases.py | 233 ++++++++++++++++++ .../test/test_foveated_camera_render.py | 227 +---------------- .../test/test_foveated_camera_render_ovrtx.py | 50 ++++ 6 files changed, 412 insertions(+), 306 deletions(-) create mode 100644 source/isaaclab_fovi/test/foveated_render_cases.py create mode 100644 source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index d5f2d1aaf4a5..5c9ece111ff1 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -15,7 +15,7 @@ import logging from collections.abc import Sequence -from typing import TYPE_CHECKING, ClassVar +from typing import TYPE_CHECKING import torch import warp as wp @@ -26,7 +26,6 @@ from .calibrated_geometry import retinal_directions from .foveated_camera import FoveatedCamera from .foveated_rays import compute_explicit_ray_array -from .gaze_kernels import CameraParams, publish_grid_kernel, record_launch, warp_stream from .native_grid import ( GRID_STYLE, allocate_grid_outputs, @@ -76,7 +75,7 @@ class FoveatedNewtonCamera(FoveatedCamera): cfg: FoveatedCameraCfg - _gaze_pose_reads_angles: ClassVar[bool] = True + _gaze_pose_reads_angles = True def __init__(self, cfg: FoveatedCameraCfg): # The parent's initialisation updates poses before the gaze exists. @@ -207,8 +206,11 @@ def _initialize_impl(self): self._public_output = proxy_outputs(source) self._data.output.clear() self._data.output.update(self._public_output) - self._grid_publish = self._prepare_grid_publish() if self._native_grid and self._pooler is None else None - self._grid_launches = None + self._grid_publish = None + if self._native_grid and self._pooler is None: + self._prepare_grid_publish( + {name: value.torch.squeeze(2) for name, value in self._flat_render_output.items()} + ) # 6. Inject foveated rays into render_data immediately. self._render_data.camera_rays = self._foveated_rays @@ -217,72 +219,6 @@ def _initialize_impl(self): self._foveated_rays.shape, ) - def _prepare_grid_publish(self) -> list[tuple[wp.array, wp.array]]: - """Byte views of each rendered output and its public grid, for :func:`publish_grid_kernel`.""" - views = [] - for name, value in self._flat_render_output.items(): - if name == "rgb" and "rgba" in self._flat_render_output: - continue - source = value.torch.squeeze(2) - target = self._grid_output[name].view(source.shape[0], -1, source.shape[-1]) - views.append((wp.from_torch(source.view(torch.uint8)), wp.from_torch(target.view(torch.uint8)))) - self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous()) - self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous()) - num_envs = views[0][1].shape[0] - if self.cfg.mask_to_sensor_fov: - identity = self._gaze_identity.expand(num_envs, -1, -1).contiguous() - self._sensor_fov_valid_buffer = torch.zeros( - num_envs, len(self._gaze_rays), dtype=torch.bool, device=self._device - ) - self._grid_sensor = ( - wp.from_torch(self._gaze_rays, dtype=wp.vec3f), - wp.from_torch(identity, dtype=wp.mat33f), - self._gaze_camera, - wp.from_torch(self._sensor_fov_valid_buffer), - ) - else: - # Placeholders: the kernel reads none of these without the sensor mask. - self._grid_sensor = ( - wp.zeros(1, dtype=wp.vec3f, device=self._device), - wp.zeros(1, dtype=wp.mat33f, device=self._device), - CameraParams(), - wp.zeros((1, 1), dtype=wp.bool, device=self._device), - ) - return views - - def _publish_grid(self) -> None: - """Mask and lay out every output in one launch each; the result equals masking, then copying to the grid.""" - mask = self.cfg.mask_to_sensor_fov - rays, identity, camera, visible = self._grid_sensor - rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation_wp - if self._grid_launches is None or self._grid_launches[0] is not rotation: - launches = [ - record_launch( - publish_grid_kernel, - (target.shape[0], target.shape[1]), - [ - source, - self._grid_indices_wp, - self._grid_footprint_wp, - rays, - rotation, - camera, - int(mask), - int(mask and index == 0), - visible, - ], - [target], - self._device, - ) - for index, (source, target) in enumerate(self._grid_publish) - ] - self._grid_launches = (rotation, launches) - stream = warp_stream(self._device) - for launch in self._grid_launches[1]: - launch.launch(stream) - if mask: - self._sensor_fov_valid = self._sensor_fov_valid_buffer - def _validate_native_render_layout(self) -> None: """Reject image dimensions that cannot be covered by Newton's tiles.""" renderer = self._renderer.cfg @@ -364,27 +300,13 @@ def _update_poses( if hasattr(self, "_foveated_rays"): self._render_data.camera_rays = self._foveated_rays - def _update_camera_state( - self, - env_ids: wp.array | None = None, - env_mask: wp.array | None = None, - pos_src: wp.array | None = None, - quat_src: wp.array | None = None, - update_pose: bool = False, - frame_op: int = 0, - ): - """Update the camera state, then turn freshly read poses by the gaze before the renderer sees them.""" - super()._update_camera_state(env_ids, env_mask, pos_src, quat_src, update_pose, frame_op) - if update_pose: - self._apply_gaze_pose(env_ids, env_mask) - def _update_buffers_impl(self, env_mask: wp.array): """Render, then (optionally) pool highres -> lowres foveated samples.""" self._data.output.clear() self._data.output.update(self._render_output) if self._pooler is None: super()._update_buffers_impl(env_mask) - if self._grid_publish is not None: + if self._grid_publish: self._publish_grid() else: output = self._flat_render_output diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 83d455f25543..8000ce504e2f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -90,6 +90,10 @@ def renderer(self) -> BaseRenderer: def __init__(self, cfg: FoveatedCameraCfg): self._gaze_angles = self._gaze_rotation = None + # OVRTX renders the poses the camera hands it, so its pose update turns the gaze. Replicator reads camera + # prims, so Isaac RTX writes the gaze into them instead. + self._gaze_pose_reads_angles = cfg.renderer_cfg.renderer_type == "ovrtx" + self._grid_publish = None # Texture buffers are owned by the parent ``Camera`` (allocated in # ``_create_buffers`` and bound to the renderer via ``set_outputs``). # Foveated / pooled buffers are allocated in ``_initialize_impl`` @@ -297,6 +301,15 @@ def _initialize_impl(self) -> None: self._grid_indices = grid_sample_indices(self._sampling_coords) new_output = self._grid_output self._data._output = proxy_outputs(new_output) + # A native grid texture already holds the samples in order, so one kernel per output masks it and lays it out. + # OVRTX's camera distance needs its near-plane offset first, and keeps the step-by-step path. + textures = {name: tex.torch if hasattr(tex, "torch") else tex for name, tex in self._texture_output.items()} + offset_distance = self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in textures + if self._native_grid and self._pooler is None and not offset_distance: + count = self._num_ray_samples + self._prepare_grid_publish( + {name: tex.reshape(tex.shape[0], count, tex.shape[-1]) for name, tex in textures.items()} + ) def _allocate_foveated_buffers(self): """Allocate ``(B, N_hi, 1, C)`` (and optionally ``(B, N_lo, 1, C)``) @@ -366,7 +379,8 @@ def _allocate_foveated_buffers(self): def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: super().set_gaze_angles(angles_deg) - self._write_gaze_local_pose() + if not self._gaze_pose_reads_angles: + self._write_gaze_local_pose() def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): """Move the camera's mount; the gaze stays relative to the new mount. @@ -374,6 +388,8 @@ def set_world_poses(self, positions=None, orientations=None, env_ids=None, conve Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. """ super().set_world_poses(positions, orientations, env_ids, convention) + if self._gaze_pose_reads_angles: + return # The pose update turned the new mount by the gaze. # The prims of the moved environments now hold the bare mount pose, which is their new base. ids = slice(None) if env_ids is None else torch.as_tensor(env_ids, device=self._device, dtype=torch.long) _, local_orientation = self._view.get_local_poses() @@ -409,6 +425,9 @@ def process_rendered_frame(self) -> None: """Extract, mask and pool the frame written by scalar or batched rendering.""" if not self._env_mask_has_any(self._is_outdated): return + if self._grid_publish: + self._publish_grid() + return # Extract per-sample values from the per-env texture buffer. self._extract_foveated_samples() if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self._foveated_output: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py index f417cfc09380..02896f3b6672 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py @@ -8,8 +8,7 @@ from __future__ import annotations import math -from collections.abc import Sequence -from typing import ClassVar +from collections.abc import Mapping, Sequence import torch import warp as wp @@ -17,9 +16,11 @@ from .calibrated_geometry import convert_camera_frame_quaternion, resolve_camera_model from .gaze_kernels import ( + CameraParams, apply_gaze_indexed_kernel, apply_gaze_kernel, camera_params, + publish_grid_kernel, record_launch, sensor_visibility_kernel, set_gaze_kernel, @@ -36,9 +37,9 @@ class VirtualGaze: to the optical axis of the physical camera it looks through. """ - _gaze_pose_reads_angles: ClassVar[bool] = False - """Whether the camera's per-frame pose update turns the gaze from its stored angles, so that a writer of - :meth:`gaze_angles_buffer` needs no other launch.""" + _gaze_pose_reads_angles: bool = False + """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses when + the gaze is set. A writer of :meth:`gaze_angles_buffer` then needs no other launch.""" def gaze_angles_buffer(self) -> torch.Tensor: """The camera's stored gaze angles [deg], shape (num_envs, 2). @@ -135,6 +136,88 @@ def _apply_gaze_pose( launch.set_dim(len(env_ids)) launch.launch(warp_stream(device)) + def _update_camera_state( + self, + env_ids: wp.array | None = None, + env_mask: wp.array | None = None, + pos_src: wp.array | None = None, + quat_src: wp.array | None = None, + update_pose: bool = False, + frame_op: int = 0, + ): + """Update the camera state; when the pose update turns the gaze, turn freshly read poses before the renderer + sees them.""" + super()._update_camera_state(env_ids, env_mask, pos_src, quat_src, update_pose, frame_op) + if update_pose and self._gaze_pose_reads_angles: + self._apply_gaze_pose(env_ids, env_mask) + + def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: + """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for + :func:`publish_grid_kernel`.""" + views = [] + for name, source in sources.items(): + if name == "rgb" and "rgba" in sources: + continue + target = self._grid_output[name].view(source.shape[0], -1, source.shape[-1]) + views.append((wp.from_torch(source.view(torch.uint8)), wp.from_torch(target.view(torch.uint8)))) + self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous()) + self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous()) + num_envs = views[0][1].shape[0] + if self.cfg.mask_to_sensor_fov: + identity = self._gaze_identity.expand(num_envs, -1, -1).contiguous() + self._sensor_fov_valid_buffer = torch.zeros( + num_envs, len(self._gaze_rays), dtype=torch.bool, device=self._device + ) + self._grid_sensor = ( + wp.from_torch(self._gaze_rays, dtype=wp.vec3f), + wp.from_torch(identity, dtype=wp.mat33f), + self._gaze_camera, + wp.from_torch(self._sensor_fov_valid_buffer), + ) + else: + # Placeholders: the kernel reads none of these without the sensor mask. + self._grid_sensor = ( + wp.zeros(1, dtype=wp.vec3f, device=self._device), + wp.zeros(1, dtype=wp.mat33f, device=self._device), + CameraParams(), + wp.zeros((1, 1), dtype=wp.bool, device=self._device), + ) + self._grid_publish = views + self._grid_launches = None + + def _publish_grid(self) -> None: + """Mask and lay out every output in one launch each; the result equals masking, then copying to the grid.""" + mask = self.cfg.mask_to_sensor_fov + rays, identity, camera, visible = self._grid_sensor + rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation_wp + if self._grid_launches is None or self._grid_launches[0] is not rotation: + launches = [ + record_launch( + publish_grid_kernel, + (target.shape[0], target.shape[1]), + [ + source, + self._grid_indices_wp, + self._grid_footprint_wp, + rays, + rotation, + camera, + int(mask), + int(mask and index == 0), + visible, + ], + [target], + self._device, + ) + for index, (source, target) in enumerate(self._grid_publish) + ] + self._grid_launches = (rotation, launches) + stream = warp_stream(self._device) + for launch in self._grid_launches[1]: + launch.launch(stream) + if mask: + self._sensor_fov_valid = self._sensor_fov_valid_buffer + def _gaze_validity(self, batch_size: int) -> torch.Tensor: """Return which samples the physical camera sees at the current gaze, shape (batch_size, num_samples).""" if self._gaze_rotation is None: diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py new file mode 100644 index 000000000000..ad2c0ca29e57 --- /dev/null +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -0,0 +1,233 @@ +# 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 + +"""Render cases for the foveated camera, shared by the render tests of each renderer. + +A camera looks down at the ground plane and renders distance. The ground distance along any camera +ray is known in closed form, so the images check the sampling geometry without reference images. + +Each case takes a backend: the physics configuration, the renderer configuration class, and the camera class the +renderer selects. Import this module after the test has launched its simulation app, if it needs one. +""" + +import math + +import numpy as np +import pytest +import torch +from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg, RigidObjectCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from isaaclab.sim import SimulationCfg, build_simulation_context +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils.configclass import configclass +from isaaclab.utils.math import create_rotation_matrix_from_view, quat_from_matrix + +DEVICE = "cuda:0" +WARMUP_STEPS = 4 +RESOLUTION = 32 + +# The physical camera the retina looks through: a 640x480 pinhole. +WIDTH, HEIGHT = 640, 480 +FOCAL, CX, CY = 550.0, 319.5, 239.5 +CLIPPING_RANGE = (0.001, 20.0) +CAMERA_MODEL = {"model": "pinhole", "image_size": (HEIGHT, WIDTH), "intrinsics": (FOCAL, FOCAL, CX, CY)} + +# The same camera given in either supported way: as fovi camera-model fields, or as the spawned +# camera's OpenCV model, from which the foveated camera derives them. +CAMERA_SOURCES = { + "camera_model": dict(camera_model=CAMERA_MODEL), + "spawn": dict( + camera_model=None, + spawn=sim_utils.PinholeCameraCfg( + clipping_range=CLIPPING_RANGE, + distortion=sim_utils.OpenCvPinholeDistortionCfg( + fx=FOCAL, fy=FOCAL, cx=CX, cy=CY, image_size=(WIDTH, HEIGHT) + ), + ), + ), +} + +# The camera looks down at the ground plane; its optical axis meets the ground at the target. +CAM_EYE = (0.0, 0.0, 2.5) +CAM_TARGET = (1.75, 0.0, 0.0) + + +@configclass +class _GroundSceneCfg(InteractiveSceneCfg): + """A ground plane, a foveated camera, and an off-screen body; Newton cannot build an empty model.""" + + ground = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + dome_light = AssetBaseCfg( + prim_path="/World/DomeLight", + spawn=sim_utils.DomeLightCfg(intensity=2000.0, color=(0.9, 0.9, 0.9)), + ) + anchor = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Anchor", + spawn=sim_utils.CuboidCfg( + size=(0.01, 0.01, 0.01), + rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), + mass_props=sim_utils.MassCfg(mass=0.001), + collision_props=sim_utils.UsdPhysicsCollisionCfg(), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, -100.0)), + ) + camera = FoveatedCameraCfg( + prim_path="{ENV_REGEX_NS}/Camera", + update_period=0.0, + data_types=["distance_to_camera"], + spawn=sim_utils.PinholeCameraCfg(clipping_range=CLIPPING_RANGE), + camera_model=CAMERA_MODEL, + foveated_res=RESOLUTION, + mask_to_sensor_fov=True, + ) + + +def _look_at(eye, target) -> tuple[float, float, float, float]: + """OpenGL camera orientation (x, y, z, w) at ``eye`` looking at ``target`` with world +Z up.""" + matrix = create_rotation_matrix_from_view(torch.tensor([eye]), torch.tensor([target]), up_axis="Z") + return tuple(quat_from_matrix(matrix)[0].tolist()) + + +def _ground_distance_along_gaze(tilt_deg: float, pan_deg: float, eye=CAM_EYE, target=CAM_TARGET) -> float: + """Distance [m] from the camera to the ground along the gaze (tilt, pan) [deg]; up and left are positive.""" + tilt, pan = math.radians(tilt_deg), math.radians(pan_deg) + # OpenGL camera frame: +X right, +Y up, looking along -Z. + ray_camera = np.array((-math.cos(tilt) * math.sin(pan), math.sin(tilt), -math.cos(tilt) * math.cos(pan))) + eye = np.asarray(eye) + forward = np.asarray(target) - eye + z_axis = -forward / np.linalg.norm(forward) + x_axis = np.cross(np.array((0.0, 0.0, 1.0)), z_axis) + x_axis /= np.linalg.norm(x_axis) + y_axis = np.cross(z_axis, x_axis) + ray_world = np.column_stack((x_axis, y_axis, z_axis)) @ ray_camera + return float(-eye[2] / ray_world[2]) + + +def _render( + backend: tuple, + gaze: torch.Tensor, + moved_mount: tuple | None = None, + later_gaze: torch.Tensor | None = None, + **camera_overrides, +) -> tuple[torch.Tensor, torch.Tensor]: + """Render ground distance for one environment per row of gaze angles (tilt, pan) [deg]. + + With ``moved_mount`` (eye, target), the last environment's camera is moved there after its gaze is set. + With ``later_gaze``, the gaze changes to it after the first frames, and the camera renders again. + + Returns: + The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid + cell, shape (H, W, 2). + """ + physics_cfg, renderer_cfg, camera_class = backend + sim_cfg = SimulationCfg(physics=physics_cfg, device=DEVICE) + with build_simulation_context(device=DEVICE, sim_cfg=sim_cfg) as sim: + sim._app_control_on_stop_handle = None + scene_cfg = _GroundSceneCfg(num_envs=len(gaze), env_spacing=20.0) + scene_cfg.camera.renderer_cfg = renderer_cfg() + rot = _look_at(CAM_EYE, CAM_TARGET) + scene_cfg.camera.offset = FoveatedCameraCfg.OffsetCfg(pos=CAM_EYE, rot=rot, convention="opengl") + for name, value in camera_overrides.items(): + setattr(scene_cfg.camera, name, value) + scene = InteractiveScene(scene_cfg) + camera: FoveatedCamera = scene["camera"] + assert isinstance(camera, camera_class) + sim.reset() + camera.set_gaze_angles(gaze.to(sim.device)) + if moved_mount is not None: + last = len(gaze) - 1 + eye, target = moved_mount + position = scene.env_origins[last : last + 1] + torch.tensor([eye], device=sim.device) + orientation = torch.tensor([_look_at(eye, target)], device=sim.device) + camera.set_world_poses(position, orientation, env_ids=[last], convention="opengl") + for _ in range(WARMUP_STEPS): + sim.step() + camera.update(sim.get_physics_dt(), force_recompute=True) + if later_gaze is not None: + camera.set_gaze_angles(later_gaze.to(sim.device)) + for _ in range(WARMUP_STEPS): + sim.step() + camera.update(sim.get_physics_dt(), force_recompute=True) + distance = camera.data.output["distance_to_camera"].torch[..., 0].detach().cpu().float().clone() + coords = camera.sampling_coords + field = coords.as_grid(coords.cartesian, sample_dim=0).detach().cpu().float().clone() + return distance, field + + +def foveated_camera_follows_gaze(backend: tuple, source: str): + """The retina's centre sees the ground along the gaze direction. + + One environment looks along the optical axis and one 16 degrees to the right. The reference is + the analytic ground distance along each gaze direction. + """ + gaze = torch.tensor([[0.0, 0.0], [0.0, -16.0]]) + distance, field = _render(backend, gaze, **CAMERA_SOURCES[source]) + + assert distance.shape == (2, RESOLUTION, RESOLUTION) + assert torch.isfinite(distance).all() + + # The grid cell closest to the centre of the visual field. + row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) + for env, (tilt, pan) in enumerate(gaze.tolist()): + assert float(distance[env, row, column]) == pytest.approx(_ground_distance_along_gaze(tilt, pan), rel=0.01) + + # The image is upright: the top looks farther along the ground than the bottom. + centred = distance[0] + seen = centred > 0 + top = centred[: RESOLUTION // 2][seen[: RESOLUTION // 2]].mean() + bottom = centred[RESOLUTION // 2 :][seen[RESOLUTION // 2 :]].mean() + assert top > bottom + 0.25 + # The camera has no roll, so the left and right halves see the same distances. + left = centred[:, : RESOLUTION // 2][seen[:, : RESOLUTION // 2]].mean() + right = centred[:, RESOLUTION // 2 :][seen[:, RESOLUTION // 2 :]].mean() + assert float(left) == pytest.approx(float(right), rel=0.01) + + # Looking right moves part of the retina past the edge of the physical camera, and those samples are zeroed. + assert (distance[1] == 0).sum() > (distance[0] == 0).sum() + + +def gaze_change_reaches_the_next_frame(backend: tuple): + """A gaze set after the camera has rendered moves the retina, as a gaze action does every step.""" + later = torch.tensor([[0.0, -16.0], [8.0, 10.0]]) + distance, field = _render(backend, torch.zeros(2, 2), later_gaze=later) + + row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) + for env, (tilt, pan) in enumerate(later.tolist()): + assert float(distance[env, row, column]) == pytest.approx(_ground_distance_along_gaze(tilt, pan), rel=0.01) + + +def gaze_stays_relative_to_a_moved_mount(backend: tuple): + """Moving one environment's camera keeps its gaze relative to the new mount and leaves the other alone.""" + gaze = torch.tensor([[0.0, -10.0], [0.0, -10.0]]) + eye, target = (0.3, -0.4, 3.2), (2.0, 0.3, 0.0) + distance, field = _render(backend, gaze, moved_mount=(eye, target)) + + row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) + assert float(distance[0, row, column]) == pytest.approx(_ground_distance_along_gaze(0.0, -10.0), rel=0.01) + assert float(distance[1, row, column]) == pytest.approx( + _ground_distance_along_gaze(0.0, -10.0, eye, target), rel=0.01 + ) + + +def foveated_camera_samples_densest_at_the_fixation(backend: tuple): + """Neighbouring samples are closer together at the fixation, and nearly even without foveation.""" + + def central_to_edge_spacing(field: torch.Tensor) -> float: + steps = field[RESOLUTION // 2, :, 0].diff() + return float(steps[len(steps) // 2] / steps[-1]) + + gaze = torch.zeros(1, 2) + foveated_distance, foveated_field = _render(backend, gaze) + uniform_distance, uniform_field = _render(backend, gaze, cmf_a_deg=1000.0) + + assert central_to_edge_spacing(foveated_field) < 0.2 + assert central_to_edge_spacing(uniform_field) > 0.9 + # Both cover the same field of view, so they see the same range of ground distances. + for distance in (foveated_distance, uniform_distance): + assert torch.isfinite(distance).all() + assert float(foveated_distance.max()) == pytest.approx(float(uniform_distance.max()), rel=0.05) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index 0711eeee6a59..eca9350bf0ac 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -5,32 +5,20 @@ """Render tests for the foveated camera on the Newton Warp and Isaac RTX renderers. -A camera looks down at the ground plane and renders distance. The ground distance along any camera -ray is known in closed form, so the images check the sampling geometry without reference images. +The cases live in :mod:`foveated_render_cases`; OVRTX runs them without Kit in ``test_foveated_camera_render_ovrtx``. """ from isaaclab.test.utils import launch_test_simulation launch_test_simulation(enable_cameras=True) -import math - -import numpy as np -import pytest -import torch -from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg, FoveatedNewtonCamera, FoveatedRTXCamera -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg -from isaaclab_newton.renderers import NewtonWarpRendererCfg -from isaaclab_physx.physics import PhysxCfg -from isaaclab_physx.renderers import IsaacRtxRendererCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import AssetBaseCfg, RigidObjectCfg -from isaaclab.scene import InteractiveScene, InteractiveSceneCfg -from isaaclab.sim import SimulationCfg, build_simulation_context -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.configclass import configclass -from isaaclab.utils.math import create_rotation_matrix_from_view, quat_from_matrix +import foveated_render_cases as cases # noqa: E402 +import pytest # noqa: E402 +from isaaclab_fovi.sensors import FoveatedNewtonCamera, FoveatedRTXCamera # noqa: E402 +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg # noqa: E402 +from isaaclab_newton.renderers import NewtonWarpRendererCfg # noqa: E402 +from isaaclab_physx.physics import PhysxCfg # noqa: E402 +from isaaclab_physx.renderers import IsaacRtxRendererCfg # noqa: E402 pytestmark = [pytest.mark.integration, pytest.mark.rendering, pytest.mark.isaacsim_ci] @@ -40,212 +28,23 @@ "isaac_rtx": (PhysxCfg(), IsaacRtxRendererCfg, FoveatedRTXCamera), } -DEVICE = "cuda:0" -WARMUP_STEPS = 4 -RESOLUTION = 32 - -# The physical camera the retina looks through: a 640x480 pinhole. -WIDTH, HEIGHT = 640, 480 -FOCAL, CX, CY = 550.0, 319.5, 239.5 -CLIPPING_RANGE = (0.001, 20.0) -CAMERA_MODEL = {"model": "pinhole", "image_size": (HEIGHT, WIDTH), "intrinsics": (FOCAL, FOCAL, CX, CY)} - -# The same camera given in either supported way: as fovi camera-model fields, or as the spawned -# camera's OpenCV model, from which the foveated camera derives them. -CAMERA_SOURCES = { - "camera_model": dict(camera_model=CAMERA_MODEL), - "spawn": dict( - camera_model=None, - spawn=sim_utils.PinholeCameraCfg( - clipping_range=CLIPPING_RANGE, - distortion=sim_utils.OpenCvPinholeDistortionCfg( - fx=FOCAL, fy=FOCAL, cx=CX, cy=CY, image_size=(WIDTH, HEIGHT) - ), - ), - ), -} - -# The camera looks down at the ground plane; its optical axis meets the ground at the target. -CAM_EYE = (0.0, 0.0, 2.5) -CAM_TARGET = (1.75, 0.0, 0.0) - - -@configclass -class _GroundSceneCfg(InteractiveSceneCfg): - """A ground plane, a foveated camera, and an off-screen body; Newton cannot build an empty model.""" - - ground = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") - dome_light = AssetBaseCfg( - prim_path="/World/DomeLight", - spawn=sim_utils.DomeLightCfg(intensity=2000.0, color=(0.9, 0.9, 0.9)), - ) - anchor = RigidObjectCfg( - prim_path="{ENV_REGEX_NS}/Anchor", - spawn=sim_utils.CuboidCfg( - size=(0.01, 0.01, 0.01), - rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), - mass_props=sim_utils.MassCfg(mass=0.001), - collision_props=sim_utils.UsdPhysicsCollisionCfg(), - ), - init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, -100.0)), - ) - camera = FoveatedCameraCfg( - prim_path="{ENV_REGEX_NS}/Camera", - update_period=0.0, - data_types=["distance_to_camera"], - spawn=sim_utils.PinholeCameraCfg(clipping_range=CLIPPING_RANGE), - camera_model=CAMERA_MODEL, - foveated_res=RESOLUTION, - mask_to_sensor_fov=True, - ) - - -def _look_at(eye, target) -> tuple[float, float, float, float]: - """OpenGL camera orientation (x, y, z, w) at ``eye`` looking at ``target`` with world +Z up.""" - matrix = create_rotation_matrix_from_view(torch.tensor([eye]), torch.tensor([target]), up_axis="Z") - return tuple(quat_from_matrix(matrix)[0].tolist()) - - -def _ground_distance_along_gaze(tilt_deg: float, pan_deg: float, eye=CAM_EYE, target=CAM_TARGET) -> float: - """Distance [m] from the camera to the ground along the gaze (tilt, pan) [deg]; up and left are positive.""" - tilt, pan = math.radians(tilt_deg), math.radians(pan_deg) - # OpenGL camera frame: +X right, +Y up, looking along -Z. - ray_camera = np.array((-math.cos(tilt) * math.sin(pan), math.sin(tilt), -math.cos(tilt) * math.cos(pan))) - eye = np.asarray(eye) - forward = np.asarray(target) - eye - z_axis = -forward / np.linalg.norm(forward) - x_axis = np.cross(np.array((0.0, 0.0, 1.0)), z_axis) - x_axis /= np.linalg.norm(x_axis) - y_axis = np.cross(z_axis, x_axis) - ray_world = np.column_stack((x_axis, y_axis, z_axis)) @ ray_camera - return float(-eye[2] / ray_world[2]) - -def _render( - backend: str, - gaze: torch.Tensor, - moved_mount: tuple | None = None, - later_gaze: torch.Tensor | None = None, - **camera_overrides, -) -> tuple[torch.Tensor, torch.Tensor]: - """Render ground distance for one environment per row of gaze angles (tilt, pan) [deg]. - - With ``moved_mount`` (eye, target), the last environment's camera is moved there after its gaze is set. - With ``later_gaze``, the gaze changes to it after the first frames, and the camera renders again. - - Returns: - The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid - cell, shape (H, W, 2). - """ - physics_cfg, renderer_cfg, camera_class = BACKENDS[backend] - sim_cfg = SimulationCfg(physics=physics_cfg, device=DEVICE) - with build_simulation_context(device=DEVICE, sim_cfg=sim_cfg) as sim: - sim._app_control_on_stop_handle = None - scene_cfg = _GroundSceneCfg(num_envs=len(gaze), env_spacing=20.0) - scene_cfg.camera.renderer_cfg = renderer_cfg() - rot = _look_at(CAM_EYE, CAM_TARGET) - scene_cfg.camera.offset = FoveatedCameraCfg.OffsetCfg(pos=CAM_EYE, rot=rot, convention="opengl") - for name, value in camera_overrides.items(): - setattr(scene_cfg.camera, name, value) - scene = InteractiveScene(scene_cfg) - camera: FoveatedCamera = scene["camera"] - assert isinstance(camera, camera_class) - sim.reset() - camera.set_gaze_angles(gaze.to(sim.device)) - if moved_mount is not None: - last = len(gaze) - 1 - eye, target = moved_mount - position = scene.env_origins[last : last + 1] + torch.tensor([eye], device=sim.device) - orientation = torch.tensor([_look_at(eye, target)], device=sim.device) - camera.set_world_poses(position, orientation, env_ids=[last], convention="opengl") - for _ in range(WARMUP_STEPS): - sim.step() - camera.update(sim.get_physics_dt(), force_recompute=True) - if later_gaze is not None: - camera.set_gaze_angles(later_gaze.to(sim.device)) - for _ in range(WARMUP_STEPS): - sim.step() - camera.update(sim.get_physics_dt(), force_recompute=True) - distance = camera.data.output["distance_to_camera"].torch[..., 0].detach().cpu().float().clone() - coords = camera.sampling_coords - field = coords.as_grid(coords.cartesian, sample_dim=0).detach().cpu().float().clone() - return distance, field - - -@pytest.mark.parametrize("source", CAMERA_SOURCES) +@pytest.mark.parametrize("source", cases.CAMERA_SOURCES) @pytest.mark.parametrize("backend", BACKENDS) def test_foveated_camera_follows_gaze(backend, source): - """The retina's centre sees the ground along the gaze direction. - - One environment looks along the optical axis and one 16 degrees to the right. The reference is - the analytic ground distance along each gaze direction. - """ - gaze = torch.tensor([[0.0, 0.0], [0.0, -16.0]]) - distance, field = _render(backend, gaze, **CAMERA_SOURCES[source]) - - assert distance.shape == (2, RESOLUTION, RESOLUTION) - assert torch.isfinite(distance).all() - - # The grid cell closest to the centre of the visual field. - row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) - for env, (tilt, pan) in enumerate(gaze.tolist()): - assert float(distance[env, row, column]) == pytest.approx(_ground_distance_along_gaze(tilt, pan), rel=0.01) - - # The image is upright: the top looks farther along the ground than the bottom. - centred = distance[0] - seen = centred > 0 - top = centred[: RESOLUTION // 2][seen[: RESOLUTION // 2]].mean() - bottom = centred[RESOLUTION // 2 :][seen[RESOLUTION // 2 :]].mean() - assert top > bottom + 0.25 - # The camera has no roll, so the left and right halves see the same distances. - left = centred[:, : RESOLUTION // 2][seen[:, : RESOLUTION // 2]].mean() - right = centred[:, RESOLUTION // 2 :][seen[:, RESOLUTION // 2 :]].mean() - assert float(left) == pytest.approx(float(right), rel=0.01) - - # Looking right moves part of the retina past the edge of the physical camera, and those samples are zeroed. - assert (distance[1] == 0).sum() > (distance[0] == 0).sum() + cases.foveated_camera_follows_gaze(BACKENDS[backend], source) @pytest.mark.parametrize("backend", BACKENDS) def test_gaze_change_reaches_the_next_frame(backend): - """A gaze set after the camera has rendered moves the retina, as a gaze action does every step.""" - later = torch.tensor([[0.0, -16.0], [8.0, 10.0]]) - distance, field = _render(backend, torch.zeros(2, 2), later_gaze=later) - - row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) - for env, (tilt, pan) in enumerate(later.tolist()): - assert float(distance[env, row, column]) == pytest.approx(_ground_distance_along_gaze(tilt, pan), rel=0.01) + cases.gaze_change_reaches_the_next_frame(BACKENDS[backend]) @pytest.mark.parametrize("backend", BACKENDS) def test_gaze_stays_relative_to_a_moved_mount(backend): - """Moving one environment's camera keeps its gaze relative to the new mount and leaves the other alone.""" - gaze = torch.tensor([[0.0, -10.0], [0.0, -10.0]]) - eye, target = (0.3, -0.4, 3.2), (2.0, 0.3, 0.0) - distance, field = _render(backend, gaze, moved_mount=(eye, target)) - - row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) - assert float(distance[0, row, column]) == pytest.approx(_ground_distance_along_gaze(0.0, -10.0), rel=0.01) - assert float(distance[1, row, column]) == pytest.approx( - _ground_distance_along_gaze(0.0, -10.0, eye, target), rel=0.01 - ) + cases.gaze_stays_relative_to_a_moved_mount(BACKENDS[backend]) @pytest.mark.parametrize("backend", BACKENDS) def test_foveated_camera_samples_densest_at_the_fixation(backend): - """Neighbouring samples are closer together at the fixation, and nearly even without foveation.""" - - def central_to_edge_spacing(field: torch.Tensor) -> float: - steps = field[RESOLUTION // 2, :, 0].diff() - return float(steps[len(steps) // 2] / steps[-1]) - - gaze = torch.zeros(1, 2) - foveated_distance, foveated_field = _render(backend, gaze) - uniform_distance, uniform_field = _render(backend, gaze, cmf_a_deg=1000.0) - - assert central_to_edge_spacing(foveated_field) < 0.2 - assert central_to_edge_spacing(uniform_field) > 0.9 - # Both cover the same field of view, so they see the same range of ground distances. - for distance in (foveated_distance, uniform_distance): - assert torch.isfinite(distance).all() - assert float(foveated_distance.max()) == pytest.approx(float(uniform_distance.max()), rel=0.05) + cases.foveated_camera_samples_densest_at_the_fixation(BACKENDS[backend]) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py new file mode 100644 index 000000000000..70995210b08f --- /dev/null +++ b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py @@ -0,0 +1,50 @@ +# 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 + +"""Render tests for the foveated camera on the OVRTX renderer, with Newton physics. + +Runs without Kit: ``ovrtx`` and Isaac Sim Kit ship conflicting RTX libraries that cannot load in one process. The +cases live in :mod:`foveated_render_cases`. +""" + +import importlib.util + +import pytest + +pytestmark = [pytest.mark.integration, pytest.mark.rendering, pytest.mark.ov] + +_REQUIRED_MODULES = ("isaaclab_ov", "ovrtx", "isaaclab_newton") +_MISSING_MODULES = [module for module in _REQUIRED_MODULES if importlib.util.find_spec(module) is None] +pytestmark.append( + pytest.mark.skipif(bool(_MISSING_MODULES), reason=f"requires optional modules: {', '.join(_MISSING_MODULES)}") +) + +if not _MISSING_MODULES: + import foveated_render_cases as cases + from isaaclab_fovi.sensors import FoveatedRTXCamera + from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + from isaaclab_ov.renderers import OVRTXRendererCfg + + BACKEND = (NewtonCfg(solver_cfg=MJWarpSolverCfg()), OVRTXRendererCfg, FoveatedRTXCamera) + SOURCES = list(cases.CAMERA_SOURCES) +else: + SOURCES = [] + + +@pytest.mark.parametrize("source", SOURCES) +def test_foveated_camera_follows_gaze(source): + cases.foveated_camera_follows_gaze(BACKEND, source) + + +def test_gaze_change_reaches_the_next_frame(): + cases.gaze_change_reaches_the_next_frame(BACKEND) + + +def test_gaze_stays_relative_to_a_moved_mount(): + cases.gaze_stays_relative_to_a_moved_mount(BACKEND) + + +def test_foveated_camera_samples_densest_at_the_fixation(): + cases.foveated_camera_samples_densest_at_the_fixation(BACKEND) From 750f16d23bd8215bfb5f4b8500b3b6e901afb6db Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 22:22:33 -0800 Subject: [PATCH 27/81] Address review findings on the foveated camera and active gaze Fix the sensor mask for rolled mounts (it now checks the rendered rays through the mount roll), publish only the environments a frame updated, keep the Isaac RTX mount when set_world_poses moves only the position or set_world_poses_from_view turns it, read OVRTX's near clip from the camera prim without a spawn configuration, reject async OVRTX with the sensor mask, release the lens-texture directory, report the published image shape, and let oracle_loss_coef=0 train plain PPO without teacher labels. Add a tracked gaze mount: the pose kernel records each camera's mount, and the teacher follows it, for software gaze on a moving head; a fixed mount stays the default and raises if the mount moves. Pooled segmentation takes each sample's modal label in its native dtype. Merge the virtual gaze into FoveatedCamera with the shared accessors and sensor mask, build Newton's ray array in the Newton camera, validate tiles before allocating, keep gaze and velocity as views of one state buffer, drop the unused single-point teacher, use stub-backed lazy exports, and tighten docs and tests (first frame after a gaze change, independent grid and lens-inverse oracles, trimmed parameter products, kitless markers). --- .../changelog.d/isaaclab-fovi.added.rst | 11 +- source/isaaclab_fovi/docs/README.md | 18 +- source/isaaclab_fovi/docs/square_foveated.md | 5 +- .../isaaclab_fovi/examples/compare_outputs.py | 15 +- .../isaaclab_fovi/examples/render_foveated.py | 7 +- .../isaaclab_fovi/mdp/__init__.py | 28 +- .../isaaclab_fovi/mdp/__init__.pyi | 32 ++ .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 157 +++---- .../isaaclab_fovi/rsl_rl/__init__.py | 4 +- .../isaaclab_fovi/rsl_rl/__init__.pyi | 8 + .../rsl_rl/gaze_supervised_ppo.py | 20 +- .../isaaclab_fovi/sensors/__init__.py | 21 +- .../isaaclab_fovi/sensors/__init__.pyi | 16 + .../isaaclab_fovi/sensors/foveated_camera.py | 379 +++++++++++++++- .../sensors/foveated_camera_cfg.py | 34 +- .../sensors/foveated_newton_camera.py | 300 ++++--------- .../isaaclab_fovi/sensors/foveated_rays.py | 48 --- .../sensors/foveated_rtx_camera.py | 406 +++++++----------- .../isaaclab_fovi/sensors/gaze_kernels.py | 51 ++- .../isaaclab_fovi/sensors/pooling.py | 181 +++++++- .../isaaclab_fovi/sensors/virtual_gaze.py | 269 ------------ .../isaaclab_fovi/tasks/active_gaze.py | 2 +- source/isaaclab_fovi/test/_check_imports.py | 1 - .../test/foveated_render_cases.py | 8 +- source/isaaclab_fovi/test/test_active_gaze.py | 145 +++---- .../test/test_backend_dispatch.py | 16 +- source/isaaclab_fovi/test/test_camera_cfg.py | 2 + .../isaaclab_fovi/test/test_gaze_kernels.py | 67 +-- source/isaaclab_fovi/test/test_lens_schema.py | 2 + source/isaaclab_fovi/test/test_native_grid.py | 83 +++- .../isaaclab_fovi/test/test_newton_buffers.py | 22 +- source/isaaclab_fovi/test/test_pooling.py | 120 +++++- source/isaaclab_fovi/test/test_rays.py | 22 +- .../test/test_spherical_geometry.py | 56 ++- .../test/test_square_native_grid.py | 16 +- 35 files changed, 1380 insertions(+), 1192 deletions(-) create mode 100644 source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi create mode 100644 source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst index 9f78714e11f3..6cc57f1d1e3f 100644 --- a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst +++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst @@ -1,6 +1,7 @@ * Introduced ``isaaclab_fovi`` and the ``fovi`` installation extra, providing a - foveated camera sensor for the Newton and RTX renderers. -* Added active-gaze manager terms in :mod:`isaaclab_fovi.mdp`, gaze-supervised PPO - for RSL-RL in :mod:`isaaclab_fovi.rsl_rl`, and the ``Isaac-Cartpole-Camera-Fovi``, - ``Isaac-Lift-KukaAllegro-Camera-Fovi`` and ``Isaac-Reorient-KukaAllegro-Camera-Fovi`` - tasks. + foveated camera sensor for the Newton, Isaac RTX and OVRTX renderers. +* Added active-gaze manager terms in :mod:`isaaclab_fovi.mdp`, with a fixed or tracked camera + mount, gaze-supervised PPO for RSL-RL in :mod:`isaaclab_fovi.rsl_rl`, and the + ``Isaac-Cartpole-Camera-Fovi``, ``Isaac-Lift-KukaAllegro-Camera-Fovi`` and + ``Isaac-Reorient-KukaAllegro-Camera-Fovi`` tasks. +* Pooled segmentation outputs take each sample's modal label in its native dtype. diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index 56b07783de5c..8a9514d18c0a 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -89,7 +89,7 @@ env.scene.eye.cmf_a_deg=1000 ### Gaze -The retina can turn while the camera prim stays in place: +The retina turns relative to the physical camera's optical axis: ```python # (tilt, pan) [deg] from the physical camera's optical axis, shape (num_envs, 2). @@ -97,6 +97,11 @@ The retina can turn while the camera prim stays in place: camera.set_gaze_angles(angles) ``` +Newton and OVRTX turn the rendered camera pose in each pose update, so the +camera prim keeps its mount pose. Isaac RTX renders from the prims, so it +writes the turned pose into them. On every renderer the gaze stays relative to +the mount when `set_world_poses` moves it. + Set `mask_to_sensor_fov=True` to zero the samples that fall outside the physical camera's image at the current gaze. @@ -106,8 +111,13 @@ physical camera's image at the current gaze. - `GazeActionCfg`: two actions that move the gaze by up to `step_size` field radii (half the retina's field of view) per step, within `gaze_limit` field - radii of the optical axis. Make it the last action term. -- `gaze_state`: the gaze and its velocity, in field radii. + radii of the optical axis. Make it the last action term. With the default + `mount="fixed"` the camera hangs on the environment and the teacher aims from + its configured mount; `mount="tracked"` lets the camera ride a moving body, + such as a turning head, and the teacher follows each camera's current mount + (Newton or OVRTX). +- `gaze_state`: the gaze, in field radii, and its velocity, in field radii per + second. - `gaze_teacher_labels`: a teacher's gaze action toward a point fixed to an asset, and whether that point is a valid target. `teacher_labels` takes any world points, for a task whose target changes during an episode. @@ -131,7 +141,7 @@ the PPO settings are the stock ones. The Kuka-Allegro tasks take the stock base-camera presets, such as `presets=depth128`. Set the retina's resolution with, for example, -`env.scene.tiled_camera.foveated_res=96`. +`env.scene.base_camera.foveated_res=96`. ```bash uv run isaaclab train --rl_library rsl_rl --task Isaac-Cartpole-Camera-Fovi diff --git a/source/isaaclab_fovi/docs/square_foveated.md b/source/isaaclab_fovi/docs/square_foveated.md index 41921e5f66d7..e2f1db96d12e 100644 --- a/source/isaaclab_fovi/docs/square_foveated.md +++ b/source/isaaclab_fovi/docs/square_foveated.md @@ -22,8 +22,9 @@ segmentation keep their usual dtypes. No cell is masked by the sensor footprint. With `mask_to_sensor_fov=True`, samples outside the physical camera's image are still zeroed. -The mode works in both field geometries. The grid keeps its two-dimensional -topology; "square" refers to the region of the visual field the grid covers. +The camera samples spherical field coordinates only; the lens lookup rejects +planar coordinates. The grid keeps its two-dimensional topology; "square" +refers to the region of the visual field the grid covers. The mapping is not smooth across the diagonals of the square, which matters when a temporal filter such as DLSS is applied to the rendered grid. diff --git a/source/isaaclab_fovi/examples/compare_outputs.py b/source/isaaclab_fovi/examples/compare_outputs.py index 015b6956fe51..6b2146471d0c 100644 --- a/source/isaaclab_fovi/examples/compare_outputs.py +++ b/source/isaaclab_fovi/examples/compare_outputs.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Compare RGB snapshots saved by render_foveated.py across installations.""" +"""Compare RGB frames saved by render_foveated.py across installations.""" import argparse import statistics @@ -12,19 +12,20 @@ def main() -> None: - """Report image differences and observed frame times without setting thresholds.""" + """Report frame differences and observed frame times without setting thresholds.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("reference") parser.add_argument("candidate") args = parser.parse_args() reference = torch.load(args.reference, map_location="cpu", weights_only=True) candidate = torch.load(args.candidate, map_location="cpu", weights_only=True) - if reference["rgb"].shape != candidate["rgb"].shape: - raise ValueError("RGB shapes differ") - if reference["rgb"].dtype != candidate["rgb"].dtype: - raise ValueError("RGB dtypes differ") + reference_frames, candidate_frames = reference["frames"], candidate["frames"] + if reference_frames.shape != candidate_frames.shape: + raise ValueError(f"Frame shapes differ: {tuple(reference_frames.shape)} vs {tuple(candidate_frames.shape)}") + if reference_frames.dtype != candidate_frames.dtype: + raise ValueError(f"Frame dtypes differ: {reference_frames.dtype} vs {candidate_frames.dtype}") torch.testing.assert_close(reference["sampling_coordinates"], candidate["sampling_coordinates"]) - difference = (reference["rgb"].float() - candidate["rgb"].float()).abs() + difference = (reference_frames.float() - candidate_frames.float()).abs() print(f"RGB absolute error: mean={difference.mean().item()}, max={difference.max().item()}") for label, snapshot in (("reference", reference), ("candidate", candidate)): durations = snapshot["frame_seconds"] diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index c3dab86a3369..2568be81081a 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -132,10 +132,11 @@ class SceneCfg(InteractiveSceneCfg): wp.synchronize_device(sim.device) if step > 0: frame_seconds.append(time.perf_counter() - start) - frames.append(camera.data.output["rgb"].torch.clone()) + rgb = camera.data.output["rgb"].torch + if args.output is not None: + frames.append(rgb.clone()) print( - f"{args.backend}: RGB shape={tuple(frames[-1].shape)}, dtype={frames[-1].dtype}, " - f"warm frame seconds={frame_seconds}", + f"{args.backend}: RGB shape={tuple(rgb.shape)}, dtype={rgb.dtype}, warm frame seconds={frame_seconds}", flush=True, ) if args.output is not None: diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py index 585edad12dae..b2c044ba52d2 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py @@ -5,30 +5,6 @@ """Manager terms for active gaze with a foveated camera.""" -from .gaze import ( - GazeAction, - GazeActionCfg, - angles_to_direction, - clamp_gaze, - direction_to_angles, - entity_point, - gaze_state, - gaze_teacher_labels, - motor_action_l2, - random_gaze, - teacher_labels, -) +from isaaclab.utils.module import lazy_export -__all__ = [ - "GazeAction", - "GazeActionCfg", - "angles_to_direction", - "clamp_gaze", - "direction_to_angles", - "entity_point", - "gaze_state", - "gaze_teacher_labels", - "motor_action_l2", - "random_gaze", - "teacher_labels", -] +lazy_export() diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi new file mode 100644 index 000000000000..7f86412ab9dd --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -0,0 +1,32 @@ +# 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 + +__all__ = [ + "GazeAction", + "GazeActionCfg", + "angles_to_direction", + "clamp_gaze", + "direction_to_angles", + "entity_point", + "gaze_state", + "gaze_teacher_labels", + "motor_action_l2", + "random_gaze", + "teacher_labels", +] + +from .gaze import ( + GazeAction, + GazeActionCfg, + angles_to_direction, + clamp_gaze, + direction_to_angles, + entity_point, + gaze_state, + gaze_teacher_labels, + motor_action_l2, + random_gaze, + teacher_labels, +) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index d456aa9d27d1..efea6551833a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -22,7 +22,7 @@ from isaaclab.managers import ActionTerm, ActionTermCfg, ManagerTermBase, ObservationTermCfg, SceneEntityCfg from isaaclab.utils import configclass -from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_apply, quat_apply_inverse +from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_apply from ..sensors.calibrated_geometry import resolve_camera_model, sampling_geometry from ..sensors.gaze_kernels import ( @@ -32,7 +32,6 @@ project_direction, project_directions, record_launch, - torch_stream, warp_stream, ) @@ -72,28 +71,6 @@ def teach( return wp.vec4f(step[0], step[1], wp.where(ok, 1.0, 0.0), error) -@wp.kernel(enable_backward=False) -def teacher_kernel( - points: wp.array(dtype=wp.vec3f), - positions: wp.array(dtype=wp.vec3f), - mount: wp.quatf, - gaze: wp.array(dtype=wp.vec2f), - field_radius_deg: wp.float32, - step_size: wp.float32, - gaze_limit: wp.float32, - camera: CameraParams, - action: wp.array(dtype=wp.vec2f), - valid: wp.array(dtype=wp.bool), - error_deg: wp.array(dtype=wp.float32), -): - """The teacher's action toward each point, whether the point is a valid target, and the gaze's error to it.""" - i = wp.tid() - result = teach(points[i], positions[i], mount, gaze[i], field_radius_deg, step_size, gaze_limit, camera) - action[i] = wp.vec2f(result[0], result[1]) - valid[i] = result[2] > 0.5 - error_deg[i] = result[3] - - @wp.kernel(enable_backward=False) def teacher_labels_kernel( targets: wp.array(dtype=wp.vec3f), @@ -101,7 +78,8 @@ def teacher_labels_kernel( offset: wp.vec3f, rotate_offset: wp.int32, positions: wp.array(dtype=wp.vec3f), - mount: wp.quatf, + mounts: wp.array(dtype=wp.quatf), + mount_per_env: wp.int32, gaze: wp.array(dtype=wp.vec2f), field_radius_deg: wp.float32, step_size: wp.float32, @@ -113,6 +91,7 @@ def teacher_labels_kernel( """Labels (action x, action y, valid) toward a point fixed to each target; and the mean gaze error to valid targets [deg] with the fraction of valid targets. + ``mounts`` holds each camera's mount (ROS convention), or one mount shared by all when ``mount_per_env`` is 0. One block labels every environment and reduces the logs itself, so the launch needs no zeroed accumulators. """ _block, lane = wp.tid() @@ -124,6 +103,9 @@ def teacher_labels_kernel( point = targets[i] if rotate_offset != 0: point = point + wp.quat_rotate(orientations[i], offset) + mount = mounts[0] + if mount_per_env != 0: + mount = mounts[i] result = teach(point, positions[i], mount, gaze[i], field_radius_deg, step_size, gaze_limit, camera) labels[i, 0] = result[0] labels[i, 1] = result[1] @@ -151,12 +133,13 @@ def gaze_reset_kernel( start: wp.array(dtype=wp.vec2f), use_start: wp.int32, field_radius_deg: wp.float32, - gaze: wp.array(dtype=wp.vec2f), - velocity: wp.array(dtype=wp.vec2f), angles_deg: wp.array(dtype=wp.vec2f), state: wp.array(dtype=wp.vec4f), ): - """Put each reset environment's gaze at its start, or on the optical axis, at rest.""" + """Put each reset environment's gaze at its start, or on the optical axis, at rest. + + ``state`` holds each gaze and its velocity, in field radii and field radii per second. + """ k = wp.tid() i = k if use_ids != 0: @@ -164,8 +147,6 @@ def gaze_reset_kernel( g = wp.vec2f(0.0, 0.0) if use_start != 0: g = start[k] - gaze[i] = g - velocity[i] = wp.vec2f(0.0, 0.0) angles_deg[i] = g * field_radius_deg state[i] = wp.vec4f(g[0], g[1], 0.0, 0.0) @@ -173,24 +154,24 @@ def gaze_reset_kernel( @wp.kernel(enable_backward=False) def gaze_step_kernel( actions: wp.array(dtype=wp.vec2f), - gaze: wp.array(dtype=wp.vec2f), - velocity: wp.array(dtype=wp.vec2f), - angles_deg: wp.array(dtype=wp.vec2f), state: wp.array(dtype=wp.vec4f), + angles_deg: wp.array(dtype=wp.vec2f), step_size: wp.float32, gaze_limit: wp.float32, step_dt: wp.float32, field_radius_deg: wp.float32, ): - """Move each gaze by its clamped action, keep it within the limit, and record its velocity, angles and state.""" + """Move each gaze by its clamped action and keep it within the limit; record the gaze, velocity and angles. + + ``state`` holds each gaze and its velocity, in field radii and field radii per second. + """ i = wp.tid() a = actions[i] - previous = gaze[i] + s = state[i] + previous = wp.vec2f(s[0], s[1]) moved = previous + wp.vec2f(wp.clamp(a[0], -1.0, 1.0), wp.clamp(a[1], -1.0, 1.0)) * step_size current = moved * (gaze_limit / wp.max(wp.length(moved), gaze_limit)) rate = (current - previous) / step_dt - gaze[i] = current - velocity[i] = rate angles_deg[i] = current * field_radius_deg state[i] = wp.vec4f(current[0], current[1], rate[0], rate[1]) @@ -226,7 +207,9 @@ class GazeAction(ActionTerm): ``step_size``, and the gaze stays within ``gaze_limit`` of the optical axis. The gaze starts each episode on the optical axis, or anywhere the physical camera sees within the limit when ``random_reset`` is set. - The camera must be mounted on the environment, so that its offset is its pose in the environment frame. + With ``mount="fixed"`` the camera hangs on the environment at its configured offset, and the teacher uses that + mount; moving the camera's mount raises. With ``mount="tracked"`` the camera may ride a moving body, for example a + robot's head, and the teacher reads each camera's current mount, so software gaze adds to hardware gaze. """ cfg: GazeActionCfg @@ -239,8 +222,20 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): super().__init__(cfg, env) self.camera = self._asset camera_cfg = self.camera.cfg - if camera_cfg.prim_path.rpartition("/")[0] not in ("{ENV_REGEX_NS}", env.scene.env_regex_ns): - raise ValueError(f"Gaze needs a camera mounted on the environment, got {camera_cfg.prim_path!r}.") + if cfg.mount not in ("fixed", "tracked"): + raise ValueError(f"Gaze mount must be 'fixed' or 'tracked', got {cfg.mount!r}.") + self.tracked_mount = cfg.mount == "tracked" + if self.tracked_mount: + if not (self.camera._gaze_pose_reads_angles and camera_cfg.update_latest_camera_pose): + raise ValueError( + "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX," + " with update_latest_camera_pose." + ) + elif camera_cfg.prim_path.rpartition("/")[0] not in ("{ENV_REGEX_NS}", env.scene.env_regex_ns): + raise ValueError( + f"A fixed gaze mount needs a camera mounted on the environment, got {camera_cfg.prim_path!r};" + " use mount='tracked' for a camera on a moving body." + ) self.camera_model = resolve_camera_model(camera_cfg) self._camera = camera_params(self.camera_model) self.field_radius_deg = sampling_geometry(camera_cfg)[0] / 2 @@ -250,17 +245,18 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): self.mount_rotation = convert_camera_frame_orientation_convention( rotation, origin=offset.convention, target="ros" )[0] - """Orientation (x, y, z, w) of the physical camera in the environment frame, ROS convention.""" - self._mount = wp.quatf(*self.mount_rotation.tolist()) + """Configured orientation (x, y, z, w) of the physical camera in the environment frame, ROS convention.""" + self._fixed_mount = wp.from_torch(self.mount_rotation[None].contiguous(), dtype=wp.quatf) + self._tracked_mounts: tuple[torch.Tensor, wp.array] | None = None self._raw = torch.zeros(self.num_envs, 2, device=self.device) """Gaze actions of the last step; once bound, a view of the action manager's buffer.""" - self._gaze = torch.zeros_like(self._raw) - self._velocity = torch.zeros_like(self._raw) self._angles = None """Gaze angles [deg] of the last step; the camera's own buffer, bound on first use.""" self._state = torch.zeros(self.num_envs, 4, device=self.device) - """Gaze and its velocity, the gaze observation.""" - self._gaze_wp, self._velocity_wp = (wp.from_torch(b, dtype=wp.vec2f) for b in (self._gaze, self._velocity)) + """Gaze and its velocity, the gaze observation; the gaze and velocity are views of it.""" + self._gaze = self._state[:, :2] + self._velocity = self._state[:, 2:] + self._gaze_wp = wp.from_torch(self._gaze, dtype=wp.vec2f) self._state_wp = wp.from_torch(self._state, dtype=wp.vec4f) self._step_launch = None self._labels = torch.zeros(self.num_envs, 3, device=self.device) @@ -287,10 +283,8 @@ def _bind(self) -> None: self.num_envs, [ wp.from_torch(self._raw, dtype=wp.vec2f), - self._gaze_wp, - self._velocity_wp, - self._angles_wp, self._state_wp, + self._angles_wp, self.cfg.step_size, self.cfg.gaze_limit, self._env.step_dt, @@ -371,7 +365,7 @@ def reset(self, env_ids=None): int(random_start), self.field_radius_deg, ], - [self._gaze_wp, self._velocity_wp, self._angles_wp, self._state_wp], + [self._angles_wp, self._state_wp], self.device, ) launch.set_dim(count) @@ -379,48 +373,10 @@ def reset(self, env_ids=None): # The camera keeps reading the same buffer, which every other environment already holds. self.camera.set_gaze_angles(self._angles) - def directions(self, points: torch.Tensor) -> torch.Tensor: - """Camera-frame unit directions from the camera to world points, shape (num_envs, 3).""" - position = self.camera.data.pos_w.torch - local = quat_apply_inverse(self.mount_rotation.expand(len(points), -1), points - position) - return torch.nn.functional.normalize(local, dim=-1) - def visible(self, direction: torch.Tensor) -> torch.Tensor: """Whether camera-frame directions fall inside the physical camera's image.""" return project_directions(direction, self._camera)[1] - def teacher(self, points: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """The teacher's action toward one world point per environment, in one launch. - - A point is a valid target when the physical camera sees it and the gaze can reach it within the limit; the - action toward an invalid target is zero. - - Returns: - The actions, shape (num_envs, 2); whether each point is a valid target, shape (num_envs,); and the angle - between the gaze and each point [deg], shape (num_envs,). - """ - points = points.float().contiguous() - action = torch.empty(len(points), 2, device=self.device) - valid = torch.empty(len(points), dtype=torch.bool, device=self.device) - error = torch.empty(len(points), device=self.device) - with torch_stream(self.device): - wp.launch( - teacher_kernel, - dim=len(points), - inputs=[ - wp.from_torch(points, dtype=wp.vec3f), - self.camera.data.pos_w.warp, - self._mount, - self._gaze_wp, - self.field_radius_deg, - self.cfg.step_size, - self.cfg.gaze_limit, - self._camera, - ], - outputs=[wp.from_torch(action, dtype=wp.vec2f), wp.from_torch(valid), wp.from_torch(error)], - ) - return action, valid, error - def _teacher_labels( self, targets: wp.array, orientations: wp.array | None = None, offset: wp.vec3f | None = None ) -> tuple[torch.Tensor, torch.Tensor]: @@ -434,9 +390,24 @@ def _teacher_labels( Returns: The labels (action x, action y, valid), shape (num_envs, 3); and the mean gaze error to valid targets [deg] with the fraction of valid targets, shape (2,). Both are buffers the next call overwrites. + + Raises: + RuntimeError: The camera's mount moved while the gaze assumes a fixed mount. """ + if self.tracked_mount: + source = self.camera.mount_quat_w_ros + if self._tracked_mounts is None or self._tracked_mounts[0] is not source: + self._tracked_mounts = (source, wp.from_torch(source, dtype=wp.quatf)) + mounts = self._tracked_mounts[1] + elif self.camera.mount_moved: + raise RuntimeError( + "The gaze camera's mount moved, so the fixed-mount teacher would aim from the configured mount;" + " use GazeActionCfg.mount='tracked'." + ) + else: + mounts = self._fixed_mount positions = self.camera.data.pos_w.warp - sources = (targets, orientations, positions, offset) + sources = (targets, orientations, positions, offset, mounts) if self._labels_launch is None or any(a is not b for a, b in zip(self._labels_launch[0], sources)): block = teacher_block_dim(self.device) launch = record_launch( @@ -448,7 +419,8 @@ def _teacher_labels( wp.vec3f(0.0, 0.0, 0.0) if offset is None else offset, int(orientations is not None), positions, - self._mount, + mounts, + int(self.tracked_mount), self._gaze_wp, self.field_radius_deg, self.cfg.step_size, @@ -477,6 +449,11 @@ class GazeActionCfg(ActionTermCfg): """Largest distance of the gaze from the camera's optical axis, in field radii.""" random_reset: bool = False """Start episodes at a random gaze the camera sees; otherwise on the optical axis.""" + mount: str = "fixed" + """``"fixed"``: the camera hangs on the environment at its configured offset, and moving its mount raises. + ``"tracked"``: the camera may ride a moving body, and the teacher follows each camera's current mount, so the gaze + adds to hardware gaze such as a turning head. Tracking needs a camera whose pose update turns the gaze (Newton or + OVRTX).""" def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py index 5377996dd684..9fb0851ccbf7 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py @@ -9,6 +9,6 @@ import RSL-RL. """ -from .gaze_supervised_ppo_cfg import GazeSupervisedPPOCfg +from isaaclab.utils.module import lazy_export -__all__ = ["GazeSupervisedPPOCfg"] +lazy_export() diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi new file mode 100644 index 000000000000..f87986fdbb3a --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi @@ -0,0 +1,8 @@ +# 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 + +__all__ = ["GazeSupervisedPPOCfg"] + +from .gaze_supervised_ppo_cfg import GazeSupervisedPPOCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py index 3594b8f36f27..e03e6306badd 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py @@ -26,7 +26,7 @@ def gaze_loss(mean: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: labels: The teacher's gaze actions and their validity, shape (batch, 3). """ valid = labels[:, 2] > 0.5 - # Select valid rows before subtracting, so an invalid label cannot reach the gradients. + # Invalid rows may hold NaN; replacing it keeps their (discarded) residuals finite, so no NaN reaches the gradients. residual = torch.where(valid[:, None], mean - torch.nan_to_num(labels[:, :2]), 0.0) return residual.norm(dim=-1).sum() / valid.sum().clamp_min(1) @@ -87,14 +87,15 @@ def update(self) -> dict[str, float]: clipped = batch.values + (values - batch.values).clamp(-self.clip_param, self.clip_param) value_error = torch.max(value_error, (clipped - batch.returns).pow(2)) value_loss = value_error.mean() - labels = batch.observations[self.oracle_group].float() - oracle = gaze_loss(self.actor.output_mean[:, -2:].float(), labels) - loss = ( - surrogate - + self.value_loss_coef * value_loss - - self.entropy_coef * entropy - + self.oracle_loss_coef * oracle - ) + loss = surrogate + self.value_loss_coef * value_loss - self.entropy_coef * entropy + if self.oracle_loss_coef > 0: + labels = batch.observations[self.oracle_group].float() + oracle = gaze_loss(self.actor.output_mean[:, -2:].float(), labels) + valid = (labels[:, 2] > 0.5).float().mean() + loss = loss + self.oracle_loss_coef * oracle + else: + # Plain PPO: the teacher's labels are neither needed nor read. + oracle = valid = torch.zeros((), device=self.device) self.optimizer.zero_grad() loss.backward() if self.is_multi_gpu: @@ -102,7 +103,6 @@ def update(self) -> dict[str, float]: nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm) nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm) self.optimizer.step() - valid = (labels[:, 2] > 0.5).float().mean() totals += torch.stack((value_loss, surrogate, entropy, oracle, valid)).detach().float() obs = self.storage.observations.flatten(0, 1) self.actor.update_normalization(obs) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py index 2ef23d9f3f3a..04c7baebc966 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py @@ -9,23 +9,6 @@ a renderer runtime. """ -from __future__ import annotations +from isaaclab.utils.module import lazy_export -import importlib -from typing import Any - -_LAZY_EXPORTS = { - "FoveatedCamera": "foveated_camera", - "FoveatedCameraCfg": "foveated_camera_cfg", - "FoveatedNewtonCamera": "foveated_newton_camera", - "FoveatedRTXCamera": "foveated_rtx_camera", -} - -__all__ = list(_LAZY_EXPORTS) - - -def __getattr__(name: str) -> Any: - module = _LAZY_EXPORTS.get(name) - if module is None: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - return getattr(importlib.import_module(f"{__name__}.{module}"), name) +lazy_export() diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi new file mode 100644 index 000000000000..09fec5f420b4 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi @@ -0,0 +1,16 @@ +# 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 + +__all__ = [ + "FoveatedCamera", + "FoveatedCameraCfg", + "FoveatedNewtonCamera", + "FoveatedRTXCamera", +] + +from .foveated_camera import FoveatedCamera +from .foveated_camera_cfg import FoveatedCameraCfg +from .foveated_newton_camera import FoveatedNewtonCamera +from .foveated_rtx_camera import FoveatedRTXCamera diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index fea0c639452b..4b8b4b5fc67d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -3,21 +3,43 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Foveated camera sensor.""" +"""Foveated camera sensor and its virtual gaze.""" from __future__ import annotations +import math +from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING +import torch +import warp as wp + from isaaclab.sensors.camera.camera import Camera -from .virtual_gaze import VirtualGaze +from .calibrated_geometry import convert_camera_frame_quaternion, resolve_camera_model, retinal_directions +from .gaze_kernels import ( + CameraParams, + apply_gaze_indexed_kernel, + apply_gaze_kernel, + camera_params, + publish_grid_kernel, + record_launch, + sensor_visibility_kernel, + set_gaze_kernel, + torch_stream, + warp_stream, +) +from .native_grid import GRID_STYLE, native_grid_directions +from .pooling import ModalPooler, is_segmentation_output, pool_hwc_buffer, pool_segmentation_buffer if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg +OPENGL_TO_ROS_AXES = (1.0, -1.0, -1.0) +"""Axis signs between OpenGL camera-frame directions (x right, y up, -z forward) and ROS ones (x right, y down).""" + -class FoveatedCamera(VirtualGaze, Camera): +class FoveatedCamera(Camera): """Camera that samples the scene on a foveated retina instead of a uniform pixel grid. The sample layout comes from :class:`fovi.sensing.coords.SamplingCoords`. Constructing this class returns the @@ -30,10 +52,18 @@ class FoveatedCamera(VirtualGaze, Camera): Both are subclasses of this class and are imported on first use, so selecting one renderer does not load the other's runtime. + + The gaze turns the retina relative to the optical axis of the physical camera it looks through. Newton and OVRTX + turn the rendered camera pose by the gaze in each pose update; Isaac RTX writes the turned pose into the camera + prims, which Replicator reads. """ cfg: FoveatedCameraCfg + _gaze_pose_reads_angles: bool = False + """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses when + the gaze is set. A writer of :meth:`gaze_angles_buffer` then needs no other launch.""" + def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): """Create the implementation that matches the configured renderer. @@ -57,3 +87,346 @@ def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): raise ValueError( f"Unsupported foveated renderer {renderer_type!r}; select 'newton_warp', 'isaac_rtx', or 'ovrtx'." ) + + def __init__(self, cfg: FoveatedCameraCfg): + # The parent's initialisation updates poses before the gaze exists. + self._gaze_angles = self._gaze_rotation = None + self._grid_publish = None + self._published_shape: tuple[int, int] | None = None + self.mount_moved = False + """Whether :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has moved the camera's mount since + construction.""" + super().__init__(cfg) + + # ------------------------------------------------------------------ + # Gaze + # ------------------------------------------------------------------ + + def gaze_angles_buffer(self) -> torch.Tensor: + """The camera's stored gaze angles [deg], shape (num_envs, 2). + + A writer that moves the gaze every step can update this buffer in place and pass it to + :meth:`set_gaze_angles`, which then copies nothing. Writes take effect when :meth:`set_gaze_angles` is called. + """ + if self._gaze_angles is None: + self._allocate_gaze(self._view.count, torch.device(self._device)) + return self._gaze_angles + + def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: + """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. + + Positive tilt looks up and positive pan looks left. Zero looks along the + optical axis. + + Args: + angles_deg: Gaze angles for every environment [deg], shape (num_envs, 2). + """ + stored = angles_deg is self._gaze_angles and angles_deg is not None + if stored and self._gaze_pose_reads_angles and self.cfg.update_latest_camera_pose: + # The next pose update reads the stored angles; nothing has to happen now. + return + angles = angles_deg if stored else angles_deg.detach().float().contiguous() + if ( + self._gaze_angles is None + or len(self._gaze_angles) != len(angles) + or self._gaze_angles.device != angles.device + ): + self._allocate_gaze(len(angles), angles.device) + # Callers usually pass the same buffer every step; record its launch once. + key = (angles.data_ptr(), angles.shape, angles.device) + if key != self._gaze_angles_key: + self._gaze_angles_key = key + self._set_gaze_launch = record_launch( + set_gaze_kernel, + len(angles), + [wp.from_torch(angles, dtype=wp.vec2f)], + [self._gaze_angles_wp, self._gaze_rotation_wp], + angles.device, + ) + self._set_gaze_launch.launch(warp_stream(angles.device)) + + @property + def mount_quat_w_ros(self) -> torch.Tensor: + """World orientation (x, y, z, w) of the physical camera before the gaze turns it, ROS convention, shape + (num_envs, 4). + + Refreshed by each pose update that turns the gaze, so it follows a mount that moves, for example a camera on + a robot's head. Only cameras whose pose update turns the gaze (Newton and OVRTX) record it. + """ + if not self._gaze_pose_reads_angles: + raise RuntimeError("Only cameras whose pose update turns the gaze (Newton, OVRTX) record their mount.") + self.gaze_angles_buffer() + return self._mount_quat_ros + + def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): + """Move the camera's mount; the gaze stays relative to the new mount. + + Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. + """ + self.mount_moved = True + super().set_world_poses(positions, orientations, env_ids, convention) + + def set_world_poses_from_view(self, eyes, targets, env_ids=None): + """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. + + Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. + """ + self.mount_moved = True + super().set_world_poses_from_view(eyes, targets, env_ids) + + def _allocate_gaze(self, count: int, device: torch.device) -> None: + """Allocate the stored gaze, on the optical axis, and its rotation.""" + self._gaze_angles = torch.zeros(count, 2, device=device) + self._gaze_rotation = torch.eye(3, device=device).repeat(count, 1, 1) + self._mount_quat_ros = torch.zeros(count, 4, device=device) + self._gaze_angles_wp = wp.from_torch(self._gaze_angles, dtype=wp.vec2f) + self._gaze_rotation_wp = wp.from_torch(self._gaze_rotation, dtype=wp.mat33f) + self._mount_quat_ros_wp = wp.from_torch(self._mount_quat_ros, dtype=wp.quatf) + self._gaze_angles_key = None + self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} + self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=str(device)) + + def _apply_gaze_pose( + self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None + ) -> None: + """Turn the camera's world orientation by the stored gaze, and record the gaze rotations and the mount.""" + if self._gaze_angles is None: + return + orientation = self._data.quat_w_world + orientation = orientation.warp if hasattr(orientation, "warp") else wp.from_torch(orientation, dtype=wp.quatf) + device = self._gaze_angles.device + frames = (self._gaze_angles_wp, *self._gaze_frames) + outputs = [orientation, self._gaze_rotation_wp, self._mount_quat_ros_wp] + indexed = env_ids is not None and env_mask is None + if indexed and not isinstance(env_ids, wp.array): + env_ids = wp.from_torch(torch.as_tensor(env_ids, dtype=torch.int32, device=device).contiguous()) + # Every pose update writes the same pose buffer: for all environments, under the camera's update mask, or + # for the indexed ones, whose indices each call swaps in. + mode = "ids" if indexed else ("all" if env_mask is None else "mask") + launch, sources = self._gaze_pose_launches.get(mode, (None, None)) + if sources is None or sources[0] is not orientation or (mode == "mask" and sources[1] is not env_mask): + if indexed: + launch = record_launch(apply_gaze_indexed_kernel, len(env_ids), [*frames, env_ids], outputs, device) + else: + mask = [self._gaze_no_mask if env_mask is None else env_mask, int(env_mask is not None)] + launch = record_launch(apply_gaze_kernel, len(self._gaze_angles), [*frames, *mask], outputs, device) + self._gaze_pose_launches[mode] = (launch, (orientation, env_mask)) + if indexed: + if len(env_ids) == 0: + return + launch.set_param_by_name("indices", env_ids) + launch.set_dim(len(env_ids)) + launch.launch(warp_stream(device)) + + def _update_camera_state( + self, + env_ids: wp.array | None = None, + env_mask: wp.array | None = None, + pos_src: wp.array | None = None, + quat_src: wp.array | None = None, + update_pose: bool = False, + frame_op: int = 0, + ): + """Update the camera state; when the pose update turns the gaze, turn freshly read poses before the renderer + sees them.""" + super()._update_camera_state(env_ids, env_mask, pos_src, quat_src, update_pose, frame_op) + if update_pose and self._gaze_pose_reads_angles: + self._apply_gaze_pose(env_ids, env_mask) + + def _initialize_gaze(self) -> None: + """Prepare the gaze geometry: the rendered rays in the physical camera's frame and the pose conversions.""" + self._camera_model = resolve_camera_model(self.cfg) + self._gaze_camera = camera_params(self._camera_model) + coords = self._sampling_coords_highres or self._sampling_coords + rotation_deg = self.cfg.image_rotation_deg + # The rays as rendered, mount roll included, in the ROS frame the camera model projects. + if coords.style == GRID_STYLE: + rays = native_grid_directions(coords, image_rotation_deg=rotation_deg) + else: + rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) + self._gaze_rays = (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() + self._gaze_rays_wp: dict[torch.device, wp.array] = {} + # No gaze until one is set: the camera looks along its optical axis untouched. + self._gaze_angles = None + self._gaze_rotation = None + device = self._gaze_rays.device + self._gaze_identity = torch.eye(3, device=device) + angle = math.radians(rotation_deg) + c, s = math.cos(angle), math.sin(angle) + # Gaze is defined in the upright image frame; the basis carries it into the rolled OpenGL camera frame. + self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) + # The same roll in the ROS frame: a rendered ray r reaches the physical camera at K gaze K^T r. + self._mask_frame = wp.mat33f(c, s, 0.0, -s, c, 0.0, 0.0, 0.0, 1.0) + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device) + opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl") + to_opengl = opengl[0].tolist() + to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0].tolist() + to_ros = convert_camera_frame_quaternion(opengl, origin="opengl", target="ros")[0].tolist() + self._gaze_frames = ( + wp.mat33f(*self._gaze_basis.flatten().tolist()), + wp.quatf(*to_opengl), + wp.quatf(*to_world), + wp.quatf(*to_ros), + ) + + # ------------------------------------------------------------------ + # Sensor mask and publication + # ------------------------------------------------------------------ + + def _gaze_validity(self, batch_size: int) -> torch.Tensor: + """Return which samples the physical camera sees at the current gaze, shape (batch_size, num_samples).""" + if self._gaze_rotation is None: + rotation = self._gaze_identity.expand(batch_size, -1, -1).contiguous() + rotation_wp = wp.from_torch(rotation, dtype=wp.mat33f) + else: + rotation, rotation_wp = self._gaze_rotation, self._gaze_rotation_wp + device = rotation.device + rays_wp = self._gaze_rays_wp.get(device) + if rays_wp is None: + rays_wp = self._gaze_rays_wp[device] = wp.from_torch(self._gaze_rays.to(device), dtype=wp.vec3f) + valid = torch.empty(batch_size, len(self._gaze_rays), dtype=torch.bool, device=device) + # A receptive field can overlap the sensor even when its center is outside it. + with torch_stream(device): + wp.launch( + sensor_visibility_kernel, + dim=valid.shape, + inputs=[rays_wp, rotation_wp, self._mask_frame, self._gaze_camera], + outputs=[wp.from_torch(valid, dtype=wp.bool)], + ) + return valid + + def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor]) -> None: + """Zero the samples that fall outside the physical camera at the current gaze, in (B, N, 1, C) outputs.""" + if not self.cfg.mask_to_sensor_fov: + return + tensors = {name: value.torch if hasattr(value, "torch") else value for name, value in outputs.items()} + valid = self._gaze_validity(next(iter(tensors.values())).shape[0]) + invalid = ~valid[:, :, None, None] + for name, tensor in tensors.items(): + if name == "rgb" and "rgba" in tensors: + continue + tensor.masked_fill_(invalid, 0) + self._sensor_fov_valid = valid + + def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: + """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for + :func:`publish_grid_kernel`.""" + views = [] + for name, source in sources.items(): + if name == "rgb" and "rgba" in sources: + continue + target = self._grid_output[name].view(source.shape[0], -1, source.shape[-1]) + views.append((wp.from_torch(source.view(torch.uint8)), wp.from_torch(target.view(torch.uint8)))) + self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous()) + self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous()) + num_envs = views[0][1].shape[0] + self._grid_every_env = wp.ones(num_envs, dtype=wp.bool, device=str(self._device)) + if self.cfg.mask_to_sensor_fov: + identity = self._gaze_identity.expand(num_envs, -1, -1).contiguous() + self._sensor_fov_valid_buffer = torch.zeros( + num_envs, len(self._gaze_rays), dtype=torch.bool, device=self._device + ) + self._grid_sensor = ( + wp.from_torch(self._gaze_rays, dtype=wp.vec3f), + wp.from_torch(identity, dtype=wp.mat33f), + self._mask_frame, + self._gaze_camera, + wp.from_torch(self._sensor_fov_valid_buffer), + ) + else: + # Placeholders: the kernel reads none of these without the sensor mask. + self._grid_sensor = ( + wp.zeros(1, dtype=wp.vec3f, device=self._device), + wp.zeros(1, dtype=wp.mat33f, device=self._device), + wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0), + CameraParams(), + wp.zeros((1, 1), dtype=wp.bool, device=self._device), + ) + self._grid_publish = views + self._grid_launches = None + + def _publish_grid(self, env_mask: wp.array | None = None) -> None: + """Mask and lay out every output of the updated environments in one launch each; the result equals masking, + then copying to the grid. The other environments keep their last published frame; None updates every one.""" + mask = self.cfg.mask_to_sensor_fov + env_mask = self._grid_every_env if env_mask is None else env_mask + rays, identity, frame, camera, visible = self._grid_sensor + rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation_wp + cached = self._grid_launches + if cached is None or cached[0][0] is not rotation or cached[0][1] is not env_mask: + launches = [ + record_launch( + publish_grid_kernel, + (target.shape[0], target.shape[1]), + [ + source, + self._grid_indices_wp, + self._grid_footprint_wp, + env_mask, + rays, + rotation, + frame, + camera, + int(mask), + int(mask and index == 0), + visible, + ], + [target], + self._device, + ) + for index, (source, target) in enumerate(self._grid_publish) + ] + self._grid_launches = ((rotation, env_mask), launches) + stream = warp_stream(self._device) + for launch in self._grid_launches[1]: + launch.launch(stream) + if mask: + self._sensor_fov_valid = self._sensor_fov_valid_buffer + + def _pool_output(self, name: str, samples: torch.Tensor) -> torch.Tensor: + """Pool one output's high-resolution samples (B, N_hi, 1, C) to the retina's (B, N_lo, 1, C), in its dtype. + + Segmentation takes each sample's modal label in its native dtype; other outputs are pooled in float. + """ + if self._pooler_int is not None and is_segmentation_output(name): + if isinstance(self._pooler_int, ModalPooler): + return pool_segmentation_buffer(self._pooler_int, samples) + return pool_hwc_buffer(self._pooler_int, samples.float()).to(samples.dtype) + return pool_hwc_buffer(self._pooler, samples.float()).to(samples.dtype) + + # ------------------------------------------------------------------ + # Output description + # ------------------------------------------------------------------ + + def _set_published_shape(self, outputs: Mapping[str, torch.Tensor]) -> None: + """Report the (height, width) of the published outputs, which differ from the rendered ones.""" + first = next(iter(outputs.values())) + tensor = first.torch if hasattr(first, "torch") else first + self._published_shape = (int(tensor.shape[1]), int(tensor.shape[2])) + self._data.image_shape = self._published_shape + + @property + def image_shape(self) -> tuple[int, int]: + """(height, width) of the published outputs: the retina's grid, or (num_samples, 1) for sample sets.""" + return self._published_shape if self._published_shape is not None else super().image_shape + + @property + def sampling_coords(self): + """The :class:`SamplingCoords` of the published samples.""" + return self._sampling_coords + + @property + def image_rotation_deg(self) -> float: + """Roll [deg] of the rendered rays around the optical axis, which undoes a rolled mount.""" + return float(self.cfg.image_rotation_deg) + + @property + def num_valid_samples(self) -> int: + """Number of published foveated samples.""" + return self._num_valid_samples + + @property + def sensor_fov_valid_fraction(self) -> torch.Tensor | None: + """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" + valid = getattr(self, "_sensor_fov_valid", None) + return None if valid is None else valid.float().mean(dim=1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 75c1fbf86d74..9121f4d71c28 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -12,7 +12,7 @@ from isaaclab.sensors.camera.camera_cfg import CameraCfg from isaaclab.utils.configclass import configclass -from isaaclab_fovi.sensors.native_grid import validate_radius_norm +from .native_grid import validate_radius_norm @configclass @@ -79,20 +79,9 @@ class FoveatedCameraCfg(CameraCfg): Ignored for non-isotropic ``foveated_style``.""" image_rotation_deg: float = 0.0 - """Rotation (degrees, counter-clockwise) applied to the foveated ray - directions around the optical axis BEFORE rendering. Used to undo a - physical camera mount rotation (e.g. an upside-down right-eye sensor) - so that the per-ray samples land in the canonical - :class:`SamplingCoords` order — i.e. sample ``i`` always corresponds to - visual-field position ``rel_cart_coords[i]`` regardless of how the - camera prim is oriented in world. General-purpose alternative to - post-render ``torch.flip`` (which would shuffle the sample order and - misalign with retinal scatter and KNN processing). - - Common values: - * ``0.0`` — no rotation (default; right-side-up sensor). - * ``180.0`` — flip vertically + horizontally (upside-down sensor). - * Other angles work in principle but are untested.""" + """Counter-clockwise roll [deg] of the rendered rays about the optical axis, which undoes a rolled mount (180 for + an upside-down sensor). Samples keep their canonical :class:`SamplingCoords` order, so the published image stays + upright; the sensor mask and the gaze use the same roll.""" mask_to_sensor_fov: bool = False """Zero the samples that fall outside the physical camera's image at the current gaze. @@ -139,13 +128,18 @@ class FoveatedCameraCfg(CameraCfg): pool_gauss_sigma: float = 10.0 """Gaussian sigma for ``pool_mode="gaussian"``. Unused otherwise.""" - pool_int_mode: str = "max" + pool_int_mode: str = "mode" """Pool mode used for outputs whose key name contains ``"segmentation"`` (``semantic_segmentation``, ``instance_segmentation_fast``, - ``instance_id_segmentation_fast``). Averaging segmentation values blurs - class labels and breaks downstream integer/equality checks, so these - outputs get a separate pooler with this mode. Set equal to ``pool_mode`` - to disable this behaviour.""" + ``instance_id_segmentation_fast``). + + The default ``"mode"`` gives each pooled sample the most common full value + (ID or colorized RGBA vector) among its pooling neighbours, in the output's + native dtype; ties go to the neighbour nearest the pooled sample. Every + pooled value therefore belongs to a rendered object. The fovi modes + (``"max"``, ``"avg"``, ``"sum"``, ``"gaussian"``) pool through float32 + instead, which mixes colorized channels and corrupts IDs above ``2**24``. + Set equal to ``pool_mode`` to pool segmentation like the other outputs.""" # -- RTX-specific parameters (ignored by Newton backend) ---------------- diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 5c9ece111ff1..5bca68419e7d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -3,13 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Newton foveated tiled camera sensor. - -Subclasses :class:`isaaclab.sensors.Camera` to replace uniform pinhole -rays with CMF-distributed foveated rays computed from -:class:`fovi.sensing.coords.SamplingCoords`. Uses Newton's Warp renderer -to shoot custom ray arrays. -""" +"""Newton foveated camera: Newton's Warp renderer casts one ray per retinal sample.""" from __future__ import annotations @@ -25,7 +19,6 @@ from .calibrated_geometry import retinal_directions from .foveated_camera import FoveatedCamera -from .foveated_rays import compute_explicit_ray_array from .native_grid import ( GRID_STYLE, allocate_grid_outputs, @@ -36,13 +29,7 @@ native_grid_directions, proxy_outputs, ) -from .pooling import ( - build_highres_coords, - build_lowres_coords, - build_pooler, - is_segmentation_output, - pool_hwc_buffer, -) +from .pooling import build_highres_coords, build_lowres_coords, build_pooler, is_segmentation_output if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg @@ -50,15 +37,23 @@ logger = logging.getLogger(__name__) -@wp.kernel(enable_backward=False) -def _pack_vector_rays( - source: wp.array2d(dtype=wp.vec3f), - target: wp.array2d(dtype=wp.vec3f), -) -> None: - i = wp.tid() - source_i = wp.min(i, source.shape[0] - 1) - target[i, 0] = source[source_i, 0] - target[i, 1] = source[source_i, 1] +def explicit_rays(directions: torch.Tensor, height: int, width: int) -> wp.array: + """Newton's ray array, shape (1, height, width, 2): a zero origin and a unit direction per ray. + + Args: + directions: Unit ray directions in the OpenGL camera frame, in sample order, shape (N, 3). + height: Rendered rows. + width: Rendered columns; ``height * width`` must cover the N rays. Padding repeats the last ray. + """ + if directions.ndim != 2 or directions.shape[1] != 3: + raise ValueError(f"Ray directions must have shape (N, 3), got {tuple(directions.shape)}.") + if height * width < len(directions): + raise ValueError(f"A {height}x{width} render cannot hold {len(directions)} rays.") + index = torch.arange(height * width, device=directions.device).clamp_max(len(directions) - 1) + rays = directions.new_zeros(1, height, width, 2, 3, dtype=torch.float32) + rays[..., 1, :] = directions.float()[index].reshape(1, height, width, 3) + # The Warp view keeps the tensor alive. + return wp.from_torch(rays, dtype=wp.vec3f) class FoveatedNewtonCamera(FoveatedCamera): @@ -69,37 +64,24 @@ class FoveatedNewtonCamera(FoveatedCamera): and injected into Newton's Warp renderer. Vector sensors publish ``(B, N, 1, C)``; native grid sensors publish upright ``(B, H, W, C)``. - The samples cover the retinal window of the physical camera, and gaze is - applied as a per-environment rotation of the rays. + The samples cover the retinal window of the physical camera; the gaze turns the rendered camera pose. """ cfg: FoveatedCameraCfg _gaze_pose_reads_angles = True - def __init__(self, cfg: FoveatedCameraCfg): - # The parent's initialisation updates poses before the gaze exists. - self._gaze_angles = self._gaze_rotation = None - super().__init__(cfg) - # ------------------------------------------------------------------ # Initialisation # ------------------------------------------------------------------ def _initialize_impl(self): - # 1. Build coords on CPU so we know N_lo (and N_hi when pooling) before - # the parent allocates buffers. The pooler is constructed later, - # after the sensor device is available, because its knn indices / - # distances / gaussian weights are plain tensor attributes that - # nn.Module.to() does not move. + # The pooler's KNN tensors are plain attributes that nn.Module.to() does not move, so the coordinates start on + # the CPU and the pooler is built on the sensor device after the parent initializes. self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") self._native_grid = self.cfg.foveated_style == GRID_STYLE - self._sampling_coords_highres = build_highres_coords( - self.cfg, - matched_res, - device="cpu", - ) - self._num_valid_samples = len(self._sampling_coords) # public / RGC count + self._sampling_coords_highres = build_highres_coords(self.cfg, matched_res, device="cpu") + self._num_valid_samples = len(self._sampling_coords) self._num_ray_samples = len(self._sampling_coords_highres or self._sampling_coords) logger.info( "FoveatedNewtonCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg", @@ -110,8 +92,7 @@ def _initialize_impl(self): self._sampling_coords.fov, ) - # 3. Size the parent's render buffers to the *rendered* ray count. - # When pooling is enabled this is N_hi; otherwise it equals N_lo. + # The parent allocates render buffers for the rendered rays: the high-resolution ones when pooling. ray_coords = self._sampling_coords_highres or self._sampling_coords self.cfg.height, self.cfg.width = grid_output_shape(ray_coords) renderer = self.cfg.renderer_cfg @@ -120,7 +101,9 @@ def _initialize_impl(self): tile_height = renderer.tile_rendering_height if tile_width <= 0 or tile_height <= 0: raise ValueError("Newton render tile dimensions must be positive.") - if not self._native_grid: + if self._native_grid: + self._validate_native_render_layout(tile_width, tile_height) + else: # Pack consecutive vector rays into complete tiles. Padding is # private renderer storage and never enters masking or pooling. self.cfg.width = tile_width @@ -128,63 +111,29 @@ def _initialize_impl(self): (self._num_ray_samples + tile_width * tile_height - 1) // (tile_width * tile_height) * tile_height ) - # 4. Run parent initialisation (creates renderer, buffers, etc.). super()._initialize_impl() - if self._native_grid: - self._validate_native_render_layout() - # 5. Move coords to the correct device. self._sampling_coords = self._sampling_coords.to(device=self._device) if self._sampling_coords_highres is not None: self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) - ray_coords_device = self._sampling_coords_highres - else: - ray_coords_device = self._sampling_coords - self._ray_coords = ray_coords_device + self._ray_coords = self._sampling_coords_highres or self._sampling_coords self._initialize_gaze() - - # 6. Build the pooler(s) on the sensor device. A second max-mode - # pooler is materialised lazily below if any integer-valued outputs - # are present (segmentation class IDs) and pool_int_mode differs - # from pool_mode. self._pooler, self._pool_k = build_pooler( - self.cfg, - self._sampling_coords, - self._sampling_coords_highres, - device=str(self._device), + self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) ) self._pooler_int = None - # 7. Pre-compute foveated rays from the highres (or lowres) cartesian. - # Apply optional image-space rotation by rotating the 2D cartesian - # coordinates around the optical axis BEFORE deriving rays. This - # keeps the per-sample index ordering identical to the canonical - # ``SamplingCoords`` (so the agent / foveated scatter visualization - # see upright samples) while undoing a physical mount rotation of - # the camera prim. Foveated analogue of a post-render - # ``torch.flip`` — but flip would shuffle the sample-to-coord - # mapping; this rotation does not. + # The rays keep the canonical sample order; image_rotation_deg rolls their directions to undo a rolled mount. if self._native_grid: self._ray_directions = native_grid_directions( - ray_coords_device, image_rotation_deg=self.cfg.image_rotation_deg + self._ray_coords, image_rotation_deg=self.cfg.image_rotation_deg ) else: self._ray_directions = retinal_directions( - ray_coords_device.cartesian, ray_coords_device.fov, self.cfg.image_rotation_deg + self._ray_coords.cartesian, self._ray_coords.fov, self.cfg.image_rotation_deg ) - self._foveated_rays = compute_explicit_ray_array(self._ray_directions, device=str(self._device)) - + self._foveated_rays = explicit_rays(self._ray_directions, self.cfg.height, self.cfg.width) render_samples = self.cfg.height * self.cfg.width - if render_samples > self._num_ray_samples: - packed = wp.empty((render_samples, 2), dtype=wp.vec3f, device=self._device) - wp.launch( - _pack_vector_rays, - dim=render_samples, - inputs=[self._foveated_rays.reshape((self._num_ray_samples, 2)), packed], - device=self._device, - ) - self._foveated_rays = packed - self._foveated_rays = self._foveated_rays.reshape((1, self.cfg.height, self.cfg.width, 2)) # Renderer buffers remain whole tiles; zero-copy canonical views hide # trailing padding and preserve every output's dtype and sample order. self._render_output = dict(self._data.output) @@ -206,26 +155,15 @@ def _initialize_impl(self): self._public_output = proxy_outputs(source) self._data.output.clear() self._data.output.update(self._public_output) - self._grid_publish = None + self._set_published_shape(self._public_output) if self._native_grid and self._pooler is None: self._prepare_grid_publish( {name: value.torch.squeeze(2) for name, value in self._flat_render_output.items()} ) - - # 6. Inject foveated rays into render_data immediately. self._render_data.camera_rays = self._foveated_rays - logger.info( - "FoveatedNewtonCamera: injected foveated rays shape=%s onto render_data", - self._foveated_rays.shape, - ) - def _validate_native_render_layout(self) -> None: - """Reject image dimensions that cannot be covered by Newton's tiles.""" - renderer = self._renderer.cfg - if renderer.render_order != "tiled": - return - tile_width = renderer.tile_rendering_width - tile_height = renderer.tile_rendering_height + def _validate_native_render_layout(self, tile_width: int, tile_height: int) -> None: + """Reject a native grid that Newton's tiles cannot cover, before the parent allocates render buffers.""" if self.cfg.width % tile_width or self.cfg.height % tile_height: raise ValueError( f"Native-grid Newton render size {self.cfg.width}x{self.cfg.height} " @@ -235,49 +173,43 @@ def _validate_native_render_layout(self) -> None: ) def _allocate_pooled_buffers(self) -> None: - """Allocate output-grid tensors from renderer-owned high-resolution buffers.""" - if self._pooler is not None: - # Stash the parent-allocated highres buffers; the renderer will keep - # writing into these, and we pool into a separate lowres dict that - # becomes the public _data.output after each update. - self._highres_output: dict[str, ProxyArray] = dict(self._data.output) - self._pooled_output: dict[str, torch.Tensor] = {} - needs_int_pooler = False - for name, tex in self._highres_output.items(): - tensor = tex.torch - B, _, _, C = tensor.shape - self._pooled_output[name] = torch.zeros( - (B, self._num_valid_samples, 1, C), - dtype=tensor.dtype, - device=tensor.device, - ) - if is_segmentation_output(name) and self.cfg.pool_int_mode != self.cfg.pool_mode: - needs_int_pooler = True - if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: - # Re-alias rgb onto the first 3 channels of pooled rgba. - self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] - if needs_int_pooler: - self._pooler_int, _ = build_pooler( - self.cfg, - self._sampling_coords, - self._sampling_coords_highres, - device=str(self._device), - mode=self.cfg.pool_int_mode, - ) - dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} - logger.info( - "FoveatedNewtonCamera: KNN pooling enabled " - "(mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) " - "outputs=%s int_pooler=%s int_mode=%s", - self.cfg.pool_mode, - self._pool_k, - self.cfg.pool_sample_cortex, - self._num_ray_samples, - self._num_valid_samples, - dtypes_summary, - self._pooler_int is not None, - self.cfg.pool_int_mode, + """Allocate pooled output tensors; the renderer keeps writing the high-resolution buffers.""" + if self._pooler is None: + return + self._highres_output: dict[str, ProxyArray] = dict(self._data.output) + self._pooled_output: dict[str, torch.Tensor] = {} + needs_int_pooler = False + for name, tex in self._highres_output.items(): + tensor = tex.torch + B, _, _, C = tensor.shape + self._pooled_output[name] = torch.zeros( + (B, self._num_valid_samples, 1, C), dtype=tensor.dtype, device=tensor.device ) + if is_segmentation_output(name) and self.cfg.pool_int_mode != self.cfg.pool_mode: + needs_int_pooler = True + if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: + self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] + if needs_int_pooler: + self._pooler_int, _ = build_pooler( + self.cfg, + self._sampling_coords, + self._sampling_coords_highres, + device=str(self._device), + mode=self.cfg.pool_int_mode, + ) + dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} + logger.info( + "FoveatedNewtonCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) " + "outputs=%s int_pooler=%s int_mode=%s", + self.cfg.pool_mode, + self._pool_k, + self.cfg.pool_sample_cortex, + self._num_ray_samples, + self._num_valid_samples, + dtypes_summary, + self._pooler_int is not None, + self.cfg.pool_int_mode, + ) # ------------------------------------------------------------------ # Per-frame overrides @@ -296,91 +228,29 @@ def _update_poses( """ # The base update turns the poses by the gaze in _update_camera_state, then hands them to the renderer. Camera._update_poses(self, env_ids, env_mask=env_mask, frame_op=frame_op) - # Ensure foveated rays (not pinhole) if hasattr(self, "_foveated_rays"): self._render_data.camera_rays = self._foveated_rays def _update_buffers_impl(self, env_mask: wp.array): - """Render, then (optionally) pool highres -> lowres foveated samples.""" + """Render, then mask and publish the updated environments, pooling high-resolution samples if enabled.""" self._data.output.clear() self._data.output.update(self._render_output) + super()._update_buffers_impl(env_mask) if self._pooler is None: - super()._update_buffers_impl(env_mask) if self._grid_publish: - self._publish_grid() + self._publish_grid(env_mask) else: output = self._flat_render_output mask_grid_samples(output, self._ray_coords) self._apply_sensor_fov_mask(output) - self._data.output.clear() - self._data.output.update(self._public_output) - return - - # Ensure the renderer writes into the highres buffers, not the pooled ones. - self._data.output.clear() - self._data.output.update(self._render_output) - super()._update_buffers_impl(env_mask) - mask_grid_samples(self._highres_output, self._ray_coords) - self._apply_sensor_fov_mask(self._highres_output) - - # Pool each output channel (B, N_hi, 1, C) -> (B, N_lo, 1, C). - # Cast to float for pooling (KNN ops need real-valued NaN semantics), - # then restore the original dtype. Integer outputs (segmentation - # class IDs) use the separate max-mode pooler so pooled values remain - # valid class IDs rather than averaged floats. - for name, hi in self._highres_output.items(): - if name == "rgb": - continue # rgba alias, refreshed below - lo = self._pooled_output[name] - use_int_pool = self._pooler_int is not None and is_segmentation_output(name) - pooler = self._pooler_int if use_int_pool else self._pooler - pooled = pool_hwc_buffer(pooler, hi.torch.float()) - lo.copy_(pooled.to(lo.dtype)) - - # Expose pooled tensors as the public sensor output. - if self._native_grid: - copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) + else: + mask_grid_samples(self._highres_output, self._ray_coords) + self._apply_sensor_fov_mask(self._highres_output) + for name, hi in self._highres_output.items(): + if name == "rgb": + continue # rgba alias + self._pooled_output[name].copy_(self._pool_output(name, hi.torch)) + if self._native_grid: + copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) self._data.output.clear() self._data.output.update(self._public_output) - - def _apply_sensor_fov_mask(self, outputs: dict[str, torch.Tensor]) -> None: - """Zero the samples that fall outside the physical camera at the current gaze.""" - if not self.cfg.mask_to_sensor_fov: - return - first_output = next(iter(outputs.values())) - first_tensor = first_output.torch if hasattr(first_output, "torch") else first_output - valid = self._gaze_validity(first_tensor.shape[0]) - invalid = ~valid[:, :, None, None] - has_rgba_alias = "rgba" in outputs - for name, output in outputs.items(): - if name == "rgb" and has_rgba_alias: - continue - tensor = output.torch if hasattr(output, "torch") else output - tensor.masked_fill_(invalid, 0) - self._sensor_fov_valid = valid - - # ------------------------------------------------------------------ - # Output helpers - # ------------------------------------------------------------------ - - @property - def sampling_coords(self): - """The :class:`SamplingCoords` used for ray generation.""" - return self._sampling_coords - - @property - def image_rotation_deg(self) -> float: - """Pre-render rotation (degrees, CCW around the optical axis) applied - to the per-ray sampling coordinates. ``0`` for the canonical mount.""" - return float(self.cfg.image_rotation_deg) - - @property - def num_valid_samples(self) -> int: - """Number of foveated sample points *N*.""" - return self._num_valid_samples - - @property - def sensor_fov_valid_fraction(self) -> torch.Tensor | None: - """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" - valid = getattr(self, "_sensor_fov_valid", None) - return None if valid is None else valid.float().mean(dim=1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py deleted file mode 100644 index e94c3995eb33..000000000000 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rays.py +++ /dev/null @@ -1,48 +0,0 @@ -# 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 - -"""Newton ray arrays for foveated cameras. - -Newton's Warp renderer takes a ray array of shape (camera_count=1, height, width, 2), -where [..., 0] is the ray origin (always zero) and [..., 1] its unit direction. -""" - -from __future__ import annotations - -import torch -import warp as wp - - -@wp.kernel(enable_backward=False) -def _fill_explicit_rays( - directions: wp.array(dtype=wp.vec3f), - out_rays: wp.array(dtype=wp.vec3f, ndim=4), -): - i = wp.tid() - out_rays[0, i, 0, 0] = wp.vec3f(0.0, 0.0, 0.0) - out_rays[0, i, 0, 1] = directions[i] - - -def compute_explicit_ray_array( - ray_directions: torch.Tensor, - *, - device: str, -) -> wp.array: - """Build a ``(1, N, 1, 2)`` Newton ray array from unit OpenGL camera-frame directions, shape (N, 3).""" - if ray_directions.ndim != 2 or ray_directions.shape[1] != 3: - raise ValueError(f"ray_directions must have shape (N, 3), got {tuple(ray_directions.shape)}.") - directions = wp.from_torch( - ray_directions.contiguous().float(), - dtype=wp.vec3f, - ) - num_rays = ray_directions.shape[0] - out_rays = wp.zeros((1, num_rays, 1, 2), dtype=wp.vec3f, device=device) - wp.launch( - kernel=_fill_explicit_rays, - dim=num_rays, - inputs=[directions, out_rays], - device=device, - ) - return out_rays diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 8000ce504e2f..1e088c79681e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -39,13 +39,7 @@ native_grid_directions, proxy_outputs, ) -from .pooling import ( - build_highres_coords, - build_lowres_coords, - build_pooler, - is_segmentation_output, - pool_hwc_buffer, -) +from .pooling import build_highres_coords, build_lowres_coords, build_pooler, is_segmentation_output if TYPE_CHECKING: from isaaclab.renderers.base_renderer import BaseRenderer @@ -89,23 +83,24 @@ def renderer(self) -> BaseRenderer: return self._renderer def __init__(self, cfg: FoveatedCameraCfg): - self._gaze_angles = self._gaze_rotation = None + ovrtx = cfg.renderer_cfg.renderer_type == "ovrtx" + if ovrtx and getattr(cfg.renderer_cfg, "async_rendering", False) and cfg.mask_to_sensor_fov: + raise ValueError( + "OVRTX async_rendering returns the previous capture, which the sensor mask would cut with the current" + " gaze. Disable async_rendering or mask_to_sensor_fov." + ) # OVRTX renders the poses the camera hands it, so its pose update turns the gaze. Replicator reads camera # prims, so Isaac RTX writes the gaze into them instead. - self._gaze_pose_reads_angles = cfg.renderer_cfg.renderer_type == "ovrtx" - self._grid_publish = None - # Texture buffers are owned by the parent ``Camera`` (allocated in - # ``_create_buffers`` and bound to the renderer via ``set_outputs``). - # Foveated / pooled buffers are allocated in ``_initialize_impl`` - # once the texture buffers are known. + self._gaze_pose_reads_angles = ovrtx + # The parent ``Camera`` allocates the renderer-bound texture buffers; the published ones follow from them. self._texture_output: dict[str, torch.Tensor] = {} self._foveated_output: dict[str, torch.Tensor] = {} self._pooled_output: dict[str, torch.Tensor] | None = None - if cfg.renderer_cfg.renderer_type == "ovrtx": + if ovrtx: self.cfg = cfg self._prepare_projection() super().__init__(cfg) - if cfg.renderer_cfg.renderer_type == "ovrtx": + if ovrtx: for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): gp.apply_generalized_projection_to_prim(prim, self._dir_tex_path, self._exit_tex_path) @@ -114,34 +109,16 @@ def __init__(self, cfg: FoveatedCameraCfg): # ------------------------------------------------------------------ def _prepare_projection(self) -> None: - # 1. Build coords on CPU. The LUT textures + UV extraction use the - # *rendered* grid (highres when pooling, else lowres). The - # public `sampling_coords` property stays on the lowres / RGC grid. + # The lens textures and sample extraction use the rendered samples: the high-resolution ones when pooling. self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") - self._sampling_coords_highres = build_highres_coords( - self.cfg, - matched_res, - device="cpu", - ) + self._sampling_coords_highres = build_highres_coords(self.cfg, matched_res, device="cpu") ray_coords = self._sampling_coords_highres or self._sampling_coords self._ray_coords = ray_coords self._native_grid = self.cfg.foveated_style == GRID_STYLE + self._num_valid_samples = len(self._sampling_coords) + self._num_ray_samples = len(ray_coords) - self._num_valid_samples = len(self._sampling_coords) # public / RGC count - self._num_ray_samples = len(ray_coords) # rendered ray count - N = self._num_ray_samples - - # 2. Compute ray directions and UV mapping from the rendered grid. - # Apply optional image-space rotation (``cfg.image_rotation_deg``) by - # rotating the per-ray polar angle ``theta`` around the optical axis - # *before* computing the ray directions. This undoes a physical - # mount rotation of the camera prim while keeping the per-sample - # index ordering identical to the canonical ``SamplingCoords`` — so - # the agent's foveator (and the foveated scatter plot) read out the - # same upright scene at every sample position. A post-render - # ``torch.flip`` would reshuffle the sample order and corrupt the - # downstream visualization / KNN mapping; this rotation is the - # foveated-camera-native analogue of that flip. + # image_rotation_deg rolls each ray's polar angle before its direction is computed; see its configuration. theta_rad = ray_coords.polar[:, 1].to(torch.float64) if self.cfg.image_rotation_deg: theta_rad = theta_rad + math.radians(float(self.cfg.image_rotation_deg)) @@ -150,38 +127,26 @@ def _prepare_projection(self) -> None: else: dirs = retinal_directions(ray_coords.cartesian, ray_coords.fov, self.cfg.image_rotation_deg) - # 3. Texture dimensions and UV layout. Grid styles render straight into their - # native grid; sample-set styles are packed onto a cortical disc, which keeps - # neighbouring samples adjacent for the renderer's spatial filtering. + # Grid styles render straight into their native grid; sample-set styles are packed onto a cortical disc, + # which keeps neighbouring samples adjacent for the renderer's spatial filtering. if self._native_grid: tw = th = ray_coords.resolution axis = (torch.arange(tw, dtype=torch.float32) + 0.5) / tw row, col = torch.meshgrid(axis, axis, indexing="ij") uv = torch.stack((col, row), -1).reshape(-1, 2) else: - tw = th = max(64, math.ceil(math.sqrt(4 * N / math.pi))) + tw = th = max(64, math.ceil(math.sqrt(4 * self._num_ray_samples / math.pi))) # Eccentricity [deg] of each sample; the disc is laid out with the same # field of view and CMF constant the samples were generated with. eccentricity = ray_coords.polar[:, 0].to(torch.float64) * (ray_coords.fov / 2.0) - uv = gp.samples_uv_cortical_disc( - eccentricity, - theta_rad, - ray_coords.fov, - ray_coords.cmf_a, - device="cpu", - ) - + uv = gp.samples_uv_cortical_disc(eccentricity, theta_rad, ray_coords.fov, ray_coords.cmf_a, device="cpu") self._texture_width = tw self._texture_height = th - self._sample_uv = uv # (N, 2) float32 - - # 4. Build and save LUT textures. - # The exit texture is an octahedral inverse map (ray direction → sensor NDC). - # It covers the full hemisphere, but only the fraction within the camera - # FOV is populated. The resolution must be high enough that each foveated - # sample maps to a distinct exit texel within that fraction. Scaling as - # 4× the direction texture dimension gives ~16× the texel count, which - # provides sufficient angular oversampling for the NN lookup. + self._sample_uv = uv + + # The exit texture is an octahedral inverse map (ray direction -> sensor NDC) over the hemisphere, of which + # only the camera's field of view is populated. Four times the direction texture's size gives each sample a + # distinct exit texel for the nearest-neighbour lookup. if self.cfg.exit_texture_size is not None: EW = EH = self.cfg.exit_texture_size else: @@ -191,23 +156,12 @@ def _prepare_projection(self) -> None: ray_coords, image_rotation_deg=self.cfg.image_rotation_deg, exit_size=EW ) else: - dir_tex, exit_tex = gp.build_generalized_projection_textures( - uv, - dirs, - tw, - th, - EW, - EH, - device="cpu", - ) - self._lut_tmpdir = tempfile.mkdtemp(prefix="rtx_foveated_luts_") + dir_tex, exit_tex = gp.build_generalized_projection_textures(uv, dirs, tw, th, EW, EH, device="cpu") + # The camera owns its textures' directory, which is removed when the camera is released. + self._lut_dir = tempfile.TemporaryDirectory(prefix="rtx_foveated_luts_") self._dir_tex_path, self._exit_tex_path = gp.save_generalized_projection_textures( - dir_tex, - exit_tex, - self._lut_tmpdir, - "foveated", + dir_tex, exit_tex, self._lut_dir.name, "foveated" ) - logger.info( "FoveatedRTXCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg, " "texture %dx%d, exit lookup %dx%d, lookup textures in %s", @@ -220,10 +174,9 @@ def _prepare_projection(self) -> None: th, EW, EH, - self._lut_tmpdir, + self._lut_dir.name, ) - - # 5. Set texture dimensions so parent allocates (B, th, tw, C) buffers. + # The parent allocates (B, th, tw, C) texture buffers. self.cfg.height = th self.cfg.width = tw @@ -233,14 +186,14 @@ def _initialize_impl(self) -> None: tw, th = self._texture_width, self._texture_height # Author the lens before Camera prepares the renderer's stage. OVRTX # snapshots a detached stage, so later USD edits would miss its cameras. - for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): + prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) + for prim in prims: gp.apply_generalized_projection_to_prim( - prim, - direction_texture_path=self._dir_tex_path, - exit_texture_path=self._exit_tex_path, + prim, direction_texture_path=self._dir_tex_path, exit_texture_path=self._exit_tex_path ) + # OVRTX's lookup-table range is measured from the near-clipped ray origin. + self._near_clip = self._near_clipping_distance(prims[0]) if prims else 0.0 - # 8. Run parent initialisation (creates renderer, buffers, etc.). super()._initialize_impl() # OVRTX owns its runtime; Kit extensions belong only to Isaac RTX. @@ -252,19 +205,6 @@ def _initialize_impl(self) -> None: if not ext_manager.set_extension_enabled_immediate(ext_name, True): logger.warning("Could not enable Kit extension '%s'; the lens lookup may not render.", ext_name) - # Moving-gaze DLSS quality still needs validation with native LUTs; - # geometry smoke tests disable temporal accumulation. - - # 10. Pre-compute extraction indices and build the pooler. The - # parent ``Camera._create_buffers`` (called from super - # ``_initialize_impl``) has already allocated the per-data-type - # ``(B, H, W, C)`` texture tensors as ``self._data.output`` and - # bound them to the renderer via ``set_outputs``. We snapshot - # them as ``_texture_output`` (same dict reference, so the - # renderer keeps writing to it across frames) and allocate the - # foveated / pooled output buffers from those shapes. Then we - # point ``self._data.output`` at the foveated/pooled dict so - # downstream consumers see the per-sample buffers. self._sampling_coords = self._sampling_coords.to(device=self._device) if self._sampling_coords_highres is not None: self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) @@ -272,109 +212,98 @@ def _initialize_impl(self) -> None: self._initialize_gaze() _, local_orientation = self._view.get_local_poses() self._base_local_orientation = matrix_from_quat(local_orientation.torch).clone() - - # Build the pooler on the sensor device (so knn tensors live there). - # A second max-mode pooler is built inside ``_allocate_foveated_buffers`` - # if any integer-valued output buffers are present (segmentation IDs). self._pooler, self._pool_k = build_pooler( - self.cfg, - self._sampling_coords, - self._sampling_coords_highres, - device=str(self._device), + self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) ) self._pooler_int = None - uv_gpu = self._sample_uv.to(self._device) - self._extract_px = (uv_gpu[:, 0] * tw).long().clamp(0, tw - 1) - self._extract_py = (uv_gpu[:, 1] * th).long().clamp(0, th - 1) - - # Capture the renderer-bound texture dict and allocate foveated / - # pooled output buffers. + # The renderer keeps writing the texture buffers the parent bound to it; the camera publishes others. self._texture_output = self._data.output - self._allocate_foveated_buffers() - # Publish the foveated (or pooled) buffers. ``CameraData.output`` is read-only, so the - # backing field is replaced; the renderer keeps writing to the texture buffers it was - # bound to by the parent ``_create_buffers``. - new_output = self._pooled_output if self._pooled_output is not None else self._foveated_output - if self._native_grid: - self._grid_output = allocate_grid_outputs(new_output, self._sampling_coords) - self._grid_indices = grid_sample_indices(self._sampling_coords) - new_output = self._grid_output - self._data._output = proxy_outputs(new_output) - # A native grid texture already holds the samples in order, so one kernel per output masks it and lays it out. - # OVRTX's camera distance needs its near-plane offset first, and keeps the step-by-step path. textures = {name: tex.torch if hasattr(tex, "torch") else tex for name, tex in self._texture_output.items()} + # A native grid texture already holds the samples in order, so one kernel per output masks it and lays it + # out. OVRTX's camera distance needs its near-plane offset first, and keeps the step-by-step path. offset_distance = self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in textures - if self._native_grid and self._pooler is None and not offset_distance: + fused = self._native_grid and self._pooler is None and not offset_distance + if fused: count = self._num_ray_samples - self._prepare_grid_publish( - {name: tex.reshape(tex.shape[0], count, tex.shape[-1]) for name, tex in textures.items()} - ) + samples = {name: tex.reshape(tex.shape[0], count, tex.shape[-1]) for name, tex in textures.items()} + self._grid_output = allocate_grid_outputs(samples, self._sampling_coords) + self._grid_indices = grid_sample_indices(self._sampling_coords) + self._prepare_grid_publish(samples) + published = self._grid_output + else: + if not self._native_grid: + uv_gpu = self._sample_uv.to(self._device) + self._extract_px = (uv_gpu[:, 0] * tw).long().clamp(0, tw - 1) + self._extract_py = (uv_gpu[:, 1] * th).long().clamp(0, th - 1) + self._allocate_foveated_buffers() + published = self._pooled_output if self._pooled_output is not None else self._foveated_output + if self._native_grid: + self._grid_output = allocate_grid_outputs(published, self._sampling_coords) + self._grid_indices = grid_sample_indices(self._sampling_coords) + published = self._grid_output + # ``CameraData.output`` is read-only, so its backing field is replaced. + self._data._output = proxy_outputs(published) + self._set_published_shape(self._data._output) + + def _near_clipping_distance(self, prim) -> float: + """Near clipping distance [m] of the camera, from its spawn configuration or else its prim.""" + if self.cfg.spawn is not None: + return float(self.cfg.spawn.clipping_range[0]) + from pxr import UsdGeom + + clipping = UsdGeom.Camera(prim).GetClippingRangeAttr().Get() + return float(clipping[0]) if clipping is not None else 0.0 def _allocate_foveated_buffers(self): - """Allocate ``(B, N_hi, 1, C)`` (and optionally ``(B, N_lo, 1, C)``) - per-data-type buffers from the captured ``_texture_output`` shapes. - - Called once from :meth:`_initialize_impl` after the parent ``Camera`` - has allocated the texture buffers. - """ - N = self._num_ray_samples + """Allocate (B, N_hi, 1, C) and, when pooling, (B, N_lo, 1, C) buffers from the texture buffers' shapes.""" has_rgba_alias = "rgba" in self._texture_output self._foveated_output = {} for name, buf in self._texture_output.items(): if name == "rgb" and has_rgba_alias: - continue # handled via rgba alias below - # IsaacLab 3.0: ``_data.output[name]`` is a ``ProxyArray`` - # wrapping a Warp array, not a torch tensor. ``buf.dtype`` is - # a Warp dtype (a Python class), incompatible with - # ``torch.zeros(dtype=...)``. Go through ``.torch`` to get - # a torch view whose dtype / device are torch-native. + continue # an alias of rgba, below + # Texture buffers are ProxyArrays; their Torch view carries the dtype and device. buf_t = buf.torch if hasattr(buf, "torch") else buf - C = buf_t.shape[-1] self._foveated_output[name] = torch.zeros( - (self._view.count, N, 1, C), - device=buf_t.device, - dtype=buf_t.dtype, - ).contiguous() + (self._view.count, self._num_ray_samples, 1, buf_t.shape[-1]), device=buf_t.device, dtype=buf_t.dtype + ) if "rgba" in self._foveated_output and "rgb" in self.cfg.data_types: self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] - if self._pooler is not None: - self._pooled_output = {} - needs_int_pooler = False - for name, buf in self._foveated_output.items(): - if name == "rgb" and has_rgba_alias: - continue - self._pooled_output[name] = torch.zeros( - (self._view.count, self._num_valid_samples, 1, buf.shape[-1]), - device=self._device, - dtype=buf.dtype, - ).contiguous() - if is_segmentation_output(name) and self.cfg.pool_int_mode != self.cfg.pool_mode: - needs_int_pooler = True - if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: - self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] - if needs_int_pooler: - self._pooler_int, _ = build_pooler( - self.cfg, - self._sampling_coords, - self._sampling_coords_highres, - device=str(self._device), - mode=self.cfg.pool_int_mode, - ) - logger.info( - "FoveatedRTXCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", - self.cfg.pool_mode, - self._pool_k, - self.cfg.pool_sample_cortex, - self._num_ray_samples, - self._num_valid_samples, - ) - else: + if self._pooler is None: self._pooled_output = None + return + self._pooled_output = {} + needs_int_pooler = False + for name, buf in self._foveated_output.items(): + if name == "rgb" and has_rgba_alias: + continue + self._pooled_output[name] = torch.zeros( + (self._view.count, self._num_valid_samples, 1, buf.shape[-1]), device=self._device, dtype=buf.dtype + ) + if is_segmentation_output(name) and self.cfg.pool_int_mode != self.cfg.pool_mode: + needs_int_pooler = True + if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: + self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] + if needs_int_pooler: + self._pooler_int, _ = build_pooler( + self.cfg, + self._sampling_coords, + self._sampling_coords_highres, + device=str(self._device), + mode=self.cfg.pool_int_mode, + ) + logger.info( + "FoveatedRTXCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", + self.cfg.pool_mode, + self._pool_k, + self.cfg.pool_sample_cortex, + self._num_ray_samples, + self._num_valid_samples, + ) # ------------------------------------------------------------------ - # Per-frame overrides + # Gaze and mount # ------------------------------------------------------------------ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: @@ -388,10 +317,35 @@ def set_world_poses(self, positions=None, orientations=None, env_ids=None, conve Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. """ super().set_world_poses(positions, orientations, env_ids, convention) + # A position-only move keeps the prims' gaze-turned orientation, and with it the saved mount. + if orientations is not None: + self._refresh_mount(env_ids) + + def set_world_poses_from_view(self, eyes, targets, env_ids=None): + """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. + + Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. + """ + super().set_world_poses_from_view(eyes, targets, env_ids) + ids = self._env_indices(env_ids) + # Rows whose eye equals their target are skipped by the base method and keep their mount. + moved = (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0 + self._refresh_mount(ids[moved]) + + def _env_indices(self, env_ids) -> torch.Tensor: + """The camera indices that ``env_ids`` selects, as a tensor.""" + every = torch.arange(self._view.count, device=self._device) + if env_ids is None or isinstance(env_ids, slice): + return every[slice(None) if env_ids is None else env_ids] + if isinstance(env_ids, wp.array): + env_ids = wp.to_torch(env_ids) + return torch.as_tensor(env_ids, device=self._device, dtype=torch.long).reshape(-1) + + def _refresh_mount(self, env_ids) -> None: + """Save the moved prims' orientations as their bare mounts and write the gaze on top of them again.""" if self._gaze_pose_reads_angles: - return # The pose update turned the new mount by the gaze. - # The prims of the moved environments now hold the bare mount pose, which is their new base. - ids = slice(None) if env_ids is None else torch.as_tensor(env_ids, device=self._device, dtype=torch.long) + return # The pose update turns the new mount by the gaze. + ids = self._env_indices(env_ids) _, local_orientation = self._view.get_local_poses() self._base_local_orientation[ids] = matrix_from_quat(local_orientation.torch[ids]) if self._gaze_rotation is not None: @@ -407,108 +361,48 @@ def _write_gaze_local_pose(self) -> None: local_orientation = quat_from_matrix(compose_rotations(self._base_local_orientation, relative)) self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f)) + # ------------------------------------------------------------------ + # Per-frame overrides + # ------------------------------------------------------------------ + def _update_buffers_impl(self, env_mask: wp.array): if not self._env_mask_has_any(env_mask): return - - # The renderer was bound to ``self._texture_output`` at create time - # via ``set_outputs`` and continues to write per-env pixel data into - # that dict regardless of what ``self._data.output`` currently - # references. ``self._data.output`` already points at the foveated - # (or pooled) buffer dict; the parent's ``render_into_camera`` only - # uses ``camera_data`` to populate ``camera_data.info`` (now a flat - # ``dict[str, Any]``), so we don't need to swap anything. + # The renderer writes the texture buffers bound at creation, whatever ``self._data.output`` publishes. super()._update_buffers_impl(env_mask) self.process_rendered_frame() def process_rendered_frame(self) -> None: - """Extract, mask and pool the frame written by scalar or batched rendering.""" + """Mask and publish the frame of the environments that scalar or batched rendering updated.""" if not self._env_mask_has_any(self._is_outdated): return if self._grid_publish: - self._publish_grid() + self._publish_grid(self._is_outdated) return - # Extract per-sample values from the per-env texture buffer. self._extract_foveated_samples() if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self._foveated_output: - # OVRTX's LUT range AOV measures from the near-clipped ray origin. - self._foveated_output["distance_to_camera"].add_(self.cfg.spawn.clipping_range[0]) + self._foveated_output["distance_to_camera"].add_(self._near_clip) mask_grid_samples(self._foveated_output, self._ray_coords) - self._apply_sensor_fov_mask() + self._apply_sensor_fov_mask(self._foveated_output) - # Optionally KNN-pool highres -> lowres samples. Integer-dtype - # outputs (segmentation class IDs) use the dedicated max-mode - # pooler so pooled values stay valid IDs. - if self._pooler is not None and self._pooled_output is not None: - has_rgba_alias = "rgba" in self._foveated_output + if self._pooled_output is not None: for name, hi in self._foveated_output.items(): - if name == "rgb" and has_rgba_alias: - continue # alias — refreshed below - lo = self._pooled_output[name] - use_int_pool = self._pooler_int is not None and is_segmentation_output(name) - pooler = self._pooler_int if use_int_pool else self._pooler - pooled = pool_hwc_buffer(pooler, hi.float()) - lo.copy_(pooled.to(lo.dtype)) - if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: - self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] + if name == "rgb" and "rgba" in self._foveated_output: + continue # rgba alias + self._pooled_output[name].copy_(self._pool_output(name, hi)) if self._native_grid: source = self._pooled_output if self._pooled_output is not None else self._foveated_output copy_grid_outputs(source, self._grid_output, self._grid_indices) def _extract_foveated_samples(self): """Extract per-sample values from rendered 2D textures into (B, N, 1, C) buffers.""" - px = self._extract_px - py = self._extract_py - has_rgba_alias = "rgba" in self._texture_output for name in self._texture_output: - if name == "rgb" and has_rgba_alias: - continue # handled via rgba alias below + if name == "rgb" and "rgba" in self._texture_output: + continue # rgba alias tex = self._texture_output[name] # (B, th, tw, C) fov = self._foveated_output[name] # (B, N, 1, C) tensor = tex.torch if hasattr(tex, "torch") else tex if self._native_grid: fov.copy_(tensor.reshape_as(fov)) else: - fov[:, :, 0, :] = tensor[:, py, px, :] - if "rgba" in self._foveated_output and "rgb" in self.cfg.data_types: - self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] - - def _apply_sensor_fov_mask(self) -> None: - """Zero the samples that fall outside the physical camera at the current gaze.""" - if not self.cfg.mask_to_sensor_fov: - return - batch_size = next(iter(self._foveated_output.values())).shape[0] - valid = self._gaze_validity(batch_size) - invalid = ~valid[:, :, None, None] - has_rgba_alias = "rgba" in self._foveated_output - for name, output in self._foveated_output.items(): - if name == "rgb" and has_rgba_alias: - continue - output.masked_fill_(invalid, 0) - self._sensor_fov_valid = valid - - # ------------------------------------------------------------------ - # Output helpers - # ------------------------------------------------------------------ - - @property - def sampling_coords(self): - """The :class:`SamplingCoords` used for ray generation.""" - return self._sampling_coords - - @property - def image_rotation_deg(self) -> float: - """Pre-render rotation (degrees, CCW around the optical axis) applied - to the per-ray sampling coordinates. ``0`` for the canonical mount.""" - return float(self.cfg.image_rotation_deg) - - @property - def num_valid_samples(self) -> int: - """Number of foveated sample points *N*.""" - return self._num_valid_samples - - @property - def sensor_fov_valid_fraction(self) -> torch.Tensor | None: - """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" - valid = getattr(self, "_sensor_fov_valid", None) - return None if valid is None else valid.float().mean(dim=1) + fov[:, :, 0, :] = tensor[:, self._extract_py, self._extract_px, :] diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py index da3441d1f829..93768f2cc613 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -176,23 +176,43 @@ def set_gaze_kernel( rotation[i] = gaze_rotation(angles) +@wp.func +def turn_pose( + i: wp.int32, + gaze: wp.mat33f, + basis: wp.mat33f, + to_opengl: wp.quatf, + to_world: wp.quatf, + to_ros: wp.quatf, + orientation: wp.array(dtype=wp.quatf), + mount: wp.array(dtype=wp.quatf), +): + """Record camera ``i``'s mount in the ROS convention, then turn its world orientation by its gaze.""" + base = orientation[i] + mount[i] = wp.normalize(base * to_ros) + orientation[i] = gaze_pose(base, gaze, basis, to_opengl, to_world) + + @wp.kernel(enable_backward=False) def apply_gaze_kernel( angles_deg: wp.array(dtype=wp.vec2f), basis: wp.mat33f, to_opengl: wp.quatf, to_world: wp.quatf, + to_ros: wp.quatf, mask: wp.array(dtype=wp.bool), use_mask: wp.int32, orientation: wp.array(dtype=wp.quatf), rotation: wp.array(dtype=wp.mat33f), + mount: wp.array(dtype=wp.quatf), ): - """Turn each camera's world orientation by its gaze, or only the masked ones, and record every gaze rotation.""" + """Turn each camera's world orientation by its gaze, or only the masked ones, record their mounts, and record + every gaze rotation.""" i = wp.tid() gaze = gaze_rotation(angles_deg[i]) rotation[i] = gaze if use_mask == 0 or mask[i]: - orientation[i] = gaze_pose(orientation[i], gaze, basis, to_opengl, to_world) + turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount) @wp.kernel(enable_backward=False) @@ -201,27 +221,36 @@ def apply_gaze_indexed_kernel( basis: wp.mat33f, to_opengl: wp.quatf, to_world: wp.quatf, + to_ros: wp.quatf, indices: wp.array(dtype=wp.int32), orientation: wp.array(dtype=wp.quatf), rotation: wp.array(dtype=wp.mat33f), + mount: wp.array(dtype=wp.quatf), ): - """Turn the indexed cameras' world orientations by their gaze, and record their gaze rotations.""" + """Turn the indexed cameras' world orientations by their gaze, and record their mounts and gaze rotations.""" i = indices[wp.tid()] gaze = gaze_rotation(angles_deg[i]) rotation[i] = gaze - orientation[i] = gaze_pose(orientation[i], gaze, basis, to_opengl, to_world) + turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount) + + +@wp.func +def sees(ray: wp.vec3f, gaze: wp.mat33f, frame: wp.mat33f, camera: CameraParams) -> wp.bool: + """Whether the physical camera sees a rendered ray (ROS frame) turned by a gaze; ``frame`` is the mount roll.""" + return project_direction(frame * gaze * wp.transpose(frame) * ray, camera)[2] > 0.5 @wp.kernel(enable_backward=False) def sensor_visibility_kernel( rays: wp.array(dtype=wp.vec3f), rotation: wp.array(dtype=wp.mat33f), + frame: wp.mat33f, camera: CameraParams, valid: wp.array2d(dtype=wp.bool), ): - """Whether the physical camera sees each canonical ray turned by each environment's gaze.""" + """Whether the physical camera sees each rendered ray turned by each environment's gaze.""" env, sample = wp.tid() - valid[env, sample] = project_direction(rotation[env] * rays[sample], camera)[2] > 0.5 + valid[env, sample] = sees(rays[sample], rotation[env], frame, camera) @wp.kernel(enable_backward=False) @@ -229,24 +258,28 @@ def publish_grid_kernel( source: wp.array3d(dtype=wp.uint8), indices: wp.array(dtype=wp.int32), footprint: wp.array(dtype=wp.bool), + updated: wp.array(dtype=wp.bool), rays: wp.array(dtype=wp.vec3f), rotation: wp.array(dtype=wp.mat33f), + frame: wp.mat33f, camera: CameraParams, mask_to_sensor: wp.int32, record_visible: wp.int32, visible: wp.array2d(dtype=wp.bool), target: wp.array3d(dtype=wp.uint8), ): - """Copy rendered samples into the upright grid, zeroing samples outside the footprint or, when masking, the - physical camera's view. + """Copy the updated environments' rendered samples into the upright grid, zeroing samples outside the footprint + or, when masking, the physical camera's view. ``source`` and ``target`` hold each sample's channels as raw bytes, so one kernel serves every output type. """ env, cell = wp.tid() + if not updated[env]: + return sample = indices[cell] keep = footprint[sample] if mask_to_sensor != 0: - seen = project_direction(rotation[env] * rays[sample], camera)[2] > 0.5 + seen = sees(rays[sample], rotation[env], frame, camera) if record_visible != 0: visible[env, sample] = seen keep = keep and seen diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index c4daa1bc8d93..93e4b7b9cc3c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -100,37 +100,127 @@ def build_highres_coords(cfg: FoveatedCameraCfg, matched_res: int, device: str) ) +MODAL_POOL_MODE = "mode" +"""Pooling mode that takes the most common neighbour value (see :func:`pool_segmentation_buffer`).""" + +# Upper bound on ``batch * outputs * k`` elements per modal-pooling chunk. Each chunk holds about ten +# int64 tensors of this size, so peak scratch memory stays near 300 MB regardless of the batch size. +_MODAL_CHUNK_ELEMENTS = 2**22 + + +class ModalPooler(torch.nn.Module): + """Modal pooler for segmentation outputs, built by :func:`build_pooler` with ``mode="mode"``. + + Holds the fixed neighbour table of a fovi pooler and pools by majority vote + (see :func:`pool_segmentation_buffer`). Like the fovi poolers, calling it + maps ``(B, C, N_hi)`` to ``(B, C, N_lo)``, so :func:`pool_hwc_buffer` also + accepts it, but only in the native dtype: casting IDs to float first loses + IDs above ``2**24``. + """ + + def __init__(self, neighbor_indices: torch.Tensor, num_inputs: int): + """Initialize the pooler. + + Args: + neighbor_indices: ``(k, N_lo)`` int64 input-sample indices of each output's neighbours, ordered by + tie-break preference (nearest first). The value ``num_inputs`` marks an excluded neighbour. + num_inputs: Number of input samples ``N_hi``. + """ + super().__init__() + self.num_inputs = num_inputs + self.register_buffer("neighbor_indices", neighbor_indices, persistent=False) + + @property + def k(self) -> int: + """Number of neighbour slots per output sample.""" + return self.neighbor_indices.shape[0] + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Pool ``(B, C, N_hi)`` values to ``(B, C, N_lo)`` by majority vote over each channel vector.""" + pooled = pool_segmentation_buffer(self, x.transpose(1, 2).unsqueeze(2)) + return pooled[:, :, 0, :].transpose(1, 2) + + def build_pooler( cfg: FoveatedCameraCfg, lowres: SamplingCoords, highres: SamplingCoords | None, device: str, mode: str | None = None, -) -> tuple[KNNPoolingLayer | GridPoolingLayer | None, int | None]: +) -> tuple[KNNPoolingLayer | GridPoolingLayer | ModalPooler | None, int | None]: """Build a retinal pooling layer. Both coord sets must already be on ``device``. If ``mode`` is None, uses ``cfg.pool_mode`` — the standard pooler for - floating-point outputs. Pass ``mode="max"`` (or similar) to build a - separate pooler for integer segmentation outputs. + floating-point outputs. ``mode="mode"`` (the default ``cfg.pool_int_mode``) + builds a :class:`ModalPooler` over the same neighbourhoods for segmentation + outputs; pool those with :func:`pool_segmentation_buffer`. Other modes are + passed to fovi (``"max"``, ``"avg"``, ``"sum"``, ``"gaussian"``). """ if highres is None: return None, None from fovi.arch.pooling import build_retinal_pooler - return build_retinal_pooler( + mode = mode if mode is not None else cfg.pool_mode + pooler, k = build_retinal_pooler( highres, lowres, k=cfg.pool_k, - mode=mode if mode is not None else cfg.pool_mode, + # The modal pooler only reuses the fovi neighbourhoods; "max" needs no Gaussian weights. + mode="max" if mode == MODAL_POOL_MODE else mode, device=device, sample_cortex=cfg.pool_sample_cortex, gauss_sigma=cfg.pool_gauss_sigma, ) + if mode == MODAL_POOL_MODE: + pooler = ModalPooler(segmentation_neighbor_indices(pooler), len(highres)) + return pooler, k + + +def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer | ModalPooler) -> torch.Tensor: + """Return a pooler's ``(k, N_lo)`` neighbour table in tie-break order. + + Entries are input-sample indices; ``N_hi`` (the number of input samples) + marks a neighbour excluded by the pooler (spatial padding or a masked input + sample), and every slot of a masked output sample is excluded. + + * :class:`KNNPoolingLayer`: its padded KNN indices, nearest neighbour first. + * :class:`GridPoolingLayer`: the samples in each pooling window (same + padding, stride and masks as the pooler), ordered by distance from the + window centre and then in row-major window order. + """ + from fovi.arch.knn import KNNPoolingLayer + from fovi.arch.pooling import GridPoolingLayer + + if isinstance(pooler, ModalPooler): + return pooler.neighbor_indices + if isinstance(pooler, KNNPoolingLayer): + return pooler.knn_indices_pad_token + if not isinstance(pooler, GridPoolingLayer): + raise TypeError(f"Modal pooling needs a KNN or grid pooler, got {type(pooler).__name__}") + + num_inputs = len(pooler.in_coords) + device = pooler.input_mask.device + # Pool sample indices (float64 is exact for any realistic count) with the pooler's own padding; + # -1 marks padding and masked samples. + grid = pooler.in_coords.as_grid(torch.arange(num_inputs, device=device, dtype=torch.float64)[None, None]) + grid = pooler._pad(torch.where(pooler.input_mask, grid, -1.0), -1.0) + side, stride = pooler.kernel_size, pooler.stride + windows = grid[0, 0].unfold(0, side, stride).unfold(1, side, stride) # (H_lo, W_lo, side, side) + windows = windows.flatten(-2).permute(2, 0, 1) # (k, H_lo, W_lo) + axis = torch.arange(side, device=device, dtype=torch.float64) - (side - 1) / 2 + radius = (axis[:, None].square() + axis[None, :].square()).flatten() + windows = windows[torch.sort(radius, stable=True).indices] + windows = torch.where(pooler.output_mask[0], windows, -1.0) + if not pooler.polar: + # Invert the upright Cartesian layout produced by ``as_grid``, as GridPoolingLayer.forward does. + windows = windows.flip(-2).transpose(-2, -1) + indices = windows.flatten(-2).long() + return torch.where(indices < 0, num_inputs, indices) def is_segmentation_output(name: str) -> bool: - """Whether a sensor output key should be pooled with ``pool_int_mode``. + """Whether a sensor output key should be pooled with ``pool_int_mode`` (modal pooling by default). Uses a key-name heuristic (``"segmentation" in name``) rather than dtype, since all IsaacLab segmentation variants — ``semantic_segmentation``, @@ -152,3 +242,82 @@ def pool_hwc_buffer(pooler: KNNPoolingLayer | GridPoolingLayer, buf: torch.Tenso x = buf[:, :, 0, :].transpose(1, 2).contiguous() # (B, C, N_hi) y = pooler(x) # (B, C, N_lo) return y.transpose(1, 2).unsqueeze(2).contiguous() # (B, N_lo, 1, C) + + +def pool_segmentation_buffer( + pooler: KNNPoolingLayer | GridPoolingLayer | ModalPooler, buf: torch.Tensor +) -> torch.Tensor: + """Pool a ``(B, N_hi, 1, C)`` segmentation buffer into ``(B, N_lo, 1, C)`` by majority vote. + + Each output sample takes the most common full channel vector among its + pooling neighbours (so neighbours ``[0, 0, 0]``, ``[0, 0, 0]``, + ``[0, 0, 1]`` give ``[0, 0, 0]``), keeping the buffer's dtype: values are + compared bitwise and copied from an input sample, never converted or mixed. + This holds for integer IDs of any width and for colorized RGBA vectors. + + Ties go to the value whose first occurrence comes earliest in the pooler's + neighbour order (see :func:`segmentation_neighbor_indices`; the nearest + neighbour wins for KNN pooling). Neighbours the pooler excludes do not + vote, and outputs without any valid neighbour are zero, as in fovi. + + Args: + pooler: A :class:`ModalPooler` from ``build_pooler(..., mode="mode")``, or a fovi KNN or grid pooler + whose neighbourhoods to use. + buf: ``(B, N_hi, 1, C)`` buffer of any dtype, on the pooler's device. + + Returns: + ``(B, N_lo, 1, C)`` pooled buffer with the dtype of ``buf``. + """ + B, N_hi, one, C = buf.shape + assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}" + indices = segmentation_neighbor_indices(pooler) # (k, N_lo), N_hi = excluded + k, N_lo = indices.shape + values = buf[:, :, 0, :].contiguous() # (B, N_hi, C) + # Equality keys, padded with one never-voting sample at index N_hi. + keys = torch.nn.functional.pad(_equality_keys(values), (0, 1)) # (B, N_hi + 1) + valid = (indices != N_hi).T # (N_lo, k) + table = indices.T # (N_lo, k) + slots = [] + for chunk in keys.split(max(1, _MODAL_CHUNK_ELEMENTS // max(1, N_lo * k))): + slots.append(_modal_slot(chunk[:, table], valid)) + slot = torch.cat(slots) # (B, N_lo); k where no neighbour is valid + has_value = slot < k + # (B, N_lo) input sample index; outputs without a value read sample 0 and are zeroed below. + source = table.gather(1, slot.clamp(max=k - 1).T).T.clamp(max=N_hi - 1) + pooled = values.gather(1, source.unsqueeze(-1).expand(-1, -1, C)) + pooled = torch.where(has_value.unsqueeze(-1), pooled, torch.zeros((), dtype=buf.dtype, device=buf.device)) + return pooled.unsqueeze(2) + + +def _equality_keys(values: torch.Tensor) -> torch.Tensor: + """Map ``(B, N, C)`` channel vectors to ``(B, N)`` int64 keys that are equal iff the vectors are bitwise equal. + + Vectors of at most 8 bytes are packed into the key directly; wider vectors + fall back to dense ranks from :func:`torch.unique`. + """ + B, N, _ = values.shape + raw = values.view(torch.uint8) if values.dtype != torch.bool else values.to(torch.uint8) + num_bytes = raw.shape[-1] + if num_bytes <= 8: + return torch.nn.functional.pad(raw, (0, 8 - num_bytes)).view(torch.int64).reshape(B, N) + return torch.unique(raw.reshape(B * N, num_bytes), dim=0, return_inverse=True)[1].reshape(B, N) + + +def _modal_slot(keys: torch.Tensor, valid: torch.Tensor) -> torch.Tensor: + """Pick the modal neighbour slot of ``(B, N_lo, k)`` keys; ``valid`` is the ``(N_lo, k)`` voting mask. + + Returns the ``(B, N_lo)`` earliest slot holding the most common valid key, + or ``k`` where no slot is valid. + """ + k = keys.shape[-1] + sorted_keys, order = torch.sort(keys, dim=-1) + # Label equal-key runs in sorted order, then count valid votes and find the earliest valid slot per run. + new_run = torch.ones_like(sorted_keys, dtype=torch.bool) + new_run[..., 1:] = sorted_keys[..., 1:] != sorted_keys[..., :-1] + run = new_run.cumsum(-1) - 1 + valid_sorted = valid.expand_as(order).gather(-1, order) + votes = torch.zeros_like(run).scatter_add_(-1, run, valid_sorted.long()) + earliest = torch.full_like(run, k).scatter_reduce_(-1, run, torch.where(valid_sorted, order, k), "amin") + # Most votes first, then earliest slot; runs without valid votes score zero. + best = (votes * (k + 1) + (k - earliest)).argmax(-1, keepdim=True) + return earliest.gather(-1, best).squeeze(-1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py deleted file mode 100644 index 02896f3b6672..000000000000 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/virtual_gaze.py +++ /dev/null @@ -1,269 +0,0 @@ -# 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 - -"""Virtual gaze: the retina turns inside a fixed physical camera.""" - -from __future__ import annotations - -import math -from collections.abc import Mapping, Sequence - -import torch -import warp as wp -from fovi.sensing.projection import angular_directions - -from .calibrated_geometry import convert_camera_frame_quaternion, resolve_camera_model -from .gaze_kernels import ( - CameraParams, - apply_gaze_indexed_kernel, - apply_gaze_kernel, - camera_params, - publish_grid_kernel, - record_launch, - sensor_visibility_kernel, - set_gaze_kernel, - torch_stream, - warp_stream, -) -from .native_grid import GRID_STYLE, native_grid_directions - - -class VirtualGaze: - """Gaze shared by the foveated camera backends. - - The camera prim stays where the scene puts it. Gaze turns the retina relative - to the optical axis of the physical camera it looks through. - """ - - _gaze_pose_reads_angles: bool = False - """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses when - the gaze is set. A writer of :meth:`gaze_angles_buffer` then needs no other launch.""" - - def gaze_angles_buffer(self) -> torch.Tensor: - """The camera's stored gaze angles [deg], shape (num_envs, 2). - - A writer that moves the gaze every step can update this buffer in place and pass it to - :meth:`set_gaze_angles`, which then copies nothing. Writes take effect when :meth:`set_gaze_angles` is called. - """ - if self._gaze_angles is None: - self._allocate_gaze(self._view.count, torch.device(self._device)) - return self._gaze_angles - - def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: - """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. - - Positive tilt looks up and positive pan looks left. Zero looks along the - optical axis. - - Args: - angles_deg: Gaze angles for every environment [deg], shape (num_envs, 2). - """ - stored = angles_deg is self._gaze_angles and angles_deg is not None - if stored and self._gaze_pose_reads_angles and self.cfg.update_latest_camera_pose: - # The next pose update reads the stored angles; nothing has to happen now. - return - angles = angles_deg if stored else angles_deg.detach().float().contiguous() - if ( - self._gaze_angles is None - or len(self._gaze_angles) != len(angles) - or self._gaze_angles.device != angles.device - ): - self._allocate_gaze(len(angles), angles.device) - # Callers usually pass the same buffer every step; record its launch once. - key = (angles.data_ptr(), angles.shape, angles.device) - if key != self._gaze_angles_key: - self._gaze_angles_key = key - self._set_gaze_launch = record_launch( - set_gaze_kernel, - len(angles), - [wp.from_torch(angles, dtype=wp.vec2f)], - [self._gaze_angles_wp, self._gaze_rotation_wp], - angles.device, - ) - self._set_gaze_launch.launch(warp_stream(angles.device)) - - def _allocate_gaze(self, count: int, device: torch.device) -> None: - """Allocate the stored gaze, on the optical axis, and its rotation.""" - self._gaze_angles = torch.zeros(count, 2, device=device) - self._gaze_rotation = torch.eye(3, device=device).repeat(count, 1, 1) - self._gaze_angles_wp = wp.from_torch(self._gaze_angles, dtype=wp.vec2f) - self._gaze_rotation_wp = wp.from_torch(self._gaze_rotation, dtype=wp.mat33f) - self._gaze_angles_key = None - self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} - self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=str(device)) - - def _apply_gaze_pose( - self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None - ) -> None: - """Turn the camera's world orientation by the stored gaze, and record the gaze rotations it uses.""" - if self._gaze_angles is None: - return - orientation = self._data.quat_w_world - orientation = orientation.warp if hasattr(orientation, "warp") else wp.from_torch(orientation, dtype=wp.quatf) - device = self._gaze_angles.device - frames = (self._gaze_angles_wp, *self._gaze_frames) - indexed = env_ids is not None and env_mask is None - if indexed and not isinstance(env_ids, wp.array): - env_ids = wp.from_torch(torch.as_tensor(env_ids, dtype=torch.int32, device=device).contiguous()) - # Every pose update writes the same pose buffer: for all environments, under the camera's update mask, or - # for the indexed ones, whose indices each call swaps in. - mode = "ids" if indexed else ("all" if env_mask is None else "mask") - launch, sources = self._gaze_pose_launches.get(mode, (None, None)) - if sources is None or sources[0] is not orientation or (mode == "mask" and sources[1] is not env_mask): - if indexed: - launch = record_launch( - apply_gaze_indexed_kernel, - len(env_ids), - [*frames, env_ids], - [orientation, self._gaze_rotation_wp], - device, - ) - else: - launch = record_launch( - apply_gaze_kernel, - len(self._gaze_angles), - [*frames, self._gaze_no_mask if env_mask is None else env_mask, int(env_mask is not None)], - [orientation, self._gaze_rotation_wp], - device, - ) - self._gaze_pose_launches[mode] = (launch, (orientation, env_mask)) - if indexed: - if len(env_ids) == 0: - return - launch.set_param_by_name("indices", env_ids) - launch.set_dim(len(env_ids)) - launch.launch(warp_stream(device)) - - def _update_camera_state( - self, - env_ids: wp.array | None = None, - env_mask: wp.array | None = None, - pos_src: wp.array | None = None, - quat_src: wp.array | None = None, - update_pose: bool = False, - frame_op: int = 0, - ): - """Update the camera state; when the pose update turns the gaze, turn freshly read poses before the renderer - sees them.""" - super()._update_camera_state(env_ids, env_mask, pos_src, quat_src, update_pose, frame_op) - if update_pose and self._gaze_pose_reads_angles: - self._apply_gaze_pose(env_ids, env_mask) - - def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: - """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for - :func:`publish_grid_kernel`.""" - views = [] - for name, source in sources.items(): - if name == "rgb" and "rgba" in sources: - continue - target = self._grid_output[name].view(source.shape[0], -1, source.shape[-1]) - views.append((wp.from_torch(source.view(torch.uint8)), wp.from_torch(target.view(torch.uint8)))) - self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous()) - self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous()) - num_envs = views[0][1].shape[0] - if self.cfg.mask_to_sensor_fov: - identity = self._gaze_identity.expand(num_envs, -1, -1).contiguous() - self._sensor_fov_valid_buffer = torch.zeros( - num_envs, len(self._gaze_rays), dtype=torch.bool, device=self._device - ) - self._grid_sensor = ( - wp.from_torch(self._gaze_rays, dtype=wp.vec3f), - wp.from_torch(identity, dtype=wp.mat33f), - self._gaze_camera, - wp.from_torch(self._sensor_fov_valid_buffer), - ) - else: - # Placeholders: the kernel reads none of these without the sensor mask. - self._grid_sensor = ( - wp.zeros(1, dtype=wp.vec3f, device=self._device), - wp.zeros(1, dtype=wp.mat33f, device=self._device), - CameraParams(), - wp.zeros((1, 1), dtype=wp.bool, device=self._device), - ) - self._grid_publish = views - self._grid_launches = None - - def _publish_grid(self) -> None: - """Mask and lay out every output in one launch each; the result equals masking, then copying to the grid.""" - mask = self.cfg.mask_to_sensor_fov - rays, identity, camera, visible = self._grid_sensor - rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation_wp - if self._grid_launches is None or self._grid_launches[0] is not rotation: - launches = [ - record_launch( - publish_grid_kernel, - (target.shape[0], target.shape[1]), - [ - source, - self._grid_indices_wp, - self._grid_footprint_wp, - rays, - rotation, - camera, - int(mask), - int(mask and index == 0), - visible, - ], - [target], - self._device, - ) - for index, (source, target) in enumerate(self._grid_publish) - ] - self._grid_launches = (rotation, launches) - stream = warp_stream(self._device) - for launch in self._grid_launches[1]: - launch.launch(stream) - if mask: - self._sensor_fov_valid = self._sensor_fov_valid_buffer - - def _gaze_validity(self, batch_size: int) -> torch.Tensor: - """Return which samples the physical camera sees at the current gaze, shape (batch_size, num_samples).""" - if self._gaze_rotation is None: - rotation = self._gaze_identity.expand(batch_size, -1, -1).contiguous() - rotation_wp = wp.from_torch(rotation, dtype=wp.mat33f) - else: - rotation, rotation_wp = self._gaze_rotation, self._gaze_rotation_wp - device = rotation.device - rays_wp = self._gaze_rays_wp.get(device) - if rays_wp is None: - rays_wp = self._gaze_rays_wp[device] = wp.from_torch(self._gaze_rays.to(device), dtype=wp.vec3f) - valid = torch.empty(batch_size, len(self._gaze_rays), dtype=torch.bool, device=device) - # A receptive field can overlap the sensor even when its center is outside it. - with torch_stream(device): - wp.launch( - sensor_visibility_kernel, - dim=valid.shape, - inputs=[rays_wp, rotation_wp, self._gaze_camera], - outputs=[wp.from_torch(valid, dtype=wp.bool)], - ) - return valid - - def _initialize_gaze(self) -> None: - self._camera_model = resolve_camera_model(self.cfg) - self._gaze_camera = camera_params(self._camera_model) - coords = self._sampling_coords_highres or self._sampling_coords - if coords.style == GRID_STYLE: - self._gaze_rays = native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1)) - else: - self._gaze_rays = angular_directions(coords.cartesian, coords.fov) - self._gaze_rays = self._gaze_rays.float().contiguous() - self._gaze_rays_wp: dict[torch.device, wp.array] = {} - # No gaze until one is set: the camera looks along its optical axis untouched. - self._gaze_angles = None - self._gaze_rotation = None - device = self._gaze_rays.device - self._gaze_identity = torch.eye(3, device=device) - angle = math.radians(self.cfg.image_rotation_deg) - c, s = math.cos(angle), math.sin(angle) - # Gaze is defined in the upright image frame; rays include mount roll. - self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) - identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device) - to_opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl")[0].tolist() - to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0].tolist() - self._gaze_frames = ( - wp.mat33f(*self._gaze_basis.flatten().tolist()), - wp.quatf(*to_opengl), - wp.quatf(*to_world), - ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py index cd7ae031a24d..65ea5ba2bdf6 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py @@ -54,7 +54,7 @@ def select_presets(options: PresetCfg, names) -> PresetCfg: @configclass class GazeObservationsCfg(ObservationGroupCfg): - """The gaze and its velocity, in field radii.""" + """The gaze, in field radii, and its velocity, in field radii per second.""" state = ObservationTermCfg(func=mdp.gaze_state) diff --git a/source/isaaclab_fovi/test/_check_imports.py b/source/isaaclab_fovi/test/_check_imports.py index f1c4a68024d9..104d7dd17c83 100644 --- a/source/isaaclab_fovi/test/_check_imports.py +++ b/source/isaaclab_fovi/test/_check_imports.py @@ -41,7 +41,6 @@ def find_spec( for module in ( "isaaclab_fovi", "isaaclab_fovi.sensors", - "isaaclab_fovi.sensors.foveated_rays", "isaaclab_fovi.sensors.pooling", "fovi.sensing.coords", "fovi.arch.knn", diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py index ad2c0ca29e57..c1ca45f12a2e 100644 --- a/source/isaaclab_fovi/test/foveated_render_cases.py +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -118,7 +118,7 @@ def _render( """Render ground distance for one environment per row of gaze angles (tilt, pan) [deg]. With ``moved_mount`` (eye, target), the last environment's camera is moved there after its gaze is set. - With ``later_gaze``, the gaze changes to it after the first frames, and the camera renders again. + With ``later_gaze``, the gaze changes to it after the first frames, and the camera renders one more frame. Returns: The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid @@ -149,10 +149,10 @@ def _render( sim.step() camera.update(sim.get_physics_dt(), force_recompute=True) if later_gaze is not None: + # The first frame rendered after the command must already show the new gaze. camera.set_gaze_angles(later_gaze.to(sim.device)) - for _ in range(WARMUP_STEPS): - sim.step() - camera.update(sim.get_physics_dt(), force_recompute=True) + sim.step() + camera.update(sim.get_physics_dt(), force_recompute=True) distance = camera.data.output["distance_to_camera"].torch[..., 0].detach().cpu().float().clone() coords = camera.sampling_coords field = coords.as_grid(coords.cartesian, sample_dim=0).detach().cpu().float().clone() diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 069d9cfcbfce..25f1f644be11 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -10,13 +10,7 @@ import warp as wp from fovi.sensing.projection import CameraModel from isaaclab_fovi.mdp import angles_to_direction, clamp_gaze, direction_to_angles -from isaaclab_fovi.mdp.gaze import ( - gaze_reset_kernel, - gaze_step_kernel, - teacher_block_dim, - teacher_kernel, - teacher_labels_kernel, -) +from isaaclab_fovi.mdp.gaze import gaze_reset_kernel, gaze_step_kernel, teacher_block_dim, teacher_labels_kernel from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream from rsl_rl.models import MLPModel @@ -25,6 +19,8 @@ from isaaclab.utils.math import quat_apply, quat_apply_inverse +pytestmark = pytest.mark.kitless + NUM_ENVS = 64 STEPS = 8 DEVICES = ["cpu", "cuda:0"] if torch.cuda.is_available() else ["cpu"] @@ -44,52 +40,6 @@ def test_clamp_gaze_is_radial(): torch.testing.assert_close(clamp_gaze(gaze, 1.0), torch.tensor([[0.3, 0.4], [0.6, 0.8]])) -def test_teacher_kernel_matches_the_torch_teacher(): - camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5), distortion=(-0.1, 0.02, 0.0, 0.0)) - field_radius, step, limit = 30.0, 0.1, 1.0 - generator = torch.Generator().manual_seed(3) - count = 4096 - mount = torch.nn.functional.normalize(torch.randn(4, generator=generator), dim=0) - positions = torch.randn(count, 3, generator=generator) - # Points mostly in front of the camera, spread across and beyond its field of view. - lateral = torch.randn(count, 2, generator=generator) * 0.6 - local = torch.cat((lateral, torch.rand(count, 1, generator=generator) + 0.2), -1) - points = positions + quat_apply(mount.expand(count, -1), local) - gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.7 - - # The torch teacher the kernel replaces. - direction = torch.nn.functional.normalize(quat_apply_inverse(mount.expand(count, -1), points - positions), dim=-1) - desired = direction_to_angles(direction) / field_radius - expected_valid = camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) - expected_action = torch.where(expected_valid[:, None], ((desired - gaze) / step).clamp(-1, 1), 0.0) - looking = angles_to_direction(gaze * field_radius) - expected_error = torch.atan2(torch.cross(looking, direction, dim=-1).norm(dim=-1), (looking * direction).sum(-1)) - - action = torch.empty(count, 2) - valid = torch.empty(count, dtype=torch.bool) - error = torch.empty(count) - with torch_stream("cpu"): - wp.launch( - teacher_kernel, - dim=count, - inputs=[ - wp.from_torch(points.contiguous(), dtype=wp.vec3f), - wp.from_torch(positions.contiguous(), dtype=wp.vec3f), - wp.quatf(*mount.tolist()), - wp.from_torch(gaze.contiguous(), dtype=wp.vec2f), - field_radius, - step, - limit, - camera_params(camera), - ], - outputs=[wp.from_torch(action, dtype=wp.vec2f), wp.from_torch(valid), wp.from_torch(error)], - ) - agree = valid == expected_valid - assert agree.float().mean() > 0.999 and expected_valid.any() and (~expected_valid).any() - torch.testing.assert_close(action[agree], expected_action[agree], atol=1e-4, rtol=0) - torch.testing.assert_close(error, expected_error.rad2deg(), atol=1e-3, rtol=0) - - def test_gaze_step_kernel_matches_the_torch_update(): generator = torch.Generator().manual_seed(4) count, step, limit, dt, radius = 2048, 0.1, 1.0, 1 / 60, 23.6 @@ -98,45 +48,48 @@ def test_gaze_step_kernel_matches_the_torch_update(): expected = clamp_gaze(gaze + actions.clamp(-1, 1) * step, limit) expected_velocity = (expected - gaze) / dt - velocity, angles = torch.empty_like(gaze), torch.empty_like(gaze) - state = torch.empty(count, 4) + state = torch.cat((gaze, torch.randn(count, 2, generator=generator)), dim=-1) + angles = torch.empty_like(gaze) with torch_stream("cpu"): wp.launch( gaze_step_kernel, dim=count, inputs=[ - *(wp.from_torch(buffer, dtype=wp.vec2f) for buffer in (actions, gaze, velocity, angles)), + wp.from_torch(actions, dtype=wp.vec2f), wp.from_torch(state, dtype=wp.vec4f), + wp.from_torch(angles, dtype=wp.vec2f), step, limit, dt, radius, ], ) - torch.testing.assert_close(gaze, expected, atol=1e-6, rtol=1e-6) - torch.testing.assert_close(velocity, expected_velocity, atol=1e-3, rtol=1e-5) + torch.testing.assert_close(state[:, :2], expected, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(state[:, 2:], expected_velocity, atol=1e-3, rtol=1e-5) torch.testing.assert_close(angles, expected * radius, atol=1e-5, rtol=1e-6) - torch.testing.assert_close(state, torch.cat((gaze, velocity), dim=-1)) @pytest.mark.parametrize("device", DEVICES) -def test_teacher_labels_kernel_matches_the_torch_labels(device): - camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5)) +@pytest.mark.parametrize("tracked", [False, True]) +def test_teacher_labels_kernel_matches_the_torch_labels(device, tracked): + camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5), distortion=(-0.1, 0.02, 0.0, 0.0)) field_radius, step, limit = 30.0, 0.1, 1.0 generator = torch.Generator().manual_seed(5) count = 4099 - mount = torch.nn.functional.normalize(torch.randn(4, generator=generator), dim=0) + # A fixed mount is shared; a tracked one differs per camera, as on a moving head. + mounts = torch.nn.functional.normalize(torch.randn(count if tracked else 1, 4, generator=generator), dim=-1) + mount = mounts.expand(count, -1) positions = torch.randn(count, 3, generator=generator) lateral = torch.randn(count, 2, generator=generator) * 0.6 local = torch.cat((lateral, torch.rand(count, 1, generator=generator) + 0.2), -1) - targets = positions + quat_apply(mount.expand(count, -1), local) + targets = positions + quat_apply(mount, local) orientations = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1) offset = torch.tensor([0.0, 0.0, 0.3]) gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.7 # The torch path the kernel replaces: entity_point, then the teacher, then the labels and logs. points = targets + quat_apply(orientations, offset.expand(count, -1)) - direction = torch.nn.functional.normalize(quat_apply_inverse(mount.expand(count, -1), points - positions), dim=-1) + direction = torch.nn.functional.normalize(quat_apply_inverse(mount, points - positions), dim=-1) desired = direction_to_angles(direction) / field_radius valid = camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) action = torch.where(valid[:, None], ((desired - gaze) / step).clamp(-1, 1), 0.0) @@ -157,7 +110,8 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device): wp.vec3f(*offset.tolist()), 1, wp.from_torch(positions.to(device), dtype=wp.vec3f), - wp.quatf(*mount.tolist()), + wp.from_torch(mounts.to(device), dtype=wp.quatf), + int(tracked), wp.from_torch(gaze.to(device), dtype=wp.vec2f), field_radius, step, @@ -181,16 +135,13 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device): def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): count, radius = 10, 23.6 generator = torch.Generator().manual_seed(6) - gaze, velocity, angles, state = (torch.randn(count, size, generator=generator) for size in (2, 2, 2, 4)) + angles, state = (torch.randn(count, size, generator=generator) for size in (2, 4)) selected = torch.arange(count) if ids is None else torch.tensor(ids) start = torch.randn(len(selected), 2, generator=generator) if random_start else torch.zeros(len(selected), 2) - expected_gaze, expected_velocity = gaze.clone(), velocity.clone() expected_angles, expected_state = angles.clone(), state.clone() - # The torch reset the kernel replaces. - expected_gaze[selected] = start - expected_velocity[selected] = 0.0 - expected_angles[selected] = expected_gaze[selected] * radius - expected_state[selected] = torch.cat((expected_gaze[selected], expected_velocity[selected]), dim=-1) + # The torch reset the kernel replaces: the gaze at its start, at rest. + expected_state[selected] = torch.cat((start, torch.zeros_like(start)), dim=-1) + expected_angles[selected] = start * radius with torch_stream("cpu"): wp.launch( @@ -203,15 +154,10 @@ def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): int(random_start), radius, ], - outputs=[ - *(wp.from_torch(buffer, dtype=wp.vec2f) for buffer in (gaze, velocity, angles)), - wp.from_torch(state, dtype=wp.vec4f), - ], + outputs=[wp.from_torch(angles, dtype=wp.vec2f), wp.from_torch(state, dtype=wp.vec4f)], ) - for actual, expected in zip( - (gaze, velocity, angles, state), (expected_gaze, expected_velocity, expected_angles, expected_state) - ): - torch.testing.assert_close(actual, expected, atol=0, rtol=0) + torch.testing.assert_close(angles, expected_angles, atol=0, rtol=0) + torch.testing.assert_close(state, expected_state, atol=0, rtol=0) def test_gaze_loss_ignores_invalid_labels(): @@ -223,19 +169,31 @@ def test_gaze_loss_ignores_invalid_labels(): assert torch.isfinite(mean.grad).all() and not mean.grad[1].any() -def _algorithm() -> tuple[GazeSupervisedPPO, TensorDict]: +def _algorithm(oracle_loss_coef: float = 1.0, with_labels: bool = True) -> tuple[GazeSupervisedPPO, TensorDict]: torch.manual_seed(0) labels = torch.rand(NUM_ENVS, 3) * 2 - 1 labels[:, 2] = (torch.arange(NUM_ENVS) % 4 != 0).float() labels[labels[:, 2] == 0, :2] = float("nan") - obs = TensorDict({"policy": torch.randn(NUM_ENVS, 6), "oracle": labels}, batch_size=[NUM_ENVS]) - groups = {"actor": ["policy"], "critic": ["policy"]} + groups = {"policy": torch.randn(NUM_ENVS, 6)} | ({"oracle": labels} if with_labels else {}) + obs = TensorDict(groups, batch_size=[NUM_ENVS]) + model_groups = {"actor": ["policy"], "critic": ["policy"]} distribution = {"class_name": "GaussianDistribution", "init_std": 1.0} - actor = MLPModel(obs, groups, "actor", 3, hidden_dims=[32], distribution_cfg=distribution) - critic = MLPModel(obs, groups, "critic", 1, hidden_dims=[32]) + actor = MLPModel(obs, model_groups, "actor", 3, hidden_dims=[32], distribution_cfg=distribution) + critic = MLPModel(obs, model_groups, "critic", 1, hidden_dims=[32]) storage = RolloutStorage("rl", NUM_ENVS, STEPS, obs, [3], "cpu") settings = dict(num_learning_epochs=4, num_mini_batches=4, learning_rate=3e-3, schedule="fixed", device="cpu") - return GazeSupervisedPPO(actor, critic, storage, **settings), obs + return GazeSupervisedPPO(actor, critic, storage, oracle_loss_coef=oracle_loss_coef, **settings), obs + + +def _train(algorithm: GazeSupervisedPPO, obs: TensorDict, iterations: int) -> dict[str, float]: + for _ in range(iterations): + for _ in range(STEPS): + with torch.inference_mode(): + algorithm.act(obs) + algorithm.process_env_step(obs, torch.zeros(NUM_ENVS), torch.zeros(NUM_ENVS), {}) + algorithm.compute_returns(obs) + losses = algorithm.update() + return losses def test_update_pulls_the_gaze_toward_the_teacher(): @@ -248,13 +206,14 @@ def distance() -> float: return float((mean - obs["oracle"][:, :2])[valid].norm(dim=-1).mean()) before = distance() - for _ in range(40): - for _ in range(STEPS): - with torch.inference_mode(): - algorithm.act(obs) - algorithm.process_env_step(obs, torch.zeros(NUM_ENVS), torch.zeros(NUM_ENVS), {}) - algorithm.compute_returns(obs) - losses = algorithm.update() + losses = _train(algorithm, obs, 40) assert losses["oracle_valid"] == pytest.approx(0.75) assert all(torch.isfinite(p).all() for p in algorithm.actor.parameters()) assert distance() < 0.7 * before + + +def test_zero_coefficient_trains_plain_ppo_without_labels(): + algorithm, obs = _algorithm(oracle_loss_coef=0.0, with_labels=False) + losses = _train(algorithm, obs, 2) + assert losses["oracle"] == 0.0 and losses["oracle_valid"] == 0.0 + assert all(torch.isfinite(p).all() for p in algorithm.actor.parameters()) diff --git a/source/isaaclab_fovi/test/test_backend_dispatch.py b/source/isaaclab_fovi/test/test_backend_dispatch.py index e91fa39b2b02..497abec2bb22 100644 --- a/source/isaaclab_fovi/test/test_backend_dispatch.py +++ b/source/isaaclab_fovi/test/test_backend_dispatch.py @@ -8,9 +8,9 @@ from dataclasses import dataclass import pytest -from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg, FoveatedNewtonCamera, FoveatedRTXCamera +from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg -from isaaclab.sensors.camera import Camera +pytestmark = pytest.mark.kitless @dataclass @@ -32,15 +32,3 @@ def test_unknown_renderer_fails_explicitly() -> None: cfg = CameraSelection(RendererSelection("unknown")) with pytest.raises(ValueError, match="Unsupported foveated renderer"): FoveatedCamera(cfg) - - -@pytest.mark.parametrize( - ("renderer_type", "implementation"), - [("newton_warp", FoveatedNewtonCamera), ("isaac_rtx", FoveatedRTXCamera), ("ovrtx", FoveatedRTXCamera)], -) -def test_renderer_selects_implementation(renderer_type: str, implementation: type, monkeypatch) -> None: - # The camera is allocated but never initialized, so it has nothing to release. - monkeypatch.setattr(Camera, "__del__", lambda self: None) - camera = FoveatedCamera.__new__(FoveatedCamera, CameraSelection(RendererSelection(renderer_type))) - assert type(camera) is implementation - assert isinstance(camera, FoveatedCamera) diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py index 0051183504a9..2edbe3acda5e 100644 --- a/source/isaaclab_fovi/test/test_camera_cfg.py +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -19,6 +19,8 @@ PinholeCameraCfg, ) +pytestmark = pytest.mark.kitless + CAMERA_MODEL = {"model": "pinhole", "image_size": (480, 640), "intrinsics": (550.0, 550.0, 319.5, 239.5)} diff --git a/source/isaaclab_fovi/test/test_gaze_kernels.py b/source/isaaclab_fovi/test/test_gaze_kernels.py index 6f485091b91c..718b92d9c127 100644 --- a/source/isaaclab_fovi/test/test_gaze_kernels.py +++ b/source/isaaclab_fovi/test/test_gaze_kernels.py @@ -20,17 +20,12 @@ set_gaze_kernel, torch_stream, ) -from isaaclab_fovi.sensors.native_grid import ( - GRID_STYLE, - allocate_grid_outputs, - copy_grid_outputs, - grid_sample_indices, - mask_grid_samples, - native_grid_directions, -) +from isaaclab_fovi.sensors.native_grid import GRID_STYLE, grid_sample_indices, native_grid_directions from isaaclab.utils.math import matrix_from_quat, quat_from_matrix +pytestmark = pytest.mark.kitless + DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" wp.init() @@ -92,9 +87,15 @@ def _set_gaze(angles: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: def _gaze_frames(basis: torch.Tensor) -> list: identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=DEVICE) - to_opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl")[0] + to_opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl") to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0] - return [wp.mat33f(*basis.flatten().tolist()), wp.quatf(*to_opengl.tolist()), wp.quatf(*to_world.tolist())] + to_ros = convert_camera_frame_quaternion(to_opengl, origin="opengl", target="ros")[0] + return [ + wp.mat33f(*basis.flatten().tolist()), + wp.quatf(*to_opengl[0].tolist()), + wp.quatf(*to_world.tolist()), + wp.quatf(*to_ros.tolist()), + ] @pytest.mark.parametrize("selection", ["all", "mask", "indices"]) @@ -123,8 +124,13 @@ def test_gaze_kernels_match_the_torch_composition(selection): selected = torch.arange(count, device=DEVICE) % 3 == 0 orientation = base.clone() rotation = torch.zeros(count, 3, 3, device=DEVICE) + mount = torch.zeros(count, 4, device=DEVICE) inputs = [wp.from_torch(angles, dtype=wp.vec2f), *_gaze_frames(basis)] - outputs = [wp.from_torch(orientation, dtype=wp.quatf), wp.from_torch(rotation, dtype=wp.mat33f)] + outputs = [ + wp.from_torch(orientation, dtype=wp.quatf), + wp.from_torch(rotation, dtype=wp.mat33f), + wp.from_torch(mount, dtype=wp.quatf), + ] with torch_stream(DEVICE): if selection == "indices": ids = wp.from_torch(torch.nonzero(selected).flatten().to(torch.int32)) @@ -137,6 +143,12 @@ def test_gaze_kernels_match_the_torch_composition(selection): matrix_from_quat(orientation[turned]), matrix_from_quat(expected[turned]), atol=1e-5, rtol=0 ) torch.testing.assert_close(orientation[~turned], base[~turned], atol=0, rtol=0) + # The turned cameras record their mount before the gaze, in the ROS convention. + ros = convert_camera_frame_quaternion( + convert_camera_frame_quaternion(base, origin="world", target="opengl"), origin="opengl", target="ros" + ) + torch.testing.assert_close(matrix_from_quat(mount[turned]), matrix_from_quat(ros[turned]), atol=1e-5, rtol=0) + assert not mount[~turned].any() # Every environment's rotation is recorded, except that the indexed kernel touches only its own. recorded = selected if selection == "indices" else torch.ones_like(selected) torch.testing.assert_close(rotation[recorded], set_rotation[recorded], atol=0, rtol=0) @@ -162,20 +174,23 @@ def test_publish_kernel_matches_masking_then_copying_to_the_grid(): "rgba": torch.randint(1, 255, (6, count, 1, 4), generator=generator, dtype=torch.uint8).to(DEVICE), "depth": (torch.rand(6, count, 1, 1, generator=generator) + 0.5).to(DEVICE), } - indices = grid_sample_indices(coords) valid = camera.project(rays @ rotation.transpose(-1, -2))[1] - - # The sequence the kernel replaces: footprint mask, sensor mask, then the grid layout. - expected = {name: value.clone() for name, value in outputs.items()} - mask_grid_samples(expected, coords) - for value in expected.values(): - value.masked_fill_(~valid[:, :, None, None], 0) - expected_grid = allocate_grid_outputs(expected, coords) - copy_grid_outputs(expected, expected_grid, indices) + # Environments 1 and 4 were not rendered this frame and keep their previous image. + updated = torch.tensor([True, False, True, True, False, True], device=DEVICE) + + # The sequence the kernel replaces: footprint mask, sensor mask, then the upright layout. The layout comes from + # fovi's own grid reshaping rather than the index permutation the kernel uses. + keep = valid & coords.valid_mask[None] + expected_grid = { + name: coords.as_grid(value.squeeze(2) * keep[..., None], sample_dim=1) for name, value in outputs.items() + } + indices = grid_sample_indices(coords).to(torch.int32).contiguous() visible = torch.zeros(6, count, dtype=torch.bool, device=DEVICE) + identity = wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) for name, value in outputs.items(): - target = torch.zeros_like(expected_grid[name]) + previous = torch.full_like(expected_grid[name], 7) + target = previous.clone() source = value.squeeze(2) with torch_stream(DEVICE): wp.launch( @@ -183,10 +198,12 @@ def test_publish_kernel_matches_masking_then_copying_to_the_grid(): dim=(6, count), inputs=[ wp.from_torch(source.view(torch.uint8)), - wp.from_torch(indices.to(torch.int32).contiguous()), + wp.from_torch(indices), wp.from_torch(coords.valid_mask.contiguous()), + wp.from_torch(updated), wp.from_torch(rays, dtype=wp.vec3f), wp.from_torch(rotation, dtype=wp.mat33f), + identity, camera_params(camera), 1, int(name == "rgba"), @@ -195,7 +212,9 @@ def test_publish_kernel_matches_masking_then_copying_to_the_grid(): outputs=[wp.from_torch(target.view(6, count, -1).view(torch.uint8))], ) # Float32 rounding may flip a sample on the image edge, nothing more. - same = (target == expected_grid[name]).all(-1) + same = (target[updated] == expected_grid[name][updated]).all(-1) assert same.float().mean() > 0.999 - assert (visible == valid).float().mean() > 0.999 + assert torch.equal(target[~updated], previous[~updated]) + assert (visible[updated] == valid[updated]).float().mean() > 0.999 + assert not visible[~updated].any() assert valid.any() and (~valid).any() diff --git a/source/isaaclab_fovi/test/test_lens_schema.py b/source/isaaclab_fovi/test/test_lens_schema.py index 3dc0b748ccef..3bf248938c7c 100644 --- a/source/isaaclab_fovi/test/test_lens_schema.py +++ b/source/isaaclab_fovi/test/test_lens_schema.py @@ -14,6 +14,8 @@ from pxr import UsdGeom # noqa: E402 +pytestmark = pytest.mark.kitless + def test_lut_schema_has_explicit_model_and_assets_after_export() -> None: stage = Usd.Stage.CreateInMemory() diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py index 83e669eae964..034d89a272f1 100644 --- a/source/isaaclab_fovi/test/test_native_grid.py +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -23,6 +23,11 @@ unbounded_angular_radius, ) +pytestmark = pytest.mark.kitless + +# Each footprint and each sensor roll once; the inverse path does not depend on the grid size. +FOOTPRINT_ROTATIONS = [("circular", 0.0), ("square", 37.0), ("wang", 180.0)] + def make_coords(resolution: int = 64, coverage: str = "circular", field: str = "spherical") -> SamplingCoords: fov = 80.0 if coverage == "wang" else 170.0 @@ -37,21 +42,53 @@ def make_coords(resolution: int = 64, coverage: str = "circular", field: str = " ) -@pytest.mark.parametrize("resolution", [64, 128]) -@pytest.mark.parametrize("rotation", [0.0, 180.0, 37.0]) -@pytest.mark.parametrize("coverage", ["circular", "square", "wang"]) -def test_analytic_inverse_returns_every_native_texel(resolution, rotation, coverage): - coords = make_coords(resolution, coverage) - rays = native_grid_directions(coords, image_rotation_deg=rotation) - uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) +def texel_centers(resolution: int) -> torch.Tensor: + """Native texture UV of each canonical sample: columns follow native x, rows native y.""" axis = (torch.arange(resolution) + 0.5) / resolution row, col = torch.meshgrid(axis, axis, indexing="ij") - expected = torch.stack((col, row), -1).reshape(-1, 2) + return torch.stack((col, row), -1).reshape(-1, 2) + + +def spherical_rays(visual: torch.Tensor, fov_deg: float, rotation_deg: float = 0.0) -> torch.Tensor: + """OpenGL rays for visual-chart points inside the nominal field, where angle is linear in radius.""" + visual = visual.to(torch.float64) + theta = torch.linalg.vector_norm(visual, dim=-1) * math.radians(fov_deg) / 2 + phi = torch.atan2(visual[..., 1], visual[..., 0]) + math.radians(rotation_deg) + return torch.stack((theta.sin() * phi.cos(), theta.sin() * phi.sin(), -theta.cos()), -1) + + +@pytest.mark.parametrize(("coverage", "rotation"), FOOTPRINT_ROTATIONS) +def test_analytic_inverse_returns_every_native_texel(coverage, rotation): + coords = make_coords(64, coverage) + rays = native_grid_directions(coords, image_rotation_deg=rotation) + uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) assert valid.all() - torch.testing.assert_close(uv, expected, atol=2e-6, rtol=0) + torch.testing.assert_close(uv, texel_centers(64), atol=2e-6, rtol=0) torch.testing.assert_close(rays.norm(dim=-1), torch.ones(len(coords)), atol=1e-6, rtol=0) +@pytest.mark.parametrize(("coverage", "rotation"), FOOTPRINT_ROTATIONS) +def test_inverse_maps_independent_rays_to_their_texels(coverage, rotation): + coords = make_coords(64, coverage) + half_fov = math.radians(coords.fov) / 2 + # Rays through Fovi's own sample positions inside the nominal field land on those samples' texels. + inside = torch.linalg.vector_norm(coords.cartesian, dim=-1) <= 1 + rays = spherical_rays(coords.cartesian[inside], coords.fov, rotation) + uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) + assert inside.sum() > len(coords) // 2 + assert valid.all() + torch.testing.assert_close(uv, texel_centers(64)[inside], atol=2e-6, rtol=0) + # The optical axis is the texture centre and the nominal rim along each rolled native axis is its edge. + roll = math.radians(rotation) + rim = [ + (math.sin(half_fov) * math.cos(angle), math.sin(half_fov) * math.sin(angle), -math.cos(half_fov)) + for angle in (roll, roll + math.pi / 2) + ] + hand_rays = torch.tensor([(0.0, 0.0, -1.0), *rim], dtype=torch.float64) + uv, _ = native_grid_exit_uv(hand_rays, coords, image_rotation_deg=rotation) + torch.testing.assert_close(uv, torch.tensor([[0.5, 0.5], [0.5, 1.0], [1.0, 0.5]]), atol=1e-6, rtol=0) + + @pytest.mark.parametrize("coverage", ["circular", "square", "wang"]) def test_spherical_valid_samples_match_calibrated_software_rays(coverage): from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions @@ -82,15 +119,31 @@ def test_spherical_padding_matches_rim_slope_and_does_not_wrap(): torch.testing.assert_close(unbounded_angular_radius(angles, half_fov), radius, atol=1e-10, rtol=0) -def test_direction_texture_is_native_rays_without_assignment(): +def test_textures_match_independent_geometry(): coords = make_coords(64) - direction, inverse = build_native_grid_textures(coords, image_rotation_deg=0, exit_size=256) - expected = native_grid_directions(coords) - torch.testing.assert_close(direction.reshape(-1, 3), expected, atol=0, rtol=0) + size = 256 + direction, inverse = build_native_grid_textures(coords, image_rotation_deg=0, exit_size=size) assert direction.shape == (64, 64, 3) - assert inverse.shape == (256, 256, 2) + assert inverse.shape == (size, size, 2) + inside = torch.linalg.vector_norm(coords.cartesian, dim=-1) <= 1 + expected = spherical_rays(coords.cartesian[inside], coords.fov).float() + torch.testing.assert_close(direction.reshape(-1, 3)[inside], expected, atol=1e-6, rtol=0) + # Forward-hemisphere octahedral texel centres decode to (x, y, -(1 - |x| - |y|)) before normalization. + axis = (torch.arange(size, dtype=torch.float64) + 0.5) / size * 2 - 1 + y, x = torch.meshgrid(axis, axis, indexing="ij") + forward = x.abs() + y.abs() < 1 + texel_rays = torch.nn.functional.normalize(torch.stack((x, y, x.abs() + y.abs() - 1), -1), dim=-1) + # Each stored UV, mapped back through Fovi's native-to-visual warp, must look along its texel's ray. + native = (inverse[forward].to(torch.float64) * 2 - 1).flip(-1) + visual = coords.native_to_visual(native) + nominal = torch.linalg.vector_norm(visual, dim=-1) <= 1 + assert nominal.sum() > 1000 + torch.testing.assert_close( + spherical_rays(visual[nominal], coords.fov), texel_rays[forward][nominal], atol=1e-5, rtol=0 + ) + # The antipode lies outside every grid. + assert (inverse[0, 0] == -1).all() and (inverse[-1, -1] == -1).all() assert torch.isfinite(inverse).all() - assert (inverse == -1).any() def test_upright_grid_masks_and_channel_aliases(): diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 0bf7a4ecf263..4ed02966f8b1 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -112,7 +112,8 @@ def render(camera, env_mask): expected = camera.renderer_rgba.reshape(2, len(ray_coords), 1, 4).clone() expected[:, ~ray_coords.valid_mask] = 0 if pooled: - expected = newton_camera.pool_hwc_buffer(pooler, expected.float()).to(torch.uint8) + # AdaptiveAvgPool1d maps the 4 * N_lo canonical samples to N_lo by averaging each run of four. + expected = expected.reshape(2, len(coords), 4, 1, 4).float().mean(dim=2).to(torch.uint8) expected = coords.as_grid(expected.squeeze(2), sample_dim=1) torch.testing.assert_close(camera._data.output["rgba"].torch, expected, rtol=0, atol=0) # The published buffers are stable across frames, and rgb shares rgba's memory. @@ -121,16 +122,11 @@ def render(camera, env_mask): assert camera._data.output["rgb"].warp.ptr == public_rgba.warp.ptr -@pytest.mark.parametrize("render_order", ["tiled", "pixel_priority", "view_priority"]) -def test_native_grid_fractional_pool_resolution_validates_newton_tiles(render_order) -> None: - camera = SimpleNamespace( - cfg=SimpleNamespace(width=83, height=83), - _renderer=SimpleNamespace( - cfg=SimpleNamespace(render_order=render_order, tile_rendering_width=16, tile_rendering_height=8) - ), - ) - if render_order == "tiled": - with pytest.raises(ValueError, match="83x83.*16x8"): - FoveatedNewtonCamera._validate_native_render_layout(camera) +@pytest.mark.parametrize("size, valid", [(83, False), (100, False), (128, True)]) +def test_native_grid_fractional_pool_resolution_validates_newton_tiles(size, valid) -> None: + camera = SimpleNamespace(cfg=SimpleNamespace(width=size, height=size)) + if valid: + FoveatedNewtonCamera._validate_native_render_layout(camera, 16, 8) else: - FoveatedNewtonCamera._validate_native_render_layout(camera) + with pytest.raises(ValueError, match=f"{size}x{size}.*16x8"): + FoveatedNewtonCamera._validate_native_render_layout(camera, 16, 8) diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 2d7ad72713ec..59c9064d20ba 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -11,12 +11,15 @@ import torch from fovi.arch.knn import KNNPoolingLayer from fovi.arch.pooling import GridPoolingLayer +from isaaclab_fovi.sensors import pooling from isaaclab_fovi.sensors.pooling import ( + ModalPooler, build_highres_coords, build_lowres_coords, build_pooler, - is_segmentation_output, pool_hwc_buffer, + pool_segmentation_buffer, + segmentation_neighbor_indices, ) from isaaclab.sim import PinholeCameraCfg @@ -71,32 +74,107 @@ def test_disabled_pooling_uses_only_output_grid() -> None: assert build_pooler(cfg, lowres, None, "cpu") == (None, None) -def test_segmentation_pooler_override_preserves_discrete_label_values() -> None: - cfg = SamplingConfig(pool_mode="avg") - lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") - assert highres is not None - pooler, _ = build_pooler(cfg, lowres, highres, "cpu", mode="max") - assert pooler is not None - labels = torch.tensor([2.0, 7.0, 19.0]) - rendered = labels[torch.arange(len(highres)) % len(labels)].reshape(1, -1, 1, 1) - pooled = pool_hwc_buffer(pooler, rendered) - assert pooled.shape == (1, len(lowres), 1, 1) - assert torch.isin(pooled, labels).all() +DEVICES = [ + "cpu", + pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable")), +] + +# Three output samples over five input samples; 5 marks an excluded neighbour. Columns are outputs, rows are +# neighbour slots nearest first. +HAND_TABLE = torch.tensor([[0, 3, 5], [1, 4, 5], [2, 5, 5]]) + + +def hand_pooler(device: str) -> ModalPooler: + return ModalPooler(HAND_TABLE, num_inputs=5).to(device) + + +@pytest.mark.parametrize("device", DEVICES) +def test_modal_pooling_keeps_majority_color_vector(device: str) -> None: + # Output 0 sees [0,0,0,255] twice and [0,0,1,255] once; a per-channel max would give [0,0,1,255]. + # Output 1 sees one vote each for two colors (its third slot is excluded): the nearest neighbour wins. + # Output 2 has no valid neighbour and is zero. + colors = torch.tensor( + [[0, 0, 0, 255], [0, 0, 0, 255], [0, 0, 1, 255], [10, 20, 30, 255], [200, 100, 0, 255]], dtype=torch.uint8 + ) + rendered = colors[None, :, None, :].to(device) + pooled = pool_segmentation_buffer(hand_pooler(device), rendered) + expected = torch.tensor([[0, 0, 0, 255], [10, 20, 30, 255], [0, 0, 0, 0]], dtype=torch.uint8) + assert pooled.dtype == torch.uint8 + assert torch.equal(pooled.cpu(), expected[None, :, None, :]) + # Swapping the tied neighbours' order flips the winner. + swapped = ModalPooler(HAND_TABLE[[1, 0, 2]], num_inputs=5).to(device) + assert torch.equal(pool_segmentation_buffer(swapped, rendered)[0, 1, 0].cpu(), colors[4]) + + +@pytest.mark.parametrize("device", DEVICES) +@pytest.mark.parametrize("dtype", [torch.int32, torch.int64]) +def test_modal_pooling_preserves_ids_above_float_precision(device: str, dtype: torch.dtype) -> None: + # 2**24 + 1 and 2**24 + 3 round to other values in float32; the IDs must come back exactly. + big = 2**30 if dtype == torch.int32 else 2**40 + ids = torch.tensor([2**24 + 1, 2**24 + 1, 2**24 + 3, big + 7, big + 7], dtype=dtype) + batch = torch.stack([ids, ids.flip(0)])[:, :, None, None].to(device) + pooled = pool_segmentation_buffer(hand_pooler(device), batch) + expected = torch.tensor([[2**24 + 1, big + 7, 0], [big + 7, 2**24 + 1, 0]], dtype=dtype) + assert pooled.dtype == dtype + assert torch.equal(pooled[..., 0, 0].cpu(), expected) + + +@pytest.mark.parametrize("device", DEVICES) +def test_modal_pooling_compares_wide_vectors_exactly(device: str) -> None: + # Two int64 channels exceed the 8-byte packed key; vectors differing only in the second channel stay distinct. + vectors = torch.tensor([[1, 2**40], [1, 2**40 + 1], [1, 2**40 + 1], [5, 6], [7, 8]], dtype=torch.int64) + pooled = pool_segmentation_buffer(hand_pooler(device), vectors[None, :, None, :].to(device)) + expected = torch.tensor([[1, 2**40 + 1], [5, 6], [0, 0]]) + assert torch.equal(pooled[0, :, 0].cpu(), expected) + + +def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Tensor: + """Brute-force modal pooling of ``(B, N_hi, C)`` values over a ``(k, N_lo)`` neighbour table.""" + batch, num_inputs, channels = values.shape + out = torch.zeros(batch, table.shape[1], channels, dtype=values.dtype) + for b in range(batch): + for n in range(table.shape[1]): + neighbours = [tuple(values[b, i].tolist()) for i in table[:, n].tolist() if i != num_inputs] + if neighbours: + # max() keeps the first of equally common values, i.e. the earliest neighbour slot. + out[b, n] = torch.tensor(max(neighbours, key=neighbours.count), dtype=values.dtype) + return out @pytest.mark.parametrize( - ("name", "expected"), + ("style", "pool_k", "sample_cortex"), [ - ("rgb", False), - ("distance_to_camera", False), - ("semantic_segmentation", True), - ("instance_segmentation_fast", True), - ("instance_id_segmentation_fast", True), + ("warped_cartesian_as_grid", 4, False), + ("warped_cartesian_as_grid", 9, False), + ("warped_cartesian", 3, True), + ("isotropic", 3, False), ], ) -def test_segmentation_dispatch_uses_semantics(name: str, expected: bool) -> None: - assert is_segmentation_output(name) is expected +def test_modal_pooler_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex: bool) -> None: + cfg = SamplingConfig(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex) + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + fovi_max, k = build_pooler(cfg, lowres, highres, "cpu", mode="max") + modal, modal_k = build_pooler(cfg, lowres, highres, "cpu", mode="mode") + assert isinstance(modal, ModalPooler) + assert modal_k == k + table = modal.neighbor_indices + assert table.shape == (k, len(lowres)) + + # The table holds exactly the samples fovi's max pooler reduces over: a max over the table matches it. + values = torch.rand(1, len(highres), 1, 1, generator=torch.Generator().manual_seed(0)) + 1 + padded = torch.cat([values[0, :, 0, 0], torch.zeros(1)]) + torch.testing.assert_close(padded[table].max(dim=0).values, pool_hwc_buffer(fovi_max, values)[0, :, 0, 0]) + # A raw fovi pooler exposes the same neighbourhoods. + assert torch.equal(segmentation_neighbor_indices(fovi_max), table) + + # Few labels so neighbourhoods hold repeats and ties; tiny chunks exercise the batched loop. + monkeypatch.setattr(pooling, "_MODAL_CHUNK_ELEMENTS", 1) + labels = torch.randint(0, 3, (3, len(highres), 1, 2), generator=torch.Generator().manual_seed(1)) + labels = labels.to(torch.uint8) + pooled = pool_segmentation_buffer(modal, labels) + assert torch.equal(pooled[:, :, 0], reference_modal_pool(table, labels[:, :, 0])) + assert torch.equal(pool_hwc_buffer(modal, labels), pooled) @pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) diff --git a/source/isaaclab_fovi/test/test_rays.py b/source/isaaclab_fovi/test/test_rays.py index 76ea397bdff2..3162cceb6b2d 100644 --- a/source/isaaclab_fovi/test/test_rays.py +++ b/source/isaaclab_fovi/test/test_rays.py @@ -3,12 +3,14 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""CPU tests of sensor ray layout and the fixed optical center.""" +"""CPU tests of Newton's foveated ray array: sample order, the fixed optical center, and tile padding.""" import pytest import torch import warp as wp -from isaaclab_fovi.sensors.foveated_rays import compute_explicit_ray_array +from isaaclab_fovi.sensors.foveated_newton_camera import explicit_rays + +pytestmark = pytest.mark.kitless @pytest.fixture(scope="module", autouse=True) @@ -20,7 +22,7 @@ def test_explicit_rays_preserve_sample_order_and_optical_center() -> None: directions = torch.nn.functional.normalize( torch.tensor([[0.7, 0.3, -1.0], [-0.2, 0.6, -1.0], [0.0, 0.0, -1.0]]), dim=-1 ) - rays = compute_explicit_ray_array(directions, device="cpu") + rays = explicit_rays(directions, 3, 1) assert rays.shape == (1, 3, 1, 2) assert rays.dtype == wp.vec3f rays = wp.to_torch(rays)[0, :, 0] @@ -28,6 +30,16 @@ def test_explicit_rays_preserve_sample_order_and_optical_center() -> None: torch.testing.assert_close(rays[:, 1], directions) -def test_explicit_rays_reject_invalid_dimensions() -> None: +def test_explicit_rays_pad_whole_tiles_with_the_last_ray() -> None: + directions = torch.nn.functional.normalize(torch.randn(5, 3), dim=-1) + rays = wp.to_torch(explicit_rays(directions, 2, 4)).reshape(8, 2, 3) + torch.testing.assert_close(rays[:5, 1], directions) + torch.testing.assert_close(rays[5:, 1], directions[-1].expand(3, -1)) + assert not rays[:, 0].any() + + +def test_explicit_rays_reject_invalid_shapes() -> None: with pytest.raises(ValueError, match="shape"): - compute_explicit_ray_array(torch.zeros(3, 2), device="cpu") + explicit_rays(torch.zeros(3, 2), 3, 1) + with pytest.raises(ValueError, match="cannot hold"): + explicit_rays(torch.zeros(5, 3), 2, 2) diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index dbcd4d8172fb..156e89538105 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -14,11 +14,18 @@ from fovi.sensing.projection import CameraModel, angular_directions from fovi.sensing.retina import RetinalTransform from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions, sampling_geometry +from isaaclab_fovi.sensors.foveated_camera import FoveatedCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.pooling import build_lowres_coords -from isaaclab_fovi.sensors.virtual_gaze import VirtualGaze -from isaaclab.utils.math import matrix_from_quat, quat_apply, quat_from_matrix +from isaaclab.utils.math import ( + convert_camera_frame_orientation_convention, + matrix_from_quat, + quat_apply, + quat_from_matrix, +) + +pytestmark = pytest.mark.kitless @pytest.fixture @@ -70,9 +77,16 @@ def test_rendering_and_software_sampling_share_window_and_nodes() -> None: assert torch.isfinite(actual).all() -class GazeHarness(VirtualGaze): - def __init__(self) -> None: +class GazeHarness(FoveatedCamera): + """The foveated camera's gaze state and kernels on stand-in pose buffers, without a simulator.""" + + def __new__(cls, **overrides): + return object.__new__(cls) + + def __init__(self, **overrides) -> None: self.cfg = camera_config() + for name, value in overrides.items(): + setattr(self.cfg, name, value) self._sampling_coords, _ = build_lowres_coords(self.cfg, "cpu") self._sampling_coords_highres = None self._gaze_rotation = None @@ -155,6 +169,40 @@ def test_gaze_preserves_camera_rotation_with_tf32( assert torch.get_float32_matmul_precision() == "high" +@pytest.mark.parametrize("rotation_deg", [0.0, 30.0, -75.0]) +def test_sensor_mask_checks_the_rendered_rays_of_a_rolled_mount(rotation_deg: float) -> None: + """The mask sees exactly the rays the turned camera renders, found here through the camera pose instead.""" + # An off-center, wide image makes a roll change which samples the camera sees. + model = CameraModel("pinhole", (80, 120), (60.0, 60.0, 45.0, 30.0)) + camera = GazeHarness(camera_model=asdict(model), image_rotation_deg=rotation_deg) + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) + mount = camera._data.quat_w_world.clone() + camera._apply_gaze_pose() + + # Rendered rays leave the turned camera along its OpenGL frame; express them in the mount's OpenGL frame. + def opengl(orientation: torch.Tensor) -> torch.Tensor: + return matrix_from_quat(convert_camera_frame_orientation_convention(orientation, "world", "opengl")) + + turn = opengl(mount).transpose(-1, -2) @ opengl(camera._data.quat_w_world) + coords = camera._sampling_coords + rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) + seen = (turn[:, None] @ rays[None, :, :, None]).squeeze(-1) * torch.tensor([1.0, -1.0, -1.0]) + expected = model.project(seen)[1] + assert expected.any() and (~expected).any() + assert (camera._gaze_validity(2) == expected).float().mean() > 0.999 + + +def test_pose_update_records_the_mount_before_the_gaze() -> None: + camera = GazeHarness() + mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) + camera._data.quat_w_world = mount.clone() + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) + camera._apply_gaze_pose() + expected = convert_camera_frame_orientation_convention(mount, "world", "ros") + torch.testing.assert_close(matrix_from_quat(camera._mount_quat_ros), matrix_from_quat(expected), atol=1e-6, rtol=0) + assert not torch.allclose(camera._data.quat_w_world, mount) + + def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pose() -> None: camera = GazeHarness() angles = torch.tensor([[6.0, -11.0], [-9.0, 17.0]]) diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index ff99dd39fe23..69919cd9ab04 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -21,6 +21,8 @@ native_grid_exit_uv, ) +pytestmark = pytest.mark.kitless + def make_coords(res: int = 16) -> SamplingCoords: fov = 170.0 @@ -35,9 +37,17 @@ def make_coords(res: int = 16) -> SamplingCoords: ) -@pytest.mark.parametrize("rotation", [0.0, 37.0, 180.0]) -@pytest.mark.parametrize("res", [1, 15, 64]) -def test_every_texel_roundtrips(rotation: float, res: int) -> None: +@pytest.mark.parametrize( + ("res", "rotation"), + [ + # A single texel sits on the optical axis, where the sensor roll has no effect. + (1, 0.0), + # Odd grids put a texel on the optical axis; even grids straddle it. + (15, 37.0), + (64, 180.0), + ], +) +def test_every_texel_roundtrips(res: int, rotation: float) -> None: coords = make_coords(res) rays = native_grid_directions(coords, image_rotation_deg=rotation) uv, visible = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) From 563990ce0451f76d6de9dd428e6a121d962343df Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 22:29:21 -0800 Subject: [PATCH 28/81] Write lens textures with OpenEXR only and trim the gaze pose test matrix The fovi extra installs OpenEXR, so the OpenCV fallback and its process-wide setting go; a missing OpenEXR now raises its own import error. The pose test keeps each selection path and autocast once instead of crossing batch sizes. --- .../sensors/generalized_projection.py | 55 ++++--------------- .../test/test_spherical_geometry.py | 12 ++-- 2 files changed, 18 insertions(+), 49 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py index 8f1a4fbe4328..267d1fd9b841 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py @@ -41,22 +41,12 @@ import math import os -# Must be set before cv2 is first imported anywhere in the process. -os.environ.setdefault("OPENCV_IO_ENABLE_OPENEXR", "1") - import numpy as np import torch from fovi.sensing.coords import SamplingCoords from .native_grid import native_grid_directions, native_grid_exit_uv -# ── Optional dependencies ──────────────────────────────────────────────────── -try: - import Imath - import OpenEXR -except ImportError: - OpenEXR = Imath = None # type: ignore - try: from pxr import Sdf, Usd, UsdGeom except ImportError: @@ -81,44 +71,23 @@ def _t(x, dtype: torch.dtype, device) -> torch.Tensor: def save_exr(path: str, data: torch.Tensor) -> None: - """Save a ``(H, W, C)`` float32 tensor to an EXR file (C ∈ {2, 3}). + """Save a ``(H, W, C)`` float32 tensor to an EXR file (C ∈ {2, 3}) with OpenEXR, which the ``fovi`` extra + installs.""" + import Imath + import OpenEXR - Uses **OpenEXR** when available; falls back to **OpenCV** otherwise. - """ arr = np.ascontiguousarray(data.detach().cpu().numpy(), dtype=np.float32) h, w, c = arr.shape if c not in (2, 3): raise ValueError(f"save_exr: expected 2 or 3 channels, got {c}") - - if OpenEXR is not None and Imath is not None: - names = ("R", "G") if c == 2 else ("R", "G", "B") - ch_t = Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT)) - hdr = OpenEXR.Header(w, h) - hdr["Compression"] = Imath.Compression.ZIP_COMPRESSION - hdr["channels"] = {n: ch_t for n in names} - exr = OpenEXR.OutputFile(path, hdr) - exr.writePixels({n: arr[:, :, i].tobytes() for i, n in enumerate(names)}) - exr.close() - return - - try: - import cv2 - - flags = [cv2.IMWRITE_EXR_TYPE, cv2.IMWRITE_EXR_TYPE_FLOAT] - if c == 2: - img = np.concatenate([np.zeros((h, w, 1), dtype=np.float32), arr[:, :, ::-1]], axis=2) - else: - img = arr[:, :, ::-1] - if not cv2.imwrite(path, img, flags): - raise RuntimeError(f"OpenCV failed to write EXR: {path}") - return - except ImportError: - pass - - raise RuntimeError( - "Neither OpenEXR nor OpenCV is installed. " - "Install one: conda install -c conda-forge openexr or pip install opencv-python" - ) + names = ("R", "G") if c == 2 else ("R", "G", "B") + ch_t = Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT)) + hdr = OpenEXR.Header(w, h) + hdr["Compression"] = Imath.Compression.ZIP_COMPRESSION + hdr["channels"] = {n: ch_t for n in names} + exr = OpenEXR.OutputFile(path, hdr) + exr.writePixels({n: arr[:, :, i].tobytes() for i, n in enumerate(names)}) + exr.close() # ============================================================================= diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 156e89538105..e57a0c2d4f65 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -129,12 +129,12 @@ def test_gaze_away_from_sensor_masks_all_rays() -> None: @pytest.mark.parametrize("device", ["cpu", "cuda"]) -@pytest.mark.parametrize("batch_size", [48, 256]) -@pytest.mark.parametrize("autocast", [False, True]) -@pytest.mark.parametrize("mode", ["spherical", "spherical_ids", "spherical_mask"]) -def test_gaze_preserves_camera_rotation_with_tf32( - device: str, batch_size: int, autocast: bool, mode: str, tf32_enabled -) -> None: +@pytest.mark.parametrize( + "mode, autocast", + [("spherical", False), ("spherical", True), ("spherical_ids", False), ("spherical_mask", False)], +) +def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, mode: str, tf32_enabled) -> None: + batch_size = 48 if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA unavailable") source_gl = torch.tensor([[0.4625, 0.4940, -0.5341, 0.5067]], device=device).repeat(batch_size, 1) From 201b0e6c5e7615c5390bcc9541670d597c57c70a Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 22:31:55 -0800 Subject: [PATCH 29/81] Name the RTX lens module after OmniLensDistortionLutAPI The camera already authors OmniLensDistortionLutAPI lookup-table lenses; the module and its functions kept names from the legacy generalized-projection API. generalized_projection becomes lens_lut, with build_lut_textures, save_lut_textures and apply_lens_lut_to_prim. --- .../isaaclab_fovi/sensors/foveated_rtx_camera.py | 16 +++++++++------- .../{generalized_projection.py => lens_lut.py} | 15 ++++++--------- source/isaaclab_fovi/test/test_lens_schema.py | 6 +++--- source/isaaclab_fovi/test/test_native_grid.py | 2 +- .../test/test_square_native_grid.py | 2 +- 5 files changed, 20 insertions(+), 21 deletions(-) rename source/isaaclab_fovi/isaaclab_fovi/sensors/{generalized_projection.py => lens_lut.py} (96%) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 1e088c79681e..cc17ee693f39 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -27,7 +27,7 @@ from isaaclab.sensors.camera.camera import Camera from isaaclab.utils.math import matrix_from_quat, quat_from_matrix -from . import generalized_projection as gp +from . import lens_lut from .calibrated_geometry import compose_rotations, retinal_directions from .foveated_camera import FoveatedCamera from .native_grid import ( @@ -102,7 +102,7 @@ def __init__(self, cfg: FoveatedCameraCfg): super().__init__(cfg) if ovrtx: for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): - gp.apply_generalized_projection_to_prim(prim, self._dir_tex_path, self._exit_tex_path) + lens_lut.apply_lens_lut_to_prim(prim, self._dir_tex_path, self._exit_tex_path) # ------------------------------------------------------------------ # Initialisation @@ -139,7 +139,9 @@ def _prepare_projection(self) -> None: # Eccentricity [deg] of each sample; the disc is laid out with the same # field of view and CMF constant the samples were generated with. eccentricity = ray_coords.polar[:, 0].to(torch.float64) * (ray_coords.fov / 2.0) - uv = gp.samples_uv_cortical_disc(eccentricity, theta_rad, ray_coords.fov, ray_coords.cmf_a, device="cpu") + uv = lens_lut.samples_uv_cortical_disc( + eccentricity, theta_rad, ray_coords.fov, ray_coords.cmf_a, device="cpu" + ) self._texture_width = tw self._texture_height = th self._sample_uv = uv @@ -152,14 +154,14 @@ def _prepare_projection(self) -> None: else: EW = EH = max(128, 4 * max(tw, th)) if self._native_grid: - dir_tex, exit_tex = gp.build_native_grid_textures( + dir_tex, exit_tex = lens_lut.build_native_grid_textures( ray_coords, image_rotation_deg=self.cfg.image_rotation_deg, exit_size=EW ) else: - dir_tex, exit_tex = gp.build_generalized_projection_textures(uv, dirs, tw, th, EW, EH, device="cpu") + dir_tex, exit_tex = lens_lut.build_lut_textures(uv, dirs, tw, th, EW, EH, device="cpu") # The camera owns its textures' directory, which is removed when the camera is released. self._lut_dir = tempfile.TemporaryDirectory(prefix="rtx_foveated_luts_") - self._dir_tex_path, self._exit_tex_path = gp.save_generalized_projection_textures( + self._dir_tex_path, self._exit_tex_path = lens_lut.save_lut_textures( dir_tex, exit_tex, self._lut_dir.name, "foveated" ) logger.info( @@ -188,7 +190,7 @@ def _initialize_impl(self) -> None: # snapshots a detached stage, so later USD edits would miss its cameras. prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) for prim in prims: - gp.apply_generalized_projection_to_prim( + lens_lut.apply_lens_lut_to_prim( prim, direction_texture_path=self._dir_tex_path, exit_texture_path=self._exit_tex_path ) # OVRTX's lookup-table range is measured from the near-clipped ray origin. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py similarity index 96% rename from source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py rename to source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index 267d1fd9b841..1330849ded2b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/generalized_projection.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -12,11 +12,9 @@ # license agreement from NVIDIA CORPORATION is strictly prohibited. """ -Utilities for building generalised-projection (LUT-based) foveated camera -models compatible with OmniLensDistortionLutAPI (Omniverse / Isaac Sim). +Lens lookup tables for RTX's ``OmniLensDistortionLutAPI`` (``omni:lensdistortion:model = "lut"``). -A generalised-projection sensor is defined by two HDR textures attached to a -camera prim: +A lookup-table lens is defined by two HDR textures attached to a camera prim: * **rayEnterDirectionTexture** ``(H × W, RGB float32)`` Maps each sensor texel NDC ``(u, v)`` → unit ray direction in camera space. @@ -25,8 +23,7 @@ Inverse map: given a ray direction (octahedral-encoded over ``[0,1]²``), returns the sensor NDC ``(u, v)`` of the nearest sample. -Ported from ``fovi-rtx/generalized_projection.py`` — contains only the -subset of functions required by :class:`FoveatedRTXCamera`. +Isaac RTX and OVRTX both render through this API; the legacy generalized-projection camera attributes are not used. Coordinate conventions: @@ -161,7 +158,7 @@ def build_native_grid_textures( return directions, exit_texture -def build_generalized_projection_textures( +def build_lut_textures( samples_uv: torch.Tensor, ray_directions: torch.Tensor, texture_width: int, @@ -253,7 +250,7 @@ def build_generalized_projection_textures( # ============================================================================= -def save_generalized_projection_textures( +def save_lut_textures( direction_texture: torch.Tensor, exit_texture: torch.Tensor, output_dir: str, @@ -277,7 +274,7 @@ def save_generalized_projection_textures( # ============================================================================= -def apply_generalized_projection_to_prim( +def apply_lens_lut_to_prim( prim: Usd.Prim, direction_texture_path: str, exit_texture_path: str, diff --git a/source/isaaclab_fovi/test/test_lens_schema.py b/source/isaaclab_fovi/test/test_lens_schema.py index 3bf248938c7c..cd2d63a36fbf 100644 --- a/source/isaaclab_fovi/test/test_lens_schema.py +++ b/source/isaaclab_fovi/test/test_lens_schema.py @@ -8,8 +8,8 @@ import pytest Usd = pytest.importorskip("pxr.Usd") -from isaaclab_fovi.sensors.generalized_projection import ( # noqa: E402 - apply_generalized_projection_to_prim, +from isaaclab_fovi.sensors.lens_lut import ( # noqa: E402 + apply_lens_lut_to_prim, ) from pxr import UsdGeom # noqa: E402 @@ -20,7 +20,7 @@ def test_lut_schema_has_explicit_model_and_assets_after_export() -> None: stage = Usd.Stage.CreateInMemory() prim = UsdGeom.Camera.Define(stage, "/Camera").GetPrim() - apply_generalized_projection_to_prim(prim, "/tmp/direction.exr", "/tmp/exit.exr") + apply_lens_lut_to_prim(prim, "/tmp/direction.exr", "/tmp/exit.exr") restored = Usd.Stage.CreateInMemory() restored.GetRootLayer().ImportFromString(stage.GetRootLayer().ExportToString()) prim = restored.GetPrimAtPath("/Camera") diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py index 034d89a272f1..225a9aa0eda4 100644 --- a/source/isaaclab_fovi/test/test_native_grid.py +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -10,7 +10,7 @@ import pytest import torch from fovi.sensing.coords import SamplingCoords -from isaaclab_fovi.sensors.generalized_projection import build_native_grid_textures +from isaaclab_fovi.sensors.lens_lut import build_native_grid_textures from isaaclab_fovi.sensors.native_grid import ( allocate_grid_outputs, bounded_angular_radius, diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 69919cd9ab04..592c321c6643 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -10,7 +10,7 @@ import pytest import torch from fovi.sensing.coords import SamplingCoords -from isaaclab_fovi.sensors.generalized_projection import build_native_grid_textures +from isaaclab_fovi.sensors.lens_lut import build_native_grid_textures from isaaclab_fovi.sensors.native_grid import ( allocate_grid_outputs, copy_grid_outputs, From 3b77af49dc09b280571f2c10603ea4f8cf053dd7 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 22:38:00 -0800 Subject: [PATCH 30/81] Drop the proprietary license header from the lens module The module carried a proprietary NVIDIA notice from its source project alongside the package's BSD-3-Clause header; the package is BSD-3-Clause. --- source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index 1330849ded2b..252d74c4e263 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -3,14 +3,6 @@ # # SPDX-License-Identifier: BSD-3-Clause -# Copyright (c) 2024-2026, NVIDIA CORPORATION. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - """ Lens lookup tables for RTX's ``OmniLensDistortionLutAPI`` (``omni:lensdistortion:model = "lut"``). From 6ec8daa344f5152d9f934d5b489731891fed5b3a Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 22:41:41 -0800 Subject: [PATCH 31/81] Test the review fixes at their boundaries A pooled Newton camera publishes exact modal segmentation IDs above 2**24 and reports the retina's image shape; a position-only mount move keeps the gaze on every renderer; OVRTX rejects async rendering with the sensor mask and reads the near clip from the camera prim; the fixed-mount teacher rejects a moved mount, which both pose setters record. --- .../test/foveated_render_cases.py | 20 +++++- source/isaaclab_fovi/test/test_active_gaze.py | 18 ++++- .../test/test_foveated_camera_render.py | 5 ++ .../test/test_foveated_camera_render_ovrtx.py | 4 ++ .../isaaclab_fovi/test/test_newton_buffers.py | 72 +++++++++++++++++++ source/isaaclab_fovi/test/test_rtx_camera.py | 34 +++++++++ .../test/test_spherical_geometry.py | 14 ++++ 7 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 source/isaaclab_fovi/test/test_rtx_camera.py diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py index c1ca45f12a2e..f937219a8ce3 100644 --- a/source/isaaclab_fovi/test/foveated_render_cases.py +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -117,7 +117,8 @@ def _render( ) -> tuple[torch.Tensor, torch.Tensor]: """Render ground distance for one environment per row of gaze angles (tilt, pan) [deg]. - With ``moved_mount`` (eye, target), the last environment's camera is moved there after its gaze is set. + With ``moved_mount`` (eye, target), the last environment's camera is moved there after its gaze is set; a target + of None moves only its position. With ``later_gaze``, the gaze changes to it after the first frames, and the camera renders one more frame. Returns: @@ -143,7 +144,8 @@ def _render( last = len(gaze) - 1 eye, target = moved_mount position = scene.env_origins[last : last + 1] + torch.tensor([eye], device=sim.device) - orientation = torch.tensor([_look_at(eye, target)], device=sim.device) + # Without a target, only the position moves and the mount keeps its orientation. + orientation = None if target is None else torch.tensor([_look_at(eye, target)], device=sim.device) camera.set_world_poses(position, orientation, env_ids=[last], convention="opengl") for _ in range(WARMUP_STEPS): sim.step() @@ -214,6 +216,20 @@ def gaze_stays_relative_to_a_moved_mount(backend: tuple): ) +def gaze_survives_a_position_only_move(backend: tuple): + """Moving only a camera's position keeps its orientation, so the gaze is not applied a second time.""" + gaze = torch.tensor([[0.0, -10.0], [0.0, -10.0]]) + eye = (0.4, -0.3, 3.0) + target = tuple(e + t - c for e, t, c in zip(eye, CAM_TARGET, CAM_EYE)) + distance, field = _render(backend, gaze, moved_mount=(eye, None)) + + row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) + assert float(distance[0, row, column]) == pytest.approx(_ground_distance_along_gaze(0.0, -10.0), rel=0.01) + assert float(distance[1, row, column]) == pytest.approx( + _ground_distance_along_gaze(0.0, -10.0, eye, target), rel=0.01 + ) + + def foveated_camera_samples_densest_at_the_fixation(backend: tuple): """Neighbouring samples are closer together at the fixation, and nearly even without foveation.""" diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 25f1f644be11..e881000f99fb 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -5,12 +5,20 @@ """Gaze geometry and gaze-supervised PPO, without a simulator.""" +from types import SimpleNamespace + import pytest import torch import warp as wp from fovi.sensing.projection import CameraModel from isaaclab_fovi.mdp import angles_to_direction, clamp_gaze, direction_to_angles -from isaaclab_fovi.mdp.gaze import gaze_reset_kernel, gaze_step_kernel, teacher_block_dim, teacher_labels_kernel +from isaaclab_fovi.mdp.gaze import ( + GazeAction, + gaze_reset_kernel, + gaze_step_kernel, + teacher_block_dim, + teacher_labels_kernel, +) from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream from rsl_rl.models import MLPModel @@ -160,6 +168,14 @@ def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): torch.testing.assert_close(state, expected_state, atol=0, rtol=0) +def test_fixed_mount_teacher_rejects_a_moved_mount(): + term = object.__new__(GazeAction) + term.tracked_mount = False + term.camera = SimpleNamespace(mount_moved=True) + with pytest.raises(RuntimeError, match="mount='tracked'"): + GazeAction._teacher_labels(term, targets=None) + + def test_gaze_loss_ignores_invalid_labels(): mean = torch.tensor([[0.0, 0.0], [1.0, 1.0]], requires_grad=True) labels = torch.tensor([[0.3, 0.4, 1.0], [float("nan"), float("nan"), 0.0]]) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index eca9350bf0ac..b834e11812ae 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -45,6 +45,11 @@ def test_gaze_stays_relative_to_a_moved_mount(backend): cases.gaze_stays_relative_to_a_moved_mount(BACKENDS[backend]) +@pytest.mark.parametrize("backend", BACKENDS) +def test_gaze_survives_a_position_only_move(backend): + cases.gaze_survives_a_position_only_move(BACKENDS[backend]) + + @pytest.mark.parametrize("backend", BACKENDS) def test_foveated_camera_samples_densest_at_the_fixation(backend): cases.foveated_camera_samples_densest_at_the_fixation(BACKENDS[backend]) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py index 70995210b08f..6edbf988c6f9 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py @@ -46,5 +46,9 @@ def test_gaze_stays_relative_to_a_moved_mount(): cases.gaze_stays_relative_to_a_moved_mount(BACKEND) +def test_gaze_survives_a_position_only_move(): + cases.gaze_survives_a_position_only_move(BACKEND) + + def test_foveated_camera_samples_densest_at_the_fixation(): cases.foveated_camera_samples_densest_at_the_fixation(BACKEND) diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 4ed02966f8b1..f8ff0610fe44 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -13,6 +13,7 @@ from fovi.sensing.coords import SamplingCoords from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera +from isaaclab_fovi.sensors.pooling import ModalPooler from isaaclab.renderers.output_contract import RenderBufferKind, RenderBufferSpec from isaaclab.sensors.camera.camera_data import CameraData @@ -122,6 +123,77 @@ def render(camera, env_mask): assert camera._data.output["rgb"].warp.ptr == public_rgba.warp.ptr +def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatch) -> None: + """A pooled camera's segmentation output holds each sample's majority label exactly, IDs above 2**24 included.""" + coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") + highres = coords.clone(resolution=32) + runs = torch.arange(len(coords)) + # Each pooled sample's neighbours are a run of four rendered samples, nearest first. + neighbors = torch.stack([4 * runs + j for j in range(4)]) + average = torch.nn.AdaptiveAvgPool1d(len(coords)) + + def build_pooler(cfg, lowres, high, device, mode=None): + return (ModalPooler(neighbors, len(highres)) if mode == "mode" else average), 4 + + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr(newton_camera, "build_pooler", build_pooler) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", lambda self: None) + + def initialize_renderer(camera): + size = (2, camera.cfg.height, camera.cfg.width) + camera.renderer_rgba = torch.zeros((*size, 4), dtype=torch.uint8) + camera.renderer_labels = torch.zeros((*size, 1), dtype=torch.int32) + camera._data = SimpleNamespace( + output={ + "rgba": ProxyArray(wp.from_torch(camera.renderer_rgba)), + "semantic_segmentation": ProxyArray(wp.from_torch(camera.renderer_labels)), + } + ) + camera._render_data = SimpleNamespace(camera_rays=None) + camera._renderer = SimpleNamespace(cleanup=lambda render_data: None) + + # In each run, three samples share a label above 2**24 and one differs; float32 would merge neighbouring labels. + majority = 2**24 + 1 + 2 * runs + labels = majority[:, None].repeat(1, 4) + labels[:, 2] = 2**30 + runs + labels = torch.stack((labels.reshape(-1), (labels + 7).reshape(-1))) + + def render(camera, env_mask): + camera.renderer_labels.copy_(labels.to(torch.int32).reshape(camera.renderer_labels.shape)) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) + camera = object.__new__(FoveatedNewtonCamera) + camera._device = "cpu" + camera.cfg = SimpleNamespace( + foveated_style="warped_cartesian_as_grid", + mask_to_sensor_fov=False, + pool_enabled=True, + pool_mode="avg", + pool_int_mode="mode", + pool_sample_cortex=False, + image_rotation_deg=0, + data_types=["rgba", "semantic_segmentation"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + camera._update_buffers_impl(None) + + # The modal label of each run after the footprint mask zeroes samples outside the retina, ties to the nearest. + rendered = labels.clone() + rendered[:, ~highres.valid_mask] = 0 + expected = torch.zeros(2, len(coords), dtype=torch.int64) + for env in range(2): + for sample in range(len(coords)): + run = rendered[env, 4 * sample : 4 * sample + 4].tolist() + expected[env, sample] = max(run, key=lambda label: (run.count(label), -run.index(label))) + published = camera._data.output["semantic_segmentation"].torch + assert published.dtype == torch.int32 + torch.testing.assert_close(published[..., 0].long(), coords.as_grid(expected, sample_dim=1), rtol=0, atol=0) + assert camera.image_shape == (16, 16) and camera._data.image_shape == (16, 16) + + @pytest.mark.parametrize("size, valid", [(83, False), (100, False), (128, True)]) def test_native_grid_fractional_pool_resolution_validates_newton_tiles(size, valid) -> None: camera = SimpleNamespace(cfg=SimpleNamespace(width=size, height=size)) diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py new file mode 100644 index 000000000000..7aa415026772 --- /dev/null +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -0,0 +1,34 @@ +# 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 + +"""RTX camera configuration contracts that need no renderer.""" + +from types import SimpleNamespace + +import pytest +from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera + +pytestmark = pytest.mark.kitless + + +def test_async_ovrtx_with_the_sensor_mask_is_rejected(monkeypatch) -> None: + # The camera never initializes, so its destructor has nothing to release. + monkeypatch.setattr(FoveatedRTXCamera, "__del__", lambda self: None, raising=False) + renderer = SimpleNamespace(renderer_type="ovrtx", async_rendering=True) + with pytest.raises(ValueError, match="async_rendering"): + FoveatedRTXCamera(SimpleNamespace(renderer_cfg=renderer, mask_to_sensor_fov=True)) + + +def test_near_clip_comes_from_spawn_or_else_the_camera_prim() -> None: + pxr = pytest.importorskip("pxr") + stage = pxr.Usd.Stage.CreateInMemory() + camera = pxr.UsdGeom.Camera.Define(stage, "/Camera") + camera.GetClippingRangeAttr().Set(pxr.Gf.Vec2f(0.05, 100.0)) + prim = camera.GetPrim() + + existing = SimpleNamespace(cfg=SimpleNamespace(spawn=None)) + assert FoveatedRTXCamera._near_clipping_distance(existing, prim) == pytest.approx(0.05) + spawned = SimpleNamespace(cfg=SimpleNamespace(spawn=SimpleNamespace(clipping_range=(0.01, 20.0)))) + assert FoveatedRTXCamera._near_clipping_distance(spawned, prim) == pytest.approx(0.01) diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index e57a0c2d4f65..845d1579130c 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -18,6 +18,7 @@ from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.pooling import build_lowres_coords +from isaaclab.sensors.camera.camera import Camera from isaaclab.utils.math import ( convert_camera_frame_orientation_convention, matrix_from_quat, @@ -192,6 +193,19 @@ def opengl(orientation: torch.Tensor) -> torch.Tensor: assert (camera._gaze_validity(2) == expected).float().mean() > 0.999 +def test_moving_the_mount_is_recorded(monkeypatch) -> None: + monkeypatch.setattr(Camera, "set_world_poses", lambda *args, **kwargs: None) + monkeypatch.setattr(Camera, "set_world_poses_from_view", lambda *args, **kwargs: None) + for move in ( + lambda camera: camera.set_world_poses(positions=torch.zeros(2, 3)), + lambda camera: camera.set_world_poses_from_view(torch.zeros(2, 3), torch.ones(2, 3)), + ): + camera = GazeHarness() + camera.mount_moved = False + move(camera) + assert camera.mount_moved + + def test_pose_update_records_the_mount_before_the_gaze() -> None: camera = GazeHarness() mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) From 0e1d7597c3568785a13760b4b5bb39541ac9d9f8 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 23:38:13 -0800 Subject: [PATCH 32/81] Address the second review round on the foveated camera and active gaze Measure teacher gazes in the upright image frame of a rolled mount, bind the fixed mount from the camera's own orientation, validate gaze bounds, consume the supplied gaze actions, and move GazeActionCfg to gaze_cfg.py with a resolvable class_type. Publish only the updated environments on partial Newton and RTX updates, keep each row's gaze rotation until its pose is turned, reuse the sensor-mask buffers, store gaze buffers as ProxyArrays, require one gaze row per camera, record only successful mount turns, and key Warp streams by device. Unlock RTX cameras at construction instead of rewriting spawn, release lens textures with the camera, import pxr where prims are authored, keep config imports free of Warp, and drop canonical_to_grid and the ModalPooler module. Tests: rolled-mount teacher fixation, config validation, supplied actions, partial publication, rendered sample density, pooling modes, dispatch, and kitless markers. --- source/isaaclab_fovi/docs/README.md | 5 +- .../isaaclab_fovi/mdp/__init__.pyi | 2 +- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 254 +++++++++--------- .../isaaclab_fovi/mdp/gaze_cfg.py | 47 ++++ .../isaaclab_fovi/sensors/foveated_camera.py | 165 +++++++----- .../sensors/foveated_camera_cfg.py | 22 +- .../sensors/foveated_newton_camera.py | 43 +-- .../sensors/foveated_rtx_camera.py | 53 ++-- .../isaaclab_fovi/sensors/gaze_kernels.py | 36 ++- .../isaaclab_fovi/sensors/lens_lut.py | 11 +- .../isaaclab_fovi/sensors/native_grid.py | 21 +- .../isaaclab_fovi/sensors/pooling.py | 39 +-- .../isaaclab_fovi/tasks/__init__.py | 3 +- .../test/foveated_render_cases.py | 64 +++-- source/isaaclab_fovi/test/test_active_gaze.py | 130 ++++++++- .../test/test_backend_dispatch.py | 22 +- .../isaaclab_fovi/test/test_gaze_kernels.py | 7 +- source/isaaclab_fovi/test/test_native_grid.py | 4 +- .../isaaclab_fovi/test/test_newton_buffers.py | 54 ++-- source/isaaclab_fovi/test/test_pooling.py | 63 ++++- source/isaaclab_fovi/test/test_rtx_camera.py | 64 ++++- .../test/test_spherical_geometry.py | 103 ++++--- 22 files changed, 788 insertions(+), 424 deletions(-) create mode 100644 source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index 8a9514d18c0a..eb5639995bb3 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -112,8 +112,9 @@ physical camera's image at the current gaze. - `GazeActionCfg`: two actions that move the gaze by up to `step_size` field radii (half the retina's field of view) per step, within `gaze_limit` field radii of the optical axis. Make it the last action term. With the default - `mount="fixed"` the camera hangs on the environment and the teacher aims from - its configured mount; `mount="tracked"` lets the camera ride a moving body, + `mount="fixed"` the teacher aims from the orientation the camera has when the + action is created, and turning the mount raises; `mount="tracked"` lets the + camera ride a moving body, such as a turning head, and the teacher follows each camera's current mount (Newton or OVRTX). - `gaze_state`: the gaze, in field radii, and its velocity, in field radii per diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi index 7f86412ab9dd..577237ff3391 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -19,7 +19,6 @@ __all__ = [ from .gaze import ( GazeAction, - GazeActionCfg, angles_to_direction, clamp_gaze, direction_to_angles, @@ -30,3 +29,4 @@ from .gaze import ( random_gaze, teacher_labels, ) +from .gaze_cfg import GazeActionCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index efea6551833a..2046f241602a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -14,21 +14,19 @@ from __future__ import annotations import math -from dataclasses import MISSING from typing import TYPE_CHECKING, ClassVar import torch import warp as wp -from isaaclab.managers import ActionTerm, ActionTermCfg, ManagerTermBase, ObservationTermCfg, SceneEntityCfg -from isaaclab.utils import configclass -from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_apply +from isaaclab.managers import ActionTerm, ManagerTermBase, ObservationTermCfg, SceneEntityCfg +from isaaclab.utils.math import quat_apply +from isaaclab.utils.warp import ProxyArray -from ..sensors.calibrated_geometry import resolve_camera_model, sampling_geometry +from ..sensors.calibrated_geometry import convert_camera_frame_quaternion from ..sensors.gaze_kernels import ( DEG_TO_RAD, CameraParams, - camera_params, project_direction, project_directions, record_launch, @@ -38,6 +36,8 @@ if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv, ManagerBasedRLEnv + from .gaze_cfg import GazeActionCfg + RAD_TO_DEG = 180.0 / math.pi @@ -47,15 +47,21 @@ def teach( position: wp.vec3f, mount: wp.quatf, g: wp.vec2f, + frame: wp.mat33f, field_radius_deg: wp.float32, step_size: wp.float32, gaze_limit: wp.float32, camera: CameraParams, ) -> wp.vec4f: - """The teacher's action (x, y) toward a point, 1 for a valid target or else 0, and the gaze's error [deg].""" + """The teacher's action (x, y) toward a point, 1 for a valid target or else 0, and the gaze's error [deg]. + + ``frame`` carries the upright image frame, in which gazes are measured, into the physical camera's frame. + """ d = wp.normalize(wp.quat_rotate_inv(mount, point - position)) - tilt = -wp.atan2(d[1], wp.sqrt(d[0] * d[0] + d[2] * d[2])) * wp.float32(RAD_TO_DEG) - pan = -wp.atan2(d[0], d[2]) * wp.float32(RAD_TO_DEG) + # The fixation reaches the physical camera at frame * gaze * z, so the gaze looks along frame^T d. + u = wp.transpose(frame) * d + tilt = -wp.atan2(u[1], wp.sqrt(u[0] * u[0] + u[2] * u[2])) * wp.float32(RAD_TO_DEG) + pan = -wp.atan2(u[0], u[2]) * wp.float32(RAD_TO_DEG) desired = wp.vec2f(tilt, pan) / field_radius_deg ok = project_direction(d, camera)[2] > 0.5 and wp.length(desired) <= gaze_limit step = wp.vec2f(0.0, 0.0) @@ -67,7 +73,7 @@ def teach( g_pan = g[1] * field_radius_deg * wp.float32(DEG_TO_RAD) looking = wp.vec3f(-wp.cos(g_tilt) * wp.sin(g_pan), -wp.sin(g_tilt), wp.cos(g_tilt) * wp.cos(g_pan)) # atan2 stays accurate near perfect alignment, unlike acos of the dot product. - error = wp.atan2(wp.length(wp.cross(looking, d)), wp.dot(looking, d)) * wp.float32(RAD_TO_DEG) + error = wp.atan2(wp.length(wp.cross(looking, u)), wp.dot(looking, u)) * wp.float32(RAD_TO_DEG) return wp.vec4f(step[0], step[1], wp.where(ok, 1.0, 0.0), error) @@ -79,8 +85,8 @@ def teacher_labels_kernel( rotate_offset: wp.int32, positions: wp.array(dtype=wp.vec3f), mounts: wp.array(dtype=wp.quatf), - mount_per_env: wp.int32, - gaze: wp.array(dtype=wp.vec2f), + state: wp.array(dtype=wp.vec4f), + frame: wp.mat33f, field_radius_deg: wp.float32, step_size: wp.float32, gaze_limit: wp.float32, @@ -91,7 +97,7 @@ def teacher_labels_kernel( """Labels (action x, action y, valid) toward a point fixed to each target; and the mean gaze error to valid targets [deg] with the fraction of valid targets. - ``mounts`` holds each camera's mount (ROS convention), or one mount shared by all when ``mount_per_env`` is 0. + ``mounts`` holds each camera's mount (ROS convention); ``state`` each gaze, in field radii, and its velocity. One block labels every environment and reduces the logs itself, so the launch needs no zeroed accumulators. """ _block, lane = wp.tid() @@ -103,10 +109,9 @@ def teacher_labels_kernel( point = targets[i] if rotate_offset != 0: point = point + wp.quat_rotate(orientations[i], offset) - mount = mounts[0] - if mount_per_env != 0: - mount = mounts[i] - result = teach(point, positions[i], mount, gaze[i], field_radius_deg, step_size, gaze_limit, camera) + s = state[i] + gaze = wp.vec2f(s[0], s[1]) + result = teach(point, positions[i], mounts[i], gaze, frame, field_radius_deg, step_size, gaze_limit, camera) labels[i, 0] = result[0] labels[i, 1] = result[1] labels[i, 2] = result[2] @@ -205,11 +210,13 @@ class GazeAction(ActionTerm): Actions, the limit and the observed gaze are in field radii. An action of 1 changes a coordinate by ``step_size``, and the gaze stays within ``gaze_limit`` of the optical axis. The gaze starts each episode on the - optical axis, or anywhere the physical camera sees within the limit when ``random_reset`` is set. + optical axis, or anywhere the physical camera sees within the limit when ``random_reset`` is set. Gazes are measured + in the upright image frame, which :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.image_rotation_deg` rolls + against a rolled mount. - With ``mount="fixed"`` the camera hangs on the environment at its configured offset, and the teacher uses that - mount; moving the camera's mount raises. With ``mount="tracked"`` the camera may ride a moving body, for example a - robot's head, and the teacher reads each camera's current mount, so software gaze adds to hardware gaze. + With ``mount="fixed"`` the camera keeps the orientation it had when the term was created, and the teacher uses + that mount; turning the camera's mount raises. With ``mount="tracked"`` the camera may ride a moving body, for + example a robot's head, and the teacher reads each camera's current mount, so software gaze adds to hardware gaze. """ cfg: GazeActionCfg @@ -219,87 +226,68 @@ class GazeAction(ActionTerm): physics may record the other terms' actions and its decimation loop into a CUDA graph.""" def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): + cfg.validate_config() super().__init__(cfg, env) self.camera = self._asset - camera_cfg = self.camera.cfg - if cfg.mount not in ("fixed", "tracked"): - raise ValueError(f"Gaze mount must be 'fixed' or 'tracked', got {cfg.mount!r}.") + camera = self.camera self.tracked_mount = cfg.mount == "tracked" - if self.tracked_mount: - if not (self.camera._gaze_pose_reads_angles and camera_cfg.update_latest_camera_pose): - raise ValueError( - "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX," - " with update_latest_camera_pose." - ) - elif camera_cfg.prim_path.rpartition("/")[0] not in ("{ENV_REGEX_NS}", env.scene.env_regex_ns): + if self.tracked_mount and not (camera._gaze_pose_reads_angles and camera.cfg.update_latest_camera_pose): + raise ValueError( + "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX," + " with update_latest_camera_pose." + ) + if not self.tracked_mount and camera.cfg.prim_path.rpartition("/")[0] not in ( + "{ENV_REGEX_NS}", + env.scene.env_regex_ns, + ): + # A body's motion turns its camera without set_world_poses, which the fixed mount could not detect. raise ValueError( - f"A fixed gaze mount needs a camera mounted on the environment, got {camera_cfg.prim_path!r};" + f"A fixed gaze mount needs a camera mounted on the environment, got {camera.cfg.prim_path!r};" " use mount='tracked' for a camera on a moving body." ) - self.camera_model = resolve_camera_model(camera_cfg) - self._camera = camera_params(self.camera_model) - self.field_radius_deg = sampling_geometry(camera_cfg)[0] / 2 + if not hasattr(camera, "_gaze_camera"): + raise RuntimeError(f"The gaze camera {cfg.asset_name!r} must be initialized before its gaze action.") + # The camera's own geometry, so the teacher and the sensor mask share one projection. + self.camera_model = camera._camera_model + self._camera = camera._gaze_camera + self._frame = camera._mask_frame + self._frame_torch = torch.tensor( + [[self._frame[row][col] for col in range(3)] for row in range(3)], device=self.device + ) + self.field_radius_deg = camera.sampling_coords.fov / 2 """Half the retina's field of view [deg].""" - offset = camera_cfg.offset - rotation = torch.tensor(offset.rot, dtype=torch.float32, device=self.device)[None] - self.mount_rotation = convert_camera_frame_orientation_convention( - rotation, origin=offset.convention, target="ros" - )[0] - """Configured orientation (x, y, z, w) of the physical camera in the environment frame, ROS convention.""" - self._fixed_mount = wp.from_torch(self.mount_rotation[None].contiguous(), dtype=wp.quatf) - self._tracked_mounts: tuple[torch.Tensor, wp.array] | None = None - self._raw = torch.zeros(self.num_envs, 2, device=self.device) - """Gaze actions of the last step; once bound, a view of the action manager's buffer.""" - self._angles = None - """Gaze angles [deg] of the last step; the camera's own buffer, bound on first use.""" - self._state = torch.zeros(self.num_envs, 4, device=self.device) + self._fixed_mount = None + if not self.tracked_mount: + # The camera's ungazed world orientation now, ROS convention; the fixed-mount teacher keeps it. + orientation = camera._data.quat_w_world + orientation = orientation.torch if hasattr(orientation, "torch") else orientation + opengl = convert_camera_frame_quaternion(orientation.float(), origin="world", target="opengl") + ros = convert_camera_frame_quaternion(opengl, origin="opengl", target="ros") + self._fixed_mount = ProxyArray(wp.from_torch(ros.contiguous(), dtype=wp.quatf)) + self._raw: torch.Tensor | None = None + """Gaze actions of the last step, as supplied to :meth:`process_actions`.""" + self._state = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec4f, device=self.device)) """Gaze and its velocity, the gaze observation; the gaze and velocity are views of it.""" - self._gaze = self._state[:, :2] - self._velocity = self._state[:, 2:] - self._gaze_wp = wp.from_torch(self._gaze, dtype=wp.vec2f) - self._state_wp = wp.from_torch(self._state, dtype=wp.vec4f) - self._step_launch = None - self._labels = torch.zeros(self.num_envs, 3, device=self.device) - self._log = torch.zeros(2, device=self.device) + self._gaze = self._state.torch[:, :2] + self._velocity = self._state.torch[:, 2:] + self._step_launch: tuple[tuple, wp.Launch] | None = None + self._labels = ProxyArray(wp.zeros((self.num_envs, 3), dtype=wp.float32, device=self.device)) + self._log = ProxyArray(wp.zeros(2, dtype=wp.float32, device=self.device)) """Mean gaze error to valid teacher targets [deg] and the fraction of valid targets.""" - self._no_orientations = wp.from_torch(torch.zeros(1, 4, device=self.device), dtype=wp.quatf) + self._no_orientations = wp.zeros(1, dtype=wp.quatf, device=self.device) self._labels_launch = None # Each reset copies its environments, and their start gazes if random, into these and replays one launch. - self._reset_ids = torch.zeros(self.num_envs, dtype=torch.int32, device=self.device) - self._reset_start = torch.zeros(self.num_envs, 2, device=self.device) + self._reset_ids = ProxyArray(wp.zeros(self.num_envs, dtype=wp.int32, device=self.device)) + self._reset_start = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec2f, device=self.device)) self._reset_launches: dict[tuple[bool, bool], wp.Launch] = {} - def _bind(self) -> None: - """Read actions from the action manager's buffer and write angles into the camera's, saving a copy each.""" - manager = self._env.action_manager - terms = [manager.get_term(name) for name in manager.active_terms] - start = sum(manager.action_term_dim[: terms.index(self)]) - # The manager stores each step's actions before handing this term its slice, so the values are the same. - self._raw = manager.action[:, start : start + self.action_dim] - self._angles = self.camera.gaze_angles_buffer() - self._angles_wp = wp.from_torch(self._angles, dtype=wp.vec2f) - self._step_launch = record_launch( - gaze_step_kernel, - self.num_envs, - [ - wp.from_torch(self._raw, dtype=wp.vec2f), - self._state_wp, - self._angles_wp, - self.cfg.step_size, - self.cfg.gaze_limit, - self._env.step_dt, - self.field_radius_deg, - ], - device=self.device, - ) - @property def action_dim(self) -> int: return 2 @property def raw_actions(self) -> torch.Tensor: - return self._raw + return self._raw if self._raw is not None else torch.zeros_like(self._gaze) @property def processed_actions(self) -> torch.Tensor: @@ -318,7 +306,7 @@ def velocity(self) -> torch.Tensor: @property def state(self) -> torch.Tensor: """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" - return self._state + return self._state.torch @property def angles_deg(self) -> torch.Tensor: @@ -326,19 +314,39 @@ def angles_deg(self) -> torch.Tensor: return self._gaze * self.field_radius_deg def process_actions(self, actions: torch.Tensor): - """Move the gaze by this step's actions, which the term reads from the action manager's buffer.""" - if self._step_launch is None: - self._bind() - self._step_launch.launch(warp_stream(self.device)) - self.camera.set_gaze_angles(self._angles) + """Move the gaze by the supplied actions, shape (num_envs, 2). + + The launch reads ``actions`` in place. The action manager hands the term the same slice of its buffer each + step, so the launch is recorded once; another buffer records a launch that reads it. + """ + if actions.dtype != torch.float32: + actions = actions.float() + key = (actions.data_ptr(), actions.stride(), actions.device) + if self._step_launch is None or self._step_launch[0] != key: + launch = record_launch( + gaze_step_kernel, + self.num_envs, + [ + wp.from_torch(actions, dtype=wp.vec2f), + self._state, + self._camera_angles(), + self.cfg.step_size, + self.cfg.gaze_limit, + self._env.step_dt, + self.field_radius_deg, + ], + device=self.device, + ) + self._step_launch = (key, launch) + self._raw = actions + self._step_launch[1].launch(warp_stream(self.device)) + self.camera.set_gaze_angles(self._camera_angles().torch) def apply_actions(self): pass def reset(self, env_ids=None): # The action manager zeroes the reset environments' actions itself. - if self._step_launch is None: - self._bind() indexed = env_ids is not None count = self.num_envs if indexed: @@ -347,35 +355,35 @@ def reset(self, env_ids=None): count = len(env_ids) if count == 0: return - self._reset_ids[:count] = torch.as_tensor(env_ids, device=self.device) + self._reset_ids.torch[:count] = torch.as_tensor(env_ids, device=self.device) random_start = self.cfg.random_reset if random_start: gaze = random_gaze(count, self.cfg.gaze_limit, self.device) visible = self.visible(angles_to_direction(gaze * self.field_radius_deg)) - self._reset_start[:count] = torch.where(visible[:, None], gaze, 0.0) + self._reset_start.torch[:count] = torch.where(visible[:, None], gaze, 0.0) + angles = self._camera_angles() launch = self._reset_launches.get((indexed, random_start)) if launch is None: launch = self._reset_launches[(indexed, random_start)] = record_launch( gaze_reset_kernel, self.num_envs, - [ - wp.from_torch(self._reset_ids), - int(indexed), - wp.from_torch(self._reset_start, dtype=wp.vec2f), - int(random_start), - self.field_radius_deg, - ], - [self._angles_wp, self._state_wp], + [self._reset_ids, int(indexed), self._reset_start, int(random_start), self.field_radius_deg], + [angles, self._state], self.device, ) launch.set_dim(count) launch.launch(warp_stream(self.device)) # The camera keeps reading the same buffer, which every other environment already holds. - self.camera.set_gaze_angles(self._angles) + self.camera.set_gaze_angles(angles.torch) + + def _camera_angles(self) -> ProxyArray: + """The camera's stored gaze angles [deg], which the gaze kernels write in place.""" + self.camera.gaze_angles_buffer() + return self.camera._gaze_angles def visible(self, direction: torch.Tensor) -> torch.Tensor: - """Whether camera-frame directions fall inside the physical camera's image.""" - return project_directions(direction, self._camera)[1] + """Whether directions in the upright gaze frame fall inside the physical camera's image.""" + return project_directions(direction @ self._frame_torch.T, self._camera)[1] def _teacher_labels( self, targets: wp.array, orientations: wp.array | None = None, offset: wp.vec3f | None = None @@ -392,16 +400,14 @@ def _teacher_labels( [deg] with the fraction of valid targets, shape (2,). Both are buffers the next call overwrites. Raises: - RuntimeError: The camera's mount moved while the gaze assumes a fixed mount. + RuntimeError: The camera's mount turned while the gaze assumes a fixed mount. """ if self.tracked_mount: - source = self.camera.mount_quat_w_ros - if self._tracked_mounts is None or self._tracked_mounts[0] is not source: - self._tracked_mounts = (source, wp.from_torch(source, dtype=wp.quatf)) - mounts = self._tracked_mounts[1] + self.camera.gaze_angles_buffer() + mounts = self.camera._mount_quat_ros elif self.camera.mount_moved: raise RuntimeError( - "The gaze camera's mount moved, so the fixed-mount teacher would aim from the configured mount;" + "The gaze camera's mount turned, so the fixed-mount teacher would aim from its first orientation;" " use GazeActionCfg.mount='tracked'." ) else: @@ -420,40 +426,20 @@ def _teacher_labels( int(orientations is not None), positions, mounts, - int(self.tracked_mount), - self._gaze_wp, + self._state, + self._frame, self.field_radius_deg, self.cfg.step_size, self.cfg.gaze_limit, self._camera, ], - [wp.from_torch(self._labels), wp.from_torch(self._log)], + [self._labels, self._log], self.device, block_dim=block, ) self._labels_launch = (sources, launch) self._labels_launch[1].launch(warp_stream(self.device)) - return self._labels, self._log - - -@configclass -class GazeActionCfg(ActionTermCfg): - """Configuration of :class:`GazeAction`.""" - - class_type: type = GazeAction - asset_name: str = MISSING - """Scene name of the foveated camera whose gaze the action moves.""" - step_size: float = 0.1 - """Change of each gaze coordinate per step at an action of 1, in field radii.""" - gaze_limit: float = 1.0 - """Largest distance of the gaze from the camera's optical axis, in field radii.""" - random_reset: bool = False - """Start episodes at a random gaze the camera sees; otherwise on the optical axis.""" - mount: str = "fixed" - """``"fixed"``: the camera hangs on the environment at its configured offset, and moving its mount raises. - ``"tracked"``: the camera may ride a moving body, and the teacher follows each camera's current mount, so the gaze - adds to hardware gaze such as a turning head. Tracking needs a camera whose pose update turns the gaze (Newton or - OVRTX).""" + return self._labels.torch, self._log.torch def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py new file mode 100644 index 000000000000..aa58d67236c3 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py @@ -0,0 +1,47 @@ +# 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 + +"""Configuration of the active-gaze action.""" + +from __future__ import annotations + +import math +from dataclasses import MISSING +from typing import TYPE_CHECKING + +from isaaclab.managers import ActionTermCfg +from isaaclab.utils import configclass + +if TYPE_CHECKING: + from .gaze import GazeAction + + +@configclass +class GazeActionCfg(ActionTermCfg): + """Configuration of :class:`~isaaclab_fovi.mdp.gaze.GazeAction`.""" + + class_type: type[GazeAction] | str = "{DIR}.gaze:GazeAction" + asset_name: str = MISSING + """Scene name of the foveated camera whose gaze the action moves.""" + step_size: float = 0.1 + """Change of each gaze coordinate per step at an action of 1, in field radii. Positive and finite.""" + gaze_limit: float = 1.0 + """Largest distance of the gaze from the camera's optical axis, in field radii. Positive and finite.""" + random_reset: bool = False + """Start episodes at a random gaze the camera sees; otherwise on the optical axis.""" + mount: str = "fixed" + """``"fixed"``: the camera keeps the orientation it has when the action is created, and turning its mount raises. + ``"tracked"``: the camera may ride a moving body, and the teacher follows each camera's current mount, so the gaze + adds to hardware gaze such as a turning head. Tracking needs a camera whose pose update turns the gaze (Newton or + OVRTX).""" + + def validate_config(self): + """Reject gaze bounds that would divide by zero and unknown mounts.""" + for name in ("step_size", "gaze_limit"): + value = getattr(self, name) + if not (isinstance(value, (int, float)) and math.isfinite(value) and value > 0): + raise ValueError(f"GazeActionCfg.{name} must be positive and finite, got {value!r}.") + if self.mount not in ("fixed", "tracked"): + raise ValueError(f"GazeActionCfg.mount must be 'fixed' or 'tracked', got {self.mount!r}.") diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 4b8b4b5fc67d..42d884f80081 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -15,6 +15,7 @@ import warp as wp from isaaclab.sensors.camera.camera import Camera +from isaaclab.utils.warp import ProxyArray from .calibrated_geometry import convert_camera_frame_quaternion, resolve_camera_model, retinal_directions from .gaze_kernels import ( @@ -26,7 +27,6 @@ record_launch, sensor_visibility_kernel, set_gaze_kernel, - torch_stream, warp_stream, ) from .native_grid import GRID_STYLE, native_grid_directions @@ -90,7 +90,9 @@ def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): def __init__(self, cfg: FoveatedCameraCfg): # The parent's initialisation updates poses before the gaze exists. - self._gaze_angles = self._gaze_rotation = None + self._gaze_angles: ProxyArray | None = None + self._gaze_rotation: ProxyArray | None = None + self._visibility = None self._grid_publish = None self._published_shape: tuple[int, int] | None = None self.mount_moved = False @@ -109,8 +111,8 @@ def gaze_angles_buffer(self) -> torch.Tensor: :meth:`set_gaze_angles`, which then copies nothing. Writes take effect when :meth:`set_gaze_angles` is called. """ if self._gaze_angles is None: - self._allocate_gaze(self._view.count, torch.device(self._device)) - return self._gaze_angles + self._allocate_gaze() + return self._gaze_angles.torch def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. @@ -120,30 +122,31 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: Args: angles_deg: Gaze angles for every environment [deg], shape (num_envs, 2). + + Raises: + ValueError: The angles do not hold one row per camera. """ - stored = angles_deg is self._gaze_angles and angles_deg is not None + stored = self._gaze_angles is not None and angles_deg is self._gaze_angles.torch if stored and self._gaze_pose_reads_angles and self.cfg.update_latest_camera_pose: # The next pose update reads the stored angles; nothing has to happen now. return - angles = angles_deg if stored else angles_deg.detach().float().contiguous() - if ( - self._gaze_angles is None - or len(self._gaze_angles) != len(angles) - or self._gaze_angles.device != angles.device - ): - self._allocate_gaze(len(angles), angles.device) + count = self._view.count + if tuple(angles_deg.shape) != (count, 2): + raise ValueError(f"Gaze angles must have shape ({count}, 2), got {tuple(angles_deg.shape)}.") + gaze = self.gaze_angles_buffer() + angles = angles_deg if stored else angles_deg.detach().to(device=gaze.device, dtype=torch.float32).contiguous() # Callers usually pass the same buffer every step; record its launch once. - key = (angles.data_ptr(), angles.shape, angles.device) + key = angles.data_ptr() if key != self._gaze_angles_key: self._gaze_angles_key = key self._set_gaze_launch = record_launch( set_gaze_kernel, - len(angles), + count, [wp.from_torch(angles, dtype=wp.vec2f)], - [self._gaze_angles_wp, self._gaze_rotation_wp], - angles.device, + [self._gaze_angles, self._gaze_rotation], + gaze.device, ) - self._set_gaze_launch.launch(warp_stream(angles.device)) + self._set_gaze_launch.launch(warp_stream(gaze.device)) @property def mount_quat_w_ros(self) -> torch.Tensor: @@ -156,35 +159,43 @@ def mount_quat_w_ros(self) -> torch.Tensor: if not self._gaze_pose_reads_angles: raise RuntimeError("Only cameras whose pose update turns the gaze (Newton, OVRTX) record their mount.") self.gaze_angles_buffer() - return self._mount_quat_ros + return self._mount_quat_ros.torch def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): """Move the camera's mount; the gaze stays relative to the new mount. Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. """ - self.mount_moved = True super().set_world_poses(positions, orientations, env_ids, convention) + # The teachers read the camera's live position, so only a turned mount counts as moved. + if orientations is not None: + self.mount_moved = True def set_world_poses_from_view(self, eyes, targets, env_ids=None): """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. """ - self.mount_moved = True super().set_world_poses_from_view(eyes, targets, env_ids) - - def _allocate_gaze(self, count: int, device: torch.device) -> None: - """Allocate the stored gaze, on the optical axis, and its rotation.""" - self._gaze_angles = torch.zeros(count, 2, device=device) - self._gaze_rotation = torch.eye(3, device=device).repeat(count, 1, 1) - self._mount_quat_ros = torch.zeros(count, 4, device=device) - self._gaze_angles_wp = wp.from_torch(self._gaze_angles, dtype=wp.vec2f) - self._gaze_rotation_wp = wp.from_torch(self._gaze_rotation, dtype=wp.mat33f) - self._mount_quat_ros_wp = wp.from_torch(self._mount_quat_ros, dtype=wp.quatf) + if self._turned_by_view(eyes, targets).any(): + self.mount_moved = True + + def _turned_by_view(self, eyes, targets) -> torch.Tensor: + """Which rows :meth:`set_world_poses_from_view` turns: the base method skips an eye equal to its target.""" + return (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0 + + def _allocate_gaze(self) -> None: + """Allocate one stored gaze per camera, on the optical axis, its rotation and the mount, on the sensor + device.""" + count, device = self._view.count, str(self._device) + self._gaze_angles = ProxyArray(wp.zeros(count, dtype=wp.vec2f, device=device)) + self._gaze_rotation = ProxyArray( + wp.from_torch(torch.eye(3, device=device).repeat(count, 1, 1), dtype=wp.mat33f) + ) + self._mount_quat_ros = ProxyArray(wp.zeros(count, dtype=wp.quatf, device=device)) self._gaze_angles_key = None self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} - self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=str(device)) + self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=device) def _apply_gaze_pose( self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None @@ -194,9 +205,9 @@ def _apply_gaze_pose( return orientation = self._data.quat_w_world orientation = orientation.warp if hasattr(orientation, "warp") else wp.from_torch(orientation, dtype=wp.quatf) - device = self._gaze_angles.device - frames = (self._gaze_angles_wp, *self._gaze_frames) - outputs = [orientation, self._gaze_rotation_wp, self._mount_quat_ros_wp] + device = self._gaze_angles.torch.device + frames = (self._gaze_angles, *self._gaze_frames) + outputs = [orientation, self._gaze_rotation, self._mount_quat_ros] indexed = env_ids is not None and env_mask is None if indexed and not isinstance(env_ids, wp.array): env_ids = wp.from_torch(torch.as_tensor(env_ids, dtype=torch.int32, device=device).contiguous()) @@ -209,7 +220,7 @@ def _apply_gaze_pose( launch = record_launch(apply_gaze_indexed_kernel, len(env_ids), [*frames, env_ids], outputs, device) else: mask = [self._gaze_no_mask if env_mask is None else env_mask, int(env_mask is not None)] - launch = record_launch(apply_gaze_kernel, len(self._gaze_angles), [*frames, *mask], outputs, device) + launch = record_launch(apply_gaze_kernel, self._view.count, [*frames, *mask], outputs, device) self._gaze_pose_launches[mode] = (launch, (orientation, env_mask)) if indexed: if len(env_ids) == 0: @@ -245,10 +256,10 @@ def _initialize_gaze(self) -> None: else: rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) self._gaze_rays = (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() - self._gaze_rays_wp: dict[torch.device, wp.array] = {} # No gaze until one is set: the camera looks along its optical axis untouched. self._gaze_angles = None self._gaze_rotation = None + self._visibility = None device = self._gaze_rays.device self._gaze_identity = torch.eye(3, device=device) angle = math.radians(rotation_deg) @@ -273,40 +284,56 @@ def _initialize_gaze(self) -> None: # Sensor mask and publication # ------------------------------------------------------------------ - def _gaze_validity(self, batch_size: int) -> torch.Tensor: - """Return which samples the physical camera sees at the current gaze, shape (batch_size, num_samples).""" - if self._gaze_rotation is None: - rotation = self._gaze_identity.expand(batch_size, -1, -1).contiguous() - rotation_wp = wp.from_torch(rotation, dtype=wp.mat33f) - else: - rotation, rotation_wp = self._gaze_rotation, self._gaze_rotation_wp - device = rotation.device - rays_wp = self._gaze_rays_wp.get(device) - if rays_wp is None: - rays_wp = self._gaze_rays_wp[device] = wp.from_torch(self._gaze_rays.to(device), dtype=wp.vec3f) - valid = torch.empty(batch_size, len(self._gaze_rays), dtype=torch.bool, device=device) - # A receptive field can overlap the sensor even when its center is outside it. - with torch_stream(device): - wp.launch( + def _visibility_buffers(self) -> dict: + """The sensor mask's camera-owned buffers, allocated once: the rendered rays, an unturned rotation per camera, + each sample's visibility and, for the updated rows, which samples to hide.""" + if self._visibility is None: + count, device = self._view.count, self._gaze_rays.device + shape = (count, len(self._gaze_rays)) + self._visibility = { + "rays": wp.from_torch(self._gaze_rays, dtype=wp.vec3f), + "identity": wp.from_torch(self._gaze_identity.expand(count, -1, -1).contiguous(), dtype=wp.mat33f), + "every_env": wp.ones(count, dtype=wp.bool, device=str(device)), + "valid": ProxyArray(wp.zeros(shape, dtype=wp.bool, device=str(device))), + "hidden": ProxyArray(wp.zeros(shape, dtype=wp.bool, device=str(device))), + "launch": None, + } + return self._visibility + + def _gaze_validity(self, env_mask: wp.array | None = None) -> torch.Tensor: + """Which samples the physical camera sees at each updated environment's gaze, shape (num_envs, num_samples). + + Each rendered ray is tested by its center direction. Environments outside ``env_mask`` keep their last + visibility; None updates every one. + """ + buffers = self._visibility_buffers() + rotation = buffers["identity"] if self._gaze_rotation is None else self._gaze_rotation.warp + updated = buffers["every_env"] if env_mask is None else env_mask + cached = buffers["launch"] + if cached is None or cached[0] is not rotation or cached[1] is not updated: + launch = record_launch( sensor_visibility_kernel, - dim=valid.shape, - inputs=[rays_wp, rotation_wp, self._mask_frame, self._gaze_camera], - outputs=[wp.from_torch(valid, dtype=wp.bool)], + buffers["valid"].warp.shape, + [buffers["rays"], rotation, self._mask_frame, self._gaze_camera, updated], + [buffers["valid"], buffers["hidden"]], + self._gaze_rays.device, ) - return valid + buffers["launch"] = cached = (rotation, updated, launch) + cached[2].launch(warp_stream(self._gaze_rays.device)) + return buffers["valid"].torch - def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor]) -> None: - """Zero the samples that fall outside the physical camera at the current gaze, in (B, N, 1, C) outputs.""" + def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor], env_mask: wp.array | None = None) -> None: + """Zero the samples outside the physical camera at the current gaze in the updated environments' (B, N, 1, C) + outputs; None updates every environment.""" if not self.cfg.mask_to_sensor_fov: return tensors = {name: value.torch if hasattr(value, "torch") else value for name, value in outputs.items()} - valid = self._gaze_validity(next(iter(tensors.values())).shape[0]) - invalid = ~valid[:, :, None, None] + self._sensor_fov_valid = self._gaze_validity(env_mask) + hidden = self._visibility["hidden"].torch[:, :, None, None] for name, tensor in tensors.items(): if name == "rgb" and "rgba" in tensors: continue - tensor.masked_fill_(invalid, 0) - self._sensor_fov_valid = valid + tensor.masked_fill_(hidden, 0) def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for @@ -320,20 +347,18 @@ def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous()) self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous()) num_envs = views[0][1].shape[0] - self._grid_every_env = wp.ones(num_envs, dtype=wp.bool, device=str(self._device)) if self.cfg.mask_to_sensor_fov: - identity = self._gaze_identity.expand(num_envs, -1, -1).contiguous() - self._sensor_fov_valid_buffer = torch.zeros( - num_envs, len(self._gaze_rays), dtype=torch.bool, device=self._device - ) + buffers = self._visibility_buffers() + self._grid_every_env = buffers["every_env"] self._grid_sensor = ( - wp.from_torch(self._gaze_rays, dtype=wp.vec3f), - wp.from_torch(identity, dtype=wp.mat33f), + buffers["rays"], + buffers["identity"], self._mask_frame, self._gaze_camera, - wp.from_torch(self._sensor_fov_valid_buffer), + buffers["valid"].warp, ) else: + self._grid_every_env = wp.ones(num_envs, dtype=wp.bool, device=str(self._device)) # Placeholders: the kernel reads none of these without the sensor mask. self._grid_sensor = ( wp.zeros(1, dtype=wp.vec3f, device=self._device), @@ -351,7 +376,7 @@ def _publish_grid(self, env_mask: wp.array | None = None) -> None: mask = self.cfg.mask_to_sensor_fov env_mask = self._grid_every_env if env_mask is None else env_mask rays, identity, frame, camera, visible = self._grid_sensor - rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation_wp + rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation.warp cached = self._grid_launches if cached is None or cached[0][0] is not rotation or cached[0][1] is not env_mask: launches = [ @@ -381,7 +406,7 @@ def _publish_grid(self, env_mask: wp.array | None = None) -> None: for launch in self._grid_launches[1]: launch.launch(stream) if mask: - self._sensor_fov_valid = self._sensor_fov_valid_buffer + self._sensor_fov_valid = self._visibility["valid"].torch def _pool_output(self, name: str, samples: torch.Tensor) -> torch.Tensor: """Pool one output's high-resolution samples (B, N_hi, 1, C) to the retina's (B, N_lo, 1, C), in its dtype. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 9121f4d71c28..0e97797ddaf9 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -7,12 +7,23 @@ from __future__ import annotations +import math + +from fovi.sensing.coords import RADIUS_NORMS, WARPED_CARTESIAN_STYLES from fovi.sensing.projection import CameraCalibration from isaaclab.sensors.camera.camera_cfg import CameraCfg from isaaclab.utils.configclass import configclass -from .native_grid import validate_radius_norm + +def validate_radius_norm(radius_norm: float, style: str, fov_type: str) -> None: + """Reject warped-grid radius norms that fovi cannot sample, before renderer startup.""" + if radius_norm not in RADIUS_NORMS: + raise ValueError(f"radius_norm must be one of {RADIUS_NORMS}, got {radius_norm!r}.") + if radius_norm != 2.0 and style not in WARPED_CARTESIAN_STYLES: + raise ValueError("Non-default radius_norm requires a warped_cartesian style.") + if radius_norm == math.inf and fov_type == "wang": + raise ValueError("radius_norm=inf does not support fov_type='wang'.") @configclass @@ -163,12 +174,3 @@ def __post_init__(self): # Resolves the default renderer and forwards deprecated renderer fields. super().__post_init__() validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) - # ``spawn`` is a ``PinholeCameraCfg`` / ``FisheyeCameraCfg`` whose - # ``lock_camera`` field defaults to True. That writes - # ``omni:kit:cameraLock=True`` on every spawned prim, which the RTX - # renderer can interpret as "static camera" and use to skip motion- - # vector synthesis — breaking DLSS-RR temporal reprojection on dynamic - # geometry. Foveated cameras always have a moving fixation pose, so - # we force the lock off here. - if self.spawn is not None and getattr(self.spawn, "lock_camera", None): - self.spawn = self.spawn.replace(lock_camera=False) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 5bca68419e7d..fcb6e3af5f65 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -232,25 +232,36 @@ def _update_poses( self._render_data.camera_rays = self._foveated_rays def _update_buffers_impl(self, env_mask: wp.array): - """Render, then mask and publish the updated environments, pooling high-resolution samples if enabled.""" + """Render, then mask and publish the updated environments, pooling high-resolution samples if enabled. + + Newton redraws every environment's render buffer, each at the pose and gaze it last received, so the sensor + mask covers every row with that row's gaze. The buffers the camera owns, pooled or laid out as a grid, change + only for the updated environments. + """ self._data.output.clear() self._data.output.update(self._render_output) - super()._update_buffers_impl(env_mask) + try: + super()._update_buffers_impl(env_mask) + finally: + self._data.output.clear() + self._data.output.update(self._public_output) + if not self._env_mask_has_any(env_mask): + return if self._pooler is None: if self._grid_publish: self._publish_grid(env_mask) else: - output = self._flat_render_output - mask_grid_samples(output, self._ray_coords) - self._apply_sensor_fov_mask(output) - else: - mask_grid_samples(self._highres_output, self._ray_coords) - self._apply_sensor_fov_mask(self._highres_output) - for name, hi in self._highres_output.items(): - if name == "rgb": - continue # rgba alias - self._pooled_output[name].copy_(self._pool_output(name, hi.torch)) - if self._native_grid: - copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) - self._data.output.clear() - self._data.output.update(self._public_output) + # The published samples are Newton's own render buffer. + mask_grid_samples(self._flat_render_output, self._ray_coords) + self._apply_sensor_fov_mask(self._flat_render_output) + return + mask_grid_samples(self._highres_output, self._ray_coords) + self._apply_sensor_fov_mask(self._highres_output) + updated = wp.to_torch(env_mask)[:, None, None, None] + for name, hi in self._highres_output.items(): + if name == "rgb": + continue # rgba alias + pooled = self._pooled_output[name] + pooled.copy_(torch.where(updated, self._pool_output(name, hi.torch), pooled)) + if self._native_grid: + copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index cc17ee693f39..0910f1a8a151 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -100,10 +100,23 @@ def __init__(self, cfg: FoveatedCameraCfg): self.cfg = cfg self._prepare_projection() super().__init__(cfg) - if ovrtx: - for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): + for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): + # A locked camera may be treated as static, which skips the motion vectors that DLSS reprojection needs; + # the gaze moves every foveated camera. + lock = prim.GetAttribute("omni:kit:cameraLock") + if lock.IsValid() and lock.Get(): + lock.Set(False) + if ovrtx: lens_lut.apply_lens_lut_to_prim(prim, self._dir_tex_path, self._exit_tex_path) + def __del__(self, *args, **kwargs): + """Release the renderer, then the lens textures it reads.""" + super().__del__(*args, **kwargs) + lut_dir = getattr(self, "_lut_dir", None) + if lut_dir is not None: + lut_dir.cleanup() + self._lut_dir = None + # ------------------------------------------------------------------ # Initialisation # ------------------------------------------------------------------ @@ -329,16 +342,15 @@ def set_world_poses_from_view(self, eyes, targets, env_ids=None): Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. """ super().set_world_poses_from_view(eyes, targets, env_ids) - ids = self._env_indices(env_ids) # Rows whose eye equals their target are skipped by the base method and keep their mount. - moved = (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0 - self._refresh_mount(ids[moved]) + self._refresh_mount(self._env_indices(env_ids)[self._turned_by_view(eyes, targets)]) def _env_indices(self, env_ids) -> torch.Tensor: """The camera indices that ``env_ids`` selects, as a tensor.""" - every = torch.arange(self._view.count, device=self._device) - if env_ids is None or isinstance(env_ids, slice): - return every[slice(None) if env_ids is None else env_ids] + if env_ids is None: + return torch.arange(self._view.count, device=self._device) + if isinstance(env_ids, slice): + return torch.arange(self._view.count, device=self._device)[env_ids] if isinstance(env_ids, wp.array): env_ids = wp.to_torch(env_ids) return torch.as_tensor(env_ids, device=self._device, dtype=torch.long).reshape(-1) @@ -359,7 +371,7 @@ def _write_gaze_local_pose(self) -> None: # The saved local base prevents accumulation and preserves parent motion. basis = self._gaze_basis with torch.autocast(basis.device.type, enabled=False): - relative = compose_rotations(compose_rotations(basis, self._gaze_rotation), basis.T) + relative = compose_rotations(compose_rotations(basis, self._gaze_rotation.torch), basis.T) local_orientation = quat_from_matrix(compose_rotations(self._base_local_orientation, relative)) self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f)) @@ -381,11 +393,11 @@ def process_rendered_frame(self) -> None: if self._grid_publish: self._publish_grid(self._is_outdated) return - self._extract_foveated_samples() - if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self._foveated_output: - self._foveated_output["distance_to_camera"].add_(self._near_clip) + # Only the updated environments' samples change, so pooling and the grid layout reproduce every other + # environment's last frame. + self._extract_foveated_samples(self._is_outdated) mask_grid_samples(self._foveated_output, self._ray_coords) - self._apply_sensor_fov_mask(self._foveated_output) + self._apply_sensor_fov_mask(self._foveated_output, self._is_outdated) if self._pooled_output is not None: for name, hi in self._foveated_output.items(): @@ -396,8 +408,11 @@ def process_rendered_frame(self) -> None: source = self._pooled_output if self._pooled_output is not None else self._foveated_output copy_grid_outputs(source, self._grid_output, self._grid_indices) - def _extract_foveated_samples(self): - """Extract per-sample values from rendered 2D textures into (B, N, 1, C) buffers.""" + def _extract_foveated_samples(self, env_mask: wp.array): + """Extract the updated environments' per-sample values from the rendered 2D textures into the (B, N, 1, C) + buffers; the other environments keep their last samples.""" + updated = wp.to_torch(env_mask)[:, None, None, None] + offset_distance = self.cfg.renderer_cfg.renderer_type == "ovrtx" for name in self._texture_output: if name == "rgb" and "rgba" in self._texture_output: continue # rgba alias @@ -405,6 +420,10 @@ def _extract_foveated_samples(self): fov = self._foveated_output[name] # (B, N, 1, C) tensor = tex.torch if hasattr(tex, "torch") else tex if self._native_grid: - fov.copy_(tensor.reshape_as(fov)) + samples = tensor.reshape_as(fov) else: - fov[:, :, 0, :] = tensor[:, self._extract_py, self._extract_px, :] + samples = tensor[:, self._extract_py, self._extract_px, :].unsqueeze(2) + if offset_distance and name == "distance_to_camera": + # OVRTX measures the distance from the near-clipped ray origin. + samples = samples + self._near_clip + fov.copy_(torch.where(updated, samples, fov)) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py index 93768f2cc613..1f90730b1ec4 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -23,8 +23,9 @@ DEG_TO_RAD = math.pi / 180.0 -_WARP_STREAMS: dict[int, wp.Stream] = {} -"""Warp streams by the CUDA stream handle of the PyTorch stream they launch on.""" +_WARP_STREAMS: dict[tuple[int, int], wp.Stream] = {} +"""Warp streams by the CUDA device index and stream handle of the PyTorch stream they launch on; default streams of +different devices share a handle.""" def warp_stream(device: torch.device | str) -> wp.Stream | None: @@ -33,15 +34,16 @@ def warp_stream(device: torch.device | str) -> wp.Stream | None: if device.type != "cuda": wp.init() return None - handle = torch.cuda.current_stream(device).cuda_stream - stream = _WARP_STREAMS.get(handle) + torch_current = torch.cuda.current_stream(device) + key = (torch_current.device_index, torch_current.cuda_stream) + stream = _WARP_STREAMS.get(key) if stream is None: wp.init() stream = wp.get_stream(wp.device_from_torch(device)) # A temporary alias of a live Warp-owned stream would unregister it when destroyed; cached aliases persist. - if stream.cuda_stream != handle: - stream = wp.stream_from_torch(torch.cuda.current_stream(device)) - _WARP_STREAMS[handle] = stream + if stream.cuda_stream != key[1]: + stream = wp.stream_from_torch(torch_current) + _WARP_STREAMS[key] = stream return stream @@ -206,12 +208,12 @@ def apply_gaze_kernel( rotation: wp.array(dtype=wp.mat33f), mount: wp.array(dtype=wp.quatf), ): - """Turn each camera's world orientation by its gaze, or only the masked ones, record their mounts, and record - every gaze rotation.""" + """Turn each camera's world orientation by its gaze, or only the masked ones, and record their mounts and gaze + rotations; every other camera keeps the rotation its pose was turned by.""" i = wp.tid() - gaze = gaze_rotation(angles_deg[i]) - rotation[i] = gaze if use_mask == 0 or mask[i]: + gaze = gaze_rotation(angles_deg[i]) + rotation[i] = gaze turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount) @@ -246,11 +248,19 @@ def sensor_visibility_kernel( rotation: wp.array(dtype=wp.mat33f), frame: wp.mat33f, camera: CameraParams, + updated: wp.array(dtype=wp.bool), valid: wp.array2d(dtype=wp.bool), + hidden: wp.array2d(dtype=wp.bool), ): - """Whether the physical camera sees each rendered ray turned by each environment's gaze.""" + """Whether the physical camera sees each rendered ray turned by each updated environment's gaze, and which + updated samples it does not see; other environments keep their last visibility and hide nothing.""" env, sample = wp.tid() - valid[env, sample] = sees(rays[sample], rotation[env], frame, camera) + if not updated[env]: + hidden[env, sample] = False + return + seen = sees(rays[sample], rotation[env], frame, camera) + valid[env, sample] = seen + hidden[env, sample] = not seen @wp.kernel(enable_backward=False) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index 252d74c4e263..2a9514c7652b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -29,6 +29,7 @@ import math import os +from typing import TYPE_CHECKING import numpy as np import torch @@ -36,10 +37,8 @@ from .native_grid import native_grid_directions, native_grid_exit_uv -try: - from pxr import Sdf, Usd, UsdGeom -except ImportError: - Sdf = Usd = UsdGeom = None # type: ignore +if TYPE_CHECKING: + from pxr import Usd # ============================================================================= @@ -272,8 +271,8 @@ def apply_lens_lut_to_prim( exit_texture_path: str, ) -> None: """Apply native OmniLensDistortion LUT textures to an existing USD Camera.""" - if Sdf is None: - raise RuntimeError("pxr.Sdf required — run inside Omniverse Kit / Isaac Sim.") + from pxr import Sdf + # RTX reads explicitly authored metadata and attributes without USD schema registration. prim.AddAppliedSchema("OmniLensDistortionLutAPI") prim.CreateAttribute("omni:lensdistortion:model", Sdf.ValueTypeNames.Token).Set("lut") diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py index 8b8e57267cea..cd0eaa3f8407 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py @@ -13,23 +13,13 @@ import torch import warp as wp -from fovi.sensing.coords import RADIUS_NORMS, WARPED_CARTESIAN_STYLES, SamplingCoords +from fovi.sensing.coords import SamplingCoords from isaaclab.utils.warp import ProxyArray GRID_STYLE = "warped_cartesian_as_grid" -def validate_radius_norm(radius_norm: float, style: str, fov_type: str) -> None: - """Reject unsupported warp configurations before renderer startup.""" - if radius_norm not in RADIUS_NORMS: - raise ValueError(f"radius_norm must be one of {RADIUS_NORMS}, got {radius_norm!r}.") - if radius_norm != 2.0 and style not in WARPED_CARTESIAN_STYLES: - raise ValueError("Non-default radius_norm requires a warped_cartesian style.") - if radius_norm == math.inf and fov_type == "wang": - raise ValueError("radius_norm=inf does not support fov_type='wang'.") - - class TorchBuffer(Protocol): """Renderer buffer exposing a Torch view.""" @@ -147,15 +137,6 @@ def grid_output_shape(coords: SamplingCoords) -> tuple[int, int]: return len(coords), 1 -def canonical_to_grid(value: torch.Tensor, coords: SamplingCoords) -> torch.Tensor: - """Convert canonical BNC or BN1C values into upright BHWC values.""" - if value.ndim == 4: - value = value.squeeze(2) - if value.ndim != 3 or value.shape[1] != len(coords): - raise ValueError(f"Expected canonical (B, {len(coords)}, C), got {tuple(value.shape)}.") - return coords.as_grid(value, sample_dim=1) - - def mask_grid_samples(outputs: Mapping[str, torch.Tensor | TorchBuffer], coords: SamplingCoords) -> None: """Zero samples outside the configured footprint before pooling or publication.""" if coords.style != GRID_STYLE: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index 93e4b7b9cc3c..e8de97a683ff 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -26,6 +26,7 @@ from __future__ import annotations +from dataclasses import dataclass from typing import TYPE_CHECKING import torch @@ -108,37 +109,19 @@ def build_highres_coords(cfg: FoveatedCameraCfg, matched_res: int, device: str) _MODAL_CHUNK_ELEMENTS = 2**22 -class ModalPooler(torch.nn.Module): - """Modal pooler for segmentation outputs, built by :func:`build_pooler` with ``mode="mode"``. +@dataclass(frozen=True) +class ModalPooler: + """Neighbour table for modal pooling of segmentation outputs, built by :func:`build_pooler` with ``mode="mode"``. - Holds the fixed neighbour table of a fovi pooler and pools by majority vote - (see :func:`pool_segmentation_buffer`). Like the fovi poolers, calling it - maps ``(B, C, N_hi)`` to ``(B, C, N_lo)``, so :func:`pool_hwc_buffer` also - accepts it, but only in the native dtype: casting IDs to float first loses - IDs above ``2**24``. + Pool with :func:`pool_segmentation_buffer`. The table stays on the device it is built on, the sensor's device. """ - def __init__(self, neighbor_indices: torch.Tensor, num_inputs: int): - """Initialize the pooler. - - Args: - neighbor_indices: ``(k, N_lo)`` int64 input-sample indices of each output's neighbours, ordered by - tie-break preference (nearest first). The value ``num_inputs`` marks an excluded neighbour. - num_inputs: Number of input samples ``N_hi``. - """ - super().__init__() - self.num_inputs = num_inputs - self.register_buffer("neighbor_indices", neighbor_indices, persistent=False) - - @property - def k(self) -> int: - """Number of neighbour slots per output sample.""" - return self.neighbor_indices.shape[0] - - def forward(self, x: torch.Tensor) -> torch.Tensor: - """Pool ``(B, C, N_hi)`` values to ``(B, C, N_lo)`` by majority vote over each channel vector.""" - pooled = pool_segmentation_buffer(self, x.transpose(1, 2).unsqueeze(2)) - return pooled[:, :, 0, :].transpose(1, 2) + neighbor_indices: torch.Tensor + """``(k, N_lo)`` int64 input-sample indices of each output's neighbours, ordered by tie-break preference + (nearest first). The value :attr:`num_inputs` marks an excluded neighbour.""" + + num_inputs: int + """Number of input samples ``N_hi``.""" def build_pooler( diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py index ad14d15ea85c..6f48b1df0ffb 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py @@ -6,7 +6,8 @@ """Camera tasks of Isaac Lab with a foveated camera whose gaze the policy moves. Each task keeps its stock counterpart's scene, rewards, vision model and PPO settings. The camera becomes a foveated -camera at the same mount, with the same optics and resolution, and the policy gets two gaze actions. A teacher's gaze +camera at the same mount, with the same optics and, except for Cartpole, the same resolution: Cartpole's retina is +32 samples across instead of 96 pixels. The policy gets two gaze actions. A teacher's gaze labels supervise those actions during training. """ diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py index f937219a8ce3..e34bec39918b 100644 --- a/source/isaaclab_fovi/test/foveated_render_cases.py +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -17,6 +17,8 @@ import numpy as np import pytest import torch +from fovi.sensing.projection import angular_directions +from isaaclab_fovi.mdp import direction_to_angles from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg import isaaclab.sim as sim_utils @@ -114,7 +116,7 @@ def _render( moved_mount: tuple | None = None, later_gaze: torch.Tensor | None = None, **camera_overrides, -) -> tuple[torch.Tensor, torch.Tensor]: +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Render ground distance for one environment per row of gaze angles (tilt, pan) [deg]. With ``moved_mount`` (eye, target), the last environment's camera is moved there after its gaze is set; a target @@ -122,8 +124,8 @@ def _render( With ``later_gaze``, the gaze changes to it after the first frames, and the camera renders one more frame. Returns: - The distance images [m], shape (num_envs, H, W), and the visual-field position of each grid - cell, shape (H, W, 2). + The distance images [m], shape (num_envs, H, W), the visual-field position of each grid cell, shape + (H, W, 2), and the angles (tilt, pan) [deg] of each grid cell's ray from the gaze, shape (H, W, 2). """ physics_cfg, renderer_cfg, camera_class = backend sim_cfg = SimulationCfg(physics=physics_cfg, device=DEVICE) @@ -158,7 +160,9 @@ def _render( distance = camera.data.output["distance_to_camera"].torch[..., 0].detach().cpu().float().clone() coords = camera.sampling_coords field = coords.as_grid(coords.cartesian, sample_dim=0).detach().cpu().float().clone() - return distance, field + # Each cell's camera-frame ray (OpenCV: x right, y down, z forward) from fovi's angular projection. + rays = angular_directions(field.double(), coords.fov) + return distance, field, direction_to_angles(rays).float() def foveated_camera_follows_gaze(backend: tuple, source: str): @@ -168,7 +172,7 @@ def foveated_camera_follows_gaze(backend: tuple, source: str): the analytic ground distance along each gaze direction. """ gaze = torch.tensor([[0.0, 0.0], [0.0, -16.0]]) - distance, field = _render(backend, gaze, **CAMERA_SOURCES[source]) + distance, field, _ = _render(backend, gaze, **CAMERA_SOURCES[source]) assert distance.shape == (2, RESOLUTION, RESOLUTION) assert torch.isfinite(distance).all() @@ -196,7 +200,7 @@ def foveated_camera_follows_gaze(backend: tuple, source: str): def gaze_change_reaches_the_next_frame(backend: tuple): """A gaze set after the camera has rendered moves the retina, as a gaze action does every step.""" later = torch.tensor([[0.0, -16.0], [8.0, 10.0]]) - distance, field = _render(backend, torch.zeros(2, 2), later_gaze=later) + distance, field, _ = _render(backend, torch.zeros(2, 2), later_gaze=later) row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) for env, (tilt, pan) in enumerate(later.tolist()): @@ -207,7 +211,7 @@ def gaze_stays_relative_to_a_moved_mount(backend: tuple): """Moving one environment's camera keeps its gaze relative to the new mount and leaves the other alone.""" gaze = torch.tensor([[0.0, -10.0], [0.0, -10.0]]) eye, target = (0.3, -0.4, 3.2), (2.0, 0.3, 0.0) - distance, field = _render(backend, gaze, moved_mount=(eye, target)) + distance, field, _ = _render(backend, gaze, moved_mount=(eye, target)) row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) assert float(distance[0, row, column]) == pytest.approx(_ground_distance_along_gaze(0.0, -10.0), rel=0.01) @@ -221,7 +225,7 @@ def gaze_survives_a_position_only_move(backend: tuple): gaze = torch.tensor([[0.0, -10.0], [0.0, -10.0]]) eye = (0.4, -0.3, 3.0) target = tuple(e + t - c for e, t, c in zip(eye, CAM_TARGET, CAM_EYE)) - distance, field = _render(backend, gaze, moved_mount=(eye, None)) + distance, field, _ = _render(backend, gaze, moved_mount=(eye, None)) row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2]) assert float(distance[0, row, column]) == pytest.approx(_ground_distance_along_gaze(0.0, -10.0), rel=0.01) @@ -230,20 +234,50 @@ def gaze_survives_a_position_only_move(backend: tuple): ) +def _relative_errors(distance: torch.Tensor, angles: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Relative error of the rendered distance of each seen cell from the ground along the cell's own ray. + + Args: + distance: Rendered distance image [m], shape (H, W). + angles: Angles (tilt, pan) [deg] of each cell's ray, shape (H, W, 2), with the gaze on the optical axis. + + Returns: + The relative errors and the eccentricities [deg] of the rays of the cells the camera sees. + """ + expected = torch.tensor([_ground_distance_along_gaze(tilt, pan) for tilt, pan in angles.view(-1, 2).tolist()]) + tilt, pan = angles.view(-1, 2).deg2rad().unbind(-1) + eccentricity = torch.acos(tilt.cos() * pan.cos()).rad2deg() + distance = distance.flatten() + seen = torch.isfinite(distance) & (distance > 0) + return ((distance - expected).abs() / expected)[seen], eccentricity[seen] + + def foveated_camera_samples_densest_at_the_fixation(backend: tuple): - """Neighbouring samples are closer together at the fixation, and nearly even without foveation.""" + """Samples are densest at the fixation, nearly even without foveation, and each renders along its own ray. + + The rendered distances match the ground along each sample's ray well off the centre, so a renderer that traced an + even grid instead of the foveated rays fails. + """ def central_to_edge_spacing(field: torch.Tensor) -> float: steps = field[RESOLUTION // 2, :, 0].diff() return float(steps[len(steps) // 2] / steps[-1]) gaze = torch.zeros(1, 2) - foveated_distance, foveated_field = _render(backend, gaze) - uniform_distance, uniform_field = _render(backend, gaze, cmf_a_deg=1000.0) + foveated_distance, foveated_field, foveated_angles = _render(backend, gaze) + uniform_distance, uniform_field, uniform_angles = _render(backend, gaze, cmf_a_deg=1000.0) assert central_to_edge_spacing(foveated_field) < 0.2 assert central_to_edge_spacing(uniform_field) > 0.9 - # Both cover the same field of view, so they see the same range of ground distances. - for distance in (foveated_distance, uniform_distance): - assert torch.isfinite(distance).all() - assert float(foveated_distance.max()) == pytest.approx(float(uniform_distance.max()), rel=0.05) + for distance, angles in ((foveated_distance, foveated_angles), (uniform_distance, uniform_angles)): + errors, eccentricity = _relative_errors(distance[0], angles) + # Most of the grid is seen, and the checked rays reach far from the centre of the field. + assert len(errors) > RESOLUTION**2 // 2 + assert (eccentricity > 10.0).sum() > RESOLUTION**2 // 4 + assert float(eccentricity.max()) > 20.0 + assert float(errors.median()) < 0.01 + assert float((errors < 0.03).float().mean()) > 0.98 + # The two grids' rays differ enough that rendering one in place of the other fails the checks above. + for distance, angles in ((foveated_distance, uniform_angles), (uniform_distance, foveated_angles)): + errors, _ = _relative_errors(distance[0], angles) + assert float((errors < 0.03).float().mean()) < 0.5 diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index e881000f99fb..f8779a5509ef 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -5,6 +5,7 @@ """Gaze geometry and gaze-supervised PPO, without a simulator.""" +import math from types import SimpleNamespace import pytest @@ -15,10 +16,12 @@ from isaaclab_fovi.mdp.gaze import ( GazeAction, gaze_reset_kernel, + gaze_state, gaze_step_kernel, teacher_block_dim, teacher_labels_kernel, ) +from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream from rsl_rl.models import MLPModel @@ -26,6 +29,7 @@ from tensordict import TensorDict from isaaclab.utils.math import quat_apply, quat_apply_inverse +from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless @@ -77,16 +81,23 @@ def test_gaze_step_kernel_matches_the_torch_update(): torch.testing.assert_close(angles, expected * radius, atol=1e-5, rtol=1e-6) +def mount_frame(rotation_deg: float) -> torch.Tensor: + """The camera's ``_mask_frame`` for an image rolled by ``rotation_deg``: upright gaze frame to physical frame.""" + angle = torch.tensor(rotation_deg).deg2rad() + c, s = float(angle.cos()), float(angle.sin()) + return torch.tensor([[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]]) + + @pytest.mark.parametrize("device", DEVICES) -@pytest.mark.parametrize("tracked", [False, True]) -def test_teacher_labels_kernel_matches_the_torch_labels(device, tracked): +@pytest.mark.parametrize("rotation_deg", [0.0, 35.0]) +def test_teacher_labels_kernel_matches_the_torch_labels(device, rotation_deg): camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5), distortion=(-0.1, 0.02, 0.0, 0.0)) field_radius, step, limit = 30.0, 0.1, 1.0 + frame = mount_frame(rotation_deg) generator = torch.Generator().manual_seed(5) count = 4099 - # A fixed mount is shared; a tracked one differs per camera, as on a moving head. - mounts = torch.nn.functional.normalize(torch.randn(count if tracked else 1, 4, generator=generator), dim=-1) - mount = mounts.expand(count, -1) + # Each camera has its own mount, as on a moving head. + mount = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1) positions = torch.randn(count, 3, generator=generator) lateral = torch.randn(count, 2, generator=generator) * 0.6 local = torch.cat((lateral, torch.rand(count, 1, generator=generator) + 0.2), -1) @@ -98,11 +109,13 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device, tracked): # The torch path the kernel replaces: entity_point, then the teacher, then the labels and logs. points = targets + quat_apply(orientations, offset.expand(count, -1)) direction = torch.nn.functional.normalize(quat_apply_inverse(mount, points - positions), dim=-1) - desired = direction_to_angles(direction) / field_radius + # Gazes are measured in the upright image frame, which the frame carries into the physical camera's. + upright = direction @ frame + desired = direction_to_angles(upright) / field_radius valid = camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) action = torch.where(valid[:, None], ((desired - gaze) / step).clamp(-1, 1), 0.0) looking = angles_to_direction(gaze * field_radius) - error = torch.atan2(torch.cross(looking, direction, dim=-1).norm(dim=-1), (looking * direction).sum(-1)).rad2deg() + error = torch.atan2(torch.cross(looking, upright, dim=-1).norm(dim=-1), (looking * upright).sum(-1)).rad2deg() expected = torch.cat((action, valid[:, None].float()), dim=-1) labels = torch.empty(count, 3, device=device) @@ -118,9 +131,9 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device, tracked): wp.vec3f(*offset.tolist()), 1, wp.from_torch(positions.to(device), dtype=wp.vec3f), - wp.from_torch(mounts.to(device), dtype=wp.quatf), - int(tracked), - wp.from_torch(gaze.to(device), dtype=wp.vec2f), + wp.from_torch(mount.to(device), dtype=wp.quatf), + wp.from_torch(torch.cat((gaze, torch.zeros_like(gaze)), -1).to(device), dtype=wp.vec4f), + wp.mat33f(*frame.flatten().tolist()), field_radius, step, limit, @@ -138,6 +151,103 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device, tracked): assert float(log[0]) == pytest.approx(float(error[labelled].mean()), rel=1e-4) +@pytest.mark.parametrize("rotation_deg", [0.0, -50.0, 120.0]) +def test_teacher_gaze_fixates_the_target_through_a_rolled_mount(rotation_deg): + """Following a teacher label puts the fixation, which reaches the physical camera at frame * gaze * z, on the + target.""" + camera = CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5)) + field_radius, step = 40.0, 10.0 + frame = mount_frame(rotation_deg) + direction = torch.nn.functional.normalize(torch.tensor([[0.25, -0.15, 1.0], [-0.3, 0.2, 1.0]]), dim=-1) + count = len(direction) + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]]).repeat(count, 1) + labels, log = torch.empty(count, 3), torch.empty(2) + with torch_stream("cpu"): + wp.launch( + teacher_labels_kernel, + dim=(1, 1), + inputs=[ + wp.from_torch(direction, dtype=wp.vec3f), + wp.zeros(1, dtype=wp.quatf), + wp.vec3f(0.0, 0.0, 0.0), + 0, + wp.zeros(count, dtype=wp.vec3f), + wp.from_torch(identity, dtype=wp.quatf), + wp.zeros(count, dtype=wp.vec4f), + wp.mat33f(*frame.flatten().tolist()), + field_radius, + step, + 1.0, + camera_params(camera), + ], + outputs=[wp.from_torch(labels), wp.from_torch(log)], + block_dim=1, + ) + assert (labels[:, 2] == 1).all() + gaze = labels[:, :2] * step + fixation = angles_to_direction(gaze * field_radius) @ frame.T + torch.testing.assert_close(fixation, direction, atol=1e-5, rtol=0) + # The error is the gaze's angle from the target before the step: the gaze starts on the optical axis. + torch.testing.assert_close(log[0], direction[:, 2].acos().rad2deg().mean(), atol=1e-3, rtol=0) + + +@pytest.mark.parametrize( + "field, value", [("step_size", 0.0), ("step_size", float("nan")), ("gaze_limit", -1.0), ("gaze_limit", math.inf)] +) +def test_gaze_config_rejects_bounds_that_divide_by_zero(field, value): + cfg = GazeActionCfg(asset_name="camera") + cfg.validate_config() + setattr(cfg, field, value) + with pytest.raises(ValueError, match=field): + cfg.validate_config() + with pytest.raises(ValueError, match="mount"): + GazeActionCfg(asset_name="camera", mount="head").validate_config() + + +def test_gaze_config_resolves_its_term_lazily(): + class_type = GazeActionCfg(asset_name="camera").class_type + assert isinstance(class_type, str) + assert class_type._resolve() is GazeAction + + +def test_process_actions_moves_the_gaze_by_the_supplied_actions(): + """The term reads whatever actions it is handed: the manager's slice in place, or another tensor.""" + num_envs = 4 + angles = ProxyArray(wp.zeros(num_envs, dtype=wp.vec2f, device="cpu")) + set_angles = [] + camera = SimpleNamespace( + _gaze_angles=angles, + gaze_angles_buffer=lambda: angles.torch, + set_gaze_angles=lambda value: set_angles.append(value), + ) + term = object.__new__(GazeAction) + term._env = SimpleNamespace(num_envs=num_envs, device="cpu", step_dt=0.5) + term.cfg = GazeActionCfg(asset_name="camera", step_size=0.1, gaze_limit=1.0) + term.camera = camera + term.field_radius_deg = 20.0 + term._state = ProxyArray(wp.zeros(num_envs, dtype=wp.vec4f, device="cpu")) + term._gaze, term._velocity = term._state.torch[:, :2], term._state.torch[:, 2:] + term._step_launch = term._raw = None + + manager_actions = torch.zeros(num_envs, 5) + manager_actions[:, 2:4] = torch.tensor([[1.0, 0.0], [0.0, -1.0], [0.5, 0.5], [3.0, 0.0]]) + term.process_actions(manager_actions[:, 2:4]) + expected = clamp_gaze(manager_actions[:, 2:4].clamp(-1, 1) * 0.1, 1.0) + torch.testing.assert_close(term.gaze, expected) + torch.testing.assert_close(term.velocity, expected / 0.5) + torch.testing.assert_close(angles.torch, expected * 20.0) + assert set_angles[-1] is angles.torch + assert term.raw_actions.data_ptr() == manager_actions[:, 2:4].data_ptr() + + supplied = torch.tensor([[-1.0, 0.0]]).repeat(num_envs, 1) + term.process_actions(supplied) + torch.testing.assert_close(term.gaze, clamp_gaze(expected - 0.1 * supplied.abs(), 1.0)) + assert term.raw_actions is supplied + torch.testing.assert_close( + gaze_state(SimpleNamespace(action_manager=SimpleNamespace(get_term=lambda name: term))), term.state + ) + + @pytest.mark.parametrize("ids", [None, [3, 0, 7]]) @pytest.mark.parametrize("random_start", [False, True]) def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): diff --git a/source/isaaclab_fovi/test/test_backend_dispatch.py b/source/isaaclab_fovi/test/test_backend_dispatch.py index 497abec2bb22..58ec2d23a246 100644 --- a/source/isaaclab_fovi/test/test_backend_dispatch.py +++ b/source/isaaclab_fovi/test/test_backend_dispatch.py @@ -9,6 +9,9 @@ import pytest from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg +from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera +from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera +from isaaclab_physx.renderers import IsaacRtxRendererCfg pytestmark = pytest.mark.kitless @@ -23,9 +26,24 @@ class CameraSelection: renderer_cfg: RendererSelection -def test_default_renderer_is_resolved_to_a_concrete_one() -> None: +def dispatch(cfg) -> type: + """The implementation class the camera selects for ``cfg``, without initialising it.""" + return type(FoveatedCamera.__new__(FoveatedCamera, cfg)) + + +def test_default_renderer_resolves_to_isaac_rtx() -> None: cfg = FoveatedCameraCfg(prim_path="/World/Camera") - assert cfg.renderer_cfg.renderer_type != "default" + assert type(cfg.renderer_cfg) is IsaacRtxRendererCfg + assert cfg.renderer_cfg.renderer_type == "isaac_rtx" + assert dispatch(cfg) is FoveatedRTXCamera + + +@pytest.mark.parametrize( + ("renderer_type", "expected"), + [("isaac_rtx", FoveatedRTXCamera), ("ovrtx", FoveatedRTXCamera), ("newton_warp", FoveatedNewtonCamera)], +) +def test_renderer_selects_its_implementation(renderer_type: str, expected: type) -> None: + assert dispatch(CameraSelection(RendererSelection(renderer_type))) is expected def test_unknown_renderer_fails_explicitly() -> None: diff --git a/source/isaaclab_fovi/test/test_gaze_kernels.py b/source/isaaclab_fovi/test/test_gaze_kernels.py index 718b92d9c127..00b9509f327a 100644 --- a/source/isaaclab_fovi/test/test_gaze_kernels.py +++ b/source/isaaclab_fovi/test/test_gaze_kernels.py @@ -149,10 +149,9 @@ def test_gaze_kernels_match_the_torch_composition(selection): ) torch.testing.assert_close(matrix_from_quat(mount[turned]), matrix_from_quat(ros[turned]), atol=1e-5, rtol=0) assert not mount[~turned].any() - # Every environment's rotation is recorded, except that the indexed kernel touches only its own. - recorded = selected if selection == "indices" else torch.ones_like(selected) - torch.testing.assert_close(rotation[recorded], set_rotation[recorded], atol=0, rtol=0) - assert not rotation[~recorded].any() + # Only the turned cameras record their gaze rotation; the others keep the one their pose was turned by. + torch.testing.assert_close(rotation[turned], set_rotation[turned], atol=0, rtol=0) + assert not rotation[~turned].any() def test_publish_kernel_matches_masking_then_copying_to_the_grid(): diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py index 225a9aa0eda4..32682e487fe2 100644 --- a/source/isaaclab_fovi/test/test_native_grid.py +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -14,7 +14,6 @@ from isaaclab_fovi.sensors.native_grid import ( allocate_grid_outputs, bounded_angular_radius, - canonical_to_grid, copy_grid_outputs, grid_sample_indices, mask_grid_samples, @@ -161,7 +160,6 @@ def test_upright_grid_masks_and_channel_aliases(): assert target["rgba"][0, :, :, 0][8, 4] < target["rgba"][0, :, :, 0][8, 11] assert target["rgba"][0, :, :, 1][4, 8] > target["rgba"][0, :, :, 1][11, 8] assert (target["rgba"][0][~coords.as_grid(coords.valid_mask)] == 0).all() - torch.testing.assert_close(canonical_to_grid(source["rgba"], coords), expected) @pytest.mark.parametrize("dtype,channels", [(torch.uint8, 4), (torch.float32, 1), (torch.int32, 1)]) @@ -176,7 +174,7 @@ def test_output_permutation_preserves_dtype_and_captures(dtype, channels, device target = allocate_grid_outputs(source, coords) indices = grid_sample_indices(coords) copy_grid_outputs(source, target, indices) - expected = canonical_to_grid(source["value"], coords) + expected = coords.as_grid(source["value"][:, :, 0], sample_dim=1) torch.testing.assert_close(target["value"], expected, atol=0, rtol=0) if device == "cuda": torch.cuda.synchronize() diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index f8ff0610fe44..b7328b84fb66 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Newton anti-aliasing consumes IsaacLab's public renderer-buffer views.""" +"""The Newton foveated camera's render layout and publication, on stand-in renderer buffers.""" from types import SimpleNamespace @@ -15,38 +15,9 @@ from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera from isaaclab_fovi.sensors.pooling import ModalPooler -from isaaclab.renderers.output_contract import RenderBufferKind, RenderBufferSpec -from isaaclab.sensors.camera.camera_data import CameraData from isaaclab.utils.warp import ProxyArray - -def test_pooled_allocation_accepts_proxy_arrays_and_preserves_render_buffers() -> None: - rgba = torch.zeros((1, 8, 1, 4), dtype=torch.uint8) - rgba_proxy = ProxyArray(wp.from_torch(rgba)) - data = CameraData.allocate( - ["rgba"], - 8, - 1, - 1, - "cpu", - {RenderBufferKind.RGBA: RenderBufferSpec(channels=4, dtype=wp.uint8)}, - ) - data.output["rgba"] = rgba_proxy - camera = SimpleNamespace() - camera._data = data - camera._pooler = torch.nn.Identity() - camera._pooler_int = None - camera._num_valid_samples = 4 - camera._num_ray_samples = 8 - camera._pool_k = 2 - camera.cfg = SimpleNamespace(data_types=["rgba"], pool_int_mode="max", pool_mode="avg", pool_sample_cortex=False) - - FoveatedNewtonCamera._allocate_pooled_buffers(camera) - - assert camera._pooled_output["rgba"].shape == (1, 4, 1, 4) - assert camera._pooled_output["rgba"].dtype == torch.uint8 - assert camera._highres_output["rgba"] is rgba_proxy - assert camera._highres_output is not data.output +pytestmark = pytest.mark.kitless @pytest.mark.parametrize("pooled", [False, True]) @@ -79,7 +50,7 @@ def initialize_renderer(camera): def render(camera, env_mask): assert camera._data.output["rgba"].torch.shape == camera.renderer_rgba.shape - values = torch.arange(camera.renderer_rgba.numel()).reshape(camera.renderer_rgba.shape) + values = torch.arange(camera.renderer_rgba.numel()).reshape(camera.renderer_rgba.shape) + camera.frame_offset camera.renderer_rgba.copy_(values.to(torch.uint8)) monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) @@ -100,6 +71,7 @@ def render(camera, env_mask): pool_int_mode="avg", pool_sample_cortex=False, image_rotation_deg=0, + update_period=0.0, data_types=["rgba", "rgb"], renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), ) @@ -109,7 +81,8 @@ def render(camera, env_mask): assert rays.shape == (1, ray_coords.resolution, ray_coords.resolution, 2, 3) torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], camera._ray_directions) public_rgba = camera._data.output["rgba"] - camera._update_buffers_impl(None) + camera.frame_offset = 0 + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) expected = camera.renderer_rgba.reshape(2, len(ray_coords), 1, 4).clone() expected[:, ~ray_coords.valid_mask] = 0 if pooled: @@ -122,6 +95,13 @@ def render(camera, env_mask): torch.testing.assert_close(camera._data.output["rgb"].torch, expected[..., :3], rtol=0, atol=0) assert camera._data.output["rgb"].warp.ptr == public_rgba.warp.ptr + # Newton redraws every row, but only the updated environment's publication changes. + camera.frame_offset = 1 + camera._update_buffers_impl(wp.array([False, True], dtype=wp.bool, device="cpu")) + published = camera._data.output["rgba"].torch + torch.testing.assert_close(published[0], expected[0], rtol=0, atol=0) + assert not torch.equal(published[1], expected[1]) + def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatch) -> None: """A pooled camera's segmentation output holds each sample's majority label exactly, IDs above 2**24 included.""" @@ -165,10 +145,16 @@ def render(camera, env_mask): monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) camera = object.__new__(FoveatedNewtonCamera) + camera._initialize_handle = None + camera._invalidate_initialize_handle = None + camera._prim_deletion_handle = None + camera._view = None + camera._renderer = None camera._device = "cpu" camera.cfg = SimpleNamespace( foveated_style="warped_cartesian_as_grid", mask_to_sensor_fov=False, + update_period=0.0, pool_enabled=True, pool_mode="avg", pool_int_mode="mode", @@ -178,7 +164,7 @@ def render(camera, env_mask): renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), ) camera._initialize_impl() - camera._update_buffers_impl(None) + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) # The modal label of each run after the footprint mask zeroes samples outside the retina, ties to the nearest. rendered = labels.clone() diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 59c9064d20ba..118df24ef34c 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -24,6 +24,8 @@ from isaaclab.sim import PinholeCameraCfg +pytestmark = pytest.mark.kitless + @dataclass class SamplingConfig: @@ -48,9 +50,8 @@ class SamplingConfig: pool_gauss_sigma: float = 10.0 -@pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) -def test_dual_grid_preserves_constant_channels_and_batch_order(mode: str) -> None: - cfg = SamplingConfig(pool_mode=mode) +def test_dual_grid_preserves_constant_channels_and_batch_order() -> None: + cfg = SamplingConfig() lowres, matched = build_lowres_coords(cfg, "cpu") highres = build_highres_coords(cfg, matched, "cpu") assert highres is not None @@ -67,6 +68,46 @@ def test_dual_grid_preserves_constant_channels_and_batch_order(mode: str) -> Non torch.testing.assert_close(actual, expected) +def reference_pool(pooler: KNNPoolingLayer, values: torch.Tensor, mode: str, sigma: float) -> torch.Tensor: + """Pool ``(B, N_hi, 1, C)`` values over a KNN pooler's neighbour table by the definition of each mode.""" + table, distances = pooler.knn_indices_pad_token, pooler.knn_distances # (k, N_lo); N_hi marks a pad + num_inputs = values.shape[1] + valid = table != num_inputs + neighbours = values[:, table.clamp(max=num_inputs - 1), 0] # (B, k, N_lo, C) + if mode == "max": + pooled = neighbours.masked_fill(~valid[None, :, :, None], -torch.inf).amax(1) + else: + if mode == "avg": + weights = valid.double() + else: + # Gaussian in the neighbour distance rescaled to [0, 1] per output, nearest weighted most. + low, high = distances.min(0).values, distances.max(0).values + scaled = (distances - low) / torch.where(high > low, high - low, 1.0) + weights = torch.exp(-scaled.double().square() / (2 * sigma**2)) * valid + weights = weights / weights.sum(0) + pooled = (neighbours.double() * weights[None, :, :, None]).sum(1).to(values.dtype) + return pooled.unsqueeze(2) + + +@pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) +def test_pooling_mode_reduces_each_neighbourhood(mode: str) -> None: + # A narrow Gaussian weights the nearest of the three neighbours well above the farthest, so it differs from avg. + sigma = 0.5 + cfg = SamplingConfig(pool_mode=mode, pool_gauss_sigma=sigma) + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + pooler, _ = build_pooler(cfg, lowres, highres, "cpu") + assert isinstance(pooler, KNNPoolingLayer) + values = torch.rand(2, len(highres), 1, 3, generator=torch.Generator().manual_seed(0)) + actual = pool_hwc_buffer(pooler, values) + expected = {other: reference_pool(pooler, values, other, sigma) for other in ("avg", "gaussian", "max")} + torch.testing.assert_close(actual, expected[mode]) + # The modes give distinct results on this input, so the match identifies the reduction that ran. + for other, other_expected in expected.items(): + if other != mode: + assert (actual - other_expected).abs().max() > 0.05 + + def test_disabled_pooling_uses_only_output_grid() -> None: cfg = SamplingConfig(pool_enabled=False) lowres, matched = build_lowres_coords(cfg, "cpu") @@ -85,7 +126,7 @@ def test_disabled_pooling_uses_only_output_grid() -> None: def hand_pooler(device: str) -> ModalPooler: - return ModalPooler(HAND_TABLE, num_inputs=5).to(device) + return ModalPooler(HAND_TABLE.to(device), num_inputs=5) @pytest.mark.parametrize("device", DEVICES) @@ -102,7 +143,7 @@ def test_modal_pooling_keeps_majority_color_vector(device: str) -> None: assert pooled.dtype == torch.uint8 assert torch.equal(pooled.cpu(), expected[None, :, None, :]) # Swapping the tied neighbours' order flips the winner. - swapped = ModalPooler(HAND_TABLE[[1, 0, 2]], num_inputs=5).to(device) + swapped = ModalPooler(HAND_TABLE[[1, 0, 2]].to(device), num_inputs=5) assert torch.equal(pool_segmentation_buffer(swapped, rendered)[0, 1, 0].cpu(), colors[4]) @@ -174,7 +215,17 @@ def test_modal_pooler_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: labels = labels.to(torch.uint8) pooled = pool_segmentation_buffer(modal, labels) assert torch.equal(pooled[:, :, 0], reference_modal_pool(table, labels[:, :, 0])) - assert torch.equal(pool_hwc_buffer(modal, labels), pooled) + + +@pytest.mark.parametrize("device", DEVICES) +def test_modal_pooler_is_built_on_the_sensor_device(device: str) -> None: + cfg = SamplingConfig() + lowres, matched = build_lowres_coords(cfg, device) + highres = build_highres_coords(cfg, matched, device) + modal, _ = build_pooler(cfg, lowres, highres, device, mode="mode") + assert modal.neighbor_indices.device.type == device + labels = torch.randint(0, 3, (1, len(highres), 1, 1), device=device) + assert pool_segmentation_buffer(modal, labels).device.type == device @pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index 7aa415026772..f8d6d6f23b1e 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -3,13 +3,19 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""RTX camera configuration contracts that need no renderer.""" +"""RTX camera contracts that need no renderer.""" +import tempfile +from pathlib import Path from types import SimpleNamespace import pytest +import torch +import warp as wp from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera +from isaaclab.sensors.camera.camera import Camera + pytestmark = pytest.mark.kitless @@ -32,3 +38,59 @@ def test_near_clip_comes_from_spawn_or_else_the_camera_prim() -> None: assert FoveatedRTXCamera._near_clipping_distance(existing, prim) == pytest.approx(0.05) spawned = SimpleNamespace(cfg=SimpleNamespace(spawn=SimpleNamespace(clipping_range=(0.01, 20.0)))) assert FoveatedRTXCamera._near_clipping_distance(spawned, prim) == pytest.approx(0.01) + + +@pytest.mark.parametrize("native_grid", [False, True]) +def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> None: + """Environments outside the update mask keep their samples, and OVRTX's near-plane offset is added once.""" + texture = torch.arange(2 * 4 * 4, dtype=torch.float32).reshape(2, 4, 4, 1) + camera = SimpleNamespace( + cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")), + _native_grid=native_grid, + _near_clip=0.25, + _texture_output={"distance_to_camera": texture}, + _foveated_output={"distance_to_camera": torch.full((2, 16, 1, 1), -1.0)}, + _extract_py=torch.arange(16) // 4, + _extract_px=torch.arange(16) % 4, + ) + updated = wp.array([True, False], dtype=wp.bool, device="cpu") + for _ in range(2): + FoveatedRTXCamera._extract_foveated_samples(camera, updated) + samples = camera._foveated_output["distance_to_camera"] + torch.testing.assert_close(samples[0, :, 0, 0], texture[0].flatten() + 0.25) + assert bool((samples[1] == -1.0).all()) + + +def test_releasing_the_camera_removes_its_lens_textures(monkeypatch, tmp_path) -> None: + monkeypatch.setattr(Camera, "__del__", lambda self, *args, **kwargs: None) + camera = object.__new__(FoveatedRTXCamera) + camera._lut_dir = tempfile.TemporaryDirectory(dir=tmp_path) + directory = Path(camera._lut_dir.name) + (directory / "foveated_ray_enter_direction.exr").write_bytes(b"") + camera.__del__() + assert not directory.exists() and camera._lut_dir is None + + +def test_construction_unlocks_spawned_cameras_without_changing_the_config(monkeypatch) -> None: + """The gaze moves every foveated camera, so RTX must not treat a spawned camera as static.""" + pxr = pytest.importorskip("pxr") + stage = pxr.Usd.Stage.CreateInMemory() + prim = pxr.UsdGeom.Camera.Define(stage, "/World/envs/env_0/Camera").GetPrim() + prim.CreateAttribute("omni:kit:cameraLock", pxr.Sdf.ValueTypeNames.Bool).Set(True) + + def construct(self, cfg): + self.cfg = cfg + self.stage = stage + + monkeypatch.setattr(Camera, "__init__", construct) + monkeypatch.setattr(FoveatedRTXCamera, "__del__", lambda self, *args, **kwargs: None) + spawn = SimpleNamespace(lock_camera=True) + cfg = SimpleNamespace( + prim_path="/World/envs/env_.*/Camera", + spawn=spawn, + mask_to_sensor_fov=False, + renderer_cfg=SimpleNamespace(renderer_type="isaac_rtx"), + ) + FoveatedRTXCamera(cfg) + assert prim.GetAttribute("omni:kit:cameraLock").Get() is False + assert cfg.spawn is spawn and spawn.lock_camera diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 845d1579130c..6e7d3b4aab91 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -73,26 +73,25 @@ def test_rendering_and_software_sampling_share_window_and_nodes() -> None: gaze_convention="pan_tilt", ) torch.testing.assert_close(coords.cartesian, retina.sampler.coords.cartesian) - actual = retina(torch.ones(2, 3, 80, 120), torch.tensor([[0.5, 0.5], [0.3, 0.8]])) - assert actual.shape == (2, 3, len(coords)) - assert torch.isfinite(actual).all() class GazeHarness(FoveatedCamera): """The foveated camera's gaze state and kernels on stand-in pose buffers, without a simulator.""" - def __new__(cls, **overrides): + def __new__(cls, *args, **overrides): return object.__new__(cls) - def __init__(self, **overrides) -> None: + def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None: self.cfg = camera_config() for name, value in overrides.items(): setattr(self.cfg, name, value) - self._sampling_coords, _ = build_lowres_coords(self.cfg, "cpu") + self._view = SimpleNamespace(count=count) + self._device = device + self._sampling_coords, _ = build_lowres_coords(self.cfg, device) self._sampling_coords_highres = None - self._gaze_rotation = None self._data = SimpleNamespace( - quat_w_world=torch.tensor([[0.0, 0.0, 0.0, 1.0]]).repeat(2, 1), pos_w=torch.zeros(2, 3) + quat_w_world=torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device).repeat(count, 1), + pos_w=torch.zeros(count, 3, device=device), ) self._initialize_gaze() @@ -113,20 +112,20 @@ def angles_toward(camera: CameraModel, pixel: tuple[float, float]) -> torch.Tens @pytest.mark.parametrize("pixel", [(119.5, 39.5), (59.5, 79.5), (120.5, 39.5), (59.5, -1.3)]) def test_edge_gaze_preserves_visible_rays(pixel: tuple[float, float]) -> None: """Looking at, or just past, an image edge keeps the part of the retina the camera still sees.""" - camera = GazeHarness() + camera = GazeHarness(count=1) camera.set_gaze_angles(angles_toward(camera._camera_model, pixel)) # An edge-centered receptive field straddles the physical sensor boundary. # Its visible part must survive even when the center lies outside the image. - valid = camera._gaze_validity(1) + valid = camera._gaze_validity() assert valid.any() assert not valid.all() def test_gaze_away_from_sensor_masks_all_rays() -> None: - camera = GazeHarness() + camera = GazeHarness(count=1) camera.set_gaze_angles(torch.tensor([[0.0, 180.0]])) - assert not camera._gaze_validity(1).any() + assert not camera._gaze_validity().any() @pytest.mark.parametrize("device", ["cpu", "cuda"]) @@ -145,12 +144,12 @@ def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, m angles = torch.tensor([[7.5, -12.0]], device=device).repeat(batch_size, 1) angles[1::2] = 0 expected = matrix_from_quat(source.double()) @ conversion - camera = GazeHarness() + camera = GazeHarness(count=batch_size, device=device) camera._data.quat_w_world = source camera._gaze_basis = camera._gaze_basis.to(device) camera.set_gaze_angles(angles) basis = camera._gaze_basis.double() - expected = expected @ basis @ camera._gaze_rotation.double() @ basis.T @ conversion.T + expected = expected @ basis @ camera._gaze_rotation.torch.double() @ basis.T @ conversion.T selected = torch.arange(batch_size, device=device) % 2 == 0 with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast): if mode == "spherical_ids": @@ -190,20 +189,60 @@ def opengl(orientation: torch.Tensor) -> torch.Tensor: seen = (turn[:, None] @ rays[None, :, :, None]).squeeze(-1) * torch.tensor([1.0, -1.0, -1.0]) expected = model.project(seen)[1] assert expected.any() and (~expected).any() - assert (camera._gaze_validity(2) == expected).float().mean() > 0.999 + assert (camera._gaze_validity() == expected).float().mean() > 0.999 -def test_moving_the_mount_is_recorded(monkeypatch) -> None: +def test_only_a_turned_mount_is_recorded(monkeypatch) -> None: + """The fixed-mount teacher reads the live camera position, so only successful turns of the mount count.""" monkeypatch.setattr(Camera, "set_world_poses", lambda *args, **kwargs: None) monkeypatch.setattr(Camera, "set_world_poses_from_view", lambda *args, **kwargs: None) - for move in ( - lambda camera: camera.set_world_poses(positions=torch.zeros(2, 3)), - lambda camera: camera.set_world_poses_from_view(torch.zeros(2, 3), torch.ones(2, 3)), + eyes = torch.zeros(2, 3) + for move, turned in ( + (lambda camera: camera.set_world_poses(positions=torch.zeros(2, 3)), False), + (lambda camera: camera.set_world_poses(orientations=torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2)), True), + (lambda camera: camera.set_world_poses_from_view(eyes, eyes), False), + (lambda camera: camera.set_world_poses_from_view(eyes, torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])), True), ): camera = GazeHarness() camera.mount_moved = False move(camera) - assert camera.mount_moved + assert camera.mount_moved is turned + + +def test_a_rejected_mount_move_is_not_recorded(monkeypatch) -> None: + def reject(*args, **kwargs): + raise ValueError("rejected") + + monkeypatch.setattr(Camera, "set_world_poses", reject) + camera = GazeHarness() + camera.mount_moved = False + with pytest.raises(ValueError, match="rejected"): + camera.set_world_poses(orientations=torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2)) + assert not camera.mount_moved + + +@pytest.mark.parametrize("shape", [(1, 2), (2, 3), (3, 2)]) +def test_gaze_angles_need_one_row_per_camera(shape) -> None: + camera = GazeHarness() + with pytest.raises(ValueError, match=r"shape \(2, 2\)"): + camera.set_gaze_angles(torch.zeros(shape)) + assert camera._gaze_angles is None + + +def test_sensor_mask_reuses_its_buffer_and_keeps_rows_that_were_not_updated() -> None: + camera = GazeHarness() + camera.cfg.mask_to_sensor_fov = True + camera.set_gaze_angles(torch.tensor([[0.0, 0.0], [0.0, 0.0]])) + first = camera._gaze_validity() + kept = first[0].clone() + output = {"distance_to_camera": torch.ones(2, len(camera._gaze_rays), 1, 1)} + camera.set_gaze_angles(torch.tensor([[0.0, 180.0], [0.0, 180.0]])) + camera._apply_sensor_fov_mask(output, wp.array([False, True], dtype=wp.bool, device="cpu")) + assert camera._visibility["valid"].torch is first + # The environment that was not updated keeps its samples and its last visibility. + torch.testing.assert_close(first[0], kept) + assert bool(output["distance_to_camera"][0].all()) + assert not output["distance_to_camera"][1].any() def test_pose_update_records_the_mount_before_the_gaze() -> None: @@ -213,7 +252,9 @@ def test_pose_update_records_the_mount_before_the_gaze() -> None: camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) camera._apply_gaze_pose() expected = convert_camera_frame_orientation_convention(mount, "world", "ros") - torch.testing.assert_close(matrix_from_quat(camera._mount_quat_ros), matrix_from_quat(expected), atol=1e-6, rtol=0) + torch.testing.assert_close( + matrix_from_quat(camera._mount_quat_ros.torch), matrix_from_quat(expected), atol=1e-6, rtol=0 + ) assert not torch.allclose(camera._data.quat_w_world, mount) @@ -234,10 +275,10 @@ def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pos camera._apply_gaze_pose([0]) torch.testing.assert_close(camera._data.quat_w_world[1], untouched) torch.testing.assert_close( - camera._gaze_validity(2), + camera._gaze_validity(), source.project( angular_directions(camera._sampling_coords.cartesian, camera._sampling_coords.fov) - @ camera._gaze_rotation.transpose(-1, -2) + @ camera._gaze_rotation.torch.transpose(-1, -2) )[1], ) @@ -253,7 +294,7 @@ def test_renderer_ray_frame_matches_cv_frame() -> None: def test_gaze_pose_is_stable_inside_model_autocast(device: str) -> None: if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA unavailable") - cameras = [GazeHarness(), GazeHarness()] + cameras = [GazeHarness(device=device), GazeHarness(device=device)] for camera in cameras: camera._data.quat_w_world = torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(2, 1) camera._gaze_basis = camera._gaze_basis.to(device) @@ -264,10 +305,10 @@ def test_gaze_pose_is_stable_inside_model_autocast(device: str) -> None: with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled): camera.set_gaze_angles(target) camera._apply_gaze_pose() - camera._test_validity = camera._gaze_validity(2) + camera._test_validity = camera._gaze_validity().clone() assert torch.isfinite(cameras[1]._data.quat_w_world).all() torch.testing.assert_close(cameras[1]._data.quat_w_world, cameras[0]._data.quat_w_world) - torch.testing.assert_close(cameras[1]._gaze_rotation, cameras[0]._gaze_rotation) + torch.testing.assert_close(cameras[1]._gaze_rotation.torch, cameras[0]._gaze_rotation.torch) torch.testing.assert_close(cameras[1]._data.quat_w_world.norm(dim=-1), torch.ones(2, device=device)) torch.testing.assert_close(cameras[1]._test_validity, cameras[0]._test_validity) @@ -277,14 +318,15 @@ def test_gaze_pose_is_stable_inside_model_autocast(device: str) -> None: def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_enabled) -> None: if device == "cuda" and not torch.cuda.is_available(): pytest.skip("CUDA unavailable") - camera = GazeHarness() + camera = GazeHarness(count=48, device=device) camera._gaze_basis = camera._gaze_basis.to(device) camera._base_local_orientation = matrix_from_quat( torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(48, 1) ) written = [] camera._view = SimpleNamespace( - set_local_poses=lambda *, orientations: written.append(torch.utils.dlpack.from_dlpack(orientations).clone()) + count=48, + set_local_poses=lambda *, orientations: written.append(torch.utils.dlpack.from_dlpack(orientations).clone()), ) # Policy outputs may themselves be BF16; both paths use the same input values. angles = torch.tensor([[-0.006677, -0.010717]], device=device, dtype=torch.bfloat16).repeat(48, 1) @@ -303,10 +345,9 @@ def test_gaze_kernels_preserve_shared_stream_for_warp_capture() -> None: wp.init() stream = wp.Stream("cuda:0") with wp.ScopedStream(stream), torch.cuda.stream(wp.stream_to_torch(stream)): - camera = GazeHarness() - camera._gaze_rays = camera._gaze_rays.to("cuda:0") + camera = GazeHarness(device="cuda:0") camera.set_gaze_angles(torch.tensor([[5.0, -8.0], [0.0, 0.0]], device="cuda:0")) - valid = camera._gaze_validity(2) + valid = camera._gaze_validity() target = wp.zeros(valid.shape, dtype=wp.bool, device="cuda:0") # Physics must still be able to capture after the camera's temporary stream scopes exit. with wp.ScopedCapture(stream=stream) as capture: From 64e26c8c1439388525c2941d8621c3e051e9e860 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 17 Nov 2026 23:55:48 -0800 Subject: [PATCH 33/81] Remove the unused teacher_labels helper No task calls it; gaze_teacher_labels covers the shipped tasks. The gaze-supervised PPO docstring now points at gaze_teacher_labels. --- source/isaaclab_fovi/docs/README.md | 3 +-- source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi | 2 -- source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 12 ------------ .../isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py | 4 ++-- 4 files changed, 3 insertions(+), 18 deletions(-) diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index eb5639995bb3..ee030b92357d 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -120,8 +120,7 @@ physical camera's image at the current gaze. - `gaze_state`: the gaze, in field radii, and its velocity, in field radii per second. - `gaze_teacher_labels`: a teacher's gaze action toward a point fixed to an - asset, and whether that point is a valid target. `teacher_labels` takes any - world points, for a task whose target changes during an episode. + asset, and whether that point is a valid target. - `motor_action_l2`: the stock action penalty without the gaze. `isaaclab_fovi.rsl_rl.GazeSupervisedPPOCfg` trains PPO with an added loss that diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi index 577237ff3391..56478d9adeb8 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -14,7 +14,6 @@ __all__ = [ "gaze_teacher_labels", "motor_action_l2", "random_gaze", - "teacher_labels", ] from .gaze import ( @@ -27,6 +26,5 @@ from .gaze import ( gaze_teacher_labels, motor_action_l2, random_gaze, - teacher_labels, ) from .gaze_cfg import GazeActionCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 2046f241602a..501281ff48bc 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -469,18 +469,6 @@ def entity_point( return position + quat_apply(orientation, offset.expand_as(position)) -def teacher_labels(env: ManagerBasedEnv, points: torch.Tensor, action_name: str = "gaze") -> torch.Tensor: - """The teacher's gaze action toward world points and its validity, shape (num_envs, 3). - - A training label, never a policy input. Tasks whose target changes, for example from an object to a goal once - the object is grasped, choose the points and call this. - """ - term: GazeAction = env.action_manager.get_term(action_name) - labels, values = term._teacher_labels(wp.from_torch(points.float().contiguous(), dtype=wp.vec3f)) - _log_teacher(env, values) - return labels - - def _log_teacher(env: ManagerBasedEnv, values: torch.Tensor) -> None: """Log the mean gaze error to valid targets and the fraction of valid targets.""" # Loggers keep each step's entries, so they get a copy rather than the buffer the next step overwrites. diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py index e03e6306badd..51961079d42e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py @@ -35,8 +35,8 @@ class GazeSupervisedPPO(PPO): """PPO whose loss also pulls the policy's gaze toward a teacher's. The gaze is the last two actions. The teacher's labels are the observation group ``oracle_group``, as - :func:`isaaclab_fovi.mdp.teacher_labels` computes them; they never enter the actor or the critic. Only the means - of the gaze actions are supervised; PPO tunes their standard deviations like any other action's. + :class:`isaaclab_fovi.mdp.gaze_teacher_labels` computes them; they never enter the actor or the critic. Only the + means of the gaze actions are supervised; PPO tunes their standard deviations like any other action's. Args: oracle_loss_coef: Weight of the gaze loss. Zero trains plain PPO. From 17a89a28cd0c5fb90ad834a8a3ff93fea809b0ce Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 00:13:05 -0800 Subject: [PATCH 34/81] Build foveated Newton rays in the renderer's (H, W, 1, 2) layout Newton's SensorCamera renderer, merged from main, indexes the shared ray field as rays[y, x, camera, origin|direction] instead of rays[camera, y, x, ...]. --- .../isaaclab_fovi/sensors/foveated_newton_camera.py | 7 ++++--- source/isaaclab_fovi/test/test_newton_buffers.py | 2 +- source/isaaclab_fovi/test/test_rays.py | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index fcb6e3af5f65..b505b649a70a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -38,7 +38,8 @@ def explicit_rays(directions: torch.Tensor, height: int, width: int) -> wp.array: - """Newton's ray array, shape (1, height, width, 2): a zero origin and a unit direction per ray. + """Newton's ray array, shape (height, width, 1, 2): a zero origin and a unit direction per ray, shared by every + camera. Args: directions: Unit ray directions in the OpenGL camera frame, in sample order, shape (N, 3). @@ -50,8 +51,8 @@ def explicit_rays(directions: torch.Tensor, height: int, width: int) -> wp.array if height * width < len(directions): raise ValueError(f"A {height}x{width} render cannot hold {len(directions)} rays.") index = torch.arange(height * width, device=directions.device).clamp_max(len(directions) - 1) - rays = directions.new_zeros(1, height, width, 2, 3, dtype=torch.float32) - rays[..., 1, :] = directions.float()[index].reshape(1, height, width, 3) + rays = directions.new_zeros(height, width, 1, 2, 3, dtype=torch.float32) + rays[..., 1, :] = directions.float()[index].reshape(height, width, 1, 3) # The Warp view keeps the tensor alive. return wp.from_torch(rays, dtype=wp.vec3f) diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index b7328b84fb66..57c6554f4ebe 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -78,7 +78,7 @@ def render(camera, env_mask): camera._initialize_impl() rays = wp.to_torch(camera._foveated_rays) - assert rays.shape == (1, ray_coords.resolution, ray_coords.resolution, 2, 3) + assert rays.shape == (ray_coords.resolution, ray_coords.resolution, 1, 2, 3) torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], camera._ray_directions) public_rgba = camera._data.output["rgba"] camera.frame_offset = 0 diff --git a/source/isaaclab_fovi/test/test_rays.py b/source/isaaclab_fovi/test/test_rays.py index 3162cceb6b2d..fcdf0cf2ac9b 100644 --- a/source/isaaclab_fovi/test/test_rays.py +++ b/source/isaaclab_fovi/test/test_rays.py @@ -23,9 +23,9 @@ def test_explicit_rays_preserve_sample_order_and_optical_center() -> None: torch.tensor([[0.7, 0.3, -1.0], [-0.2, 0.6, -1.0], [0.0, 0.0, -1.0]]), dim=-1 ) rays = explicit_rays(directions, 3, 1) - assert rays.shape == (1, 3, 1, 2) + assert rays.shape == (3, 1, 1, 2) assert rays.dtype == wp.vec3f - rays = wp.to_torch(rays)[0, :, 0] + rays = wp.to_torch(rays)[:, 0, 0] torch.testing.assert_close(rays[:, 0], torch.zeros_like(directions)) torch.testing.assert_close(rays[:, 1], directions) From b11a11b880280e1f1e16927b1a9f8357ce4854ed Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 00:26:20 -0800 Subject: [PATCH 35/81] Address the third review round and support Newton OptiX Gaze: the camera's stored angles own the gaze, so the step and the teacher start from them; the fixed-mount teacher counts mount turns from its own capture; the teacher honours its offset argument; GazeAction uses a public camera interface (gaze_angles, mount_quat_w_ros, ungazed_quat_w_ros, camera_model, projection_params, image_frame, turns_pose_by_gaze) instead of private fields. Cameras: OVRTX clones the configuration before sizing its textures; camera members follow the contributing guide's order; FoveatedCameraCfg resolves its class with {DIR}; modal segmentation pooling reuses the standard pooler's neighbour table and ModalPooler is gone. newton_optix dispatches to the Newton camera, whose rays Newton's OptiX backend takes unchanged. Style: export GazeSupervisedPPO, relative imports in the tasks, inline the Kuka reward assignment, direct field validation, trimmed docstrings. Tests: lazy config resolution in a fresh interpreter, zero-coefficient PPO equal to stock PPO, sparse permuted RTX extraction, independent square-shell rays, a gaze set on the camera carrying into the next step, and OptiX render cases that skip where OptiX cannot load. --- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 84 +++-- .../isaaclab_fovi/mdp/gaze_cfg.py | 12 +- .../isaaclab_fovi/rsl_rl/__init__.pyi | 3 +- .../isaaclab_fovi/sensors/foveated_camera.py | 315 +++++++++++------- .../sensors/foveated_camera_cfg.py | 15 +- .../sensors/foveated_newton_camera.py | 20 +- .../sensors/foveated_rtx_camera.py | 155 ++++----- .../isaaclab_fovi/sensors/pooling.py | 51 +-- .../isaaclab_fovi/tasks/active_gaze.py | 4 +- .../isaaclab_fovi/tasks/agents.py | 2 +- .../isaaclab_fovi/tasks/cartpole/env_cfg.py | 5 +- .../tasks/kuka_allegro/env_cfg.py | 14 +- source/isaaclab_fovi/test/test_active_gaze.py | 84 +++-- .../test/test_backend_dispatch.py | 2 +- .../test/test_foveated_camera_render.py | 31 +- .../isaaclab_fovi/test/test_newton_buffers.py | 9 +- source/isaaclab_fovi/test/test_pooling.py | 43 +-- source/isaaclab_fovi/test/test_rtx_camera.py | 16 +- .../test/test_spherical_geometry.py | 8 +- .../test/test_square_native_grid.py | 103 ++++++ 20 files changed, 573 insertions(+), 403 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 501281ff48bc..25530749bc90 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -23,7 +23,6 @@ from isaaclab.utils.math import quat_apply from isaaclab.utils.warp import ProxyArray -from ..sensors.calibrated_geometry import convert_camera_frame_quaternion from ..sensors.gaze_kernels import ( DEG_TO_RAD, CameraParams, @@ -85,7 +84,7 @@ def teacher_labels_kernel( rotate_offset: wp.int32, positions: wp.array(dtype=wp.vec3f), mounts: wp.array(dtype=wp.quatf), - state: wp.array(dtype=wp.vec4f), + angles_deg: wp.array(dtype=wp.vec2f), frame: wp.mat33f, field_radius_deg: wp.float32, step_size: wp.float32, @@ -97,7 +96,7 @@ def teacher_labels_kernel( """Labels (action x, action y, valid) toward a point fixed to each target; and the mean gaze error to valid targets [deg] with the fraction of valid targets. - ``mounts`` holds each camera's mount (ROS convention); ``state`` each gaze, in field radii, and its velocity. + ``mounts`` holds each camera's mount (ROS convention); ``angles_deg`` the camera's stored gaze angles [deg]. One block labels every environment and reduces the logs itself, so the launch needs no zeroed accumulators. """ _block, lane = wp.tid() @@ -109,8 +108,7 @@ def teacher_labels_kernel( point = targets[i] if rotate_offset != 0: point = point + wp.quat_rotate(orientations[i], offset) - s = state[i] - gaze = wp.vec2f(s[0], s[1]) + gaze = angles_deg[i] / field_radius_deg result = teach(point, positions[i], mounts[i], gaze, frame, field_radius_deg, step_size, gaze_limit, camera) labels[i, 0] = result[0] labels[i, 1] = result[1] @@ -168,12 +166,12 @@ def gaze_step_kernel( ): """Move each gaze by its clamped action and keep it within the limit; record the gaze, velocity and angles. - ``state`` holds each gaze and its velocity, in field radii and field radii per second. + The step starts from the camera's stored ``angles_deg``, which own the gaze. ``state`` records each gaze and its + velocity, in field radii and field radii per second. """ i = wp.tid() a = actions[i] - s = state[i] - previous = wp.vec2f(s[0], s[1]) + previous = angles_deg[i] / field_radius_deg moved = previous + wp.vec2f(wp.clamp(a[0], -1.0, 1.0), wp.clamp(a[1], -1.0, 1.0)) * step_size current = moved * (gaze_limit / wp.max(wp.length(moved), gaze_limit)) rate = (current - previous) / step_dt @@ -215,8 +213,13 @@ class GazeAction(ActionTerm): against a rolled mount. With ``mount="fixed"`` the camera keeps the orientation it had when the term was created, and the teacher uses - that mount; turning the camera's mount raises. With ``mount="tracked"`` the camera may ride a moving body, for - example a robot's head, and the teacher reads each camera's current mount, so software gaze adds to hardware gaze. + that mount; turning the camera's mount afterwards raises. With ``mount="tracked"`` the camera may ride a moving + body, for example a robot's head, and the teacher reads each camera's current mount, so software gaze adds to + hardware gaze. + + The camera's stored gaze angles own the gaze: each step and the teacher start from them, so a gaze set directly + with :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles` carries on. :attr:`state`, the observation, is + the gaze and velocity as of the last step or reset. """ cfg: GazeActionCfg @@ -231,7 +234,7 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): self.camera = self._asset camera = self.camera self.tracked_mount = cfg.mount == "tracked" - if self.tracked_mount and not (camera._gaze_pose_reads_angles and camera.cfg.update_latest_camera_pose): + if self.tracked_mount and not camera.turns_pose_by_gaze: raise ValueError( "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX," " with update_latest_camera_pose." @@ -245,12 +248,10 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): f"A fixed gaze mount needs a camera mounted on the environment, got {camera.cfg.prim_path!r};" " use mount='tracked' for a camera on a moving body." ) - if not hasattr(camera, "_gaze_camera"): - raise RuntimeError(f"The gaze camera {cfg.asset_name!r} must be initialized before its gaze action.") # The camera's own geometry, so the teacher and the sensor mask share one projection. - self.camera_model = camera._camera_model - self._camera = camera._gaze_camera - self._frame = camera._mask_frame + self.camera_model = camera.camera_model + self._camera = camera.projection_params + self._frame = camera.image_frame self._frame_torch = torch.tensor( [[self._frame[row][col] for col in range(3)] for row in range(3)], device=self.device ) @@ -258,17 +259,14 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): """Half the retina's field of view [deg].""" self._fixed_mount = None if not self.tracked_mount: - # The camera's ungazed world orientation now, ROS convention; the fixed-mount teacher keeps it. - orientation = camera._data.quat_w_world - orientation = orientation.torch if hasattr(orientation, "torch") else orientation - opengl = convert_camera_frame_quaternion(orientation.float(), origin="world", target="opengl") - ros = convert_camera_frame_quaternion(opengl, origin="opengl", target="ros") - self._fixed_mount = ProxyArray(wp.from_torch(ros.contiguous(), dtype=wp.quatf)) + # The fixed-mount teacher keeps the camera's mount as it is now; only later turns invalidate it. + mount = camera.ungazed_quat_w_ros() + self._fixed_mount = ProxyArray(wp.from_torch(mount.contiguous(), dtype=wp.quatf)) + self._mount_turns = camera.mount_turns self._raw: torch.Tensor | None = None """Gaze actions of the last step, as supplied to :meth:`process_actions`.""" self._state = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec4f, device=self.device)) - """Gaze and its velocity, the gaze observation; the gaze and velocity are views of it.""" - self._gaze = self._state.torch[:, :2] + """Gaze and its velocity as of the last step or reset, the gaze observation.""" self._velocity = self._state.torch[:, 2:] self._step_launch: tuple[tuple, wp.Launch] | None = None self._labels = ProxyArray(wp.zeros((self.num_envs, 3), dtype=wp.float32, device=self.device)) @@ -287,16 +285,16 @@ def action_dim(self) -> int: @property def raw_actions(self) -> torch.Tensor: - return self._raw if self._raw is not None else torch.zeros_like(self._gaze) + return self._raw if self._raw is not None else torch.zeros_like(self._velocity) @property def processed_actions(self) -> torch.Tensor: - return self._gaze + return self.gaze @property def gaze(self) -> torch.Tensor: - """Current gaze in field radii, shape (num_envs, 2).""" - return self._gaze + """Current gaze in field radii, from the camera's stored angles, shape (num_envs, 2).""" + return self.angles_deg / self.field_radius_deg @property def velocity(self) -> torch.Tensor: @@ -310,8 +308,8 @@ def state(self) -> torch.Tensor: @property def angles_deg(self) -> torch.Tensor: - """Current gaze angles [deg], shape (num_envs, 2).""" - return self._gaze * self.field_radius_deg + """Current gaze angles [deg], the camera's stored ones, shape (num_envs, 2).""" + return self.camera.gaze_angles.torch def process_actions(self, actions: torch.Tensor): """Move the gaze by the supplied actions, shape (num_envs, 2). @@ -329,7 +327,7 @@ def process_actions(self, actions: torch.Tensor): [ wp.from_torch(actions, dtype=wp.vec2f), self._state, - self._camera_angles(), + self.camera.gaze_angles, self.cfg.step_size, self.cfg.gaze_limit, self._env.step_dt, @@ -340,7 +338,7 @@ def process_actions(self, actions: torch.Tensor): self._step_launch = (key, launch) self._raw = actions self._step_launch[1].launch(warp_stream(self.device)) - self.camera.set_gaze_angles(self._camera_angles().torch) + self.camera.set_gaze_angles(self.camera.gaze_angles.torch) def apply_actions(self): pass @@ -361,7 +359,7 @@ def reset(self, env_ids=None): gaze = random_gaze(count, self.cfg.gaze_limit, self.device) visible = self.visible(angles_to_direction(gaze * self.field_radius_deg)) self._reset_start.torch[:count] = torch.where(visible[:, None], gaze, 0.0) - angles = self._camera_angles() + angles = self.camera.gaze_angles launch = self._reset_launches.get((indexed, random_start)) if launch is None: launch = self._reset_launches[(indexed, random_start)] = record_launch( @@ -376,11 +374,6 @@ def reset(self, env_ids=None): # The camera keeps reading the same buffer, which every other environment already holds. self.camera.set_gaze_angles(angles.torch) - def _camera_angles(self) -> ProxyArray: - """The camera's stored gaze angles [deg], which the gaze kernels write in place.""" - self.camera.gaze_angles_buffer() - return self.camera._gaze_angles - def visible(self, direction: torch.Tensor) -> torch.Tensor: """Whether directions in the upright gaze frame fall inside the physical camera's image.""" return project_directions(direction @ self._frame_torch.T, self._camera)[1] @@ -403,9 +396,8 @@ def _teacher_labels( RuntimeError: The camera's mount turned while the gaze assumes a fixed mount. """ if self.tracked_mount: - self.camera.gaze_angles_buffer() - mounts = self.camera._mount_quat_ros - elif self.camera.mount_moved: + mounts = self.camera.mount_quat_w_ros + elif self.camera.mount_turns != self._mount_turns: raise RuntimeError( "The gaze camera's mount turned, so the fixed-mount teacher would aim from its first orientation;" " use GazeActionCfg.mount='tracked'." @@ -426,7 +418,7 @@ def _teacher_labels( int(orientations is not None), positions, mounts, - self._state, + self.camera.gaze_angles, self._frame, self.field_radius_deg, self.cfg.step_size, @@ -489,7 +481,7 @@ class gaze_teacher_labels(ManagerTermBase): def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv): super().__init__(cfg, env) - self._offset = wp.vec3f(*cfg.params.get("offset", (0.0, 0.0, 0.0))) + self._offset: tuple[tuple[float, ...], wp.vec3f] | None = None self._sources = None self._targets = self._orientations = None @@ -514,8 +506,12 @@ def __call__( body = target_cfg.body_ids[0] self._targets = wp.from_torch(positions.torch[:, body], dtype=wp.vec3f) self._orientations = wp.from_torch(orientations.torch[:, body], dtype=wp.quatf) + # The recorded teacher launch is kept while the point stays the same object. + point = tuple(float(value) for value in offset) + if self._offset is None or self._offset[0] != point: + self._offset = (point, wp.vec3f(*point)) term: GazeAction = env.action_manager.get_term(action_name) - labels, values = term._teacher_labels(self._targets, self._orientations, self._offset) + labels, values = term._teacher_labels(self._targets, self._orientations, self._offset[1]) _log_teacher(env, values) return labels diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py index aa58d67236c3..03869532e85a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py @@ -39,9 +39,13 @@ class GazeActionCfg(ActionTermCfg): def validate_config(self): """Reject gaze bounds that would divide by zero and unknown mounts.""" - for name in ("step_size", "gaze_limit"): - value = getattr(self, name) - if not (isinstance(value, (int, float)) and math.isfinite(value) and value > 0): - raise ValueError(f"GazeActionCfg.{name} must be positive and finite, got {value!r}.") + if not _positive_finite(self.step_size): + raise ValueError(f"GazeActionCfg.step_size must be positive and finite, got {self.step_size!r}.") + if not _positive_finite(self.gaze_limit): + raise ValueError(f"GazeActionCfg.gaze_limit must be positive and finite, got {self.gaze_limit!r}.") if self.mount not in ("fixed", "tracked"): raise ValueError(f"GazeActionCfg.mount must be 'fixed' or 'tracked', got {self.mount!r}.") + + +def _positive_finite(value) -> bool: + return isinstance(value, (int, float)) and math.isfinite(value) and value > 0 diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi index f87986fdbb3a..e437684a352f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi @@ -3,6 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -__all__ = ["GazeSupervisedPPOCfg"] +__all__ = ["GazeSupervisedPPO", "GazeSupervisedPPOCfg"] +from .gaze_supervised_ppo import GazeSupervisedPPO from .gaze_supervised_ppo_cfg import GazeSupervisedPPOCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 42d884f80081..3cae499852df 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -13,6 +13,7 @@ import torch import warp as wp +from fovi.sensing.projection import CameraModel from isaaclab.sensors.camera.camera import Camera from isaaclab.utils.warp import ProxyArray @@ -30,7 +31,14 @@ warp_stream, ) from .native_grid import GRID_STYLE, native_grid_directions -from .pooling import ModalPooler, is_segmentation_output, pool_hwc_buffer, pool_segmentation_buffer +from .pooling import ( + MODAL_POOL_MODE, + build_pooler, + is_segmentation_output, + pool_hwc_buffer, + pool_segmentation_buffer, + segmentation_neighbor_indices, +) if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg @@ -45,8 +53,8 @@ class FoveatedCamera(Camera): The sample layout comes from :class:`fovi.sensing.coords.SamplingCoords`. Constructing this class returns the implementation for the renderer selected by :attr:`FoveatedCameraCfg.renderer_cfg`: - * ``newton_warp``: :class:`~isaaclab_fovi.sensors.foveated_newton_camera.FoveatedNewtonCamera`, which injects - the foveated rays into the Newton Warp renderer. + * ``newton_warp`` and ``newton_optix``: :class:`~isaaclab_fovi.sensors.foveated_newton_camera.FoveatedNewtonCamera`, + which injects the foveated rays into Newton's renderer. * ``isaac_rtx`` and ``ovrtx``: :class:`~isaaclab_fovi.sensors.foveated_rtx_camera.FoveatedRTXCamera`, which authors a lens lookup table on the camera prim. @@ -62,7 +70,7 @@ class FoveatedCamera(Camera): _gaze_pose_reads_angles: bool = False """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses when - the gaze is set. A writer of :meth:`gaze_angles_buffer` then needs no other launch.""" + the gaze is set; see :attr:`turns_pose_by_gaze`.""" def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): """Create the implementation that matches the configured renderer. @@ -76,7 +84,7 @@ def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): if cls is not FoveatedCamera: return super().__new__(cls) renderer_type = cfg.renderer_cfg.renderer_type - if renderer_type == "newton_warp": + if renderer_type in ("newton_warp", "newton_optix"): from .foveated_newton_camera import FoveatedNewtonCamera return super().__new__(FoveatedNewtonCamera) @@ -85,7 +93,8 @@ def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): return super().__new__(FoveatedRTXCamera) raise ValueError( - f"Unsupported foveated renderer {renderer_type!r}; select 'newton_warp', 'isaac_rtx', or 'ovrtx'." + f"Unsupported foveated renderer {renderer_type!r}; select 'newton_warp', 'newton_optix', 'isaac_rtx', or" + " 'ovrtx'." ) def __init__(self, cfg: FoveatedCameraCfg): @@ -95,24 +104,84 @@ def __init__(self, cfg: FoveatedCameraCfg): self._visibility = None self._grid_publish = None self._published_shape: tuple[int, int] | None = None - self.mount_moved = False - """Whether :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has moved the camera's mount since - construction.""" + self._pooler_int = None + self._segmentation_neighbors: torch.Tensor | None = None + self.mount_turns = 0 + """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount.""" super().__init__(cfg) - # ------------------------------------------------------------------ - # Gaze - # ------------------------------------------------------------------ + @property + def image_shape(self) -> tuple[int, int]: + """(height, width) of the published outputs: the retina's grid, or (num_samples, 1) for sample sets.""" + return self._published_shape if self._published_shape is not None else super().image_shape + + @property + def sampling_coords(self): + """The :class:`SamplingCoords` of the published samples.""" + return self._sampling_coords + + @property + def image_rotation_deg(self) -> float: + """Roll [deg] of the rendered rays around the optical axis, which undoes a rolled mount.""" + return float(self.cfg.image_rotation_deg) + + @property + def num_valid_samples(self) -> int: + """Number of published foveated samples.""" + return self._num_valid_samples - def gaze_angles_buffer(self) -> torch.Tensor: - """The camera's stored gaze angles [deg], shape (num_envs, 2). + @property + def sensor_fov_valid_fraction(self) -> torch.Tensor | None: + """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" + valid = getattr(self, "_sensor_fov_valid", None) + return None if valid is None else valid.float().mean(dim=1) - A writer that moves the gaze every step can update this buffer in place and pass it to + @property + def camera_model(self) -> CameraModel: + """The physical camera the retina looks through, as resolved at initialization.""" + return self._camera_model + + @property + def projection_params(self) -> CameraParams: + """:attr:`camera_model` as a Warp struct, for kernels that project camera-frame directions.""" + return self._gaze_camera + + @property + def image_frame(self) -> wp.mat33f: + """Rotation from the upright image frame, in which gazes are measured, to the physical camera's frame (ROS + convention); it undoes :attr:`image_rotation_deg`.""" + return self._mask_frame + + @property + def turns_pose_by_gaze(self) -> bool: + """Whether each pose update turns the rendered pose by the stored gaze (Newton and OVRTX with + ``update_latest_camera_pose``). A writer of :attr:`gaze_angles` then needs no other launch.""" + return self._gaze_pose_reads_angles and self.cfg.update_latest_camera_pose + + @property + def gaze_angles(self) -> ProxyArray: + """The camera's stored gaze angles [deg], shape (num_envs,) of ``vec2f`` (Torch view (num_envs, 2)). + + A writer that moves the gaze every step can update this buffer in place and pass its Torch view to :meth:`set_gaze_angles`, which then copies nothing. Writes take effect when :meth:`set_gaze_angles` is called. """ if self._gaze_angles is None: self._allocate_gaze() - return self._gaze_angles.torch + return self._gaze_angles + + @property + def mount_quat_w_ros(self) -> ProxyArray: + """World orientation (x, y, z, w) of the physical camera before the gaze turns it, ROS convention, shape + (num_envs,) of ``quatf``. + + Refreshed by each pose update that turns the gaze, so it follows a mount that moves, for example a camera on + a robot's head. Only cameras whose pose update turns the gaze (Newton and OVRTX) record it. + """ + if not self._gaze_pose_reads_angles: + raise RuntimeError("Only cameras whose pose update turns the gaze (Newton, OVRTX) record their mount.") + if self._gaze_angles is None: + self._allocate_gaze() + return self._mount_quat_ros def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. @@ -127,13 +196,13 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: ValueError: The angles do not hold one row per camera. """ stored = self._gaze_angles is not None and angles_deg is self._gaze_angles.torch - if stored and self._gaze_pose_reads_angles and self.cfg.update_latest_camera_pose: + if stored and self.turns_pose_by_gaze: # The next pose update reads the stored angles; nothing has to happen now. return count = self._view.count if tuple(angles_deg.shape) != (count, 2): raise ValueError(f"Gaze angles must have shape ({count}, 2), got {tuple(angles_deg.shape)}.") - gaze = self.gaze_angles_buffer() + gaze = self.gaze_angles.torch angles = angles_deg if stored else angles_deg.detach().to(device=gaze.device, dtype=torch.float32).contiguous() # Callers usually pass the same buffer every step; record its launch once. key = angles.data_ptr() @@ -148,18 +217,22 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: ) self._set_gaze_launch.launch(warp_stream(gaze.device)) - @property - def mount_quat_w_ros(self) -> torch.Tensor: - """World orientation (x, y, z, w) of the physical camera before the gaze turns it, ROS convention, shape + def ungazed_quat_w_ros(self) -> torch.Tensor: + """World orientation (x, y, z, w) of the physical camera now, before the gaze turns it, ROS convention, shape (num_envs, 4). - Refreshed by each pose update that turns the gaze, so it follows a mount that moves, for example a camera on - a robot's head. Only cameras whose pose update turns the gaze (Newton and OVRTX) record it. + Raises: + RuntimeError: A gaze is set on a camera that writes it into its prims (Isaac RTX), so the current pose + includes it. """ - if not self._gaze_pose_reads_angles: - raise RuntimeError("Only cameras whose pose update turns the gaze (Newton, OVRTX) record their mount.") - self.gaze_angles_buffer() - return self._mount_quat_ros.torch + if self._gaze_angles is None: + orientation = self._data.quat_w_world + orientation = orientation.torch if hasattr(orientation, "torch") else orientation + opengl = convert_camera_frame_quaternion(orientation.float(), origin="world", target="opengl") + return convert_camera_frame_quaternion(opengl, origin="opengl", target="ros") + if self._gaze_pose_reads_angles: + return self._mount_quat_ros.torch.clone() + raise RuntimeError("The camera's prims already hold a gaze; read its mount before setting one.") def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): """Move the camera's mount; the gaze stays relative to the new mount. @@ -167,9 +240,9 @@ def set_world_poses(self, positions=None, orientations=None, env_ids=None, conve Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. """ super().set_world_poses(positions, orientations, env_ids, convention) - # The teachers read the camera's live position, so only a turned mount counts as moved. + # The teachers read the camera's live position, so only a turned mount counts. if orientations is not None: - self.mount_moved = True + self.mount_turns += 1 def set_world_poses_from_view(self, eyes, targets, env_ids=None): """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. @@ -178,11 +251,43 @@ def set_world_poses_from_view(self, eyes, targets, env_ids=None): """ super().set_world_poses_from_view(eyes, targets, env_ids) if self._turned_by_view(eyes, targets).any(): - self.mount_moved = True + self.mount_turns += 1 - def _turned_by_view(self, eyes, targets) -> torch.Tensor: - """Which rows :meth:`set_world_poses_from_view` turns: the base method skips an eye equal to its target.""" - return (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0 + def _initialize_gaze(self) -> None: + """Prepare the gaze geometry: the rendered rays in the physical camera's frame and the pose conversions.""" + self._camera_model = resolve_camera_model(self.cfg) + self._gaze_camera = camera_params(self._camera_model) + coords = self._sampling_coords_highres or self._sampling_coords + rotation_deg = self.cfg.image_rotation_deg + # The rays as rendered, mount roll included, in the ROS frame the camera model projects. + if coords.style == GRID_STYLE: + rays = native_grid_directions(coords, image_rotation_deg=rotation_deg) + else: + rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) + self._gaze_rays = (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() + # No gaze until one is set: the camera looks along its optical axis untouched. + self._gaze_angles = None + self._gaze_rotation = None + self._visibility = None + device = self._gaze_rays.device + self._gaze_identity = torch.eye(3, device=device) + angle = math.radians(rotation_deg) + c, s = math.cos(angle), math.sin(angle) + # Gaze is defined in the upright image frame; the basis carries it into the rolled OpenGL camera frame. + self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) + # The same roll in the ROS frame: a rendered ray r reaches the physical camera at K gaze K^T r. + self._mask_frame = wp.mat33f(c, s, 0.0, -s, c, 0.0, 0.0, 0.0, 1.0) + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device) + opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl") + to_opengl = opengl[0].tolist() + to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0].tolist() + to_ros = convert_camera_frame_quaternion(opengl, origin="opengl", target="ros")[0].tolist() + self._gaze_frames = ( + wp.mat33f(*self._gaze_basis.flatten().tolist()), + wp.quatf(*to_opengl), + wp.quatf(*to_world), + wp.quatf(*to_ros), + ) def _allocate_gaze(self) -> None: """Allocate one stored gaze per camera, on the optical axis, its rotation and the mount, on the sensor @@ -197,6 +302,21 @@ def _allocate_gaze(self) -> None: self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=device) + def _update_camera_state( + self, + env_ids: wp.array | None = None, + env_mask: wp.array | None = None, + pos_src: wp.array | None = None, + quat_src: wp.array | None = None, + update_pose: bool = False, + frame_op: int = 0, + ): + """Update the camera state; when the pose update turns the gaze, turn freshly read poses before the renderer + sees them.""" + super()._update_camera_state(env_ids, env_mask, pos_src, quat_src, update_pose, frame_op) + if update_pose and self._gaze_pose_reads_angles: + self._apply_gaze_pose(env_ids, env_mask) + def _apply_gaze_pose( self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None ) -> None: @@ -229,60 +349,9 @@ def _apply_gaze_pose( launch.set_dim(len(env_ids)) launch.launch(warp_stream(device)) - def _update_camera_state( - self, - env_ids: wp.array | None = None, - env_mask: wp.array | None = None, - pos_src: wp.array | None = None, - quat_src: wp.array | None = None, - update_pose: bool = False, - frame_op: int = 0, - ): - """Update the camera state; when the pose update turns the gaze, turn freshly read poses before the renderer - sees them.""" - super()._update_camera_state(env_ids, env_mask, pos_src, quat_src, update_pose, frame_op) - if update_pose and self._gaze_pose_reads_angles: - self._apply_gaze_pose(env_ids, env_mask) - - def _initialize_gaze(self) -> None: - """Prepare the gaze geometry: the rendered rays in the physical camera's frame and the pose conversions.""" - self._camera_model = resolve_camera_model(self.cfg) - self._gaze_camera = camera_params(self._camera_model) - coords = self._sampling_coords_highres or self._sampling_coords - rotation_deg = self.cfg.image_rotation_deg - # The rays as rendered, mount roll included, in the ROS frame the camera model projects. - if coords.style == GRID_STYLE: - rays = native_grid_directions(coords, image_rotation_deg=rotation_deg) - else: - rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) - self._gaze_rays = (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() - # No gaze until one is set: the camera looks along its optical axis untouched. - self._gaze_angles = None - self._gaze_rotation = None - self._visibility = None - device = self._gaze_rays.device - self._gaze_identity = torch.eye(3, device=device) - angle = math.radians(rotation_deg) - c, s = math.cos(angle), math.sin(angle) - # Gaze is defined in the upright image frame; the basis carries it into the rolled OpenGL camera frame. - self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) - # The same roll in the ROS frame: a rendered ray r reaches the physical camera at K gaze K^T r. - self._mask_frame = wp.mat33f(c, s, 0.0, -s, c, 0.0, 0.0, 0.0, 1.0) - identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device) - opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl") - to_opengl = opengl[0].tolist() - to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0].tolist() - to_ros = convert_camera_frame_quaternion(opengl, origin="opengl", target="ros")[0].tolist() - self._gaze_frames = ( - wp.mat33f(*self._gaze_basis.flatten().tolist()), - wp.quatf(*to_opengl), - wp.quatf(*to_world), - wp.quatf(*to_ros), - ) - - # ------------------------------------------------------------------ - # Sensor mask and publication - # ------------------------------------------------------------------ + def _turned_by_view(self, eyes, targets) -> torch.Tensor: + """Which rows :meth:`set_world_poses_from_view` turns: the base method skips an eye equal to its target.""" + return (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0 def _visibility_buffers(self) -> dict: """The sensor mask's camera-owned buffers, allocated once: the rendered rays, an unturned rotation per camera, @@ -335,6 +404,37 @@ def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor], env_mask: continue tensor.masked_fill_(hidden, 0) + def _prepare_segmentation_pooling(self, names) -> None: + """Choose how pooled segmentation outputs among ``names`` are reduced: by modal label over the main pooler's + neighbourhoods (``pool_int_mode="mode"``), or by a second fovi pooler for another ``pool_int_mode``.""" + self._pooler_int = None + self._segmentation_neighbors = None + if self._pooler is None or not any(is_segmentation_output(name) for name in names): + return + if self.cfg.pool_int_mode == MODAL_POOL_MODE: + self._segmentation_neighbors = segmentation_neighbor_indices(self._pooler) + elif self.cfg.pool_int_mode != self.cfg.pool_mode: + self._pooler_int, _ = build_pooler( + self.cfg, + self._sampling_coords, + self._sampling_coords_highres, + device=str(self._device), + mode=self.cfg.pool_int_mode, + ) + + def _pool_output(self, name: str, samples: torch.Tensor) -> torch.Tensor: + """Pool one output's high-resolution samples (B, N_hi, 1, C) to the retina's (B, N_lo, 1, C), in its dtype. + + Segmentation takes each sample's modal label in its native dtype by default; other outputs are pooled in + float. + """ + if is_segmentation_output(name): + if self._segmentation_neighbors is not None: + return pool_segmentation_buffer(self._segmentation_neighbors, samples) + if self._pooler_int is not None: + return pool_hwc_buffer(self._pooler_int, samples.float()).to(samples.dtype) + return pool_hwc_buffer(self._pooler, samples.float()).to(samples.dtype) + def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for :func:`publish_grid_kernel`.""" @@ -408,50 +508,9 @@ def _publish_grid(self, env_mask: wp.array | None = None) -> None: if mask: self._sensor_fov_valid = self._visibility["valid"].torch - def _pool_output(self, name: str, samples: torch.Tensor) -> torch.Tensor: - """Pool one output's high-resolution samples (B, N_hi, 1, C) to the retina's (B, N_lo, 1, C), in its dtype. - - Segmentation takes each sample's modal label in its native dtype; other outputs are pooled in float. - """ - if self._pooler_int is not None and is_segmentation_output(name): - if isinstance(self._pooler_int, ModalPooler): - return pool_segmentation_buffer(self._pooler_int, samples) - return pool_hwc_buffer(self._pooler_int, samples.float()).to(samples.dtype) - return pool_hwc_buffer(self._pooler, samples.float()).to(samples.dtype) - - # ------------------------------------------------------------------ - # Output description - # ------------------------------------------------------------------ - def _set_published_shape(self, outputs: Mapping[str, torch.Tensor]) -> None: """Report the (height, width) of the published outputs, which differ from the rendered ones.""" first = next(iter(outputs.values())) tensor = first.torch if hasattr(first, "torch") else first self._published_shape = (int(tensor.shape[1]), int(tensor.shape[2])) self._data.image_shape = self._published_shape - - @property - def image_shape(self) -> tuple[int, int]: - """(height, width) of the published outputs: the retina's grid, or (num_samples, 1) for sample sets.""" - return self._published_shape if self._published_shape is not None else super().image_shape - - @property - def sampling_coords(self): - """The :class:`SamplingCoords` of the published samples.""" - return self._sampling_coords - - @property - def image_rotation_deg(self) -> float: - """Roll [deg] of the rendered rays around the optical axis, which undoes a rolled mount.""" - return float(self.cfg.image_rotation_deg) - - @property - def num_valid_samples(self) -> int: - """Number of published foveated samples.""" - return self._num_valid_samples - - @property - def sensor_fov_valid_fraction(self) -> torch.Tensor | None: - """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" - valid = getattr(self, "_sensor_fov_valid", None) - return None if valid is None else valid.float().mean(dim=1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 0e97797ddaf9..99e5d047bf40 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -8,6 +8,7 @@ from __future__ import annotations import math +from typing import TYPE_CHECKING from fovi.sensing.coords import RADIUS_NORMS, WARPED_CARTESIAN_STYLES from fovi.sensing.projection import CameraCalibration @@ -15,6 +16,9 @@ from isaaclab.sensors.camera.camera_cfg import CameraCfg from isaaclab.utils.configclass import configclass +if TYPE_CHECKING: + from .foveated_camera import FoveatedCamera + def validate_radius_norm(radius_norm: float, style: str, fov_type: str) -> None: """Reject warped-grid radius norms that fovi cannot sample, before renderer startup.""" @@ -36,11 +40,11 @@ class FoveatedCameraCfg(CameraCfg): from :class:`fovi.sensing.coords.SamplingCoords`; ``height`` and ``width`` are computed from the number of samples. - :class:`~isaaclab_fovi.sensors.FoveatedCamera` selects its Newton or RTX - implementation from ``renderer_cfg.renderer_type``. + :class:`~isaaclab_fovi.sensors.FoveatedCamera` selects its Newton (Warp or + OptiX) or RTX implementation from ``renderer_cfg.renderer_type``. """ - class_type: type | str = "isaaclab_fovi.sensors:FoveatedCamera" + class_type: type[FoveatedCamera] | str = "{DIR}.foveated_camera:FoveatedCamera" # -- Foveation parameters (no img_height/img_width/fixation_size) -------- @@ -95,10 +99,7 @@ class FoveatedCameraCfg(CameraCfg): upright; the sensor mask and the gaze use the same roll.""" mask_to_sensor_fov: bool = False - """Zero the samples that fall outside the physical camera's image at the current gaze. - - With gaze the retina can look past the edge of the physical camera; this - keeps what the sensor reports to what that camera could have seen.""" + """Zero the samples that fall outside the physical camera's image at the current gaze.""" retinal_window_short_side_fraction: float = 1.0 """Diameter of the retinal window as a fraction of the reference image side.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index b505b649a70a..9992dbc247bd 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -29,7 +29,7 @@ native_grid_directions, proxy_outputs, ) -from .pooling import build_highres_coords, build_lowres_coords, build_pooler, is_segmentation_output +from .pooling import build_highres_coords, build_lowres_coords, build_pooler if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg @@ -62,7 +62,7 @@ class FoveatedNewtonCamera(FoveatedCamera): Instead of a uniform pixel grid, this sensor shoots *N* rays whose directions are derived from :class:`fovi.sensing.coords.SamplingCoords` - and injected into Newton's Warp renderer. Vector sensors publish + and injected into Newton's renderer, with Warp or OptiX traversal. Vector sensors publish ``(B, N, 1, C)``; native grid sensors publish upright ``(B, H, W, C)``. The samples cover the retinal window of the physical camera; the gaze turns the rendered camera pose. @@ -122,7 +122,6 @@ def _initialize_impl(self): self._pooler, self._pool_k = build_pooler( self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) ) - self._pooler_int = None # The rays keep the canonical sample order; image_rotation_deg rolls their directions to undo a rolled mount. if self._native_grid: @@ -179,36 +178,25 @@ def _allocate_pooled_buffers(self) -> None: return self._highres_output: dict[str, ProxyArray] = dict(self._data.output) self._pooled_output: dict[str, torch.Tensor] = {} - needs_int_pooler = False for name, tex in self._highres_output.items(): tensor = tex.torch B, _, _, C = tensor.shape self._pooled_output[name] = torch.zeros( (B, self._num_valid_samples, 1, C), dtype=tensor.dtype, device=tensor.device ) - if is_segmentation_output(name) and self.cfg.pool_int_mode != self.cfg.pool_mode: - needs_int_pooler = True if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] - if needs_int_pooler: - self._pooler_int, _ = build_pooler( - self.cfg, - self._sampling_coords, - self._sampling_coords_highres, - device=str(self._device), - mode=self.cfg.pool_int_mode, - ) + self._prepare_segmentation_pooling(self._highres_output) dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} logger.info( "FoveatedNewtonCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) " - "outputs=%s int_pooler=%s int_mode=%s", + "outputs=%s int_mode=%s", self.cfg.pool_mode, self._pool_k, self.cfg.pool_sample_cortex, self._num_ray_samples, self._num_valid_samples, dtypes_summary, - self._pooler_int is not None, self.cfg.pool_int_mode, ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 0910f1a8a151..6489e7cf527a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -25,6 +25,7 @@ from isaaclab import sim as sim_utils from isaaclab.sensors.camera.camera import Camera +from isaaclab.utils import clone from isaaclab.utils.math import matrix_from_quat, quat_from_matrix from . import lens_lut @@ -39,7 +40,7 @@ native_grid_directions, proxy_outputs, ) -from .pooling import build_highres_coords, build_lowres_coords, build_pooler, is_segmentation_output +from .pooling import build_highres_coords, build_lowres_coords, build_pooler if TYPE_CHECKING: from isaaclab.renderers.base_renderer import BaseRenderer @@ -65,23 +66,6 @@ class FoveatedRTXCamera(FoveatedCamera): cfg: FoveatedCameraCfg - @property - def supports_batch_update(self) -> bool: - return True - - @staticmethod - def _update_buffers_batch_impl(sensors: Sequence[FoveatedRTXCamera]) -> None: - Camera._update_buffers_batch_impl(sensors) - if sim_utils.SimulationContext.instance() is None: - return # The base implementation already invoked scalar capture. - for sensor in sensors: - sensor.process_rendered_frame() - - @property - def renderer(self) -> BaseRenderer: - """Renderer shared with task-owned visual animation bindings.""" - return self._renderer - def __init__(self, cfg: FoveatedCameraCfg): ovrtx = cfg.renderer_cfg.renderer_type == "ovrtx" if ovrtx and getattr(cfg.renderer_cfg, "async_rendering", False) and cfg.mask_to_sensor_fov: @@ -97,6 +81,9 @@ def __init__(self, cfg: FoveatedCameraCfg): self._foveated_output: dict[str, torch.Tensor] = {} self._pooled_output: dict[str, torch.Tensor] | None = None if ovrtx: + # The projection sets the texture size on the configuration before the parent allocates for it; the + # caller's configuration stays untouched. + cfg = clone(cfg) self.cfg = cfg self._prepare_projection() super().__init__(cfg) @@ -117,9 +104,60 @@ def __del__(self, *args, **kwargs): lut_dir.cleanup() self._lut_dir = None - # ------------------------------------------------------------------ - # Initialisation - # ------------------------------------------------------------------ + @property + def supports_batch_update(self) -> bool: + return True + + @property + def renderer(self) -> BaseRenderer: + """Renderer shared with task-owned visual animation bindings.""" + return self._renderer + + def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: + super().set_gaze_angles(angles_deg) + if not self._gaze_pose_reads_angles: + self._write_gaze_local_pose() + + def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): + """Move the camera's mount; the gaze stays relative to the new mount. + + Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. + """ + super().set_world_poses(positions, orientations, env_ids, convention) + # A position-only move keeps the prims' gaze-turned orientation, and with it the saved mount. + if orientations is not None: + self._refresh_mount(env_ids) + + def set_world_poses_from_view(self, eyes, targets, env_ids=None): + """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. + + Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. + """ + super().set_world_poses_from_view(eyes, targets, env_ids) + # Rows whose eye equals their target are skipped by the base method and keep their mount. + self._refresh_mount(self._env_indices(env_ids)[self._turned_by_view(eyes, targets)]) + + def process_rendered_frame(self) -> None: + """Mask and publish the frame of the environments that scalar or batched rendering updated.""" + if not self._env_mask_has_any(self._is_outdated): + return + if self._grid_publish: + self._publish_grid(self._is_outdated) + return + # Only the updated environments' samples change, so pooling and the grid layout reproduce every other + # environment's last frame. + self._extract_foveated_samples(self._is_outdated) + mask_grid_samples(self._foveated_output, self._ray_coords) + self._apply_sensor_fov_mask(self._foveated_output, self._is_outdated) + + if self._pooled_output is not None: + for name, hi in self._foveated_output.items(): + if name == "rgb" and "rgba" in self._foveated_output: + continue # rgba alias + self._pooled_output[name].copy_(self._pool_output(name, hi)) + if self._native_grid: + source = self._pooled_output if self._pooled_output is not None else self._foveated_output + copy_grid_outputs(source, self._grid_output, self._grid_indices) def _prepare_projection(self) -> None: # The lens textures and sample extraction use the rendered samples: the high-resolution ones when pooling. @@ -230,7 +268,6 @@ def _initialize_impl(self) -> None: self._pooler, self._pool_k = build_pooler( self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) ) - self._pooler_int = None # The renderer keeps writing the texture buffers the parent bound to it; the camera publishes others. self._texture_output = self._data.output @@ -289,25 +326,15 @@ def _allocate_foveated_buffers(self): self._pooled_output = None return self._pooled_output = {} - needs_int_pooler = False for name, buf in self._foveated_output.items(): if name == "rgb" and has_rgba_alias: continue self._pooled_output[name] = torch.zeros( (self._view.count, self._num_valid_samples, 1, buf.shape[-1]), device=self._device, dtype=buf.dtype ) - if is_segmentation_output(name) and self.cfg.pool_int_mode != self.cfg.pool_mode: - needs_int_pooler = True if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] - if needs_int_pooler: - self._pooler_int, _ = build_pooler( - self.cfg, - self._sampling_coords, - self._sampling_coords_highres, - device=str(self._device), - mode=self.cfg.pool_int_mode, - ) + self._prepare_segmentation_pooling(self._pooled_output) logger.info( "FoveatedRTXCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", self.cfg.pool_mode, @@ -317,34 +344,6 @@ def _allocate_foveated_buffers(self): self._num_valid_samples, ) - # ------------------------------------------------------------------ - # Gaze and mount - # ------------------------------------------------------------------ - - def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: - super().set_gaze_angles(angles_deg) - if not self._gaze_pose_reads_angles: - self._write_gaze_local_pose() - - def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): - """Move the camera's mount; the gaze stays relative to the new mount. - - Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. - """ - super().set_world_poses(positions, orientations, env_ids, convention) - # A position-only move keeps the prims' gaze-turned orientation, and with it the saved mount. - if orientations is not None: - self._refresh_mount(env_ids) - - def set_world_poses_from_view(self, eyes, targets, env_ids=None): - """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. - - Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. - """ - super().set_world_poses_from_view(eyes, targets, env_ids) - # Rows whose eye equals their target are skipped by the base method and keep their mount. - self._refresh_mount(self._env_indices(env_ids)[self._turned_by_view(eyes, targets)]) - def _env_indices(self, env_ids) -> torch.Tensor: """The camera indices that ``env_ids`` selects, as a tensor.""" if env_ids is None: @@ -375,10 +374,6 @@ def _write_gaze_local_pose(self) -> None: local_orientation = quat_from_matrix(compose_rotations(self._base_local_orientation, relative)) self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f)) - # ------------------------------------------------------------------ - # Per-frame overrides - # ------------------------------------------------------------------ - def _update_buffers_impl(self, env_mask: wp.array): if not self._env_mask_has_any(env_mask): return @@ -386,28 +381,6 @@ def _update_buffers_impl(self, env_mask: wp.array): super()._update_buffers_impl(env_mask) self.process_rendered_frame() - def process_rendered_frame(self) -> None: - """Mask and publish the frame of the environments that scalar or batched rendering updated.""" - if not self._env_mask_has_any(self._is_outdated): - return - if self._grid_publish: - self._publish_grid(self._is_outdated) - return - # Only the updated environments' samples change, so pooling and the grid layout reproduce every other - # environment's last frame. - self._extract_foveated_samples(self._is_outdated) - mask_grid_samples(self._foveated_output, self._ray_coords) - self._apply_sensor_fov_mask(self._foveated_output, self._is_outdated) - - if self._pooled_output is not None: - for name, hi in self._foveated_output.items(): - if name == "rgb" and "rgba" in self._foveated_output: - continue # rgba alias - self._pooled_output[name].copy_(self._pool_output(name, hi)) - if self._native_grid: - source = self._pooled_output if self._pooled_output is not None else self._foveated_output - copy_grid_outputs(source, self._grid_output, self._grid_indices) - def _extract_foveated_samples(self, env_mask: wp.array): """Extract the updated environments' per-sample values from the rendered 2D textures into the (B, N, 1, C) buffers; the other environments keep their last samples.""" @@ -427,3 +400,11 @@ def _extract_foveated_samples(self, env_mask: wp.array): # OVRTX measures the distance from the near-clipped ray origin. samples = samples + self._near_clip fov.copy_(torch.where(updated, samples, fov)) + + @staticmethod + def _update_buffers_batch_impl(sensors: Sequence[FoveatedRTXCamera]) -> None: + Camera._update_buffers_batch_impl(sensors) + if sim_utils.SimulationContext.instance() is None: + return # The base implementation already invoked scalar capture. + for sensor in sensors: + sensor.process_rendered_frame() diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index e8de97a683ff..0024802f9b84 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -26,7 +26,6 @@ from __future__ import annotations -from dataclasses import dataclass from typing import TYPE_CHECKING import torch @@ -109,35 +108,18 @@ def build_highres_coords(cfg: FoveatedCameraCfg, matched_res: int, device: str) _MODAL_CHUNK_ELEMENTS = 2**22 -@dataclass(frozen=True) -class ModalPooler: - """Neighbour table for modal pooling of segmentation outputs, built by :func:`build_pooler` with ``mode="mode"``. - - Pool with :func:`pool_segmentation_buffer`. The table stays on the device it is built on, the sensor's device. - """ - - neighbor_indices: torch.Tensor - """``(k, N_lo)`` int64 input-sample indices of each output's neighbours, ordered by tie-break preference - (nearest first). The value :attr:`num_inputs` marks an excluded neighbour.""" - - num_inputs: int - """Number of input samples ``N_hi``.""" - - def build_pooler( cfg: FoveatedCameraCfg, lowres: SamplingCoords, highres: SamplingCoords | None, device: str, mode: str | None = None, -) -> tuple[KNNPoolingLayer | GridPoolingLayer | ModalPooler | None, int | None]: +) -> tuple[KNNPoolingLayer | GridPoolingLayer | None, int | None]: """Build a retinal pooling layer. Both coord sets must already be on ``device``. - If ``mode`` is None, uses ``cfg.pool_mode`` — the standard pooler for - floating-point outputs. ``mode="mode"`` (the default ``cfg.pool_int_mode``) - builds a :class:`ModalPooler` over the same neighbourhoods for segmentation - outputs; pool those with :func:`pool_segmentation_buffer`. Other modes are - passed to fovi (``"max"``, ``"avg"``, ``"sum"``, ``"gaussian"``). + If ``mode`` is None, uses ``cfg.pool_mode`` — the standard pooler for floating-point outputs. Modes are fovi's + (``"max"``, ``"avg"``, ``"sum"``, ``"gaussian"``). Modal pooling (``"mode"``) needs no pooler of its own: pass the + standard pooler's :func:`segmentation_neighbor_indices` to :func:`pool_segmentation_buffer`. """ if highres is None: return None, None @@ -145,22 +127,20 @@ def build_pooler( from fovi.arch.pooling import build_retinal_pooler mode = mode if mode is not None else cfg.pool_mode - pooler, k = build_retinal_pooler( + if mode == MODAL_POOL_MODE: + raise ValueError("Modal pooling uses the standard pooler's neighbourhoods: see segmentation_neighbor_indices.") + return build_retinal_pooler( highres, lowres, k=cfg.pool_k, - # The modal pooler only reuses the fovi neighbourhoods; "max" needs no Gaussian weights. - mode="max" if mode == MODAL_POOL_MODE else mode, + mode=mode, device=device, sample_cortex=cfg.pool_sample_cortex, gauss_sigma=cfg.pool_gauss_sigma, ) - if mode == MODAL_POOL_MODE: - pooler = ModalPooler(segmentation_neighbor_indices(pooler), len(highres)) - return pooler, k -def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer | ModalPooler) -> torch.Tensor: +def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer) -> torch.Tensor: """Return a pooler's ``(k, N_lo)`` neighbour table in tie-break order. Entries are input-sample indices; ``N_hi`` (the number of input samples) @@ -175,8 +155,6 @@ def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer | M from fovi.arch.knn import KNNPoolingLayer from fovi.arch.pooling import GridPoolingLayer - if isinstance(pooler, ModalPooler): - return pooler.neighbor_indices if isinstance(pooler, KNNPoolingLayer): return pooler.knn_indices_pad_token if not isinstance(pooler, GridPoolingLayer): @@ -227,9 +205,7 @@ def pool_hwc_buffer(pooler: KNNPoolingLayer | GridPoolingLayer, buf: torch.Tenso return y.transpose(1, 2).unsqueeze(2).contiguous() # (B, N_lo, 1, C) -def pool_segmentation_buffer( - pooler: KNNPoolingLayer | GridPoolingLayer | ModalPooler, buf: torch.Tensor -) -> torch.Tensor: +def pool_segmentation_buffer(neighbors: torch.Tensor, buf: torch.Tensor) -> torch.Tensor: """Pool a ``(B, N_hi, 1, C)`` segmentation buffer into ``(B, N_lo, 1, C)`` by majority vote. Each output sample takes the most common full channel vector among its @@ -244,16 +220,15 @@ def pool_segmentation_buffer( vote, and outputs without any valid neighbour are zero, as in fovi. Args: - pooler: A :class:`ModalPooler` from ``build_pooler(..., mode="mode")``, or a fovi KNN or grid pooler - whose neighbourhoods to use. - buf: ``(B, N_hi, 1, C)`` buffer of any dtype, on the pooler's device. + neighbors: ``(k, N_lo)`` neighbour table from :func:`segmentation_neighbor_indices`, on the buffer's device. + buf: ``(B, N_hi, 1, C)`` buffer of any dtype. Returns: ``(B, N_lo, 1, C)`` pooled buffer with the dtype of ``buf``. """ B, N_hi, one, C = buf.shape assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}" - indices = segmentation_neighbor_indices(pooler) # (k, N_lo), N_hi = excluded + indices = neighbors # (k, N_lo), N_hi = excluded k, N_lo = indices.shape values = buf[:, :, 0, :].contiguous() # (B, N_hi, C) # Equality keys, padded with one never-voting sample at index N_hi. diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py index 65ea5ba2bdf6..96b1684f85f0 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py @@ -15,8 +15,8 @@ from isaaclab_tasks.utils import PresetCfg, preset -from isaaclab_fovi import mdp -from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg +from .. import mdp +from ..sensors.foveated_camera_cfg import FoveatedCameraCfg def foveated_camera(camera: CameraCfg, foveated_res: int | None = None) -> FoveatedCameraCfg: diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py index b488d92c4bd8..34560877599a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py @@ -9,7 +9,7 @@ from isaaclab_rl.rsl_rl import RslRlPpoAlgorithmCfg -from isaaclab_fovi.rsl_rl import GazeSupervisedPPOCfg +from ..rsl_rl import GazeSupervisedPPOCfg def gaze_supervised(algorithm: RslRlPpoAlgorithmCfg, **kwargs) -> GazeSupervisedPPOCfg: diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py index f0b5ae0723ec..5b0ec4f842f4 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py @@ -19,15 +19,14 @@ from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ObservationsCfg as CartpoleObservationsCfg from isaaclab_tasks.utils import PresetCfg -from isaaclab_fovi import mdp - +from ... import mdp from ..active_gaze import GazeObservationsCfg, foveated_presets, oracle_observations, select_presets POLE_TIP = (0.0, 0.0, 1.0) """The pole's tip in the pole's frame [m].""" RETINA_RES = 32 -"""Retina samples across. The stock camera's 96 pixels train no better on this task, at several times the cost.""" +"""Retina samples across; the stock camera is 96 pixels across.""" @configclass diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py index 83c4812be710..15fbbe118c7a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py @@ -21,8 +21,7 @@ KukaAllegroReorientEnvCfg, ) -from isaaclab_fovi import mdp - +from ... import mdp from ..active_gaze import GazeObservationsCfg, foveated_presets, oracle_observations, select_presets BASE_CAMERAS = foveated_presets(BaseTiledCameraCfg()) @@ -53,11 +52,6 @@ class BaseImageObsCfg(SingleCameraObservationsCfg.BaseImageObsCfg): oracle = oracle_observations(SceneEntityCfg("object")) -def _foveate(env_cfg): - # Moving the gaze is free; the action penalty applies to the hand and arm only. - env_cfg.rewards.action_l2.func = mdp.motor_action_l2 - - @configclass class KukaAllegroLiftFoviEnvCfg(KukaAllegroLiftEnvCfg): scene: SceneCfg = SceneCfg(num_envs=4096, env_spacing=3) @@ -66,7 +60,8 @@ class KukaAllegroLiftFoviEnvCfg(KukaAllegroLiftEnvCfg): def __post_init__(self): super().__post_init__() - _foveate(self) + # Moving the gaze is free; the action penalty applies to the hand and arm only. + self.rewards.action_l2.func = mdp.motor_action_l2 @configclass @@ -77,4 +72,5 @@ class KukaAllegroReorientFoviEnvCfg(KukaAllegroReorientEnvCfg): def __post_init__(self): super().__post_init__() - _foveate(self) + # Moving the gaze is free; the action penalty applies to the hand and arm only. + self.rewards.action_l2.func = mdp.motor_action_l2 diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index f8779a5509ef..fbd344074807 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -6,6 +6,8 @@ """Gaze geometry and gaze-supervised PPO, without a simulator.""" import math +import subprocess +import sys from types import SimpleNamespace import pytest @@ -24,6 +26,7 @@ from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream +from rsl_rl.algorithms import PPO from rsl_rl.models import MLPModel from rsl_rl.storage import RolloutStorage from tensordict import TensorDict @@ -60,8 +63,9 @@ def test_gaze_step_kernel_matches_the_torch_update(): expected = clamp_gaze(gaze + actions.clamp(-1, 1) * step, limit) expected_velocity = (expected - gaze) / dt - state = torch.cat((gaze, torch.randn(count, 2, generator=generator)), dim=-1) - angles = torch.empty_like(gaze) + # The step starts from the camera's stored angles, not from the state it records. + state = torch.randn(count, 4, generator=generator) + angles = gaze * radius with torch_stream("cpu"): wp.launch( gaze_step_kernel, @@ -77,7 +81,7 @@ def test_gaze_step_kernel_matches_the_torch_update(): ], ) torch.testing.assert_close(state[:, :2], expected, atol=1e-6, rtol=1e-6) - torch.testing.assert_close(state[:, 2:], expected_velocity, atol=1e-3, rtol=1e-5) + torch.testing.assert_close(state[:, 2:], expected_velocity, atol=2e-3, rtol=1e-5) torch.testing.assert_close(angles, expected * radius, atol=1e-5, rtol=1e-6) @@ -132,7 +136,7 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device, rotation_deg): 1, wp.from_torch(positions.to(device), dtype=wp.vec3f), wp.from_torch(mount.to(device), dtype=wp.quatf), - wp.from_torch(torch.cat((gaze, torch.zeros_like(gaze)), -1).to(device), dtype=wp.vec4f), + wp.from_torch((gaze * field_radius).to(device), dtype=wp.vec2f), wp.mat33f(*frame.flatten().tolist()), field_radius, step, @@ -173,7 +177,7 @@ def test_teacher_gaze_fixates_the_target_through_a_rolled_mount(rotation_deg): 0, wp.zeros(count, dtype=wp.vec3f), wp.from_torch(identity, dtype=wp.quatf), - wp.zeros(count, dtype=wp.vec4f), + wp.zeros(count, dtype=wp.vec2f), wp.mat33f(*frame.flatten().tolist()), field_radius, step, @@ -200,14 +204,29 @@ def test_gaze_config_rejects_bounds_that_divide_by_zero(field, value): setattr(cfg, field, value) with pytest.raises(ValueError, match=field): cfg.validate_config() + + +def test_gaze_config_rejects_an_unknown_mount(): + GazeActionCfg(asset_name="camera", mount="tracked").validate_config() with pytest.raises(ValueError, match="mount"): GazeActionCfg(asset_name="camera", mount="head").validate_config() def test_gaze_config_resolves_its_term_lazily(): - class_type = GazeActionCfg(asset_name="camera").class_type - assert isinstance(class_type, str) - assert class_type._resolve() is GazeAction + script = ( + "import sys\n" + "from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg\n" + "class_type = GazeActionCfg(asset_name='camera').class_type\n" + "assert isinstance(class_type, str), type(class_type)\n" + "assert 'isaaclab_fovi.mdp.gaze' not in sys.modules, 'the config imported its runtime term'\n" + "term = class_type._resolve()\n" + "assert 'isaaclab_fovi.mdp.gaze' in sys.modules\n" + "print(term.__module__, term.__qualname__)\n" + ) + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=120, check=False) + assert result.returncode == 0, result.stdout + result.stderr + assert result.stdout.split()[-2:] == ["isaaclab_fovi.mdp.gaze", "GazeAction"] + assert GazeActionCfg(asset_name="camera").class_type._resolve() is GazeAction def test_process_actions_moves_the_gaze_by_the_supplied_actions(): @@ -215,18 +234,14 @@ def test_process_actions_moves_the_gaze_by_the_supplied_actions(): num_envs = 4 angles = ProxyArray(wp.zeros(num_envs, dtype=wp.vec2f, device="cpu")) set_angles = [] - camera = SimpleNamespace( - _gaze_angles=angles, - gaze_angles_buffer=lambda: angles.torch, - set_gaze_angles=lambda value: set_angles.append(value), - ) + camera = SimpleNamespace(gaze_angles=angles, set_gaze_angles=lambda value: set_angles.append(value)) term = object.__new__(GazeAction) term._env = SimpleNamespace(num_envs=num_envs, device="cpu", step_dt=0.5) term.cfg = GazeActionCfg(asset_name="camera", step_size=0.1, gaze_limit=1.0) term.camera = camera term.field_radius_deg = 20.0 term._state = ProxyArray(wp.zeros(num_envs, dtype=wp.vec4f, device="cpu")) - term._gaze, term._velocity = term._state.torch[:, :2], term._state.torch[:, 2:] + term._velocity = term._state.torch[:, 2:] term._step_launch = term._raw = None manager_actions = torch.zeros(num_envs, 5) @@ -247,6 +262,11 @@ def test_process_actions_moves_the_gaze_by_the_supplied_actions(): gaze_state(SimpleNamespace(action_manager=SimpleNamespace(get_term=lambda name: term))), term.state ) + # A gaze set on the camera directly is where the next step starts. + angles.torch.copy_(torch.tensor([[10.0, 0.0]]).repeat(num_envs, 1)) + term.process_actions(torch.zeros(num_envs, 2)) + torch.testing.assert_close(term.gaze, torch.tensor([[0.5, 0.0]]).repeat(num_envs, 1)) + @pytest.mark.parametrize("ids", [None, [3, 0, 7]]) @pytest.mark.parametrize("random_start", [False, True]) @@ -278,10 +298,12 @@ def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): torch.testing.assert_close(state, expected_state, atol=0, rtol=0) -def test_fixed_mount_teacher_rejects_a_moved_mount(): +def test_fixed_mount_teacher_rejects_only_turns_after_capture(): + """A mount turned before the term captured it is the captured mount; a later turn makes it stale.""" term = object.__new__(GazeAction) term.tracked_mount = False - term.camera = SimpleNamespace(mount_moved=True) + term._mount_turns = 2 + term.camera = SimpleNamespace(mount_turns=3) with pytest.raises(RuntimeError, match="mount='tracked'"): GazeAction._teacher_labels(term, targets=None) @@ -295,7 +317,9 @@ def test_gaze_loss_ignores_invalid_labels(): assert torch.isfinite(mean.grad).all() and not mean.grad[1].any() -def _algorithm(oracle_loss_coef: float = 1.0, with_labels: bool = True) -> tuple[GazeSupervisedPPO, TensorDict]: +def _algorithm( + oracle_loss_coef: float = 1.0, with_labels: bool = True, stock: bool = False +) -> tuple[PPO | GazeSupervisedPPO, TensorDict]: torch.manual_seed(0) labels = torch.rand(NUM_ENVS, 3) * 2 - 1 labels[:, 2] = (torch.arange(NUM_ENVS) % 4 != 0).float() @@ -308,10 +332,12 @@ def _algorithm(oracle_loss_coef: float = 1.0, with_labels: bool = True) -> tuple critic = MLPModel(obs, model_groups, "critic", 1, hidden_dims=[32]) storage = RolloutStorage("rl", NUM_ENVS, STEPS, obs, [3], "cpu") settings = dict(num_learning_epochs=4, num_mini_batches=4, learning_rate=3e-3, schedule="fixed", device="cpu") + if stock: + return PPO(actor, critic, storage, **settings), obs return GazeSupervisedPPO(actor, critic, storage, oracle_loss_coef=oracle_loss_coef, **settings), obs -def _train(algorithm: GazeSupervisedPPO, obs: TensorDict, iterations: int) -> dict[str, float]: +def _train(algorithm: PPO, obs: TensorDict, iterations: int) -> dict[str, float]: for _ in range(iterations): for _ in range(STEPS): with torch.inference_mode(): @@ -338,8 +364,22 @@ def distance() -> float: assert distance() < 0.7 * before -def test_zero_coefficient_trains_plain_ppo_without_labels(): - algorithm, obs = _algorithm(oracle_loss_coef=0.0, with_labels=False) - losses = _train(algorithm, obs, 2) +def test_zero_coefficient_update_matches_stock_ppo_without_labels(): + def updated(stock: bool) -> tuple[list[torch.Tensor], list[torch.Tensor], dict[str, float]]: + algorithm, obs = _algorithm(oracle_loss_coef=0.0, with_labels=False, stock=stock) + modules = (algorithm.actor, algorithm.critic) + initial = [p.detach().clone() for module in modules for p in module.parameters()] + torch.manual_seed(1) + losses = _train(algorithm, obs, 1) + return initial, [p.detach().clone() for module in modules for p in module.parameters()], losses + + initial, gaze_params, losses = updated(stock=False) + stock_initial, stock_params, stock_losses = updated(stock=True) assert losses["oracle"] == 0.0 and losses["oracle_valid"] == 0.0 - assert all(torch.isfinite(p).all() for p in algorithm.actor.parameters()) + for name in ("value", "surrogate", "entropy"): + assert losses[name] == pytest.approx(stock_losses[name], rel=1e-6, abs=1e-7) + for start, stock_start in zip(initial, stock_initial, strict=True): + torch.testing.assert_close(start, stock_start, atol=0, rtol=0) + for param, stock_param in zip(gaze_params, stock_params, strict=True): + torch.testing.assert_close(param, stock_param, atol=0, rtol=0) + assert all(not torch.equal(param, start) for param, start in zip(gaze_params, initial, strict=True)) diff --git a/source/isaaclab_fovi/test/test_backend_dispatch.py b/source/isaaclab_fovi/test/test_backend_dispatch.py index 58ec2d23a246..e9a6b1792735 100644 --- a/source/isaaclab_fovi/test/test_backend_dispatch.py +++ b/source/isaaclab_fovi/test/test_backend_dispatch.py @@ -40,7 +40,7 @@ def test_default_renderer_resolves_to_isaac_rtx() -> None: @pytest.mark.parametrize( ("renderer_type", "expected"), - [("isaac_rtx", FoveatedRTXCamera), ("ovrtx", FoveatedRTXCamera), ("newton_warp", FoveatedNewtonCamera)], + [("ovrtx", FoveatedRTXCamera), ("newton_warp", FoveatedNewtonCamera), ("newton_optix", FoveatedNewtonCamera)], ) def test_renderer_selects_its_implementation(renderer_type: str, expected: type) -> None: assert dispatch(CameraSelection(RendererSelection(renderer_type))) is expected diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index b834e11812ae..d6cef8585f8a 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -3,11 +3,13 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Render tests for the foveated camera on the Newton Warp and Isaac RTX renderers. +"""Render tests for the foveated camera on the Newton (Warp and OptiX) and Isaac RTX renderers. The cases live in :mod:`foveated_render_cases`; OVRTX runs them without Kit in ``test_foveated_camera_render_ovrtx``. """ +import os + from isaaclab.test.utils import launch_test_simulation launch_test_simulation(enable_cameras=True) @@ -16,7 +18,7 @@ import pytest # noqa: E402 from isaaclab_fovi.sensors import FoveatedNewtonCamera, FoveatedRTXCamera # noqa: E402 from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg # noqa: E402 -from isaaclab_newton.renderers import NewtonWarpRendererCfg # noqa: E402 +from isaaclab_newton.renderers import NewtonOptixRendererCfg, NewtonWarpRendererCfg # noqa: E402 from isaaclab_physx.physics import PhysxCfg # noqa: E402 from isaaclab_physx.renderers import IsaacRtxRendererCfg # noqa: E402 @@ -25,31 +27,46 @@ # Each backend pairs a physics engine with the renderer under test and the implementation it selects. BACKENDS = { "newton_warp": (NewtonCfg(solver_cfg=MJWarpSolverCfg()), NewtonWarpRendererCfg, FoveatedNewtonCamera), + "newton_optix": (NewtonCfg(solver_cfg=MJWarpSolverCfg()), NewtonOptixRendererCfg, FoveatedNewtonCamera), "isaac_rtx": (PhysxCfg(), IsaacRtxRendererCfg, FoveatedRTXCamera), } +def backend_cfg(name: str): + """The backend, after checking that its renderer can run here. + + OptiX needs the ``optix`` extra and a driver that supports its ABI; without them its cases skip, unless + ``ISAACLAB_TEST_REQUIRE_OPTIX`` is set, as in Isaac Lab's own OptiX rendering tests. + """ + if name == "newton_optix": + if os.environ.get("ISAACLAB_TEST_REQUIRE_OPTIX"): + import optix # noqa: F401 + else: + pytest.importorskip("optix", exc_type=ImportError) + return BACKENDS[name] + + @pytest.mark.parametrize("source", cases.CAMERA_SOURCES) @pytest.mark.parametrize("backend", BACKENDS) def test_foveated_camera_follows_gaze(backend, source): - cases.foveated_camera_follows_gaze(BACKENDS[backend], source) + cases.foveated_camera_follows_gaze(backend_cfg(backend), source) @pytest.mark.parametrize("backend", BACKENDS) def test_gaze_change_reaches_the_next_frame(backend): - cases.gaze_change_reaches_the_next_frame(BACKENDS[backend]) + cases.gaze_change_reaches_the_next_frame(backend_cfg(backend)) @pytest.mark.parametrize("backend", BACKENDS) def test_gaze_stays_relative_to_a_moved_mount(backend): - cases.gaze_stays_relative_to_a_moved_mount(BACKENDS[backend]) + cases.gaze_stays_relative_to_a_moved_mount(backend_cfg(backend)) @pytest.mark.parametrize("backend", BACKENDS) def test_gaze_survives_a_position_only_move(backend): - cases.gaze_survives_a_position_only_move(BACKENDS[backend]) + cases.gaze_survives_a_position_only_move(backend_cfg(backend)) @pytest.mark.parametrize("backend", BACKENDS) def test_foveated_camera_samples_densest_at_the_fixation(backend): - cases.foveated_camera_samples_densest_at_the_fixation(BACKENDS[backend]) + cases.foveated_camera_samples_densest_at_the_fixation(backend_cfg(backend)) diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 57c6554f4ebe..4fc39abc9d92 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -11,9 +11,9 @@ import torch import warp as wp from fovi.sensing.coords import SamplingCoords +from isaaclab_fovi.sensors import foveated_camera as base_camera from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera -from isaaclab_fovi.sensors.pooling import ModalPooler from isaaclab.utils.warp import ProxyArray @@ -112,12 +112,11 @@ def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatc neighbors = torch.stack([4 * runs + j for j in range(4)]) average = torch.nn.AdaptiveAvgPool1d(len(coords)) - def build_pooler(cfg, lowres, high, device, mode=None): - return (ModalPooler(neighbors, len(highres)) if mode == "mode" else average), 4 - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) - monkeypatch.setattr(newton_camera, "build_pooler", build_pooler) + monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (average, 4)) + # The camera reads the modal neighbourhoods from its standard pooler. + monkeypatch.setattr(base_camera, "segmentation_neighbor_indices", lambda pooler: neighbors) monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", lambda self: None) def initialize_renderer(camera): diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 118df24ef34c..48c6e738c196 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -13,7 +13,6 @@ from fovi.arch.pooling import GridPoolingLayer from isaaclab_fovi.sensors import pooling from isaaclab_fovi.sensors.pooling import ( - ModalPooler, build_highres_coords, build_lowres_coords, build_pooler, @@ -125,8 +124,8 @@ def test_disabled_pooling_uses_only_output_grid() -> None: HAND_TABLE = torch.tensor([[0, 3, 5], [1, 4, 5], [2, 5, 5]]) -def hand_pooler(device: str) -> ModalPooler: - return ModalPooler(HAND_TABLE.to(device), num_inputs=5) +def hand_table(device: str) -> torch.Tensor: + return HAND_TABLE.to(device) @pytest.mark.parametrize("device", DEVICES) @@ -138,12 +137,12 @@ def test_modal_pooling_keeps_majority_color_vector(device: str) -> None: [[0, 0, 0, 255], [0, 0, 0, 255], [0, 0, 1, 255], [10, 20, 30, 255], [200, 100, 0, 255]], dtype=torch.uint8 ) rendered = colors[None, :, None, :].to(device) - pooled = pool_segmentation_buffer(hand_pooler(device), rendered) + pooled = pool_segmentation_buffer(hand_table(device), rendered) expected = torch.tensor([[0, 0, 0, 255], [10, 20, 30, 255], [0, 0, 0, 0]], dtype=torch.uint8) assert pooled.dtype == torch.uint8 assert torch.equal(pooled.cpu(), expected[None, :, None, :]) # Swapping the tied neighbours' order flips the winner. - swapped = ModalPooler(HAND_TABLE[[1, 0, 2]].to(device), num_inputs=5) + swapped = HAND_TABLE[[1, 0, 2]].to(device) assert torch.equal(pool_segmentation_buffer(swapped, rendered)[0, 1, 0].cpu(), colors[4]) @@ -154,7 +153,7 @@ def test_modal_pooling_preserves_ids_above_float_precision(device: str, dtype: t big = 2**30 if dtype == torch.int32 else 2**40 ids = torch.tensor([2**24 + 1, 2**24 + 1, 2**24 + 3, big + 7, big + 7], dtype=dtype) batch = torch.stack([ids, ids.flip(0)])[:, :, None, None].to(device) - pooled = pool_segmentation_buffer(hand_pooler(device), batch) + pooled = pool_segmentation_buffer(hand_table(device), batch) expected = torch.tensor([[2**24 + 1, big + 7, 0], [big + 7, 2**24 + 1, 0]], dtype=dtype) assert pooled.dtype == dtype assert torch.equal(pooled[..., 0, 0].cpu(), expected) @@ -164,7 +163,7 @@ def test_modal_pooling_preserves_ids_above_float_precision(device: str, dtype: t def test_modal_pooling_compares_wide_vectors_exactly(device: str) -> None: # Two int64 channels exceed the 8-byte packed key; vectors differing only in the second channel stay distinct. vectors = torch.tensor([[1, 2**40], [1, 2**40 + 1], [1, 2**40 + 1], [5, 6], [7, 8]], dtype=torch.int64) - pooled = pool_segmentation_buffer(hand_pooler(device), vectors[None, :, None, :].to(device)) + pooled = pool_segmentation_buffer(hand_table(device), vectors[None, :, None, :].to(device)) expected = torch.tensor([[1, 2**40 + 1], [5, 6], [0, 0]]) assert torch.equal(pooled[0, :, 0].cpu(), expected) @@ -191,41 +190,47 @@ def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Ten ("isotropic", 3, False), ], ) -def test_modal_pooler_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex: bool) -> None: +def test_modal_pooling_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex: bool) -> None: cfg = SamplingConfig(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex) lowres, matched = build_lowres_coords(cfg, "cpu") highres = build_highres_coords(cfg, matched, "cpu") fovi_max, k = build_pooler(cfg, lowres, highres, "cpu", mode="max") - modal, modal_k = build_pooler(cfg, lowres, highres, "cpu", mode="mode") - assert isinstance(modal, ModalPooler) - assert modal_k == k - table = modal.neighbor_indices + # The camera takes the table from its standard pooler, whatever that pooler's mode. + standard, _ = build_pooler(cfg, lowres, highres, "cpu") + table = segmentation_neighbor_indices(standard) assert table.shape == (k, len(lowres)) + assert torch.equal(segmentation_neighbor_indices(fovi_max), table) # The table holds exactly the samples fovi's max pooler reduces over: a max over the table matches it. values = torch.rand(1, len(highres), 1, 1, generator=torch.Generator().manual_seed(0)) + 1 padded = torch.cat([values[0, :, 0, 0], torch.zeros(1)]) torch.testing.assert_close(padded[table].max(dim=0).values, pool_hwc_buffer(fovi_max, values)[0, :, 0, 0]) - # A raw fovi pooler exposes the same neighbourhoods. - assert torch.equal(segmentation_neighbor_indices(fovi_max), table) # Few labels so neighbourhoods hold repeats and ties; tiny chunks exercise the batched loop. monkeypatch.setattr(pooling, "_MODAL_CHUNK_ELEMENTS", 1) labels = torch.randint(0, 3, (3, len(highres), 1, 2), generator=torch.Generator().manual_seed(1)) labels = labels.to(torch.uint8) - pooled = pool_segmentation_buffer(modal, labels) + pooled = pool_segmentation_buffer(table, labels) assert torch.equal(pooled[:, :, 0], reference_modal_pool(table, labels[:, :, 0])) +def test_modal_mode_builds_no_pooler_of_its_own() -> None: + cfg = SamplingConfig() + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, matched, "cpu") + with pytest.raises(ValueError, match="segmentation_neighbor_indices"): + build_pooler(cfg, lowres, highres, "cpu", mode="mode") + + @pytest.mark.parametrize("device", DEVICES) -def test_modal_pooler_is_built_on_the_sensor_device(device: str) -> None: +def test_modal_neighbourhoods_stay_on_the_sensor_device(device: str) -> None: cfg = SamplingConfig() lowres, matched = build_lowres_coords(cfg, device) highres = build_highres_coords(cfg, matched, device) - modal, _ = build_pooler(cfg, lowres, highres, device, mode="mode") - assert modal.neighbor_indices.device.type == device + table = segmentation_neighbor_indices(build_pooler(cfg, lowres, highres, device)[0]) + assert table.device.type == device labels = torch.randint(0, 3, (1, len(highres), 1, 1), device=device) - assert pool_segmentation_buffer(modal, labels).device.type == device + assert pool_segmentation_buffer(table, labels).device.type == device @pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index f8d6d6f23b1e..b143734ec02e 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -43,21 +43,27 @@ def test_near_clip_comes_from_spawn_or_else_the_camera_prim() -> None: @pytest.mark.parametrize("native_grid", [False, True]) def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> None: """Environments outside the update mask keep their samples, and OVRTX's near-plane offset is added once.""" - texture = torch.arange(2 * 4 * 4, dtype=torch.float32).reshape(2, 4, 4, 1) + height, width = 4, 5 + texture = torch.arange(2 * height * width, dtype=torch.float32).reshape(2, height, width, 1) + if native_grid: + texels = [(py, px) for py in range(height) for px in range(width)] + else: + texels = [(3, 1), (0, 4), (2, 0), (1, 3), (3, 4), (0, 2), (2, 2)] camera = SimpleNamespace( cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")), _native_grid=native_grid, _near_clip=0.25, _texture_output={"distance_to_camera": texture}, - _foveated_output={"distance_to_camera": torch.full((2, 16, 1, 1), -1.0)}, - _extract_py=torch.arange(16) // 4, - _extract_px=torch.arange(16) % 4, + _foveated_output={"distance_to_camera": torch.full((2, len(texels), 1, 1), -1.0)}, + _extract_py=torch.tensor([py for py, _ in texels]), + _extract_px=torch.tensor([px for _, px in texels]), ) updated = wp.array([True, False], dtype=wp.bool, device="cpu") for _ in range(2): FoveatedRTXCamera._extract_foveated_samples(camera, updated) samples = camera._foveated_output["distance_to_camera"] - torch.testing.assert_close(samples[0, :, 0, 0], texture[0].flatten() + 0.25) + expected = torch.tensor([float(texture[0, py, px, 0]) + 0.25 for py, px in texels]) + torch.testing.assert_close(samples[0, :, 0, 0], expected, atol=0, rtol=0) assert bool((samples[1] == -1.0).all()) diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 6e7d3b4aab91..fd6923681dac 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -204,9 +204,9 @@ def test_only_a_turned_mount_is_recorded(monkeypatch) -> None: (lambda camera: camera.set_world_poses_from_view(eyes, torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])), True), ): camera = GazeHarness() - camera.mount_moved = False + camera.mount_turns = 0 move(camera) - assert camera.mount_moved is turned + assert camera.mount_turns == int(turned) def test_a_rejected_mount_move_is_not_recorded(monkeypatch) -> None: @@ -215,10 +215,10 @@ def reject(*args, **kwargs): monkeypatch.setattr(Camera, "set_world_poses", reject) camera = GazeHarness() - camera.mount_moved = False + camera.mount_turns = 0 with pytest.raises(ValueError, match="rejected"): camera.set_world_poses(orientations=torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2)) - assert not camera.mount_moved + assert camera.mount_turns == 0 @pytest.mark.parametrize("shape", [(1, 2), (2, 3), (3, 2)]) diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 592c321c6643..9da0ac50377e 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -59,6 +59,109 @@ def test_every_texel_roundtrips(res: int, rotation: float) -> None: torch.testing.assert_close(rays.norm(dim=-1), torch.ones(len(coords)), atol=1e-6, rtol=0) +def texel_centers(res: int) -> torch.Tensor: + """Native texture UV of each canonical sample, in row-major sample order.""" + axis = (torch.arange(res) + 0.5) / res + row, col = torch.meshgrid(axis, axis, indexing="ij") + return torch.stack((col, row), -1).reshape(-1, 2) + + +def eccentricity_rays(visual: torch.Tensor, fov_deg: float, rotation_deg: float = 0.0) -> torch.Tensor: + """OpenGL rays for visual-chart points, at Fovi's spherical eccentricity: Euclidean visual radius times the half + FoV. Square-shell corners reach sqrt(2) half FoVs, behind the optical hemisphere for wide fields.""" + visual = visual.to(torch.float64) + theta = torch.linalg.vector_norm(visual, dim=-1) * math.radians(fov_deg) / 2 + phi = torch.atan2(visual[..., 1], visual[..., 0]) + math.radians(rotation_deg) + return torch.stack((theta.sin() * phi.cos(), theta.sin() * phi.sin(), -theta.cos()), -1) + + +def ray_visual(rays: torch.Tensor, fov_deg: float, rotation_deg: float = 0.0) -> torch.Tensor: + """Visual-chart point of each ray: its eccentricity over the half FoV along its unrolled azimuth.""" + rays = rays.to(torch.float64) + theta = torch.atan2(torch.linalg.vector_norm(rays[..., :2], dim=-1), -rays[..., 2]) + phi = torch.atan2(rays[..., 1], rays[..., 0]) - math.radians(rotation_deg) + radius = theta / (math.radians(fov_deg) / 2) + return torch.stack((radius * phi.cos(), radius * phi.sin()), -1) + + +def octahedral_texel_rays(size: int) -> torch.Tensor: + """OpenGL rays at octahedral texel centres; the outer triangles fold onto the back hemisphere.""" + axis = (torch.arange(size, dtype=torch.float64) + 0.5) / size * 2 - 1 + y, x = torch.meshgrid(axis, axis, indexing="ij") + forward = 1 - x.abs() - y.abs() + back = forward < 0 + fx = torch.where(back, (1 - y.abs()) * x.sign(), x) + fy = torch.where(back, (1 - x.abs()) * y.sign(), y) + return torch.nn.functional.normalize(torch.stack((fx, fy, -forward), -1), dim=-1) + + +@pytest.mark.parametrize("rotation", [0.0, 37.0]) +def test_inverse_maps_independent_rays_to_their_texels(rotation: float) -> None: + coords = make_coords(64) + half_fov = math.radians(coords.fov) / 2 + # Square shells keep every sample, so every one of Fovi's sample positions must land on its own texel. + rays = eccentricity_rays(coords.cartesian, coords.fov, rotation) + assert (rays[:, 2] > 0).any() + uv, visible = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) + assert visible.all() + torch.testing.assert_close(uv, texel_centers(64), atol=2e-6, rtol=0) + torch.testing.assert_close( + native_grid_directions(coords, image_rotation_deg=rotation), rays.float(), atol=1e-6, rtol=0 + ) + # The optical axis is the texture centre, the nominal rim along each rolled native axis is an edge midpoint, and + # the square's corners lie sqrt(2) half FoVs out along the rolled diagonals. + roll = math.radians(rotation) + + def ray(angle: float, azimuth: float) -> tuple[float, float, float]: + return ( + math.sin(angle) * math.cos(roll + azimuth), + math.sin(angle) * math.sin(roll + azimuth), + -math.cos(angle), + ) + + corner = math.sqrt(2) * half_fov + hand_rays = torch.tensor( + [ + (0.0, 0.0, -1.0), + ray(half_fov, 0.0), + ray(half_fov, math.pi / 2), + ray(half_fov, math.pi), + ray(corner, math.pi / 4), + ray(corner, -math.pi / 4), + ray(corner, -3 * math.pi / 4), + ], + dtype=torch.float64, + ) + uv, visible = native_grid_exit_uv(hand_rays, coords, image_rotation_deg=rotation) + assert visible.all() + expected = torch.tensor([[0.5, 0.5], [0.5, 1.0], [1.0, 0.5], [0.5, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]]) + torch.testing.assert_close(uv, expected, atol=1e-6, rtol=0) + + +@pytest.mark.parametrize("rotation", [0.0, 37.0]) +def test_textures_match_independent_geometry(rotation: float) -> None: + coords = make_coords(64) + size = 256 + direction, inverse = build_native_grid_textures(coords, image_rotation_deg=rotation, exit_size=size) + assert direction.shape == (64, 64, 3) and inverse.shape == (size, size, 2) + expected = eccentricity_rays(coords.cartesian, coords.fov, rotation).float() + torch.testing.assert_close(direction.reshape(-1, 3), expected, atol=1e-6, rtol=0) + # A texel's ray is on the sensor exactly when its visual point lies in the unit square. + texel_rays = octahedral_texel_rays(size) + extent = ray_visual(texel_rays, coords.fov, rotation).abs().amax(-1) + inside, outside = extent < 1 - 1e-6, extent > 1 + 1e-6 + assert (texel_rays[inside][:, 2] > 0).any() and outside.any() + assert (inverse[inside] >= 0).all() and (inverse[outside] == -1).all() + # Each stored UV, mapped back through Fovi's native-to-visual warp, must look along its texel's ray. + native = (inverse[inside].to(torch.float64) * 2 - 1).flip(-1) + torch.testing.assert_close( + eccentricity_rays(coords.native_to_visual(native), coords.fov, rotation), + texel_rays[inside], + atol=1e-5, + rtol=0, + ) + + def test_textures_and_public_modalities() -> None: coords = make_coords() directions, inverse = build_native_grid_textures(coords, image_rotation_deg=0, exit_size=64) From f025ea6fecea8b29af86d6f0fa41ea6726a4ca3e Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 00:26:27 -0800 Subject: [PATCH 36/81] List Newton OptiX among the foveated camera's renderers --- source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst | 2 +- source/isaaclab_fovi/docs/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst index 6cc57f1d1e3f..aa5323306a00 100644 --- a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst +++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst @@ -1,5 +1,5 @@ * Introduced ``isaaclab_fovi`` and the ``fovi`` installation extra, providing a - foveated camera sensor for the Newton, Isaac RTX and OVRTX renderers. + foveated camera sensor for the Newton (Warp and OptiX), Isaac RTX and OVRTX renderers. * Added active-gaze manager terms in :mod:`isaaclab_fovi.mdp`, with a fixed or tracked camera mount, gaze-supervised PPO for RSL-RL in :mod:`isaaclab_fovi.rsl_rl`, and the ``Isaac-Cartpole-Camera-Fovi``, ``Isaac-Lift-KukaAllegro-Camera-Fovi`` and diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index ee030b92357d..9100307cd682 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -20,7 +20,7 @@ RTX renderers use to write lens lookup textures. Add a `FoveatedCameraCfg` to a scene like any other camera. `FoveatedCamera` picks its implementation from the renderer: it supports `newton_warp`, -`isaac_rtx` and `ovrtx`. +`newton_optix` (needs the `optix` extra), `isaac_rtx` and `ovrtx`. ```python import isaaclab.sim as sim_utils From 53c03999d161ed9f6331b591c83fd0a4ab63c2b9 Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 08:23:37 -0800 Subject: [PATCH 37/81] Author the RTX lens at camera construction for both renderers Isaac RTX now prepares and authors the lens lookup on the camera prims during construction, as OVRTX did, and _initialize_impl no longer authors it a second time. Construction clones the configuration first for both renderers. --- .../sensors/foveated_rtx_camera.py | 23 ++++------- source/isaaclab_fovi/test/test_rtx_camera.py | 39 ++++++++++++------- 2 files changed, 33 insertions(+), 29 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 6489e7cf527a..b1674ce59c6d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -80,21 +80,20 @@ def __init__(self, cfg: FoveatedCameraCfg): self._texture_output: dict[str, torch.Tensor] = {} self._foveated_output: dict[str, torch.Tensor] = {} self._pooled_output: dict[str, torch.Tensor] | None = None - if ovrtx: - # The projection sets the texture size on the configuration before the parent allocates for it; the - # caller's configuration stays untouched. - cfg = clone(cfg) - self.cfg = cfg - self._prepare_projection() + # The projection sets the texture size on the configuration before the parent allocates for it; the caller's + # configuration stays untouched. + cfg = clone(cfg) + self.cfg = cfg + self._prepare_projection() super().__init__(cfg) + # The lens belongs to the camera prims from construction: OVRTX snapshots the stage when the renderer starts. for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): # A locked camera may be treated as static, which skips the motion vectors that DLSS reprojection needs; # the gaze moves every foveated camera. lock = prim.GetAttribute("omni:kit:cameraLock") if lock.IsValid() and lock.Get(): lock.Set(False) - if ovrtx: - lens_lut.apply_lens_lut_to_prim(prim, self._dir_tex_path, self._exit_tex_path) + lens_lut.apply_lens_lut_to_prim(prim, self._dir_tex_path, self._exit_tex_path) def __del__(self, *args, **kwargs): """Release the renderer, then the lens textures it reads.""" @@ -234,16 +233,8 @@ def _prepare_projection(self) -> None: self.cfg.width = tw def _initialize_impl(self) -> None: - if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": - self._prepare_projection() tw, th = self._texture_width, self._texture_height - # Author the lens before Camera prepares the renderer's stage. OVRTX - # snapshots a detached stage, so later USD edits would miss its cameras. prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) - for prim in prims: - lens_lut.apply_lens_lut_to_prim( - prim, direction_texture_path=self._dir_tex_path, exit_texture_path=self._exit_tex_path - ) # OVRTX's lookup-table range is measured from the near-clipped ray origin. self._near_clip = self._near_clipping_distance(prims[0]) if prims else 0.0 diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index b143734ec02e..eaf2beadef70 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -12,9 +12,13 @@ import pytest import torch import warp as wp +from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera +from isaaclab_ov.renderers import OVRTXRendererCfg +from isaaclab_physx.renderers import IsaacRtxRendererCfg from isaaclab.sensors.camera.camera import Camera +from isaaclab.sim import PinholeCameraCfg pytestmark = pytest.mark.kitless @@ -77,26 +81,35 @@ def test_releasing_the_camera_removes_its_lens_textures(monkeypatch, tmp_path) - assert not directory.exists() and camera._lut_dir is None -def test_construction_unlocks_spawned_cameras_without_changing_the_config(monkeypatch) -> None: - """The gaze moves every foveated camera, so RTX must not treat a spawned camera as static.""" +@pytest.mark.parametrize("renderer_cfg", [IsaacRtxRendererCfg(), OVRTXRendererCfg()], ids=["isaac_rtx", "ovrtx"]) +def test_construction_authors_the_lens_and_unlocks_cameras_without_changing_the_config(monkeypatch, renderer_cfg): + """Construction authors the lens lookup on every camera prim and unlocks it, since the gaze moves every foveated + camera; the caller's configuration, spawn and texture size included, stays as it was.""" pxr = pytest.importorskip("pxr") stage = pxr.Usd.Stage.CreateInMemory() - prim = pxr.UsdGeom.Camera.Define(stage, "/World/envs/env_0/Camera").GetPrim() - prim.CreateAttribute("omni:kit:cameraLock", pxr.Sdf.ValueTypeNames.Bool).Set(True) + prims = [pxr.UsdGeom.Camera.Define(stage, f"/World/envs/env_{i}/Camera").GetPrim() for i in range(2)] + for prim in prims: + prim.CreateAttribute("omni:kit:cameraLock", pxr.Sdf.ValueTypeNames.Bool).Set(True) def construct(self, cfg): self.cfg = cfg self.stage = stage + def prepare(self): + self.cfg.height = self.cfg.width = 64 + self._dir_tex_path, self._exit_tex_path = "/textures/enter.exr", "/textures/exit.exr" + monkeypatch.setattr(Camera, "__init__", construct) + monkeypatch.setattr(FoveatedRTXCamera, "_prepare_projection", prepare) monkeypatch.setattr(FoveatedRTXCamera, "__del__", lambda self, *args, **kwargs: None) - spawn = SimpleNamespace(lock_camera=True) - cfg = SimpleNamespace( - prim_path="/World/envs/env_.*/Camera", - spawn=spawn, - mask_to_sensor_fov=False, - renderer_cfg=SimpleNamespace(renderer_type="isaac_rtx"), + cfg = FoveatedCameraCfg( + prim_path="/World/envs/env_.*/Camera", spawn=PinholeCameraCfg(), renderer_cfg=renderer_cfg, data_types=["rgb"] ) - FoveatedRTXCamera(cfg) - assert prim.GetAttribute("omni:kit:cameraLock").Get() is False - assert cfg.spawn is spawn and spawn.lock_camera + assert cfg.spawn.lock_camera + camera = FoveatedRTXCamera(cfg) + for prim in prims: + assert prim.GetAttribute("omni:kit:cameraLock").Get() is False + assert prim.GetAttribute("omni:lensdistortion:model").Get() == "lut" + assert prim.GetAttribute("omni:lensdistortion:lut:rayEnterDirectionTexture").Get().path == "/textures/enter.exr" + assert camera.cfg is not cfg and camera.cfg.height == 64 + assert cfg.spawn.lock_camera and (cfg.height, cfg.width) == (1, 1) From 84893507b0928a2b478a0bb1bbdc294c2b1e0d1a Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 09:20:52 -0800 Subject: [PATCH 38/81] Fix the gaze actions' noise with a dedicated Gaussian action head The gaze step clamps each gaze action to [-1, 1], so a learned gaze noise met no resistance from the reward or the surrogate, and PPO's entropy bonus grew it without bound: in the Kuka lift sweep the gaze std reached 20 by iteration 15000 and the sampled gaze random-walked to a 17 degree error while its mean followed the teacher. GazeGaussianDistribution keeps a learned std for the other actions and a fixed one (gaze_std, 0.1) for the last two, stored with the policy. Both fovi tasks use it through gaze_actor(). --- .../changelog.d/isaaclab-fovi.added.rst | 2 +- source/isaaclab_fovi/docs/README.md | 6 +- .../isaaclab_fovi/rsl_rl/__init__.pyi | 4 +- .../isaaclab_fovi/rsl_rl/gaze_distribution.py | 60 +++++++++++++++++++ .../rsl_rl/gaze_distribution_cfg.py | 26 ++++++++ .../rsl_rl/gaze_supervised_ppo.py | 3 +- .../isaaclab_fovi/tasks/agents.py | 13 +++- .../isaaclab_fovi/tasks/cartpole/agents.py | 5 +- .../tasks/kuka_allegro/agents.py | 6 +- source/isaaclab_fovi/test/test_active_gaze.py | 43 ++++++++++++- 10 files changed, 157 insertions(+), 11 deletions(-) create mode 100644 source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution.py create mode 100644 source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution_cfg.py diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst index aa5323306a00..3e7fac996ca0 100644 --- a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst +++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst @@ -1,7 +1,7 @@ * Introduced ``isaaclab_fovi`` and the ``fovi`` installation extra, providing a foveated camera sensor for the Newton (Warp and OptiX), Isaac RTX and OVRTX renderers. * Added active-gaze manager terms in :mod:`isaaclab_fovi.mdp`, with a fixed or tracked camera - mount, gaze-supervised PPO for RSL-RL in :mod:`isaaclab_fovi.rsl_rl`, and the + mount, gaze-supervised PPO for RSL-RL with a fixed gaze action noise in :mod:`isaaclab_fovi.rsl_rl`, and the ``Isaac-Cartpole-Camera-Fovi``, ``Isaac-Lift-KukaAllegro-Camera-Fovi`` and ``Isaac-Reorient-KukaAllegro-Camera-Fovi`` tasks. * Pooled segmentation outputs take each sample's modal label in its native dtype. diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index 9100307cd682..dbcef23fcf71 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -126,12 +126,16 @@ physical camera's image at the current gaze. `isaaclab_fovi.rsl_rl.GazeSupervisedPPOCfg` trains PPO with an added loss that pulls the means of the gaze actions toward the teacher's. The labels come from an `oracle` observation group that the actor and critic never see. +`GazeGaussianDistributionCfg` is the actor's action head for it: the gaze +actions' noise is fixed (`gaze_std`, 0.1 by default) instead of learned. The gaze +step clamps its actions, so a learned gaze noise meets no resistance from the +reward and the entropy bonus grows it until the sampled gaze random-walks. ### Tasks Each task is its stock camera counterpart with the camera foveated at the same mount and optics, two gaze actions, and gaze supervision. The vision model and -the PPO settings are the stock ones. +the PPO settings are the stock ones; the gaze actions' noise is fixed. | Task | Retina | Teacher looks at | | --- | --- | --- | diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi index e437684a352f..b9c685bbee11 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi @@ -3,7 +3,9 @@ # # SPDX-License-Identifier: BSD-3-Clause -__all__ = ["GazeSupervisedPPO", "GazeSupervisedPPOCfg"] +__all__ = ["GazeGaussianDistribution", "GazeGaussianDistributionCfg", "GazeSupervisedPPO", "GazeSupervisedPPOCfg"] +from .gaze_distribution import GazeGaussianDistribution +from .gaze_distribution_cfg import GazeGaussianDistributionCfg from .gaze_supervised_ppo import GazeSupervisedPPO from .gaze_supervised_ppo_cfg import GazeSupervisedPPOCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution.py new file mode 100644 index 000000000000..bbaa59ac3714 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution.py @@ -0,0 +1,60 @@ +# 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 + +"""Gaussian action head whose gaze actions have a fixed standard deviation.""" + +from __future__ import annotations + +import math + +import torch +from rsl_rl.modules.distribution import GaussianDistribution +from torch.distributions import Normal + + +class GazeGaussianDistribution(GaussianDistribution): + """Gaussian action head with a learned standard deviation for every action but the last ``gaze_dims``, the gaze, + whose standard deviation is fixed at ``gaze_std``. + + The gaze step clamps each gaze action to [-1, 1], so beyond that range a wider gaze distribution changes neither + the reward nor PPO's surrogate, and the entropy bonus grows a learned standard deviation without bound; the sampled + gaze then random-walks however well its mean follows the teacher. + + Args: + output_dim: Number of actions, the gaze included. + init_std: Initial standard deviation of the other actions. + std_range: (min, max) clamp of the other actions' standard deviation. + std_type: Parameterization of the other actions' standard deviation: ``"scalar"`` or ``"log"``. + learn_std: Whether the other actions' standard deviation is learned. + gaze_std: Fixed standard deviation of the gaze actions. + gaze_dims: Number of gaze actions, the last ones. + """ + + def __init__( + self, + output_dim: int, + init_std: float = 1.0, + std_range: tuple[float, float] = (1e-6, 1e6), + std_type: str = "scalar", + learn_std: bool = True, + gaze_std: float = 0.1, + gaze_dims: int = 2, + ) -> None: + if not 0 < gaze_dims < output_dim: + raise ValueError(f"gaze_dims must leave other actions, got {gaze_dims} of {output_dim}.") + if not (math.isfinite(gaze_std) and gaze_std > 0): + raise ValueError(f"gaze_std must be positive and finite, got {gaze_std!r}.") + # The learned parameter covers the other actions only. + super().__init__(output_dim - gaze_dims, init_std, std_range, std_type, learn_std) + self.output_dim = output_dim + self.register_buffer("gaze_std", torch.full((gaze_dims,), float(gaze_std))) + + def update(self, mlp_output: torch.Tensor) -> None: + """Update the distribution from the MLP output: learned noise for the other actions, fixed for the gaze.""" + if self.std_type == "scalar": + std = self.std_param.clamp(self.std_range[0], self.std_range[1]) + else: + std = self.log_std_param.clamp(self.log_std_range[0], self.log_std_range[1]).exp() + self._distribution = Normal(mlp_output, torch.cat((std, self.gaze_std))) diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution_cfg.py new file mode 100644 index 000000000000..34ff9c57d261 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution_cfg.py @@ -0,0 +1,26 @@ +# 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 + +"""Configuration of :class:`~isaaclab_fovi.rsl_rl.gaze_distribution.GazeGaussianDistribution`.""" + +from __future__ import annotations + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlMLPModelCfg + + +@configclass +class GazeGaussianDistributionCfg(RslRlMLPModelCfg.GaussianDistributionCfg): + """Gaussian action head whose gaze actions, the last ``gaze_dims``, have a fixed standard deviation. + + ``init_std``, ``std_type`` and ``std_range`` apply to the other actions. + """ + + class_name: str = "isaaclab_fovi.rsl_rl.gaze_distribution:GazeGaussianDistribution" + gaze_std: float = 0.1 + """Fixed standard deviation of the gaze actions. One action moves the gaze by the gaze action's ``step_size``.""" + gaze_dims: int = 2 + """Number of gaze actions, the last ones.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py index 51961079d42e..9edc4ebef4b5 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py @@ -36,7 +36,8 @@ class GazeSupervisedPPO(PPO): The gaze is the last two actions. The teacher's labels are the observation group ``oracle_group``, as :class:`isaaclab_fovi.mdp.gaze_teacher_labels` computes them; they never enter the actor or the critic. Only the - means of the gaze actions are supervised; PPO tunes their standard deviations like any other action's. + means of the gaze actions are supervised; pair it with + :class:`~isaaclab_fovi.rsl_rl.gaze_distribution.GazeGaussianDistribution`, which fixes their noise. Args: oracle_loss_coef: Weight of the gaze loss. Zero trains plain PPO. diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py index 34560877599a..83576a612a0e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/agents.py @@ -7,12 +7,21 @@ from dataclasses import fields -from isaaclab_rl.rsl_rl import RslRlPpoAlgorithmCfg +from isaaclab.utils import replace -from ..rsl_rl import GazeSupervisedPPOCfg +from isaaclab_rl.rsl_rl import RslRlMLPModelCfg, RslRlPpoAlgorithmCfg + +from ..rsl_rl import GazeGaussianDistributionCfg, GazeSupervisedPPOCfg def gaze_supervised(algorithm: RslRlPpoAlgorithmCfg, **kwargs) -> GazeSupervisedPPOCfg: """The PPO settings of ``algorithm`` with gaze supervision by the teacher.""" values = {field.name: getattr(algorithm, field.name) for field in fields(algorithm) if field.name != "class_name"} return GazeSupervisedPPOCfg(**values, **kwargs) + + +def gaze_actor(actor: RslRlMLPModelCfg) -> RslRlMLPModelCfg: + """The stock actor with a fixed, small noise on its gaze actions, the last two.""" + stock = actor.distribution_cfg + head = GazeGaussianDistributionCfg(init_std=stock.init_std, std_type=stock.std_type, std_range=stock.std_range) + return replace(actor, distribution_cfg=head) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py index c9b931ba3a5a..2778bb594755 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py @@ -3,17 +3,18 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""The stock camera PPO with gaze supervision; the actor and critic also see the gaze.""" +"""The stock camera PPO with gaze supervision and a fixed gaze noise; the actor and critic also see the gaze.""" from isaaclab.utils import configclass from isaaclab_tasks.core.cartpole.agents.rsl_rl_ppo_cfg import CartpoleCameraPPORunnerCfg -from ..agents import gaze_supervised +from ..agents import gaze_actor, gaze_supervised @configclass class CartpoleFoviPPORunnerCfg(CartpoleCameraPPORunnerCfg): experiment_name = "cartpole_fovi" obs_groups = {"actor": ["policy", "gaze"], "critic": ["critic", "gaze"]} + actor = gaze_actor(CartpoleCameraPPORunnerCfg().actor) algorithm = gaze_supervised(CartpoleCameraPPORunnerCfg().algorithm) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py index 05b64dc0a4ea..31d28ebf7e7b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py @@ -3,16 +3,17 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""The stock single-camera PPO with gaze supervision; the actor and critic also see the gaze.""" +"""The stock single-camera PPO with gaze supervision and a fixed gaze noise; the actor and critic also see the gaze.""" from isaaclab.utils import configclass from isaaclab_tasks.core.lift.config.kuka_allegro.agents.rsl_rl_ppo_cfg import ( CAMERA_ALGO_CFG, + CNN_POLICY_CFG, KukaAllegroSingleCameraPPORunnerCfg, ) -from ..agents import gaze_supervised +from ..agents import gaze_actor, gaze_supervised @configclass @@ -22,4 +23,5 @@ class KukaAllegroFoviPPORunnerCfg(KukaAllegroSingleCameraPPORunnerCfg): "actor": ["policy", "proprio", "base_image", "gaze"], "critic": ["policy", "proprio", "perception", "gaze"], } + actor = gaze_actor(CNN_POLICY_CFG) algorithm = gaze_supervised(CAMERA_ALGO_CFG) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index fbd344074807..90d6b34996e3 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -24,6 +24,8 @@ teacher_labels_kernel, ) from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg +from isaaclab_fovi.rsl_rl.gaze_distribution import GazeGaussianDistribution +from isaaclab_fovi.rsl_rl.gaze_distribution_cfg import GazeGaussianDistributionCfg from isaaclab_fovi.rsl_rl.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream from rsl_rl.algorithms import PPO @@ -318,7 +320,7 @@ def test_gaze_loss_ignores_invalid_labels(): def _algorithm( - oracle_loss_coef: float = 1.0, with_labels: bool = True, stock: bool = False + oracle_loss_coef: float = 1.0, with_labels: bool = True, stock: bool = False, gaze_head: bool = False ) -> tuple[PPO | GazeSupervisedPPO, TensorDict]: torch.manual_seed(0) labels = torch.rand(NUM_ENVS, 3) * 2 - 1 @@ -328,6 +330,9 @@ def _algorithm( obs = TensorDict(groups, batch_size=[NUM_ENVS]) model_groups = {"actor": ["policy"], "critic": ["policy"]} distribution = {"class_name": "GaussianDistribution", "init_std": 1.0} + if gaze_head: + head = GazeGaussianDistributionCfg(init_std=1.0, gaze_std=0.1) + distribution = {"class_name": head.class_name, "init_std": 1.0, "gaze_std": head.gaze_std} actor = MLPModel(obs, model_groups, "actor", 3, hidden_dims=[32], distribution_cfg=distribution) critic = MLPModel(obs, model_groups, "critic", 1, hidden_dims=[32]) storage = RolloutStorage("rl", NUM_ENVS, STEPS, obs, [3], "cpu") @@ -383,3 +388,39 @@ def updated(stock: bool) -> tuple[list[torch.Tensor], list[torch.Tensor], dict[s for param, stock_param in zip(gaze_params, stock_params, strict=True): torch.testing.assert_close(param, stock_param, atol=0, rtol=0) assert all(not torch.equal(param, start) for param, start in zip(gaze_params, initial, strict=True)) + + +def test_gaze_head_keeps_the_gaze_noise_fixed_while_ppo_learns_the_rest(): + """The entropy bonus and the surrogate move the other actions' noise, never the gaze's.""" + algorithm, obs = _algorithm(gaze_head=True) + algorithm.entropy_coef = 0.5 + head = algorithm.actor.distribution + assert isinstance(head, GazeGaussianDistribution) + assert head.std_param.shape == (1,) + _train(algorithm, obs, iterations=3) + with torch.no_grad(): + head.update(torch.zeros(1, 3)) + std = head.std[0] + torch.testing.assert_close(std[1:], torch.full((2,), 0.1)) + assert abs(float(std[0]) - 1.0) > 1e-3 + # The gaze noise is part of the saved policy, so a checkpoint restores it. + assert torch.equal(head.state_dict()["gaze_std"], torch.full((2,), 0.1)) + + +@pytest.mark.parametrize("std_type", ["scalar", "log"]) +def test_gaze_head_samples_with_the_fixed_gaze_noise(std_type): + head = GazeGaussianDistribution(5, init_std=2.0, std_type=std_type, gaze_std=0.05) + assert head.input_dim == 5 + head.update(torch.zeros(4096, 5)) + torch.testing.assert_close(head.std[0], torch.tensor([2.0, 2.0, 2.0, 0.05, 0.05])) + samples = head.sample() + assert samples.shape == (4096, 5) + torch.testing.assert_close(samples.std(dim=0)[3:], torch.full((2,), 0.05), atol=5e-3, rtol=0) + + +@pytest.mark.parametrize( + "kwargs", [dict(gaze_std=0.0), dict(gaze_std=float("inf")), dict(gaze_dims=5), dict(gaze_dims=0)] +) +def test_gaze_head_rejects_invalid_settings(kwargs): + with pytest.raises(ValueError, match="gaze"): + GazeGaussianDistribution(5, **kwargs) From 10b2790fd0ec8f7b30330851104ae4ddab309325 Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 11:31:15 -0800 Subject: [PATCH 39/81] Keep bundled packages' entry points in the aggregate wheel gen_pyproject.py wrote only the isaaclab console script, so a wheel install lost the isaaclab.tasks entry point of isaaclab_fovi and listed none of its tasks. The bundled source/isaaclab* packages' [project.entry-points] are now carried into the wheel metadata, failing on conflicting names. Checked by building the wheel, installing isaaclab[fovi] from it into a fresh environment and running isaaclab list_envs --keyword Fovi. --- .../wheel-bundled-entry-points.fixed.rst | 2 ++ .../test/cli/test_wheel_builder_metadata.py | 11 +++++++ tools/wheel_builder/gen_pyproject.py | 32 ++++++++++++++++++- 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 source/isaaclab/changelog.d/wheel-bundled-entry-points.fixed.rst diff --git a/source/isaaclab/changelog.d/wheel-bundled-entry-points.fixed.rst b/source/isaaclab/changelog.d/wheel-bundled-entry-points.fixed.rst new file mode 100644 index 000000000000..329d7bca2384 --- /dev/null +++ b/source/isaaclab/changelog.d/wheel-bundled-entry-points.fixed.rst @@ -0,0 +1,2 @@ +* Kept the entry points of bundled packages in the aggregate ``isaaclab`` wheel, such as the + ``isaaclab.tasks`` entry points that register their tasks with ``isaaclab list_envs`` and ``isaaclab train``. diff --git a/source/isaaclab/test/cli/test_wheel_builder_metadata.py b/source/isaaclab/test/cli/test_wheel_builder_metadata.py index 19f948de5f72..332fb87d1059 100644 --- a/source/isaaclab/test/cli/test_wheel_builder_metadata.py +++ b/source/isaaclab/test/cli/test_wheel_builder_metadata.py @@ -95,6 +95,17 @@ def test_wheel_console_delegates_to_the_full_isaaclab_cli(source_checkout_root: cli.assert_called_once_with() +def test_wheel_keeps_the_entry_points_of_bundled_packages(source_checkout_root: Path, generated_wheel_project: dict): + """Bundled sub-packages keep their entry points, e.g. the ``isaaclab.tasks`` ones that register their tasks.""" + expected: dict[str, dict[str, str]] = {} + for package_pyproject in sorted((source_checkout_root / "source").glob("isaaclab*/pyproject.toml")): + with package_pyproject.open("rb") as f: + for group, entries in tomllib.load(f).get("project", {}).get("entry-points", {}).items(): + expected.setdefault(group, {}).update(entries) + assert expected, "no bundled package declares an entry point" + assert generated_wheel_project.get("entry-points") == expected + + def test_wheel_console_uses_compatibility_dispatcher(generated_wheel_project: dict): """The generated console script must preserve legacy installed-wheel options.""" assert generated_wheel_project["scripts"]["isaaclab"] == "isaaclab.__main__:main" diff --git a/tools/wheel_builder/gen_pyproject.py b/tools/wheel_builder/gen_pyproject.py index 6a7d9666752e..26b70d7a02fa 100644 --- a/tools/wheel_builder/gen_pyproject.py +++ b/tools/wheel_builder/gen_pyproject.py @@ -8,11 +8,14 @@ The published wheel bundles every ``isaaclab*`` sub-package as a top-level module, so the workspace self-references in the root ``[project.dependencies]`` and ``[project.optional-dependencies]`` are dropped here; only third-party -requirements end up in the wheel metadata. +requirements end up in the wheel metadata. The bundled sub-packages' entry points, +such as the ``isaaclab.tasks`` entry points that register their tasks, are carried +into the wheel's metadata. """ import re import sys +from pathlib import Path import tomllib @@ -116,6 +119,28 @@ def _dedup(requirements: list[str]) -> list[str]: ] ) + +def _bundled_entry_points(source_dir: Path) -> dict[str, dict[str, str]]: + """Collect the ``[project.entry-points]`` of the ``isaaclab*`` packages that the wheel bundles. + + Raises: + SystemExit: Two packages declare the same entry point name in a group with different targets. + """ + groups: dict[str, dict[str, str]] = {} + for package_pyproject in sorted(source_dir.glob("isaaclab*/pyproject.toml")): + with package_pyproject.open("rb") as f: + package_project = tomllib.load(f).get("project", {}) + for group, entries in package_project.get("entry-points", {}).items(): + merged = groups.setdefault(group, {}) + for name, target in entries.items(): + if merged.get(name, target) != target: + sys.exit(f"Entry point {name!r} in group {group!r} has conflicting targets in {package_pyproject}.") + merged[name] = target + return groups + + +entry_points = _bundled_entry_points(Path(root_pyproject_path).resolve().parent / "source") + # Write pyproject.toml lines = [] lines.append("[build-system]") @@ -147,6 +172,11 @@ def _dedup(requirements: list[str]) -> list[str]: lines.append("[project.scripts]") lines.append('isaaclab = "isaaclab.__main__:main"') lines.append("") +for group, entries in entry_points.items(): + lines.append(f'[project.entry-points."{group}"]') + for name, target in entries.items(): + lines.append(f'"{name}" = "{target}"') + lines.append("") lines.append("[project.optional-dependencies]") for name, dep_list in opt_deps.items(): formatted = ", ".join(f'"{d}"' for d in dep_list) From 400ed99f0f56700fa6639fbfb700e6e0451bc02b Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 11:58:26 -0800 Subject: [PATCH 40/81] Address the fourth review round on the foveated camera and active gaze Cameras: Newton and OVRTX reject update_latest_camera_pose=False, under which the renderer would never see the gaze; the mount record starts at the current ungazed pose; Isaac RTX reads its pose as the mount until a gaze is written; each OVRTX camera adds its own near clip; sample-set exit LUTs mark out-of-field rays invalid instead of sending them to the fovea; Newton sample sets publish their own buffers so a partial update changes only the updated rows; Newton reuses the gaze geometry's rendered rays. Gaze: the teacher's labels, logs and launch live in gaze_teacher_labels; GazeAction exposes teacher_mounts(); entity_point, direction_to_angles and clamp_gaze are gone; the gaze width is fixed at two actions (GAZE_ACTIONS) for the head and the loss; slice resets build only the selected indices. Small: pool_mode lists its modes, render_foveated.py takes --cmf_a_deg, lens_lut drops its banners, an explicit foveated_res is kept. Tests: the repository's device selection replaces hard-coded CUDA devices; new tests for the mount record, the pose-update guard, sample-set publication, per-camera near clips and the invalid exit texels. --- source/isaaclab_fovi/docs/README.md | 2 +- .../isaaclab_fovi/examples/render_foveated.py | 2 +- .../isaaclab_fovi/mdp/__init__.pyi | 6 - .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 149 +++++++----------- .../isaaclab_fovi/rsl_rl/gaze_distribution.py | 19 +-- .../rsl_rl/gaze_distribution_cfg.py | 4 +- .../rsl_rl/gaze_supervised_ppo.py | 4 +- .../isaaclab_fovi/sensors/foveated_camera.py | 42 +++-- .../sensors/foveated_camera_cfg.py | 4 +- .../sensors/foveated_newton_camera.py | 38 +++-- .../sensors/foveated_rtx_camera.py | 8 +- .../isaaclab_fovi/sensors/lens_lut.py | 26 +-- .../isaaclab_fovi/tasks/active_gaze.py | 4 +- .../test/foveated_render_cases.py | 8 +- source/isaaclab_fovi/test/test_active_gaze.py | 43 ++--- .../isaaclab_fovi/test/test_gaze_kernels.py | 4 +- source/isaaclab_fovi/test/test_lens_lut.py | 37 +++++ source/isaaclab_fovi/test/test_native_grid.py | 8 +- .../isaaclab_fovi/test/test_newton_buffers.py | 91 +++++++++-- source/isaaclab_fovi/test/test_pooling.py | 10 +- source/isaaclab_fovi/test/test_rtx_camera.py | 24 +-- .../test/test_spherical_geometry.py | 67 ++++++-- 22 files changed, 355 insertions(+), 245 deletions(-) create mode 100644 source/isaaclab_fovi/test/test_lens_lut.py diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index dbcef23fcf71..440738a1ff0b 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -170,4 +170,4 @@ uv run python source/isaaclab_fovi/examples/render_foveated.py --backend newton ``` Add `--backend rtx` for the RTX renderer, `--lens fisheye` for an ideal -equidistant fisheye, or `--cmf-a-deg 1000` for the non-foveated baseline. +equidistant fisheye, or `--cmf_a_deg 1000` for the non-foveated baseline. diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index 2568be81081a..10bf864fe061 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -26,7 +26,7 @@ parser.add_argument("--lens", choices=("pinhole", "fisheye"), default="pinhole", help="The camera the retina uses.") parser.add_argument("--pool", action="store_true", help="Pool a denser photoreceptor grid to the output grid.") parser.add_argument("--resolution", type=int, default=64, help="Side length of the output grid.") -parser.add_argument("--cmf-a-deg", type=float, default=None, help="CMF constant [deg]; a large value is non-foveated.") +parser.add_argument("--cmf_a_deg", type=float, default=None, help="CMF constant [deg]; a large value is non-foveated.") parser.add_argument("--steps", type=int, default=8) parser.add_argument("--output", type=Path, help="Save the RGB frames and warm frame timings.") AppLauncher.add_app_launcher_args(parser) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi index 56478d9adeb8..b0a95ebf64b3 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -7,9 +7,6 @@ __all__ = [ "GazeAction", "GazeActionCfg", "angles_to_direction", - "clamp_gaze", - "direction_to_angles", - "entity_point", "gaze_state", "gaze_teacher_labels", "motor_action_l2", @@ -19,9 +16,6 @@ __all__ = [ from .gaze import ( GazeAction, angles_to_direction, - clamp_gaze, - direction_to_angles, - entity_point, gaze_state, gaze_teacher_labels, motor_action_l2, diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 25530749bc90..062a009b18bd 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -20,7 +20,6 @@ import warp as wp from isaaclab.managers import ActionTerm, ManagerTermBase, ObservationTermCfg, SceneEntityCfg -from isaaclab.utils.math import quat_apply from isaaclab.utils.warp import ProxyArray from ..sensors.gaze_kernels import ( @@ -185,17 +184,6 @@ def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) -def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: - """Gaze angles [deg] of camera-frame directions, shape (..., 3) to (..., 2).""" - x, y, z = direction.unbind(-1) - return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg() - - -def clamp_gaze(gaze: torch.Tensor, limit: float) -> torch.Tensor: - """Scale gazes back onto the circle of radius ``limit`` when they leave it, shape (..., 2).""" - return gaze * (limit / gaze.norm(dim=-1, keepdim=True).clamp_min(limit)) - - def random_gaze(count: int, limit: float, device: torch.device | str | None = None) -> torch.Tensor: """Gazes drawn uniformly over the disc of radius ``limit``, shape (count, 2).""" radius = limit * torch.rand(count, device=device).sqrt() @@ -236,8 +224,7 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): self.tracked_mount = cfg.mount == "tracked" if self.tracked_mount and not camera.turns_pose_by_gaze: raise ValueError( - "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX," - " with update_latest_camera_pose." + "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX." ) if not self.tracked_mount and camera.cfg.prim_path.rpartition("/")[0] not in ( "{ENV_REGEX_NS}", @@ -250,10 +237,12 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): ) # The camera's own geometry, so the teacher and the sensor mask share one projection. self.camera_model = camera.camera_model - self._camera = camera.projection_params - self._frame = camera.image_frame + self.projection_params = camera.projection_params + """The physical camera as a Warp struct, for the teacher kernel.""" + self.image_frame = camera.image_frame + """Rotation from the upright gaze frame to the physical camera's frame (ROS convention).""" self._frame_torch = torch.tensor( - [[self._frame[row][col] for col in range(3)] for row in range(3)], device=self.device + [[self.image_frame[row][col] for col in range(3)] for row in range(3)], device=self.device ) self.field_radius_deg = camera.sampling_coords.fov / 2 """Half the retina's field of view [deg].""" @@ -269,11 +258,6 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): """Gaze and its velocity as of the last step or reset, the gaze observation.""" self._velocity = self._state.torch[:, 2:] self._step_launch: tuple[tuple, wp.Launch] | None = None - self._labels = ProxyArray(wp.zeros((self.num_envs, 3), dtype=wp.float32, device=self.device)) - self._log = ProxyArray(wp.zeros(2, dtype=wp.float32, device=self.device)) - """Mean gaze error to valid teacher targets [deg] and the fraction of valid targets.""" - self._no_orientations = wp.zeros(1, dtype=wp.quatf, device=self.device) - self._labels_launch = None # Each reset copies its environments, and their start gazes if random, into these and replays one launch. self._reset_ids = ProxyArray(wp.zeros(self.num_envs, dtype=wp.int32, device=self.device)) self._reset_start = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec2f, device=self.device)) @@ -349,7 +333,7 @@ def reset(self, env_ids=None): count = self.num_envs if indexed: if isinstance(env_ids, slice): - env_ids = torch.arange(self.num_envs, device=self.device)[env_ids] + env_ids = torch.arange(*env_ids.indices(self.num_envs), device=self.device) count = len(env_ids) if count == 0: return @@ -376,62 +360,23 @@ def reset(self, env_ids=None): def visible(self, direction: torch.Tensor) -> torch.Tensor: """Whether directions in the upright gaze frame fall inside the physical camera's image.""" - return project_directions(direction @ self._frame_torch.T, self._camera)[1] - - def _teacher_labels( - self, targets: wp.array, orientations: wp.array | None = None, offset: wp.vec3f | None = None - ) -> tuple[torch.Tensor, torch.Tensor]: - """Teacher labels toward a point fixed to each target, in one launch. + return project_directions(direction @ self._frame_torch.T, self.projection_params)[1] - Args: - targets: Target positions in the world frame, one per environment. - orientations: Target orientations (x, y, z, w), to place ``offset`` in each target's frame. - offset: The point in each target's frame [m]. - - Returns: - The labels (action x, action y, valid), shape (num_envs, 3); and the mean gaze error to valid targets - [deg] with the fraction of valid targets, shape (2,). Both are buffers the next call overwrites. + def teacher_mounts(self) -> ProxyArray: + """Each camera's mount (x, y, z, w), ROS convention, that the teacher aims from: the current one when + tracked, else the one captured when the term was created. Raises: RuntimeError: The camera's mount turned while the gaze assumes a fixed mount. """ if self.tracked_mount: - mounts = self.camera.mount_quat_w_ros - elif self.camera.mount_turns != self._mount_turns: + return self.camera.mount_quat_w_ros + if self.camera.mount_turns != self._mount_turns: raise RuntimeError( "The gaze camera's mount turned, so the fixed-mount teacher would aim from its first orientation;" " use GazeActionCfg.mount='tracked'." ) - else: - mounts = self._fixed_mount - positions = self.camera.data.pos_w.warp - sources = (targets, orientations, positions, offset, mounts) - if self._labels_launch is None or any(a is not b for a, b in zip(self._labels_launch[0], sources)): - block = teacher_block_dim(self.device) - launch = record_launch( - teacher_labels_kernel, - (1, block), - [ - targets, - self._no_orientations if orientations is None else orientations, - wp.vec3f(0.0, 0.0, 0.0) if offset is None else offset, - int(orientations is not None), - positions, - mounts, - self.camera.gaze_angles, - self._frame, - self.field_radius_deg, - self.cfg.step_size, - self.cfg.gaze_limit, - self._camera, - ], - [self._labels, self._log], - self.device, - block_dim=block, - ) - self._labels_launch = (sources, launch) - self._labels_launch[1].launch(warp_stream(self.device)) - return self._labels.torch, self._log.torch + return self._fixed_mount def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: @@ -440,27 +385,6 @@ def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: return term.state -def entity_point( - env: ManagerBasedEnv, - asset_cfg: SceneEntityCfg, - offset: tuple[float, float, float] | torch.Tensor = (0.0, 0.0, 0.0), -) -> torch.Tensor: - """World position of a point fixed to an asset's root, or to its first selected body, shape (num_envs, 3). - - Args: - asset_cfg: The asset, and optionally one body by ``body_names``. - offset: The point in the root's or the body's frame [m]. - """ - data = env.scene[asset_cfg.name].data - if asset_cfg.body_names is None: - position, orientation = data.root_pos_w.torch, data.root_quat_w.torch - else: - body = asset_cfg.body_ids[0] - position, orientation = data.body_pos_w.torch[:, body], data.body_quat_w.torch[:, body] - offset = torch.as_tensor(offset, dtype=position.dtype, device=position.device) - return position + quat_apply(orientation, offset.expand_as(position)) - - def _log_teacher(env: ManagerBasedEnv, values: torch.Tensor) -> None: """Log the mean gaze error to valid targets and the fraction of valid targets.""" # Loggers keep each step's entries, so they get a copy rather than the buffer the next step overwrites. @@ -473,6 +397,9 @@ def _log_teacher(env: ManagerBasedEnv, values: torch.Tensor) -> None: class gaze_teacher_labels(ManagerTermBase): """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3). + A training label, never a policy input. One launch labels every environment and logs the mean gaze error to valid + targets and the fraction of valid targets. + Args: target_cfg: The asset, and optionally one body by ``body_names``. offset: The point in the root's or the body's frame [m]. @@ -481,9 +408,14 @@ class gaze_teacher_labels(ManagerTermBase): def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv): super().__init__(cfg, env) + self._gaze: GazeAction = env.action_manager.get_term(cfg.params.get("action_name", "gaze")) + self._labels = ProxyArray(wp.zeros((env.num_envs, 3), dtype=wp.float32, device=env.device)) + self._log = ProxyArray(wp.zeros(2, dtype=wp.float32, device=env.device)) + """Mean gaze error to valid targets [deg] and the fraction of valid targets.""" self._offset: tuple[tuple[float, ...], wp.vec3f] | None = None self._sources = None self._targets = self._orientations = None + self._launch: tuple[tuple, wp.Launch] | None = None def __call__( self, @@ -506,14 +438,41 @@ def __call__( body = target_cfg.body_ids[0] self._targets = wp.from_torch(positions.torch[:, body], dtype=wp.vec3f) self._orientations = wp.from_torch(orientations.torch[:, body], dtype=wp.quatf) - # The recorded teacher launch is kept while the point stays the same object. point = tuple(float(value) for value in offset) if self._offset is None or self._offset[0] != point: self._offset = (point, wp.vec3f(*point)) - term: GazeAction = env.action_manager.get_term(action_name) - labels, values = term._teacher_labels(self._targets, self._orientations, self._offset[1]) - _log_teacher(env, values) - return labels + gaze = self._gaze + mounts = gaze.teacher_mounts() + camera_positions = gaze.camera.data.pos_w.warp + # The launch is recorded once and recorded again only when one of its arrays or the point changes. + sources = (self._targets, self._orientations, camera_positions, mounts, self._offset[1]) + if self._launch is None or any(a is not b for a, b in zip(self._launch[0], sources)): + block = teacher_block_dim(env.device) + launch = record_launch( + teacher_labels_kernel, + (1, block), + [ + self._targets, + self._orientations, + self._offset[1], + 1, + camera_positions, + mounts, + gaze.camera.gaze_angles, + gaze.image_frame, + gaze.field_radius_deg, + gaze.cfg.step_size, + gaze.cfg.gaze_limit, + gaze.projection_params, + ], + [self._labels, self._log], + env.device, + block_dim=block, + ) + self._launch = (sources, launch) + self._launch[1].launch(warp_stream(env.device)) + _log_teacher(env, self._log.torch) + return self._labels.torch def motor_action_l2(env: ManagerBasedRLEnv, gaze_action_name: str = "gaze") -> torch.Tensor: diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution.py index bbaa59ac3714..9829707c282f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution.py +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution.py @@ -13,23 +13,25 @@ from rsl_rl.modules.distribution import GaussianDistribution from torch.distributions import Normal +GAZE_ACTIONS = 2 +"""The gaze actions (tilt, pan) are the policy's last two actions.""" + class GazeGaussianDistribution(GaussianDistribution): - """Gaussian action head with a learned standard deviation for every action but the last ``gaze_dims``, the gaze, - whose standard deviation is fixed at ``gaze_std``. + """Gaussian action head with a learned standard deviation for every action but the gaze, the last two, whose + standard deviation is fixed at ``gaze_std``. The gaze step clamps each gaze action to [-1, 1], so beyond that range a wider gaze distribution changes neither the reward nor PPO's surrogate, and the entropy bonus grows a learned standard deviation without bound; the sampled gaze then random-walks however well its mean follows the teacher. Args: - output_dim: Number of actions, the gaze included. + output_dim: Number of actions, the two gaze actions included. init_std: Initial standard deviation of the other actions. std_range: (min, max) clamp of the other actions' standard deviation. std_type: Parameterization of the other actions' standard deviation: ``"scalar"`` or ``"log"``. learn_std: Whether the other actions' standard deviation is learned. gaze_std: Fixed standard deviation of the gaze actions. - gaze_dims: Number of gaze actions, the last ones. """ def __init__( @@ -40,16 +42,15 @@ def __init__( std_type: str = "scalar", learn_std: bool = True, gaze_std: float = 0.1, - gaze_dims: int = 2, ) -> None: - if not 0 < gaze_dims < output_dim: - raise ValueError(f"gaze_dims must leave other actions, got {gaze_dims} of {output_dim}.") + if output_dim <= GAZE_ACTIONS: + raise ValueError(f"The gaze head needs actions besides the {GAZE_ACTIONS} gaze actions, got {output_dim}.") if not (math.isfinite(gaze_std) and gaze_std > 0): raise ValueError(f"gaze_std must be positive and finite, got {gaze_std!r}.") # The learned parameter covers the other actions only. - super().__init__(output_dim - gaze_dims, init_std, std_range, std_type, learn_std) + super().__init__(output_dim - GAZE_ACTIONS, init_std, std_range, std_type, learn_std) self.output_dim = output_dim - self.register_buffer("gaze_std", torch.full((gaze_dims,), float(gaze_std))) + self.register_buffer("gaze_std", torch.full((GAZE_ACTIONS,), float(gaze_std))) def update(self, mlp_output: torch.Tensor) -> None: """Update the distribution from the MLP output: learned noise for the other actions, fixed for the gaze.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution_cfg.py index 34ff9c57d261..54a65a3c194f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_distribution_cfg.py @@ -14,7 +14,7 @@ @configclass class GazeGaussianDistributionCfg(RslRlMLPModelCfg.GaussianDistributionCfg): - """Gaussian action head whose gaze actions, the last ``gaze_dims``, have a fixed standard deviation. + """Gaussian action head whose gaze actions, the last two, have a fixed standard deviation. ``init_std``, ``std_type`` and ``std_range`` apply to the other actions. """ @@ -22,5 +22,3 @@ class GazeGaussianDistributionCfg(RslRlMLPModelCfg.GaussianDistributionCfg): class_name: str = "isaaclab_fovi.rsl_rl.gaze_distribution:GazeGaussianDistribution" gaze_std: float = 0.1 """Fixed standard deviation of the gaze actions. One action moves the gaze by the gaze action's ``step_size``.""" - gaze_dims: int = 2 - """Number of gaze actions, the last ones.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py index 9edc4ebef4b5..45572c45d431 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py +++ b/source/isaaclab_fovi/isaaclab_fovi/rsl_rl/gaze_supervised_ppo.py @@ -17,6 +17,8 @@ from rsl_rl.algorithms import PPO from torch import nn +from .gaze_distribution import GAZE_ACTIONS + def gaze_loss(mean: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: """Mean distance between the policy's gaze-action means and the teacher's, over valid labels. @@ -91,7 +93,7 @@ def update(self) -> dict[str, float]: loss = surrogate + self.value_loss_coef * value_loss - self.entropy_coef * entropy if self.oracle_loss_coef > 0: labels = batch.observations[self.oracle_group].float() - oracle = gaze_loss(self.actor.output_mean[:, -2:].float(), labels) + oracle = gaze_loss(self.actor.output_mean[:, -GAZE_ACTIONS:].float(), labels) valid = (labels[:, 2] > 0.5).float().mean() loss = loss + self.oracle_loss_coef * oracle else: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 3cae499852df..2c8da353f6a3 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -98,7 +98,19 @@ def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): ) def __init__(self, cfg: FoveatedCameraCfg): + """Create the camera. + + Raises: + ValueError: A Newton or OVRTX camera without ``update_latest_camera_pose``, whose renderer would never see + the gaze. + """ + if self._gaze_pose_reads_angles and not cfg.update_latest_camera_pose: + raise ValueError( + "Newton and OVRTX turn the rendered pose by the gaze in each pose update; set" + " update_latest_camera_pose=True so the renderer sees the gaze." + ) # The parent's initialisation updates poses before the gaze exists. + self._gaze_written = False self._gaze_angles: ProxyArray | None = None self._gaze_rotation: ProxyArray | None = None self._visibility = None @@ -154,9 +166,9 @@ def image_frame(self) -> wp.mat33f: @property def turns_pose_by_gaze(self) -> bool: - """Whether each pose update turns the rendered pose by the stored gaze (Newton and OVRTX with - ``update_latest_camera_pose``). A writer of :attr:`gaze_angles` then needs no other launch.""" - return self._gaze_pose_reads_angles and self.cfg.update_latest_camera_pose + """Whether each pose update turns the rendered pose by the stored gaze (Newton and OVRTX). A writer of + :attr:`gaze_angles` then needs no other launch.""" + return self._gaze_pose_reads_angles @property def gaze_angles(self) -> ProxyArray: @@ -216,6 +228,7 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: gaze.device, ) self._set_gaze_launch.launch(warp_stream(gaze.device)) + self._gaze_written = True def ungazed_quat_w_ros(self) -> torch.Tensor: """World orientation (x, y, z, w) of the physical camera now, before the gaze turns it, ROS convention, shape @@ -225,14 +238,19 @@ def ungazed_quat_w_ros(self) -> torch.Tensor: RuntimeError: A gaze is set on a camera that writes it into its prims (Isaac RTX), so the current pose includes it. """ - if self._gaze_angles is None: - orientation = self._data.quat_w_world - orientation = orientation.torch if hasattr(orientation, "torch") else orientation - opengl = convert_camera_frame_quaternion(orientation.float(), origin="world", target="opengl") - return convert_camera_frame_quaternion(opengl, origin="opengl", target="ros") - if self._gaze_pose_reads_angles: + if self._gaze_pose_reads_angles and self._gaze_angles is not None: + # The record starts at the pose before any gaze and follows each pose update. return self._mount_quat_ros.torch.clone() - raise RuntimeError("The camera's prims already hold a gaze; read its mount before setting one.") + if self._gaze_written and not self._gaze_pose_reads_angles: + raise RuntimeError("The camera's prims already hold a gaze; read its mount before setting one.") + return self._pose_quat_w_ros() + + def _pose_quat_w_ros(self) -> torch.Tensor: + """The camera's current world orientation in the ROS convention, shape (num_envs, 4).""" + orientation = self._data.quat_w_world + orientation = orientation.torch if hasattr(orientation, "torch") else orientation + opengl = convert_camera_frame_quaternion(orientation.float(), origin="world", target="opengl") + return convert_camera_frame_quaternion(opengl, origin="opengl", target="ros") def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): """Move the camera's mount; the gaze stays relative to the new mount. @@ -297,7 +315,9 @@ def _allocate_gaze(self) -> None: self._gaze_rotation = ProxyArray( wp.from_torch(torch.eye(3, device=device).repeat(count, 1, 1), dtype=wp.mat33f) ) - self._mount_quat_ros = ProxyArray(wp.zeros(count, dtype=wp.quatf, device=device)) + # No gaze has turned the pose yet, so the current orientation is the mount. + mount = self._pose_quat_w_ros().to(device).contiguous() + self._mount_quat_ros = ProxyArray(wp.from_torch(mount, dtype=wp.quatf)) self._gaze_angles_key = None self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=device) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 99e5d047bf40..a6949f376751 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -130,7 +130,7 @@ class FoveatedCameraCfg(CameraCfg): uses the rounded sample-count ratio.""" pool_mode: str = "avg" - """Retinal pooling mode. ``"avg"`` or ``"gaussian"``.""" + """Retinal pooling mode: ``"avg"``, ``"gaussian"``, ``"max"`` or ``"sum"``.""" pool_sample_cortex: bool | str = "geodesic" """Space in which KNN neighbours are selected. ``True`` = Euclidean on @@ -168,8 +168,8 @@ class FoveatedCameraCfg(CameraCfg): width: int = 1 height: int = 1 - # Enable per-frame pose updates so the gaze rotation is applied each step. update_latest_camera_pose: bool = True + """Update the camera pose every frame. Newton and OVRTX require it: their pose update applies the gaze.""" def __post_init__(self): # Resolves the default renderer and forwards deprecated renderer fields. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 9992dbc247bd..db1802030b00 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -17,8 +17,7 @@ from isaaclab.sensors.camera.camera import Camera from isaaclab.utils.warp import ProxyArray -from .calibrated_geometry import retinal_directions -from .foveated_camera import FoveatedCamera +from .foveated_camera import OPENGL_TO_ROS_AXES, FoveatedCamera from .native_grid import ( GRID_STYLE, allocate_grid_outputs, @@ -26,7 +25,6 @@ grid_output_shape, grid_sample_indices, mask_grid_samples, - native_grid_directions, proxy_outputs, ) from .pooling import build_highres_coords, build_lowres_coords, build_pooler @@ -123,15 +121,9 @@ def _initialize_impl(self): self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) ) - # The rays keep the canonical sample order; image_rotation_deg rolls their directions to undo a rolled mount. - if self._native_grid: - self._ray_directions = native_grid_directions( - self._ray_coords, image_rotation_deg=self.cfg.image_rotation_deg - ) - else: - self._ray_directions = retinal_directions( - self._ray_coords.cartesian, self._ray_coords.fov, self.cfg.image_rotation_deg - ) + # The gaze geometry's rendered rays, in canonical sample order and rolled by image_rotation_deg, back in the + # OpenGL frame Newton traces. + self._ray_directions = self._gaze_rays * self._gaze_rays.new_tensor(OPENGL_TO_ROS_AXES) self._foveated_rays = explicit_rays(self._ray_directions, self.cfg.height, self.cfg.width) render_samples = self.cfg.height * self.cfg.width # Renderer buffers remain whole tiles; zero-copy canonical views hide @@ -147,6 +139,17 @@ def _initialize_impl(self): self._allocate_pooled_buffers() source = self._pooled_output if self._pooler is not None else self._flat_render_output + self._sample_output = None + if self._pooler is None and not self._native_grid: + # Newton redraws every environment, so sample sets publish a copy that changes only on update. + self._sample_output = { + name: torch.zeros_like(value.torch) + for name, value in self._flat_render_output.items() + if not (name == "rgb" and "rgba" in self._flat_render_output) + } + if "rgba" in self._sample_output and "rgb" in self._flat_render_output: + self._sample_output["rgb"] = self._sample_output["rgba"][..., :3] + source = self._sample_output if self._native_grid: self._grid_output = allocate_grid_outputs(source, self._sampling_coords) self._grid_indices = grid_sample_indices(self._sampling_coords) @@ -224,8 +227,8 @@ def _update_buffers_impl(self, env_mask: wp.array): """Render, then mask and publish the updated environments, pooling high-resolution samples if enabled. Newton redraws every environment's render buffer, each at the pose and gaze it last received, so the sensor - mask covers every row with that row's gaze. The buffers the camera owns, pooled or laid out as a grid, change - only for the updated environments. + mask covers every row with that row's gaze. The published buffers, which the camera owns, change only for the + updated environments. """ self._data.output.clear() self._data.output.update(self._render_output) @@ -240,9 +243,12 @@ def _update_buffers_impl(self, env_mask: wp.array): if self._grid_publish: self._publish_grid(env_mask) else: - # The published samples are Newton's own render buffer. - mask_grid_samples(self._flat_render_output, self._ray_coords) self._apply_sensor_fov_mask(self._flat_render_output) + updated = wp.to_torch(env_mask)[:, None, None, None] + for name, samples in self._sample_output.items(): + if name == "rgb" and "rgba" in self._sample_output: + continue # rgba alias + samples.copy_(torch.where(updated, self._flat_render_output[name].torch, samples)) return mask_grid_samples(self._highres_output, self._ray_coords) self._apply_sensor_fov_mask(self._highres_output) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index b1674ce59c6d..131017ba77e3 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -235,11 +235,13 @@ def _prepare_projection(self) -> None: def _initialize_impl(self) -> None: tw, th = self._texture_width, self._texture_height prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) - # OVRTX's lookup-table range is measured from the near-clipped ray origin. - self._near_clip = self._near_clipping_distance(prims[0]) if prims else 0.0 + # OVRTX's lookup-table range is measured from each camera's near-clipped ray origin. + near_clips = [self._near_clipping_distance(prim) for prim in prims] super()._initialize_impl() + self._near_clip = torch.tensor(near_clips, dtype=torch.float32, device=self._device).view(-1, 1, 1, 1) + # OVRTX owns its runtime; Kit extensions belong only to Isaac RTX. if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": import omni.kit.app @@ -389,7 +391,7 @@ def _extract_foveated_samples(self, env_mask: wp.array): samples = tensor[:, self._extract_py, self._extract_px, :].unsqueeze(2) if offset_distance and name == "distance_to_camera": # OVRTX measures the distance from the near-clipped ray origin. - samples = samples + self._near_clip + samples = samples + self._near_clip.to(samples.dtype) fov.copy_(torch.where(updated, samples, fov)) @staticmethod diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index 2a9514c7652b..bcb49b3cf397 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -41,9 +41,7 @@ from pxr import Usd -# ============================================================================= # Internal helpers -# ============================================================================= def _t(x, dtype: torch.dtype, device) -> torch.Tensor: @@ -53,9 +51,7 @@ def _t(x, dtype: torch.dtype, device) -> torch.Tensor: return torch.as_tensor(np.asarray(x), dtype=dtype, device=device) -# ============================================================================= # EXR I/O -# ============================================================================= def save_exr(path: str, data: torch.Tensor) -> None: @@ -78,9 +74,7 @@ def save_exr(path: str, data: torch.Tensor) -> None: exr.close() -# ============================================================================= # Octahedral decoding (internal) -# ============================================================================= def _octahedral_decode( @@ -106,9 +100,7 @@ def _octahedral_decode( return dx / n, dy / n, -dz / n -# ============================================================================= # Nearest-neighbour search -# ============================================================================= def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tensor: @@ -130,9 +122,7 @@ def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tens return idx -# ============================================================================= # Core LUT tensor builders -# ============================================================================= def build_native_grid_textures( @@ -180,7 +170,7 @@ def build_lut_textures( N = uv_t.shape[0] Q = texture_width * texture_height - # ── Direction texture ───────────────────────────────────────────────────── + # Direction texture. dir_out = torch.zeros(texture_height, texture_width, 3, dtype=torch.float32, device=device) dir_out[:, :, 2] = -1.0 @@ -196,12 +186,12 @@ def build_lut_textures( k_nn = _nn_chunk(texel_uv, uv_t, chunk) dir_out.reshape(-1, 3)[:] = dirs_t[k_nn] - # ── Exit texture ────────────────────────────────────────────────────────── + # Exit texture. # The exit texture is an octahedral inverse map: given a ray direction # (encoded over [0,1]² via octahedral projection), it returns the sensor # NDC (u, v) of the nearest foveated sample. The octahedral grid covers # the full hemisphere, but only texels whose decoded direction falls within - # the camera's FOV (r ≤ max_r) are populated; the rest default to (0.5, 0.5). + # the camera's FOV (r ≤ max_r) are populated; the rest hold the invalid UV (-1, -1), as in native-grid LUTs. # Resolution (exit_width × exit_height) should be large enough to resolve # individual samples — typically 4× the direction texture dimension. d = dirs_t.to(torch.float64) @@ -220,8 +210,8 @@ def build_lut_textures( odz_f = oct_z.float() valid = (r_q <= max_r) & (odz_f < -1e-9) - exit_u = torch.full((exit_height, exit_width), 0.5, dtype=torch.float32, device=device) - exit_v = torch.full((exit_height, exit_width), 0.5, dtype=torch.float32, device=device) + exit_u = torch.full((exit_height, exit_width), -1.0, dtype=torch.float32, device=device) + exit_v = torch.full((exit_height, exit_width), -1.0, dtype=torch.float32, device=device) if N > 0 and valid.any(): sample_cart = torch.stack([xs, ys], dim=1) @@ -236,9 +226,7 @@ def build_lut_textures( return dir_out, torch.stack([exit_u, exit_v], dim=2) -# ============================================================================= # EXR save helpers -# ============================================================================= def save_lut_textures( @@ -260,9 +248,7 @@ def save_lut_textures( return os.path.abspath(dir_path), os.path.abspath(exit_path) -# ============================================================================= # USD prim authoring -# ============================================================================= def apply_lens_lut_to_prim( @@ -284,9 +270,7 @@ def apply_lens_lut_to_prim( ) -# ============================================================================= # NDC layout functions -# ============================================================================= def samples_uv_cortical_disc( diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py index 96b1684f85f0..ca53cdcc826b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py @@ -26,10 +26,12 @@ def foveated_camera(camera: CameraCfg, foveated_res: int | None = None) -> Fovea so the number of rendered rays stays close to the camera's pixels. Samples the camera does not see are zero. The foveated camera keeps its own image size and per-frame pose updates, which render each new gaze. """ + # A copy, so the foveated camera shares no nested configuration (spawn, renderer, offset) with the preset's. camera = camera.copy() own = {"class_type", "width", "height", "update_latest_camera_pose"} values = {field.name: getattr(camera, field.name) for field in fields(CameraCfg) if field.name not in own} - return FoveatedCameraCfg(**values, foveated_res=foveated_res or camera.width, mask_to_sensor_fov=True) + resolution = camera.width if foveated_res is None else foveated_res + return FoveatedCameraCfg(**values, foveated_res=resolution, mask_to_sensor_fov=True) def foveated_presets(cameras: PresetCfg, foveated_res: int | None = None) -> PresetCfg: diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py index e34bec39918b..e946f3548593 100644 --- a/source/isaaclab_fovi/test/foveated_render_cases.py +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -18,7 +18,6 @@ import pytest import torch from fovi.sensing.projection import angular_directions -from isaaclab_fovi.mdp import direction_to_angles from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg import isaaclab.sim as sim_utils @@ -26,10 +25,11 @@ from isaaclab.scene import InteractiveScene, InteractiveSceneCfg from isaaclab.sim import SimulationCfg, build_simulation_context from isaaclab.terrains import TerrainImporterCfg +from isaaclab.test.utils.devices import resolve_test_sim_device from isaaclab.utils.configclass import configclass from isaaclab.utils.math import create_rotation_matrix_from_view, quat_from_matrix -DEVICE = "cuda:0" +DEVICE = resolve_test_sim_device() WARMUP_STEPS = 4 RESOLUTION = 32 @@ -162,7 +162,9 @@ def _render( field = coords.as_grid(coords.cartesian, sample_dim=0).detach().cpu().float().clone() # Each cell's camera-frame ray (OpenCV: x right, y down, z forward) from fovi's angular projection. rays = angular_directions(field.double(), coords.fov) - return distance, field, direction_to_angles(rays).float() + x, y, z = rays.unbind(-1) + angles = torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1) + return distance, field, angles.rad2deg().float() def foveated_camera_follows_gaze(backend: tuple, source: str): diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 90d6b34996e3..a25719a4ca34 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -14,7 +14,7 @@ import torch import warp as wp from fovi.sensing.projection import CameraModel -from isaaclab_fovi.mdp import angles_to_direction, clamp_gaze, direction_to_angles +from isaaclab_fovi.mdp import angles_to_direction from isaaclab_fovi.mdp.gaze import ( GazeAction, gaze_reset_kernel, @@ -33,6 +33,7 @@ from rsl_rl.storage import RolloutStorage from tensordict import TensorDict +from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.math import quat_apply, quat_apply_inverse from isaaclab.utils.warp import ProxyArray @@ -40,7 +41,18 @@ NUM_ENVS = 64 STEPS = 8 -DEVICES = ["cpu", "cuda:0"] if torch.cuda.is_available() else ["cpu"] +DEVICES = test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA) + + +def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: + """Gaze angles [deg] of camera-frame directions, shape (..., 3) to (..., 2): the reference for the kernels.""" + x, y, z = direction.unbind(-1) + return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg() + + +def clamp_gaze(gaze: torch.Tensor, limit: float) -> torch.Tensor: + """Gazes scaled back onto the circle of radius ``limit`` when they leave it: the reference for the step kernel.""" + return gaze * (limit / gaze.norm(dim=-1, keepdim=True).clamp_min(limit)) def test_gaze_angles_round_trip_and_follow_the_camera_convention(): @@ -52,11 +64,6 @@ def test_gaze_angles_round_trip_and_follow_the_camera_convention(): assert directions[1, 1] < 0 and directions[2, 0] < 0 -def test_clamp_gaze_is_radial(): - gaze = torch.tensor([[0.3, 0.4], [3.0, 4.0]]) - torch.testing.assert_close(clamp_gaze(gaze, 1.0), torch.tensor([[0.3, 0.4], [0.6, 0.8]])) - - def test_gaze_step_kernel_matches_the_torch_update(): generator = torch.Generator().manual_seed(4) count, step, limit, dt, radius = 2048, 0.1, 1.0, 1 / 60, 23.6 @@ -305,9 +312,12 @@ def test_fixed_mount_teacher_rejects_only_turns_after_capture(): term = object.__new__(GazeAction) term.tracked_mount = False term._mount_turns = 2 - term.camera = SimpleNamespace(mount_turns=3) + term._fixed_mount = "captured" + term.camera = SimpleNamespace(mount_turns=2) + assert GazeAction.teacher_mounts(term) == "captured" + term.camera.mount_turns = 3 with pytest.raises(RuntimeError, match="mount='tracked'"): - GazeAction._teacher_labels(term, targets=None) + GazeAction.teacher_mounts(term) def test_gaze_loss_ignores_invalid_labels(): @@ -408,19 +418,16 @@ def test_gaze_head_keeps_the_gaze_noise_fixed_while_ppo_learns_the_rest(): @pytest.mark.parametrize("std_type", ["scalar", "log"]) -def test_gaze_head_samples_with_the_fixed_gaze_noise(std_type): +def test_gaze_head_fixes_the_last_two_actions_noise(std_type): head = GazeGaussianDistribution(5, init_std=2.0, std_type=std_type, gaze_std=0.05) assert head.input_dim == 5 - head.update(torch.zeros(4096, 5)) - torch.testing.assert_close(head.std[0], torch.tensor([2.0, 2.0, 2.0, 0.05, 0.05])) - samples = head.sample() - assert samples.shape == (4096, 5) - torch.testing.assert_close(samples.std(dim=0)[3:], torch.full((2,), 0.05), atol=5e-3, rtol=0) + head.update(torch.zeros(3, 5)) + torch.testing.assert_close(head.std, torch.tensor([[2.0, 2.0, 2.0, 0.05, 0.05]]).expand(3, -1)) @pytest.mark.parametrize( - "kwargs", [dict(gaze_std=0.0), dict(gaze_std=float("inf")), dict(gaze_dims=5), dict(gaze_dims=0)] + "output_dim, gaze_std", [(5, 0.0), (5, float("inf")), (2, 0.1)], ids=["zero", "infinite", "gaze_only"] ) -def test_gaze_head_rejects_invalid_settings(kwargs): +def test_gaze_head_rejects_invalid_settings(output_dim, gaze_std): with pytest.raises(ValueError, match="gaze"): - GazeGaussianDistribution(5, **kwargs) + GazeGaussianDistribution(output_dim, gaze_std=gaze_std) diff --git a/source/isaaclab_fovi/test/test_gaze_kernels.py b/source/isaaclab_fovi/test/test_gaze_kernels.py index 00b9509f327a..863270de94a0 100644 --- a/source/isaaclab_fovi/test/test_gaze_kernels.py +++ b/source/isaaclab_fovi/test/test_gaze_kernels.py @@ -22,11 +22,13 @@ ) from isaaclab_fovi.sensors.native_grid import GRID_STYLE, grid_sample_indices, native_grid_directions +from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.math import matrix_from_quat, quat_from_matrix pytestmark = pytest.mark.kitless -DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu" +DEVICE = next(iter(test_devices(DeviceScope.DEFAULT_CUDA)), "cpu") +"""The run's default GPU, or the CPU when the run selects none.""" wp.init() CAMERAS = { diff --git a/source/isaaclab_fovi/test/test_lens_lut.py b/source/isaaclab_fovi/test/test_lens_lut.py new file mode 100644 index 000000000000..cb9549b263d2 --- /dev/null +++ b/source/isaaclab_fovi/test/test_lens_lut.py @@ -0,0 +1,37 @@ +# 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 + +"""The sample-set lens lookup textures, without a renderer.""" + +import math + +import pytest +import torch +from isaaclab_fovi.sensors.lens_lut import build_lut_textures + +pytestmark = pytest.mark.kitless + + +def test_exit_texture_marks_rays_outside_the_field_invalid(): + """The inverse lookup sends each in-field ray to its nearest sample, and every other ray to the invalid UV, never + to the fovea.""" + # Three samples: the optical axis (OpenGL -z) and two rays 10 degrees off it. + angle = math.radians(10.0) + directions = torch.tensor( + [[0.0, 0.0, -1.0], [math.sin(angle), 0.0, -math.cos(angle)], [0.0, math.sin(angle), -math.cos(angle)]] + ) + uv = torch.tensor([[0.5, 0.5], [0.9, 0.5], [0.5, 0.9]]) + _, exit_texture = build_lut_textures(uv, directions, 8, 8, 32, 32, device="cpu") + texels = exit_texture.reshape(-1, exit_texture.shape[-1])[:, :2] + + invalid = (texels == -1.0).all(dim=-1) + assert invalid.any() and (~invalid).any() + # Rays outside the 10 degree field outnumber those inside it on the hemisphere's octahedral grid. + assert invalid.float().mean() > 0.5 + # Every valid texel holds one of the samples' UVs. + assert all(any(torch.equal(texel, sample) for sample in uv) for texel in texels[~invalid]) + # The octahedral centre is the optical axis, which reaches the axis sample. + centre = exit_texture[exit_texture.shape[0] // 2, exit_texture.shape[1] // 2, :2] + torch.testing.assert_close(centre, uv[0]) diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py index 32682e487fe2..a2e09e4ff172 100644 --- a/source/isaaclab_fovi/test/test_native_grid.py +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -22,6 +22,8 @@ unbounded_angular_radius, ) +from isaaclab.test.utils import DeviceScope, test_devices + pytestmark = pytest.mark.kitless # Each footprint and each sensor roll once; the inverse path does not depend on the grid size. @@ -163,10 +165,8 @@ def test_upright_grid_masks_and_channel_aliases(): @pytest.mark.parametrize("dtype,channels", [(torch.uint8, 4), (torch.float32, 1), (torch.int32, 1)]) -@pytest.mark.parametrize("device", ["cpu", "cuda"]) +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) def test_output_permutation_preserves_dtype_and_captures(dtype, channels, device): - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA required") coords = make_coords(16).to(device=device) source = { "value": torch.arange(3 * len(coords) * channels, device=device).to(dtype).reshape(3, len(coords), 1, channels) @@ -176,7 +176,7 @@ def test_output_permutation_preserves_dtype_and_captures(dtype, channels, device copy_grid_outputs(source, target, indices) expected = coords.as_grid(source["value"][:, :, 0], sample_dim=1) torch.testing.assert_close(target["value"], expected, atol=0, rtol=0) - if device == "cuda": + if torch.device(device).type == "cuda": torch.cuda.synchronize() graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 4fc39abc9d92..c5bc197d780e 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -13,13 +13,39 @@ from fovi.sensing.coords import SamplingCoords from isaaclab_fovi.sensors import foveated_camera as base_camera from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera +from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera +from isaaclab_fovi.sensors.native_grid import native_grid_directions from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless +def rendered_rays_only(camera) -> None: + """Stand-in for the gaze geometry: only the rendered rays, in the ROS frame the camera keeps them in.""" + coords = camera._ray_coords + if coords.style == "warped_cartesian_as_grid": + rays = native_grid_directions(coords, image_rotation_deg=0) + else: + rays = retinal_directions(coords.cartesian, coords.fov, 0) + camera._gaze_rays = (rays * rays.new_tensor((1.0, -1.0, -1.0))).float() + + +def new_camera() -> FoveatedNewtonCamera: + """A Newton camera without its constructor: the state its constructor sets and the handles its destructor reads.""" + camera = object.__new__(FoveatedNewtonCamera) + camera._gaze_angles = camera._gaze_rotation = camera._visibility = camera._grid_publish = None + camera._published_shape = camera._pooler_int = camera._segmentation_neighbors = None + camera._initialize_handle = None + camera._invalidate_initialize_handle = None + camera._prim_deletion_handle = None + camera._view = None + camera._renderer = None + camera._device = "cpu" + return camera + + @pytest.mark.parametrize("pooled", [False, True]) def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatch, pooled) -> None: coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") @@ -29,7 +55,7 @@ def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatc monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (pooler, 4)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", lambda self: None) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) def initialize_renderer(camera): # Newton launches image tiles; a vector-shaped width of one is not valid. @@ -55,13 +81,7 @@ def render(camera, env_mask): monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) - camera = object.__new__(FoveatedNewtonCamera) - camera._initialize_handle = None - camera._invalidate_initialize_handle = None - camera._prim_deletion_handle = None - camera._view = None - camera._renderer = None - camera._device = "cpu" + camera = new_camera() camera.cfg = SimpleNamespace( foveated_style="warped_cartesian_as_grid", mask_to_sensor_fov=False, @@ -79,7 +99,8 @@ def render(camera, env_mask): rays = wp.to_torch(camera._foveated_rays) assert rays.shape == (ray_coords.resolution, ray_coords.resolution, 1, 2, 3) - torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], camera._ray_directions) + expected_rays = native_grid_directions(ray_coords, image_rotation_deg=0).float() + torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], expected_rays) public_rgba = camera._data.output["rgba"] camera.frame_offset = 0 camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) @@ -103,6 +124,48 @@ def render(camera, env_mask): assert not torch.equal(published[1], expected[1]) +def test_sample_set_publication_keeps_environments_that_were_not_updated(monkeypatch) -> None: + """A sample-set camera publishes its own buffers: Newton redraws every row, but only updated rows change.""" + coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu") + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 8)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: None) + monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (None, None)) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) + + def initialize_renderer(camera): + depth = torch.zeros((2, camera.cfg.height, camera.cfg.width, 1)) + camera._data = SimpleNamespace(output={"distance_to_camera": ProxyArray(wp.from_torch(depth))}) + camera._render_data = SimpleNamespace(camera_rays=None) + camera.renderer_depth = depth + + def render(camera, env_mask): + camera.renderer_depth.fill_(camera.frame_value) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) + camera = new_camera() + camera.cfg = SimpleNamespace( + foveated_style="isotropic", + mask_to_sensor_fov=False, + pool_enabled=False, + image_rotation_deg=0, + update_period=0.0, + data_types=["distance_to_camera"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + published = camera._data.output["distance_to_camera"] + assert published.torch.shape == (2, len(coords), 1, 1) + assert published.warp.ptr != camera._flat_render_output["distance_to_camera"].warp.ptr + + camera.frame_value = 1.0 + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) + camera.frame_value = 2.0 + camera._update_buffers_impl(wp.array([False, True], dtype=wp.bool, device="cpu")) + assert camera._data.output["distance_to_camera"] is published + assert bool((published.torch[0] == 1.0).all()) and bool((published.torch[1] == 2.0).all()) + + def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatch) -> None: """A pooled camera's segmentation output holds each sample's majority label exactly, IDs above 2**24 included.""" coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") @@ -115,9 +178,9 @@ def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatc monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (average, 4)) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) # The camera reads the modal neighbourhoods from its standard pooler. monkeypatch.setattr(base_camera, "segmentation_neighbor_indices", lambda pooler: neighbors) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", lambda self: None) def initialize_renderer(camera): size = (2, camera.cfg.height, camera.cfg.width) @@ -143,13 +206,7 @@ def render(camera, env_mask): monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) - camera = object.__new__(FoveatedNewtonCamera) - camera._initialize_handle = None - camera._invalidate_initialize_handle = None - camera._prim_deletion_handle = None - camera._view = None - camera._renderer = None - camera._device = "cpu" + camera = new_camera() camera.cfg = SimpleNamespace( foveated_style="warped_cartesian_as_grid", mask_to_sensor_fov=False, diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 48c6e738c196..aefdb643cf36 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -22,6 +22,7 @@ ) from isaaclab.sim import PinholeCameraCfg +from isaaclab.test.utils import DeviceScope, test_devices pytestmark = pytest.mark.kitless @@ -114,10 +115,7 @@ def test_disabled_pooling_uses_only_output_grid() -> None: assert build_pooler(cfg, lowres, None, "cpu") == (None, None) -DEVICES = [ - "cpu", - pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable")), -] +DEVICES = test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA) # Three output samples over five input samples; 5 marks an excluded neighbour. Columns are outputs, rows are # neighbour slots nearest first. @@ -228,9 +226,9 @@ def test_modal_neighbourhoods_stay_on_the_sensor_device(device: str) -> None: lowres, matched = build_lowres_coords(cfg, device) highres = build_highres_coords(cfg, matched, device) table = segmentation_neighbor_indices(build_pooler(cfg, lowres, highres, device)[0]) - assert table.device.type == device + assert table.device == torch.device(device) labels = torch.randint(0, 3, (1, len(highres), 1, 1), device=device) - assert pool_segmentation_buffer(table, labels).device.type == device + assert pool_segmentation_buffer(table, labels).device == torch.device(device) @pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index eaf2beadef70..fcbb8b8e6ce8 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -15,7 +15,6 @@ from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_ov.renderers import OVRTXRendererCfg -from isaaclab_physx.renderers import IsaacRtxRendererCfg from isaaclab.sensors.camera.camera import Camera from isaaclab.sim import PinholeCameraCfg @@ -46,9 +45,9 @@ def test_near_clip_comes_from_spawn_or_else_the_camera_prim() -> None: @pytest.mark.parametrize("native_grid", [False, True]) def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> None: - """Environments outside the update mask keep their samples, and OVRTX's near-plane offset is added once.""" + """Environments outside the update mask keep their samples, and each camera's near-plane offset is added once.""" height, width = 4, 5 - texture = torch.arange(2 * height * width, dtype=torch.float32).reshape(2, height, width, 1) + texture = torch.arange(3 * height * width, dtype=torch.float32).reshape(3, height, width, 1) if native_grid: texels = [(py, px) for py in range(height) for px in range(width)] else: @@ -56,18 +55,19 @@ def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> camera = SimpleNamespace( cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")), _native_grid=native_grid, - _near_clip=0.25, + _near_clip=torch.tensor([0.25, 0.5, 0.75]).view(-1, 1, 1, 1), _texture_output={"distance_to_camera": texture}, - _foveated_output={"distance_to_camera": torch.full((2, len(texels), 1, 1), -1.0)}, + _foveated_output={"distance_to_camera": torch.full((3, len(texels), 1, 1), -1.0)}, _extract_py=torch.tensor([py for py, _ in texels]), _extract_px=torch.tensor([px for _, px in texels]), ) - updated = wp.array([True, False], dtype=wp.bool, device="cpu") + updated = wp.array([True, False, True], dtype=wp.bool, device="cpu") for _ in range(2): FoveatedRTXCamera._extract_foveated_samples(camera, updated) samples = camera._foveated_output["distance_to_camera"] - expected = torch.tensor([float(texture[0, py, px, 0]) + 0.25 for py, px in texels]) - torch.testing.assert_close(samples[0, :, 0, 0], expected, atol=0, rtol=0) + for env, near_clip in ((0, 0.25), (2, 0.75)): + expected = torch.tensor([float(texture[env, py, px, 0]) + near_clip for py, px in texels]) + torch.testing.assert_close(samples[env, :, 0, 0], expected, atol=0, rtol=0) assert bool((samples[1] == -1.0).all()) @@ -81,8 +81,7 @@ def test_releasing_the_camera_removes_its_lens_textures(monkeypatch, tmp_path) - assert not directory.exists() and camera._lut_dir is None -@pytest.mark.parametrize("renderer_cfg", [IsaacRtxRendererCfg(), OVRTXRendererCfg()], ids=["isaac_rtx", "ovrtx"]) -def test_construction_authors_the_lens_and_unlocks_cameras_without_changing_the_config(monkeypatch, renderer_cfg): +def test_construction_authors_the_lens_and_unlocks_cameras_without_changing_the_config(monkeypatch): """Construction authors the lens lookup on every camera prim and unlocks it, since the gaze moves every foveated camera; the caller's configuration, spawn and texture size included, stays as it was.""" pxr = pytest.importorskip("pxr") @@ -103,7 +102,10 @@ def prepare(self): monkeypatch.setattr(FoveatedRTXCamera, "_prepare_projection", prepare) monkeypatch.setattr(FoveatedRTXCamera, "__del__", lambda self, *args, **kwargs: None) cfg = FoveatedCameraCfg( - prim_path="/World/envs/env_.*/Camera", spawn=PinholeCameraCfg(), renderer_cfg=renderer_cfg, data_types=["rgb"] + prim_path="/World/envs/env_.*/Camera", + spawn=PinholeCameraCfg(), + renderer_cfg=OVRTXRendererCfg(), + data_types=["rgb"], ) assert cfg.spawn.lock_camera camera = FoveatedRTXCamera(cfg) diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index fd6923681dac..1f4576ce6d33 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -19,6 +19,7 @@ from isaaclab_fovi.sensors.pooling import build_lowres_coords from isaaclab.sensors.camera.camera import Camera +from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.math import ( convert_camera_frame_orientation_convention, matrix_from_quat, @@ -28,6 +29,8 @@ pytestmark = pytest.mark.kitless +CPU_AND_CUDA = test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA) + @pytest.fixture def tf32_enabled(): @@ -93,6 +96,7 @@ def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None: quat_w_world=torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device).repeat(count, 1), pos_w=torch.zeros(count, 3, device=device), ) + self._gaze_written = False self._initialize_gaze() @@ -128,15 +132,13 @@ def test_gaze_away_from_sensor_masks_all_rays() -> None: assert not camera._gaze_validity().any() -@pytest.mark.parametrize("device", ["cpu", "cuda"]) +@pytest.mark.parametrize("device", CPU_AND_CUDA) @pytest.mark.parametrize( "mode, autocast", [("spherical", False), ("spherical", True), ("spherical_ids", False), ("spherical_mask", False)], ) def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, mode: str, tf32_enabled) -> None: batch_size = 48 - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA unavailable") source_gl = torch.tensor([[0.4625, 0.4940, -0.5341, 0.5067]], device=device).repeat(batch_size, 1) conversion = source_gl.new_tensor([[0, 0, -1], [-1, 0, 0], [0, 1, 0]]).double() source = quat_from_matrix(matrix_from_quat(source_gl.double()) @ conversion.T).float() @@ -229,6 +231,45 @@ def test_gaze_angles_need_one_row_per_camera(shape) -> None: assert camera._gaze_angles is None +def test_mount_record_starts_at_the_current_pose() -> None: + """Allocating the gaze before any pose update records the camera's current, ungazed mount, not zeros.""" + camera = GazeHarness() + camera._gaze_pose_reads_angles = True + mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) + camera._data.quat_w_world = mount.clone() + camera.gaze_angles + expected = convert_camera_frame_orientation_convention(mount, "world", "ros") + torch.testing.assert_close( + matrix_from_quat(camera.ungazed_quat_w_ros()), matrix_from_quat(expected), atol=1e-6, rtol=0 + ) + + +def test_prim_writing_camera_reads_its_mount_until_a_gaze_is_written() -> None: + """Isaac RTX writes the gaze into its prims, so its pose is the mount only until the first gaze.""" + camera = GazeHarness() + camera.gaze_angles + expected = convert_camera_frame_orientation_convention(camera._data.quat_w_world, "world", "ros") + torch.testing.assert_close( + matrix_from_quat(camera.ungazed_quat_w_ros()), matrix_from_quat(expected), atol=1e-6, rtol=0 + ) + camera.set_gaze_angles(torch.zeros(2, 2)) + with pytest.raises(RuntimeError, match="already hold a gaze"): + camera.ungazed_quat_w_ros() + + +def test_newton_and_ovrtx_need_per_frame_pose_updates(monkeypatch) -> None: + """Without pose updates the renderer would never see the gaze while the sensor mask used it.""" + monkeypatch.setattr(Camera, "__init__", lambda self, cfg: None) + monkeypatch.setattr(FoveatedCamera, "__del__", lambda self, *args, **kwargs: None, raising=False) + cfg = SimpleNamespace(update_latest_camera_pose=False) + harness = object.__new__(GazeHarness) + harness._gaze_pose_reads_angles = True + with pytest.raises(ValueError, match="update_latest_camera_pose=True"): + FoveatedCamera.__init__(harness, cfg) + harness._gaze_pose_reads_angles = False + FoveatedCamera.__init__(harness, cfg) + + def test_sensor_mask_reuses_its_buffer_and_keeps_rows_that_were_not_updated() -> None: camera = GazeHarness() camera.cfg.mask_to_sensor_fov = True @@ -290,10 +331,8 @@ def test_renderer_ray_frame_matches_cv_frame() -> None: torch.testing.assert_close(rendered, cv * torch.tensor([1, -1, -1])) -@pytest.mark.parametrize("device", ["cpu", "cuda"]) +@pytest.mark.parametrize("device", CPU_AND_CUDA) def test_gaze_pose_is_stable_inside_model_autocast(device: str) -> None: - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA unavailable") cameras = [GazeHarness(device=device), GazeHarness(device=device)] for camera in cameras: camera._data.quat_w_world = torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(2, 1) @@ -314,10 +353,8 @@ def test_gaze_pose_is_stable_inside_model_autocast(device: str) -> None: torch.testing.assert_close(cameras[1]._test_validity, cameras[0]._test_validity) -@pytest.mark.parametrize("device", ["cpu", "cuda"]) +@pytest.mark.parametrize("device", CPU_AND_CUDA) def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_enabled) -> None: - if device == "cuda" and not torch.cuda.is_available(): - pytest.skip("CUDA unavailable") camera = GazeHarness(count=48, device=device) camera._gaze_basis = camera._gaze_basis.to(device) camera._base_local_orientation = matrix_from_quat( @@ -340,15 +377,15 @@ def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_ torch.testing.assert_close(written[1], written[0]) -@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable") -def test_gaze_kernels_preserve_shared_stream_for_warp_capture() -> None: +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_gaze_kernels_preserve_shared_stream_for_warp_capture(device: str) -> None: wp.init() - stream = wp.Stream("cuda:0") + stream = wp.Stream(device) with wp.ScopedStream(stream), torch.cuda.stream(wp.stream_to_torch(stream)): - camera = GazeHarness(device="cuda:0") - camera.set_gaze_angles(torch.tensor([[5.0, -8.0], [0.0, 0.0]], device="cuda:0")) + camera = GazeHarness(device=device) + camera.set_gaze_angles(torch.tensor([[5.0, -8.0], [0.0, 0.0]], device=device)) valid = camera._gaze_validity() - target = wp.zeros(valid.shape, dtype=wp.bool, device="cuda:0") + target = wp.zeros(valid.shape, dtype=wp.bool, device=device) # Physics must still be able to capture after the camera's temporary stream scopes exit. with wp.ScopedCapture(stream=stream) as capture: wp.copy(target, wp.from_torch(valid)) From e504210ada5c538c9681c1fd4b2f769c9b32c2b2 Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 12:48:23 -0800 Subject: [PATCH 41/81] Fix gaze poses, pooled outputs and the sensor mask on partial updates - Isaac RTX reports the mount, without the gaze, from get_world_poses, so a get-then-set round trip keeps the mount and the gaze. - Foveated cameras skip set_intrinsic_matrices with a warning: the retina sets their rays, which the renderer would otherwise replace. - Pooled integer outputs are rounded to the nearest value, not truncated. - Pooled rgb is the view of pooled rgba whenever the renderer publishes rgb, so an rgba-only pooled sample set no longer publishes zero rgb. - On Newton, the sensor mask and its visibility record change only for the updated environments, matching the frames the camera publishes. - Segmentation pools by modal label (pool_int_mode="modal", the only accepted value); pool_mode accepts only fovi's modes. - Document that sample-set styles are experimental on RTX. - Update the tests to the camera's real pose buffers and the teacher kernel without rotate_offset, and remove the remaining banners. --- .../changelog.d/isaaclab-fovi.added.rst | 3 +- source/isaaclab_fovi/docs/README.md | 4 +- .../isaaclab_fovi/mdp/__init__.pyi | 4 - .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 96 +++++++------ .../sensors/calibrated_geometry.py | 41 +----- .../isaaclab_fovi/sensors/foveated_camera.py | 103 +++++++------- .../sensors/foveated_camera_cfg.py | 49 ++++--- .../sensors/foveated_newton_camera.py | 41 +++--- .../sensors/foveated_rtx_camera.py | 54 +++++--- .../isaaclab_fovi/sensors/lens_lut.py | 127 +++++++----------- .../isaaclab_fovi/sensors/native_grid.py | 56 ++++---- .../isaaclab_fovi/sensors/pooling.py | 41 +++--- .../isaaclab_fovi/tasks/__init__.py | 8 +- source/isaaclab_fovi/test/test_active_gaze.py | 42 ++++-- .../test/test_backend_dispatch.py | 30 +++++ source/isaaclab_fovi/test/test_camera_cfg.py | 19 +++ .../isaaclab_fovi/test/test_gaze_kernels.py | 37 ++++- .../isaaclab_fovi/test/test_newton_buffers.py | 118 +++++++++++++++- source/isaaclab_fovi/test/test_pooling.py | 28 ++-- source/isaaclab_fovi/test/test_rtx_camera.py | 4 +- .../test/test_spherical_geometry.py | 127 +++++++++++++----- 21 files changed, 625 insertions(+), 407 deletions(-) diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst index 3e7fac996ca0..2221bf7206eb 100644 --- a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst +++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst @@ -4,4 +4,5 @@ mount, gaze-supervised PPO for RSL-RL with a fixed gaze action noise in :mod:`isaaclab_fovi.rsl_rl`, and the ``Isaac-Cartpole-Camera-Fovi``, ``Isaac-Lift-KukaAllegro-Camera-Fovi`` and ``Isaac-Reorient-KukaAllegro-Camera-Fovi`` tasks. -* Pooled segmentation outputs take each sample's modal label in its native dtype. +* Added modal-label pooling for segmentation outputs, which keeps their native dtype (``pool_int_mode="modal"``, + the only accepted value); ``pool_mode`` pools the other outputs and accepts only fovi's modes. diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index 440738a1ff0b..f360d30b9a22 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -135,7 +135,9 @@ reward and the entropy bonus grows it until the sampled gaze random-walks. Each task is its stock camera counterpart with the camera foveated at the same mount and optics, two gaze actions, and gaze supervision. The vision model and -the PPO settings are the stock ones; the gaze actions' noise is fixed. +the PPO settings are the stock ones; the gaze actions' noise is fixed. The Kuka +tasks' action penalty leaves out the gaze (`motor_action_l2`), so moving it is +free. | Task | Retina | Teacher looks at | | --- | --- | --- | diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi index b0a95ebf64b3..327b6beb0bf7 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -6,19 +6,15 @@ __all__ = [ "GazeAction", "GazeActionCfg", - "angles_to_direction", "gaze_state", "gaze_teacher_labels", "motor_action_l2", - "random_gaze", ] from .gaze import ( GazeAction, - angles_to_direction, gaze_state, gaze_teacher_labels, motor_action_l2, - random_gaze, ) from .gaze_cfg import GazeActionCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 062a009b18bd..6502ea7537c6 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -34,6 +34,7 @@ if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv, ManagerBasedRLEnv + from ..sensors import FoveatedCamera from .gaze_cfg import GazeActionCfg RAD_TO_DEG = 180.0 / math.pi @@ -80,7 +81,6 @@ def teacher_labels_kernel( targets: wp.array(dtype=wp.vec3f), orientations: wp.array(dtype=wp.quatf), offset: wp.vec3f, - rotate_offset: wp.int32, positions: wp.array(dtype=wp.vec3f), mounts: wp.array(dtype=wp.quatf), angles_deg: wp.array(dtype=wp.vec2f), @@ -92,8 +92,8 @@ def teacher_labels_kernel( labels: wp.array2d(dtype=wp.float32), log: wp.array(dtype=wp.float32), ): - """Labels (action x, action y, valid) toward a point fixed to each target; and the mean gaze error to valid - targets [deg] with the fraction of valid targets. + """Labels (action x, action y, valid) toward the point ``offset`` fixed to each target's frame; and the mean gaze + error to valid targets [deg] with the fraction of valid targets. ``mounts`` holds each camera's mount (ROS convention); ``angles_deg`` the camera's stored gaze angles [deg]. One block labels every environment and reduces the logs itself, so the launch needs no zeroed accumulators. @@ -104,9 +104,7 @@ def teacher_labels_kernel( valid_count = wp.float32(0.0) i = lane while i < count: - point = targets[i] - if rotate_offset != 0: - point = point + wp.quat_rotate(orientations[i], offset) + point = targets[i] + wp.quat_rotate(orientations[i], offset) gaze = angles_deg[i] / field_radius_deg result = teach(point, positions[i], mounts[i], gaze, frame, field_radius_deg, step_size, gaze_limit, camera) labels[i, 0] = result[0] @@ -178,17 +176,19 @@ def gaze_step_kernel( state[i] = wp.vec4f(current[0], current[1], rate[0], rate[1]) -def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: - """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3).""" - tilt, pan = angles_deg.deg2rad().unbind(-1) - return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) +def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: + """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" + term: GazeAction = env.action_manager.get_term(action_name) + return term.state -def random_gaze(count: int, limit: float, device: torch.device | str | None = None) -> torch.Tensor: - """Gazes drawn uniformly over the disc of radius ``limit``, shape (count, 2).""" - radius = limit * torch.rand(count, device=device).sqrt() - angle = 2 * math.pi * torch.rand(count, device=device) - return torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1) +def motor_action_l2(env: ManagerBasedRLEnv, gaze_action_name: str = "gaze") -> torch.Tensor: + """Squared L2 norm of the actions other than the gaze, shape (num_envs,). + + Matches :func:`isaaclab.envs.mdp.action_l2` on the task's own actions, so moving the gaze costs nothing. + """ + gaze = env.action_manager.get_term(gaze_action_name).raw_actions + return env.action_manager.action.square().sum(-1) - gaze.square().sum(-1) class GazeAction(ActionTerm): @@ -217,9 +217,7 @@ class GazeAction(ActionTerm): physics may record the other terms' actions and its decimation loop into a CUDA graph.""" def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): - cfg.validate_config() super().__init__(cfg, env) - self.camera = self._asset camera = self.camera self.tracked_mount = cfg.mount == "tracked" if self.tracked_mount and not camera.turns_pose_by_gaze: @@ -236,13 +234,9 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): " use mount='tracked' for a camera on a moving body." ) # The camera's own geometry, so the teacher and the sensor mask share one projection. - self.camera_model = camera.camera_model - self.projection_params = camera.projection_params - """The physical camera as a Warp struct, for the teacher kernel.""" - self.image_frame = camera.image_frame - """Rotation from the upright gaze frame to the physical camera's frame (ROS convention).""" + frame = camera.image_frame self._frame_torch = torch.tensor( - [[self.image_frame[row][col] for col in range(3)] for row in range(3)], device=self.device + [[frame[row][col] for col in range(3)] for row in range(3)], device=self.device ) self.field_radius_deg = camera.sampling_coords.fov / 2 """Half the retina's field of view [deg].""" @@ -267,6 +261,11 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): def action_dim(self) -> int: return 2 + @property + def camera(self) -> FoveatedCamera: + """The foveated camera whose gaze the term moves.""" + return self._asset + @property def raw_actions(self) -> torch.Tensor: return self._raw if self._raw is not None else torch.zeros_like(self._velocity) @@ -340,8 +339,8 @@ def reset(self, env_ids=None): self._reset_ids.torch[:count] = torch.as_tensor(env_ids, device=self.device) random_start = self.cfg.random_reset if random_start: - gaze = random_gaze(count, self.cfg.gaze_limit, self.device) - visible = self.visible(angles_to_direction(gaze * self.field_radius_deg)) + gaze = _random_gaze(count, self.cfg.gaze_limit, self.device) + visible = self.visible(_angles_to_direction(gaze * self.field_radius_deg)) self._reset_start.torch[:count] = torch.where(visible[:, None], gaze, 0.0) angles = self.camera.gaze_angles launch = self._reset_launches.get((indexed, random_start)) @@ -360,7 +359,7 @@ def reset(self, env_ids=None): def visible(self, direction: torch.Tensor) -> torch.Tensor: """Whether directions in the upright gaze frame fall inside the physical camera's image.""" - return project_directions(direction @ self._frame_torch.T, self.projection_params)[1] + return project_directions(direction @ self._frame_torch.T, self.camera.projection_params)[1] def teacher_mounts(self) -> ProxyArray: """Each camera's mount (x, y, z, w), ROS convention, that the teacher aims from: the current one when @@ -379,21 +378,6 @@ def teacher_mounts(self) -> ProxyArray: return self._fixed_mount -def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: - """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" - term: GazeAction = env.action_manager.get_term(action_name) - return term.state - - -def _log_teacher(env: ManagerBasedEnv, values: torch.Tensor) -> None: - """Log the mean gaze error to valid targets and the fraction of valid targets.""" - # Loggers keep each step's entries, so they get a copy rather than the buffer the next step overwrites. - error, fraction = values.clone() - log = env.extras.setdefault("log", {}) - log["Gaze/target_error_deg"] = error - log["Gaze/valid_target_fraction"] = fraction - - class gaze_teacher_labels(ManagerTermBase): """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3). @@ -455,15 +439,14 @@ def __call__( self._targets, self._orientations, self._offset[1], - 1, camera_positions, mounts, gaze.camera.gaze_angles, - gaze.image_frame, + gaze.camera.image_frame, gaze.field_radius_deg, gaze.cfg.step_size, gaze.cfg.gaze_limit, - gaze.projection_params, + gaze.camera.projection_params, ], [self._labels, self._log], env.device, @@ -475,10 +458,23 @@ def __call__( return self._labels.torch -def motor_action_l2(env: ManagerBasedRLEnv, gaze_action_name: str = "gaze") -> torch.Tensor: - """Squared L2 norm of the actions other than the gaze, shape (num_envs,). +def _log_teacher(env: ManagerBasedEnv, values: torch.Tensor) -> None: + """Log the mean gaze error to valid targets and the fraction of valid targets.""" + # Loggers keep each step's entries, so they get a copy rather than the buffer the next step overwrites. + error, fraction = values.clone() + log = env.extras.setdefault("log", {}) + log["Gaze/target_error_deg"] = error + log["Gaze/valid_target_fraction"] = fraction - Matches :func:`isaaclab.envs.mdp.action_l2` on the task's own actions, so moving the gaze costs nothing. - """ - gaze = env.action_manager.get_term(gaze_action_name).raw_actions - return env.action_manager.action.square().sum(-1) - gaze.square().sum(-1) + +def _angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3).""" + tilt, pan = angles_deg.deg2rad().unbind(-1) + return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + + +def _random_gaze(count: int, limit: float, device: torch.device | str | None = None) -> torch.Tensor: + """Gazes drawn uniformly over the disc of radius ``limit``, shape (count, 2).""" + radius = limit * torch.rand(count, device=device).sqrt() + angle = 2 * math.pi * torch.rand(count, device=device) + return torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index af930faf6fb8..38298fef7800 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -8,7 +8,7 @@ from __future__ import annotations import math -from typing import Any, Literal, Protocol +from typing import Any, Protocol import torch from fovi.sensing.projection import CameraCalibration, CameraModel, angular_directions @@ -23,7 +23,7 @@ class SamplingGeometryConfig(Protocol): camera_model: CameraCalibration | None cmf_a_deg: float retinal_window_reference_side: str - retinal_window_short_side_fraction: float + retinal_window_fraction: float spawn: Any @@ -96,9 +96,7 @@ def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: The field of view is the angular span of the retinal window in the physical camera. Both values are in the units :class:`fovi.sensing.coords.SamplingCoords` takes. """ - fov = resolve_camera_model(cfg).field_of_view( - cfg.retinal_window_reference_side, cfg.retinal_window_short_side_fraction - ) + fov = resolve_camera_model(cfg).field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_fraction) return fov, cfg.cmf_a_deg @@ -118,36 +116,3 @@ def compose_rotations(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor: training process enables reduced-precision matrix multiplication. """ return (left[..., :, :, None] * right[..., None, :, :]).sum(dim=-2) - - -def convert_camera_frame_quaternion( - orientation: torch.Tensor, - *, - origin: Literal["world", "opengl"], - target: Literal["world", "opengl", "ros"], -) -> torch.Tensor: - """Convert world/OpenGL or OpenGL/ROS poses without a matrix round trip. - - Args: - orientation: Camera quaternions in XYZW order, shape (..., 4). - origin: Input camera-frame convention. - target: Opposite world/OpenGL convention, or ROS for OpenGL input. - - Returns: - Normalized float32 quaternions, shape (..., 4). Quaternion sign may change. - """ - quat = orientation.float() - quat = quat / quat.norm(dim=-1, keepdim=True) - x, y, z, w = quat.unbind(-1) - # Right multiplication by exact fixed-basis quaternions, without allocating - # device constants or making the matrix round-trip sensitive to AMP/TF32. - if origin == "world" and target == "opengl": - components = (w + x - y + z, -w + x + y + z, -w - x - y + z, w - x + y + z) - elif origin == "opengl" and target == "world": - components = (-w + x + y - z, w - x + y - z, w + x + y + z, w + x - y - z) - elif origin == "opengl" and target == "ros": - # ROS flips the OpenGL Y/Z axes: right-multiply by a half-turn about X. - return torch.stack((w, z, -y, -x), dim=-1) - else: - raise ValueError(f"Unsupported camera conversion: {origin!r} to {target!r}") - return torch.stack(components, dim=-1) * 0.5 diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 2c8da353f6a3..016e9c4eb9f9 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -7,6 +7,7 @@ from __future__ import annotations +import logging import math from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING @@ -16,9 +17,10 @@ from fovi.sensing.projection import CameraModel from isaaclab.sensors.camera.camera import Camera +from isaaclab.utils.math import convert_camera_frame_orientation_convention from isaaclab.utils.warp import ProxyArray -from .calibrated_geometry import convert_camera_frame_quaternion, resolve_camera_model, retinal_directions +from .calibrated_geometry import resolve_camera_model, retinal_directions from .gaze_kernels import ( CameraParams, apply_gaze_indexed_kernel, @@ -30,10 +32,8 @@ set_gaze_kernel, warp_stream, ) -from .native_grid import GRID_STYLE, native_grid_directions +from .native_grid import GRID_STYLE, buffer_tensor, native_grid_directions from .pooling import ( - MODAL_POOL_MODE, - build_pooler, is_segmentation_output, pool_hwc_buffer, pool_segmentation_buffer, @@ -43,6 +43,8 @@ if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg +logger = logging.getLogger(__name__) + OPENGL_TO_ROS_AXES = (1.0, -1.0, -1.0) """Axis signs between OpenGL camera-frame directions (x right, y up, -z forward) and ROS ones (x right, y down).""" @@ -68,10 +70,6 @@ class FoveatedCamera(Camera): cfg: FoveatedCameraCfg - _gaze_pose_reads_angles: bool = False - """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses when - the gaze is set; see :attr:`turns_pose_by_gaze`.""" - def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): """Create the implementation that matches the configured renderer. @@ -104,6 +102,9 @@ def __init__(self, cfg: FoveatedCameraCfg): ValueError: A Newton or OVRTX camera without ``update_latest_camera_pose``, whose renderer would never see the gaze. """ + self._gaze_pose_reads_angles = self._pose_update_turns_gaze(cfg) + """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses + when the gaze is set; see :attr:`turns_pose_by_gaze`.""" if self._gaze_pose_reads_angles and not cfg.update_latest_camera_pose: raise ValueError( "Newton and OVRTX turn the rendered pose by the gaze in each pose update; set" @@ -116,8 +117,8 @@ def __init__(self, cfg: FoveatedCameraCfg): self._visibility = None self._grid_publish = None self._published_shape: tuple[int, int] | None = None - self._pooler_int = None self._segmentation_neighbors: torch.Tensor | None = None + self._sensor_fov_valid: torch.Tensor | None = None self.mount_turns = 0 """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount.""" super().__init__(cfg) @@ -132,11 +133,6 @@ def sampling_coords(self): """The :class:`SamplingCoords` of the published samples.""" return self._sampling_coords - @property - def image_rotation_deg(self) -> float: - """Roll [deg] of the rendered rays around the optical axis, which undoes a rolled mount.""" - return float(self.cfg.image_rotation_deg) - @property def num_valid_samples(self) -> int: """Number of published foveated samples.""" @@ -145,8 +141,7 @@ def num_valid_samples(self) -> int: @property def sensor_fov_valid_fraction(self) -> torch.Tensor | None: """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" - valid = getattr(self, "_sensor_fov_valid", None) - return None if valid is None else valid.float().mean(dim=1) + return None if self._sensor_fov_valid is None else self._sensor_fov_valid.float().mean(dim=1) @property def camera_model(self) -> CameraModel: @@ -161,7 +156,7 @@ def projection_params(self) -> CameraParams: @property def image_frame(self) -> wp.mat33f: """Rotation from the upright image frame, in which gazes are measured, to the physical camera's frame (ROS - convention); it undoes :attr:`image_rotation_deg`.""" + convention); it undoes ``cfg.image_rotation_deg``.""" return self._mask_frame @property @@ -243,14 +238,7 @@ def ungazed_quat_w_ros(self) -> torch.Tensor: return self._mount_quat_ros.torch.clone() if self._gaze_written and not self._gaze_pose_reads_angles: raise RuntimeError("The camera's prims already hold a gaze; read its mount before setting one.") - return self._pose_quat_w_ros() - - def _pose_quat_w_ros(self) -> torch.Tensor: - """The camera's current world orientation in the ROS convention, shape (num_envs, 4).""" - orientation = self._data.quat_w_world - orientation = orientation.torch if hasattr(orientation, "torch") else orientation - opengl = convert_camera_frame_quaternion(orientation.float(), origin="world", target="opengl") - return convert_camera_frame_quaternion(opengl, origin="opengl", target="ros") + return self._data.quat_w_ros.torch.clone() def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): """Move the camera's mount; the gaze stays relative to the new mount. @@ -271,6 +259,14 @@ def set_world_poses_from_view(self, eyes, targets, env_ids=None): if self._turned_by_view(eyes, targets).any(): self.mount_turns += 1 + def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): + """Skip runtime intrinsics with a warning, as stock cameras with an OpenCV lens model do: the retina and + :attr:`camera_model` define a foveated camera's rays, and the renderer must keep rendering them. + + Args are those of :meth:`isaaclab.sensors.Camera.set_intrinsic_matrices`. + """ + logger.warning("set_intrinsic_matrices() skipped a foveated camera; its retina and camera_model set its rays.") + def _initialize_gaze(self) -> None: """Prepare the gaze geometry: the rendered rays in the physical camera's frame and the pose conversions.""" self._camera_model = resolve_camera_model(self.cfg) @@ -295,11 +291,11 @@ def _initialize_gaze(self) -> None: self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) # The same roll in the ROS frame: a rendered ray r reaches the physical camera at K gaze K^T r. self._mask_frame = wp.mat33f(c, s, 0.0, -s, c, 0.0, 0.0, 0.0, 1.0) - identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device) - opengl = convert_camera_frame_quaternion(identity, origin="world", target="opengl") - to_opengl = opengl[0].tolist() - to_world = convert_camera_frame_quaternion(identity, origin="opengl", target="world")[0].tolist() - to_ros = convert_camera_frame_quaternion(opengl, origin="opengl", target="ros")[0].tolist() + # Fixed right-multiplied frame changes, on the CPU in float64, where no reduced-precision matmul applies. + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], dtype=torch.float64) + to_opengl = convert_camera_frame_orientation_convention(identity, origin="world", target="opengl")[0].tolist() + to_world = convert_camera_frame_orientation_convention(identity, origin="opengl", target="world")[0].tolist() + to_ros = convert_camera_frame_orientation_convention(identity, origin="world", target="ros")[0].tolist() self._gaze_frames = ( wp.mat33f(*self._gaze_basis.flatten().tolist()), wp.quatf(*to_opengl), @@ -316,7 +312,7 @@ def _allocate_gaze(self) -> None: wp.from_torch(torch.eye(3, device=device).repeat(count, 1, 1), dtype=wp.mat33f) ) # No gaze has turned the pose yet, so the current orientation is the mount. - mount = self._pose_quat_w_ros().to(device).contiguous() + mount = self._data.quat_w_ros.torch.clone() self._mount_quat_ros = ProxyArray(wp.from_torch(mount, dtype=wp.quatf)) self._gaze_angles_key = None self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} @@ -343,8 +339,7 @@ def _apply_gaze_pose( """Turn the camera's world orientation by the stored gaze, and record the gaze rotations and the mount.""" if self._gaze_angles is None: return - orientation = self._data.quat_w_world - orientation = orientation.warp if hasattr(orientation, "warp") else wp.from_torch(orientation, dtype=wp.quatf) + orientation = self._data.quat_w_world.warp device = self._gaze_angles.torch.device frames = (self._gaze_angles, *self._gaze_frames) outputs = [orientation, self._gaze_rotation, self._mount_quat_ros] @@ -416,7 +411,7 @@ def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor], env_mask: outputs; None updates every environment.""" if not self.cfg.mask_to_sensor_fov: return - tensors = {name: value.torch if hasattr(value, "torch") else value for name, value in outputs.items()} + tensors = {name: buffer_tensor(value) for name, value in outputs.items()} self._sensor_fov_valid = self._gaze_validity(env_mask) hidden = self._visibility["hidden"].torch[:, :, None, None] for name, tensor in tensors.items(): @@ -425,35 +420,25 @@ def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor], env_mask: tensor.masked_fill_(hidden, 0) def _prepare_segmentation_pooling(self, names) -> None: - """Choose how pooled segmentation outputs among ``names`` are reduced: by modal label over the main pooler's - neighbourhoods (``pool_int_mode="mode"``), or by a second fovi pooler for another ``pool_int_mode``.""" - self._pooler_int = None + """Take the modal-label neighbourhoods of pooled segmentation outputs among ``names`` from the main pooler.""" self._segmentation_neighbors = None - if self._pooler is None or not any(is_segmentation_output(name) for name in names): - return - if self.cfg.pool_int_mode == MODAL_POOL_MODE: + if self._pooler is not None and any(is_segmentation_output(name) for name in names): self._segmentation_neighbors = segmentation_neighbor_indices(self._pooler) - elif self.cfg.pool_int_mode != self.cfg.pool_mode: - self._pooler_int, _ = build_pooler( - self.cfg, - self._sampling_coords, - self._sampling_coords_highres, - device=str(self._device), - mode=self.cfg.pool_int_mode, - ) def _pool_output(self, name: str, samples: torch.Tensor) -> torch.Tensor: """Pool one output's high-resolution samples (B, N_hi, 1, C) to the retina's (B, N_lo, 1, C), in its dtype. - Segmentation takes each sample's modal label in its native dtype by default; other outputs are pooled in - float. + Segmentation takes each sample's modal label in its native dtype; other outputs are pooled in float with + ``pool_mode``. """ if is_segmentation_output(name): - if self._segmentation_neighbors is not None: - return pool_segmentation_buffer(self._segmentation_neighbors, samples) - if self._pooler_int is not None: - return pool_hwc_buffer(self._pooler_int, samples.float()).to(samples.dtype) - return pool_hwc_buffer(self._pooler, samples.float()).to(samples.dtype) + return pool_segmentation_buffer(self._segmentation_neighbors, samples) + pooled = pool_hwc_buffer(self._pooler, samples.float()) + if not samples.dtype.is_floating_point: + # Round to the nearest value the output can hold, e.g. 0-255 for RGB, rather than truncating. + limits = torch.iinfo(samples.dtype) + pooled = pooled.round().clamp(limits.min, limits.max) + return pooled.to(samples.dtype) def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for @@ -530,7 +515,11 @@ def _publish_grid(self, env_mask: wp.array | None = None) -> None: def _set_published_shape(self, outputs: Mapping[str, torch.Tensor]) -> None: """Report the (height, width) of the published outputs, which differ from the rendered ones.""" - first = next(iter(outputs.values())) - tensor = first.torch if hasattr(first, "torch") else first + tensor = next(iter(outputs.values())).torch self._published_shape = (int(tensor.shape[1]), int(tensor.shape[2])) self._data.image_shape = self._published_shape + + @staticmethod + def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: + """Whether this implementation turns its rendered pose by the stored gaze in each pose update.""" + return False diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index a6949f376751..df6181fb6ea1 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -20,6 +20,13 @@ from .foveated_camera import FoveatedCamera +POOL_MODES = ("avg", "gaussian", "max", "sum") +"""fovi pooling modes for the outputs other than segmentation.""" + +SEGMENTATION_POOL_MODES = ("modal",) +"""Pooling modes for segmentation outputs: the modal label only.""" + + def validate_radius_norm(radius_norm: float, style: str, fov_type: str) -> None: """Reject warped-grid radius norms that fovi cannot sample, before renderer startup.""" if radius_norm not in RADIUS_NORMS: @@ -78,7 +85,10 @@ class FoveatedCameraCfg(CameraCfg): The default ``"warped_cartesian_as_grid"`` publishes an upright image of shape ``(B, H, W, C)``. Sample-set styles such as ``"isotropic"`` are an - advanced option and publish ``(B, N, 1, C)``.""" + advanced option and publish ``(B, N, 1, C)``. Newton renders their rays + directly; on RTX they are experimental: the lens lookup places the samples on + a cortical disc texture, where crowded samples can share a texel and so read + the same ray.""" fov_type: str = "circular" """Visual footprint; circular is the default for native warped grids.""" @@ -101,7 +111,7 @@ class FoveatedCameraCfg(CameraCfg): mask_to_sensor_fov: bool = False """Zero the samples that fall outside the physical camera's image at the current gaze.""" - retinal_window_short_side_fraction: float = 1.0 + retinal_window_fraction: float = 1.0 """Diameter of the retinal window as a fraction of the reference image side.""" retinal_window_reference_side: str = "short" @@ -130,7 +140,8 @@ class FoveatedCameraCfg(CameraCfg): uses the rounded sample-count ratio.""" pool_mode: str = "avg" - """Retinal pooling mode: ``"avg"``, ``"gaussian"``, ``"max"`` or ``"sum"``.""" + """Pooling of every output except segmentation: ``"avg"``, ``"gaussian"``, ``"max"`` or ``"sum"``. + Segmentation pools with :attr:`pool_int_mode`.""" pool_sample_cortex: bool | str = "geodesic" """Space in which KNN neighbours are selected. ``True`` = Euclidean on @@ -140,18 +151,14 @@ class FoveatedCameraCfg(CameraCfg): pool_gauss_sigma: float = 10.0 """Gaussian sigma for ``pool_mode="gaussian"``. Unused otherwise.""" - pool_int_mode: str = "mode" - """Pool mode used for outputs whose key name contains ``"segmentation"`` - (``semantic_segmentation``, ``instance_segmentation_fast``, - ``instance_id_segmentation_fast``). + pool_int_mode: str = "modal" + """Pooling of segmentation outputs: any output whose name contains ``"segmentation"``, i.e. semantic (class), + instance and instance-ID segmentation, as integer IDs or colorized RGBA. Only ``"modal"`` is supported. - The default ``"mode"`` gives each pooled sample the most common full value - (ID or colorized RGBA vector) among its pooling neighbours, in the output's - native dtype; ties go to the neighbour nearest the pooled sample. Every - pooled value therefore belongs to a rendered object. The fovi modes - (``"max"``, ``"avg"``, ``"sum"``, ``"gaussian"``) pool through float32 - instead, which mixes colorized channels and corrupts IDs above ``2**24``. - Set equal to ``pool_mode`` to pool segmentation like the other outputs.""" + ``"modal"`` gives each pooled sample the most common full value among its pooling neighbours, in the output's + dtype, and ties go to the neighbour nearest the pooled sample, so every pooled value is a label a rendered object + has. The ``pool_mode`` options (``"avg"``, ``"gaussian"``, ``"max"``, ``"sum"``) would mix labels into ones no + object has, and corrupt IDs above ``2**24`` in float32, so they are rejected.""" # -- RTX-specific parameters (ignored by Newton backend) ---------------- @@ -162,9 +169,8 @@ class FoveatedCameraCfg(CameraCfg): sufficient angular resolution to distinguish individual foveated samples. Ignored by Newton backend.""" - # height / width are set automatically in _initialize_impl before the - # parent allocates buffers. We default them to 1 here so the MISSING - # sentinel from CameraCfg is satisfied at config-validation time. + # The camera sets height and width on its own copy of the configuration, from the retina's samples, before the + # parent allocates buffers. The defaults only satisfy CameraCfg's required fields. width: int = 1 height: int = 1 @@ -175,3 +181,12 @@ def __post_init__(self): # Resolves the default renderer and forwards deprecated renderer fields. super().__post_init__() validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) + if self.pool_mode not in POOL_MODES: + raise ValueError( + f"pool_mode must be one of {POOL_MODES}, got {self.pool_mode!r}; segmentation pools with pool_int_mode." + ) + if self.pool_int_mode not in SEGMENTATION_POOL_MODES: + raise ValueError( + f"pool_int_mode must be one of {SEGMENTATION_POOL_MODES}, got {self.pool_int_mode!r}: segmentation" + " pools by modal label, since other modes would mix labels into ones no object has." + ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index db1802030b00..6b84cb55ff6e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -68,11 +68,10 @@ class FoveatedNewtonCamera(FoveatedCamera): cfg: FoveatedCameraCfg - _gaze_pose_reads_angles = True - - # ------------------------------------------------------------------ - # Initialisation - # ------------------------------------------------------------------ + def __init__(self, cfg: FoveatedCameraCfg): + # The parent's initialisation updates poses before the rays exist. + self._foveated_rays: wp.array | None = None + super().__init__(cfg) def _initialize_impl(self): # The pooler's KNN tensors are plain attributes that nn.Module.to() does not move, so the coordinates start on @@ -182,31 +181,29 @@ def _allocate_pooled_buffers(self) -> None: self._highres_output: dict[str, ProxyArray] = dict(self._data.output) self._pooled_output: dict[str, torch.Tensor] = {} for name, tex in self._highres_output.items(): + if name == "rgb" and "rgba" in self._highres_output: + continue # an alias of rgba, below tensor = tex.torch B, _, _, C = tensor.shape self._pooled_output[name] = torch.zeros( (B, self._num_valid_samples, 1, C), dtype=tensor.dtype, device=tensor.device ) - if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: + # The renderer publishes rgb as a view of rgba whenever either is requested; so does the pooled output. + if "rgb" in self._highres_output and "rgba" in self._pooled_output: self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] self._prepare_segmentation_pooling(self._highres_output) dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} logger.info( - "FoveatedNewtonCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) " - "outputs=%s int_mode=%s", + "FoveatedNewtonCamera: %s pooling (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) outputs=%s", + type(self._pooler).__name__, self.cfg.pool_mode, self._pool_k, self.cfg.pool_sample_cortex, self._num_ray_samples, self._num_valid_samples, dtypes_summary, - self.cfg.pool_int_mode, ) - # ------------------------------------------------------------------ - # Per-frame overrides - # ------------------------------------------------------------------ - def _update_poses( self, env_ids: Sequence[int] | wp.array | None = None, @@ -220,15 +217,15 @@ def _update_poses( """ # The base update turns the poses by the gaze in _update_camera_state, then hands them to the renderer. Camera._update_poses(self, env_ids, env_mask=env_mask, frame_op=frame_op) - if hasattr(self, "_foveated_rays"): + if self._foveated_rays is not None: self._render_data.camera_rays = self._foveated_rays def _update_buffers_impl(self, env_mask: wp.array): """Render, then mask and publish the updated environments, pooling high-resolution samples if enabled. - Newton redraws every environment's render buffer, each at the pose and gaze it last received, so the sensor - mask covers every row with that row's gaze. The published buffers, which the camera owns, change only for the - updated environments. + Newton redraws every environment's render buffer, each at the pose and gaze it last received. The sensor mask, + its visibility record and the published buffers, which the camera owns, change only for the updated + environments. """ self._data.output.clear() self._data.output.update(self._render_output) @@ -243,7 +240,7 @@ def _update_buffers_impl(self, env_mask: wp.array): if self._grid_publish: self._publish_grid(env_mask) else: - self._apply_sensor_fov_mask(self._flat_render_output) + self._apply_sensor_fov_mask(self._flat_render_output, env_mask) updated = wp.to_torch(env_mask)[:, None, None, None] for name, samples in self._sample_output.items(): if name == "rgb" and "rgba" in self._sample_output: @@ -251,12 +248,16 @@ def _update_buffers_impl(self, env_mask: wp.array): samples.copy_(torch.where(updated, self._flat_render_output[name].torch, samples)) return mask_grid_samples(self._highres_output, self._ray_coords) - self._apply_sensor_fov_mask(self._highres_output) + self._apply_sensor_fov_mask(self._highres_output, env_mask) updated = wp.to_torch(env_mask)[:, None, None, None] for name, hi in self._highres_output.items(): - if name == "rgb": + if name == "rgb" and "rgba" in self._highres_output: continue # rgba alias pooled = self._pooled_output[name] pooled.copy_(torch.where(updated, self._pool_output(name, hi.torch), pooled)) if self._native_grid: copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) + + @staticmethod + def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: + return True diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 131017ba77e3..80e09562acaf 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -26,7 +26,7 @@ from isaaclab import sim as sim_utils from isaaclab.sensors.camera.camera import Camera from isaaclab.utils import clone -from isaaclab.utils.math import matrix_from_quat, quat_from_matrix +from isaaclab.utils.math import convert_camera_frame_orientation_convention, matrix_from_quat, quat_from_matrix from . import lens_lut from .calibrated_geometry import compose_rotations, retinal_directions @@ -43,8 +43,6 @@ from .pooling import build_highres_coords, build_lowres_coords, build_pooler if TYPE_CHECKING: - from isaaclab.renderers.base_renderer import BaseRenderer - from .foveated_camera_cfg import FoveatedCameraCfg logger = logging.getLogger(__name__) @@ -68,14 +66,11 @@ class FoveatedRTXCamera(FoveatedCamera): def __init__(self, cfg: FoveatedCameraCfg): ovrtx = cfg.renderer_cfg.renderer_type == "ovrtx" - if ovrtx and getattr(cfg.renderer_cfg, "async_rendering", False) and cfg.mask_to_sensor_fov: + if ovrtx and cfg.renderer_cfg.async_rendering and cfg.mask_to_sensor_fov: raise ValueError( "OVRTX async_rendering returns the previous capture, which the sensor mask would cut with the current" " gaze. Disable async_rendering or mask_to_sensor_fov." ) - # OVRTX renders the poses the camera hands it, so its pose update turns the gaze. Replicator reads camera - # prims, so Isaac RTX writes the gaze into them instead. - self._gaze_pose_reads_angles = ovrtx # The parent ``Camera`` allocates the renderer-bound texture buffers; the published ones follow from them. self._texture_output: dict[str, torch.Tensor] = {} self._foveated_output: dict[str, torch.Tensor] = {} @@ -107,11 +102,6 @@ def __del__(self, *args, **kwargs): def supports_batch_update(self) -> bool: return True - @property - def renderer(self) -> BaseRenderer: - """Renderer shared with task-owned visual animation bindings.""" - return self._renderer - def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: super().set_gaze_angles(angles_deg) if not self._gaze_pose_reads_angles: @@ -136,6 +126,26 @@ def set_world_poses_from_view(self, eyes, targets, env_ids=None): # Rows whose eye equals their target are skipped by the base method and keep their mount. self._refresh_mount(self._env_indices(env_ids)[self._turned_by_view(eyes, targets)]) + def get_world_poses(self, env_ids=None, convention="ros"): + """Read the cameras' mount poses, without the gaze, as every foveated camera reports them. + + Isaac RTX holds the gaze in the camera prims, so it is taken back out; passing the result to + :meth:`set_world_poses` keeps the mount and the gaze as they are. + + Args and returns are those of :meth:`isaaclab.sensors.Camera.get_world_poses`. + """ + positions, orientations = super().get_world_poses(env_ids, convention="opengl") + if not self._gaze_pose_reads_angles and self._gaze_rotation is not None: + # The prims hold the mount turned by the gaze's rotation in their own (OpenGL) frame. + basis = self._gaze_basis + gaze = self._gaze_rotation.torch[self._env_indices(env_ids)] + with torch.autocast(basis.device.type, enabled=False): + relative = compose_rotations(compose_rotations(basis, gaze), basis.T) + orientations = quat_from_matrix( + compose_rotations(matrix_from_quat(orientations), relative.transpose(-1, -2)) + ) + return positions, convert_camera_frame_orientation_convention(orientations, origin="opengl", target=convention) + def process_rendered_frame(self) -> None: """Mask and publish the frame of the environments that scalar or batched rendering updated.""" if not self._env_mask_has_any(self._is_outdated): @@ -264,7 +274,7 @@ def _initialize_impl(self) -> None: # The renderer keeps writing the texture buffers the parent bound to it; the camera publishes others. self._texture_output = self._data.output - textures = {name: tex.torch if hasattr(tex, "torch") else tex for name, tex in self._texture_output.items()} + textures = {name: tex.torch for name, tex in self._texture_output.items()} # A native grid texture already holds the samples in order, so one kernel per output masks it and lays it # out. OVRTX's camera distance needs its near-plane offset first, and keeps the step-by-step path. offset_distance = self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in textures @@ -308,11 +318,12 @@ def _allocate_foveated_buffers(self): if name == "rgb" and has_rgba_alias: continue # an alias of rgba, below # Texture buffers are ProxyArrays; their Torch view carries the dtype and device. - buf_t = buf.torch if hasattr(buf, "torch") else buf + buf_t = buf.torch self._foveated_output[name] = torch.zeros( (self._view.count, self._num_ray_samples, 1, buf_t.shape[-1]), device=buf_t.device, dtype=buf_t.dtype ) - if "rgba" in self._foveated_output and "rgb" in self.cfg.data_types: + # The renderer publishes rgb as a view of rgba whenever either is requested; so do the foveated outputs. + if "rgb" in self._texture_output and "rgba" in self._foveated_output: self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] if self._pooler is None: @@ -325,11 +336,12 @@ def _allocate_foveated_buffers(self): self._pooled_output[name] = torch.zeros( (self._view.count, self._num_valid_samples, 1, buf.shape[-1]), device=self._device, dtype=buf.dtype ) - if "rgba" in self._pooled_output and "rgb" in self.cfg.data_types: + if "rgb" in self._texture_output and "rgba" in self._pooled_output: self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] self._prepare_segmentation_pooling(self._pooled_output) logger.info( - "FoveatedRTXCamera: KNN pooling enabled (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", + "FoveatedRTXCamera: %s pooling (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", + type(self._pooler).__name__, self.cfg.pool_mode, self._pool_k, self.cfg.pool_sample_cortex, @@ -384,7 +396,7 @@ def _extract_foveated_samples(self, env_mask: wp.array): continue # rgba alias tex = self._texture_output[name] # (B, th, tw, C) fov = self._foveated_output[name] # (B, N, 1, C) - tensor = tex.torch if hasattr(tex, "torch") else tex + tensor = tex.torch if self._native_grid: samples = tensor.reshape_as(fov) else: @@ -394,6 +406,12 @@ def _extract_foveated_samples(self, env_mask: wp.array): samples = samples + self._near_clip.to(samples.dtype) fov.copy_(torch.where(updated, samples, fov)) + @staticmethod + def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: + # OVRTX renders the poses the camera hands it, so its pose update turns the gaze. Replicator reads camera + # prims, so Isaac RTX writes the gaze into them instead. + return cfg.renderer_cfg.renderer_type == "ovrtx" + @staticmethod def _update_buffers_batch_impl(sensors: Sequence[FoveatedRTXCamera]) -> None: Camera._update_buffers_batch_impl(sensors) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index bcb49b3cf397..97b055de36a9 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -41,19 +41,6 @@ from pxr import Usd -# Internal helpers - - -def _t(x, dtype: torch.dtype, device) -> torch.Tensor: - """Convert array-like or tensor *x* to a ``torch.Tensor`` on *device*.""" - if isinstance(x, torch.Tensor): - return x.to(dtype=dtype, device=device) - return torch.as_tensor(np.asarray(x), dtype=dtype, device=device) - - -# EXR I/O - - def save_exr(path: str, data: torch.Tensor) -> None: """Save a ``(H, W, C)`` float32 tensor to an EXR file (C ∈ {2, 3}) with OpenEXR, which the ``fovi`` extra installs.""" @@ -74,57 +61,6 @@ def save_exr(path: str, data: torch.Tensor) -> None: exr.close() -# Octahedral decoding (internal) - - -def _octahedral_decode( - width: int, - height: int, - device="cuda", -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Decode octahedral-LUT texel centres to unit directions (camera −Z convention). - - Returns: - Three ``(height, width)`` float64 tensors ``(dx, dy, dz)``. - """ - u = (torch.arange(width, dtype=torch.float64, device=device) + 0.5) / width - v = (torch.arange(height, dtype=torch.float64, device=device) + 0.5) / height - px = u.unsqueeze(0).expand(height, width) * 2.0 - 1.0 - py = v.unsqueeze(1).expand(height, width) * 2.0 - 1.0 - dz = 1.0 - px.abs() - py.abs() - sx = torch.sign(px) - sy = torch.sign(py) - dx = torch.where(dz <= 0.0, (1.0 - py.abs()) * sx, px) - dy = torch.where(dz <= 0.0, (1.0 - px.abs()) * sy, py) - n = torch.clamp((dx**2 + dy**2 + dz**2).sqrt(), min=1e-20) - return dx / n, dy / n, -dz / n - - -# Nearest-neighbour search - - -def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tensor: - """Chunked nearest-neighbour search via ``torch.cdist``. - - Chunk size is capped so the float32 distance matrix stays within 2 GiB. - - Returns: - ``(M,)`` int64 index of the closest key for each query row. - """ - N = keys.shape[0] - safe_chunk = max(1, (2 << 30) // (4 * max(N, 1))) - effective = min(chunk, safe_chunk) - M = query.shape[0] - idx = torch.empty(M, dtype=torch.long, device=query.device) - for s in range(0, M, effective): - e = min(s + effective, M) - idx[s:e] = torch.cdist(query[s:e], keys).argmin(dim=1) - return idx - - -# Core LUT tensor builders - - def build_native_grid_textures( coords: SamplingCoords, *, image_rotation_deg: float, exit_size: int ) -> tuple[torch.Tensor, torch.Tensor]: @@ -147,7 +83,8 @@ def build_lut_textures( exit_width: int, exit_height: int, chunk: int = 8192, - device="cuda", + *, + device: torch.device | str, ) -> tuple[torch.Tensor, torch.Tensor]: """Build direction and exit LUT tensors from a labelled set of sensor samples. @@ -226,9 +163,6 @@ def build_lut_textures( return dir_out, torch.stack([exit_u, exit_v], dim=2) -# EXR save helpers - - def save_lut_textures( direction_texture: torch.Tensor, exit_texture: torch.Tensor, @@ -248,9 +182,6 @@ def save_lut_textures( return os.path.abspath(dir_path), os.path.abspath(exit_path) -# USD prim authoring - - def apply_lens_lut_to_prim( prim: Usd.Prim, direction_texture_path: str, @@ -270,15 +201,12 @@ def apply_lens_lut_to_prim( ) -# NDC layout functions - - def samples_uv_cortical_disc( r_deg, theta_rad, fov_deg: float, cmf_a: float, - device="cuda", + device: torch.device | str, ) -> torch.Tensor: """Map samples to NDC using the cortical polar disc layout. @@ -295,3 +223,52 @@ def samples_uv_cortical_disc( u = (rho * th.cos() / (2.0 * rho_max) + 0.5).float() v = (-rho * th.sin() / (2.0 * rho_max) + 0.5).float() return torch.stack([u, v], dim=1) + + +def _t(x, dtype: torch.dtype, device) -> torch.Tensor: + """Convert array-like or tensor *x* to a ``torch.Tensor`` on *device*.""" + if isinstance(x, torch.Tensor): + return x.to(dtype=dtype, device=device) + return torch.as_tensor(np.asarray(x), dtype=dtype, device=device) + + +def _octahedral_decode( + width: int, + height: int, + device: torch.device | str, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Decode octahedral-LUT texel centres to unit directions (camera −Z convention). + + Returns: + Three ``(height, width)`` float64 tensors ``(dx, dy, dz)``. + """ + u = (torch.arange(width, dtype=torch.float64, device=device) + 0.5) / width + v = (torch.arange(height, dtype=torch.float64, device=device) + 0.5) / height + px = u.unsqueeze(0).expand(height, width) * 2.0 - 1.0 + py = v.unsqueeze(1).expand(height, width) * 2.0 - 1.0 + dz = 1.0 - px.abs() - py.abs() + sx = torch.sign(px) + sy = torch.sign(py) + dx = torch.where(dz <= 0.0, (1.0 - py.abs()) * sx, px) + dy = torch.where(dz <= 0.0, (1.0 - px.abs()) * sy, py) + n = torch.clamp((dx**2 + dy**2 + dz**2).sqrt(), min=1e-20) + return dx / n, dy / n, -dz / n + + +def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tensor: + """Chunked nearest-neighbour search via ``torch.cdist``. + + Chunk size is capped so the float32 distance matrix stays within 2 GiB. + + Returns: + ``(M,)`` int64 index of the closest key for each query row. + """ + N = keys.shape[0] + safe_chunk = max(1, (2 << 30) // (4 * max(N, 1))) + effective = min(chunk, safe_chunk) + M = query.shape[0] + idx = torch.empty(M, dtype=torch.long, device=query.device) + for s in range(0, M, effective): + e = min(s + effective, M) + idx[s:e] = torch.cdist(query[s:e], keys).argmin(dim=1) + return idx diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py index cd0eaa3f8407..0da4070dd53a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py @@ -20,13 +20,6 @@ GRID_STYLE = "warped_cartesian_as_grid" -class TorchBuffer(Protocol): - """Renderer buffer exposing a Torch view.""" - - @property - def torch(self) -> torch.Tensor: ... - - def buffer_tensor(value: torch.Tensor | TorchBuffer) -> torch.Tensor: """Get a renderer or public tensor without copying.""" return value if isinstance(value, torch.Tensor) else value.torch @@ -40,27 +33,6 @@ def proxy_outputs(outputs: Mapping[str, torch.Tensor | ProxyArray]) -> dict[str, } -def _require_spherical(coords: SamplingCoords) -> None: - if coords.field_geometry != "spherical": - raise ValueError(f"Foveated cameras sample spherical coordinates, got {coords.field_geometry!r}.") - - -def _angular_padding_boundary(coords: SamplingCoords) -> tuple[float, float]: - if coords.fov_type == "circular": - radius = 1.0 - elif coords.fov_type == "square": - radius = math.sqrt(2) - elif coords.fov_type == "wang": - corner = coords.cartesian.new_tensor([[1.0, 1.0]]) - radius = float(torch.linalg.vector_norm(coords.native_to_visual(corner)).item()) - else: - raise ValueError(f"Unsupported native grid footprint {coords.fov_type!r}.") - angle = radius * math.radians(coords.fov) / 2 - if angle >= math.pi: - raise ValueError("Spherical native grid footprint reaches the antipode; reduce FoV or use circular coverage.") - return radius, angle - - def bounded_angular_radius(radius: torch.Tensor, half_fov_rad: float) -> torch.Tensor: """Continue angular padding monotonically toward the antipode. @@ -182,3 +154,31 @@ def copy_grid_outputs( flat_source = tensor.reshape(tensor.shape[0], -1, tensor.shape[-1]) flat_target = target[name].view(tensor.shape[0], -1, tensor.shape[-1]) torch.index_select(flat_source, 1, indices, out=flat_target) + + +class TorchBuffer(Protocol): + """Renderer buffer exposing a Torch view.""" + + @property + def torch(self) -> torch.Tensor: ... + + +def _require_spherical(coords: SamplingCoords) -> None: + if coords.field_geometry != "spherical": + raise ValueError(f"Foveated cameras sample spherical coordinates, got {coords.field_geometry!r}.") + + +def _angular_padding_boundary(coords: SamplingCoords) -> tuple[float, float]: + if coords.fov_type == "circular": + radius = 1.0 + elif coords.fov_type == "square": + radius = math.sqrt(2) + elif coords.fov_type == "wang": + corner = coords.cartesian.new_tensor([[1.0, 1.0]]) + radius = float(torch.linalg.vector_norm(coords.native_to_visual(corner)).item()) + else: + raise ValueError(f"Unsupported native grid footprint {coords.fov_type!r}.") + angle = radius * math.radians(coords.fov) / 2 + if angle >= math.pi: + raise ValueError("Spherical native grid footprint reaches the antipode; reduce FoV or use circular coverage.") + return radius, angle diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index 0024802f9b84..d402e200bba3 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -40,6 +40,11 @@ from .foveated_camera_cfg import FoveatedCameraCfg +# Upper bound on ``batch * outputs * k`` elements per modal-pooling chunk. Each chunk holds about ten +# int64 tensors of this size, so peak scratch memory stays near 300 MB regardless of the batch size. +_MODAL_CHUNK_ELEMENTS = 2**22 + + def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCoords, int]: """Build the lowres (RGC / public output) SamplingCoords. @@ -100,40 +105,28 @@ def build_highres_coords(cfg: FoveatedCameraCfg, matched_res: int, device: str) ) -MODAL_POOL_MODE = "mode" -"""Pooling mode that takes the most common neighbour value (see :func:`pool_segmentation_buffer`).""" - -# Upper bound on ``batch * outputs * k`` elements per modal-pooling chunk. Each chunk holds about ten -# int64 tensors of this size, so peak scratch memory stays near 300 MB regardless of the batch size. -_MODAL_CHUNK_ELEMENTS = 2**22 - - def build_pooler( cfg: FoveatedCameraCfg, lowres: SamplingCoords, highres: SamplingCoords | None, device: str, - mode: str | None = None, ) -> tuple[KNNPoolingLayer | GridPoolingLayer | None, int | None]: - """Build a retinal pooling layer. Both coord sets must already be on ``device``. + """Build the retinal pooling layer of ``cfg.pool_mode``, which pools every output except segmentation. Both coord + sets must already be on ``device``. - If ``mode`` is None, uses ``cfg.pool_mode`` — the standard pooler for floating-point outputs. Modes are fovi's - (``"max"``, ``"avg"``, ``"sum"``, ``"gaussian"``). Modal pooling (``"mode"``) needs no pooler of its own: pass the - standard pooler's :func:`segmentation_neighbor_indices` to :func:`pool_segmentation_buffer`. + Segmentation pools by modal label over this pooler's neighbourhoods: pass :func:`segmentation_neighbor_indices` of + it to :func:`pool_segmentation_buffer`. """ if highres is None: return None, None from fovi.arch.pooling import build_retinal_pooler - mode = mode if mode is not None else cfg.pool_mode - if mode == MODAL_POOL_MODE: - raise ValueError("Modal pooling uses the standard pooler's neighbourhoods: see segmentation_neighbor_indices.") return build_retinal_pooler( highres, lowres, k=cfg.pool_k, - mode=mode, + mode=cfg.pool_mode, device=device, sample_cortex=cfg.pool_sample_cortex, gauss_sigma=cfg.pool_gauss_sigma, @@ -181,14 +174,12 @@ def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer) -> def is_segmentation_output(name: str) -> bool: - """Whether a sensor output key should be pooled with ``pool_int_mode`` (modal pooling by default). - - Uses a key-name heuristic (``"segmentation" in name``) rather than dtype, - since all IsaacLab segmentation variants — ``semantic_segmentation``, - ``instance_segmentation_fast``, ``instance_id_segmentation_fast`` — - produce class-like values whose per-pixel semantics are broken by - averaging, regardless of whether they're stored as int32 class IDs or - uint8 colorized RGBA. + """Whether a sensor output holds segmentation labels, which pool with ``pool_int_mode``, the modal label + (:func:`pool_segmentation_buffer`). + + Uses the key name (``"segmentation" in name``) rather than the dtype: every Isaac Lab segmentation variant + (``semantic_segmentation``, ``instance_segmentation_fast``, ``instance_id_segmentation_fast``) holds labels that + averaging would corrupt, whether stored as integer IDs or colorized RGBA. """ return "segmentation" in name diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py index 6f48b1df0ffb..83352835e9ef 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py @@ -5,10 +5,10 @@ """Camera tasks of Isaac Lab with a foveated camera whose gaze the policy moves. -Each task keeps its stock counterpart's scene, rewards, vision model and PPO settings. The camera becomes a foveated -camera at the same mount, with the same optics and, except for Cartpole, the same resolution: Cartpole's retina is -32 samples across instead of 96 pixels. The policy gets two gaze actions. A teacher's gaze -labels supervise those actions during training. +Each task keeps its stock counterpart's scene, vision model and PPO settings. The camera becomes a foveated camera at +the same mount, with the same optics and, except for Cartpole, the same resolution: Cartpole's retina is 32 samples +across instead of 96 pixels. The policy gets two gaze actions, whose noise is fixed, and a teacher's gaze labels +supervise them during training. The Kuka tasks' action penalty leaves out the gaze, so moving it is free. """ from . import cartpole, kuka_allegro # noqa: F401 (registers the tasks) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index a25719a4ca34..7109d6fd534d 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -14,7 +14,6 @@ import torch import warp as wp from fovi.sensing.projection import CameraModel -from isaaclab_fovi.mdp import angles_to_direction from isaaclab_fovi.mdp.gaze import ( GazeAction, gaze_reset_kernel, @@ -44,6 +43,12 @@ DEVICES = test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA) +def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3): up and left are positive.""" + tilt, pan = angles_deg.deg2rad().unbind(-1) + return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + + def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: """Gaze angles [deg] of camera-frame directions, shape (..., 3) to (..., 2): the reference for the kernels.""" x, y, z = direction.unbind(-1) @@ -119,13 +124,24 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device, rotation_deg): offset = torch.tensor([0.0, 0.0, 0.3]) gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.7 - # The torch path the kernel replaces: entity_point, then the teacher, then the labels and logs. + # The torch path the kernel replaces: the point fixed to each target, the teacher, then the labels and logs. points = targets + quat_apply(orientations, offset.expand(count, -1)) direction = torch.nn.functional.normalize(quat_apply_inverse(mount, points - positions), dim=-1) - # Gazes are measured in the upright image frame, which the frame carries into the physical camera's. + + def teachable(direction: torch.Tensor) -> torch.Tensor: + # Gazes are measured in the upright image frame, which the frame carries into the physical camera's. + desired = direction_to_angles(direction @ frame) / field_radius + return camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) + upright = direction @ frame desired = direction_to_angles(upright) / field_radius - valid = camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) + valid = teachable(direction) + # A target within 1e-4 rad of the image edge, the lens's widest angle or the gaze limit may land on either side + # in float32; every other target must agree exactly. + nudges = 1e-4 * torch.cat((torch.eye(3), -torch.eye(3))) + decisive = torch.stack( + [teachable(torch.nn.functional.normalize(direction + nudge, dim=-1)) == valid for nudge in nudges] + ).all(0) action = torch.where(valid[:, None], ((desired - gaze) / step).clamp(-1, 1), 0.0) looking = angles_to_direction(gaze * field_radius) error = torch.atan2(torch.cross(looking, upright, dim=-1).norm(dim=-1), (looking * upright).sum(-1)).rad2deg() @@ -142,7 +158,6 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device, rotation_deg): wp.from_torch(targets.to(device), dtype=wp.vec3f), wp.from_torch(orientations.to(device), dtype=wp.quatf), wp.vec3f(*offset.tolist()), - 1, wp.from_torch(positions.to(device), dtype=wp.vec3f), wp.from_torch(mount.to(device), dtype=wp.quatf), wp.from_torch((gaze * field_radius).to(device), dtype=wp.vec2f), @@ -156,9 +171,8 @@ def test_teacher_labels_kernel_matches_the_torch_labels(device, rotation_deg): block_dim=block, ) labels, log = labels.cpu(), log.cpu() - agree = (labels[:, 2] > 0.5) == valid - assert agree.float().mean() > 0.999 and valid.any() and (~valid).any() - torch.testing.assert_close(labels[agree], expected[agree], atol=1e-4, rtol=0) + assert valid[decisive].any() and (~valid[decisive]).any() and decisive.float().mean() > 0.99 + torch.testing.assert_close(labels[decisive], expected[decisive], atol=1e-4, rtol=0) labelled = labels[:, 2] > 0.5 assert float(log[1]) == pytest.approx(float(labelled.float().mean())) assert float(log[0]) == pytest.approx(float(error[labelled].mean()), rel=1e-4) @@ -181,9 +195,8 @@ def test_teacher_gaze_fixates_the_target_through_a_rolled_mount(rotation_deg): dim=(1, 1), inputs=[ wp.from_torch(direction, dtype=wp.vec3f), - wp.zeros(1, dtype=wp.quatf), + wp.from_torch(identity, dtype=wp.quatf), wp.vec3f(0.0, 0.0, 0.0), - 0, wp.zeros(count, dtype=wp.vec3f), wp.from_torch(identity, dtype=wp.quatf), wp.zeros(count, dtype=wp.vec2f), @@ -247,7 +260,7 @@ def test_process_actions_moves_the_gaze_by_the_supplied_actions(): term = object.__new__(GazeAction) term._env = SimpleNamespace(num_envs=num_envs, device="cpu", step_dt=0.5) term.cfg = GazeActionCfg(asset_name="camera", step_size=0.1, gaze_limit=1.0) - term.camera = camera + term._asset = camera term.field_radius_deg = 20.0 term._state = ProxyArray(wp.zeros(num_envs, dtype=wp.vec4f, device="cpu")) term._velocity = term._state.torch[:, 2:] @@ -308,14 +321,15 @@ def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): def test_fixed_mount_teacher_rejects_only_turns_after_capture(): - """A mount turned before the term captured it is the captured mount; a later turn makes it stale.""" + """The fixed-mount teacher aims from the captured mount while the camera has turned its mount as many times as + when the term captured it, and refuses once a later turn makes the capture stale.""" term = object.__new__(GazeAction) term.tracked_mount = False term._mount_turns = 2 term._fixed_mount = "captured" - term.camera = SimpleNamespace(mount_turns=2) + term._asset = SimpleNamespace(mount_turns=2) assert GazeAction.teacher_mounts(term) == "captured" - term.camera.mount_turns = 3 + term._asset.mount_turns = 3 with pytest.raises(RuntimeError, match="mount='tracked'"): GazeAction.teacher_mounts(term) diff --git a/source/isaaclab_fovi/test/test_backend_dispatch.py b/source/isaaclab_fovi/test/test_backend_dispatch.py index e9a6b1792735..f256eff15813 100644 --- a/source/isaaclab_fovi/test/test_backend_dispatch.py +++ b/source/isaaclab_fovi/test/test_backend_dispatch.py @@ -11,8 +11,14 @@ from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera +from isaaclab_newton.renderers import NewtonWarpRendererCfg +from isaaclab_ov.renderers import OVRTXRendererCfg from isaaclab_physx.renderers import IsaacRtxRendererCfg +import isaaclab.sim as sim_utils +from isaaclab.sensors.camera.camera import Camera +from isaaclab.sim import PinholeCameraCfg + pytestmark = pytest.mark.kitless @@ -50,3 +56,27 @@ def test_unknown_renderer_fails_explicitly() -> None: cfg = CameraSelection(RendererSelection("unknown")) with pytest.raises(ValueError, match="Unsupported foveated renderer"): FoveatedCamera(cfg) + + +@pytest.mark.parametrize( + ("renderer_cfg", "turns_pose_by_gaze"), + [(NewtonWarpRendererCfg(), True), (OVRTXRendererCfg(), True), (IsaacRtxRendererCfg(), False)], + ids=["newton_warp", "ovrtx", "isaac_rtx"], +) +def test_cameras_that_turn_their_pose_by_the_gaze_need_per_frame_pose_updates( + monkeypatch, renderer_cfg, turns_pose_by_gaze: bool +) -> None: + """Newton and OVRTX turn the rendered pose by the gaze in each pose update, so without pose updates the renderer + would never see the gaze; Isaac RTX writes the gaze into its camera prims instead.""" + monkeypatch.setattr(Camera, "__init__", lambda self, cfg: setattr(self, "stage", None)) + monkeypatch.setattr(Camera, "__del__", lambda self: None) + monkeypatch.setattr(FoveatedRTXCamera, "_prepare_projection", lambda self: None) + monkeypatch.setattr(sim_utils, "find_matching_prims", lambda *args: []) + cfg = FoveatedCameraCfg( + prim_path="/World/Camera", spawn=PinholeCameraCfg(), renderer_cfg=renderer_cfg, update_latest_camera_pose=False + ) + if turns_pose_by_gaze: + with pytest.raises(ValueError, match="update_latest_camera_pose=True"): + FoveatedCamera(cfg) + else: + assert not FoveatedCamera(cfg).turns_pose_by_gaze diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py index 2edbe3acda5e..c118bd709795 100644 --- a/source/isaaclab_fovi/test/test_camera_cfg.py +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -117,3 +117,22 @@ def test_explicit_camera_model_wins_over_the_spawn() -> None: def test_cameras_fovi_cannot_model_are_rejected(spawn, message: str) -> None: with pytest.raises(ValueError, match=message): resolve_camera_model(make_cfg(spawn=spawn)) + + +@pytest.mark.parametrize("mode", ["avg", "gaussian", "max", "sum"]) +def test_pool_mode_accepts_fovi_modes(mode: str) -> None: + assert make_cfg(pool_mode=mode).pool_mode == mode + + +@pytest.mark.parametrize("mode", ["modal", "median", "average"]) +def test_pool_mode_rejects_other_modes(mode: str) -> None: + with pytest.raises(ValueError, match="pool_mode must be one of"): + make_cfg(pool_mode=mode) + + +@pytest.mark.parametrize("mode", ["avg", "gaussian", "max", "sum", "mode"]) +def test_segmentation_pools_only_by_modal_label(mode: str) -> None: + """Pooling modes that would mix labels into ones no object has are rejected for segmentation.""" + assert make_cfg().pool_int_mode == "modal" + with pytest.raises(ValueError, match="pool_int_mode must be one of"): + make_cfg(pool_int_mode=mode) diff --git a/source/isaaclab_fovi/test/test_gaze_kernels.py b/source/isaaclab_fovi/test/test_gaze_kernels.py index 863270de94a0..b578ba5b07aa 100644 --- a/source/isaaclab_fovi/test/test_gaze_kernels.py +++ b/source/isaaclab_fovi/test/test_gaze_kernels.py @@ -5,12 +5,14 @@ """The gaze kernels agree with fovi's camera geometry and with the composition they replace.""" +from typing import Literal + import pytest import torch import warp as wp from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel, gaze_rotation -from isaaclab_fovi.sensors.calibrated_geometry import compose_rotations, convert_camera_frame_quaternion +from isaaclab_fovi.sensors.calibrated_geometry import compose_rotations from isaaclab_fovi.sensors.gaze_kernels import ( apply_gaze_indexed_kernel, apply_gaze_kernel, @@ -50,6 +52,39 @@ } +def convert_camera_frame_quaternion( + orientation: torch.Tensor, + *, + origin: Literal["world", "opengl"], + target: Literal["world", "opengl", "ros"], +) -> torch.Tensor: + """Reference conversion of world/OpenGL or OpenGL/ROS poses by exact fixed-basis quaternions. + + Args: + orientation: Camera quaternions in XYZW order, shape (..., 4). + origin: Input camera-frame convention. + target: Opposite world/OpenGL convention, or ROS for OpenGL input. + + Returns: + Normalized float32 quaternions, shape (..., 4). Quaternion sign may change. + """ + quat = orientation.float() + quat = quat / quat.norm(dim=-1, keepdim=True) + x, y, z, w = quat.unbind(-1) + # Right multiplication by exact fixed-basis quaternions, without allocating + # device constants or making the matrix round-trip sensitive to AMP/TF32. + if origin == "world" and target == "opengl": + components = (w + x - y + z, -w + x + y + z, -w - x - y + z, w - x + y + z) + elif origin == "opengl" and target == "world": + components = (-w + x + y - z, w - x + y - z, w + x + y + z, w + x - y - z) + elif origin == "opengl" and target == "ros": + # ROS flips the OpenGL Y/Z axes: right-multiply by a half-turn about X. + return torch.stack((w, z, -y, -x), dim=-1) + else: + raise ValueError(f"Unsupported camera conversion: {origin!r} to {target!r}") + return torch.stack(components, dim=-1) * 0.5 + + def _directions(count: int) -> torch.Tensor: generator = torch.Generator().manual_seed(0) directions = torch.randn(count, 3, generator=generator) diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index c5bc197d780e..29070b425e3b 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -5,12 +5,15 @@ """The Newton foveated camera's render layout and publication, on stand-in renderer buffers.""" +import logging +from dataclasses import asdict from types import SimpleNamespace import pytest import torch import warp as wp from fovi.sensing.coords import SamplingCoords +from fovi.sensing.projection import CameraModel from isaaclab_fovi.sensors import foveated_camera as base_camera from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions @@ -36,7 +39,7 @@ def new_camera() -> FoveatedNewtonCamera: """A Newton camera without its constructor: the state its constructor sets and the handles its destructor reads.""" camera = object.__new__(FoveatedNewtonCamera) camera._gaze_angles = camera._gaze_rotation = camera._visibility = camera._grid_publish = None - camera._published_shape = camera._pooler_int = camera._segmentation_neighbors = None + camera._published_shape = camera._segmentation_neighbors = None camera._initialize_handle = None camera._invalidate_initialize_handle = None camera._prim_deletion_handle = None @@ -88,7 +91,6 @@ def render(camera, env_mask): cmf_a_deg=0.591, pool_enabled=pooled, pool_mode="avg", - pool_int_mode="avg", pool_sample_cortex=False, image_rotation_deg=0, update_period=0.0, @@ -107,8 +109,9 @@ def render(camera, env_mask): expected = camera.renderer_rgba.reshape(2, len(ray_coords), 1, 4).clone() expected[:, ~ray_coords.valid_mask] = 0 if pooled: - # AdaptiveAvgPool1d maps the 4 * N_lo canonical samples to N_lo by averaging each run of four. - expected = expected.reshape(2, len(coords), 4, 1, 4).float().mean(dim=2).to(torch.uint8) + # AdaptiveAvgPool1d maps the 4 * N_lo canonical samples to N_lo by averaging each run of four, which the + # camera rounds to the nearest uint8 value. + expected = expected.reshape(2, len(coords), 4, 1, 4).float().mean(dim=2).round().to(torch.uint8) expected = coords.as_grid(expected.squeeze(2), sample_dim=1) torch.testing.assert_close(camera._data.output["rgba"].torch, expected, rtol=0, atol=0) # The published buffers are stable across frames, and rgb shares rgba's memory. @@ -166,6 +169,51 @@ def render(camera, env_mask): assert bool((published.torch[0] == 1.0).all()) and bool((published.torch[1] == 2.0).all()) +def test_sample_set_sensor_mask_follows_the_published_frame(monkeypatch) -> None: + """An environment that was not updated keeps its published samples and the sensor visibility that masked them.""" + coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu") + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 8)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: None) + monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (None, None)) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) + + def initialize_renderer(camera): + camera.renderer_depth = torch.ones((2, camera.cfg.height, camera.cfg.width, 1)) + camera._data = SimpleNamespace(output={"distance_to_camera": ProxyArray(wp.from_torch(camera.renderer_depth))}) + camera._render_data = SimpleNamespace(camera_rays=None) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", lambda camera, env_mask: None) + camera = new_camera() + camera.cfg = SimpleNamespace( + foveated_style="isotropic", + mask_to_sensor_fov=True, + camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), + spawn=None, + pool_enabled=False, + image_rotation_deg=0, + update_period=0.0, + data_types=["distance_to_camera"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + # The real gaze geometry, on stand-in pose buffers. + base_camera.FoveatedCamera._initialize_gaze(camera) + camera._view = SimpleNamespace(count=2, close=lambda: None) + camera._data.quat_w_ros = ProxyArray(wp.from_torch(torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2), dtype=wp.quatf)) + + # The second camera looks away from the physical camera's image, so it sees nothing. + camera.set_gaze_angles(torch.tensor([[0.0, 0.0], [0.0, 180.0]])) + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) + seen = camera.sensor_fov_valid_fraction.clone() + assert seen[0] > 0.5 and seen[1] == 0 + # Both look ahead now, but only the first camera's frame is published. + camera.set_gaze_angles(torch.zeros(2, 2)) + camera._update_buffers_impl(wp.array([True, False], dtype=wp.bool, device="cpu")) + assert not camera._data.output["distance_to_camera"].torch[1].any() + torch.testing.assert_close(camera.sensor_fov_valid_fraction, seen) + + def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatch) -> None: """A pooled camera's segmentation output holds each sample's majority label exactly, IDs above 2**24 included.""" coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") @@ -213,7 +261,6 @@ def render(camera, env_mask): update_period=0.0, pool_enabled=True, pool_mode="avg", - pool_int_mode="mode", pool_sample_cortex=False, image_rotation_deg=0, data_types=["rgba", "semantic_segmentation"], @@ -244,3 +291,64 @@ def test_native_grid_fractional_pool_resolution_validates_newton_tiles(size, val else: with pytest.raises(ValueError, match=f"{size}x{size}.*16x8"): FoveatedNewtonCamera._validate_native_render_layout(camera, 16, 8) + + +@pytest.mark.parametrize("style", ["warped_cartesian_as_grid", "isotropic"]) +@pytest.mark.parametrize("requested", [["rgba"], ["rgb"]]) +def test_pooled_rgb_is_the_view_of_pooled_rgba_whichever_is_requested(monkeypatch, style, requested) -> None: + """The renderer publishes rgb as a view of rgba when either is requested, and so do pooled grids and sample sets.""" + coords = SamplingCoords(60.0, 0.591, 16, style=style, field_geometry="spherical", device="cpu") + highres = coords.clone(resolution=32) + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr( + newton_camera, "build_pooler", lambda *args, **kwargs: (torch.nn.AdaptiveAvgPool1d(len(coords)), 4) + ) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) + + def initialize_renderer(camera): + camera.renderer_rgba = torch.zeros((2, camera.cfg.height, camera.cfg.width, 4), dtype=torch.uint8) + rgba = ProxyArray(wp.from_torch(camera.renderer_rgba)) + camera._data = SimpleNamespace( + output={"rgba": rgba, "rgb": ProxyArray(wp.from_torch(camera.renderer_rgba[..., :3]))} + ) + camera._render_data = SimpleNamespace(camera_rays=None) + camera._renderer = SimpleNamespace(cleanup=lambda render_data: None) + + def render(camera, env_mask): + camera.renderer_rgba.copy_(torch.tensor([10, 20, 30, 255], dtype=torch.uint8)) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) + camera = new_camera() + camera.cfg = SimpleNamespace( + foveated_style=style, + mask_to_sensor_fov=False, + update_period=0.0, + pool_enabled=True, + pool_mode="avg", + pool_sample_cortex=False, + image_rotation_deg=0, + data_types=requested, + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) + + rgb, rgba = camera._data.output["rgb"].torch, camera._data.output["rgba"].torch + assert rgb.any() + torch.testing.assert_close(rgb, rgba[..., :3], rtol=0, atol=0) + + +def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch, caplog) -> None: + """The retina sets a foveated camera's rays, so runtime intrinsics, such as a viewer's zoom sets, are skipped with + a warning rather than handed to the renderer, which would replace the rays with a pinhole's.""" + + def replace_rays(*args, **kwargs): + raise AssertionError("the stock setter replaces the renderer's rays") + + monkeypatch.setattr(newton_camera.Camera, "set_intrinsic_matrices", replace_rays) + camera = new_camera() + with caplog.at_level(logging.WARNING): + camera.set_intrinsic_matrices(torch.eye(3).repeat(2, 1, 1)) + assert "skipped a foveated camera" in caplog.text diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index aefdb643cf36..03ec14f6ebc6 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -5,7 +5,7 @@ """Dual-grid geometry and modality-specific pooling without a simulator.""" -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace import pytest import torch @@ -36,7 +36,7 @@ class SamplingConfig: spawn: PinholeCameraCfg = field(default_factory=lambda: PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0)) camera_model: dict[str, str | tuple[int, int] | tuple[float, ...]] | None = None retinal_window_reference_side: str = "short" - retinal_window_short_side_fraction: float = 1.0 + retinal_window_fraction: float = 1.0 foveated_res: int = 8 foveated_style: str = "isotropic" fov_type: str = "circular" @@ -192,7 +192,7 @@ def test_modal_pooling_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: cfg = SamplingConfig(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex) lowres, matched = build_lowres_coords(cfg, "cpu") highres = build_highres_coords(cfg, matched, "cpu") - fovi_max, k = build_pooler(cfg, lowres, highres, "cpu", mode="max") + fovi_max, k = build_pooler(replace(cfg, pool_mode="max"), lowres, highres, "cpu") # The camera takes the table from its standard pooler, whatever that pooler's mode. standard, _ = build_pooler(cfg, lowres, highres, "cpu") table = segmentation_neighbor_indices(standard) @@ -212,14 +212,6 @@ def test_modal_pooling_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: assert torch.equal(pooled[:, :, 0], reference_modal_pool(table, labels[:, :, 0])) -def test_modal_mode_builds_no_pooler_of_its_own() -> None: - cfg = SamplingConfig() - lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") - with pytest.raises(ValueError, match="segmentation_neighbor_indices"): - build_pooler(cfg, lowres, highres, "cpu", mode="mode") - - @pytest.mark.parametrize("device", DEVICES) def test_modal_neighbourhoods_stay_on_the_sensor_device(device: str) -> None: cfg = SamplingConfig() @@ -232,9 +224,17 @@ def test_modal_neighbourhoods_stay_on_the_sensor_device(device: str) -> None: @pytest.mark.parametrize("mode", ["avg", "gaussian", "max"]) -@pytest.mark.parametrize("sample_cortex", [False, True, "geodesic"]) -@pytest.mark.parametrize("style", ["warped_cartesian_as_grid", "warped_cartesian"]) -def test_native_grid_pooling_excludes_invalid_photoreceptors(mode, sample_cortex, style) -> None: +@pytest.mark.parametrize( + ("style", "sample_cortex"), + # Grid pooling takes fixed windows; only KNN pooling selects neighbours in the sample_cortex space. + [ + ("warped_cartesian_as_grid", False), + ("warped_cartesian", False), + ("warped_cartesian", True), + ("warped_cartesian", "geodesic"), + ], +) +def test_native_grid_pooling_excludes_invalid_photoreceptors(mode, style, sample_cortex) -> None: cfg = SamplingConfig( foveated_style=style, pool_mode=mode, diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index fcbb8b8e6ce8..6c4a1c6abf61 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -18,6 +18,7 @@ from isaaclab.sensors.camera.camera import Camera from isaaclab.sim import PinholeCameraCfg +from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless @@ -56,7 +57,8 @@ def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")), _native_grid=native_grid, _near_clip=torch.tensor([0.25, 0.5, 0.75]).view(-1, 1, 1, 1), - _texture_output={"distance_to_camera": texture}, + # The renderer-bound texture buffers are ProxyArrays, as the parent camera allocates them. + _texture_output={"distance_to_camera": ProxyArray(wp.from_torch(texture))}, _foveated_output={"distance_to_camera": torch.full((3, len(texels), 1, 1), -1.0)}, _extract_py=torch.tensor([py for py, _ in texels]), _extract_px=torch.tensor([px for _, px in texels]), diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 1f4576ce6d33..6a5799e96554 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -19,6 +19,7 @@ from isaaclab_fovi.sensors.pooling import build_lowres_coords from isaaclab.sensors.camera.camera import Camera +from isaaclab.sensors.camera.camera_data import CameraData from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.math import ( convert_camera_frame_orientation_convention, @@ -26,6 +27,7 @@ quat_apply, quat_from_matrix, ) +from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless @@ -49,7 +51,7 @@ def camera_config() -> SimpleNamespace: cmf_a_deg=2.5, spawn=None, retinal_window_reference_side="long", - retinal_window_short_side_fraction=0.75, + retinal_window_fraction=0.75, foveated_res=12, foveated_style="isotropic", fov_type="circular", @@ -92,13 +94,56 @@ def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None: self._device = device self._sampling_coords, _ = build_lowres_coords(self.cfg, device) self._sampling_coords_highres = None - self._data = SimpleNamespace( - quat_w_world=torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device).repeat(count, 1), - pos_w=torch.zeros(count, 3, device=device), - ) + # The camera's own pose buffers, at the identity orientation, with their world-to-ROS conversion. + self._data = CameraData() + self._data.create_buffers(count, device) + self._data.quat_w_world.torch[:, 3] = 1.0 + # Isaac RTX's behaviour; Newton and OVRTX turn the pose by the gaze in their pose update. + self._gaze_pose_reads_angles = False self._gaze_written = False self._initialize_gaze() + @property + def orientation(self) -> torch.Tensor: + """The camera's world orientation (x, y, z, w), world convention, shape (count, 4).""" + return self._data.quat_w_world.torch + + def __del__(self) -> None: + """The harness registers no simulator callbacks to release.""" + + +class PrimView: + """Camera prims under an unturned parent: their world poses are their local poses (x, y, z, w), OpenGL.""" + + def __init__(self, orientations: torch.Tensor) -> None: + self.count = len(orientations) + self.local = orientations.clone() + + def get_world_poses(self, indices=None): + ids = slice(None) if indices is None else wp.to_torch(indices).long() + orientations = self.local[ids].contiguous() + positions = torch.zeros(len(orientations), 3) + return ProxyArray(wp.from_torch(positions, dtype=wp.vec3f)), ProxyArray( + wp.from_torch(orientations, dtype=wp.quatf) + ) + + def get_local_poses(self): + return None, ProxyArray(wp.from_torch(self.local.clone(), dtype=wp.quatf)) + + def set_local_poses(self, *, orientations) -> None: + self.local = wp.to_torch(orientations).clone() + + +class RtxGazeHarness(GazeHarness, FoveatedRTXCamera): + """The Isaac RTX camera's prim-writing gaze on stand-in camera prims.""" + + def __init__(self, mount_opengl: torch.Tensor) -> None: + super().__init__(count=len(mount_opengl)) + self._view = PrimView(mount_opengl) + self._ALL_INDICES = wp.array(list(range(len(mount_opengl))), dtype=wp.int32, device="cpu") + self._base_local_orientation = matrix_from_quat(mount_opengl) + self.mount_turns = 0 + def gaze_direction(angles_deg: torch.Tensor) -> torch.Tensor: """OpenCV camera-frame unit direction of (tilt, pan) gaze angles [deg]: up and left are positive.""" @@ -147,7 +192,9 @@ def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, m angles[1::2] = 0 expected = matrix_from_quat(source.double()) @ conversion camera = GazeHarness(count=batch_size, device=device) - camera._data.quat_w_world = source + camera.orientation.copy_(source) + # The gaze turns the camera's own pose buffer in place. + source = camera.orientation camera._gaze_basis = camera._gaze_basis.to(device) camera.set_gaze_angles(angles) basis = camera._gaze_basis.double() @@ -178,14 +225,14 @@ def test_sensor_mask_checks_the_rendered_rays_of_a_rolled_mount(rotation_deg: fl model = CameraModel("pinhole", (80, 120), (60.0, 60.0, 45.0, 30.0)) camera = GazeHarness(camera_model=asdict(model), image_rotation_deg=rotation_deg) camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) - mount = camera._data.quat_w_world.clone() + mount = camera.orientation.clone() camera._apply_gaze_pose() # Rendered rays leave the turned camera along its OpenGL frame; express them in the mount's OpenGL frame. def opengl(orientation: torch.Tensor) -> torch.Tensor: return matrix_from_quat(convert_camera_frame_orientation_convention(orientation, "world", "opengl")) - turn = opengl(mount).transpose(-1, -2) @ opengl(camera._data.quat_w_world) + turn = opengl(mount).transpose(-1, -2) @ opengl(camera.orientation) coords = camera._sampling_coords rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) seen = (turn[:, None] @ rays[None, :, :, None]).squeeze(-1) * torch.tensor([1.0, -1.0, -1.0]) @@ -236,7 +283,7 @@ def test_mount_record_starts_at_the_current_pose() -> None: camera = GazeHarness() camera._gaze_pose_reads_angles = True mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) - camera._data.quat_w_world = mount.clone() + camera.orientation.copy_(mount) camera.gaze_angles expected = convert_camera_frame_orientation_convention(mount, "world", "ros") torch.testing.assert_close( @@ -248,7 +295,7 @@ def test_prim_writing_camera_reads_its_mount_until_a_gaze_is_written() -> None: """Isaac RTX writes the gaze into its prims, so its pose is the mount only until the first gaze.""" camera = GazeHarness() camera.gaze_angles - expected = convert_camera_frame_orientation_convention(camera._data.quat_w_world, "world", "ros") + expected = convert_camera_frame_orientation_convention(camera.orientation, "world", "ros") torch.testing.assert_close( matrix_from_quat(camera.ungazed_quat_w_ros()), matrix_from_quat(expected), atol=1e-6, rtol=0 ) @@ -257,19 +304,6 @@ def test_prim_writing_camera_reads_its_mount_until_a_gaze_is_written() -> None: camera.ungazed_quat_w_ros() -def test_newton_and_ovrtx_need_per_frame_pose_updates(monkeypatch) -> None: - """Without pose updates the renderer would never see the gaze while the sensor mask used it.""" - monkeypatch.setattr(Camera, "__init__", lambda self, cfg: None) - monkeypatch.setattr(FoveatedCamera, "__del__", lambda self, *args, **kwargs: None, raising=False) - cfg = SimpleNamespace(update_latest_camera_pose=False) - harness = object.__new__(GazeHarness) - harness._gaze_pose_reads_angles = True - with pytest.raises(ValueError, match="update_latest_camera_pose=True"): - FoveatedCamera.__init__(harness, cfg) - harness._gaze_pose_reads_angles = False - FoveatedCamera.__init__(harness, cfg) - - def test_sensor_mask_reuses_its_buffer_and_keeps_rows_that_were_not_updated() -> None: camera = GazeHarness() camera.cfg.mask_to_sensor_fov = True @@ -289,14 +323,14 @@ def test_sensor_mask_reuses_its_buffer_and_keeps_rows_that_were_not_updated() -> def test_pose_update_records_the_mount_before_the_gaze() -> None: camera = GazeHarness() mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) - camera._data.quat_w_world = mount.clone() + camera.orientation.copy_(mount) camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) camera._apply_gaze_pose() expected = convert_camera_frame_orientation_convention(mount, "world", "ros") torch.testing.assert_close( matrix_from_quat(camera._mount_quat_ros.torch), matrix_from_quat(expected), atol=1e-6, rtol=0 ) - assert not torch.allclose(camera._data.quat_w_world, mount) + assert not torch.allclose(camera.orientation, mount) def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pose() -> None: @@ -304,17 +338,17 @@ def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pos angles = torch.tensor([[6.0, -11.0], [-9.0, 17.0]]) camera.set_gaze_angles(angles) camera._apply_gaze_pose() - forward = quat_apply(camera._data.quat_w_world, torch.tensor([[1.0, 0.0, 0.0]]).expand(2, -1)) + forward = quat_apply(camera.orientation, torch.tensor([[1.0, 0.0, 0.0]]).expand(2, -1)) source = CameraModel(**camera.cfg.camera_model) # The world camera frame looks along +X with +Z up; OpenCV looks along +Z with +Y down. directions = gaze_direction(angles) expected = torch.stack((directions[:, 2], -directions[:, 0], -directions[:, 1]), -1) torch.testing.assert_close(forward, expected, atol=1e-6, rtol=1e-6) - assert torch.count_nonzero(camera._data.pos_w) == 0 - untouched = camera._data.quat_w_world[1].clone() - camera._data.quat_w_world[0] = torch.tensor([0.0, 0.0, 0.0, 1.0]) + assert torch.count_nonzero(camera._data.pos_w.torch) == 0 + untouched = camera.orientation[1].clone() + camera.orientation[0] = torch.tensor([0.0, 0.0, 0.0, 1.0]) camera._apply_gaze_pose([0]) - torch.testing.assert_close(camera._data.quat_w_world[1], untouched) + torch.testing.assert_close(camera.orientation[1], untouched) torch.testing.assert_close( camera._gaze_validity(), source.project( @@ -335,7 +369,7 @@ def test_renderer_ray_frame_matches_cv_frame() -> None: def test_gaze_pose_is_stable_inside_model_autocast(device: str) -> None: cameras = [GazeHarness(device=device), GazeHarness(device=device)] for camera in cameras: - camera._data.quat_w_world = torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(2, 1) + camera.orientation.copy_(torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(2, 1)) camera._gaze_basis = camera._gaze_basis.to(device) camera._gaze_rays = camera._gaze_rays.to(device) camera._gaze_identity = camera._gaze_identity.to(device) @@ -345,11 +379,11 @@ def test_gaze_pose_is_stable_inside_model_autocast(device: str) -> None: camera.set_gaze_angles(target) camera._apply_gaze_pose() camera._test_validity = camera._gaze_validity().clone() - assert torch.isfinite(cameras[1]._data.quat_w_world).all() - torch.testing.assert_close(cameras[1]._data.quat_w_world, cameras[0]._data.quat_w_world) + assert torch.isfinite(cameras[1].orientation).all() + torch.testing.assert_close(cameras[1].orientation, cameras[0].orientation) torch.testing.assert_close(cameras[1]._gaze_rotation.torch, cameras[0]._gaze_rotation.torch) - torch.testing.assert_close(cameras[1]._data.quat_w_world.norm(dim=-1), torch.ones(2, device=device)) + torch.testing.assert_close(cameras[1].orientation.norm(dim=-1), torch.ones(2, device=device)) torch.testing.assert_close(cameras[1]._test_validity, cameras[0]._test_validity) @@ -377,6 +411,31 @@ def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_ torch.testing.assert_close(written[1], written[0]) +def test_rtx_world_poses_are_the_mount_so_a_round_trip_keeps_mount_and_gaze(monkeypatch) -> None: + """Isaac RTX holds the gaze in its prims; its world poses still report the bare mount, as the other renderers' + do, so writing them back (as a viewer navigating the camera does) neither moves the mount nor doubles the gaze.""" + + def write_prims(camera, positions=None, orientations=None, env_ids=None, convention="ros"): + ids = slice(None) if env_ids is None else torch.as_tensor(env_ids) + camera._view.local[ids] = convert_camera_frame_orientation_convention(orientations, convention, "opengl") + + monkeypatch.setattr(Camera, "set_world_poses", write_prims) + mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) + camera = RtxGazeHarness(mount) + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) + gazed = camera._view.local.clone() + assert not torch.allclose(matrix_from_quat(gazed), matrix_from_quat(mount), atol=1e-3) + + _, orientations = camera.get_world_poses(env_ids=[1], convention="ros") + expected = convert_camera_frame_orientation_convention(mount[1:], "opengl", "ros") + torch.testing.assert_close(matrix_from_quat(orientations), matrix_from_quat(expected), atol=1e-6, rtol=0) + + _, orientations = camera.get_world_poses(convention="world") + camera.set_world_poses(orientations=orientations, convention="world") + torch.testing.assert_close(camera._base_local_orientation, matrix_from_quat(mount), atol=1e-6, rtol=0) + torch.testing.assert_close(matrix_from_quat(camera._view.local), matrix_from_quat(gazed), atol=1e-6, rtol=0) + + @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) def test_gaze_kernels_preserve_shared_stream_for_warp_capture(device: str) -> None: wp.init() From 79306508d008bb32603f088cf4db4b6444355aa7 Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 13:29:54 -0800 Subject: [PATCH 42/81] Add the fovi API docs and port the render example to launch_simulation - Add API reference pages for isaaclab_fovi.mdp, .rsl_rl and .sensors. - Port render_foveated.py to launch_simulation; its scene types are imported once Kit has started, as Kit must provide USD support first. - Remove the compare_outputs.py example. - Check the aggregate wheel's fovi task entry point directly, and test that conflicting entry points stop the wheel generator. --- docs/conf.py | 3 + docs/source/api/index.rst | 14 ++ .../source/api/lab_fovi/isaaclab_fovi.mdp.rst | 45 +++++ .../api/lab_fovi/isaaclab_fovi.rsl_rl.rst | 39 ++++ .../api/lab_fovi/isaaclab_fovi.sensors.rst | 41 ++++ .../test/cli/test_wheel_builder_metadata.py | 42 +++- .../isaaclab_fovi/examples/compare_outputs.py | 37 ---- .../isaaclab_fovi/examples/render_foveated.py | 182 +++++++++--------- 8 files changed, 268 insertions(+), 135 deletions(-) create mode 100644 docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst create mode 100644 docs/source/api/lab_fovi/isaaclab_fovi.rsl_rl.rst create mode 100644 docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst delete mode 100644 source/isaaclab_fovi/examples/compare_outputs.py diff --git a/docs/conf.py b/docs/conf.py index 8900d855f2b6..d47e5f0c79d8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -48,6 +48,8 @@ sys.path.insert(0, os.path.abspath("../source/isaaclab_ov/isaaclab_ov")) sys.path.insert(0, os.path.abspath("../source/isaaclab_visualizers")) sys.path.insert(0, os.path.abspath("../source/isaaclab_visualizers/isaaclab_visualizers")) +# Only the package root: the package's ``rsl_rl`` subpackage would shadow RSL-RL as a top-level module. +sys.path.insert(0, os.path.abspath("../source/isaaclab_fovi")) # -- Project information ----------------------------------------------------- @@ -300,6 +302,7 @@ def _read_pinned_versions() -> dict: "hydra.core.config_store", "omegaconf", "newton", + "fovi", ] # List of zero or more Sphinx-specific warning categories to be squelched (i.e., diff --git a/docs/source/api/index.rst b/docs/source/api/index.rst index 432381d286b0..13d3439f1eec 100644 --- a/docs/source/api/index.rst +++ b/docs/source/api/index.rst @@ -91,6 +91,20 @@ The following modules are available in the ``isaaclab_contrib`` extension: rl sensors +isaaclab_fovi extension +----------------------- + +The following modules are available in the ``isaaclab_fovi`` extension: + +.. currentmodule:: isaaclab_fovi + +.. autosummary:: + :toctree: lab_fovi + + mdp + rsl_rl + sensors + isaaclab_tasks extension ------------------------ diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst new file mode 100644 index 000000000000..0be111108358 --- /dev/null +++ b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst @@ -0,0 +1,45 @@ +isaaclab_fovi.mdp +================= + +.. automodule:: isaaclab_fovi.mdp + + .. rubric:: Classes + + .. autosummary:: + + GazeAction + GazeActionCfg + gaze_teacher_labels + + .. rubric:: Functions + + .. autosummary:: + + gaze_state + motor_action_l2 + +Actions +------- + +.. autoclass:: GazeAction + :members: + :show-inheritance: + +.. autoclass:: GazeActionCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Observations +------------ + +.. autofunction:: gaze_state + +.. autoclass:: gaze_teacher_labels + :show-inheritance: + +Rewards +------- + +.. autofunction:: motor_action_l2 diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.rsl_rl.rst b/docs/source/api/lab_fovi/isaaclab_fovi.rsl_rl.rst new file mode 100644 index 000000000000..4a8d7fc727d8 --- /dev/null +++ b/docs/source/api/lab_fovi/isaaclab_fovi.rsl_rl.rst @@ -0,0 +1,39 @@ +isaaclab_fovi.rsl_rl +==================== + +.. automodule:: isaaclab_fovi.rsl_rl + + .. rubric:: Classes + + .. autosummary:: + + GazeSupervisedPPO + GazeSupervisedPPOCfg + GazeGaussianDistribution + GazeGaussianDistributionCfg + +Gaze-Supervised PPO +------------------- + +.. autoclass:: GazeSupervisedPPO + :members: + :show-inheritance: + +.. autoclass:: GazeSupervisedPPOCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ + +Gaze Action Distribution +------------------------ + +.. autoclass:: GazeGaussianDistribution + :members: + :show-inheritance: + +.. autoclass:: GazeGaussianDistributionCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__ diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst b/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst new file mode 100644 index 000000000000..32c513aace16 --- /dev/null +++ b/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst @@ -0,0 +1,41 @@ +isaaclab_fovi.sensors +===================== + +.. automodule:: isaaclab_fovi.sensors + + .. rubric:: Classes + + .. autosummary:: + + FoveatedCamera + FoveatedCameraCfg + FoveatedNewtonCamera + FoveatedRTXCamera + + +Foveated Camera +--------------- + +.. autoclass:: FoveatedCamera + :members: + :show-inheritance: + +.. autoclass:: FoveatedCameraCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +Renderer Implementations +------------------------ + +Constructing :class:`FoveatedCamera` returns one of the following implementations, selected by the renderer in +:attr:`FoveatedCameraCfg.renderer_cfg`. + +.. autoclass:: FoveatedNewtonCamera + :members: + :show-inheritance: + +.. autoclass:: FoveatedRTXCamera + :members: + :show-inheritance: diff --git a/source/isaaclab/test/cli/test_wheel_builder_metadata.py b/source/isaaclab/test/cli/test_wheel_builder_metadata.py index 332fb87d1059..af6f2531ec5c 100644 --- a/source/isaaclab/test/cli/test_wheel_builder_metadata.py +++ b/source/isaaclab/test/cli/test_wheel_builder_metadata.py @@ -95,15 +95,41 @@ def test_wheel_console_delegates_to_the_full_isaaclab_cli(source_checkout_root: cli.assert_called_once_with() -def test_wheel_keeps_the_entry_points_of_bundled_packages(source_checkout_root: Path, generated_wheel_project: dict): +def test_wheel_keeps_the_entry_points_of_bundled_packages(generated_wheel_project: dict): """Bundled sub-packages keep their entry points, e.g. the ``isaaclab.tasks`` ones that register their tasks.""" - expected: dict[str, dict[str, str]] = {} - for package_pyproject in sorted((source_checkout_root / "source").glob("isaaclab*/pyproject.toml")): - with package_pyproject.open("rb") as f: - for group, entries in tomllib.load(f).get("project", {}).get("entry-points", {}).items(): - expected.setdefault(group, {}).update(entries) - assert expected, "no bundled package declares an entry point" - assert generated_wheel_project.get("entry-points") == expected + task_entry_points = generated_wheel_project.get("entry-points", {}).get("isaaclab.tasks", {}) + + assert task_entry_points.items() >= {"isaaclab_fovi": "isaaclab_fovi.tasks"}.items() + + +def test_wheel_builder_rejects_conflicting_entry_points(source_checkout_root: Path, tmp_path: Path): + """Two bundled packages that map one entry point name to different targets must stop the generator.""" + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "isaaclab-dev"\nrequires-python = ">=3.12"\ndependencies = []\n', encoding="utf-8" + ) + for package in ("isaaclab_a", "isaaclab_b"): + package_dir = tmp_path / "source" / package + package_dir.mkdir(parents=True) + (package_dir / "pyproject.toml").write_text( + f'[project.entry-points."isaaclab.tasks"]\nshared = "{package}.tasks"\n', encoding="utf-8" + ) + + result = subprocess.run( + [ + sys.executable, + str(source_checkout_root / "tools/wheel_builder/gen_pyproject.py"), + str(tmp_path / "pyproject.toml"), + str(tmp_path / "generated.toml"), + "3.0.0", + ], + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode != 0 + assert "Entry point 'shared' in group 'isaaclab.tasks' has conflicting targets" in result.stderr + assert not (tmp_path / "generated.toml").exists() def test_wheel_console_uses_compatibility_dispatcher(generated_wheel_project: dict): diff --git a/source/isaaclab_fovi/examples/compare_outputs.py b/source/isaaclab_fovi/examples/compare_outputs.py deleted file mode 100644 index 6b2146471d0c..000000000000 --- a/source/isaaclab_fovi/examples/compare_outputs.py +++ /dev/null @@ -1,37 +0,0 @@ -# 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 - -"""Compare RGB frames saved by render_foveated.py across installations.""" - -import argparse -import statistics - -import torch - - -def main() -> None: - """Report frame differences and observed frame times without setting thresholds.""" - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("reference") - parser.add_argument("candidate") - args = parser.parse_args() - reference = torch.load(args.reference, map_location="cpu", weights_only=True) - candidate = torch.load(args.candidate, map_location="cpu", weights_only=True) - reference_frames, candidate_frames = reference["frames"], candidate["frames"] - if reference_frames.shape != candidate_frames.shape: - raise ValueError(f"Frame shapes differ: {tuple(reference_frames.shape)} vs {tuple(candidate_frames.shape)}") - if reference_frames.dtype != candidate_frames.dtype: - raise ValueError(f"Frame dtypes differ: {reference_frames.dtype} vs {candidate_frames.dtype}") - torch.testing.assert_close(reference["sampling_coordinates"], candidate["sampling_coordinates"]) - difference = (reference_frames.float() - candidate_frames.float()).abs() - print(f"RGB absolute error: mean={difference.mean().item()}, max={difference.max().item()}") - for label, snapshot in (("reference", reference), ("candidate", candidate)): - durations = snapshot["frame_seconds"] - if durations: - print(f"{label} median warm frame seconds: {statistics.median(durations)}") - - -if __name__ == "__main__": - main() diff --git a/source/isaaclab_fovi/examples/render_foveated.py b/source/isaaclab_fovi/examples/render_foveated.py index 10bf864fe061..0e1f47a9a052 100644 --- a/source/isaaclab_fovi/examples/render_foveated.py +++ b/source/isaaclab_fovi/examples/render_foveated.py @@ -16,10 +16,10 @@ import argparse import math import time -import traceback from pathlib import Path +from types import SimpleNamespace -from isaaclab.app import AppLauncher +from isaaclab.app import add_launcher_args, launch_simulation parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--backend", choices=("newton", "rtx"), required=True) @@ -29,42 +29,24 @@ parser.add_argument("--cmf_a_deg", type=float, default=None, help="CMF constant [deg]; a large value is non-foveated.") parser.add_argument("--steps", type=int, default=8) parser.add_argument("--output", type=Path, help="Save the RGB frames and warm frame timings.") -AppLauncher.add_app_launcher_args(parser) +add_launcher_args(parser) +# Camera output is required, but the example does not need an interactive visualizer. +parser.set_defaults(enable_cameras=True) args = parser.parse_args() if args.steps <= 0: parser.error("--steps must be positive") if args.resolution <= 0: parser.error("--resolution must be positive") -args.enable_cameras = True -launcher = AppLauncher(args) +import torch +import warp as wp +from isaaclab_fovi.sensors import FoveatedCameraCfg -def main() -> None: - """Render RGB of a static cube while the gaze moves.""" - # Isaac Sim plugins must be available before importing simulator-bound types. - import torch - import warp as wp - from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg - - import isaaclab.sim as sim_utils - from isaaclab.assets import AssetBaseCfg, RigidObjectCfg - from isaaclab.scene import InteractiveScene, InteractiveSceneCfg - from isaaclab.terrains import TerrainImporterCfg - from isaaclab.utils.configclass import configclass +import isaaclab.sim as sim_utils - if args.backend == "newton": - from isaaclab_newton.physics.mjwarp_solver_cfg import MJWarpSolverCfg - from isaaclab_newton.physics.newton_manager_cfg import NewtonCfg - from isaaclab_newton.renderers import NewtonWarpRendererCfg - - physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) - renderer = NewtonWarpRendererCfg(render_order="pixel_priority") - else: - from isaaclab_physx.physics.physx_manager_cfg import PhysxCfg - from isaaclab_physx.renderers import IsaacRtxRendererCfg - physics = PhysxCfg() - renderer = IsaacRtxRendererCfg() +def make_camera_cfg(renderer) -> FoveatedCameraCfg: + """The foveated camera, looking at the cube through the selected lens.""" if args.lens == "pinhole": # An ideal pinhole with a 60 degree field of view. @@ -93,70 +75,90 @@ def main() -> None: ) if args.cmf_a_deg is not None: camera_cfg.cmf_a_deg = args.cmf_a_deg + return camera_cfg + + +def main() -> None: + """Render RGB of a static cube while the gaze moves.""" + if args.backend == "newton": + from isaaclab_newton.physics.mjwarp_solver_cfg import MJWarpSolverCfg + from isaaclab_newton.physics.newton_manager_cfg import NewtonCfg + from isaaclab_newton.renderers import NewtonWarpRendererCfg + + physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) + renderer = NewtonWarpRendererCfg(render_order="pixel_priority") + else: + from isaaclab_physx.physics.physx_manager_cfg import PhysxCfg + from isaaclab_physx.renderers import IsaacRtxRendererCfg + + physics = PhysxCfg() + renderer = IsaacRtxRendererCfg() - @configclass - class SceneCfg(InteractiveSceneCfg): - """A red cube on the ground in front of the camera.""" - - ground = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") - light = AssetBaseCfg(prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=500.0)) - cube = RigidObjectCfg( - prim_path="{ENV_REGEX_NS}/Cube", - spawn=sim_utils.CuboidCfg( - size=(0.5, 0.5, 0.5), - rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), - mass_props=sim_utils.MassCfg(mass=1.0), - collision_props=sim_utils.UsdPhysicsCollisionCfg(), - visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.8, 0.2, 0.1)), - ), - init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 2.0, 0.25)), + sim_cfg = sim_utils.SimulationCfg(device=args.device, physics=physics) + # The launcher starts the runtime that the physics and the camera's renderer need. + with launch_simulation(SimpleNamespace(sim=sim_cfg, renderer=renderer), args): + # Scene types load USD support, which Kit must provide first. + from isaaclab.assets import AssetBaseCfg, RigidObjectCfg + from isaaclab.scene import InteractiveScene, InteractiveSceneCfg + from isaaclab.terrains import TerrainImporterCfg + from isaaclab.utils.configclass import configclass + + @configclass + class SceneCfg(InteractiveSceneCfg): + """A red cube on the ground in front of the camera.""" + + ground = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") + light = AssetBaseCfg(prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=500.0)) + cube = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Cube", + spawn=sim_utils.CuboidCfg( + size=(0.5, 0.5, 0.5), + rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(), + mass_props=sim_utils.MassCfg(mass=1.0), + collision_props=sim_utils.UsdPhysicsCollisionCfg(), + visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.8, 0.2, 0.1)), + ), + init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 2.0, 0.25)), + ) + eye = make_camera_cfg(renderer) + + sim_utils.create_new_stage() + sim = sim_utils.SimulationContext(sim_cfg) + scene = InteractiveScene(SceneCfg(num_envs=1, env_spacing=4.0)) + camera = scene["eye"] + sim.reset() + + frame_seconds: list[float] = [] + frames: list[torch.Tensor] = [] + for step in range(args.steps): + # Gaze (tilt, pan) [deg] from the optical axis: look ahead, then 8 degrees to the right. + pan = (0.0, -8.0, -8.0, 0.0)[step % 4] + camera.set_gaze_angles(torch.tensor([[0.0, pan]], device=sim.device)) + wp.synchronize_device(sim.device) + start = time.perf_counter() + sim.step() + camera.update(sim.get_physics_dt(), force_recompute=True) + wp.synchronize_device(sim.device) + if step > 0: + frame_seconds.append(time.perf_counter() - start) + rgb = camera.data.output["rgb"].torch + if args.output is not None: + frames.append(rgb.clone()) + print( + f"{args.backend}: RGB shape={tuple(rgb.shape)}, dtype={rgb.dtype}, warm frame seconds={frame_seconds}", + flush=True, ) - eye = camera_cfg - - sim_utils.create_new_stage() - sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(device=args.device, physics=physics)) - scene = InteractiveScene(SceneCfg(num_envs=1, env_spacing=4.0)) - camera: FoveatedCamera = scene["eye"] - sim.reset() - - frame_seconds: list[float] = [] - frames: list[torch.Tensor] = [] - for step in range(args.steps): - # Gaze (tilt, pan) [deg] from the optical axis: look ahead, then 8 degrees to the right. - pan = (0.0, -8.0, -8.0, 0.0)[step % 4] - camera.set_gaze_angles(torch.tensor([[0.0, pan]], device=sim.device)) - wp.synchronize_device(sim.device) - start = time.perf_counter() - sim.step() - camera.update(sim.get_physics_dt(), force_recompute=True) - wp.synchronize_device(sim.device) - if step > 0: - frame_seconds.append(time.perf_counter() - start) - rgb = camera.data.output["rgb"].torch if args.output is not None: - frames.append(rgb.clone()) - print( - f"{args.backend}: RGB shape={tuple(rgb.shape)}, dtype={rgb.dtype}, warm frame seconds={frame_seconds}", - flush=True, - ) - if args.output is not None: - torch.save( - { - "frames": torch.stack(frames).cpu(), - "sampling_coordinates": camera.sampling_coords.cartesian.cpu(), - "frame_seconds": frame_seconds, - }, - args.output, - ) - sim.stop() + torch.save( + { + "frames": torch.stack(frames).cpu(), + "sampling_coordinates": camera.sampling_coords.cartesian.cpu(), + "frame_seconds": frame_seconds, + }, + args.output, + ) + sim.stop() if __name__ == "__main__": - try: - main() - except Exception: - # Kit shutdown can terminate before Python prints an uncaught exception. - traceback.print_exc() - raise - finally: - launcher.app.close() + main() From 3362afe5d2707120aca21d444751b62c54535add Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 13:40:23 -0800 Subject: [PATCH 43/81] Explain that set_intrinsic_matrices leaves a foveated camera as configured --- .../isaaclab_fovi/sensors/foveated_camera.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 016e9c4eb9f9..a762eaa43ac0 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -260,8 +260,13 @@ def set_world_poses_from_view(self, eyes, targets, env_ids=None): self.mount_turns += 1 def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): - """Skip runtime intrinsics with a warning, as stock cameras with an OpenCV lens model do: the retina and - :attr:`camera_model` define a foveated camera's rays, and the renderer must keep rendering them. + """Keep the camera as configured and log a warning. + + A foveated camera's projection comes from its retina and :attr:`camera_model`, which pinhole intrinsics + cannot describe, so this call changes nothing: the rendered rays and the reported intrinsic matrices stay as + configured. Stock cameras with an OpenCV lens model handle the call the same way. To change the projection, + configure :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.camera_model` (or ``spawn``) and + :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.cmf_a_deg`. Args are those of :meth:`isaaclab.sensors.Camera.set_intrinsic_matrices`. """ From d926df300c6403acbafa31680e608cf71356ee23 Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 13:56:55 -0800 Subject: [PATCH 44/81] Address the fifth review round on the foveated camera - Count a mount turn only when set_world_poses changes a selected camera's mount, so writing back the reported pose leaves the fixed-mount teacher valid. - Warn callers of set_intrinsic_matrices with a UserWarning. - Read near clips only for OVRTX distance_to_camera output. - Point fov_type and radius_norm to fovi's documentation instead of a square-coverage page; the fixed-mount docs say the teacher raises. - Follow the module member order, type the RTX texture buffers as ProxyArray, and trim stale comments. - Build the pooling tests from FoveatedCameraCfg and remove tests that only exercised test helpers or replayed other tests. --- source/isaaclab_fovi/docs/README.md | 7 ++- source/isaaclab_fovi/docs/square_foveated.md | 32 ----------- .../isaaclab_fovi/mdp/gaze_cfg.py | 3 +- .../sensors/calibrated_geometry.py | 18 +++--- .../isaaclab_fovi/sensors/foveated_camera.py | 29 +++++++--- .../sensors/foveated_camera_cfg.py | 12 +++- .../sensors/foveated_rtx_camera.py | 25 ++++++--- .../isaaclab_fovi/sensors/lens_lut.py | 10 +--- .../isaaclab_fovi/tasks/active_gaze.py | 18 +++--- .../isaaclab_fovi/tasks/cartpole/env_cfg.py | 22 ++++---- source/isaaclab_fovi/test/test_active_gaze.py | 9 --- .../isaaclab_fovi/test/test_newton_buffers.py | 21 +++---- source/isaaclab_fovi/test/test_pooling.py | 56 +++++++++---------- source/isaaclab_fovi/test/test_rtx_camera.py | 2 + .../test/test_spherical_geometry.py | 49 +++++++++++----- .../test/test_square_native_grid.py | 34 +---------- 16 files changed, 160 insertions(+), 187 deletions(-) delete mode 100644 source/isaaclab_fovi/docs/square_foveated.md diff --git a/source/isaaclab_fovi/docs/README.md b/source/isaaclab_fovi/docs/README.md index f360d30b9a22..27b217a382d7 100644 --- a/source/isaaclab_fovi/docs/README.md +++ b/source/isaaclab_fovi/docs/README.md @@ -113,7 +113,7 @@ physical camera's image at the current gaze. radii (half the retina's field of view) per step, within `gaze_limit` field radii of the optical axis. Make it the last action term. With the default `mount="fixed"` the teacher aims from the orientation the camera has when the - action is created, and turning the mount raises; `mount="tracked"` lets the + action is created, and raises if the mount turns later; `mount="tracked"` lets the camera ride a moving body, such as a turning head, and the teacher follows each camera's current mount (Newton or OVRTX). @@ -161,8 +161,9 @@ package, so they are available from a source checkout. - Sample-set styles such as `foveated_style="isotropic"` publish `(num_envs, num_samples, 1, channels)`. Log-polar styles are not available, because fovi does not support them in spherical coordinates. -- `fov_type` and `radius_norm` select circular or square coverage. See - [square-foveated rendering](square_foveated.md). +- `fov_type` (`"circular"`, `"square"` or `"wang"`) and `radius_norm` set + the field the retina covers; they are passed to fovi's `SamplingCoords`, + whose [documentation](https://nblauch.github.io/fovi/docs/) describes them. - `pool_enabled=True` renders a denser grid and pools it to the output grid. ## Example diff --git a/source/isaaclab_fovi/docs/square_foveated.md b/source/isaaclab_fovi/docs/square_foveated.md deleted file mode 100644 index e2f1db96d12e..000000000000 --- a/source/isaaclab_fovi/docs/square_foveated.md +++ /dev/null @@ -1,32 +0,0 @@ -# Square-foveated rendering - -By default the foveated grid covers a circular field: cells outside the circle -are masked. A square field uses every cell. Both the RTX and Newton foveated -cameras accept this configuration: - -```python -FoveatedCameraCfg( - prim_path="/World/Camera", - foveated_style="warped_cartesian_as_grid", - radius_norm=float("inf"), - fov_type="square", - foveated_res=64, -) -``` - -`fovi` owns the concentric-square mapping and its analytic inverse. The lens -lookup textures and the gaze use that geometry. The published image -is upright, `(num_envs, height, width, channels)`, and RGB, depth and -segmentation keep their usual dtypes. - -No cell is masked by the sensor footprint. With `mask_to_sensor_fov=True`, -samples outside the physical camera's image are still zeroed. - -The camera samples spherical field coordinates only; the lens lookup rejects -planar coordinates. The grid keeps its two-dimensional topology; "square" -refers to the region of the visual field the grid covers. -The mapping is not smooth across the diagonals of the square, which matters -when a temporal filter such as DLSS is applied to the rendered grid. - -A policy that consumes the image has to be configured with the same field -geometry, `radius_norm` and resolution as the camera. diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py index 03869532e85a..2d0c0eda2c7d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py @@ -32,7 +32,8 @@ class GazeActionCfg(ActionTermCfg): random_reset: bool = False """Start episodes at a random gaze the camera sees; otherwise on the optical axis.""" mount: str = "fixed" - """``"fixed"``: the camera keeps the orientation it has when the action is created, and turning its mount raises. + """``"fixed"``: the teacher aims from the orientation the camera has when the action is created, and raises if the + mount turns later. The gaze itself always moves relative to the camera's current mount. ``"tracked"``: the camera may ride a moving body, and the teacher follows each camera's current mount, so the gaze adds to hardware gaze such as a turning head. Tracking needs a camera whose pose update turns the gaze (Newton or OVRTX).""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index 38298fef7800..1d5edc707b35 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -19,14 +19,6 @@ The scale is arbitrary: the retinal window and the gaze are angles, so neither depends on it.""" -class SamplingGeometryConfig(Protocol): - camera_model: CameraCalibration | None - cmf_a_deg: float - retinal_window_reference_side: str - retinal_window_fraction: float - spawn: Any - - def camera_model_from_spawn(spawn: Any) -> CameraCalibration: """Describe the camera that the spawn configuration creates as :class:`CameraModel` fields. @@ -116,3 +108,13 @@ def compose_rotations(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor: training process enables reduced-precision matrix multiplication. """ return (left[..., :, :, None] * right[..., None, :, :]).sum(dim=-2) + + +class SamplingGeometryConfig(Protocol): + """The configuration fields that place the retina in the physical camera.""" + + camera_model: CameraCalibration | None + cmf_a_deg: float + retinal_window_reference_side: str + retinal_window_fraction: float + spawn: Any diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index a762eaa43ac0..ebd03ca8fb33 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -7,8 +7,8 @@ from __future__ import annotations -import logging import math +import warnings from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING @@ -17,7 +17,7 @@ from fovi.sensing.projection import CameraModel from isaaclab.sensors.camera.camera import Camera -from isaaclab.utils.math import convert_camera_frame_orientation_convention +from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_error_magnitude from isaaclab.utils.warp import ProxyArray from .calibrated_geometry import resolve_camera_model, retinal_directions @@ -43,7 +43,8 @@ if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg -logger = logging.getLogger(__name__) +MOUNT_TURN_TOLERANCE_RAD = 1e-5 +"""Smallest change of a camera's mount orientation [rad] that counts as a turn; smaller ones are float rounding.""" OPENGL_TO_ROS_AXES = (1.0, -1.0, -1.0) """Axis signs between OpenGL camera-frame directions (x right, y up, -z forward) and ROS ones (x right, y down).""" @@ -245,9 +246,11 @@ def set_world_poses(self, positions=None, orientations=None, env_ids=None, conve Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. """ + # The teachers read the camera's live position, so only a write that turns a selected mount counts; writing + # back the poses that get_world_poses reports does not. + turned = orientations is not None and self._turns_mount(orientations, env_ids, convention) super().set_world_poses(positions, orientations, env_ids, convention) - # The teachers read the camera's live position, so only a turned mount counts. - if orientations is not None: + if turned: self.mount_turns += 1 def set_world_poses_from_view(self, eyes, targets, env_ids=None): @@ -260,7 +263,7 @@ def set_world_poses_from_view(self, eyes, targets, env_ids=None): self.mount_turns += 1 def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): - """Keep the camera as configured and log a warning. + """Keep the camera as configured and warn the caller. A foveated camera's projection comes from its retina and :attr:`camera_model`, which pinhole intrinsics cannot describe, so this call changes nothing: the rendered rays and the reported intrinsic matrices stay as @@ -270,7 +273,12 @@ def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): Args are those of :meth:`isaaclab.sensors.Camera.set_intrinsic_matrices`. """ - logger.warning("set_intrinsic_matrices() skipped a foveated camera; its retina and camera_model set its rays.") + warnings.warn( + "set_intrinsic_matrices() leaves a foveated camera as configured: its retina and camera_model set its" + " projection.", + UserWarning, + stacklevel=2, + ) def _initialize_gaze(self) -> None: """Prepare the gaze geometry: the rendered rays in the physical camera's frame and the pose conversions.""" @@ -369,6 +377,13 @@ def _apply_gaze_pose( launch.set_dim(len(env_ids)) launch.launch(warp_stream(device)) + def _turns_mount(self, orientations, env_ids, convention: str) -> bool: + """Whether writing ``orientations`` would turn any selected camera's mount, compared with its current one.""" + _, current = self.get_world_poses(env_ids, convention=convention) + requested = self._as_device_tensor(orientations, 4).to(current.dtype).expand_as(current) + requested = torch.nn.functional.normalize(requested, dim=-1) + return bool((quat_error_magnitude(current, requested) > MOUNT_TURN_TOLERANCE_RAD).any()) + def _turned_by_view(self, eyes, targets) -> torch.Tensor: """Which rows :meth:`set_world_poses_from_view` turns: the base method skips an eye equal to its target.""" return (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0 diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index df6181fb6ea1..6c0c64f38b79 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -53,7 +53,7 @@ class FoveatedCameraCfg(CameraCfg): class_type: type[FoveatedCamera] | str = "{DIR}.foveated_camera:FoveatedCamera" - # -- Foveation parameters (no img_height/img_width/fixation_size) -------- + # -- Foveation parameters ------------------------------------------------ cmf_a_deg: float = 0.591 """Cortical magnification constant *a* of ``M(e) = 1 / (e + a)`` [deg]. @@ -91,10 +91,16 @@ class FoveatedCameraCfg(CameraCfg): the same ray.""" fov_type: str = "circular" - """Visual footprint; circular is the default for native warped grids.""" + """Region of the visual field the retina covers: ``"circular"``, ``"square"`` or ``"wang"``. + + Passed to :class:`fovi.sensing.coords.SamplingCoords`; see the `fovi documentation + `__.""" radius_norm: float = 2.0 - """Warped-Cartesian shell norm: 2.0 for circular shells, infinity for square shells.""" + """Norm of the warped-Cartesian sampling shells: 2.0 for circular shells, infinity for square ones. + + Passed to :class:`fovi.sensing.coords.SamplingCoords`; see the `fovi documentation + `__.""" isotropic_plotting_type: str = "v1like" """Plotting-space mapping passed to :class:`SamplingCoords` for isotropic diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 80e09562acaf..2db28d7d2d5c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -43,6 +43,8 @@ from .pooling import build_highres_coords, build_lowres_coords, build_pooler if TYPE_CHECKING: + from isaaclab.utils.warp import ProxyArray + from .foveated_camera_cfg import FoveatedCameraCfg logger = logging.getLogger(__name__) @@ -72,7 +74,7 @@ def __init__(self, cfg: FoveatedCameraCfg): " gaze. Disable async_rendering or mask_to_sensor_fov." ) # The parent ``Camera`` allocates the renderer-bound texture buffers; the published ones follow from them. - self._texture_output: dict[str, torch.Tensor] = {} + self._texture_output: dict[str, ProxyArray] = {} self._foveated_output: dict[str, torch.Tensor] = {} self._pooled_output: dict[str, torch.Tensor] | None = None # The projection sets the texture size on the configuration before the parent allocates for it; the caller's @@ -244,13 +246,20 @@ def _prepare_projection(self) -> None: def _initialize_impl(self) -> None: tw, th = self._texture_width, self._texture_height - prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) - # OVRTX's lookup-table range is measured from each camera's near-clipped ray origin. - near_clips = [self._near_clipping_distance(prim) for prim in prims] + # OVRTX measures distance_to_camera from each camera's near-clipped ray origin, so it needs the near clips. + self._offset_distance = ( + self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self.cfg.data_types + ) + near_clips = None + if self._offset_distance: + prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) + near_clips = [self._near_clipping_distance(prim) for prim in prims] super()._initialize_impl() - self._near_clip = torch.tensor(near_clips, dtype=torch.float32, device=self._device).view(-1, 1, 1, 1) + self._near_clip = None + if near_clips is not None: + self._near_clip = torch.tensor(near_clips, dtype=torch.float32, device=self._device).view(-1, 1, 1, 1) # OVRTX owns its runtime; Kit extensions belong only to Isaac RTX. if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": @@ -277,8 +286,7 @@ def _initialize_impl(self) -> None: textures = {name: tex.torch for name, tex in self._texture_output.items()} # A native grid texture already holds the samples in order, so one kernel per output masks it and lays it # out. OVRTX's camera distance needs its near-plane offset first, and keeps the step-by-step path. - offset_distance = self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in textures - fused = self._native_grid and self._pooler is None and not offset_distance + fused = self._native_grid and self._pooler is None and not self._offset_distance if fused: count = self._num_ray_samples samples = {name: tex.reshape(tex.shape[0], count, tex.shape[-1]) for name, tex in textures.items()} @@ -390,7 +398,6 @@ def _extract_foveated_samples(self, env_mask: wp.array): """Extract the updated environments' per-sample values from the rendered 2D textures into the (B, N, 1, C) buffers; the other environments keep their last samples.""" updated = wp.to_torch(env_mask)[:, None, None, None] - offset_distance = self.cfg.renderer_cfg.renderer_type == "ovrtx" for name in self._texture_output: if name == "rgb" and "rgba" in self._texture_output: continue # rgba alias @@ -401,7 +408,7 @@ def _extract_foveated_samples(self, env_mask: wp.array): samples = tensor.reshape_as(fov) else: samples = tensor[:, self._extract_py, self._extract_px, :].unsqueeze(2) - if offset_distance and name == "distance_to_camera": + if self._offset_distance and name == "distance_to_camera": # OVRTX measures the distance from the near-clipped ray origin. samples = samples + self._near_clip.to(samples.dtype) fov.copy_(torch.where(updated, samples, fov)) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index 97b055de36a9..510a6d393139 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -123,14 +123,8 @@ def build_lut_textures( k_nn = _nn_chunk(texel_uv, uv_t, chunk) dir_out.reshape(-1, 3)[:] = dirs_t[k_nn] - # Exit texture. - # The exit texture is an octahedral inverse map: given a ray direction - # (encoded over [0,1]² via octahedral projection), it returns the sensor - # NDC (u, v) of the nearest foveated sample. The octahedral grid covers - # the full hemisphere, but only texels whose decoded direction falls within - # the camera's FOV (r ≤ max_r) are populated; the rest hold the invalid UV (-1, -1), as in native-grid LUTs. - # Resolution (exit_width × exit_height) should be large enough to resolve - # individual samples — typically 4× the direction texture dimension. + # Exit texture: only texels whose direction lies within the samples' field (r <= max_r) map to a sample; the rest + # hold the invalid UV (-1, -1), as in native-grid LUTs, so rays outside the field never reach the fovea. d = dirs_t.to(torch.float64) r_s = (torch.atan2((d[:, 0] ** 2 + d[:, 1] ** 2).sqrt(), (-d[:, 2]).clamp(min=1e-20)) * (180.0 / math.pi)).float() th_s = torch.atan2(d[:, 1], d[:, 0]).float() diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py index ca53cdcc826b..8ef97d0e6655 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py @@ -54,6 +54,15 @@ def select_presets(options: PresetCfg, names) -> PresetCfg: ) +def oracle_observations( + target_cfg: SceneEntityCfg, offset: tuple[float, float, float] = (0.0, 0.0, 0.0) +) -> OracleObservationsCfg: + """The teacher's gaze labels toward a point fixed to an asset.""" + return OracleObservationsCfg( + labels=ObservationTermCfg(func=mdp.gaze_teacher_labels, params={"target_cfg": target_cfg, "offset": offset}) + ) + + @configclass class GazeObservationsCfg(ObservationGroupCfg): """The gaze, in field radii, and its velocity, in field radii per second.""" @@ -74,12 +83,3 @@ class OracleObservationsCfg(ObservationGroupCfg): def __post_init__(self): self.enable_corruption = False self.concatenate_terms = True - - -def oracle_observations( - target_cfg: SceneEntityCfg, offset: tuple[float, float, float] = (0.0, 0.0, 0.0) -) -> OracleObservationsCfg: - """The teacher's gaze labels toward a point fixed to an asset.""" - return OracleObservationsCfg( - labels=ObservationTermCfg(func=mdp.gaze_teacher_labels, params={"target_cfg": target_cfg, "offset": offset}) - ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py index 5b0ec4f842f4..9afafd355ba8 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py @@ -29,17 +29,6 @@ """Retina samples across; the stock camera is 96 pixels across.""" -@configclass -class SceneCfg(CartpoleCameraSceneCfg): - tiled_camera = select_presets(foveated_presets(CartpoleTiledCameraCfg(), RETINA_RES), ("rgb", "depth")) - - -@configclass -class ActionsCfg(CartpoleActionsCfg): - # The gaze must be the last action term. - gaze = mdp.GazeActionCfg(asset_name="tiled_camera") - - def observations(data_type: str, image_term) -> object: """The stock camera observations of ``data_type``, the gaze, and the teacher's labels.""" @@ -69,6 +58,17 @@ def __post_init__(self): return ObservationsCfg() +@configclass +class SceneCfg(CartpoleCameraSceneCfg): + tiled_camera = select_presets(foveated_presets(CartpoleTiledCameraCfg(), RETINA_RES), ("rgb", "depth")) + + +@configclass +class ActionsCfg(CartpoleActionsCfg): + # The gaze must be the last action term. + gaze = mdp.GazeActionCfg(asset_name="tiled_camera") + + @configclass class CartpoleFoviEnvCfg(PresetCfg): """Cartpole with a foveated camera; ``presets=depth`` selects depth images.""" diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 7109d6fd534d..03d2382c9d2c 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -60,15 +60,6 @@ def clamp_gaze(gaze: torch.Tensor, limit: float) -> torch.Tensor: return gaze * (limit / gaze.norm(dim=-1, keepdim=True).clamp_min(limit)) -def test_gaze_angles_round_trip_and_follow_the_camera_convention(): - angles = torch.tensor([[0.0, 0.0], [10.0, 0.0], [0.0, 10.0], [-20.0, 35.0]]) - directions = angles_to_direction(angles) - torch.testing.assert_close(direction_to_angles(directions), angles, atol=1e-4, rtol=0) - # OpenCV camera frame: z forward, y down, x right; positive tilt looks up, positive pan looks left. - torch.testing.assert_close(directions[0], torch.tensor([0.0, 0.0, 1.0])) - assert directions[1, 1] < 0 and directions[2, 0] < 0 - - def test_gaze_step_kernel_matches_the_torch_update(): generator = torch.Generator().manual_seed(4) count, step, limit, dt, radius = 2048, 0.1, 1.0, 1 / 60, 23.6 diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 29070b425e3b..3496c467f45d 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -5,7 +5,6 @@ """The Newton foveated camera's render layout and publication, on stand-in renderer buffers.""" -import logging from dataclasses import asdict from types import SimpleNamespace @@ -294,9 +293,9 @@ def test_native_grid_fractional_pool_resolution_validates_newton_tiles(size, val @pytest.mark.parametrize("style", ["warped_cartesian_as_grid", "isotropic"]) -@pytest.mark.parametrize("requested", [["rgba"], ["rgb"]]) -def test_pooled_rgb_is_the_view_of_pooled_rgba_whichever_is_requested(monkeypatch, style, requested) -> None: - """The renderer publishes rgb as a view of rgba when either is requested, and so do pooled grids and sample sets.""" +def test_pooled_rgb_is_the_view_of_pooled_rgba(monkeypatch, style) -> None: + """The renderer publishes rgb as a view of rgba even when only rgba is requested, and so do pooled grids and + sample sets.""" coords = SamplingCoords(60.0, 0.591, 16, style=style, field_geometry="spherical", device="cpu") highres = coords.clone(resolution=32) monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) @@ -329,7 +328,7 @@ def render(camera, env_mask): pool_mode="avg", pool_sample_cortex=False, image_rotation_deg=0, - data_types=requested, + data_types=["rgba"], renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), ) camera._initialize_impl() @@ -340,15 +339,17 @@ def render(camera, env_mask): torch.testing.assert_close(rgb, rgba[..., :3], rtol=0, atol=0) -def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch, caplog) -> None: - """The retina sets a foveated camera's rays, so runtime intrinsics, such as a viewer's zoom sets, are skipped with - a warning rather than handed to the renderer, which would replace the rays with a pinhole's.""" +def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch) -> None: + """The retina sets a foveated camera's rays, so runtime intrinsics, such as a viewer's zoom sets, leave the camera + as configured with a warning to the caller, rather than reaching the renderer, which would replace the rays with a + pinhole's.""" def replace_rays(*args, **kwargs): raise AssertionError("the stock setter replaces the renderer's rays") monkeypatch.setattr(newton_camera.Camera, "set_intrinsic_matrices", replace_rays) camera = new_camera() - with caplog.at_level(logging.WARNING): + with pytest.warns(UserWarning, match="leaves a foveated camera as configured") as caught: camera.set_intrinsic_matrices(torch.eye(3).repeat(2, 1, 1)) - assert "skipped a foveated camera" in caplog.text + # The warning points at the caller's line. + assert caught[0].filename == __file__ diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 03ec14f6ebc6..5667c2021fa3 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -5,13 +5,13 @@ """Dual-grid geometry and modality-specific pooling without a simulator.""" -from dataclasses import dataclass, field, replace +from dataclasses import replace import pytest import torch from fovi.arch.knn import KNNPoolingLayer from fovi.arch.pooling import GridPoolingLayer -from isaaclab_fovi.sensors import pooling +from isaaclab_fovi.sensors import FoveatedCameraCfg, pooling from isaaclab_fovi.sensors.pooling import ( build_highres_coords, build_lowres_coords, @@ -27,31 +27,27 @@ pytestmark = pytest.mark.kitless -@dataclass -class SamplingConfig: - """Sampling fields consumed by the shared pooling helpers.""" - - # A 90 degree pinhole window (focal length 1, aperture 2) with a CMF constant of a tenth of it. - cmf_a_deg: float = 9.0 - spawn: PinholeCameraCfg = field(default_factory=lambda: PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0)) - camera_model: dict[str, str | tuple[int, int] | tuple[float, ...]] | None = None - retinal_window_reference_side: str = "short" - retinal_window_fraction: float = 1.0 - foveated_res: int = 8 - foveated_style: str = "isotropic" - fov_type: str = "circular" - radius_norm: float = 2.0 - isotropic_plotting_type: str = "v1like" - pool_enabled: bool = True - pool_res_mult: float = 2.0 - pool_k: int | None = 3 - pool_mode: str = "avg" - pool_sample_cortex: bool = False - pool_gauss_sigma: float = 10.0 +def pooling_cfg(**overrides) -> FoveatedCameraCfg: + """A pooled foveated camera configuration for the pooling helpers, with ``overrides`` applied. + + A 90 degree pinhole window (focal length 1, aperture 2) with a CMF constant of a tenth of it, and a small isotropic + retina pooled from three visual-field neighbours. + """ + values = dict( + prim_path="/World/Camera", + spawn=PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0), + cmf_a_deg=9.0, + foveated_res=8, + foveated_style="isotropic", + pool_enabled=True, + pool_k=3, + pool_sample_cortex=False, + ) + return FoveatedCameraCfg(**{**values, **overrides}) def test_dual_grid_preserves_constant_channels_and_batch_order() -> None: - cfg = SamplingConfig() + cfg = pooling_cfg() lowres, matched = build_lowres_coords(cfg, "cpu") highres = build_highres_coords(cfg, matched, "cpu") assert highres is not None @@ -93,7 +89,7 @@ def reference_pool(pooler: KNNPoolingLayer, values: torch.Tensor, mode: str, sig def test_pooling_mode_reduces_each_neighbourhood(mode: str) -> None: # A narrow Gaussian weights the nearest of the three neighbours well above the farthest, so it differs from avg. sigma = 0.5 - cfg = SamplingConfig(pool_mode=mode, pool_gauss_sigma=sigma) + cfg = pooling_cfg(pool_mode=mode, pool_gauss_sigma=sigma) lowres, matched = build_lowres_coords(cfg, "cpu") highres = build_highres_coords(cfg, matched, "cpu") pooler, _ = build_pooler(cfg, lowres, highres, "cpu") @@ -109,7 +105,7 @@ def test_pooling_mode_reduces_each_neighbourhood(mode: str) -> None: def test_disabled_pooling_uses_only_output_grid() -> None: - cfg = SamplingConfig(pool_enabled=False) + cfg = pooling_cfg(pool_enabled=False) lowres, matched = build_lowres_coords(cfg, "cpu") assert build_highres_coords(cfg, matched, "cpu") is None assert build_pooler(cfg, lowres, None, "cpu") == (None, None) @@ -189,7 +185,7 @@ def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Ten ], ) def test_modal_pooling_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex: bool) -> None: - cfg = SamplingConfig(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex) + cfg = pooling_cfg(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex) lowres, matched = build_lowres_coords(cfg, "cpu") highres = build_highres_coords(cfg, matched, "cpu") fovi_max, k = build_pooler(replace(cfg, pool_mode="max"), lowres, highres, "cpu") @@ -214,7 +210,7 @@ def test_modal_pooling_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: @pytest.mark.parametrize("device", DEVICES) def test_modal_neighbourhoods_stay_on_the_sensor_device(device: str) -> None: - cfg = SamplingConfig() + cfg = pooling_cfg() lowres, matched = build_lowres_coords(cfg, device) highres = build_highres_coords(cfg, matched, device) table = segmentation_neighbor_indices(build_pooler(cfg, lowres, highres, device)[0]) @@ -235,7 +231,7 @@ def test_modal_neighbourhoods_stay_on_the_sensor_device(device: str) -> None: ], ) def test_native_grid_pooling_excludes_invalid_photoreceptors(mode, style, sample_cortex) -> None: - cfg = SamplingConfig( + cfg = pooling_cfg( foveated_style=style, pool_mode=mode, pool_sample_cortex=sample_cortex, @@ -262,7 +258,7 @@ def test_native_grid_pooling_excludes_invalid_photoreceptors(mode, style, sample ], ) def test_native_grid_default_kernel_matches_deployment(style: str, expected: type) -> None: - cfg = SamplingConfig( + cfg = pooling_cfg( foveated_style=style, pool_k=None, pool_sample_cortex=True, diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index 6c4a1c6abf61..bdc84551bb4d 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -55,6 +55,8 @@ def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> texels = [(3, 1), (0, 4), (2, 0), (1, 3), (3, 4), (0, 2), (2, 2)] camera = SimpleNamespace( cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")), + # An OVRTX camera with distance_to_camera output adds each camera's near clip. + _offset_distance=True, _native_grid=native_grid, _near_clip=torch.tensor([0.25, 0.5, 0.75]).view(-1, 1, 1, 1), # The renderer-bound texture buffers are ProxyArrays, as the parent camera allocates them. diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index 6a5799e96554..a06ab3289505 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -5,6 +5,7 @@ """Rendering, gaze and software-sampling contracts, without launching a simulator.""" +import math from dataclasses import asdict from types import SimpleNamespace @@ -26,6 +27,7 @@ matrix_from_quat, quat_apply, quat_from_matrix, + quat_mul, ) from isaaclab.utils.warp import ProxyArray @@ -145,6 +147,17 @@ def __init__(self, mount_opengl: torch.Tensor) -> None: self.mount_turns = 0 +MOUNT = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) +"""Two cameras' mount orientations (x, y, z, w), OpenGL convention, for the prim-writing harness.""" + + +def write_prims(camera, positions=None, orientations=None, env_ids=None, convention="ros"): + """Stand-in for the stock pose write on :class:`RtxGazeHarness`: the orientations become the prims' poses.""" + if orientations is not None: + ids = slice(None) if env_ids is None else torch.as_tensor(env_ids) + camera._view.local[ids] = convert_camera_frame_orientation_convention(orientations, convention, "opengl") + + def gaze_direction(angles_deg: torch.Tensor) -> torch.Tensor: """OpenCV camera-frame unit direction of (tilt, pan) gaze angles [deg]: up and left are positive.""" tilt, pan = angles_deg.deg2rad().unbind(-1) @@ -242,18 +255,31 @@ def opengl(orientation: torch.Tensor) -> torch.Tensor: def test_only_a_turned_mount_is_recorded(monkeypatch) -> None: - """The fixed-mount teacher reads the live camera position, so only successful turns of the mount count.""" - monkeypatch.setattr(Camera, "set_world_poses", lambda *args, **kwargs: None) + """The fixed-mount teacher reads the live camera position, so only writes that turn a mount count: not a position + move, and not writing back the reported mount (of either quaternion sign), even with a gaze held in the prims.""" + monkeypatch.setattr(Camera, "set_world_poses", write_prims) monkeypatch.setattr(Camera, "set_world_poses_from_view", lambda *args, **kwargs: None) eyes = torch.zeros(2, 3) + + def reported(camera, env_ids=None): + return camera.get_world_poses(env_ids, convention="ros")[1] + + def turn_second(camera): + # One degree about the second camera's optical axis. + half = torch.tensor(math.radians(1.0) / 2) + roll = torch.tensor([[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, float(half.sin()), float(half.cos())]]) + camera.set_world_poses(orientations=quat_mul(reported(camera), roll)) + for move, turned in ( (lambda camera: camera.set_world_poses(positions=torch.zeros(2, 3)), False), - (lambda camera: camera.set_world_poses(orientations=torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2)), True), + (lambda camera: camera.set_world_poses(orientations=reported(camera)), False), + (lambda camera: camera.set_world_poses(orientations=-reported(camera, [1]), env_ids=[1]), False), + (turn_second, True), (lambda camera: camera.set_world_poses_from_view(eyes, eyes), False), (lambda camera: camera.set_world_poses_from_view(eyes, torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])), True), ): - camera = GazeHarness() - camera.mount_turns = 0 + camera = RtxGazeHarness(MOUNT) + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) move(camera) assert camera.mount_turns == int(turned) @@ -263,8 +289,8 @@ def reject(*args, **kwargs): raise ValueError("rejected") monkeypatch.setattr(Camera, "set_world_poses", reject) - camera = GazeHarness() - camera.mount_turns = 0 + # The identity differs from both mounts, so only the rejection keeps the count. + camera = RtxGazeHarness(MOUNT) with pytest.raises(ValueError, match="rejected"): camera.set_world_poses(orientations=torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2)) assert camera.mount_turns == 0 @@ -414,14 +440,9 @@ def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_ def test_rtx_world_poses_are_the_mount_so_a_round_trip_keeps_mount_and_gaze(monkeypatch) -> None: """Isaac RTX holds the gaze in its prims; its world poses still report the bare mount, as the other renderers' do, so writing them back (as a viewer navigating the camera does) neither moves the mount nor doubles the gaze.""" - - def write_prims(camera, positions=None, orientations=None, env_ids=None, convention="ros"): - ids = slice(None) if env_ids is None else torch.as_tensor(env_ids) - camera._view.local[ids] = convert_camera_frame_orientation_convention(orientations, convention, "opengl") - monkeypatch.setattr(Camera, "set_world_poses", write_prims) - mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) - camera = RtxGazeHarness(mount) + camera = RtxGazeHarness(MOUNT) + mount = MOUNT camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) gazed = camera._view.local.clone() assert not torch.allclose(matrix_from_quat(gazed), matrix_from_quat(mount), atol=1e-3) diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 9da0ac50377e..71e6f90aeb7a 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -11,15 +11,7 @@ import torch from fovi.sensing.coords import SamplingCoords from isaaclab_fovi.sensors.lens_lut import build_native_grid_textures -from isaaclab_fovi.sensors.native_grid import ( - allocate_grid_outputs, - copy_grid_outputs, - grid_output_shape, - grid_sample_indices, - mask_grid_samples, - native_grid_directions, - native_grid_exit_uv, -) +from isaaclab_fovi.sensors.native_grid import native_grid_directions, native_grid_exit_uv pytestmark = pytest.mark.kitless @@ -162,30 +154,6 @@ def test_textures_match_independent_geometry(rotation: float) -> None: ) -def test_textures_and_public_modalities() -> None: - coords = make_coords() - directions, inverse = build_native_grid_textures(coords, image_rotation_deg=0, exit_size=64) - torch.testing.assert_close(directions.reshape(-1, 3), native_grid_directions(coords)) - assert torch.isfinite(inverse).all() - assert (inverse == -1).any() - assert grid_output_shape(coords) == (16, 16) - source = { - "rgba": torch.ones(2, len(coords), 1, 4, dtype=torch.uint8), - "depth": torch.arange(len(coords), dtype=torch.float32)[None, :, None, None], - "segmentation": torch.arange(len(coords), dtype=torch.int32)[None, :, None, None], - } - source["rgb"] = source["rgba"][..., :3] - mask_grid_samples(source, coords) - assert source["rgba"].all() - target = allocate_grid_outputs(source, coords) - pointers = {name: tensor.data_ptr() for name, tensor in target.items()} - copy_grid_outputs(source, target, grid_sample_indices(coords)) - for name in source: - torch.testing.assert_close(target[name], coords.as_grid(source[name][:, :, 0], sample_dim=1)) - assert target[name].data_ptr() == pointers[name] - assert target["rgb"].untyped_storage().data_ptr() == target["rgba"].untyped_storage().data_ptr() - - def test_camera_config_rejects_wang_with_square_shells() -> None: from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg From 18c30801371f5d1a9de1fe002695be9543d24af3 Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Thu, 19 Nov 2026 15:42:16 -0800 Subject: [PATCH 45/81] Reduce FOVI to a shared retinal grid and gaze control --- docs/conf.py | 3 - .../source/_static/css/environment-browser.js | 1 - .../css/foveation-pooling-isotropic.json | 1 - docs/source/_static/css/foveation-viewer.css | 206 ---- docs/source/_static/css/foveation-viewer.js | 987 ------------------ .../sensors/foveated_camera_active_gaze.jpg | Bin 115472 -> 0 bytes .../sensors/foveated_camera_pooling.jpg | Bin 68546 -> 0 bytes .../source/api/lab_fovi/isaaclab_fovi.mdp.rst | 4 - .../concepts/sensors/foveated_camera.rst | 107 +- .../changelog.d/isaaclab-fovi.added.rst | 5 +- .../isaaclab_fovi/mdp/__init__.pyi | 7 +- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 376 +------ .../isaaclab_fovi/mdp/gaze_cfg.py | 18 +- .../sensors/calibrated_geometry.py | 46 +- .../isaaclab_fovi/sensors/foveated_camera.py | 378 ++----- .../sensors/foveated_camera_cfg.py | 70 +- .../sensors/foveated_newton_camera.py | 250 +---- .../sensors/foveated_rtx_camera.py | 332 ++---- .../isaaclab_fovi/sensors/gaze_kernels.py | 89 +- .../isaaclab_fovi/sensors/lens_lut.py | 141 +-- .../isaaclab_fovi/sensors/native_grid.py | 152 +-- .../isaaclab_fovi/sensors/pooling.py | 282 ----- source/isaaclab_fovi/test/test_active_gaze.py | 216 +--- source/isaaclab_fovi/test/test_camera_cfg.py | 58 +- source/isaaclab_fovi/test/test_camera_gaze.py | 367 +++---- source/isaaclab_fovi/test/test_native_grid.py | 177 +--- .../isaaclab_fovi/test/test_newton_buffers.py | 356 +------ source/isaaclab_fovi/test/test_pooling.py | 172 --- source/isaaclab_fovi/test/test_rtx_camera.py | 68 +- .../active-gaze-cartpole.added.rst | 3 - .../changelog.d/active-gaze-cartpole.minor | 0 .../contrib/active_gaze/__init__.py | 29 - .../contrib/active_gaze/active_gaze_cfg.py | 85 -- .../contrib/active_gaze/agents.py | 40 - .../cartpole_camera_fovi_env_cfg.py | 85 -- .../contrib/active_gaze/gaze_distribution.py | 61 -- .../active_gaze/gaze_distribution_cfg.py | 24 - .../active_gaze/gaze_supervised_ppo.py | 134 --- .../active_gaze/gaze_supervised_ppo_cfg.py | 26 - .../test/contrib/test_active_gaze_ppo.py | 129 --- 40 files changed, 437 insertions(+), 5048 deletions(-) delete mode 100644 docs/source/_static/css/foveation-pooling-isotropic.json delete mode 100644 docs/source/_static/css/foveation-viewer.css delete mode 100644 docs/source/_static/css/foveation-viewer.js delete mode 100644 docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg delete mode 100644 docs/source/_static/overview/sensors/foveated_camera_pooling.jpg delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py delete mode 100644 source/isaaclab_fovi/test/test_pooling.py delete mode 100644 source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst delete mode 100644 source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py delete mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py delete mode 100644 source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py diff --git a/docs/conf.py b/docs/conf.py index f68ddf96c4b6..dc83014e7029 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -48,7 +48,6 @@ sys.path.insert(0, os.path.abspath("../source/isaaclab_ov/isaaclab_ov")) sys.path.insert(0, os.path.abspath("../source/isaaclab_visualizers")) sys.path.insert(0, os.path.abspath("../source/isaaclab_visualizers/isaaclab_visualizers")) -# Only the package root: the package's ``rsl_rl`` subpackage would shadow RSL-RL as a top-level module. sys.path.insert(0, os.path.abspath("../source/isaaclab_fovi")) # -- Project information ----------------------------------------------------- @@ -352,13 +351,11 @@ def _read_pinned_versions() -> dict: "css/environment-browser.css", "css/demo-browser.css", "css/guide-browser.css", - "css/foveation-viewer.css", ] html_js_files = [ "css/environment-browser.js", "css/demo-browser.js", "css/guide-browser.js", - "css/foveation-viewer.js", ] html_theme_options = { diff --git a/docs/source/_static/css/environment-browser.js b/docs/source/_static/css/environment-browser.js index f1793a6e0d33..66bbc79dd875 100644 --- a/docs/source/_static/css/environment-browser.js +++ b/docs/source/_static/css/environment-browser.js @@ -69,7 +69,6 @@ ["IsaacContrib-Assemble-Trocar-G129-Dex3", "rlinf", "isaacsim_physx,newton_mjwarp", "", "", "environments/previews/manipulation/g1_assemble_trocar.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "newton_mjwarp||"]], ["IsaacContrib-AutoMate-Assembly-Direct", "rl_games", "", "", "", "environment-previews/automate_assembly.jpg"], ["IsaacContrib-AutoMate-Disassembly-Direct", "rl_games", "", "", "", "environment-previews/automate_disassembly.jpg"], - ["IsaacContrib-Cartpole-Camera-Fovi", "rsl_rl", "isaacsim_physx,newton_kamino,newton_mjwarp,newton_steel,ovphysx", "isaacsim_rtx,newton_optix,newton_warp,ovrtx", "depth,rgb", "", false, {}, {}, "", null, ["||", "||depth", "||rgb", "|isaacsim_rtx|", "|isaacsim_rtx|depth", "|isaacsim_rtx|rgb", "|newton_optix|", "|newton_optix|depth", "|newton_optix|rgb", "|newton_warp|", "|newton_warp|depth", "|newton_warp|rgb", "|ovrtx|", "|ovrtx|depth", "|ovrtx|rgb", "isaacsim_physx||", "isaacsim_physx||depth", "isaacsim_physx||rgb", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|isaacsim_rtx|depth", "isaacsim_physx|isaacsim_rtx|rgb", "isaacsim_physx|newton_optix|", "isaacsim_physx|newton_optix|depth", "isaacsim_physx|newton_optix|rgb", "isaacsim_physx|newton_warp|", "isaacsim_physx|newton_warp|depth", "isaacsim_physx|newton_warp|rgb", "newton_kamino||", "newton_kamino||depth", "newton_kamino||rgb", "newton_kamino|isaacsim_rtx|", "newton_kamino|isaacsim_rtx|depth", "newton_kamino|isaacsim_rtx|rgb", "newton_kamino|newton_optix|", "newton_kamino|newton_optix|depth", "newton_kamino|newton_optix|rgb", "newton_kamino|newton_warp|", "newton_kamino|newton_warp|depth", "newton_kamino|newton_warp|rgb", "newton_kamino|ovrtx|", "newton_kamino|ovrtx|depth", "newton_kamino|ovrtx|rgb", "newton_mjwarp||", "newton_mjwarp||depth", "newton_mjwarp||rgb", "newton_mjwarp|isaacsim_rtx|", "newton_mjwarp|isaacsim_rtx|depth", "newton_mjwarp|isaacsim_rtx|rgb", "newton_mjwarp|newton_optix|", "newton_mjwarp|newton_optix|depth", "newton_mjwarp|newton_optix|rgb", "newton_mjwarp|newton_warp|", "newton_mjwarp|newton_warp|depth", "newton_mjwarp|newton_warp|rgb", "newton_mjwarp|ovrtx|", "newton_mjwarp|ovrtx|depth", "newton_mjwarp|ovrtx|rgb", "newton_steel||", "newton_steel||depth", "newton_steel||rgb", "newton_steel|isaacsim_rtx|", "newton_steel|isaacsim_rtx|depth", "newton_steel|isaacsim_rtx|rgb", "newton_steel|newton_optix|", "newton_steel|newton_optix|depth", "newton_steel|newton_optix|rgb", "newton_steel|newton_warp|", "newton_steel|newton_warp|depth", "newton_steel|newton_warp|rgb", "newton_steel|ovrtx|", "newton_steel|ovrtx|depth", "newton_steel|ovrtx|rgb", "ovphysx||", "ovphysx||depth", "ovphysx||rgb", "ovphysx|newton_optix|", "ovphysx|newton_optix|depth", "ovphysx|newton_optix|rgb", "ovphysx|newton_warp|", "ovphysx|newton_warp|depth", "ovphysx|newton_warp|rgb", "ovphysx|ovrtx|", "ovphysx|ovrtx|depth", "ovphysx|ovrtx|rgb"]], ["IsaacContrib-Cartpole-Camera-Showcase-Direct", "skrl", "", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete"]], ["IsaacContrib-Cartpole-Showcase-Direct", "skrl", "isaacsim_physx,newton_kamino,newton_mjwarp,newton_steel,ovphysx", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,discrete_box,discrete_discrete,discrete_multidiscrete,multidiscrete_box,multidiscrete_discrete,multidiscrete_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "environment-previews/cartpole.jpg", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||discrete_box", "||discrete_discrete", "||discrete_multidiscrete", "||multidiscrete_box", "||multidiscrete_discrete", "||multidiscrete_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete", "isaacsim_physx||", "isaacsim_physx||box_box", "isaacsim_physx||box_discrete", "isaacsim_physx||box_multidiscrete", "isaacsim_physx||dict_box", "isaacsim_physx||dict_discrete", "isaacsim_physx||dict_multidiscrete", "isaacsim_physx||discrete_box", "isaacsim_physx||discrete_discrete", "isaacsim_physx||discrete_multidiscrete", "isaacsim_physx||multidiscrete_box", "isaacsim_physx||multidiscrete_discrete", "isaacsim_physx||multidiscrete_multidiscrete", "isaacsim_physx||tuple_box", "isaacsim_physx||tuple_discrete", "isaacsim_physx||tuple_multidiscrete", "newton_kamino||", "newton_kamino||box_box", "newton_kamino||box_discrete", "newton_kamino||box_multidiscrete", "newton_kamino||dict_box", "newton_kamino||dict_discrete", "newton_kamino||dict_multidiscrete", "newton_kamino||discrete_box", "newton_kamino||discrete_discrete", "newton_kamino||discrete_multidiscrete", "newton_kamino||multidiscrete_box", "newton_kamino||multidiscrete_discrete", "newton_kamino||multidiscrete_multidiscrete", "newton_kamino||tuple_box", "newton_kamino||tuple_discrete", "newton_kamino||tuple_multidiscrete", "newton_mjwarp||", "newton_mjwarp||box_box", "newton_mjwarp||box_discrete", "newton_mjwarp||box_multidiscrete", "newton_mjwarp||dict_box", "newton_mjwarp||dict_discrete", "newton_mjwarp||dict_multidiscrete", "newton_mjwarp||discrete_box", "newton_mjwarp||discrete_discrete", "newton_mjwarp||discrete_multidiscrete", "newton_mjwarp||multidiscrete_box", "newton_mjwarp||multidiscrete_discrete", "newton_mjwarp||multidiscrete_multidiscrete", "newton_mjwarp||tuple_box", "newton_mjwarp||tuple_discrete", "newton_mjwarp||tuple_multidiscrete", "newton_steel||", "newton_steel||box_box", "newton_steel||box_discrete", "newton_steel||box_multidiscrete", "newton_steel||dict_box", "newton_steel||dict_discrete", "newton_steel||dict_multidiscrete", "newton_steel||discrete_box", "newton_steel||discrete_discrete", "newton_steel||discrete_multidiscrete", "newton_steel||multidiscrete_box", "newton_steel||multidiscrete_discrete", "newton_steel||multidiscrete_multidiscrete", "newton_steel||tuple_box", "newton_steel||tuple_discrete", "newton_steel||tuple_multidiscrete", "ovphysx||", "ovphysx||box_box", "ovphysx||box_discrete", "ovphysx||box_multidiscrete", "ovphysx||dict_box", "ovphysx||dict_discrete", "ovphysx||dict_multidiscrete", "ovphysx||discrete_box", "ovphysx||discrete_discrete", "ovphysx||discrete_multidiscrete", "ovphysx||multidiscrete_box", "ovphysx||multidiscrete_discrete", "ovphysx||multidiscrete_multidiscrete", "ovphysx||tuple_box", "ovphysx||tuple_discrete", "ovphysx||tuple_multidiscrete"]], ["IsaacContrib-Deploy-GearAssembly-Rizon4s-Grav", "rsl_rl", "", "", "", "environment-previews/rizon4s_gear_assembly.jpg"], diff --git a/docs/source/_static/css/foveation-pooling-isotropic.json b/docs/source/_static/css/foveation-pooling-isotropic.json deleted file mode 100644 index 90d14b291e94..000000000000 --- a/docs/source/_static/css/foveation-pooling-isotropic.json +++ /dev/null @@ -1 +0,0 @@ -{"fov":90,"cmfA":2.0,"res":16,"rings":14,"count":243,"mult":{"2":{"rings":28,"count":1026,"defaultK":4,"kMax":8,"geodesic":[0,1,4,2,3,5,6,8,7,18,8,1,19,34,20,2,9,10,8,2,22,21,23,3,11,12,10,3,24,25,23,2,13,14,12,4,27,28,26,5,15,14,16,5,30,29,31,4,17,16,18,6,32,33,31,5,35,55,36,19,56,79,57,34,37,38,36,58,21,20,59,57,39,38,40,22,61,60,23,21,41,40,42,63,24,23,62,64,43,42,44,25,65,66,26,64,46,47,45,69,27,68,28,70,48,49,47,29,71,70,28,72,50,51,49,73,30,31,74,72,52,51,53,32,75,76,31,33,54,53,55,78,33,34,77,79,80,107,81,56,108,109,137,79,82,81,83,110,58,57,111,109,84,83,85,112,59,60,113,111,86,87,85,61,114,115,62,60,88,87,89,63,117,116,62,64,90,89,91,119,65,64,118,120,92,93,91,121,66,67,120,122,94,95,93,68,123,124,122,67,96,95,97,125,70,69,126,124,98,99,97,127,71,72,128,126,100,101,99,73,129,130,74,72,102,101,103,75,132,131,74,76,104,105,103,134,77,76,133,135,106,105,107,136,78,79,135,137,138,170,139,108,171,172,205,109,140,141,139,173,110,174,109,172,142,141,143,175,112,111,176,174,144,145,143,177,113,114,178,176,146,147,145,115,179,180,116,114,148,147,149,117,182,181,118,116,150,151,149,119,184,183,118,120,152,153,151,186,121,120,185,187,154,153,155,188,123,122,187,189,157,158,156,191,125,126,192,190,159,158,160,127,193,194,128,126,161,160,162,129,195,196,128,130,163,162,164,131,198,197,130,132,165,164,166,200,133,132,199,201,167,168,166,202,134,135,201,203,169,168,170,204,136,203,137,205,206,207,242,171,243,244,281,205,208,209,207,245,173,246,172,244,210,209,211,247,175,248,174,246,212,211,213,249,177,250,176,248,214,215,213,251,179,252,178,250,216,217,215,254,180,253,181,255,218,217,219,256,182,255,183,257,220,221,219,258,184,257,185,259,222,223,221,260,186,259,187,261,225,226,224,263,189,264,262,188,227,228,226,265,191,266,190,264,229,230,228,267,193,268,192,266,231,232,230,269,195,270,194,268,233,234,232,271,197,272,196,270,235,234,236,274,198,273,199,275,237,236,238,276,200,275,201,277,239,240,238,278,202,277,203,279,241,242,240,280,204,279,205,281,282,322,283,243,323,364,324,244,284,285,283,325,245,244,326,324,286,287,285,327,247,246,328,326,288,289,287,329,249,248,330,328,290,289,291,331,251,250,332,330,292,293,291,333,253,252,334,332,294,295,293,335,254,255,336,334,296,295,297,256,337,338,257,336,340,339,341,383,299,298,382,384,342,341,343,385,301,300,384,386,344,343,345,387,303,302,388,386,346,347,345,389,304,305,390,388,348,349,347,391,306,307,392,390,309,308,310,269,351,350,268,352,311,310,312,353,271,270,352,354,313,312,314,355,272,273,354,356,315,316,314,357,274,275,356,358,317,318,316,359,276,277,358,360,319,318,320,361,278,279,360,362,321,322,320,363,280,281,362,364,409,410,453,365,454,499,455,366,411,410,412,456,367,457,366,455,413,414,412,458,369,459,368,457,371,370,372,415,329,328,416,414,418,419,417,463,374,464,373,462,420,421,419,465,376,466,375,464,422,421,423,467,378,468,377,466,424,425,423,469,380,470,379,468,426,425,427,471,382,472,381,470,428,429,427,473,384,474,383,472,386,385,387,343,430,431,344,342,388,389,387,345,433,432,344,346,435,434,436,481,390,480,391,482,437,438,436,483,392,482,393,484,439,440,438,485,394,484,395,486,441,440,442,487,396,486,397,488,443,442,444,489,398,488,399,490,445,446,444,491,400,490,401,492,403,404,402,448,359,360,447,449,450,449,451,496,405,495,406,497,452,451,453,498,407,497,408,499,500,545,501,454,546,592,547,499,502,501,503,456,548,549,455,457,504,503,505,458,550,551,457,459,506,507,505,460,552,553,461,459,508,507,509,462,554,555,461,463,510,509,511,464,556,557,463,465,513,514,512,467,559,560,468,466,515,516,514,469,561,562,470,468,517,518,516,471,563,564,470,472,519,518,520,473,565,566,474,472,521,522,520,475,567,568,476,474,523,524,522,477,570,569,478,476,525,524,526,479,572,571,478,480,527,528,526,481,574,573,482,480,529,528,530,483,576,575,484,482,531,532,530,485,578,577,486,484,533,534,532,487,580,579,486,488,536,535,537,490,583,582,489,491,538,539,537,492,585,584,493,491,540,539,541,494,587,586,493,495,542,543,541,496,589,588,495,497,544,543,545,498,591,590,499,497,593,594,640,641,546,642,688,592,595,594,596,643,548,547,642,644,597,596,598,645,550,549,644,646,599,598,600,647,552,551,646,648,601,602,600,649,554,553,650,648,603,602,604,651,556,555,650,652,606,605,607,654,559,558,653,655,608,607,609,656,561,560,657,655,610,611,609,658,563,562,657,659,612,611,613,660,565,564,661,659,614,615,613,662,567,566,663,661,616,615,617,664,569,568,663,665,618,617,619,666,570,571,667,665,620,619,621,668,572,573,669,667,622,623,621,670,574,575,671,669,624,623,625,672,576,577,671,673,626,627,625,674,578,579,675,673,628,629,627,676,580,581,677,675,631,630,632,679,583,584,678,680,633,632,634,681,585,586,680,682,635,636,634,683,587,588,684,682,637,638,636,685,589,590,686,684,639,640,638,687,591,592,688,686,689,690,736,737,641,785,738,642,691,690,692,643,739,740,642,644,693,694,692,645,741,742,644,646,695,694,696,647,743,744,646,648,697,698,696,649,745,746,650,648,699,698,700,651,747,748,650,652,702,701,703,654,750,751,653,655,704,703,705,656,752,753,655,657,706,707,705,658,754,755,659,657,708,707,709,660,756,757,659,661,710,711,709,662,758,759,663,661,712,711,713,664,760,761,663,665,714,715,713,666,763,762,667,665,716,715,717,668,765,764,669,667,718,719,717,670,767,766,671,669,720,719,721,672,769,768,671,673,722,723,721,674,771,770,675,673,724,725,723,676,773,772,677,675,727,726,728,679,776,775,678,680,729,728,730,681,778,777,680,682,731,732,730,683,780,779,684,682,733,734,732,685,782,781,686,684,735,736,734,687,784,783,688,686,786,834,787,835,737,785,738,836,788,789,787,739,837,836,740,738,790,791,789,741,839,838,740,742,792,793,791,743,841,840,744,742,795,796,794,746,844,843,745,747,797,796,798,748,846,845,749,747,799,800,798,750,848,847,749,751,801,802,800,752,850,849,753,751,803,802,804,754,852,851,753,755,805,804,806,756,854,853,755,757,807,806,808,758,856,855,757,759,809,810,808,760,858,857,761,759,812,813,811,763,860,861,764,762,814,813,815,765,862,863,764,766,816,817,815,767,864,865,766,768,818,819,817,769,866,867,770,768,820,819,821,771,868,869,770,772,822,823,821,773,870,871,774,772,824,823,825,775,872,873,774,776,826,827,825,777,874,875,778,776,829,830,828,780,877,878,781,779,831,830,832,782,879,880,781,783,833,834,832,784,881,882,785,783,883,884,930,931,835,932,978,836,885,884,886,933,837,932,934,836,887,886,888,935,839,934,936,838,889,888,890,937,841,936,938,840,891,890,892,939,843,940,938,844,893,892,894,941,845,940,942,844,896,895,897,944,848,943,945,847,898,897,899,946,850,945,947,849,900,901,899,948,852,949,947,853,902,901,903,950,854,949,951,853,904,905,903,952,856,953,951,857,906,905,907,954,858,953,955,857,908,909,907,956,860,957,955,861,910,909,911,958,862,957,959,861,912,913,911,960,864,961,959,865,914,913,915,962,866,963,961,865,916,917,915,964,868,965,963,869,918,919,917,966,870,967,965,871,921,920,922,969,873,968,970,872,923,922,924,971,875,970,972,874,925,926,924,973,877,974,972,878,927,928,926,975,879,976,974,880,929,930,928,977,881,978,976,882,979,-1,1025,980,-1,931,-1,932,981,-1,980,982,933,-1,934,932,983,-1,984,982,935,-1,936,-1,985,-1,984,986,937,-1,-1,938,987,-1,988,986,939,-1,940,-1,989,-1,990,988,941,-1,942,-1,991,-1,990,992,943,-1,944,-1,993,-1,992,994,945,-1,946,-1,995,-1,994,996,-1,947,948,-1,997,-1,996,998,949,-1,950,-1,999,-1,1000,998,951,-1,952,-1,1001,-1,1000,1002,-1,953,954,-1,1004,-1,1005,1003,957,956,-1,-1,1006,-1,1007,1005,-1,959,958,-1,1008,-1,1009,1007,-1,961,960,-1,1010,-1,1011,1009,963,962,-1,-1,1012,-1,1011,1013,965,-1,964,-1,1014,-1,1015,1013,-1,967,966,-1,1016,-1,1017,1015,969,-1,968,-1,1018,-1,1017,1019,971,-1,970,-1,1020,-1,1021,1019,973,-1,972,974,1022,-1,1023,1021,975,-1,-1,974,1024,-1,1023,1025,977,-1,-1,976],"visual":[0,3,4,1,5,2,6,8,7,18,8,19,1,20,34,2,9,8,10,2,22,21,23,3,11,12,10,3,24,25,23,4,13,12,14,27,4,28,26,3,15,14,16,5,30,29,31,6,17,16,18,6,32,33,31,5,35,56,55,36,19,79,57,34,37,38,58,59,36,21,20,57,39,40,61,22,38,60,23,62,41,42,63,24,64,40,23,62,43,44,66,65,25,26,42,45,45,46,68,27,67,69,44,47,48,47,70,71,29,28,49,46,50,49,73,30,72,51,31,74,52,51,75,32,53,76,31,74,54,53,78,77,55,33,34,79,80,108,107,81,56,137,109,79,82,110,81,83,111,58,57,109,84,112,83,85,113,59,60,111,86,114,115,87,85,61,62,60,88,117,116,87,89,63,62,64,90,119,91,89,118,65,64,120,92,121,93,91,120,66,67,122,94,123,95,93,68,122,124,67,96,125,97,95,126,70,69,124,98,127,99,97,128,71,72,126,100,129,130,99,101,73,74,72,102,132,131,101,103,75,74,76,104,134,105,103,133,77,76,135,106,136,107,105,135,78,79,137,138,171,170,139,108,205,172,137,140,173,141,139,174,110,172,109,142,175,143,176,141,112,111,174,144,178,145,177,143,114,113,179,146,180,147,179,145,115,116,181,148,182,149,181,117,183,147,118,150,151,184,185,119,183,149,120,152,153,186,187,121,151,122,185,154,155,188,189,123,153,156,124,157,156,191,190,125,158,124,192,159,158,193,192,127,194,160,126,161,195,160,196,129,194,162,128,163,197,162,198,164,130,131,196,165,199,164,200,166,132,133,198,167,202,166,201,168,134,135,203,169,204,168,170,203,136,205,137,206,243,242,207,244,281,171,205,208,245,209,246,207,173,244,172,210,247,248,211,209,175,246,174,212,249,250,213,211,177,176,251,214,252,215,251,213,179,178,253,216,254,217,253,181,215,255,180,218,256,219,257,255,183,217,182,220,258,221,259,185,257,184,219,222,223,260,261,187,186,221,259,224,225,262,263,188,189,226,223,227,226,265,264,190,191,228,266,229,267,228,266,192,268,193,230,231,269,230,270,268,194,232,195,233,271,232,272,196,234,270,197,235,273,234,274,236,198,199,272,237,275,276,236,238,200,201,274,239,278,277,238,240,202,279,203,241,280,240,279,242,204,281,205,282,323,322,283,364,324,243,244,284,325,285,326,283,324,245,244,286,327,287,328,285,326,247,246,288,329,330,289,287,249,328,248,290,331,332,291,289,251,330,250,292,333,334,293,291,253,252,332,294,336,295,335,293,255,254,337,296,338,297,337,295,257,339,256,340,298,299,339,341,259,297,258,342,300,301,341,343,261,260,299,344,303,302,343,345,263,262,301,346,305,304,347,345,264,265,306,348,307,306,349,347,266,308,267,309,350,308,351,310,268,349,269,311,352,310,353,312,270,271,351,313,354,355,312,314,272,273,353,315,357,356,314,316,274,358,275,317,359,358,316,318,276,360,277,319,361,318,360,320,362,278,279,321,363,320,362,322,364,280,281,409,365,366,408,410,453,323,454,411,367,412,368,366,410,325,456,369,413,414,370,368,412,327,458,371,415,416,372,370,329,414,417,373,418,417,374,331,372,419,463,420,375,376,419,421,333,374,377,422,378,377,421,423,335,379,376,424,380,379,425,423,381,337,469,426,382,381,427,425,383,339,472,384,428,429,383,385,427,341,474,386,430,431,385,387,343,429,476,388,433,432,389,387,345,434,478,390,435,434,391,389,436,347,480,437,392,393,436,438,391,349,482,439,394,395,440,438,393,351,485,441,396,397,442,440,353,395,398,443,399,398,444,442,355,400,397,401,445,446,400,357,402,444,491,403,448,447,402,404,359,449,446,405,450,449,404,406,451,361,496,452,407,451,406,408,453,363,498,500,454,545,501,455,499,409,546,502,456,503,457,501,455,411,548,504,458,505,459,503,457,413,550,506,460,507,461,459,505,415,552,508,462,509,463,461,507,417,555,510,511,464,465,419,463,557,509,513,512,467,466,421,468,559,514,515,469,514,468,470,516,423,561,517,471,516,470,472,518,563,425,519,473,518,472,520,474,427,565,521,475,520,474,522,476,429,567,523,477,522,524,476,478,432,431,525,479,526,480,524,478,434,572,527,481,528,482,526,480,436,574,529,483,530,484,482,528,576,438,531,485,532,486,484,530,440,578,533,534,487,488,442,486,580,532,536,535,490,489,444,491,582,537,538,492,537,491,493,539,446,584,540,494,539,493,495,541,448,587,542,496,541,495,543,497,450,589,544,498,543,497,545,499,452,591,593,546,640,594,592,547,641,500,595,548,596,549,594,547,643,502,597,550,598,551,596,549,645,504,599,552,600,553,551,598,647,506,601,554,602,555,553,600,649,508,603,604,556,557,555,602,651,510,606,605,558,559,557,654,653,607,608,607,560,561,559,609,656,514,610,562,609,563,611,658,561,516,612,564,611,565,613,660,563,518,614,566,567,613,615,662,520,565,616,568,569,615,617,664,522,567,618,571,570,619,617,666,524,572,620,573,572,621,619,668,526,574,622,575,623,574,621,670,576,528,624,577,625,576,623,672,578,530,626,627,579,578,580,625,674,532,628,629,581,580,582,676,677,627,631,630,583,582,584,632,679,536,633,585,632,584,586,634,681,538,635,587,634,586,588,636,683,540,637,589,636,588,638,590,685,542,639,591,638,590,640,592,687,544,689,641,690,736,688,642,737,593,691,643,692,690,644,642,739,595,693,645,694,646,692,741,644,742,695,647,696,648,694,743,646,744,697,698,649,650,696,746,745,648,699,700,651,652,748,747,698,650,702,701,654,653,750,703,749,700,704,703,656,655,752,705,657,608,706,705,658,657,754,707,659,610,708,660,707,659,709,756,661,757,710,662,709,661,711,663,758,759,712,664,711,713,663,665,760,761,714,666,715,713,667,665,763,762,716,668,717,669,715,667,765,764,718,670,719,671,717,767,669,766,720,721,672,673,769,719,671,624,722,723,674,675,771,721,673,626,724,725,676,677,773,723,774,726,727,726,679,678,775,776,728,680,729,728,681,680,730,777,778,682,731,683,730,682,732,780,684,779,733,685,732,684,734,782,686,781,735,687,734,736,686,688,784,639,786,737,834,787,835,785,738,689,788,739,789,740,787,837,738,838,790,791,741,742,839,789,740,840,792,793,743,744,841,791,842,742,795,794,746,745,843,844,796,793,797,796,748,747,845,846,798,749,799,798,750,749,800,848,847,751,801,752,800,802,751,850,753,849,803,754,804,802,755,852,753,851,805,756,806,757,804,854,755,853,807,808,758,759,856,806,757,855,809,810,760,761,858,808,759,811,812,811,763,762,860,813,764,810,814,813,765,764,862,815,766,863,816,767,815,766,817,864,768,865,818,769,817,819,768,866,770,867,820,771,821,819,772,868,770,869,822,823,773,774,821,870,871,772,824,825,775,776,873,872,823,774,826,827,777,778,875,874,825,828,829,828,780,779,877,830,876,781,831,830,782,781,879,832,783,878,833,784,832,783,834,881,785,880,883,835,930,884,931,882,836,932,885,837,886,933,884,838,836,934,887,888,839,935,840,886,838,936,889,890,841,842,937,888,938,840,891,892,843,844,939,940,890,842,893,894,845,846,941,942,892,895,896,895,848,847,944,943,897,894,898,897,850,849,946,945,899,851,900,899,852,851,948,901,947,853,902,901,854,853,950,903,949,855,904,856,903,952,905,855,857,951,906,858,905,907,954,857,859,953,908,860,909,907,956,861,859,957,910,862,911,958,909,863,861,959,912,913,864,865,960,911,961,863,914,915,866,867,962,913,963,865,916,917,868,869,964,965,915,867,918,919,870,871,966,967,917,920,921,920,873,872,969,968,922,919,923,922,875,874,971,970,924,876,925,924,877,876,973,926,972,878,927,926,879,975,878,928,880,974,929,881,928,977,930,880,882,976,979,931,-1,-1,1025,980,-1,978,981,933,-1,982,-1,980,934,932,983,935,-1,984,982,-1,936,934,985,-1,986,937,938,984,-1,-1,987,988,939,-1,-1,940,986,938,989,990,-1,941,942,-1,988,-1,991,992,-1,944,943,-1,990,-1,993,994,946,-1,-1,945,992,947,995,996,-1,948,947,-1,-1,994,997,998,950,-1,-1,949,996,951,999,1000,952,-1,-1,951,953,998,1001,1002,954,-1,-1,953,955,-1,1004,1003,956,-1,-1,957,955,1005,1006,1005,958,-1,-1,959,957,-1,1008,1007,-1,960,961,-1,-1,1009,1010,1009,962,-1,-1,963,1011,961,1012,1011,-1,964,965,-1,1013,-1,1014,1013,-1,966,967,-1,1015,-1,1016,1015,-1,969,968,-1,1017,-1,1018,1017,-1,971,970,1019,-1,-1,1020,1019,973,-1,-1,972,1021,974,1022,975,-1,1021,1023,-1,974,976,1024,977,-1,1023,1025,-1,976,978]},"3":{"rings":42,"count":2340,"defaultK":10,"kMax":18,"geodesic":[0,6,3,4,2,7,1,5,14,9,19,12,16,17,11,10,18,15,20,21,36,8,37,38,58,19,9,22,35,39,57,1,59,60,85,7,23,24,22,41,10,40,42,11,9,39,21,25,64,2,43,63,65,3,26,27,25,45,12,44,13,46,11,43,24,28,69,68,3,4,47,14,28,27,29,47,14,48,13,46,49,15,30,26,72,4,71,12,73,5,31,30,32,51,16,52,15,50,17,53,33,29,76,77,6,5,49,14,34,35,33,55,18,56,54,17,19,57,36,32,81,7,53,82,80,6,86,116,87,59,117,150,118,60,85,115,88,37,151,119,149,188,152,84,89,90,88,120,62,61,121,119,63,122,91,87,60,39,155,154,40,156,92,93,91,64,124,123,65,63,125,122,90,94,41,158,159,66,42,157,95,96,94,127,67,126,66,128,68,97,93,162,125,43,44,65,163,161,98,97,99,130,69,70,131,129,68,71,96,100,132,166,46,45,165,128,102,103,101,73,135,134,72,74,136,133,104,100,171,48,170,49,71,172,105,104,106,138,76,75,137,139,77,74,103,107,136,174,50,51,175,140,108,109,107,141,78,142,79,140,77,106,110,178,143,53,52,80,177,179,111,112,110,81,144,145,80,82,143,146,113,109,55,182,181,79,54,183,114,115,113,148,83,84,147,149,82,146,112,116,85,57,185,186,56,184,189,229,190,151,230,231,273,188,152,228,191,117,274,232,272,320,275,150,192,191,193,233,154,234,153,232,155,235,194,190,277,278,119,120,152,231,195,194,196,236,157,237,156,235,158,238,155,197,193,122,281,280,282,121,198,197,199,240,159,239,160,241,158,238,161,196,200,284,124,125,285,283,201,200,202,243,162,242,163,244,161,199,203,127,288,241,287,164,126,245,204,205,203,246,165,247,164,245,166,206,202,291,129,248,130,292,163,244,249,250,248,294,207,295,206,293,208,296,251,247,205,343,167,342,168,344,252,251,253,297,298,209,210,296,299,208,211,250,254,170,346,345,347,169,255,256,254,301,212,300,213,302,211,299,257,253,214,349,173,350,172,348,215,214,216,258,175,257,176,259,174,213,217,304,139,256,138,303,177,260,218,217,219,261,178,262,177,260,179,220,216,141,307,263,308,176,142,259,221,222,220,264,181,265,180,263,182,266,179,223,219,311,144,143,310,312,224,225,223,268,183,267,184,269,182,266,185,226,222,146,314,315,313,147,227,228,226,271,186,270,187,272,185,269,229,225,318,317,149,148,188,273,371,372,422,321,423,476,424,370,322,421,373,274,477,425,475,478,532,369,374,375,373,426,324,427,323,425,325,376,372,480,277,428,481,276,322,424,377,378,376,429,327,430,326,428,328,379,375,431,325,279,483,484,280,427,381,382,380,433,331,434,330,432,332,435,329,379,383,283,488,487,284,282,384,383,385,436,437,333,334,435,438,332,335,382,386,491,286,285,490,492,387,388,386,440,336,439,337,441,335,438,338,385,389,494,288,289,495,493,391,392,390,444,340,443,341,445,339,393,389,442,292,342,499,498,293,291,394,395,393,447,343,446,344,448,342,396,392,295,502,445,501,345,294,449,397,396,398,346,450,449,451,345,347,395,399,505,297,298,448,452,504,506,400,401,399,453,349,454,348,452,350,402,398,300,508,455,509,347,301,451,404,405,403,457,353,458,352,456,354,459,406,402,304,351,513,512,303,305,407,408,406,460,356,461,355,459,357,462,354,409,405,516,307,306,515,517,410,409,411,463,464,358,359,462,465,357,360,408,412,519,309,310,518,520,413,412,414,467,361,466,362,468,360,465,363,411,415,312,522,523,311,313,417,416,418,471,365,470,366,472,364,415,419,469,367,316,527,526,315,473,420,419,421,474,368,473,369,475,367,422,418,530,318,472,529,319,370,476,533,534,590,477,591,650,592,532,478,535,589,423,651,593,649,652,712,476,536,535,537,594,480,595,479,593,481,538,534,654,426,596,655,425,478,592,539,538,540,597,483,598,482,596,484,537,541,599,657,429,481,658,428,595,543,542,544,601,487,602,486,600,488,603,485,541,545,662,432,661,433,663,546,547,545,604,490,605,489,603,491,606,488,544,548,665,435,664,436,666,549,550,548,608,492,607,493,609,491,606,494,551,547,668,438,669,437,667,552,551,553,611,495,610,496,612,494,609,497,550,554,671,441,672,440,670,556,555,557,615,499,614,500,616,498,554,558,613,676,444,501,675,445,617,559,560,558,618,502,617,503,619,501,561,557,679,447,616,678,448,504,620,562,561,563,505,621,620,622,504,506,560,564,450,682,619,623,681,683,449,565,564,566,624,508,625,507,623,509,563,567,685,453,626,686,452,506,622,568,569,567,627,511,628,510,626,512,570,566,629,688,456,509,689,455,625,572,573,571,631,515,632,514,630,516,633,513,574,570,693,459,692,460,694,575,576,574,634,518,635,517,633,519,636,516,577,573,696,462,695,463,697,578,579,577,638,520,637,521,639,519,636,522,580,576,699,465,700,464,698,581,582,580,641,523,640,524,642,522,639,525,583,579,702,468,703,467,701,585,584,586,645,527,644,528,646,526,587,583,643,707,471,529,706,472,647,588,587,589,648,530,647,531,649,529,586,590,710,474,646,709,475,532,650,713,714,775,651,776,839,777,712,652,774,715,591,840,838,778,841,905,711,716,715,717,779,654,780,653,778,655,718,714,843,594,844,781,593,652,777,719,718,720,782,657,783,656,781,658,717,721,846,597,847,596,784,655,780,722,721,723,785,660,786,659,784,661,724,720,849,600,850,599,787,658,783,726,727,725,789,664,790,663,788,665,724,728,854,791,603,662,853,604,787,729,728,730,792,667,793,666,791,668,731,727,794,665,857,606,856,607,858,732,731,733,795,670,796,669,794,671,797,668,730,734,860,609,859,610,861,735,736,734,798,673,799,672,797,674,800,671,737,733,863,612,864,611,862,738,739,737,801,676,802,675,800,677,803,674,736,740,866,615,867,614,865,741,740,742,804,679,805,678,803,680,806,677,743,739,869,618,870,617,868,744,743,745,807,682,808,681,806,683,809,680,742,746,872,621,873,620,871,748,749,747,812,685,811,686,813,684,810,687,746,750,877,624,876,625,878,751,750,752,815,688,814,689,816,687,813,690,753,749,880,627,879,628,881,754,753,755,818,691,817,692,819,690,816,693,752,756,883,630,882,631,884,757,758,756,821,694,820,695,822,693,819,696,759,755,886,633,887,632,885,760,761,759,824,697,823,698,825,696,758,762,822,699,889,636,890,635,888,763,762,764,827,700,826,701,828,699,765,761,892,825,639,702,893,638,829,767,766,768,831,704,830,705,832,703,765,769,897,642,896,643,829,706,833,770,771,769,834,707,833,708,835,706,772,768,900,645,899,646,832,709,836,773,772,774,837,710,836,711,838,709,775,771,903,648,902,835,649,712,839,906,907,972,840,973,974,1040,841,905,971,908,776,1041,1039,975,1042,1109,904,909,910,908,976,843,977,842,975,844,911,907,1044,779,978,778,1045,841,974,912,911,913,979,846,980,845,978,847,910,914,1047,782,981,781,844,1048,977,916,917,915,983,850,984,849,982,851,914,918,1051,786,985,785,848,1052,981,919,920,918,986,853,987,852,985,854,921,917,1054,988,788,851,789,1055,984,922,923,921,989,856,990,855,988,857,924,920,991,854,791,1057,1058,792,790,925,924,926,992,859,993,858,991,860,994,927,923,857,794,1061,1060,795,793,928,927,929,995,862,996,861,994,863,997,860,926,930,797,1064,1063,798,796,932,931,933,999,866,1000,865,998,867,1001,864,930,934,801,1068,1067,800,802,935,936,934,1002,869,1003,868,1001,870,1004,867,937,933,1071,804,803,1070,1072,938,937,939,1005,872,1006,871,1004,873,1007,870,936,940,1074,807,806,1073,1075,941,940,942,1009,874,1008,875,1010,873,1007,876,939,943,1077,809,810,1078,1076,944,943,945,1012,877,1011,878,1013,876,1010,879,942,946,1080,812,813,1081,1079,947,946,948,1015,880,1014,881,1016,879,1013,882,945,949,815,1083,1084,816,814,951,952,950,1019,884,1018,885,1020,883,1017,886,953,949,819,1087,1088,818,820,954,955,953,1022,887,1021,888,1023,886,1020,952,956,889,822,1090,1091,821,823,957,956,958,1025,890,1024,891,1026,889,955,959,1023,892,825,1094,1093,824,826,960,959,961,1028,893,1027,894,1029,892,958,962,1097,1026,828,895,827,1096,1030,963,962,964,1031,896,1030,897,1032,895,961,965,1100,830,1029,831,898,1099,1033,967,966,968,1035,900,1034,901,1036,899,969,965,1104,834,1033,835,902,1103,1037,970,969,971,1038,903,1037,904,1039,902,968,972,1107,837,1036,838,1106,905,1040,1110,1179,1111,1180,1041,1249,1181,1042,1109,1178,1112,973,1250,1248,1182,1251,1320,1043,1113,1112,1114,1183,1044,1043,1182,1184,1045,1111,1115,1253,976,1042,975,1254,1181,1185,1116,1115,1117,1186,1047,1046,1185,1187,1048,1114,1118,1256,979,1045,978,1257,1184,1188,1120,1121,1119,1190,1051,1050,1191,1189,1052,1122,1118,1260,983,1049,982,1261,1192,1188,1123,1122,1124,1193,1054,1053,1192,1194,1055,1125,1121,1263,986,1052,985,1264,1195,1191,1126,1125,1127,1196,1057,1056,1195,1197,1058,1128,1124,1266,1055,989,988,1267,1194,1198,1129,1130,1128,1199,1060,1059,1200,1198,1061,1131,1127,1058,1269,991,992,1270,1201,1197,1132,1133,1131,1202,1063,1062,1203,1201,1064,1061,1130,1134,1272,994,995,1273,1204,1200,1135,1134,1136,1205,1066,1065,1206,1204,1067,1064,1137,1133,997,1275,1276,998,1207,1203,1139,1138,1140,1209,1070,1069,1208,1210,1071,1068,1137,1141,1001,1279,1280,1002,1207,1211,1142,1143,1141,1212,1073,1072,1213,1211,1074,1071,1144,1140,1004,1282,1283,1005,1214,1210,1145,1146,1144,1215,1076,1075,1216,1214,1077,1074,1147,1143,1007,1286,1285,1217,1213,1008,1148,1147,1149,1218,1078,1079,1217,1219,1077,1080,1150,1146,1010,1289,1288,1009,1216,1220,1151,1152,1150,1221,1081,1082,1222,1220,1080,1083,1153,1149,1013,1292,1291,1012,1223,1219,1155,1154,1156,1225,1085,1086,1224,1226,1084,1087,1153,1157,1017,1296,1295,1016,1223,1227,1158,1159,1157,1228,1088,1089,1227,1229,1087,1090,1160,1156,1299,1020,1019,1298,1230,1226,1161,1160,1162,1231,1091,1092,1230,1232,1090,1159,1163,1093,1302,1023,1022,1301,1229,1233,1164,1163,1165,1234,1094,1095,1233,1235,1093,1162,1166,1305,1096,1025,1026,1304,1232,1236,1167,1168,1166,1237,1097,1098,1238,1236,1096,1169,1165,1308,1028,1099,1029,1307,1239,1235,1170,1171,1169,1240,1100,1101,1241,1239,1099,1168,1172,1311,1031,1102,1032,1310,1242,1238,1174,1173,1175,1244,1104,1105,1245,1243,1103,1172,1176,1315,1035,1106,1036,1314,1246,1242,1177,1176,1178,1247,1107,1108,1246,1248,1106,1175,1179,1318,1038,1109,1039,1317,1245,1249,1321,1322,1392,1393,1250,1394,1464,1251,1320,1323,1391,1465,1180,1395,1463,1466,1537,1252,1324,1325,1323,1396,1253,1252,1397,1395,1254,1326,1322,1468,1183,1251,1182,1469,1398,1394,1327,1328,1326,1399,1256,1255,1400,1398,1257,1329,1325,1471,1186,1254,1185,1472,1401,1397,1330,1329,1331,1402,1259,1258,1401,1403,1260,1328,1332,1474,1189,1257,1188,1475,1404,1400,1334,1333,1335,1406,1263,1262,1405,1407,1264,1336,1332,1478,1193,1261,1192,1479,1408,1404,1337,1336,1338,1409,1266,1265,1410,1408,1267,1339,1335,1481,1264,1196,1195,1482,1407,1411,1340,1339,1341,1412,1269,1268,1413,1411,1270,1338,1342,1267,1484,1198,1199,1485,1410,1414,1343,1344,1342,1415,1272,1271,1414,1416,1273,1270,1341,1345,1487,1201,1202,1488,1413,1417,1346,1347,1345,1418,1275,1274,1419,1417,1276,1273,1348,1344,1204,1490,1491,1205,1420,1416,1349,1350,1348,1421,1278,1277,1422,1420,1279,1276,1347,1351,1207,1493,1494,1208,1419,1423,1352,1351,1353,1424,1281,1280,1423,1425,1282,1279,1354,1350,1210,1496,1497,1211,1426,1422,1355,1356,1354,1427,1284,1283,1428,1426,1285,1282,1353,1357,1213,1499,1500,1214,1429,1425,1359,1360,1358,1431,1287,1288,1432,1430,1286,1289,1361,1357,1217,1504,1503,1216,1433,1429,1362,1363,1361,1434,1290,1291,1435,1433,1289,1292,1364,1360,1220,1507,1506,1219,1436,1432,1365,1364,1366,1437,1293,1294,1436,1438,1292,1295,1367,1363,1223,1510,1509,1222,1439,1435,1368,1367,1369,1440,1296,1297,1439,1441,1295,1298,1366,1370,1226,1513,1512,1225,1438,1442,1371,1370,1372,1443,1299,1300,1442,1444,1298,1301,1373,1369,1516,1229,1228,1515,1445,1441,1374,1375,1373,1446,1302,1303,1447,1445,1301,1376,1372,1304,1519,1232,1231,1518,1444,1448,1377,1378,1376,1449,1305,1306,1450,1448,1304,1379,1375,1522,1307,1234,1235,1521,1451,1447,1380,1379,1381,1452,1308,1309,1451,1453,1307,1378,1382,1525,1237,1310,1238,1524,1450,1454,1384,1383,1385,1456,1312,1313,1455,1457,1311,1382,1386,1529,1241,1314,1242,1528,1454,1458,1387,1386,1388,1459,1315,1316,1460,1458,1314,1389,1385,1532,1244,1317,1245,1531,1461,1457,1390,1391,1389,1462,1318,1319,1463,1461,1317,1392,1388,1535,1247,1320,1248,1534,1464,1460,1611,1612,1683,1684,1538,1757,1685,1539,1610,1613,1682,1758,1465,1686,1756,1540,1609,1831,1614,1613,1615,1541,1687,1688,1540,1542,1686,1612,1616,1468,1761,1689,1762,1539,1543,1467,1617,1618,1616,1544,1690,1691,1545,1543,1689,1619,1615,1471,1764,1692,1765,1542,1546,1472,1621,1620,1622,1548,1694,1695,1547,1549,1693,1619,1623,1475,1768,1696,1769,1546,1550,1474,1624,1623,1625,1551,1697,1698,1550,1552,1696,1626,1622,1478,1771,1699,1772,1549,1553,1477,1627,1628,1626,1554,1700,1701,1553,1555,1699,1629,1625,1481,1774,1702,1775,1556,1552,1482,1630,1631,1629,1557,1703,1704,1556,1558,1702,1705,1628,1632,1484,1777,1778,1555,1559,1485,1633,1632,1634,1560,1706,1707,1559,1561,1705,1708,1631,1635,1487,1780,1781,1558,1562,1486,1636,1637,1635,1563,1709,1710,1564,1562,1708,1711,1638,1634,1490,1783,1784,1565,1561,1491,1640,1641,1639,1567,1713,1714,1568,1566,1712,1715,1642,1638,1494,1787,1788,1565,1569,1495,1643,1644,1642,1570,1716,1717,1571,1569,1715,1718,1645,1641,1497,1790,1791,1572,1568,1498,1646,1645,1647,1573,1719,1720,1572,1574,1718,1721,1644,1648,1500,1793,1794,1571,1575,1501,1649,1650,1648,1576,1723,1722,1575,1577,1724,1721,1651,1647,1503,1797,1796,1578,1574,1502,1652,1653,1651,1579,1726,1725,1580,1578,1727,1724,1654,1650,1506,1800,1799,1581,1577,1507,1655,1654,1656,1582,1729,1728,1583,1581,1730,1727,1657,1653,1509,1803,1802,1584,1580,1510,1659,1658,1660,1586,1733,1732,1585,1587,1734,1731,1657,1661,1513,1807,1806,1584,1588,1512,1662,1663,1661,1589,1736,1735,1588,1590,1737,1734,1660,1664,1516,1810,1809,1591,1587,1517,1665,1666,1664,1592,1739,1738,1593,1591,1740,1737,1663,1667,1519,1813,1812,1594,1590,1520,1668,1667,1669,1595,1742,1741,1594,1596,1743,1666,1670,1522,1816,1740,1815,1593,1597,1521,1671,1672,1670,1598,1745,1744,1599,1597,1746,1669,1673,1525,1819,1743,1818,1596,1600,1524,1674,1673,1675,1601,1748,1747,1602,1600,1749,1676,1672,1528,1822,1746,1821,1603,1599,1527,1678,1679,1677,1605,1752,1751,1606,1604,1753,1676,1680,1532,1826,1750,1825,1607,1603,1533,1681,1680,1682,1608,1755,1754,1609,1607,1756,1683,1679,1535,1829,1753,1828,1606,1610,1534,1832,1905,1833,1906,1758,1831,1759,1907,1978,1834,1904,1979,1684,1760,1830,1757,1685,1980,1835,1836,1834,1761,1909,1908,1762,1760,1910,1833,1837,1687,1982,1907,1759,1763,1981,1688,1838,1837,1839,1764,1912,1911,1765,1763,1913,1836,1840,1690,1985,1910,1984,1766,1762,1691,1842,1841,1843,1768,1916,1915,1767,1769,1917,1844,1840,1694,1989,1914,1988,1770,1766,1695,1845,1844,1846,1771,1919,1918,1770,1772,1920,1843,1847,1697,1992,1917,1991,1769,1773,1696,1848,1849,1847,1774,1922,1921,1773,1775,1923,1850,1846,1700,1995,1920,1994,1776,1772,1701,1851,1852,1850,1777,1925,1924,1778,1776,1926,1853,1849,1703,1923,1998,1997,1779,1775,1704,1855,1854,1856,1781,1929,1928,1780,1782,1930,1927,1853,1857,1707,2002,2001,1779,1783,1708,1858,1857,1859,1784,1932,1931,1783,1785,1933,1930,1856,1860,1710,2005,2004,1782,1786,1709,1861,1860,1862,1787,1935,1934,1786,1788,1936,1933,1859,1863,1713,2008,2007,1785,1789,1712,1864,1865,1863,1790,1938,1937,1789,1791,1939,1936,1866,1862,1716,2011,2010,1792,1788,1717,1867,1868,1866,1793,1941,1940,1794,1792,1942,1939,1865,1869,1719,2014,2013,1795,1791,1720,1871,1870,1872,1797,1944,1945,1796,1798,1943,1946,1869,1873,1723,2017,2018,1795,1799,1722,1874,1875,1873,1800,1947,1948,1801,1799,1946,1949,1876,1872,1726,2020,2021,1802,1798,1727,1877,1876,1878,1803,1950,1951,1802,1804,1949,1952,1875,1879,1729,2023,2024,1801,1805,1728,1880,1879,1881,1806,1953,1954,1805,1807,1952,1955,1878,1882,1732,2026,2027,1804,1808,1731,1883,1884,1882,1809,1956,1957,1810,1808,1955,1958,1885,1881,1735,2029,2030,1811,1807,1736,1887,1888,1886,1813,1960,1961,1814,1812,1959,1889,1885,1739,1962,2033,2034,1815,1811,1740,1890,1891,1889,1816,1963,1964,1815,1817,1962,1888,1892,1742,2036,1965,2037,1814,1818,1741,1893,1894,1892,1819,1966,1967,1820,1818,1965,1895,1891,1745,2039,1968,2040,1821,1817,1746,1896,1895,1897,1822,1969,1970,1821,1823,1968,1894,1898,1748,2042,1971,2043,1820,1824,1747,1900,1901,1899,1826,1973,1974,1825,1827,1972,1898,1902,1752,2046,1975,2047,1824,1828,1753,1903,1904,1902,1829,1976,1977,1830,1828,1975,1905,1901,1755,2049,1978,1831,1827,2050,1756,2052,2053,2124,1979,2125,1980,2051,2126,2196,2054,2123,2197,1906,1981,2050,1907,1978,2198,2055,2056,2054,1982,2128,2127,1983,1981,2129,2057,2053,1909,2200,2126,2199,1984,1980,1908,2058,2059,2057,1985,2131,2130,1986,1984,2132,2060,2056,1912,2203,2129,2202,1987,1983,1911,2062,2061,2063,1989,2135,2134,1988,1990,2136,2060,2064,1916,2207,2133,2206,1987,1991,1917,2065,2064,2066,1992,2138,2137,1991,1993,2139,2067,2063,1919,2210,2136,2209,1994,1990,1918,2068,2069,2067,1995,2141,2140,1994,1996,2142,2070,2066,1922,2213,2139,2212,1997,1993,1921,2071,2072,2070,1998,2144,2143,1999,1997,2145,2069,2073,1925,2142,2216,2215,1996,2000,1926,2074,2073,2075,2001,2147,2146,2002,2000,2148,2145,2072,2076,1928,2219,2218,1999,2003,1927,2077,2078,2076,2004,2150,2149,2005,2003,2151,2148,2079,2075,1931,2222,2221,2006,2002,1932,2081,2082,2080,2008,2154,2153,2009,2007,2155,2152,2079,2083,1935,2226,2225,2006,2010,1936,2084,2085,2083,2011,2157,2156,2012,2010,2158,2155,2086,2082,1938,2229,2228,2013,2009,1939,2087,2086,2088,2014,2160,2159,2013,2015,2161,2158,2085,2089,1941,2232,2231,2012,2016,1940,2090,2089,2091,2017,2162,2163,2016,2018,2161,2164,2092,2088,1944,2234,2235,2019,2015,1945,2093,2094,2092,2020,2165,2166,2021,2019,2164,2167,2095,2091,1947,2237,2238,2022,2018,1946,2096,2095,2097,2023,2168,2169,2022,2024,2167,2170,2098,2094,1950,2240,2241,2021,2025,1949,2100,2099,2101,2027,2172,2173,2026,2028,2171,2174,2098,2102,1954,2244,2245,2025,2029,1953,2103,2102,2104,2030,2175,2176,2029,2031,2174,2177,2101,2105,1957,2247,2248,2032,2028,1956,2106,2107,2105,2033,2178,2179,2034,2032,2177,2108,2104,1960,2180,2250,2251,2035,2031,1959,2109,2108,2110,2036,2181,2182,2035,2037,2180,2107,2111,1963,2253,2183,2254,2034,2038,1962,2112,2113,2111,2039,2184,2185,2040,2038,2183,2114,2110,1966,2256,2186,2257,2041,2037,1967,2115,2116,2114,2042,2187,2188,2043,2041,2186,2113,2117,1969,2259,2189,2260,2040,2044,1968,2119,2118,2120,2046,2191,2192,2045,2047,2190,2117,2121,1973,2263,2193,2264,2048,2044,1972,2122,2121,2123,2049,2194,2195,2048,2050,2193,2120,2124,1976,2266,2196,2267,2047,2051,1975,2269,-1,-1,2339,2270,2197,-1,-1,2198,2268,-1,-1,-1,2271,2338,-1,2125,-1,2272,2273,2271,-1,2200,-1,2201,2199,-1,-1,-1,-1,2270,2274,2128,2202,-1,2129,2275,-1,2276,2274,2203,-1,2204,-1,2202,-1,-1,-1,2277,2273,2131,-1,-1,2205,2278,-1,2279,2277,2206,-1,2207,-1,2205,-1,-1,-1,2280,2276,2134,2208,-1,-1,2281,-1,2282,2280,2209,-1,2210,-1,2208,-1,-1,-1,2283,2279,2137,2211,-1,2138,2284,-1,2283,2285,2212,-1,2213,-1,2211,-1,-1,-1,2282,2286,2140,2214,-1,-1,2288,-1,2289,2287,2216,-1,2217,-1,2215,-1,-1,-1,2218,2290,2286,2144,-1,2145,2291,-1,2290,2292,2219,-1,2220,-1,2218,-1,-1,-1,2221,2289,2293,2147,-1,-1,2294,2293,2295,-1,-1,2222,2223,-1,-1,2221,-1,-1,2224,2296,2292,2150,2151,-1,2297,-1,2298,2296,2225,2226,-1,-1,2224,-1,2227,-1,-1,2299,2295,-1,-1,2153,2300,2301,2299,-1,-1,2228,2229,-1,-1,2227,2230,-1,-1,2302,2298,2156,2157,-1,2303,-1,2304,2302,2231,2232,-1,-1,2230,-1,2233,-1,-1,2305,2301,-1,-1,2159,2306,-1,2307,2305,2235,-1,2234,-1,-1,2236,2233,-1,-1,2308,2304,2163,2162,-1,2309,-1,2308,2310,2238,-1,2237,-1,2239,-1,-1,2236,-1,2307,2311,2166,2165,-1,2312,-1,2311,2313,2241,2240,-1,-1,2242,-1,-1,2239,-1,2310,2314,2169,-1,-1,2315,2314,2316,-1,2244,-1,2243,-1,-1,2245,-1,-1,2242,2317,2313,2172,2171,-1,2318,-1,2317,2319,2247,2246,-1,-1,2248,-1,-1,2245,-1,-1,2316,2320,-1,2175,2321,2320,2322,-1,2250,-1,2249,-1,2251,-1,-1,-1,2248,2319,2323,2178,2177,-1,2325,-1,2326,2324,2254,-1,2253,-1,2255,-1,-1,-1,-1,2327,2323,-1,2182,2252,2328,2329,2327,-1,2257,-1,2256,2258,-1,-1,-1,-1,2330,2326,2185,2255,2184,-1,2331,-1,2332,2330,2260,-1,2259,-1,2261,-1,-1,-1,2333,2329,2188,-1,-1,2258,2334,-1,2335,2333,2263,-1,2262,2264,-1,-1,-1,-1,2336,2332,2191,-1,2261,2190,2337,-1,2338,2336,2266,-1,2265,-1,2267,-1,-1,-1,2339,2335,2194,-1,-1,2264],"visual":[0,5,4,3,1,7,6,2,16,8,17,9,10,15,11,18,14,12,20,37,36,21,8,38,58,19,9,22,35,59,1,39,57,60,85,7,23,22,41,40,10,24,42,9,11,39,21,2,64,63,25,3,43,65,26,25,44,45,12,27,43,13,11,24,46,68,3,69,67,4,42,28,29,28,48,14,49,47,30,27,15,13,50,46,72,73,4,5,74,71,31,32,52,51,16,30,53,15,17,33,50,77,6,78,76,5,54,29,34,35,55,56,18,33,54,17,19,57,36,7,81,82,32,6,53,83,86,117,116,87,150,118,59,85,60,151,115,88,188,152,119,149,37,84,89,120,121,90,88,62,61,119,122,63,155,91,154,87,60,39,156,40,92,124,93,123,91,64,125,65,94,159,63,158,122,66,41,90,42,160,95,127,96,128,67,94,126,68,66,97,162,163,129,44,43,161,93,69,98,99,131,130,70,97,69,132,100,129,71,166,167,46,165,68,45,96,101,102,134,133,135,73,72,100,103,170,74,71,169,171,136,132,48,49,105,104,137,138,75,106,76,136,103,139,74,174,173,50,175,77,51,107,108,141,107,140,78,109,142,77,79,106,178,177,139,52,53,179,110,76,111,144,110,145,112,81,143,80,109,181,82,182,146,79,55,113,54,180,114,148,147,113,115,83,84,149,146,82,185,112,186,116,85,57,184,56,189,230,229,190,273,231,151,274,152,188,320,275,228,191,232,272,117,187,192,233,234,191,193,232,154,153,277,278,155,235,190,194,276,152,231,119,195,236,237,194,196,235,156,157,281,280,238,193,155,158,282,197,122,234,198,239,240,197,199,159,238,160,284,241,158,196,285,283,200,124,161,125,201,243,242,200,202,162,244,161,241,287,288,199,163,286,127,289,160,203,204,246,203,245,247,205,165,164,291,202,244,290,166,292,163,129,248,206,249,207,206,248,250,167,208,168,205,294,295,166,247,293,169,251,132,131,252,209,210,253,251,170,208,211,171,169,297,298,250,254,296,299,134,168,255,212,213,256,254,173,211,172,214,301,300,174,257,302,171,253,136,137,215,258,216,259,257,214,175,176,304,217,260,305,174,303,177,139,256,213,218,261,262,219,217,178,260,179,263,308,307,220,177,309,141,306,180,216,221,265,264,222,220,181,266,180,311,263,182,223,310,312,219,144,179,143,224,268,267,225,223,269,184,183,314,315,266,226,185,182,313,222,146,270,227,271,270,228,226,272,186,187,318,317,185,269,229,225,319,188,273,149,371,321,372,422,370,322,423,274,476,424,320,275,373,421,369,323,230,276,374,324,375,325,323,373,426,277,427,276,376,278,326,425,322,428,372,233,377,378,327,328,326,430,280,376,379,429,279,329,281,431,325,428,278,235,381,330,380,331,382,433,329,283,332,282,434,379,432,284,383,281,238,328,384,333,334,383,385,286,437,436,332,335,285,287,386,382,438,435,284,241,387,337,388,336,386,440,338,289,288,335,439,389,441,290,287,385,244,339,391,390,340,339,341,443,392,389,292,291,444,338,442,293,290,342,445,246,394,343,393,342,344,395,447,295,446,294,392,341,448,296,293,345,445,396,397,346,398,396,345,347,450,297,298,449,451,395,399,344,348,296,299,252,400,349,401,350,348,399,453,300,454,301,402,351,452,299,302,347,455,398,403,404,352,353,351,457,405,402,303,304,456,354,458,302,305,350,455,258,407,355,406,356,408,460,354,306,307,357,461,405,459,305,308,409,260,353,410,359,358,409,411,309,463,464,357,360,310,308,412,408,462,465,311,263,413,362,414,361,412,467,363,312,360,313,466,415,468,311,411,314,266,364,416,417,365,364,366,470,315,418,415,471,316,363,314,469,367,472,317,269,420,368,419,367,369,421,474,318,473,319,418,317,366,475,370,472,422,271,533,477,534,590,532,478,591,650,592,423,476,424,535,589,531,479,593,649,536,480,537,481,535,479,594,595,426,538,593,425,427,482,596,478,534,654,539,540,483,484,598,482,597,538,541,429,599,485,430,428,596,481,658,537,543,542,486,487,601,544,485,600,602,432,541,488,433,431,545,484,599,603,546,489,545,490,547,604,605,488,435,491,603,544,434,436,548,606,665,487,549,493,550,492,548,608,607,494,438,491,609,551,437,439,547,606,668,495,552,553,496,495,611,551,497,612,610,441,554,494,440,442,550,498,613,609,556,555,499,498,614,500,615,557,554,444,613,497,443,445,616,501,675,558,559,502,558,501,560,503,618,617,447,557,619,448,446,500,616,504,561,679,562,505,563,561,506,504,621,622,620,450,449,451,560,564,507,503,619,623,565,508,566,509,564,507,624,625,453,567,623,452,454,510,626,506,563,685,568,569,511,512,628,510,627,567,570,456,629,513,455,457,626,509,689,566,572,571,514,515,631,573,513,630,632,459,570,516,458,460,574,512,633,629,575,517,574,518,576,634,635,516,462,519,633,573,461,463,577,636,696,515,578,521,579,520,577,638,637,522,465,519,639,580,464,466,576,636,699,523,581,582,524,523,641,580,525,642,640,468,583,522,467,469,579,526,639,643,585,584,527,526,644,528,645,586,583,471,643,525,470,472,646,529,706,587,588,530,587,529,589,531,648,647,474,586,649,475,473,528,646,532,590,710,713,651,714,775,776,652,712,839,777,591,774,715,592,650,711,653,840,778,716,717,654,779,715,655,653,780,778,594,718,593,595,656,714,781,652,843,719,720,657,658,782,783,718,656,721,597,781,659,784,598,596,717,847,655,722,723,660,661,786,785,721,659,724,600,787,662,784,599,601,850,658,720,726,725,663,664,789,788,727,724,662,790,665,603,602,604,787,853,728,854,729,728,667,666,792,730,791,793,665,668,727,606,607,605,731,857,856,790,732,731,670,669,733,795,796,671,794,668,609,730,610,608,734,797,860,859,735,673,736,734,672,798,799,674,612,797,671,737,800,611,613,733,863,675,738,739,676,675,802,737,801,677,615,740,803,674,800,616,614,736,866,678,741,742,679,805,678,740,680,804,743,806,618,619,617,677,803,681,870,739,745,744,682,808,681,683,746,743,807,809,621,622,620,680,684,873,806,810,748,747,685,811,686,749,684,812,746,810,624,623,625,687,813,683,876,750,751,750,688,689,814,752,815,687,627,749,813,690,816,628,626,753,880,686,754,691,753,755,692,818,817,690,630,819,693,752,816,629,631,756,883,689,757,758,694,695,756,821,820,693,822,696,633,759,632,634,755,819,886,887,760,761,697,698,824,759,823,825,696,699,762,636,637,635,758,890,889,826,763,764,701,700,827,828,762,765,702,826,699,639,638,640,829,893,761,892,767,766,704,703,830,831,768,705,765,642,829,702,832,643,641,896,706,769,770,769,707,706,834,833,771,708,768,645,835,705,832,644,646,772,899,709,773,772,710,837,774,709,711,836,838,648,771,649,647,708,775,835,712,903,906,973,972,907,840,1040,974,841,905,776,971,908,1041,839,777,904,842,1039,909,910,976,843,908,977,844,842,975,911,779,978,845,1044,780,778,907,1045,912,913,846,979,980,847,911,914,845,978,981,782,848,783,1048,1047,781,910,916,915,983,849,850,982,917,914,984,848,851,785,981,1051,786,784,1050,1052,919,918,986,853,852,920,985,987,854,917,851,788,789,1054,984,921,787,1055,922,921,989,923,856,855,990,988,857,791,920,854,924,792,991,1057,1058,790,925,926,859,992,993,924,858,860,991,927,994,794,795,857,1061,923,1060,793,928,929,996,862,995,927,863,861,930,997,797,994,798,1064,864,860,796,926,932,931,999,865,866,998,933,1000,864,930,800,801,867,1067,997,1068,863,799,935,934,1002,868,869,936,1003,1001,867,933,870,803,804,1071,1004,1070,937,802,938,937,1005,939,871,1006,872,1004,870,873,936,1007,806,807,940,1074,1073,805,941,942,1009,940,875,1008,874,1010,876,873,943,1007,810,809,939,1077,1078,811,944,945,1012,878,877,943,1011,1013,879,946,876,813,812,1080,1010,1081,942,814,947,948,1015,881,880,1016,946,1014,882,949,816,815,879,1084,1017,1083,883,817,951,950,1018,884,1019,952,885,883,949,1017,819,1020,818,1087,886,882,820,953,954,953,887,1022,1021,955,888,886,1023,952,1020,822,821,889,1090,956,1091,823,957,958,1025,956,890,891,1024,1026,889,825,959,892,955,824,1023,1094,1093,826,960,961,1028,893,894,959,1029,1027,892,962,895,828,827,1097,1030,958,829,1096,963,964,1031,897,896,1032,962,965,1030,898,895,831,1033,1100,830,832,1101,1099,967,966,900,1035,1034,899,968,965,901,1036,1033,834,898,833,1103,1104,835,969,970,969,1038,903,971,1037,902,904,1039,968,837,1036,901,1107,836,838,972,1106,1110,1180,1111,1179,1041,1249,1181,1042,1109,1250,1178,1112,973,1320,1251,1248,1182,1043,1113,1183,1114,1184,1044,1112,1045,1182,1043,1115,1253,1185,976,1254,1046,1111,977,975,1116,1117,1186,1187,1047,1048,1115,1185,1118,1046,1188,1256,1257,1049,979,980,978,1114,1120,1119,1190,1189,1050,1051,1121,1118,1191,1188,1049,1052,1260,1259,982,983,1261,981,1123,1122,1193,1192,1054,1124,1053,1194,1121,1055,1052,1263,1191,985,1262,986,1264,1125,1126,1196,1125,1127,1057,1195,1056,1197,1058,1124,1266,1055,1128,988,1267,989,1194,1265,1129,1199,1130,1128,1060,1200,1198,1059,1061,1131,1269,1270,1127,992,1058,991,1201,1197,1132,1133,1202,1203,1063,1131,1062,1201,1064,1134,1273,1204,1272,995,994,1061,1130,1065,1135,1136,1205,1206,1066,1134,1067,1137,1065,1204,1207,1276,998,1275,997,1068,1277,1064,1139,1138,1209,1208,1069,1140,1070,1210,1137,1068,1207,1279,1001,1071,1280,1000,1278,1002,1142,1212,1141,1211,1143,1072,1073,1213,1071,1140,1282,1074,1210,1283,1004,1144,1003,1005,1145,1215,1144,1146,1075,1076,1216,1214,1077,1074,1286,1285,1147,1143,1007,1217,1213,1006,1148,1218,1149,1219,1147,1079,1078,1217,1080,1150,1289,1077,1220,1288,1010,1146,1011,1009,1151,1152,1221,1222,1082,1150,1081,1220,1153,1083,1223,1292,1013,1080,1291,1014,1293,1012,1155,1154,1225,1224,1085,1156,1084,1153,1086,1226,1223,1295,1016,1296,1017,1083,1294,1087,1158,1157,1228,1227,1088,1159,1089,1229,1087,1156,1298,1226,1299,1019,1020,1090,1160,1086,1161,1231,1160,1162,1091,1230,1232,1092,1090,1159,1302,1301,1163,1022,1093,1023,1229,1233,1164,1234,1165,1163,1094,1235,1095,1233,1093,1166,1305,1096,1162,1026,1304,1025,1236,1306,1167,1168,1237,1238,1097,1166,1098,1236,1169,1096,1099,1308,1239,1029,1309,1028,1307,1165,1170,1171,1240,1241,1101,1100,1169,1172,1239,1242,1102,1099,1311,1312,1032,1031,1310,1033,1174,1173,1244,1243,1104,1103,1175,1245,1172,1105,1242,1315,1314,1102,1035,1034,1036,1176,1177,1247,1176,1246,1107,1178,1106,1248,1108,1175,1318,1245,1038,1317,1105,1179,1037,1039,1321,1393,1322,1392,1464,1394,1250,1251,1320,1465,1323,1391,1537,1466,1395,1463,1180,1319,1324,1396,1325,1397,1323,1253,1395,1254,1252,1468,1326,1469,1398,1467,1322,1183,1255,1394,1327,1399,1328,1400,1326,1256,1398,1257,1255,1471,1329,1472,1401,1186,1258,1470,1325,1187,1330,1331,1402,1403,1259,1329,1260,1401,1332,1404,1258,1475,1474,1261,1189,1190,1476,1473,1334,1333,1406,1405,1262,1263,1335,1332,1407,1404,1478,1261,1477,1264,1192,1479,1193,1191,1337,1409,1336,1408,1265,1338,1266,1410,1335,1481,1407,1264,1480,1267,1482,1195,1196,1339,1340,1412,1339,1411,1341,1269,1268,1413,1484,1338,1270,1410,1267,1485,1483,1198,1342,1199,1343,1415,1342,1414,1344,1416,1272,1271,1487,1273,1488,1341,1270,1413,1345,1486,1201,1417,1346,1418,1347,1345,1419,1417,1275,1274,1490,1276,1491,1348,1344,1273,1420,1416,1204,1205,1349,1421,1350,1422,1348,1278,1420,1277,1279,1494,1493,1351,1423,1276,1347,1207,1208,1495,1352,1424,1353,1425,1281,1351,1423,1280,1282,1354,1497,1426,1496,1498,1210,1279,1211,1350,1355,1356,1427,1428,1284,1354,1357,1283,1426,1285,1500,1429,1499,1501,1213,1214,1282,1286,1359,1358,1431,1430,1287,1360,1357,1288,1432,1286,1503,1429,1504,1502,1217,1216,1289,1285,1362,1434,1361,1433,1290,1363,1435,1291,1289,1360,1506,1432,1507,1505,1220,1292,1219,1364,1365,1437,1364,1436,1366,1293,1438,1294,1292,1509,1510,1363,1435,1295,1367,1223,1222,1508,1368,1440,1367,1369,1439,1441,1296,1297,1513,1295,1512,1366,1370,1298,1438,1442,1226,1225,1371,1443,1372,1444,1370,1442,1299,1300,1516,1298,1515,1373,1301,1445,1369,1517,1229,1441,1374,1446,1375,1447,1373,1302,1303,1445,1519,1376,1301,1448,1304,1518,1520,1232,1372,1231,1377,1449,1378,1450,1306,1376,1305,1448,1379,1522,1451,1307,1523,1304,1521,1235,1234,1375,1380,1381,1452,1453,1309,1308,1379,1382,1451,1454,1525,1310,1526,1307,1238,1524,1237,1239,1384,1383,1456,1455,1312,1385,1311,1457,1382,1454,1313,1528,1529,1310,1241,1240,1527,1530,1387,1459,1386,1458,1388,1315,1460,1314,1316,1532,1385,1531,1457,1244,1313,1533,1389,1243,1390,1462,1389,1461,1391,1318,1463,1317,1319,1535,1388,1534,1460,1536,1392,1247,1316,1464,1611,1538,1539,1610,1612,1683,1465,1684,1466,1537,1685,1757,1540,1609,1613,1682,1393,1467,1614,1541,1542,1615,1540,1613,1468,1687,1469,1688,1467,1543,1616,1686,1539,1470,1612,1396,1617,1544,1618,1545,1543,1616,1471,1472,1690,1691,1546,1619,1470,1473,1689,1692,1399,1542,1621,1548,1620,1547,1475,1474,1549,1694,1546,1622,1619,1693,1476,1473,1695,1402,1692,1403,1624,1551,1623,1550,1552,1625,1478,1697,1477,1549,1696,1622,1479,1698,1476,1406,1553,1405,1627,1554,1553,1626,1555,1628,1481,1700,1480,1482,1701,1552,1699,1625,1556,1629,1479,1409,1630,1557,1558,1631,1556,1629,1484,1703,1485,1704,1483,1559,1702,1632,1555,1628,1412,1486,1633,1560,1634,1561,1559,1632,1487,1707,1488,1706,1562,1486,1635,1708,1489,1705,1558,1415,1636,1563,1637,1564,1562,1490,1635,1491,1710,1565,1638,1709,1489,1711,1492,1418,1708,1561,1640,1567,1639,1566,1494,1568,1713,1493,1641,1565,1638,1712,1714,1495,1492,1421,1422,1569,1643,1570,1642,1569,1571,1644,1497,1716,1496,1717,1568,1641,1498,1715,1495,1572,1424,1645,1646,1573,1572,1645,1574,1647,1500,1719,1720,1499,1501,1571,1644,1575,1718,1648,1721,1498,1649,1576,1577,1650,1575,1648,1503,1723,1722,1504,1502,1578,1651,1574,1724,1647,1721,1505,1652,1579,1653,1580,1578,1651,1506,1726,1507,1725,1581,1654,1505,1727,1508,1577,1434,1650,1655,1582,1656,1583,1509,1581,1729,1510,1654,1584,1657,1730,1728,1508,1511,1437,1436,1580,1659,1586,1658,1585,1587,1513,1660,1512,1732,1584,1657,1733,1514,1731,1511,1440,1734,1588,1662,1589,1661,1588,1590,1663,1516,1735,1515,1736,1587,1517,1660,1734,1514,1737,1591,1443,1665,1592,1591,1664,1593,1666,1519,1739,1518,1738,1520,1590,1740,1663,1594,1667,1446,1517,1668,1595,1596,1669,1594,1667,1522,1742,1523,1521,1741,1597,1743,1670,1593,1666,1524,1449,1671,1598,1672,1599,1597,1670,1525,1745,1526,1600,1746,1673,1524,1744,1527,1452,1596,1453,1674,1601,1675,1602,1528,1529,1600,1748,1603,1673,1676,1749,1527,1530,1747,1456,1750,1455,1678,1605,1677,1604,1606,1679,1532,1531,1752,1751,1603,1676,1533,1530,1753,1750,1459,1607,1681,1608,1607,1680,1609,1682,1535,1755,1534,1754,1536,1606,1679,1756,1610,1533,1683,1462,1832,1758,1833,1905,1759,1831,1906,1684,1978,1907,1685,1757,1834,1904,1830,1760,1611,1756,1835,1761,1836,1762,1834,1760,1909,1687,1910,1688,1837,1908,1763,1686,1759,1833,1689,1911,1838,1839,1764,1765,1912,1837,1913,1763,1690,1840,1691,1766,1911,1689,1692,1914,1617,1618,1842,1841,1768,1767,1843,1916,1915,1769,1694,1693,1840,1766,1695,1917,1914,1692,1770,1844,1845,1771,1844,1770,1846,1772,1919,1918,1697,1696,1698,1843,1769,1920,1773,1847,1917,1695,1848,1774,1849,1775,1847,1773,1922,1700,1921,1701,1923,1699,1850,1776,1772,1846,1702,1627,1851,1777,1852,1778,1925,1850,1776,1703,1704,1926,1853,1924,1779,1702,1705,1775,1849,1630,1855,1854,1781,1780,1928,1856,1853,1782,1929,1707,1779,1706,1927,1708,1705,1930,1633,2001,1858,1784,1857,1783,1859,1785,1931,1932,1710,1709,1856,1782,1711,1930,1933,1708,1786,1860,1861,1787,1860,1862,1786,1788,1935,1934,1713,1712,1714,1859,1785,1936,1789,1863,1933,1711,1864,1790,1865,1791,1863,1789,1938,1716,1937,1717,1866,1792,1715,1939,1788,1862,1936,1718,1867,1868,1793,1794,1941,1866,1792,1719,1720,1869,1940,1795,1942,1718,1721,1646,1791,1865,1871,1870,1797,1796,1944,1872,1798,1723,1722,1869,1945,1795,1943,1724,1721,1649,1799,1873,1874,1800,1873,1799,1875,1801,1947,1726,1948,1725,1872,1798,1727,1946,1802,1876,1949,1724,1877,1803,1878,1876,1804,1802,1950,1951,1729,1730,1728,1879,1805,1949,1801,1875,1952,1731,1880,1806,1881,1807,1879,1805,1954,1953,1732,1733,1882,1808,1731,1955,1952,1734,1804,1878,1883,1884,1809,1810,1957,1882,1885,1808,1956,1735,1811,1736,1958,1734,1737,1955,1662,2030,1887,1813,1886,1812,1960,1888,1814,1739,1738,1959,1885,1961,1811,1740,1737,1815,1889,1665,1890,1816,1889,1815,1891,1817,1963,1742,1964,1741,1962,1743,1888,1814,1818,1892,1740,1668,1893,1819,1894,1820,1892,1818,1966,1967,1745,1746,1744,1895,1821,1965,1817,1891,1968,1747,1896,1897,1822,1823,1895,1969,1970,1821,1748,1749,1898,1824,1747,1968,1971,1750,1820,1894,1900,1899,1826,1825,1973,1901,1972,1827,1752,1898,1751,1824,1974,1753,1750,1971,1678,1677,1903,1829,1902,1828,1904,1830,1976,1755,1975,1754,1901,1977,1827,1756,1831,1905,1753,1974,2052,1979,2053,2124,2125,1980,2051,2126,2196,1906,1907,1978,2054,2123,2050,1981,2197,2127,2055,1982,2056,1983,2128,2054,1981,2129,1909,2127,1910,2057,1984,1908,2053,2200,1980,2130,2058,2059,1985,1986,2131,2057,2132,1984,1912,2060,1913,2130,1987,1911,2133,1914,2203,2204,2062,2061,1989,1988,2134,2135,2063,2060,1990,1987,1916,1915,2133,2136,1917,1914,2206,2207,2065,2064,1992,1991,2138,2137,2066,1993,1919,2063,1918,1990,2139,2136,1920,1917,2210,2209,2068,1995,2067,1994,2069,2141,2140,1996,1922,1921,2142,2066,1923,1993,2139,2070,1997,2213,2071,1998,2072,2070,2144,1999,1997,2143,1925,2145,1926,1924,2073,2000,2069,1996,2142,2216,2074,2075,2001,2002,2147,2073,2000,2146,2148,1928,1929,2076,2003,1927,2219,2072,1999,1930,2077,2078,2004,2005,2150,2076,2151,2003,2149,2079,1931,1932,2006,1930,1933,2222,2152,2075,2081,2080,2008,2007,2153,2154,2082,2079,2009,1935,2152,2006,1934,1936,1933,2225,2155,2226,2084,2083,2011,2010,2156,2085,2157,2012,1938,2082,1937,2155,2009,1939,2158,2228,2086,1936,2087,2014,2086,2088,2013,2159,2160,2015,1941,1940,2158,1942,2085,2012,2161,2089,2016,2231,2090,2017,2091,2089,2018,2163,2162,2016,1944,1945,2164,1943,2092,2019,2161,2088,2015,2235,2093,2094,2020,2021,2166,2092,2165,2019,1947,2095,1948,2167,2022,1946,2164,2238,2091,1949,2096,2097,2023,2024,2169,2168,2095,2098,2022,1950,2170,2025,1951,1949,1952,2241,2167,2240,2100,2099,2027,2026,2172,2101,2171,2028,2173,2098,1954,1953,2025,1955,1952,2244,2170,2102,2103,2102,2030,2029,2175,2104,2031,2176,2174,1957,1956,2101,2028,1958,2247,2105,2032,1955,2106,2033,2105,2107,2178,2032,2034,2179,1960,2177,1959,1961,2104,2031,2108,2035,2180,2250,2109,2036,2110,2037,2108,2181,2182,2035,1963,1964,2180,2111,1962,2038,2183,2107,2034,2253,2112,2113,2039,2040,2184,2185,2111,2038,1966,2114,1967,2041,2183,2186,1965,1968,2256,2257,2115,2116,2042,2043,2188,2187,2114,2117,2041,2044,1969,1970,2189,2186,1968,1971,2260,2259,2119,2118,2046,2045,2191,2120,2190,2047,1973,2117,1972,2192,2044,1974,2189,1971,2263,2262,2122,2049,2121,2048,2194,2123,2050,2193,1976,2195,1975,2120,2047,1977,2124,2266,2051,2192,2269,2197,-1,-1,2270,2339,-1,2198,2268,-1,2125,-1,-1,2126,2196,-1,2338,2271,2272,2200,2273,-1,-1,2271,2201,2199,-1,-1,2128,-1,-1,2129,2274,2202,2127,2270,2275,2276,-1,2203,2204,2274,-1,-1,2202,2131,-1,2132,2277,2205,-1,-1,-1,2130,2278,2279,2206,-1,-1,2207,2277,-1,2205,-1,2134,2280,2208,2135,-1,-1,2133,-1,2281,2282,-1,2210,2209,-1,-1,2280,2211,2283,2208,2138,2137,-1,-1,-1,-1,-1,2284,2285,-1,2213,-1,2212,2283,-1,2214,2286,2141,-1,-1,2140,2211,-1,2142,-1,2288,2287,-1,2216,2215,-1,-1,2217,2289,2286,2144,-1,2143,-1,2214,-1,2145,-1,2291,2290,2219,-1,-1,2218,2220,2292,-1,2289,2147,-1,-1,-1,2146,2148,2217,-1,2294,2293,2222,-1,-1,2223,2295,2221,-1,2150,2292,-1,-1,-1,2151,2149,2224,-1,2297,2296,2225,-1,-1,2226,2298,2224,-1,2153,-1,2295,-1,2154,-1,2227,2152,-1,2300,2299,-1,2228,-1,2229,2301,-1,2227,2156,-1,-1,2157,2230,2298,-1,2155,2302,2303,-1,2302,2231,2232,2304,-1,-1,2230,2233,2159,-1,2160,-1,-1,2301,2305,-1,2306,-1,2307,2235,2234,2305,-1,-1,2236,2233,2163,-1,2162,-1,-1,2308,2304,2164,2309,2310,-1,2238,2237,2308,-1,-1,2239,2166,-1,2165,2236,2311,-1,-1,-1,2167,2312,2313,2241,-1,-1,2240,2311,2242,-1,-1,2169,2314,-1,-1,2168,2239,2170,-1,2315,2316,2244,-1,-1,2243,-1,2314,2245,2172,2317,-1,2171,2173,-1,-1,-1,2242,2318,2319,2247,-1,-1,2248,2246,2317,-1,2320,-1,2175,-1,-1,2176,2174,2249,2245,2321,2322,-1,2250,2251,-1,-1,2249,2320,2323,2178,-1,2179,2252,-1,-1,-1,-1,2325,2324,2253,-1,-1,2254,2326,2252,2323,-1,-1,2181,2182,2255,-1,-1,2180,-1,2328,2327,-1,2256,2257,-1,-1,2329,2255,2326,2258,2184,2185,-1,-1,-1,-1,-1,2331,2330,2260,-1,-1,2259,2332,-1,2261,-1,2188,2329,2258,2187,-1,-1,2189,-1,2334,2333,-1,2263,2262,2335,-1,-1,2264,2191,-1,2190,2332,2261,-1,-1,2192,-1,2337,2266,2336,-1,-1,2338,2265,2267,-1,2194,-1,-1,-1,2193,2335,2264,2195,2339]},"4":{"rings":56,"count":4187,"defaultK":17,"kMax":32,"geodesic":[0,5,4,1,2,6,3,7,14,9,19,16,12,17,11,10,18,15,13,8,24,34,21,37,31,27,36,22,29,28,30,32,38,60,39,20,61,88,62,21,37,59,40,8,89,87,63,90,120,22,36,19,9,91,119,64,86,41,58,1,121,122,157,92,42,43,41,66,23,65,24,67,22,64,40,44,10,95,94,68,25,96,11,93,9,21,63,97,39,45,69,92,127,2,128,126,46,47,45,71,26,70,27,72,25,69,44,48,100,12,101,28,99,73,13,102,11,68,24,98,43,49,134,74,133,3,29,103,49,50,48,74,29,75,28,73,76,30,51,47,27,104,14,105,13,103,72,106,77,15,31,102,52,46,26,107,139,138,4,12,53,52,54,79,32,80,31,78,33,81,55,51,110,16,109,30,111,77,15,108,17,82,34,112,56,50,145,76,146,6,29,107,57,58,56,84,35,85,34,83,36,86,59,55,18,115,116,82,33,114,17,117,19,37,87,113,60,54,81,118,152,7,151,153,158,198,159,121,199,200,243,157,122,197,160,89,244,201,242,245,291,156,123,120,90,290,246,196,161,241,202,61,292,119,91,293,162,163,161,203,125,204,124,202,126,205,123,164,160,92,249,248,93,250,91,201,247,206,127,122,94,251,165,159,297,64,90,298,166,165,167,208,128,207,129,209,127,206,164,168,95,253,254,130,96,210,252,94,126,255,205,97,163,169,251,302,131,66,67,303,170,169,171,212,132,213,131,211,133,172,168,214,258,98,99,130,259,257,210,134,97,260,100,256,215,173,167,307,69,129,308,209,217,218,216,263,174,175,264,262,173,176,219,215,265,313,136,312,135,314,261,137,311,172,134,315,177,266,214,220,366,102,138,367,179,178,180,222,140,223,139,221,141,181,177,269,105,268,224,106,220,138,142,270,267,104,107,225,182,176,271,319,219,75,318,266,226,225,227,273,183,182,272,274,184,181,224,228,271,323,143,324,144,322,275,142,325,185,145,321,180,270,229,223,377,108,141,376,187,186,188,231,147,230,148,232,146,185,189,229,278,112,111,149,277,279,233,145,113,276,110,280,228,184,190,329,81,150,328,234,191,192,190,235,151,236,150,234,152,237,193,189,115,283,282,149,114,233,284,116,153,281,238,113,194,188,285,334,148,84,83,333,195,194,196,240,154,239,155,241,153,238,156,193,197,118,287,288,117,286,119,242,289,237,152,157,116,285,192,198,339,86,120,338,399,400,456,344,457,517,458,345,398,401,455,292,518,516,459,581,519,293,343,346,397,580,520,342,294,402,454,244,582,515,460,583,403,402,404,461,348,462,347,460,349,405,401,463,522,296,523,346,295,459,521,350,297,524,294,464,406,400,345,247,520,587,586,248,407,406,408,465,352,466,351,464,353,467,350,409,405,527,299,526,300,528,298,463,525,354,468,301,349,529,404,410,591,297,251,250,411,410,412,470,355,469,356,471,354,468,357,409,413,531,303,532,302,530,304,472,533,353,301,467,358,529,408,414,254,596,595,305,416,415,417,475,360,474,361,476,359,414,418,537,307,473,536,308,362,477,538,358,306,535,309,539,472,413,419,258,601,602,305,363,420,421,419,479,364,480,363,478,365,422,418,541,311,481,542,310,362,477,540,312,366,543,309,539,423,417,482,606,313,261,262,605,424,423,425,483,368,484,367,482,369,485,422,426,366,546,314,545,315,547,481,313,544,370,316,486,365,421,427,265,548,610,611,264,428,427,429,487,488,371,372,486,489,370,373,426,430,318,550,549,551,317,319,485,490,369,374,548,552,316,320,425,431,268,615,614,432,431,433,492,375,491,376,493,374,490,430,434,377,554,322,555,321,553,494,323,556,373,320,489,378,429,435,271,552,620,619,272,436,435,437,496,379,495,380,497,378,434,438,559,325,494,558,326,381,498,560,324,377,557,327,561,433,439,493,624,323,275,274,625,440,439,441,500,383,501,382,499,384,438,442,563,329,502,564,328,381,498,562,385,330,565,327,561,503,443,437,278,629,628,331,380,445,446,444,505,388,506,387,504,389,507,386,447,443,569,333,568,334,570,332,503,567,390,335,508,385,571,442,448,282,634,635,331,449,448,450,510,391,509,392,511,390,508,393,447,451,573,337,574,336,572,338,512,575,389,507,335,394,571,446,452,639,339,285,286,453,452,454,514,395,513,396,515,394,451,455,512,578,340,577,397,341,516,579,393,339,576,342,511,450,456,398,289,580,643,644,288,648,649,716,582,717,787,718,647,583,650,715,518,788,719,786,789,860,581,519,646,584,790,859,580,520,651,714,457,861,785,720,862,652,651,653,721,586,585,722,720,587,650,654,792,522,723,584,521,793,719,791,523,588,794,520,790,655,649,724,865,583,461,460,866,657,656,658,726,591,590,727,725,592,589,728,655,659,526,798,797,527,724,525,799,796,528,593,588,729,654,660,465,871,870,800,524,661,660,662,730,594,595,731,729,593,732,596,663,659,530,802,801,531,529,803,728,800,592,733,597,532,528,804,664,658,875,468,469,665,664,666,598,734,735,599,597,733,736,663,667,806,534,600,533,805,807,535,596,732,737,532,804,808,601,662,668,472,879,536,880,670,669,671,603,740,739,604,602,741,738,668,672,811,538,539,812,605,601,810,537,742,540,813,737,667,673,809,885,476,477,884,606,674,673,675,607,744,743,606,608,745,672,676,742,542,816,815,605,543,541,609,746,817,814,544,741,540,677,671,480,889,604,890,818,678,679,677,748,611,610,747,749,612,680,676,609,546,820,746,819,545,750,547,821,613,818,544,608,822,681,675,745,548,894,484,483,683,684,682,753,615,616,754,752,614,617,685,681,825,550,551,755,751,826,824,549,552,613,618,827,823,686,680,488,899,756,750,900,687,688,686,757,619,620,758,756,618,685,689,621,554,829,759,830,555,755,553,828,617,831,556,622,827,684,690,760,552,903,491,492,691,692,690,623,761,762,624,622,760,693,689,763,558,833,834,625,557,559,621,759,832,835,556,764,560,694,688,495,908,626,907,831,695,694,696,627,765,766,626,628,764,767,693,697,838,562,561,837,625,629,839,563,763,560,836,768,692,698,840,912,499,498,913,624,700,699,701,632,771,770,631,633,772,769,698,702,843,566,630,567,844,842,565,634,773,768,568,845,841,629,697,703,503,918,564,917,704,705,703,775,636,635,774,776,637,773,634,706,702,570,847,848,569,571,846,777,849,638,772,633,568,572,845,707,701,922,507,506,708,709,707,779,639,640,778,780,638,641,777,710,706,574,851,852,573,781,575,850,853,572,637,642,776,711,705,510,926,927,849,576,713,714,712,784,644,645,783,785,643,715,711,857,578,782,646,579,856,786,858,577,642,855,580,859,716,710,781,932,647,514,515,931,936,937,1012,861,1013,1014,1091,862,935,938,1011,788,1092,1090,1015,1172,1093,789,860,863,934,1171,1094,790,859,1010,939,717,1173,1016,1089,1254,940,941,939,1017,865,1018,864,1016,866,942,938,1096,792,1019,1097,863,791,1015,1095,867,793,1098,790,1094,943,937,1020,1177,794,721,720,1178,945,946,944,1022,870,1023,869,1021,871,947,943,1024,868,1101,797,1102,796,1020,1100,872,1103,798,795,1025,867,948,942,725,1183,1182,726,1099,949,950,948,1026,874,1027,873,1025,875,1028,872,951,947,1106,800,1105,801,1107,799,1024,876,1104,802,1029,871,952,946,729,1187,1108,798,1186,953,954,952,1030,878,1031,877,1029,879,1032,876,955,951,1110,804,1109,805,1111,803,1028,880,1033,1108,875,806,1112,802,956,950,1191,733,732,957,958,956,1035,881,1034,882,1036,880,1033,883,959,955,1114,808,1115,807,1113,809,1037,879,1032,1116,884,806,1112,810,954,960,1195,736,1196,962,963,961,1040,886,1039,887,1041,885,1038,888,964,960,1119,813,1120,812,1118,814,1042,884,1121,811,1037,889,965,959,741,1201,1117,1200,815,966,965,967,1044,890,1043,891,1045,889,968,964,1042,1124,816,892,1123,817,1046,1125,888,815,1122,818,1041,893,963,969,1205,745,744,1126,1204,970,971,969,1048,894,1047,895,1049,893,972,968,1128,820,1046,1127,896,821,1050,1129,892,819,1126,822,1130,973,967,1045,1209,748,818,897,749,975,976,974,1053,899,1054,1052,898,900,977,973,1133,825,1055,1134,1051,1132,824,897,826,901,1135,1131,823,827,978,972,753,1215,1214,1056,1050,979,978,980,1057,903,1058,902,1056,904,977,981,1137,829,1059,1138,901,828,1055,1136,905,830,1139,827,1135,976,982,1060,1219,757,831,900,756,983,984,982,1061,907,1062,906,1060,908,985,981,1063,1141,833,905,1142,832,1059,1140,909,834,1143,831,1064,904,986,980,1223,760,761,1139,1224,987,986,988,1065,911,1066,910,1064,912,1067,909,985,989,1146,836,1145,837,1147,835,1063,913,1144,838,1068,908,984,990,764,1227,1148,1228,834,992,991,993,1070,916,1071,915,1069,917,1072,914,990,994,1151,841,1150,842,1152,840,1068,918,1073,1149,913,843,1153,839,989,995,1233,769,1232,996,997,995,1075,919,1074,920,1076,918,1073,921,994,998,1155,845,1156,844,1154,846,1077,917,1072,1157,922,843,1153,847,993,999,1237,772,773,1000,1001,999,1079,923,1078,924,1080,922,1077,925,998,1002,1159,849,1160,848,1158,850,1081,921,1161,847,1076,926,1003,997,776,1241,1157,851,1242,1004,1005,1003,1083,927,1082,928,1084,926,1006,1002,1081,929,1164,852,1163,853,1085,1165,925,1162,851,854,1080,930,1007,1001,780,1245,1246,779,1166,1009,1010,1008,1088,932,1087,933,1089,931,1011,1007,1169,857,1086,1168,934,858,1090,1170,930,856,1167,859,1171,1012,1006,1085,1251,855,784,785,1250,1255,1338,1256,1339,1173,1340,1423,1254,1174,1337,1257,1092,1424,1341,1422,1425,1509,1172,1093,1253,1175,1508,1426,1171,1094,1336,1258,1013,1510,1342,1421,1511,1259,1260,1258,1343,1177,1176,1344,1342,1178,1261,1257,1428,1096,1175,1345,1095,1429,1341,1427,1097,1179,1094,1430,1426,1098,1262,1256,1514,1017,1346,1174,1016,1263,1264,1262,1347,1181,1180,1348,1346,1182,1265,1261,1432,1100,1179,1099,1349,1433,1345,1431,1101,1183,1098,1434,1430,1266,1260,1178,1518,1350,1021,1020,1102,1268,1269,1267,1352,1186,1185,1353,1351,1187,1184,1270,1266,1437,1105,1104,1354,1438,1350,1436,1106,1188,1103,1439,1183,1271,1265,1355,1025,1524,1435,1523,1026,1272,1271,1273,1356,1190,1189,1357,1355,1191,1188,1270,1274,1358,1108,1441,1442,1109,1354,1440,1107,1443,1110,1192,1187,1359,1269,1275,1029,1528,1439,1527,1106,1276,1275,1277,1360,1193,1194,1361,1359,1192,1195,1274,1278,1362,1112,1446,1445,1113,1111,1358,1444,1447,1114,1191,1196,1363,1279,1273,1532,1033,1110,1032,1533,1280,1281,1279,1364,1197,1198,1365,1363,1196,1199,1366,1278,1282,1116,1450,1449,1117,1115,1451,1362,1448,1195,1118,1200,1367,1114,1277,1283,1536,1037,1036,1452,1284,1283,1285,1201,1368,1369,1202,1200,1367,1370,1203,1282,1286,1120,1454,1453,1119,1121,1455,1366,1199,1452,1371,1118,1122,1204,1287,1281,1040,1540,1456,1541,1289,1288,1290,1206,1373,1374,1207,1205,1372,1375,1287,1291,1459,1125,1208,1124,1458,1460,1126,1204,1371,1457,1123,1376,1461,1286,1292,1209,1127,1045,1546,1545,1293,1292,1294,1210,1377,1378,1211,1209,1376,1379,1291,1295,1463,1129,1128,1212,1462,1464,1208,1130,1127,1375,1380,1461,1465,1290,1296,1550,1049,1213,1048,1549,1297,1298,1296,1214,1382,1381,1215,1213,1383,1380,1295,1299,1467,1132,1133,1468,1466,1212,1216,1131,1134,1384,1379,1469,1465,1294,1300,1554,1053,1052,1553,1555,1301,1302,1300,1218,1386,1385,1217,1219,1387,1384,1303,1299,1471,1136,1137,1216,1472,1470,1220,1135,1138,1388,1383,1473,1469,1304,1298,1558,1056,1215,1057,1559,1305,1306,1304,1222,1390,1389,1221,1223,1391,1388,1307,1303,1475,1140,1220,1141,1476,1474,1139,1224,1392,1477,1142,1387,1473,1308,1302,1219,1138,1060,1562,1563,1310,1311,1309,1227,1395,1394,1226,1228,1396,1393,1225,1312,1308,1145,1480,1481,1146,1144,1479,1397,1229,1482,1392,1147,1143,1224,1313,1307,1065,1568,1478,1567,1314,1313,1315,1399,1231,1230,1398,1400,1232,1229,1397,1312,1316,1149,1484,1485,1148,1150,1483,1401,1486,1233,1147,1228,1396,1151,1311,1317,1572,1068,1069,1482,1318,1317,1319,1403,1234,1235,1402,1404,1233,1236,1316,1320,1401,1153,1488,1489,1152,1154,1405,1490,1487,1151,1232,1237,1400,1315,1321,1576,1072,1155,1073,1575,1322,1323,1321,1407,1238,1239,1406,1408,1237,1240,1324,1320,1405,1157,1493,1492,1156,1409,1494,1158,1491,1155,1236,1241,1404,1325,1319,1076,1580,1495,1581,1159,1326,1325,1327,1411,1242,1243,1410,1412,1241,1244,1328,1324,1497,1160,1161,1409,1496,1413,1498,1159,1240,1162,1495,1245,1329,1323,1408,1080,1584,1499,1585,1079,1331,1330,1332,1416,1247,1248,1415,1417,1246,1329,1333,1502,1165,1249,1166,1414,1501,1418,1503,1164,1245,1167,1500,1504,1328,1334,1250,1590,1413,1084,1085,1163,1335,1336,1334,1420,1251,1252,1419,1421,1250,1333,1337,1506,1169,1253,1418,1170,1505,1422,1507,1168,1249,1171,1504,1508,1167,1332,1338,1594,1088,1417,1254,1089,1687,1776,1688,1777,1598,1778,1867,1686,1599,1775,1689,1868,1510,1779,1866,1959,1869,1685,1600,1511,1597,1958,1870,1596,1512,1690,1774,1424,1960,1780,1865,2052,1691,1692,1690,1781,1602,1782,1601,1780,1603,1689,1693,1872,1514,1783,1873,1600,1513,1779,1871,1604,1515,1874,1512,1870,1516,1688,1694,1964,1428,1784,1427,1965,1696,1695,1697,1786,1607,1787,1606,1785,1608,1694,1698,1877,1519,1788,1605,1878,1518,1784,1876,1609,1520,1879,1517,1875,1521,1693,1699,1969,1433,1789,1432,1604,1700,1699,1701,1790,1611,1791,1610,1789,1612,1698,1702,1881,1523,1792,1609,1882,1522,1788,1613,1880,1524,1883,1521,1697,1703,1793,1879,1608,1973,1436,1525,1974,1704,1703,1705,1794,1615,1795,1614,1793,1616,1702,1706,1885,1527,1796,1613,1886,1526,1792,1617,1884,1528,1887,1525,1797,1612,1701,1707,1440,1978,1977,1883,1441,1708,1709,1707,1798,1619,1799,1618,1797,1620,1710,1706,1800,1617,1889,1531,1890,1530,1796,1621,1888,1532,1891,1529,1801,1616,1711,1705,1444,1982,1981,1887,1445,1713,1714,1712,1803,1624,1804,1623,1802,1625,1805,1622,1711,1715,1895,1535,1894,1536,1896,1534,1801,1626,1893,1537,1806,1621,1710,1716,1987,1449,1897,1986,1448,1717,1718,1716,1807,1628,1808,1627,1806,1629,1809,1626,1719,1715,1899,1539,1898,1540,1900,1538,1805,1630,1897,1541,1810,1625,1714,1720,1991,1453,1901,1452,1537,1721,1720,1722,1811,1632,1812,1631,1810,1633,1813,1630,1719,1723,1903,1543,1902,1544,1904,1542,1809,1634,1901,1545,1814,1629,1905,1718,1724,1995,1541,1456,1457,1726,1727,1725,1816,1637,1817,1636,1815,1638,1818,1635,1728,1724,1908,1548,1907,1549,1909,1547,1814,1639,1906,1819,1550,1634,1910,1546,1729,1723,1461,2000,2001,1730,1729,1731,1820,1641,1821,1640,1819,1642,1822,1639,1728,1732,1912,1552,1911,1553,1913,1551,1818,1643,1823,1638,1910,1554,1914,1550,1727,1733,1465,2004,2005,1734,1735,1733,1825,1644,1824,1645,1826,1643,1823,1646,1736,1732,1916,1556,1917,1555,1915,1557,1827,1642,1822,1647,1918,1554,1914,1558,1737,1731,1469,2009,2008,1738,1737,1739,1829,1648,1828,1649,1830,1647,1827,1650,1736,1740,1920,1560,1921,1559,1919,1561,1831,1646,1922,1826,1558,1651,1918,1562,1735,1741,1473,2013,2012,1743,1744,1742,1834,1653,1833,1654,1835,1652,1832,1655,1745,1741,1925,1565,1926,1564,1924,1566,1836,1651,1927,1563,1831,1656,1923,1746,1740,2018,1567,1478,1477,1747,1748,1746,1838,1657,1837,1658,1839,1656,1836,1659,1749,1745,1929,1569,1930,1568,1928,1570,1840,1655,1931,1567,1835,1660,1750,1744,2022,1481,1927,1482,1571,1751,1750,1752,1842,1661,1841,1662,1843,1660,1840,1663,1753,1749,1933,1573,1934,1572,1932,1574,1844,1659,1935,1571,1839,1664,1748,1754,2026,1485,1931,2027,1486,1756,1755,1757,1847,1666,1846,1667,1848,1665,1754,1758,1845,1668,1939,1577,1938,1578,1849,1664,1940,1576,1937,1579,1844,1669,1753,1759,1490,2031,2032,1941,1489,1760,1759,1761,1851,1670,1850,1671,1852,1669,1758,1762,1943,1581,1849,1672,1942,1582,1853,1668,1944,1580,1941,1583,1848,1673,1757,1763,1494,2035,2036,1945,1493,1764,1763,1765,1855,1674,1854,1675,1856,1673,1766,1762,1947,1585,1853,1676,1946,1586,1857,1672,1948,1584,1945,1587,1767,1761,1852,1949,1677,2040,1498,1583,2039,1768,1769,1767,1859,1678,1858,1679,1860,1677,1770,1766,1951,1589,1857,1680,1950,1590,1861,1952,1676,1588,1949,1591,1953,1587,1765,1771,2044,1501,1856,1502,1681,1773,1774,1772,1864,1683,1863,1684,1865,1682,1771,1775,1956,1594,1862,1955,1685,1595,1866,1957,1681,1593,1954,1596,1958,1592,1770,1776,2049,1506,1861,1507,2048,2053,2146,2054,2147,1960,2240,2148,2052,1961,2145,2055,1868,2241,2239,2149,2242,2335,2051,1962,1959,1869,2243,2334,1958,1870,2144,2056,1777,2336,2238,2150,2050,2057,2056,2058,2151,1964,1963,2152,2150,1965,2059,2055,2245,1872,1962,1871,2246,2149,2153,2244,1966,1873,1870,2247,2243,1874,2054,2060,2340,1781,1961,1780,2341,2062,2061,2063,2156,1969,1968,2155,2157,1970,2060,2064,2250,1877,1967,1876,2251,2154,2158,2249,1971,1878,1875,2252,2248,1879,2065,2059,2345,1786,1966,1785,2346,2066,2065,2067,2160,1973,1972,2159,2161,1974,2064,2068,2254,1881,1971,1880,2255,2158,2162,2253,1975,1882,1879,2256,2252,2063,2069,2349,1970,1790,1883,1789,2350,2070,2071,2069,2164,1977,1976,2165,2163,1978,2072,2068,2258,1885,1975,1884,2259,2166,2162,2257,1979,1886,1883,2260,2256,2067,2073,1974,2353,1793,1794,2354,1887,2074,2073,2075,2168,1981,1980,2167,2169,1982,2072,2076,2262,1979,1889,1888,2263,2166,2170,2261,1983,1890,1887,2264,1978,2260,2071,2077,1797,2357,2358,1798,2165,2079,2080,2078,2173,1986,1985,2174,2172,1987,2081,2077,1984,2267,1893,1894,2268,2175,2171,2266,1892,1988,1895,2269,1983,2082,2076,1802,2265,2363,2362,1803,2176,2083,2082,2084,2177,1990,1989,2176,2178,1991,1988,2081,2085,2271,1897,1898,2272,2179,2175,2270,1896,1992,1899,2273,1987,2080,2086,1806,2367,2269,2366,1895,2174,2087,2086,2088,2181,1994,1993,2180,2182,1995,1992,2089,2085,1901,2275,2276,1902,2183,2179,1900,2274,1996,2277,1903,1991,2090,2084,1810,2371,1899,2273,2370,1809,2091,2092,2090,2185,1998,1997,2186,2184,1999,1996,2089,2093,1905,2279,2280,1906,2183,2187,1904,2278,2281,2000,1907,1995,1903,2088,2094,2375,1814,2374,1813,2277,2096,2097,2095,2190,2003,2002,2191,2189,2004,2001,2098,2094,1910,2284,2285,1911,2192,2188,1909,2283,2286,2005,2000,1912,1908,2093,2099,2380,1819,1818,2379,2282,2100,2101,2099,2194,2007,2006,2195,2193,2008,2005,2102,2098,1914,2289,2288,2196,2192,1915,1913,2290,2287,2009,2004,1916,1912,2103,2097,2384,1823,1822,2197,2191,2104,2105,2103,2198,2010,2011,2199,2197,2009,2012,2106,2102,1918,2293,2292,1917,2200,2196,1919,2294,2291,2008,2013,1916,1920,2107,2101,2388,1826,1827,2389,2295,2109,2108,2110,2203,2015,2016,2202,2204,2014,2017,2111,2107,1923,2298,2297,1922,2205,2201,1924,2299,2296,2013,1921,2018,1925,2112,2106,2393,1831,2394,1832,2300,2113,2112,2114,2207,2019,2020,2206,2208,2018,2021,2111,2115,1927,2302,2301,1926,2205,2209,1928,2303,2017,2300,1925,2022,2110,2116,1835,2397,1929,2304,2398,1836,2117,2118,2116,2211,2023,2024,2212,2210,2022,2025,2119,2115,2306,1931,1930,2305,2213,2209,2307,1932,2021,1929,2304,2026,2120,2114,1839,2401,2308,2402,1933,2214,2121,2122,2120,2215,2027,2028,2216,2214,2026,2123,2119,2029,2310,1935,1934,2309,2217,2213,2311,1936,2025,1933,2308,2030,2124,2118,1843,2312,2405,2406,1842,2218,2126,2125,2127,2220,2032,2033,2219,2221,2031,2124,2128,2315,2034,1939,1940,2314,2218,2222,2316,2030,1938,1941,2313,2035,2317,2123,2129,1848,2411,2410,1847,2217,2130,2131,2129,2224,2036,2037,2225,2223,2035,2132,2128,2319,1943,2038,1944,2318,2226,2222,2320,2034,1942,1945,2317,2321,2133,2127,2039,2415,1852,1851,2414,1941,2134,2133,2135,2228,2040,2041,2227,2229,2039,2132,2136,2323,1947,2042,1948,2322,2226,2230,2324,2038,1946,1949,2321,2325,2131,2137,2419,2043,1855,1945,1856,2418,2138,2139,2137,2232,2044,2045,2233,2231,2043,2140,2136,2327,1951,2046,1952,2326,2234,2230,2328,2042,1950,1953,2325,2329,1949,2135,2141,2423,1859,2047,1860,2422,2143,2142,2144,2237,2049,2050,2236,2238,2048,2141,2145,2332,1956,2051,1957,2331,2235,2239,2333,2047,1955,1958,2330,2334,1954,2146,2140,2428,1864,2052,1865,2427,2432,2527,2433,2336,2528,2624,2529,2431,2337,2434,2526,2241,2625,2623,2530,2338,2430,2721,2626,2335,2242,2720,2627,2243,2334,2525,2435,2147,2722,2622,2531,2429,2436,2437,2435,2340,2532,2533,2339,2341,2531,2434,2438,2245,2629,2534,2630,2244,2338,2342,2628,2246,2530,2631,2243,2627,2247,2433,2439,2726,2151,2535,2727,2150,2440,2439,2441,2344,2536,2537,2343,2345,2535,2442,2438,2633,2249,2538,2634,2248,2342,2346,2632,2250,2534,2635,2247,2631,2251,2437,2443,2730,2155,2539,2731,2154,2445,2444,2446,2349,2541,2542,2348,2350,2540,2443,2447,2638,2254,2543,2639,2253,2347,2351,2637,2255,2539,2640,2252,2636,2256,2442,2448,2544,2735,2160,2736,2159,2449,2450,2448,2353,2545,2546,2352,2354,2544,2447,2451,2642,2258,2547,2643,2257,2351,2355,2641,2259,2543,2644,2256,2640,2260,2548,2446,2452,2739,2164,2740,2163,2453,2454,2452,2357,2549,2550,2358,2356,2548,2455,2451,2646,2262,2551,2647,2261,2359,2355,2645,2263,2547,2648,2260,2552,2644,2264,2456,2450,2743,2168,2744,2167,2457,2458,2456,2361,2553,2554,2362,2360,2552,2555,2455,2459,2650,2266,2651,2265,2359,2363,2649,2267,2551,2652,2264,2556,2454,2460,2648,2268,2748,2171,2747,2172,2461,2460,2462,2365,2557,2558,2364,2366,2556,2559,2463,2459,2654,2270,2655,2269,2367,2363,2653,2271,2555,2656,2268,2560,2464,2458,2752,2175,2652,2272,2751,2176,2465,2466,2464,2369,2561,2562,2370,2368,2560,2563,2467,2463,2658,2274,2659,2273,2371,2367,2657,2275,2559,2660,2272,2564,2468,2462,2756,2179,2656,2755,2180,2276,2470,2469,2471,2374,2566,2567,2373,2375,2565,2568,2468,2472,2663,2279,2664,2278,2372,2376,2662,2280,2665,2277,2564,2569,2467,2473,2761,2184,2760,2185,2661,2281,2474,2475,2473,2378,2570,2571,2379,2377,2569,2572,2476,2472,2667,2283,2668,2282,2380,2376,2666,2284,2669,2281,2568,2573,2477,2471,2765,2188,2764,2189,2665,2381,2478,2479,2477,2382,2574,2575,2383,2381,2573,2576,2476,2480,2671,2287,2672,2286,2380,2384,2670,2288,2673,2285,2572,2577,2475,2481,2769,2192,2768,2379,2385,2193,2482,2481,2483,2386,2579,2578,2385,2387,2580,2577,2480,2484,2676,2290,2675,2291,2388,2384,2677,2289,2674,2292,2581,2576,2485,2479,2773,2196,2774,2383,2389,2195,2486,2485,2487,2390,2583,2582,2389,2391,2584,2581,2484,2488,2680,2294,2679,2295,2388,2392,2681,2293,2678,2296,2585,2580,2483,2489,2777,2200,2778,2199,2682,2387,2490,2491,2489,2394,2587,2586,2395,2393,2588,2585,2492,2488,2684,2298,2683,2299,2396,2392,2685,2297,2682,2300,2589,2584,2493,2487,2781,2204,2782,2203,2686,2296,2495,2496,2494,2399,2592,2591,2400,2398,2593,2590,2497,2493,2689,2303,2688,2304,2401,2397,2690,2302,2594,2687,2305,2589,2492,2498,2786,2209,2691,2787,2208,2301,2499,2498,2500,2403,2596,2595,2402,2404,2597,2594,2501,2497,2693,2307,2692,2308,2405,2401,2694,2306,2598,2691,2309,2593,2502,2496,2790,2213,2695,2305,2791,2212,2503,2504,2502,2407,2600,2599,2408,2406,2601,2598,2501,2505,2697,2311,2696,2312,2405,2409,2698,2310,2602,2695,2313,2597,2506,2500,2699,2309,2794,2217,2795,2216,2507,2506,2508,2411,2604,2603,2410,2412,2605,2505,2509,2701,2315,2602,2700,2316,2409,2413,2702,2314,2606,2699,2317,2601,2703,2313,2510,2504,2799,2220,2798,2221,2511,2512,2510,2415,2608,2607,2416,2414,2609,2509,2513,2705,2319,2606,2704,2320,2413,2417,2706,2318,2610,2703,2321,2707,2317,2605,2514,2508,2803,2224,2802,2225,2515,2514,2516,2419,2612,2611,2418,2420,2613,2513,2517,2709,2323,2610,2708,2324,2417,2421,2710,2322,2614,2707,2325,2711,2321,2512,2518,2609,2807,2228,2806,2229,2520,2521,2519,2424,2617,2616,2425,2423,2618,2522,2518,2714,2328,2615,2713,2329,2426,2422,2715,2327,2619,2712,2330,2716,2326,2523,2517,2812,2233,2614,2811,2234,2524,2523,2525,2428,2621,2620,2427,2429,2622,2526,2522,2332,2718,2619,2717,2333,2430,2426,2719,2331,2623,2716,2334,2720,2330,2521,2527,2816,2237,2618,2815,2238,2820,2917,2821,2722,2918,2819,2723,3015,2919,2916,2822,2625,3016,2818,2724,3014,2920,3113,3017,2721,2626,3112,3018,2720,2627,2915,2823,3114,2528,2817,2725,3013,2824,2825,2823,2726,2922,2727,2725,2923,2921,2826,2822,3020,2629,2628,2728,2724,2924,2920,3019,3021,2630,2627,3022,3018,2631,2827,2821,3118,2532,2729,2723,3119,2829,2830,2828,2731,2927,2730,2732,2928,2926,2827,2831,3025,2634,2633,2729,2733,2925,2929,3026,3024,2635,2632,3027,3023,2636,2826,2832,3123,2537,3124,2536,2728,2833,2832,2834,2735,2931,2734,2736,2930,2932,2831,2835,3029,2638,2637,2733,2737,2929,2933,3028,3030,2639,2636,3027,3031,2640,2830,2836,3127,2541,3128,2540,2732,2837,2836,2838,2739,2935,2740,2738,2934,2936,2835,2839,3033,2642,2641,2737,2741,2933,2937,3032,3034,2643,2640,3031,3035,2644,2834,2840,3131,2545,3132,2544,2736,2841,2842,2840,2743,2939,2742,2744,2938,2940,2843,2839,3037,2646,2645,2745,2741,2937,2941,3038,3036,2647,2644,3039,3035,2838,2844,2648,3135,2549,3136,2548,2746,2846,2847,2845,2748,2944,2749,2747,2945,2943,2848,2844,3042,2651,2650,2750,2746,2946,2942,3043,3041,2652,2649,3044,3040,2849,2843,3140,2554,2653,3141,2553,2751,2850,2849,2851,2752,2948,2753,2751,2947,2949,2848,2852,3046,2655,2654,2750,2754,2950,2946,3045,3047,2656,2653,3044,3048,2847,2853,3144,2558,2657,3145,2557,2749,2854,2853,2855,2756,2952,2755,2757,2951,2953,2852,2856,3050,2659,2658,2754,2758,2950,2954,3049,3051,2660,2657,3048,3052,2851,2857,3148,2562,3149,2561,2661,2753,2858,2857,2859,2760,2956,2759,2761,2955,2957,2856,2860,3054,2663,2662,2758,2762,2954,2958,3055,3053,2664,2661,3052,3056,2855,2861,3152,2566,3153,2565,2665,2757,2863,2864,2862,2765,2961,2766,2764,2962,2960,2865,2861,3059,2668,2667,2767,2763,2963,2959,3058,3060,2669,2666,3061,3057,2860,2866,3157,2571,3158,2570,2762,2768,2867,2866,2868,2769,2965,2768,2770,2966,2964,2869,2865,3063,2672,2671,2771,2767,2967,2963,3062,3064,2673,2670,3065,3061,2870,2864,3161,2575,3162,2574,2772,2766,2871,2872,2870,2773,2969,2774,2772,2968,2970,2873,2869,3067,2675,2676,2775,2771,2971,2967,3068,3066,2674,2677,3069,3065,2874,2868,3166,2578,3165,2579,2776,2770,2875,2876,2874,2777,2973,2778,2776,2972,2974,2873,2877,3071,2679,2680,2775,2779,2971,2975,3070,3072,2678,2681,3069,3073,2872,2878,3170,2582,3169,2583,2774,2780,2880,2881,2879,2782,2978,2781,2783,2977,2979,2878,2882,3076,2684,2685,2780,2784,2976,2980,3077,3075,2683,2686,3074,3078,2877,2883,3175,2587,3174,2588,2682,2785,2884,2885,2883,2786,2982,2787,2785,2983,2981,2886,2882,3080,2688,2689,2788,2784,2984,2980,3081,3079,2687,2690,3082,3078,2887,2881,3179,2591,3178,2592,2686,2789,2888,2887,2889,2790,2986,2791,2789,2985,2987,2886,2890,3084,2692,2693,2788,2792,2984,2988,3083,3085,2691,2694,3082,3086,2885,2891,3183,2595,2690,3182,2596,2787,2892,2893,2891,2794,2990,2793,2795,2991,2989,2894,2890,3088,2696,2697,2796,2792,2992,2988,3089,3087,2695,2698,3090,3086,2895,2889,3187,2599,2694,3186,2600,2797,2897,2896,2898,2799,2995,2798,2800,2994,2996,2895,2899,3093,2701,2702,2797,2801,2993,2997,3092,3094,2700,2703,3091,3095,2894,2900,2699,3192,2604,3191,2605,2796,2901,2900,2902,2803,2999,2802,2804,2998,3000,2903,2899,3097,2705,2706,2805,2801,3001,2997,3096,3098,2704,2707,3099,3095,2703,2904,2898,3196,2608,3195,2609,2806,2905,2904,2906,3003,2807,2806,2808,3002,3004,2903,2907,3101,2709,2710,2805,2809,3005,3001,3102,3100,2708,2711,3103,3099,2707,2908,2902,3200,2612,3199,2613,2810,2909,2910,2908,2811,3007,2812,2810,3008,3006,2907,2911,3105,2713,2714,2809,2813,3005,3009,3106,3104,2712,2715,3103,3107,2711,2906,2912,3204,2616,3203,2617,2808,2914,2915,2913,3012,2816,2817,2815,3013,3011,2916,2912,3110,2718,2719,2818,2814,3014,3010,3109,3111,2717,2720,3112,3108,2716,2917,2911,3209,2621,2819,2813,3208,3312,3410,3313,3411,3213,3214,3311,3508,3412,3409,3314,3509,3114,3310,3215,3212,3115,3606,3510,3507,3413,3211,3116,3605,3511,3408,3315,3607,3016,3309,3216,3608,3316,3317,3315,3217,3415,3414,3218,3216,3416,3318,3314,3118,3513,3413,3512,3219,3215,3117,3119,3514,3417,3511,3120,3116,3515,3319,3313,3611,3020,3412,3214,3220,3321,3320,3322,3222,3420,3419,3221,3223,3421,3323,3319,3123,3518,3418,3517,3224,3220,3124,3122,3519,3422,3516,3125,3121,3520,3318,3324,3616,3025,3417,3615,3024,3325,3324,3326,3226,3424,3423,3227,3225,3425,3327,3323,3127,3522,3422,3521,3228,3224,3128,3126,3523,3426,3520,3129,3125,3524,3328,3322,3620,3029,3421,3619,3028,3329,3328,3330,3230,3428,3427,3229,3231,3429,3331,3327,3131,3526,3426,3525,3232,3228,3130,3132,3527,3430,3524,3133,3129,3528,3326,3332,3425,3624,3033,3623,3032,3334,3333,3335,3235,3433,3432,3234,3236,3434,3332,3336,3136,3531,3431,3530,3233,3237,3135,3137,3532,3435,3529,3134,3138,3430,3331,3337,3533,3629,3038,3628,3037,3338,3339,3337,3239,3437,3436,3240,3238,3438,3340,3336,3140,3435,3535,3534,3241,3237,3141,3139,3536,3439,3533,3142,3138,3434,3341,3335,3633,3042,3537,3632,3041,3342,3341,3343,3243,3441,3440,3242,3244,3442,3439,3340,3344,3144,3539,3538,3241,3245,3143,3145,3540,3443,3537,3142,3146,3438,3339,3345,3637,3046,3541,3636,3045,3346,3347,3345,3247,3445,3444,3248,3246,3446,3443,3348,3344,3148,3543,3542,3249,3245,3149,3147,3544,3447,3541,3150,3146,3442,3349,3343,3641,3050,3640,3049,3545,3351,3350,3352,3252,3450,3449,3251,3253,3451,3448,3349,3353,3153,3548,3547,3250,3254,3152,3154,3549,3546,3452,3447,3151,3155,3348,3354,3646,3055,3645,3054,3550,3355,3356,3354,3256,3454,3453,3257,3255,3455,3452,3357,3353,3157,3552,3551,3258,3254,3158,3156,3553,3550,3456,3451,3159,3155,3358,3352,3650,3059,3649,3058,3259,3359,3360,3358,3260,3458,3457,3259,3261,3459,3456,3357,3361,3161,3556,3555,3258,3262,3162,3160,3557,3554,3460,3455,3159,3163,3356,3362,3654,3063,3653,3062,3257,3364,3365,3363,3265,3462,3463,3266,3264,3461,3464,3366,3362,3166,3560,3561,3267,3263,3167,3165,3559,3562,3460,3465,3168,3164,3367,3361,3658,3067,3659,3068,3268,3368,3369,3367,3269,3466,3467,3270,3268,3465,3468,3370,3366,3170,3564,3565,3271,3267,3171,3169,3563,3566,3464,3469,3172,3168,3371,3365,3662,3071,3663,3072,3272,3372,3371,3373,3273,3470,3471,3274,3272,3469,3472,3374,3370,3174,3568,3569,3275,3271,3175,3173,3567,3570,3468,3473,3176,3172,3375,3369,3666,3075,3667,3076,3566,3377,3376,3378,3278,3475,3476,3277,3279,3474,3477,3375,3379,3179,3573,3574,3276,3280,3178,3180,3572,3473,3575,3177,3181,3478,3374,3380,3671,3080,3672,3081,3571,3381,3382,3380,3282,3479,3480,3283,3281,3478,3481,3383,3379,3183,3577,3578,3280,3284,3184,3182,3576,3477,3579,3185,3181,3482,3384,3378,3675,3084,3575,3676,3085,3385,3384,3386,3286,3483,3484,3285,3287,3482,3383,3387,3187,3485,3581,3582,3284,3288,3186,3188,3580,3481,3583,3185,3189,3486,3382,3388,3679,3088,3579,3680,3089,3389,3390,3388,3290,3487,3488,3291,3289,3486,3391,3387,3191,3585,3489,3586,3292,3288,3192,3190,3584,3485,3587,3193,3189,3490,3386,3392,3583,3683,3092,3684,3093,3394,3395,3393,3295,3492,3493,3296,3294,3491,3392,3396,3196,3590,3494,3591,3297,3293,3197,3195,3589,3490,3592,3198,3194,3588,3397,3391,3495,3688,3097,3689,3098,3398,3397,3399,3299,3496,3497,3298,3300,3495,3400,3396,3200,3594,3498,3595,3301,3297,3201,3199,3593,3494,3596,3202,3198,3592,3401,3395,3692,3101,3499,3693,3102,3402,3401,3403,3303,3500,3501,3302,3304,3499,3400,3404,3204,3598,3502,3599,3301,3305,3203,3205,3597,3498,3600,3202,3206,3596,3399,3405,3696,3105,3503,3697,3106,3407,3408,3406,3308,3505,3506,3309,3307,3504,3409,3405,3209,3603,3507,3604,3310,3306,3210,3208,3602,3503,3605,3211,3207,3601,3410,3404,3701,3110,3508,3311,3305,3705,3802,3706,3803,3607,3704,3608,3899,3804,3801,3707,3900,3509,3703,3609,3606,3510,3898,3805,3995,3901,3605,3511,3994,3902,3800,3708,3996,3411,3702,3610,3897,3709,3708,3710,3611,3807,3806,3610,3612,3808,3711,3707,3513,3904,3805,3903,3609,3613,3512,3514,3809,3905,3902,3515,3511,3906,3706,3712,3415,4000,3804,3999,3608,3714,3713,3715,3616,3812,3811,3615,3617,3813,3712,3716,3518,3909,3810,3908,3614,3618,3519,3517,3814,3910,3907,3516,3520,3911,3717,3711,3420,4005,3809,4004,3619,3718,3717,3719,3620,3816,3815,3619,3621,3817,3716,3720,3522,3913,3814,3912,3618,3622,3523,3521,3818,3914,3911,3524,3520,3715,3721,3424,4009,3915,3813,4008,3617,3722,3721,3723,3624,3820,3819,3623,3625,3821,3720,3724,3526,3917,3818,3916,3622,3626,3525,3527,3822,3918,3915,3524,3528,3719,3725,3817,3428,4013,4012,3919,3621,3726,3727,3725,3628,3824,3823,3629,3627,3825,3728,3724,3530,3822,3921,3920,3630,3626,3531,3529,3826,3922,3919,3532,3528,3821,3723,3729,3432,4017,4016,3631,3625,3731,3732,3730,3633,3829,3828,3634,3632,3830,3733,3729,3535,3827,3925,3926,3635,3631,3536,3534,3831,3924,3927,3537,3533,3826,3734,3728,3437,4021,4022,3636,3630,3735,3734,3736,3637,3833,3832,3636,3638,3834,3831,3733,3737,3539,3929,3930,3635,3639,3540,3538,3928,3835,3931,3541,3537,3830,3732,3738,3441,4025,4026,3927,3634,3739,3738,3740,3641,3837,3836,3640,3642,3838,3835,3737,3741,3543,3933,3934,3639,3643,3544,3542,3932,3839,3935,3541,3545,3834,3736,3742,3445,4029,3931,4030,3638,3743,3742,3744,3645,3841,3840,3644,3646,3842,3839,3741,3745,3547,3937,3938,3643,3647,3546,3548,3936,3843,3939,3838,3545,3549,3740,3746,3449,3935,4033,4034,3642,3748,3747,3749,3650,3846,3845,3649,3651,3847,3844,3750,3746,3552,3942,3943,3652,3648,3553,3551,3941,3848,3843,3944,3554,3550,3940,3745,3751,3454,4038,4039,3647,3752,3751,3753,3654,3850,3849,3653,3655,3851,3848,3754,3750,3556,3946,3947,3656,3652,3555,3557,3945,3852,3847,3948,3554,3558,3944,3755,3749,3458,4042,3657,3651,3756,3757,3755,3658,3853,3854,3659,3657,3852,3855,3758,3754,3560,3950,3949,3660,3656,3561,3559,3951,3851,3856,3948,3562,3558,3952,3759,3753,3462,4046,3661,3655,3760,3761,3759,3662,3857,3858,3663,3661,3856,3859,3758,3762,3564,3954,3953,3660,3664,3565,3563,3955,3855,3860,3952,3562,3566,3956,3757,3763,3466,4050,4049,3659,3765,3764,3766,3667,3862,3863,3666,3668,3861,3864,3763,3767,3569,3959,3958,3665,3669,3568,3570,3960,3860,3957,3865,3567,3571,3762,3768,3471,3961,4055,4054,3664,3769,3770,3768,3671,3866,3867,3672,3670,3865,3868,3771,3767,3573,3963,3962,3673,3669,3574,3572,3964,3864,3961,3571,3575,3869,3772,3766,3475,4059,3965,4058,3674,3773,3772,3774,3675,3870,3871,3676,3674,3869,3872,3771,3775,3577,3967,3966,3673,3677,3578,3576,3968,3868,3965,3575,3579,3873,3770,3776,3479,4063,4062,3969,3672,3777,3776,3778,3679,3874,3875,3680,3678,3873,3779,3775,3581,3876,3971,3970,3681,3677,3582,3580,3872,3972,3969,3579,3583,3877,3780,3774,3483,4067,4066,3682,3676,3782,3781,3783,3684,3879,3880,3683,3685,3878,3780,3784,3586,3881,3975,3976,3682,3686,3585,3587,3877,3974,3977,3588,3584,3882,3779,3785,3488,4071,4072,3681,3687,3786,3785,3787,3688,3883,3884,3687,3689,3882,3788,3784,3590,3979,3885,3980,3690,3686,3591,3589,3881,3978,3981,3592,3588,3789,3783,3886,3492,4075,4076,3977,3691,3790,3791,3789,3692,3887,3888,3691,3693,3886,3792,3788,3594,3983,3889,3984,3694,3690,3595,3593,3885,3982,3985,3596,3592,3793,3787,3496,4079,3981,3890,4080,3695,3794,3793,3795,3696,3891,3892,3695,3697,3890,3792,3796,3598,3987,3893,3988,3694,3698,3599,3597,3889,3986,3989,3596,3600,3985,3791,3797,3500,4083,3894,4084,3693,3799,3798,3800,3701,3896,3897,3702,3700,3895,3801,3797,3603,3992,3898,3993,3703,3699,3604,3602,3894,3991,3994,3605,3601,3990,3796,3802,3505,4088,3899,4089,3704,4092,-1,4093,4186,3996,-1,-1,4091,3997,-1,-1,-1,-1,4094,4185,3900,-1,3998,4090,3995,3901,-1,-1,-1,-1,-1,-1,3902,3994,-1,4095,4184,4096,4095,4097,4000,-1,-1,4001,3999,-1,-1,-1,-1,4094,4098,3904,4002,3905,-1,3998,3903,-1,-1,-1,-1,-1,3906,-1,3902,-1,-1,4093,4099,4100,-1,4099,4101,4004,-1,-1,4005,4003,-1,-1,4098,4102,3908,-1,-1,-1,4006,3909,3907,4002,-1,-1,-1,-1,3910,-1,-1,-1,3906,4097,4103,4104,4103,4105,-1,4008,-1,4009,4007,-1,-1,-1,-1,4106,4102,3912,4010,3913,-1,-1,3911,-1,4006,-1,-1,3914,-1,-1,3910,-1,-1,4107,4101,4109,-1,4108,4110,4013,-1,4014,-1,4012,-1,-1,-1,4107,4111,3917,4015,-1,3918,-1,3916,-1,4011,-1,3919,-1,-1,-1,-1,3915,4016,-1,4106,4113,-1,4114,4112,4017,-1,4018,-1,4016,-1,-1,-1,4115,4111,3921,4019,-1,-1,3922,3920,4015,-1,-1,-1,3923,-1,-1,-1,-1,4020,3919,4116,4117,4116,4118,-1,4021,-1,4022,-1,4020,-1,-1,-1,4023,4115,4119,3925,3926,-1,-1,-1,3924,4019,-1,3927,-1,-1,-1,4024,-1,-1,4114,4120,4121,-1,4122,4120,4025,4026,-1,-1,4024,-1,-1,4027,4119,4123,-1,3929,-1,-1,3930,3928,-1,4023,-1,3931,-1,-1,-1,-1,4028,-1,4118,4124,4125,4124,4126,-1,-1,4029,4030,-1,-1,4028,-1,-1,4031,4123,4127,3933,3934,-1,-1,-1,-1,3932,4027,3935,-1,-1,4032,-1,-1,-1,4122,4128,4129,-1,4130,4128,4033,4034,-1,-1,4032,-1,4035,-1,-1,4127,4131,-1,-1,3937,3938,3936,-1,-1,3939,4031,-1,4036,-1,-1,-1,-1,4126,4132,4133,4132,4134,-1,-1,4037,4038,-1,-1,4036,4039,-1,-1,4135,4131,3941,3942,-1,-1,-1,-1,3940,3943,4035,-1,4040,-1,-1,-1,-1,4136,4130,4137,-1,4136,4138,4041,4042,-1,-1,4040,4043,-1,-1,4135,4139,-1,-1,3945,3946,-1,3944,-1,3947,-1,4039,4044,-1,-1,-1,-1,-1,4134,4140,4142,-1,4141,4143,4047,4046,-1,-1,4048,-1,4045,-1,-1,4140,4144,3951,3950,-1,-1,-1,3952,3949,-1,4049,-1,4044,-1,-1,-1,-1,4139,4145,4146,-1,4147,4145,4051,-1,4050,-1,4052,-1,4049,-1,-1,4148,4144,3955,3954,-1,-1,-1,3956,-1,3953,4053,-1,-1,4048,-1,-1,-1,4143,4149,4150,-1,4151,4149,4055,4054,-1,-1,4056,-1,-1,4053,-1,4152,4148,3959,3958,-1,-1,3960,-1,3957,4057,-1,-1,-1,4052,-1,-1,-1,4153,4147,4154,4155,4153,-1,4059,-1,4058,-1,4060,-1,-1,4057,-1,4156,4152,3963,3962,-1,-1,-1,3964,-1,4061,3961,-1,-1,-1,4056,-1,-1,4157,4151,4158,-1,4157,4159,4063,4062,-1,-1,4064,-1,-1,4061,4156,4160,-1,3967,-1,-1,3966,3968,-1,4065,-1,3965,-1,-1,-1,-1,4060,-1,4155,4161,4162,4163,4161,-1,4067,-1,4066,-1,4068,-1,-1,-1,4065,4164,4160,3971,3970,-1,-1,-1,3972,-1,4069,3969,-1,-1,-1,-1,4064,-1,4165,4159,4166,-1,4165,4167,4071,4070,-1,-1,4072,-1,-1,-1,4164,4168,3975,4069,-1,-1,3974,3976,4073,-1,-1,3973,-1,-1,-1,-1,-1,4068,3977,4163,4170,4169,4171,4075,-1,-1,4074,4076,-1,-1,-1,-1,4168,4172,3979,4073,3978,-1,-1,3980,-1,4077,-1,3977,-1,-1,-1,-1,3981,4072,-1,4167,4175,-1,4176,4174,4080,-1,4079,-1,4081,-1,-1,-1,4177,4173,3984,4078,-1,-1,3983,3985,4082,-1,-1,-1,-1,3982,-1,-1,3986,-1,4178,4172,4179,-1,4178,4180,4084,-1,4083,-1,4085,-1,-1,-1,4177,4181,3988,-1,4082,-1,3987,3989,4086,-1,-1,-1,-1,3986,-1,3990,-1,-1,4182,4176,4183,-1,4184,4182,4088,-1,4087,4089,-1,-1,-1,-1,4185,4181,3992,-1,4086,3991,-1,4090,3993,-1,-1,-1,-1,-1,3990,3994,-1,-1,4186,4180],"visual":[0,7,4,2,1,3,6,5,9,10,16,15,8,18,19,17,11,12,13,14,31,20,21,22,23,24,25,26,27,28,29,30,38,61,60,39,20,88,62,21,37,89,59,40,63,87,120,90,8,22,36,19,9,91,119,64,86,41,58,1,121,157,122,118,42,66,41,65,43,23,67,24,22,64,40,94,95,10,44,93,68,96,25,21,9,11,63,39,92,2,127,97,45,128,69,126,46,45,70,71,26,47,69,27,25,44,72,100,99,12,101,68,48,98,28,24,13,11,73,43,102,3,133,97,134,67,4,49,50,49,75,29,74,76,48,51,30,28,105,73,77,106,104,14,31,27,52,47,15,13,107,103,78,72,139,140,4,5,108,102,53,54,80,79,32,52,81,33,31,55,78,110,111,16,109,82,51,112,34,30,15,17,77,56,108,6,146,113,145,83,5,50,57,84,58,85,56,35,83,36,34,86,59,116,115,18,55,117,82,114,33,37,17,19,87,60,118,7,152,113,54,151,81,153,158,199,198,159,200,243,121,244,157,122,245,291,201,242,197,160,89,156,123,290,246,120,90,292,293,343,241,202,196,161,91,119,162,204,203,163,161,125,202,205,124,249,248,126,164,250,160,123,92,247,93,201,206,91,251,127,297,298,165,296,94,122,159,64,166,208,167,209,207,165,128,129,254,253,168,127,206,210,255,130,164,252,95,96,94,302,126,169,303,256,97,205,211,131,251,301,170,212,213,171,169,132,211,214,258,133,259,172,131,257,260,168,99,134,98,215,210,130,173,100,308,307,256,97,261,309,306,69,217,174,175,218,216,136,173,135,263,176,264,137,262,219,215,134,102,265,172,101,177,138,103,261,313,312,220,214,314,100,133,72,178,179,222,221,139,140,177,180,220,223,268,267,269,141,138,105,224,219,176,181,266,270,104,106,318,137,142,319,317,103,107,75,226,183,182,227,225,143,184,144,273,181,272,142,274,228,224,145,108,271,185,109,180,141,107,275,323,324,229,223,322,110,146,78,187,231,230,186,188,147,229,232,278,146,277,185,148,279,276,189,111,145,112,228,233,149,184,110,328,329,280,113,275,327,330,81,191,235,190,234,236,192,151,150,282,283,189,152,237,233,281,149,193,284,115,114,116,334,153,188,333,280,113,238,232,148,285,335,195,240,239,194,196,154,241,238,155,287,288,153,193,286,197,156,118,289,117,242,237,119,285,152,339,338,192,340,116,157,198,86,399,344,400,456,398,345,457,292,517,458,293,343,455,401,397,346,516,459,518,244,294,342,581,519,245,291,402,454,347,396,580,520,403,348,404,347,402,349,461,462,296,295,405,460,346,297,463,401,350,294,523,247,522,248,459,298,406,524,246,521,249,464,345,351,407,352,408,351,406,353,466,465,299,300,409,467,350,298,464,354,301,405,527,251,528,250,468,410,526,252,297,349,302,463,529,249,411,412,356,355,470,357,410,413,303,471,469,304,354,302,358,472,409,305,468,532,254,414,531,255,301,533,253,353,530,256,473,306,416,415,360,359,474,361,417,475,414,307,306,358,473,308,476,362,418,305,536,258,413,537,257,309,357,472,535,259,477,538,256,304,420,364,419,363,421,479,365,478,311,310,418,362,480,312,477,309,422,366,541,261,481,540,262,361,417,542,260,313,308,476,539,263,424,368,367,423,425,483,369,484,314,366,315,482,422,313,426,485,316,370,545,481,265,546,264,365,312,421,544,266,547,263,317,427,428,372,371,429,427,487,488,318,373,370,317,319,430,426,486,489,550,268,316,320,374,369,549,551,267,269,490,485,431,425,548,552,432,375,376,433,431,492,374,491,322,377,321,493,434,323,430,490,320,373,555,494,271,554,272,378,324,435,556,270,553,273,319,429,436,379,437,380,435,496,378,497,325,326,438,381,495,324,498,327,434,377,559,275,494,560,274,382,439,558,276,323,328,499,561,273,440,441,383,384,501,382,439,500,442,329,330,385,502,328,499,381,438,331,564,278,443,563,279,327,386,503,565,277,498,562,280,332,445,444,387,388,505,386,446,443,333,504,506,332,389,334,385,503,447,331,507,568,282,442,569,281,335,567,283,390,570,280,502,330,449,391,448,392,450,390,509,510,337,336,447,508,393,338,511,389,335,451,573,285,572,286,507,446,574,284,339,394,334,512,571,287,453,395,452,396,454,394,514,513,340,341,451,515,397,339,512,455,393,342,577,289,578,288,516,338,450,576,290,579,287,511,398,392,648,582,649,716,717,647,583,787,718,518,650,715,581,519,584,646,788,786,719,789,860,520,580,457,517,458,651,714,859,790,645,585,652,653,586,721,587,722,651,585,654,522,720,723,588,521,523,793,584,792,650,794,655,520,524,719,461,791,724,460,462,589,583,459,657,656,590,726,591,658,725,589,727,655,526,592,525,527,724,797,659,798,588,728,796,654,524,528,465,464,593,799,466,723,795,463,661,660,594,662,595,730,731,593,729,530,596,659,732,663,531,529,802,801,592,728,803,528,532,468,597,469,800,658,733,664,467,470,665,666,599,598,735,664,734,736,600,597,667,534,533,535,733,806,663,807,737,805,596,601,532,536,472,668,473,808,471,732,474,804,670,669,603,602,739,740,671,668,604,738,538,601,537,539,741,811,810,672,737,605,812,667,536,540,476,600,477,809,475,742,813,478,674,673,607,675,606,744,743,608,745,542,672,605,742,543,541,676,815,816,609,814,746,544,540,480,817,479,671,604,741,481,677,478,678,679,611,748,677,610,612,749,747,680,546,609,545,547,676,820,750,613,746,819,821,548,544,484,483,681,818,608,485,822,675,482,683,682,615,753,752,616,614,684,681,550,751,754,549,551,617,613,825,824,685,680,548,552,826,823,487,488,750,755,486,489,618,612,687,686,619,757,688,620,618,756,758,685,554,621,553,555,689,829,755,617,759,830,828,556,552,491,492,684,831,622,490,827,690,493,691,692,623,690,624,761,762,622,760,558,693,625,763,557,559,689,834,833,621,835,759,560,556,495,832,496,694,626,764,494,688,497,695,696,627,628,766,765,694,697,626,767,562,629,563,561,764,838,839,693,768,625,837,698,564,560,499,630,498,840,500,763,836,497,700,699,631,632,770,701,771,769,630,633,698,566,565,567,772,843,702,842,768,844,634,629,568,564,503,697,502,841,504,773,501,845,704,705,636,703,635,775,774,637,776,570,634,706,773,702,571,569,847,848,638,777,846,572,568,507,633,506,849,707,772,701,508,505,708,709,640,779,639,707,780,641,778,710,574,638,575,573,781,852,706,851,642,777,853,711,576,572,510,511,637,850,509,782,854,512,713,712,644,784,643,783,714,645,711,578,785,782,642,579,577,856,646,857,715,855,710,580,576,786,514,858,781,515,513,641,647,516,936,1013,937,1012,861,1014,1091,935,862,1092,938,1011,788,1090,1015,1172,1093,789,860,863,934,790,859,1171,1094,717,1010,939,787,718,1173,864,940,941,1017,1018,865,939,866,864,1016,942,1019,1097,1096,792,867,793,938,791,863,1095,1098,1015,943,794,1020,790,721,868,720,722,1178,1177,945,944,1022,869,1021,870,946,1023,943,868,1101,871,1020,796,797,1100,1102,795,1024,947,867,942,798,1099,1103,872,794,725,1019,724,726,1182,949,948,1026,950,1027,874,873,1025,947,875,872,1106,1105,800,1028,951,801,799,1024,1107,1104,876,871,802,946,729,798,1029,728,730,1187,952,953,954,1031,1030,952,878,877,1032,879,1029,955,1110,876,804,951,805,1109,1111,803,880,1033,806,1028,1108,1112,875,956,733,802,732,950,1191,957,958,1035,882,1034,1036,881,956,883,959,1114,1115,808,880,1033,809,1037,807,955,884,1113,1116,960,810,737,736,879,806,1032,1196,738,1038,962,961,1039,1040,886,963,887,885,1038,960,1041,1119,812,813,1118,1120,888,884,964,811,1037,814,959,1042,1117,1121,741,740,810,1200,889,883,966,1044,965,967,890,1043,891,1045,889,964,1042,1124,1123,968,816,817,892,888,815,1046,1122,1125,818,1041,745,963,744,893,969,814,1205,746,970,971,1048,894,969,1049,895,1047,893,972,1128,896,820,1050,821,1129,1127,968,1046,819,822,892,973,1130,1126,897,749,748,1051,818,1209,1210,975,974,1052,1053,898,899,973,976,1051,1054,897,900,1132,1133,825,824,1131,1134,972,977,826,823,1050,1055,896,901,752,753,1214,827,822,1130,979,978,1057,903,980,1056,902,1058,904,977,1137,901,829,1055,828,1136,1138,981,1059,830,827,905,976,1135,1139,900,756,757,1054,831,1219,1218,983,1061,984,982,907,1062,906,1060,908,985,1063,1142,1141,981,833,832,905,909,834,1059,1140,1143,831,1064,760,986,761,904,980,835,1223,759,987,988,1066,1065,911,986,910,912,1067,989,1064,1146,837,836,1145,1147,913,909,985,838,1068,835,990,1063,1144,1148,764,765,839,1228,914,908,992,991,1070,915,1071,1069,916,993,914,990,1150,1151,841,917,1072,840,1068,842,994,913,1149,1152,989,839,768,769,918,843,1073,1232,767,1067,996,995,1074,1075,997,919,920,1073,918,1076,994,1155,921,845,998,844,1154,1156,846,917,1072,843,1077,1153,1157,922,993,772,847,773,999,1237,1000,1001,1079,999,1078,924,923,1080,1002,922,925,1159,1160,849,1077,998,848,850,1081,1161,1158,921,926,847,1003,776,851,1076,777,775,1241,997,1004,1005,1083,928,1084,927,1003,1082,1006,929,1164,926,1085,853,852,1163,1165,854,1081,1002,930,1007,851,1162,1166,925,855,780,1086,781,779,1246,1009,1008,1088,1087,932,1010,931,933,1089,1007,1086,1169,1168,857,930,856,1011,858,934,1167,1170,1090,1006,855,1085,859,784,929,785,783,1250,1251,1255,1339,1338,1256,1340,1423,1173,1174,1254,1424,1425,1509,1257,1337,1341,1422,1092,1175,1253,1172,1093,1508,1426,1510,1171,1094,1258,1336,1511,1597,1013,1342,1259,1343,1260,1344,1258,1177,1342,1178,1176,1428,1261,1429,1345,1427,1257,1096,1179,1341,1097,1175,1095,1430,1262,1346,1514,1515,1098,1426,1094,1017,1180,1256,1263,1264,1347,1348,1181,1262,1182,1265,1346,1349,1433,1180,1432,1183,1434,1100,1431,1101,1261,1099,1179,1266,1350,1345,1519,1102,1518,1098,1435,1184,1021,1520,1268,1352,1267,1351,1185,1353,1269,1186,1266,1437,1184,1350,1436,1438,1187,1104,1354,1105,1270,1103,1265,1435,1183,1439,1523,1106,1349,1188,1524,1102,1025,1522,1272,1356,1271,1357,1355,1273,1189,1190,1441,1270,1442,1188,1191,1440,1354,1358,1274,1108,1109,1107,1443,1187,1269,1110,1439,1192,1528,1527,1106,1029,1353,1359,1276,1360,1361,1277,1275,1359,1194,1193,1446,1445,1362,1192,1195,1274,1278,1112,1444,1447,1113,1358,1111,1191,1196,1114,1532,1363,1279,1273,1533,1531,1110,1033,1280,1365,1364,1281,1279,1198,1197,1366,1363,1450,1282,1449,1199,1196,1451,1278,1116,1117,1448,1115,1362,1367,1200,1118,1283,1452,1195,1536,1537,1037,1114,1036,1284,1369,1285,1368,1202,1370,1283,1201,1286,1454,1203,1367,1455,1453,1200,1120,1121,1371,1282,1119,1287,1456,1204,1122,1452,1541,1366,1199,1540,1542,1041,1040,1289,1373,1288,1374,1372,1206,1290,1205,1287,1458,1207,1459,1375,1371,1204,1457,1124,1125,1460,1291,1208,1286,1123,1126,1545,1546,1456,1203,1376,1370,1544,1045,1293,1377,1292,1378,1294,1210,1376,1209,1211,1463,1291,1462,1379,1464,1295,1128,1208,1129,1375,1212,1461,1127,1130,1290,1380,1550,1549,1465,1049,1207,1048,1296,1297,1382,1381,1296,1298,1214,1383,1380,1215,1213,1467,1466,1468,1295,1299,1132,1133,1212,1216,1384,1379,1131,1134,1465,1469,1554,1294,1300,1553,1555,1052,1053,1301,1386,1302,1385,1300,1218,1387,1219,1217,1471,1303,1472,1384,1470,1299,1137,1220,1136,1388,1216,1473,1138,1135,1304,1383,1558,1559,1469,1056,1221,1057,1298,1305,1390,1306,1391,1389,1222,1304,1223,1307,1476,1221,1475,1392,1388,1224,1477,1141,1140,1474,1303,1220,1308,1142,1139,1563,1562,1478,1225,1393,1387,1564,1060,1310,1394,1309,1395,1226,1393,1311,1227,1308,1480,1225,1396,1479,1481,1228,1145,1144,1392,1312,1146,1307,1478,1224,1143,1482,1567,1397,1229,1568,1566,1064,1065,1314,1399,1398,1313,1315,1230,1231,1397,1400,1484,1312,1485,1229,1232,1483,1316,1149,1148,1486,1150,1396,1401,1228,1147,1311,1482,1233,1572,1571,1068,1151,1069,1318,1403,1402,1317,1319,1404,1234,1235,1488,1489,1401,1233,1236,1316,1320,1153,1490,1487,1152,1405,1154,1232,1237,1151,1576,1400,1315,1321,1577,1575,1155,1072,1322,1407,1323,1408,1406,1321,1239,1238,1493,1324,1492,1240,1237,1494,1409,1405,1320,1157,1156,1158,1491,1241,1325,1155,1495,1236,1580,1581,1159,1076,1410,1404,1326,1411,1327,1412,1243,1410,1325,1242,1328,1497,1244,1413,1498,1496,1241,1161,1409,1160,1324,1162,1329,1499,1245,1495,1585,1159,1414,1240,1584,1163,1080,1586,1331,1330,1416,1415,1247,1332,1246,1329,1417,1414,1501,1248,1502,1245,1500,1165,1503,1164,1333,1166,1249,1328,1418,1413,1589,1163,1590,1167,1499,1244,1084,1588,1335,1420,1334,1419,1336,1251,1421,1250,1252,1506,1333,1505,1418,1507,1337,1169,1249,1422,1168,1253,1170,1504,1332,1417,1594,1593,1167,1508,1171,1088,1248,1338,1687,1598,1688,1776,1599,1686,1777,1510,1867,1778,1597,1511,1689,1775,1685,1600,1424,1512,1596,1779,1866,1868,1425,1509,1959,1869,1684,1601,1690,1774,1508,1426,1691,1602,1692,1603,1690,1601,1781,1514,1782,1515,1693,1604,1513,1780,1783,1600,1516,1689,1428,1429,1872,1512,1873,1427,1694,1605,1779,1871,1430,1874,1784,1517,1696,1695,1606,1607,1786,1697,1605,1518,1785,1608,1694,1519,1787,1517,1520,1784,1432,1698,1604,1433,1609,1877,1693,1431,1876,1516,1788,1878,1521,1434,1783,1875,1700,1611,1610,1699,1701,1612,1790,1523,1522,1791,1789,1609,1698,1524,1521,1702,1613,1436,1792,1788,1437,1881,1882,1435,1608,1525,1880,1697,1520,1438,1703,1883,1704,1615,1705,1614,1616,1703,1794,1527,1795,1526,1706,1528,1793,1613,1617,1702,1796,1525,1440,1441,1886,1885,1529,1439,1792,1442,1707,1612,1887,1884,1618,1524,1708,1619,1709,1620,1618,1799,1707,1531,1798,1710,1530,1532,1621,1800,1617,1797,1529,1444,1706,1445,1533,1890,1711,1889,1443,1801,1891,1622,1446,1796,1616,1528,1713,1623,1712,1624,1714,1803,1622,1535,1625,1536,1711,1802,1804,1534,1715,1537,1621,1449,1448,1805,1801,1533,1894,1626,1895,1710,1450,1447,1893,1896,1538,1363,1717,1628,1627,1718,1716,1629,1807,1539,1808,1540,1626,1806,1538,1719,1715,1541,1809,1630,1453,1452,1899,1898,1625,1537,1454,1805,1451,1900,1542,1714,1720,1810,1721,1632,1722,1631,1633,1720,1812,1811,1544,1543,1723,1630,1813,1545,1542,1634,1810,1719,1457,1456,1903,1458,1904,1724,1902,1814,1546,1541,1629,1455,1635,1809,1726,1636,1725,1637,1635,1816,1727,1548,1724,1547,1815,1817,1638,1549,1634,1546,1461,1728,1818,1814,1460,1907,1723,1908,1462,1550,1639,1906,1459,1545,1909,1633,1730,1640,1641,1729,1731,1820,1639,1552,1821,1642,1551,1553,1728,1819,1732,1822,1550,1638,1465,1554,1912,1464,1466,1643,1911,1818,1913,1727,1463,1823,1467,1549,1734,1645,1644,1735,1733,1825,1646,1556,1824,1643,1557,1555,1736,1826,1732,1823,1558,1647,1469,1554,1916,1470,1468,1642,1917,1827,1915,1737,1471,1822,1467,1559,1738,1649,1739,1648,1650,1829,1737,1560,1740,1561,1830,1828,1647,1559,1651,1562,1473,1736,1831,1827,1474,1921,1741,1920,1472,1558,1646,1922,1475,1563,1919,1652,1743,1653,1742,1654,1652,1744,1833,1834,1564,1565,1741,1655,1832,1563,1566,1651,1835,1745,1477,1478,1925,1476,1924,1740,1926,1831,1562,1567,1656,1479,1650,1836,1747,1657,1658,1748,1746,1656,1838,1569,1837,1568,1659,1839,1570,1749,1745,1567,1836,1655,1481,1482,1929,1930,1660,1571,1480,1840,1483,1928,1566,1750,1744,1835,1751,1662,1752,1661,1750,1842,1663,1573,1660,1572,1753,1843,1841,1574,1749,1571,1664,1485,1486,1844,1840,1575,1934,1659,1933,1754,1484,1487,1935,1932,1570,1400,1756,1666,1755,1665,1667,1846,1757,1577,1847,1754,1578,1576,1664,1845,1668,1848,1579,1490,1758,1489,1575,1938,1753,1939,1491,1844,1937,1663,1488,1849,1669,1580,1760,1670,1759,1671,1669,1761,1851,1581,1850,1582,1758,1580,1852,1672,1668,1762,1849,1583,1494,1493,1942,1943,1579,1495,1853,1492,1757,1673,1941,1944,1667,1584,1764,1674,1675,1765,1763,1673,1855,1585,1586,1856,1854,1676,1766,1584,1587,1762,1672,1498,1857,1853,1497,1947,1946,1499,1677,1583,1948,1767,1588,1496,1761,1945,1768,1769,1679,1678,1859,1767,1680,1590,1860,1677,1770,1589,1858,1591,1588,1861,1502,1766,1681,1501,1676,1951,1771,1503,1952,1592,1857,1950,1587,1500,1862,1953,1773,1683,1772,1682,1774,1684,1864,1594,1863,1593,1771,1681,1595,1865,1862,1685,1592,1775,1506,1505,1956,1596,1955,1507,1770,1680,1866,1957,1504,1954,1861,1591,2053,1960,2054,2146,2147,2052,1961,2148,2240,1868,1869,1959,2145,2055,2051,1962,2241,2239,2149,2335,2242,1870,1958,1777,1778,1867,2144,2056,2050,1963,2334,2243,2057,2058,1964,1965,2151,2056,2152,1963,2059,1872,2150,1873,1966,1871,2153,2055,2245,1962,2246,1874,1781,2149,2244,1870,2060,1782,1780,1967,2247,2154,1783,1875,2062,2061,1968,1969,2156,2155,2063,2060,1967,1970,1876,1877,2157,2154,1875,2250,1878,2249,2064,1966,2059,1971,1785,2251,1786,2158,1874,2248,1784,2153,1879,1787,2066,2065,1973,1972,2067,2160,2159,1974,2161,1881,1880,2064,1971,2068,2158,1882,1879,2254,1975,2253,2255,2162,1789,1790,1970,2063,1883,1788,1878,1791,2252,2157,2070,1977,2071,2069,2164,1976,1978,2165,2163,1885,1884,2072,1975,2068,1886,1979,2166,2258,1883,2259,2162,1794,2257,1793,1887,2073,2260,1795,1974,1792,2067,1980,2074,2075,1981,1982,2168,2169,2073,1980,2076,1889,2167,1888,1983,1890,2170,1979,2263,2072,2262,1887,1798,2077,1891,1797,2166,2264,2261,1799,1984,2171,1796,1978,2079,2078,1985,1986,2173,2172,2080,1984,2077,1893,1987,2174,1894,1892,2171,2267,2081,1983,2266,1895,2268,1802,2076,1891,1988,2175,1801,1803,2170,2265,1800,2269,2083,1990,2082,1989,2084,2177,2176,1991,2178,1988,1897,1898,2081,2085,1896,2271,2175,1899,2272,2179,1992,1806,2270,1987,1805,1895,1807,2080,2273,2086,1900,1804,2087,2088,1994,1993,2086,2181,1995,2182,2180,1901,1902,2089,1992,2085,2183,1900,1996,1903,2276,2275,2179,1810,1811,2277,1809,2274,2090,1991,1899,1904,2184,1812,2091,2092,1998,1999,2185,1997,2186,2090,2093,1906,1905,2184,2187,2000,1996,1907,2280,1904,2089,2279,2094,2281,1814,1815,2183,1908,1813,2188,2001,2278,1903,1995,2096,2095,2002,2003,2190,2097,2189,2001,2094,1910,2191,2004,1909,1911,2188,2098,2284,2000,2285,1908,2283,2192,1818,1819,1912,2093,2005,1817,2286,1820,2187,1907,2100,2007,2006,2101,2099,2194,2195,2193,2005,2008,1914,1913,1915,2098,2102,2289,2288,2192,2196,2009,2004,1916,1912,1822,1823,2287,2290,1824,1821,2097,2103,2191,2104,2105,2011,2010,2198,2103,2199,2012,2106,1918,2197,2009,1919,1917,2200,2102,2293,2013,2292,1920,2294,2196,1827,1826,1916,2107,2008,1828,2291,1825,2201,1921,2109,2108,2015,2014,2203,2016,2202,2110,2107,1922,1923,2204,2201,2013,2017,1921,2297,1924,2111,2298,2106,2296,1831,1830,2205,1920,1832,2200,2012,2299,1925,2018,2113,2112,2019,2020,2114,2207,2018,2206,2208,1927,1926,2111,2021,2115,2205,1928,2017,1925,2301,2302,2209,1835,1834,2300,1836,2303,2110,2022,1929,1924,2204,1833,2117,2023,2118,2024,2116,2211,2212,2022,2210,2025,1931,1930,2119,2115,1932,2306,2213,1929,2305,2209,2021,1839,2307,2026,1840,1933,1838,2120,2304,2114,1928,1841,2121,2122,2028,2027,2215,2216,2120,2029,2123,1935,2026,2214,1934,1936,2217,2310,2119,2030,2311,1933,2309,1843,2124,1937,2025,2213,1844,1842,2218,2312,1845,2308,2126,2125,2032,2031,2220,2219,2127,2033,2124,1939,2221,1940,2030,1938,2218,2034,2314,2128,2315,1941,1847,2123,1937,1848,2222,2313,2316,1846,2029,2217,1849,2035,2130,2036,2129,2131,2224,2037,2035,2223,2225,1943,1944,2128,2038,2132,1942,2034,2222,2319,1945,2318,2226,1851,2320,1852,1941,2127,2317,1850,2039,1853,2133,2033,2134,2135,2040,2041,2133,2228,2229,2039,2227,1947,1948,2136,2042,2132,2230,1946,1949,2323,2038,2324,2322,2226,1856,1855,2043,2137,1945,1857,1950,1854,2325,2231,2138,2139,2045,2044,2232,2233,2137,2140,2046,2043,1952,1951,2231,2234,1953,2327,1950,2328,2136,2047,2141,2042,1860,2326,1859,2230,1954,2329,1861,2235,1949,1858,2143,2142,2049,2048,2237,2144,2236,2050,2141,1956,2238,1955,2047,1957,2235,2145,2332,2051,2331,1954,1864,2239,2333,1958,2140,1863,1865,2046,2330,2234,1862,1953,2432,2528,2527,2433,2336,2529,2624,2337,2431,2241,2434,2526,2625,2242,2335,2338,2430,2623,2530,2626,2721,2334,2243,2147,2720,2627,2240,2148,2435,2525,2429,2339,2436,2437,2532,2340,2435,2533,2341,2339,2531,2438,2245,2629,2342,2534,2246,2434,2630,2244,2338,2628,2530,2247,2631,2151,2243,2439,2152,2343,2150,2535,2627,2726,2440,2441,2536,2344,2537,2345,2439,2442,2343,2535,2538,2346,2249,2250,2633,2634,2248,2438,2342,2632,2251,2635,2443,2534,2347,2539,2155,2247,2156,2154,2731,2730,2445,2444,2541,2349,2348,2540,2446,2443,2542,2350,2347,2539,2253,2254,2638,2637,2252,2639,2255,2447,2442,2543,2351,2346,2636,2159,2538,2160,2251,2158,2256,2735,2449,2448,2545,2353,2352,2544,2450,2546,2354,2447,2351,2258,2257,2642,2543,2641,2451,2643,2547,2259,2256,2355,2446,2350,2163,2640,2164,2644,2260,2162,2255,2542,2453,2452,2549,2357,2454,2550,2356,2548,2358,2451,2262,2646,2261,2355,2455,2551,2647,2359,2645,2263,2547,2260,2167,2168,2648,2450,2264,2354,2644,2166,2552,2456,2457,2458,2553,2361,2456,2554,2362,2360,2552,2266,2459,2555,2650,2455,2265,2651,2363,2359,2267,2649,2551,2264,2652,2172,2171,2268,2556,2460,2364,2454,2173,2358,2461,2462,2365,2558,2557,2460,2366,2364,2559,2463,2556,2270,2367,2655,2654,2269,2271,2459,2363,2656,2653,2268,2560,2555,2272,2464,2176,2175,2368,2177,2752,2174,2465,2466,2562,2369,2370,2561,2464,2563,2467,2368,2371,2274,2560,2659,2275,2658,2273,2463,2660,2564,2367,2468,2276,2657,2372,2272,2180,2179,2559,2181,2661,2756,2470,2469,2566,2374,2373,2565,2567,2471,2468,2375,2372,2278,2663,2279,2564,2277,2662,2568,2664,2472,2467,2376,2280,2371,2184,2276,2661,2183,2665,2185,2563,2760,2474,2473,2570,2378,2377,2571,2475,2569,2379,2472,2282,2376,2667,2283,2572,2668,2476,2281,2666,2568,2380,2284,2471,2669,2188,2375,2187,2280,2189,2573,2665,2765,2478,2477,2574,2382,2479,2575,2381,2383,2573,2576,2476,2286,2287,2671,2480,2672,2380,2384,2285,2288,2670,2572,2673,2192,2577,2475,2191,2193,2379,2284,2481,2289,2482,2483,2579,2386,2481,2578,2387,2385,2580,2577,2484,2291,2290,2676,2480,2675,2388,2384,2292,2289,2677,2581,2674,2196,2576,2485,2197,2195,2389,2293,2479,2288,2486,2487,2583,2390,2391,2582,2485,2584,2389,2488,2295,2392,2680,2294,2581,2679,2484,2296,2681,2585,2388,2293,2489,2678,2200,2393,2201,2297,2199,2580,2682,2777,2490,2491,2587,2394,2395,2588,2586,2489,2492,2393,2396,2299,2684,2298,2589,2300,2685,2585,2683,2488,2493,2392,2297,2397,2204,2301,2686,2205,2682,2203,2590,2782,2495,2494,2591,2399,2398,2592,2496,2590,2493,2400,2397,2303,2593,2688,2302,2689,2304,2497,2687,2589,2401,2492,2301,2690,2396,2305,2208,2209,2594,2207,2686,2786,2499,2498,2403,2595,2596,2500,2402,2404,2594,2497,2597,2307,2401,2692,2693,2308,2306,2501,2405,2691,2694,2309,2593,2598,2305,2496,2212,2213,2400,2211,2790,2214,2503,2502,2600,2407,2504,2599,2406,2408,2601,2311,2501,2598,2697,2505,2312,2696,2405,2409,2310,2698,2602,2313,2695,2216,2217,2309,2597,2500,2404,2506,2215,2410,2507,2508,2604,2411,2506,2603,2412,2605,2410,2509,2315,2701,2316,2413,2505,2602,2700,2409,2702,2314,2606,2317,2221,2220,2699,2510,2313,2414,2703,2222,2601,2504,2511,2512,2608,2415,2416,2609,2510,2607,2414,2513,2417,2319,2320,2705,2610,2706,2509,2704,2606,2318,2321,2413,2514,2418,2225,2707,2224,2703,2317,2226,2322,2611,2515,2516,2612,2419,2420,2613,2514,2517,2611,2418,2421,2614,2324,2323,2709,2710,2325,2708,2322,2513,2518,2610,2417,2422,2711,2229,2615,2228,2326,2230,2321,2807,2520,2519,2617,2424,2616,2423,2521,2518,2425,2618,2615,2422,2328,2327,2714,2713,2329,2522,2426,2715,2326,2712,2517,2619,2421,2614,2233,2330,2232,2234,2811,2812,2524,2523,2621,2428,2525,2620,2427,2429,2622,2522,2332,2718,2426,2619,2331,2526,2717,2333,2430,2719,2623,2330,2716,2237,2334,2521,2236,2425,2238,2618,2720,2816,2820,2918,2821,2917,3015,2919,2722,2819,2723,3016,2916,2822,3113,3017,2625,3014,2920,2724,2818,2626,2721,3112,3018,2720,2627,3114,2528,2915,2823,3212,3115,2624,2824,2922,2825,2923,2726,2823,2727,2921,2725,2826,3020,2924,3021,2728,2629,3019,2630,2822,2628,2920,2724,3022,2631,2827,3118,2925,2729,3018,3119,2532,2627,2533,2829,2828,2927,2926,2731,2730,2830,2827,2928,2925,3025,3024,2732,2729,2633,2634,3026,3023,2831,2826,2632,2635,2929,2924,2733,2728,3123,3122,2536,2537,2631,3027,2833,2931,2832,2930,2834,2735,2932,2734,2736,3029,2831,3028,2929,2733,2638,3030,2637,2835,2933,2737,2639,3027,2636,2830,3127,3031,2928,2732,2541,2540,3126,2640,2837,2935,2838,2836,2936,2739,2934,2740,2738,3033,2839,3034,2835,3032,2937,2642,2933,2741,2641,2737,2643,3035,2640,3031,3131,2644,2840,2545,3132,2834,2544,2742,2841,2842,2939,2940,2743,2840,2744,2938,2843,2742,3037,2941,3038,2745,2646,3036,2647,2839,2645,2937,3039,2741,2844,2648,2942,2746,2644,3136,3135,2549,3035,2550,2846,2845,2944,2943,2748,2747,2847,2844,2945,2942,3042,3041,2749,2746,2650,2651,3043,3040,2848,2649,2843,2946,2750,2652,2941,2745,3140,2553,3139,2554,2648,3044,2850,2948,2849,2947,2851,2752,2949,2751,2753,3046,2848,3045,2946,3047,2750,2655,2852,2654,2950,2754,2656,2653,3044,2847,3144,3048,2945,2749,2558,2557,3145,3143,2854,2952,2855,2853,2953,2756,2951,2757,2755,3050,2856,3051,2954,2852,3049,2659,2758,2658,2950,2754,2660,3052,2657,3048,2857,3148,3149,2562,2661,2561,2955,2759,2858,2859,2956,2957,2760,2857,2761,2955,2860,3054,2759,2958,3055,2762,2663,3053,2662,2664,2856,3056,2954,2758,2861,2959,2661,2763,2665,3153,2566,3152,3052,2565,2863,2862,2961,2960,2765,2764,2864,2962,2861,2959,3059,2766,3058,2763,2667,2668,3060,2865,2666,3057,2963,2860,2767,2669,2958,2762,3157,2665,2570,3158,2571,3061,2867,2965,2866,2964,2868,2769,2966,2768,2770,3063,2865,3062,2963,3064,2869,2671,2767,2672,2967,2771,2670,2673,3061,3065,2864,3161,3162,2574,2575,2962,2766,2669,2871,2969,2872,2970,2870,2773,2968,2774,2772,3067,2873,3068,2971,3066,2869,2676,2775,2675,2967,2771,2677,2674,3069,3065,2874,3166,3165,2579,2578,2972,2776,2678,2875,2876,2973,2974,2777,2778,2874,2972,2877,2975,3071,2776,3072,2779,2680,2679,3070,2873,2681,3073,2971,2878,2775,2678,2976,2780,3170,2682,2583,3169,2582,3069,2880,2879,2978,2977,2782,2881,2781,2979,2878,3076,2783,2976,3075,2780,2684,3077,2685,2683,2882,3074,2980,2784,2877,2975,2686,2779,2682,3174,2587,3175,3078,2588,2884,2982,2883,2885,2981,2786,2983,2785,2787,3080,2882,3079,2980,2886,3081,2688,2784,2689,2984,2788,2687,3078,2690,3082,2881,3179,3178,2591,2686,2592,2979,2783,2888,2986,2889,2987,2887,2790,2985,2791,2789,3084,2890,3085,2988,3083,2792,2692,2886,2693,2984,2788,2691,2694,3086,2891,3183,3082,2989,2793,2595,2596,3182,3184,2892,2893,2990,2991,2794,2795,2891,2894,2989,2992,3088,3089,2793,2796,2697,2696,3087,3090,2890,2698,2895,2988,2792,2695,2993,2797,3187,2600,3188,2599,2699,3086,2897,2896,2995,2994,2799,2898,2798,2996,2895,2800,3093,2993,3092,2797,2701,3094,2700,2899,2702,2997,3091,2801,2894,2699,2992,2796,2703,3191,3192,2604,3095,2603,2901,2999,2900,2902,2998,2803,3000,2802,2804,3097,2899,3096,2903,3098,2997,2705,3001,2801,2706,2805,2704,3095,2707,3099,3196,2703,2898,2608,3195,2904,2609,2800,2905,3003,2906,3004,2904,2807,3002,2808,2806,3101,2907,3102,3005,2809,2709,3100,2710,2903,3001,2805,2708,3103,2711,2908,3200,3099,3006,2810,2612,2613,3201,2707,2909,2910,3007,3008,2811,2812,2908,2911,3006,3009,3105,3106,2810,2813,2714,2713,3104,3107,2907,2912,2715,2712,3005,3010,2809,2814,3204,3205,2617,2616,2716,3103,2914,3012,2913,3011,2816,2915,2815,3013,2817,2912,3110,3010,3109,2814,2718,3111,2717,2916,2719,3014,2818,3108,2716,2911,3209,3009,2813,3112,3208,2621,2720,2620,3312,3213,3311,3214,3410,3313,3114,3411,3212,3115,3412,3508,3215,3310,3314,3409,3016,3211,3116,3113,3017,3509,3507,3413,3606,3510,3112,3018,3216,3309,3408,3315,3316,3217,3317,3218,3216,3315,3118,3415,3119,3416,3219,3318,3117,3414,3120,3020,3215,3417,3314,3021,3019,3513,3116,3514,3220,3319,3413,3022,3512,3121,3018,2922,3321,3222,3320,3221,3223,3123,3322,3122,3420,3419,3220,3319,3124,3121,3421,3418,3025,3024,3224,3323,3219,3518,3517,3026,3318,3125,3023,3120,3422,3519,3417,3516,3325,3226,3324,3225,3227,3326,3127,3424,3126,3423,3128,3224,3425,3323,3228,3327,3029,3125,3422,3028,3129,3030,3522,3521,3426,3027,3523,3223,3322,3229,3031,2931,3329,3230,3330,3231,3229,3328,3131,3428,3132,3429,3232,3130,3427,3331,3133,3228,3327,3033,3034,3032,3430,3129,3526,3426,3527,3233,3525,3332,3035,3031,3134,2935,3334,3333,3235,3234,3136,3135,3432,3236,3335,3233,3332,3433,3137,3431,3134,3037,3434,3038,3237,3232,3336,3530,3331,3036,3531,3138,3039,3133,3430,3529,2939,3035,3338,3239,3337,3238,3240,3339,3140,3437,3436,3139,3141,3237,3336,3438,3241,3435,3340,3138,3042,3041,3142,3535,3534,3043,3040,3236,3335,3439,3536,3137,3533,3434,3342,3243,3343,3244,3242,3341,3144,3441,3145,3440,3143,3245,3442,3344,3241,3340,3146,3046,3045,3439,3142,3047,3539,3538,3443,3044,3246,3540,3345,3048,3147,2948,3346,3247,3347,3248,3445,3148,3246,3345,3149,3249,3348,3446,3444,3147,3150,3050,3245,3051,3447,3344,3049,3543,3250,3349,3443,3146,3544,3542,3151,3052,3048,2952,3351,3252,3350,3251,3253,3352,3153,3449,3152,3450,3250,3349,3154,3448,3151,3254,3451,3054,3353,3055,3155,3547,3053,3548,3249,3056,3348,3447,3546,3150,2956,3549,3355,3256,3356,3257,3255,3354,3157,3454,3453,3158,3156,3258,3357,3254,3455,3353,3452,3059,3159,3058,3155,3552,3060,3551,3057,3456,3259,3553,3358,3253,3550,3352,3359,3260,3360,3261,3259,3358,3161,3458,3162,3262,3361,3457,3459,3160,3163,3063,3258,3357,3062,3456,3064,3556,3159,3263,3460,3362,3555,3557,3061,3164,3065,2965,3364,3265,3363,3264,3266,3365,3166,3462,3165,3263,3362,3463,3461,3167,3164,3067,3267,3366,3068,3464,3066,3560,3168,3262,3460,3361,3561,3559,3069,3163,3065,2969,3368,3269,3367,3268,3270,3369,3170,3466,3467,3169,3171,3267,3366,3271,3465,3370,3468,3071,3168,3072,3172,3564,3070,3565,3073,3464,3266,3563,3365,3272,3566,3371,3372,3273,3373,3274,3272,3371,3174,3471,3175,3470,3275,3374,3173,3472,3176,3271,3469,3076,3370,3075,3172,3569,3077,3568,3276,3074,3375,3473,3570,3177,2978,3567,3377,3278,3376,3277,3475,3179,3279,3378,3178,3276,3375,3474,3476,3180,3177,3080,3280,3079,3473,3379,3081,3573,3275,3374,3477,3181,3572,3574,3176,3078,3082,2982,3381,3282,3380,3281,3283,3382,3183,3479,3182,3480,3184,3280,3478,3379,3284,3383,3181,3084,3085,3481,3185,3083,3577,3578,3477,3086,3279,3576,3378,3082,3180,2986,3385,3286,3386,3287,3285,3384,3187,3483,3484,3188,3186,3288,3387,3482,3284,3485,3383,3189,3088,3089,3185,3581,3582,3087,3090,3289,3388,3481,3580,3190,3583,3486,3389,3390,3290,3291,3191,3192,3488,3289,3388,3292,3391,3487,3190,3489,3193,3093,3486,3092,3288,3293,3387,3586,3392,3094,3585,3189,3091,3194,3490,3587,2995,3095,3394,3295,3393,3294,3296,3395,3196,3492,3195,3491,3293,3197,3493,3392,3194,3297,3396,3097,3096,3098,3490,3198,3590,3494,3589,3292,3591,3391,3095,3099,3193,2999,3398,3299,3399,3300,3298,3397,3200,3496,3201,3497,3199,3301,3495,3400,3297,3396,3101,3202,3498,3102,3198,3100,3594,3595,3494,3103,3593,3302,3401,3296,3099,3003,3402,3303,3403,3304,3302,3204,3401,3205,3500,3501,3305,3404,3203,3206,3499,3502,3105,3106,3301,3400,3306,3598,3599,3104,3405,3202,3107,3207,3498,3597,3503,3600,3407,3308,3406,3307,3309,3408,3209,3505,3208,3504,3306,3405,3210,3506,3207,3110,3310,3503,3409,3109,3111,3603,3211,3602,3305,3404,3507,3108,3604,3206,3112,3012,3705,3607,3706,3802,3803,3704,3608,3509,3899,3804,3606,3510,3801,3707,3703,3609,3900,3898,3805,3411,3605,3511,3995,3901,3508,3412,3702,3610,3800,3708,3413,3507,3709,3611,3710,3612,3807,3708,3610,3808,3513,3514,3806,3711,3613,3512,3809,3904,3707,3515,3609,3905,3415,3416,3903,3805,3511,3414,3712,3614,3417,3906,3516,3810,3714,3713,3616,3615,3811,3812,3715,3712,3617,3614,3518,3517,3810,3813,3519,3516,3908,3909,3420,3419,3716,3618,3711,3613,3907,3421,3418,3809,3520,3515,3910,3814,3718,3620,3717,3619,3719,3816,3621,3815,3522,3521,3716,3817,3618,3523,3814,3720,3622,3913,3520,3912,3424,3423,3524,3425,3818,3914,3911,3617,3715,3422,3813,3519,3722,3624,3723,3721,3625,3820,3623,3819,3526,3821,3527,3525,3724,3626,3720,3622,3917,3818,3916,3428,3528,3524,3822,3429,3427,3918,3915,3627,3725,3430,3621,3426,3726,3727,3628,3629,3824,3725,3627,3825,3530,3823,3728,3531,3630,3529,3921,3532,3724,3826,3626,3432,3920,3822,3433,3922,3528,3431,3729,3631,3434,3533,3919,3430,3731,3730,3633,3632,3828,3829,3732,3634,3729,3535,3534,3631,3827,3536,3830,3533,3925,3437,3733,3436,3635,3926,3924,3728,3630,3826,3438,3537,3435,3532,3831,3927,3735,3637,3734,3636,3736,3833,3832,3638,3539,3538,3733,3635,3540,3834,3831,3737,3639,3929,3537,3930,3441,3440,3541,3928,3442,3634,3732,3835,3830,3439,3931,3536,3739,3641,3740,3738,3642,3837,3640,3836,3543,3838,3544,3542,3741,3643,3737,3639,3835,3933,3934,3545,3445,3541,3446,3444,3839,3932,3935,3644,3742,3447,3443,3638,3743,3744,3645,3646,3841,3742,3644,3840,3547,3842,3745,3548,3647,3546,3549,3938,3937,3741,3839,3643,3449,3843,3450,3746,3648,3448,3545,3939,3936,3451,3550,3351,3748,3747,3650,3649,3845,3749,3846,3651,3746,3552,3551,3844,3648,3553,3550,3847,3942,3941,3750,3652,3454,3453,3843,3745,3943,3647,3455,3554,3452,3549,3940,3848,3752,3654,3751,3653,3753,3849,3655,3850,3556,3555,3848,3750,3557,3652,3851,3754,3656,3946,3554,3458,3945,3947,3457,3558,3459,3847,3651,3749,3456,3852,3944,3460,3756,3658,3757,3659,3755,3854,3657,3853,3560,3561,3855,3758,3559,3660,3852,3754,3656,3950,3562,3462,3951,3949,3463,3558,3461,3856,3661,3759,3464,3851,3952,3460,3760,3761,3662,3663,3858,3759,3857,3661,3762,3564,3565,3859,3664,3563,3566,3856,3954,3955,3758,3660,3466,3467,3860,3763,3953,3665,3465,3562,3468,3567,3956,3855,3765,3764,3667,3666,3862,3766,3668,3863,3569,3861,3763,3568,3665,3570,3567,3958,3959,3767,3864,3669,3471,3860,3470,3762,3664,3472,3571,3957,3960,3469,3566,3372,3769,3671,3768,3770,3670,3866,3672,3867,3573,3865,3572,3574,3767,3669,3771,3673,3868,3963,3962,3571,3475,3575,3474,3476,3864,3964,3961,3668,3766,3473,3477,3674,3773,3675,3774,3676,3772,3870,3871,3674,3577,3578,3775,3677,3576,3869,3872,3771,3673,3967,3579,3966,3479,3480,3575,3968,3478,3678,3776,3868,3873,3481,3965,3580,3777,3778,3679,3680,3875,3874,3776,3678,3779,3581,3582,3681,3876,3580,3873,3583,3971,3483,3775,3484,3677,3970,3972,3780,3682,3877,3482,3579,3485,3584,3872,3969,3782,3781,3684,3683,3879,3783,3685,3878,3586,3880,3780,3585,3682,3587,3975,3584,3784,3877,3686,3488,3976,3881,3487,3974,3588,3489,3779,3681,3486,3583,3977,3490,3786,3688,3785,3787,3687,3883,3689,3884,3590,3882,3589,3591,3784,3686,3788,3690,3979,3885,3980,3492,3588,3592,3881,3491,3493,3978,3981,3685,3783,3490,3691,3494,3790,3692,3791,3693,3789,3887,3691,3888,3594,3595,3792,3886,3694,3593,3889,3788,3690,3983,3596,3984,3496,3497,3592,3495,3885,3982,3985,3695,3793,3498,3890,3597,3794,3795,3696,3697,3892,3891,3793,3796,3695,3698,3598,3599,3893,3890,3597,3600,3988,3987,3500,3501,3792,3694,3797,3699,3989,3499,3502,3894,3596,3601,3986,3889,3799,3701,3798,3700,3896,3800,3702,3895,3603,3602,3897,3797,3699,3604,3894,3992,3801,3601,3703,3991,3505,3504,3993,3898,3605,3506,3796,3698,3503,3990,3600,3893,4092,3996,-1,4093,4186,-1,-1,4091,3997,3900,-1,-1,-1,3995,3901,-1,4094,4185,-1,4090,3998,-1,3803,3902,3994,-1,-1,3899,3804,-1,-1,-1,4096,4097,4000,-1,-1,4095,4001,3999,-1,3904,-1,-1,4098,-1,3905,4002,3903,4094,-1,3998,-1,-1,3906,3807,-1,3808,3902,-1,-1,3806,-1,4003,4100,4101,4004,-1,-1,4005,4099,-1,4003,-1,4102,3908,-1,4006,3909,-1,3907,-1,4098,3910,-1,-1,4002,3811,-1,3812,-1,4007,-1,4103,3906,3810,4104,4105,-1,4009,4008,-1,-1,4103,4106,4010,4007,-1,3913,3912,-1,-1,-1,-1,3914,3911,4102,3816,-1,4011,3815,4006,4107,-1,-1,3817,-1,-1,4109,4108,-1,4013,4012,-1,-1,4110,4107,4014,3917,-1,-1,3916,4011,-1,3918,-1,-1,3915,4015,-1,4111,3820,4106,3819,-1,-1,3821,4010,-1,-1,4113,4112,4017,-1,-1,4016,4114,4018,-1,4111,-1,3921,-1,-1,3920,4015,3922,-1,4019,-1,4115,-1,3919,-1,3824,3923,3825,4110,-1,3823,-1,-1,4117,4116,4021,-1,-1,4118,4022,4020,-1,3925,-1,4115,-1,3926,-1,3924,-1,4023,-1,4019,4119,-1,3927,3828,3923,3829,-1,-1,-1,3827,-1,4114,4121,-1,4025,4120,4122,-1,4026,-1,4024,3929,-1,3930,-1,4119,-1,4027,3928,-1,4123,-1,4023,3931,-1,3833,3832,-1,3927,-1,-1,-1,4028,3834,4125,4126,4029,-1,-1,4124,4030,4028,-1,-1,3933,4031,3934,-1,-1,4127,4123,3932,-1,-1,3935,-1,-1,4027,3837,3836,4032,-1,-1,3838,3931,-1,4129,4130,-1,4034,4033,-1,4128,-1,4035,4032,3938,-1,3937,4131,-1,-1,-1,4127,3939,-1,3936,-1,4036,3841,4031,3840,-1,3842,-1,-1,-1,4132,4133,4134,-1,4038,4037,-1,4132,-1,4039,4135,3942,-1,3941,4036,-1,-1,-1,3943,-1,4131,4040,3940,-1,3845,3846,-1,-1,4136,3844,3944,-1,4035,4137,4138,4042,-1,-1,4041,4043,4136,-1,4139,-1,3946,-1,-1,3945,3947,4040,4044,-1,-1,-1,4135,3944,-1,3849,3850,4140,3948,-1,-1,3848,-1,4142,4141,4046,-1,-1,4047,4045,4143,-1,4140,3950,-1,-1,-1,3951,3949,4048,-1,4044,-1,-1,4144,3952,3854,3853,4139,3948,-1,-1,-1,-1,3855,4146,4145,-1,4050,4051,-1,-1,4147,4049,4144,3954,-1,3955,4052,-1,-1,-1,-1,3953,4148,4048,3956,3858,-1,-1,3857,-1,4143,3859,3952,4053,-1,4150,4149,-1,4054,4055,-1,4151,-1,4053,-1,4056,3958,3959,-1,4148,-1,-1,4152,3957,3960,-1,-1,4052,3862,-1,4057,3863,-1,3861,-1,-1,4147,4154,-1,4153,4059,4155,4058,-1,-1,4060,-1,3963,4057,-1,3962,-1,4152,4156,3964,-1,3961,-1,-1,4061,3866,-1,3867,4056,-1,-1,3865,-1,3965,4158,-1,4063,4159,4157,4062,-1,-1,4064,3967,-1,3966,4160,4061,-1,-1,-1,-1,3968,4156,4065,3965,3870,3871,-1,-1,-1,3969,-1,4060,-1,3869,4162,4163,4067,-1,-1,4161,4066,4068,-1,3971,-1,4164,-1,-1,3970,3972,4065,-1,4069,4160,-1,-1,3969,3875,3973,3874,-1,-1,-1,3876,-1,4165,4166,4167,4071,-1,-1,4072,4165,4070,-1,4168,-1,3975,-1,-1,3976,4073,3974,-1,4069,-1,-1,4164,3977,3879,-1,3973,3878,4169,-1,3880,-1,-1,4170,4171,-1,4075,4076,-1,-1,4169,4172,4074,3979,-1,3980,4077,-1,-1,-1,-1,3978,3981,4073,4168,3883,-1,4173,3884,-1,-1,3882,4078,3977,-1,4175,4174,-1,4079,4080,-1,4176,-1,4173,4078,4081,3983,-1,3984,-1,-1,-1,3982,-1,3985,4177,-1,3887,4077,3888,4082,4172,-1,-1,-1,-1,3886,4179,4178,4084,-1,-1,4083,4180,4085,-1,-1,4177,3988,-1,4082,3987,-1,3989,-1,4181,-1,3986,-1,4086,-1,3892,3891,-1,-1,4081,4176,3990,3893,4183,4182,-1,4088,4184,-1,4087,-1,4089,3992,-1,4181,3991,-1,-1,4086,3993,-1,4185,-1,4090,3990,-1,3896,3895,-1,3994,-1,-1,3897,-1,4085]}}} diff --git a/docs/source/_static/css/foveation-viewer.css b/docs/source/_static/css/foveation-viewer.css deleted file mode 100644 index 8d12840598d8..000000000000 --- a/docs/source/_static/css/foveation-viewer.css +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) 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 - */ - -/* Interactive sampling-grid and pooling viewers on the Foveated Camera page. */ - -.fovi-viewer { - --fovi-ink: #1f2a37; - --fovi-muted: #8a96a8; - --fovi-faint: #d7dee8; - --fovi-surface: #ffffff; - --fovi-panel: #f6f8fb; - --fovi-border: #dfe5ec; - --fovi-accent: #2458d3; - --fovi-camera: #167d72; - --fovi-highlight: #d47b00; - --fovi-body: #29364b; - margin: 1.25rem 0 1.75rem; - padding: 1rem; - border: 1px solid var(--fovi-border); - border-radius: 8px; - background: var(--fovi-panel); - color: var(--fovi-ink); -} - -html[data-theme="dark"] .fovi-viewer { - --fovi-ink: #e3e8ef; - --fovi-muted: #7d8899; - --fovi-faint: #3a4556; - --fovi-surface: #11161d; - --fovi-panel: #1a2029; - --fovi-border: #343d4b; - --fovi-accent: #6d9cff; - --fovi-camera: #3cc2ad; - --fovi-highlight: #f0a33a; - --fovi-body: #5b6f8c; -} - -.fovi-controls { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(12.5rem, 1fr)); - gap: 0.6rem 1.2rem; - align-items: end; -} - -.fovi-control { - display: grid; - grid-template-columns: 1fr auto; - gap: 0.15rem 0.5rem; - margin: 0; - font-size: 0.85rem; -} - -.fovi-viewer [hidden] { - display: none; -} - -.fovi-control-name { - grid-column: 1 / -1; -} - -.fovi-control input[type="range"], -.fovi-control select { - width: 100%; - min-width: 0; - accent-color: var(--fovi-accent); -} - -.fovi-control select { - padding: 0.15rem 0.3rem; - border: 1px solid var(--fovi-border); - border-radius: 4px; - background: var(--fovi-surface); - color: var(--fovi-ink); -} - -.fovi-control-value { - min-width: 3.5rem; - font-variant-numeric: tabular-nums; - text-align: right; -} - -.fovi-reset { - justify-self: start; - padding: 0.25rem 0.9rem; - border: 1px solid var(--fovi-border); - border-radius: 4px; - background: var(--fovi-surface); - color: var(--fovi-ink); - font-size: 0.85rem; - cursor: pointer; -} - -.fovi-summary { - margin: 0.9rem 0 0.6rem; - font-size: 0.9rem; -} - -.fovi-panels { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr)); - gap: 1rem; -} - -.fovi-panels-stacked { - grid-template-columns: 1fr; -} - -.fovi-panels-three { - grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); -} - -.fovi-panel { - margin: 0; - padding: 0.6rem; - border: 1px solid var(--fovi-border); - border-radius: 6px; - background: var(--fovi-surface); -} - -.fovi-panel-control { - max-width: 22rem; - margin-bottom: 0.4rem; -} - -.fovi-panel figcaption { - margin-bottom: 0.4rem; - font-weight: 600; - font-size: 0.9rem; -} - -.fovi-views { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 0.4rem; -} - -.fovi-canvas { - display: block; - width: 100%; - aspect-ratio: 1; - touch-action: none; -} - -.fovi-sphere { - cursor: grab; -} - -.fovi-panel-labels { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 0.4rem; - color: var(--fovi-muted); - font-size: 0.75rem; - text-align: center; -} - -.fovi-panel-note { - margin: 0.4rem 0 0; - font-size: 0.8rem; -} - -.fovi-legend { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.3rem 0.5rem; - margin: 0.7rem 0 0; - font-size: 0.8rem; -} - -.fovi-key { - display: inline-block; - width: 0.7rem; - height: 0.7rem; - margin-left: 0.6rem; - border-radius: 50%; -} - -.fovi-key:first-child { - margin-left: 0; -} - -.fovi-key-accent { - background: var(--fovi-accent); -} - -.fovi-key-muted { - background: var(--fovi-muted); -} - -.fovi-key-camera { - background: var(--fovi-camera); -} - -.fovi-key-highlight { - background: var(--fovi-highlight); -} - -.fovi-legend-note { - margin-left: auto; - color: var(--fovi-muted); -} diff --git a/docs/source/_static/css/foveation-viewer.js b/docs/source/_static/css/foveation-viewer.js deleted file mode 100644 index 1e7bdda1d9b3..000000000000 --- a/docs/source/_static/css/foveation-viewer.js +++ /dev/null @@ -1,987 +0,0 @@ -/* - * Copyright (c) 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 - */ - -// Interactive sampling-grid and pooling viewers for the Foveated Camera page. -// The sampling follows fovi's SamplingCoords with spherical field geometry, as the camera configures it. -(() => { - "use strict"; - - const DEG = Math.PI / 180; - const TAU = 2 * Math.PI; - // fovi's isotropic pooling neighbourhoods for the pooling viewer, beside this script; fetched only when used. - const SCRIPT_URL = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : null; - const TABLES_URL = SCRIPT_URL ? new URL("foveation-pooling-isotropic.json", SCRIPT_URL).href : null; - - // -- Sampling geometry ------------------------------------------------------------------------------------------- - - // Warped Cartesian grid: an N x N lattice in the native plane, mapped radially by the integrated CMF. - // Returns samples in canonical order (x index major), each with normalized visual coordinates s = (x, y) / r_max. - const warpedGrid = (fov, a, res) => { - const half = fov / 2; - const growth = 1 + half / a; - const samples = []; - for (let i = 0; i < res; i++) { - for (let j = 0; j < res; j++) { - const cx = -1 + (2 * i + 1) / res; - const cy = -1 + (2 * j + 1) / res; - const rho = Math.hypot(cx, cy); - const r = a * (Math.pow(growth, rho) - 1); - const theta = Math.atan2(cy, cx); - samples.push({i, j, native: [cx, cy], s: [(r / half) * Math.cos(theta), (r / half) * Math.sin(theta)], valid: rho <= 1 + 1e-12}); - } - } - return samples; - }; - - // Isotropic rings: radii even in cortical distance w = log(r + a), angles per ring matched to the radial step. - const isotropicRings = (fov, a, res) => { - if (res === 1) { - return {radius: [0], count: [1]}; - } - const half = fov / 2; - const wMin = Math.log(a); - const wDelta = (Math.log(half + a) - wMin) / (res - 1); - const radius = Array.from({length: res + 1}, (_, k) => Math.exp(wMin + k * wDelta) - a); - const count = [1]; - for (let k = 1; k < res; k++) { - const step = (radius[k + 1] - radius[k - 1]) / 2; - const tangential = Math.sin(radius[k] * DEG) / DEG; // spherical field geometry - count.push(Math.ceil((TAU * tangential) / step)); - } - return {radius: radius.slice(0, res).map((r) => r / half), count}; - }; - - const isotropicCount = (fov, a, res) => isotropicRings(fov, a, res).count.reduce((sum, n) => sum + n, 0); - - // The camera matches an isotropic retina to foveated_res^2 samples (fovi's auto_match_num_coords). - const matchedIsotropicRes = (fov, a, target) => { - let left = 1; - let right = 1000; - let best = 1; - let bestDiff = Infinity; - while (left <= right) { - const mid = (left + right) >> 1; - const n = isotropicCount(fov, a, mid); - const diff = Math.abs(n - target); - if (diff < bestDiff) { - bestDiff = diff; - best = mid; - } - if (n < target) { - left = mid + 1; - } else { - right = mid - 1; - } - } - while (best > 1 && isotropicCount(fov, a, best) > target) { - best -= 1; - } - return best; - }; - - const isotropicSamples = (fov, a, rings) => { - const {radius, count} = isotropicRings(fov, a, rings); - const samples = []; - radius.forEach((r, ring) => { - for (let k = 0; k < count[ring]; k++) { - const angle = (k * TAU) / count[ring]; - samples.push({ring, s: [r * Math.cos(angle), r * Math.sin(angle)], valid: true}); - } - }); - return samples; - }; - - // Unit ray of a normalized visual coordinate, in the image frame: x right, y down, z forward. - const ray = (s, fov) => { - const e = Math.hypot(s[0], s[1]) * (fov / 2) * DEG; - const theta = Math.atan2(s[1], s[0]); - return [Math.sin(e) * Math.cos(theta), -Math.sin(e) * Math.sin(theta), Math.cos(e)]; - }; - - // Pan-then-tilt gaze rotation (row-major), as isaaclab_fovi's gaze kernels: positive tilt looks up, pan left. - const gazeRotation = (tilt, pan) => { - const x = -Math.cos(tilt * DEG) * Math.sin(pan * DEG); - const y = -Math.sin(tilt * DEG); - const z = Math.cos(tilt * DEG) * Math.cos(pan * DEG); - const pitch = Math.atan2(x, z); - const roll = Math.atan2(-y, Math.hypot(x, z)); - const [cp, sp, cr, sr] = [Math.cos(pitch), Math.sin(pitch), Math.cos(roll), Math.sin(roll)]; - return [[cp, sp * sr, sp * cr], [0, cr, -sr], [-sp, cp * sr, cp * cr]]; - }; - - const rotate = (m, v) => m.map((row) => row[0] * v[0] + row[1] * v[1] + row[2] * v[2]); - - // An ideal square camera whose field of view spans its side; the retina spans the same angle. - const SIDE = 1000; - const cameraModels = { - fisheye: { - label: "Equidistant fisheye", - fov: {min: 40, max: 240, initial: 180}, - focal: (fov) => SIDE / 2 / ((fov / 2) * DEG), - project(d, f) { - const lateral = Math.hypot(d[0], d[1]); - const theta = Math.atan2(lateral, d[2]); - if (lateral < 1e-12) { - return [SIDE / 2, SIDE / 2]; - } - return [SIDE / 2 + (f * theta * d[0]) / lateral, SIDE / 2 + (f * theta * d[1]) / lateral]; - }, - unproject(p, f) { - const dx = p[0] - SIDE / 2; - const dy = p[1] - SIDE / 2; - const theta = Math.hypot(dx, dy) / f; - const lateral = Math.hypot(dx, dy) || 1; - return [(Math.sin(theta) * dx) / lateral, (Math.sin(theta) * dy) / lateral, Math.cos(theta)]; - }, - }, - pinhole: { - label: "Pinhole", - fov: {min: 20, max: 170, initial: 80}, - focal: (fov) => SIDE / 2 / Math.tan((fov / 2) * DEG), - project(d, f) { - if (d[2] <= 1e-9) { - return null; - } - return [SIDE / 2 + (f * d[0]) / d[2], SIDE / 2 + (f * d[1]) / d[2]]; - }, - unproject(p, f) { - return normalize([(p[0] - SIDE / 2) / f, (p[1] - SIDE / 2) / f, 1]); - }, - }, - }; - - const normalize = (v) => { - const n = Math.hypot(v[0], v[1], v[2]); - return [v[0] / n, v[1] / n, v[2] / n]; - }; - - const inImage = (p) => p !== null && p[0] >= 0 && p[0] < SIDE && p[1] >= 0 && p[1] < SIDE; - - const imageBorder = (model, f) => { - const points = []; - const corners = [[0, 0], [SIDE, 0], [SIDE, SIDE], [0, SIDE], [0, 0]]; - for (let k = 0; k < 4; k++) { - for (let t = 0; t < 40; t++) { - const [a, b] = [corners[k], corners[k + 1]]; - points.push(model.unproject([a[0] + ((b[0] - a[0]) * t) / 40, a[1] + ((b[1] - a[1]) * t) / 40], f)); - } - } - points.push(points[0]); - return points; - }; - - // Spacing of neighbouring samples [deg] at the fixation and at the edge of the field. - const spacing = (style, fov, a, res) => { - const half = fov / 2; - if (style === "isotropic") { - const step = (Math.log(half + a) - Math.log(a)) / Math.max(res - 1, 1); - return [a * (Math.exp(step) - 1), (half + a) * (1 - Math.exp(-step))]; - } - const rate = Math.log(1 + half / a) * (2 / res); - return [a * rate, (half + a) * rate]; - }; - - // -- Drawing helpers --------------------------------------------------------------------------------------------- - - const palette = (element) => { - const style = getComputedStyle(element); - const get = (name, fallback) => style.getPropertyValue(name).trim() || fallback; - return { - ink: get("--fovi-ink", "#1f2a37"), - muted: get("--fovi-muted", "#8a96a8"), - faint: get("--fovi-faint", "#d7dee8"), - surface: get("--fovi-surface", "#ffffff"), - accent: get("--fovi-accent", "#2458d3"), - camera: get("--fovi-camera", "#167d72"), - highlight: get("--fovi-highlight", "#d47b00"), - body: get("--fovi-body", "#29364b"), - }; - }; - - const fitCanvas = (canvas) => { - const box = canvas.getBoundingClientRect(); - const ratio = Math.min(window.devicePixelRatio || 1, 2); - canvas.width = Math.max(1, Math.round(box.width * ratio)); - canvas.height = Math.max(1, Math.round(box.height * ratio)); - const ctx = canvas.getContext("2d"); - ctx.setTransform(ratio, 0, 0, ratio, 0, 0); - return {ctx, w: box.width, h: box.height}; - }; - - const polyline = (ctx, points, color, width, dash = []) => { - if (points.length < 2) { - return; - } - ctx.beginPath(); - ctx.setLineDash(dash); - ctx.strokeStyle = color; - ctx.lineWidth = width; - points.forEach((p, k) => (k === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]))); - ctx.stroke(); - ctx.setLineDash([]); - }; - - const dots = (ctx, points, color, radius, alpha = 1) => { - ctx.globalAlpha = alpha; - ctx.fillStyle = color; - ctx.beginPath(); - for (const p of points) { - ctx.moveTo(p[0] + radius, p[1]); - ctx.arc(p[0], p[1], radius, 0, TAU); - } - ctx.fill(); - ctx.globalAlpha = 1; - }; - - // Orbiting orthographic view of the viewing sphere; the camera sits at its centre looking along +z. - const sphereProjector = (view, w, h) => { - const scale = Math.min(w, h) * 0.4; - const [cy, sy, cp, sp] = [Math.cos(view.yaw), Math.sin(view.yaw), Math.cos(view.pitch), Math.sin(view.pitch)]; - return ([x, y, z]) => { - const rx = cy * x - sy * z; - const rz = sy * x + cy * z; - const ry = cp * y - sp * rz; - const depth = sp * y + cp * rz; - return [w / 2 + rx * scale, h / 2 + ry * scale, depth]; - }; - }; - - const bindOrbit = (canvas, view, redraw, initial) => { - let last = null; - canvas.addEventListener("pointerdown", (event) => { - last = [event.clientX, event.clientY]; - canvas.setPointerCapture(event.pointerId); - }); - canvas.addEventListener("pointermove", (event) => { - if (!last) { - return; - } - view.yaw += (event.clientX - last[0]) * 0.01; - view.pitch = Math.max(-1.5, Math.min(1.5, view.pitch - (event.clientY - last[1]) * 0.01)); - last = [event.clientX, event.clientY]; - redraw(); - }); - for (const name of ["pointerup", "pointercancel"]) { - canvas.addEventListener(name, () => (last = null)); - } - canvas.addEventListener("dblclick", () => { - Object.assign(view, initial); - redraw(); - }); - }; - - const drawSphere = (canvas, view, scene, colors) => { - const {ctx, w, h} = fitCanvas(canvas); - const project = sphereProjector(view, w, h); - // The viewer looks from behind the camera, so smaller depths are nearer; nothing is opaque but the camera. - const segment = (points, color, width) => polyline(ctx, points.map(project), color, width); - const circle = (polar) => Array.from({length: 121}, (_, k) => { - const az = (k * TAU) / 120; - return [Math.sin(polar) * Math.cos(az), Math.sin(polar) * Math.sin(az), Math.cos(polar)]; - }); - for (const polar of [30, 60, 90, 120, 150]) { - segment(circle(polar * DEG), colors.faint, polar === 90 ? 1.2 : 0.7); - } - for (let k = 0; k < 12; k++) { - const az = (k * TAU) / 12; - segment(Array.from({length: 61}, (_, t) => { - const polar = (t * Math.PI) / 60; - return [Math.sin(polar) * Math.cos(az), Math.sin(polar) * Math.sin(az), Math.cos(polar)]; - }), colors.faint, 0.7); - } - segment(scene.border, colors.camera, 2); - const radius = scene.dotRadius; - dots(ctx, scene.rays.filter((r) => !r.valid).map((r) => project(r.dir)), colors.muted, radius, 0.5); - dots(ctx, scene.rays.filter((r) => r.valid).map((r) => project(r.dir)), colors.accent, radius, 0.7); - for (const line of scene.lines) { - segment(line, colors.accent, 0.8); - } - segment(scene.retinaEdge, colors.accent, 1.6); - const gaze = project(scene.gaze); - dots(ctx, [gaze], colors.surface, 4.5); - ctx.beginPath(); - ctx.arc(gaze[0], gaze[1], 4.5, 0, TAU); - ctx.strokeStyle = colors.accent; - ctx.lineWidth = 2; - ctx.stroke(); - // Camera housing at the centre. - const body = [[-0.09, -0.06, -0.22], [0.09, -0.06, -0.22], [0.09, 0.06, -0.22], [-0.09, 0.06, -0.22], - [-0.09, -0.06, -0.06], [0.09, -0.06, -0.06], [0.09, 0.06, -0.06], [-0.09, 0.06, -0.06]]; - const faces = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]] - .map((face) => face.map((k) => project(body[k]))) - .sort((a, b) => b.reduce((s, p) => s + p[2], 0) - a.reduce((s, p) => s + p[2], 0)); - for (const face of faces) { - ctx.beginPath(); - face.forEach((p, k) => (k === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]))); - ctx.closePath(); - ctx.fillStyle = colors.body; - ctx.fill(); - ctx.strokeStyle = colors.faint; - ctx.lineWidth = 0.6; - ctx.stroke(); - } - }; - - // -- Sampling viewer --------------------------------------------------------------------------------------------- - - const control = (label, input, output) => { - const wrapper = document.createElement("label"); - wrapper.className = "fovi-control"; - const name = document.createElement("span"); - name.className = "fovi-control-name"; - name.innerHTML = label; - wrapper.append(name, input); - if (output) { - wrapper.append(output); - } - return wrapper; - }; - - const slider = (min, max, step, value) => { - const input = document.createElement("input"); - Object.assign(input, {type: "range", min, max, step, value}); - return input; - }; - - const select = (options, value) => { - const input = document.createElement("select"); - for (const [key, text] of options) { - input.append(new Option(text, key)); - } - input.value = value; - return input; - }; - - const readout = () => { - const output = document.createElement("output"); - output.className = "fovi-control-value"; - return output; - }; - - const formatA = (a) => (a >= 100 ? a.toFixed(0) : a >= 10 ? a.toFixed(1) : a >= 1 ? a.toFixed(2) : a.toFixed(3)); - - const initSamplingViewer = (root) => { - const defaults = {style: "warped_cartesian_as_grid", logA: Math.log10(0.591), res: 32, tilt: 0, pan: 0}; - const state = {...defaults}; - const inputs = { - style: select([["warped_cartesian_as_grid", "warped_cartesian_as_grid"], ["isotropic", "isotropic"]], state.style), - logA: slider(-2, 3, 0.01, state.logA), - res: slider(8, 128, 1, state.res), - tilt: slider(-60, 60, 1, state.tilt), - pan: slider(-60, 60, 1, state.pan), - }; - const outputs = {logA: readout(), res: readout(), tilt: readout(), pan: readout()}; - const controls = document.createElement("div"); - controls.className = "fovi-controls"; - controls.append( - control("foveated_style", inputs.style), - control("cmf_a_deg", inputs.logA, outputs.logA), - control("foveated_res", inputs.res, outputs.res), - control("Gaze tilt", inputs.tilt, outputs.tilt), - control("Gaze pan", inputs.pan, outputs.pan), - ); - const reset = document.createElement("button"); - reset.type = "button"; - reset.className = "fovi-reset"; - reset.textContent = "Reset"; - controls.append(reset); - const summary = document.createElement("p"); - summary.className = "fovi-summary"; - summary.setAttribute("aria-live", "polite"); - const panels = document.createElement("div"); - panels.className = "fovi-panels fovi-panels-stacked"; - const initialView = {yaw: -0.6, pitch: 0.35}; - const cameras = Object.entries(cameraModels).map(([key, model]) => { - const panel = document.createElement("figure"); - panel.className = "fovi-panel"; - const title = document.createElement("figcaption"); - title.textContent = model.label; - const sphere = document.createElement("canvas"); - sphere.className = "fovi-canvas fovi-sphere"; - sphere.setAttribute("aria-label", `${model.label}: the retina's rays on the viewing sphere. Drag to rotate; double-click to reset.`); - const image = document.createElement("canvas"); - image.className = "fovi-canvas fovi-image"; - image.setAttribute("aria-label", `${model.label}: where the retina's samples land in the camera image.`); - const labels = document.createElement("div"); - labels.className = "fovi-panel-labels"; - labels.innerHTML = "Viewing sphere (drag to rotate)Camera image"; - const views = document.createElement("div"); - views.className = "fovi-views"; - views.append(sphere, image); - const note = document.createElement("p"); - note.className = "fovi-panel-note"; - // Each camera has its own field of view; the retina spans it. - const fovInput = slider(model.fov.min, model.fov.max, 1, model.fov.initial); - const fovOutput = readout(); - const fovControl = control("Field of view", fovInput, fovOutput); - fovControl.classList.add("fovi-panel-control"); - panel.append(title, fovControl, views, labels, note); - panels.append(panel); - const view = {...initialView}; - const camera = {key, model, sphere, image, note, view, fov: model.fov.initial, fovInput, fovOutput}; - fovInput.addEventListener("input", () => { - camera.fov = Number(fovInput.value); - sync(); - }); - return camera; - }); - const legend = document.createElement("p"); - legend.className = "fovi-legend"; - legend.innerHTML = 'retinal sample' - + 'outside the camera image (masked with mask_to_sensor_fov)' - + 'camera image border'; - root.append(controls, summary, panels, legend); - - const samplesCache = new Map(); - const samplesFor = (fov) => { - const a = Math.pow(10, state.logA); - const key = `${state.style}/${a}/${state.res}/${fov}`; - if (samplesCache.has(key)) { - return samplesCache.get(key); - } - let samples; - let description; - let resolution = state.res; - if (state.style === "isotropic") { - resolution = matchedIsotropicRes(fov, a, state.res * state.res); - samples = isotropicSamples(fov, a, resolution); - description = `${samples.length.toLocaleString("en-US")} samples on ${resolution} rings, published as (num_envs, ${samples.length}, 1, C)`; - } else { - samples = warpedGrid(fov, a, state.res); - const valid = samples.filter((s) => s.valid).length; - description = `${state.res} × ${state.res} grid, ${valid.toLocaleString("en-US")} samples inside the circular field, published as (num_envs, ${state.res}, ${state.res}, C)`; - } - const [centre, edge] = spacing(state.style, fov, a, resolution); - const entry = {samples: samples.filter((s) => s.valid), all: samples, description, centre, edge}; - samplesCache.set(key, entry); - if (samplesCache.size > 4) { - samplesCache.delete(samplesCache.keys().next().value); // keep the recent settings of both cameras - } - return entry; - }; - - // The retina's rays, outline and warped-grid lattice lines (every few rows and columns) for a field of view. - const retinaFor = (fov, rotation) => { - const data = samplesFor(fov); - const rays = data.samples.map((s) => rotate(rotation, ray(s.s, fov))); - const edge = Array.from({length: 181}, (_, k) => rotate(rotation, ray([Math.cos((k * TAU) / 180), Math.sin((k * TAU) / 180)], fov))); - const lines = []; - if (state.style !== "isotropic") { - const every = Math.max(1, Math.round(state.res / 16)); - const index = new Map(data.all.map((s) => [s.i * state.res + s.j, s])); - for (let fixed = Math.floor(every / 2); fixed < state.res; fixed += every) { - for (const transpose of [false, true]) { - let run = []; - for (let moving = 0; moving < state.res; moving++) { - const s = index.get(transpose ? moving * state.res + fixed : fixed * state.res + moving); - if (s && s.valid) { - run.push(rotate(rotation, ray(s.s, fov))); - } else if (run.length) { - lines.push(run); - run = []; - } - } - if (run.length) { - lines.push(run); - } - } - } - } - return {data, rays, edge, lines}; - }; - - const redraw = () => { - const colors = palette(root); - const rotation = gazeRotation(state.tilt, state.pan); - const gaze = rotate(rotation, [0, 0, 1]); - summary.textContent = "Each camera's retina spans that camera's field of view; move its slider to compare fields."; - for (const camera of cameras) { - const {data, rays, edge, lines} = retinaFor(camera.fov, rotation); - const count = rays.length; - const dotRadius = Math.max(0.6, Math.min(2.4, 70 / Math.sqrt(count))); - const f = camera.model.focal(camera.fov); - const projected = rays.map((d) => camera.model.project(d, f)); - const valid = projected.map(inImage); - const inside = valid.filter(Boolean).length; - drawSphere(camera.sphere, camera.view, { - rays: rays.map((dir, k) => ({dir, valid: valid[k]})), - border: imageBorder(camera.model, f), - lines, - retinaEdge: edge, - gaze, - dotRadius, - }, colors); - drawImagePlane(camera.image, projected, valid, edge.map((d) => camera.model.project(d, f)), camera.model.project(gaze, f), dotRadius, colors); - camera.note.innerHTML = `${data.description}. Sample spacing: ${data.centre.toPrecision(2)}° at the fixation, ` - + `${data.edge.toPrecision(2)}° at the edge of the ${camera.fov}° field. ` - + `${inside.toLocaleString("en-US")} of ${count.toLocaleString("en-US")} samples inside the image (${((100 * inside) / count).toFixed(0)}%).`; - } - }; - - const drawImagePlane = (canvas, projected, valid, edge, gaze, radius, colors) => { - const {ctx, w, h} = fitCanvas(canvas); - const margin = 0.18; - const scale = Math.min(w, h) / (SIDE * (1 + 2 * margin)); - const ox = (w - SIDE * scale) / 2; - const oy = (h - SIDE * scale) / 2; - const map = (p) => [ox + p[0] * scale, oy + p[1] * scale]; - ctx.fillStyle = colors.surface; - ctx.fillRect(ox, oy, SIDE * scale, SIDE * scale); - ctx.strokeStyle = colors.camera; - ctx.lineWidth = 2; - ctx.strokeRect(ox, oy, SIDE * scale, SIDE * scale); - polyline(ctx, [map([SIDE / 2, 0]), map([SIDE / 2, SIDE])], colors.faint, 0.7); - polyline(ctx, [map([0, SIDE / 2]), map([SIDE, SIDE / 2])], colors.faint, 0.7); - const visible = (p) => p !== null && p[0] > -SIDE && p[0] < 2 * SIDE && p[1] > -SIDE && p[1] < 2 * SIDE; - ctx.save(); - ctx.beginPath(); - ctx.rect(0, 0, w, h); - ctx.clip(); - dots(ctx, projected.filter((p, k) => !valid[k] && visible(p)).map(map), colors.muted, radius, 0.5); - dots(ctx, projected.filter((p, k) => valid[k]).map(map), colors.accent, radius, 0.75); - const edgeRuns = []; - let run = []; - for (const p of edge) { - if (visible(p)) { - run.push(map(p)); - } else if (run.length) { - edgeRuns.push(run); - run = []; - } - } - edgeRuns.push(run); - for (const r of edgeRuns) { - polyline(ctx, r, colors.accent, 1.4); - } - if (gaze && visible(gaze)) { - const g = map(gaze); - ctx.beginPath(); - ctx.arc(g[0], g[1], 4.5, 0, TAU); - ctx.fillStyle = colors.surface; - ctx.fill(); - ctx.strokeStyle = colors.accent; - ctx.lineWidth = 2; - ctx.stroke(); - } - ctx.restore(); - }; - - const sync = () => { - const a = Math.pow(10, state.logA); - outputs.logA.textContent = `${formatA(a)}°`; - outputs.res.textContent = state.res; - for (const camera of cameras) { - camera.fovOutput.textContent = `${camera.fov}°`; - } - outputs.tilt.textContent = `${state.tilt}°`; - outputs.pan.textContent = `${state.pan}°`; - redraw(); - }; - for (const [name, input] of Object.entries(inputs)) { - input.addEventListener("input", () => { - state[name] = name === "style" ? input.value : Number(input.value); - sync(); - }); - } - reset.addEventListener("click", () => { - Object.assign(state, defaults); - for (const [name, input] of Object.entries(inputs)) { - input.value = state[name]; - } - for (const camera of cameras) { - Object.assign(camera.view, initialView); - camera.fov = camera.model.fov.initial; - camera.fovInput.value = camera.fov; - } - sync(); - }); - for (const camera of cameras) { - bindOrbit(camera.sphere, camera.view, redraw, initialView); - } - new ResizeObserver(() => redraw()).observe(panels); - sync(); - }; - - // -- Pooling viewer ---------------------------------------------------------------------------------------------- - - // Upright layout of a canonical warped grid (fovi's sampling_as_grid): row = res - 1 - j, column = i. - // Pooling windows follow fovi's GridPoolingLayer: stride = resolution multiple, SAME-style padding. - const poolingWindow = (lowRes, mult, side, row, col) => { - const stride = mult; - const before = Math.floor((side - stride) / 2); - const cells = []; - for (let dr = 0; dr < side; dr++) { - for (let dc = 0; dc < side; dc++) { - const r = row * stride - before + dr; - const c = col * stride - before + dc; - if (r >= 0 && r < lowRes * mult && c >= 0 && c < lowRes * mult) { - cells.push([r, c]); - } - } - } - return cells; - }; - - const initPoolingViewer = (root) => { - const FOV = Number(root.dataset.fov || 90); - const A = Number(root.dataset.cmfA || 2); - const LOW = Number(root.dataset.res || 16); - const defaults = {style: "warped_cartesian_as_grid", mult: 2, side: 2, row: 8, col: 11, k: 4, space: "geodesic", unit: 120}; - const state = {...defaults}; - const inputs = { - style: select([["warped_cartesian_as_grid", "warped_cartesian_as_grid"], ["isotropic", "isotropic"]], state.style), - mult: select([["2", "2"], ["3", "3"], ["4", "4"]], String(state.mult)), - side: slider(1, 9, 1, state.side), - row: slider(0, LOW - 1, 1, state.row), - col: slider(0, LOW - 1, 1, state.col), - k: slider(1, 32, 1, state.k), - space: select([["geodesic", "geodesic (default)"], ["visual", "visual field (False)"]], state.space), - unit: slider(0, 1, 1, state.unit), - }; - const outputs = {side: readout(), row: readout(), col: readout(), k: readout(), unit: readout()}; - const controls = document.createElement("div"); - controls.className = "fovi-controls"; - const gridControls = [ - control("Window side (pool_k = side²)", inputs.side, outputs.side), - control("Pooled sample row", inputs.row, outputs.row), - control("Pooled sample column", inputs.col, outputs.col), - ]; - const isotropicControls = [ - control("pool_k (neighbours)", inputs.k, outputs.k), - control("pool_sample_cortex", inputs.space), - control("Pooled sample", inputs.unit, outputs.unit), - ]; - controls.append(control("foveated_style", inputs.style), control("pool_res_mult", inputs.mult), ...gridControls, ...isotropicControls); - const reset = document.createElement("button"); - reset.type = "button"; - reset.className = "fovi-reset"; - reset.textContent = "Reset"; - controls.append(reset); - const summary = document.createElement("p"); - summary.className = "fovi-summary"; - summary.setAttribute("aria-live", "polite"); - const panels = document.createElement("div"); - panels.className = "fovi-panels fovi-panels-three"; - const makePanel = (title, label) => { - const panel = document.createElement("figure"); - panel.className = "fovi-panel"; - const caption = document.createElement("figcaption"); - caption.textContent = title; - const canvas = document.createElement("canvas"); - canvas.className = "fovi-canvas fovi-square"; - canvas.setAttribute("aria-label", label); - panel.append(caption, canvas); - panels.append(panel); - return {panel, canvas}; - }; - const nativeView = makePanel("Published grid (click a sample)", "The pooled grid and its photoreceptor grid in the published image layout. Click a pooled sample to select it."); - const fieldView = makePanel("Visual field (click a sample)", "Photoreceptor and pooled samples by visual angle. Click a pooled sample to select it."); - const zoomView = makePanel("Around the selected sample", "The selected pooled sample's neighbourhood, enlarged."); - const legend = document.createElement("p"); - legend.className = "fovi-legend"; - legend.innerHTML = 'photoreceptor' - + 'pooled into the selected sample' - + 'pooled sample' - + `Fixed: ${FOV}° field, cmf_a_deg=${A}, foveated_res=${LOW}.`; - root.append(controls, summary, panels, legend); - - // fovi's pooling neighbourhoods for the isotropic retina, exported with the camera's own helpers. - let isotropicTables = null; - if (TABLES_URL) { - fetch(TABLES_URL) - .then((response) => (response.ok ? response.json() : Promise.reject(new Error(response.statusText)))) - .then((data) => { - if (data.fov !== FOV || data.cmfA !== A || data.res !== LOW) { - throw new Error("the exported tables describe another retina"); - } - isotropicTables = data; - if (state.style === "isotropic") { - sync(); - } - }) - .catch((error) => { - isotropicTables = {error: String(error.message || error)}; - if (state.style === "isotropic") { - sync(); - } - }); - } - - // Grid retina: samples keyed by their upright (row, column) in the published image. - const gridLayout = (res) => { - const samples = warpedGrid(FOV, A, res).map((s) => ({...s, row: res - 1 - s.j, col: s.i})); - return {samples, at: new Map(samples.map((s) => [`${s.row},${s.col}`, s]))}; - }; - const layouts = new Map(); - const layoutFor = () => { - const key = `${state.style}/${state.mult}`; - if (layouts.has(key)) { - return layouts.get(key); - } - let layout; - if (state.style === "isotropic") { - const rings = matchedIsotropicRes(FOV, A, LOW * LOW); - const highRings = Math.round(state.mult * rings); - layout = { - rings, - highRings, - low: isotropicSamples(FOV, A, rings), - high: isotropicSamples(FOV, A, highRings), - }; - } else { - layout = {low: gridLayout(LOW), high: gridLayout(LOW * state.mult)}; - } - layouts.set(key, layout); - return layout; - }; - - // The selected pooled sample, the photoreceptors it pools, and a description, for the current style. - const selection = (layout) => { - if (state.style !== "isotropic") { - const unit = layout.low.at.get(`${state.row},${state.col}`); - const cells = poolingWindow(LOW, state.mult, state.side, state.row, state.col); - const members = cells.map(([r, c]) => layout.high.at.get(`${r},${c}`)).filter((s) => s.valid); - const k = state.side * state.side; - const text = `pool_k=${k} (window side ${state.side}, stride ${state.mult}); the photoreceptor grid is ` - + `${LOW * state.mult} × ${LOW * state.mult}` - + (k < state.mult * state.mult ? "; a window smaller than the stride skips photoreceptors." : "."); - return {unit, members, valid: unit.valid && members.length > 0, text, label: `(${state.row}, ${state.col})`}; - } - const unit = layout.low[state.unit]; - const table = isotropicTable(layout); - if (!table) { - return {unit, members: [], valid: false, pending: true, text: "", label: `${state.unit}`}; - } - const members = table.slice(0, state.k).filter((index) => index >= 0).map((index) => layout.high[index]); - const text = `pool_k=${state.k} nearest photoreceptors ${state.space === "geodesic" ? "along the cortex" : "in the visual field"}; ` - + `${layout.high.length.toLocaleString("en-US")} photoreceptors on ${layout.highRings} rings pool into ${layout.low.length} samples on ${layout.rings} rings` - + ` (default pool_k ${Math.round(layout.high.length / layout.low.length)}).`; - return {unit, members, valid: members.length > 0, text, label: `${state.unit}`}; - }; - - // The selected sample's neighbours, nearest first, from fovi's table for the chosen space. - const isotropicTable = (layout) => { - const entry = isotropicTables && !isotropicTables.error && isotropicTables.mult[String(state.mult)]; - if (!entry) { - return null; - } - if (entry.count !== layout.high.length || isotropicTables.count !== layout.low.length) { - isotropicTables = {error: "the exported tables do not match this retina"}; - return null; - } - return entry[state.space].slice(state.unit * entry.kMax, (state.unit + 1) * entry.kMax); - }; - - const fieldTransform = (w, h, centre, radius) => { - const scale = (Math.min(w, h) / 2 - 8) / radius; - return (s) => [w / 2 + (s[0] - centre[0]) * scale, h / 2 - (s[1] - centre[1]) * scale]; - }; - - const redraw = () => { - const colors = palette(root); - const layout = layoutFor(); - const isotropic = state.style === "isotropic"; - const lowSamples = isotropic ? layout.low : layout.low.samples; - const highSamples = isotropic ? layout.high : layout.high.samples; - const chosen = selection(layout); - const members = new Set(chosen.members); - const {unit} = chosen; - nativeView.panel.hidden = isotropic; - // Published-grid view: photoreceptor cells, pooled cell borders, and the window. - if (!isotropic) { - const highRes = LOW * state.mult; - const {ctx, w, h} = fitCanvas(nativeView.canvas); - const size = Math.min(w, h) - 8; - const ox = (w - size) / 2; - const oy = (h - size) / 2; - const cell = size / highRes; - const windowCells = new Set(poolingWindow(LOW, state.mult, state.side, state.row, state.col).map(([r, c]) => `${r},${c}`)); - for (const s of highSamples) { - const member = windowCells.has(`${s.row},${s.col}`); - ctx.fillStyle = member ? colors.highlight : s.valid ? colors.faint : colors.surface; - ctx.globalAlpha = member && !s.valid ? 0.35 : 1; - ctx.fillRect(ox + s.col * cell + 0.5, oy + s.row * cell + 0.5, Math.max(cell - 1, 0.5), Math.max(cell - 1, 0.5)); - } - ctx.globalAlpha = 1; - for (let k = 0; k <= LOW; k++) { - polyline(ctx, [[ox + (k * size) / LOW, oy], [ox + (k * size) / LOW, oy + size]], colors.muted, 0.6); - polyline(ctx, [[ox, oy + (k * size) / LOW], [ox + size, oy + (k * size) / LOW]], colors.muted, 0.6); - } - ctx.strokeStyle = colors.accent; - ctx.lineWidth = 2.4; - ctx.strokeRect(ox + (state.col * size) / LOW, oy + (state.row * size) / LOW, size / LOW, size / LOW); - nativeView.canvas.onclick = (event) => { - const box = nativeView.canvas.getBoundingClientRect(); - const col = Math.floor(((event.clientX - box.left - ox) / size) * LOW); - const row = Math.floor(((event.clientY - box.top - oy) / size) * LOW); - if (row >= 0 && row < LOW && col >= 0 && col < LOW) { - choose({row, col}); - } - }; - } - const zoomRegion = () => { - const points = chosen.members.map((s) => s.s); - points.push(unit.s); - const xs = points.map((p) => p[0]); - const ys = points.map((p) => p[1]); - const centre = [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2]; - const extent = Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys), 0.002); - return [centre, extent * 1.1]; - }; - // Visual-field views: the whole retina, and the selected sample's neighbourhood. - const drawField = (canvas, centre, radius, showZoomBox) => { - const {ctx, w, h} = fitCanvas(canvas); - const map = fieldTransform(w, h, centre, radius); - const scale = (Math.min(w, h) / 2 - 8) / radius; - const dotHigh = Math.max(0.7, Math.min(3, scale * 0.004 * Math.sqrt(1024 / highSamples.length) * 6)); - const highPoints = highSamples.filter((s) => s.valid); - dots(ctx, highPoints.filter((s) => !members.has(s)).map((s) => map(s.s)), colors.muted, dotHigh, 0.55); - dots(ctx, highPoints.filter((s) => members.has(s)).map((s) => map(s.s)), colors.highlight, dotHigh * 1.4, 1); - dots(ctx, lowSamples.filter((s) => s.valid).map((s) => map(s.s)), colors.accent, dotHigh * 1.2, 0.9); - const u = map(unit.s); - ctx.beginPath(); - ctx.arc(u[0], u[1], dotHigh * 1.2 + 4, 0, TAU); - ctx.strokeStyle = colors.accent; - ctx.lineWidth = 2; - ctx.stroke(); - polyline(ctx, Array.from({length: 181}, (_, k) => map([Math.cos((k * TAU) / 180), Math.sin((k * TAU) / 180)])), colors.camera, 1.2); - if (showZoomBox) { - const [zc, zr] = zoomRegion(); - const corner = map([zc[0] - zr, zc[1] + zr]); - ctx.strokeStyle = colors.ink; - ctx.setLineDash([3, 3]); - ctx.lineWidth = 1; - ctx.strokeRect(corner[0], corner[1], 2 * zr * scale, 2 * zr * scale); - ctx.setLineDash([]); - } - return map; - }; - const map = drawField(fieldView.canvas, [0, 0], 1, true); - fieldView.canvas.onclick = (event) => { - const box = fieldView.canvas.getBoundingClientRect(); - const x = event.clientX - box.left; - const y = event.clientY - box.top; - let best = null; - lowSamples.forEach((s, index) => { - if (!s.valid) { - return; - } - const p = map(s.s); - const d = Math.hypot(p[0] - x, p[1] - y); - if (!best || d < best.d) { - best = {d, s, index}; - } - }); - if (best) { - choose(isotropic ? {unit: best.index} : {row: best.s.row, col: best.s.col}); - } - }; - const [zc, zr] = zoomRegion(); - drawField(zoomView.canvas, zc, zr, false); - const ecc = Math.hypot(unit.s[0], unit.s[1]) * (FOV / 2); - const span = chosen.members.length - ? Math.max(...chosen.members.map((s) => Math.hypot(s.s[0] - unit.s[0], s.s[1] - unit.s[1]))) * (FOV / 2) * 2 - : 0; - if (chosen.pending) { - const reason = isotropicTables && isotropicTables.error ? `could not be loaded (${isotropicTables.error})` : "are loading"; - summary.innerHTML = `fovi's pooling neighbourhoods ${reason}.`; - return; - } - summary.innerHTML = `Pooled sample ${chosen.label} at ${ecc.toFixed(2)}° eccentricity` - + (chosen.valid - ? ` averages ${chosen.members.length} photoreceptors spanning about ${span.toPrecision(2)}°. ` - : " lies outside the retina, so the camera publishes zero there. ") - + chosen.text; - }; - - const choose = (selected) => { - Object.assign(state, selected); - for (const name of Object.keys(selected)) { - inputs[name].value = state[name]; - } - sync(); - }; - - const sync = () => { - const isotropic = state.style === "isotropic"; - for (const element of gridControls) { - element.hidden = isotropic; - } - for (const element of isotropicControls) { - element.hidden = !isotropic; - } - if (isotropic) { - const layout = layoutFor(); - inputs.unit.max = layout.low.length - 1; - state.unit = Math.min(state.unit, layout.low.length - 1); - inputs.unit.value = state.unit; - inputs.k.max = 2 * state.mult * state.mult; - state.k = Math.min(state.k, Number(inputs.k.max)); - inputs.k.value = state.k; - } - outputs.side.textContent = `${state.side} (pool_k=${state.side * state.side})`; - outputs.row.textContent = state.row; - outputs.col.textContent = state.col; - outputs.k.textContent = state.k; - outputs.unit.textContent = state.unit; - redraw(); - }; - inputs.style.addEventListener("input", () => { - state.style = inputs.style.value; - sync(); - }); - inputs.space.addEventListener("input", () => { - state.space = inputs.space.value; - sync(); - }); - inputs.mult.addEventListener("input", () => { - // Keep the default neighbourhood when it was in use: pool_res_mult squared photoreceptors. - const defaultSide = state.side === state.mult; - const defaultK = state.k === state.mult * state.mult; - state.mult = Number(inputs.mult.value); - if (defaultSide) { - state.side = state.mult; - inputs.side.value = state.side; - } - if (defaultK) { - state.k = state.mult * state.mult; - } - sync(); - }); - for (const name of ["side", "row", "col", "k", "unit"]) { - inputs[name].addEventListener("input", () => { - state[name] = Number(inputs[name].value); - sync(); - }); - } - reset.addEventListener("click", () => { - Object.assign(state, defaults); - for (const [name, input] of Object.entries(inputs)) { - input.value = state[name]; - } - sync(); - }); - new ResizeObserver(() => redraw()).observe(panels); - sync(); - }; - - const initialize = () => { - document.querySelectorAll("[data-fovi-sampling-viewer]").forEach(initSamplingViewer); - document.querySelectorAll("[data-fovi-pooling-viewer]").forEach(initPoolingViewer); - }; - - // Exposed for the documentation's geometry checks. - window.FoviViewerGeometry = {warpedGrid, isotropicRings, matchedIsotropicRes, isotropicSamples, ray, gazeRotation, poolingWindow}; - - if (typeof document !== "undefined") { - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", initialize); - } else { - initialize(); - } - } -})(); diff --git a/docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg b/docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg deleted file mode 100644 index 40d6786c3d163c6288466ef92c1c2a22eededbca..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 115472 zcm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RzdcsD4HX1-QIzkpuY-+ypV^vV1s1bA+@mC zV%?h#{A!bMTtUXW+W;49b?FO15o}oZIw-8fDXP*L>~mBO{8jynJB1y3s!^{6E+4{o zgm@}>s=I#%r*cu=JcVZl)E8g4AX);ZGDu3|2Uj>7SPa!@0;${bT#D7V%y-R}lU;`U z<<?!ZH-PXW@Y!)HGFiyC>fK8p zJ#Feaj$bHOW(Gr?HX=y4G58&+ju_q~^yPuwe+k|P0Dv$`fiKn)f01o?JzJD)XiELk zx(bLel;5(T>I$m`oG5svL@WI2dsBBG2=uU9Q)L9j2?;QDKy@SDdPSdOY~#Ch)NrGg zn-fU>NQwK4sTmUEDbH_WUbu90mhPNI_N8<1wb~o%r&gfi8}(358Vt<`v>yu>3DlO{ zO;v(LAd|zX3+eaE%|6ldsKt~l<95D);U6W+M3!>op*9mz*svouP!+~B!g@9NgH59R z^3B7Le=^-Z705s1rV7GO`Bb!|Tnv2?am_}F9~*mce>Gypx(Q=%rgdGXw*Kn_8xtmT zf$?@ee_ZwWCWisbyP`ZLys%+0Y0H2o72M<;bXPOq@BD9oO5r{lo%u$+^E-FtB)F>1{C{6^;T^q z!iU+sHQyIRj_kk#`Rx=A9drP~WJCKR-{2(@~$-eN}KSFpI_J!bhq#JQU*G;i8 z(FQjUjOfcg8u?hC|D^=jHj49T$(n!tnYU!CPt5_GidLIfviVy<`p9)vxQc68tfL|? l)5ELR)Zb4(bW8mFZ|9`{>FX}2HxBB5!{I@vix2-j_aAAP$(H~C diff --git a/docs/source/_static/overview/sensors/foveated_camera_pooling.jpg b/docs/source/_static/overview/sensors/foveated_camera_pooling.jpg deleted file mode 100644 index d5c0ac8ef1bd3e3899eda804ffdf345a00b62c27..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 68546 zcmbSy1ymi&((c9y?k)-L?gY2swt?UwxVvjYfZ)O1-GjRXcXti$?*2AO&b{|P|6OmL z_hxGK>^)syb=6Eyb#?X3^X&6a0E(2jq&NT!3;+NF?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?JG)Mu;Ibc14?$1&NB|7tZ5C_ch*wrBa7^^4-N}HWB1b+?l_)++A0Uv@=PcThP3kf|b-P zKcB>2{2YItx>pth>9g^kzGQb*lS@_pF;o-VQ@DBt#qttxZ?QWCZ_8v!8WkA4ynw`b ze24_ep2C`$B?Pi3Ig`Fknyf~eX_1bn@7C@ib13Zaj|EBLluZ1^Y!dD;Vy%~9VF>Ul z-Al}2@7p-sYaqfiQP29_zh1M8PkD*F9!@fOZqg3niUgz`BV8l!-L&m^`(I zYJJQ8g24k)QkA{OYMN)rr+_)-c5io({2_q>46+|R{nT2`>8V%IfZX1 z07XwxB0GoS*!|wNn!g1eN>8ZJ2+)IAXUt&g0~~^>Dwy%OR}dvdj0-$iRVs9VFkXDF zJWq>PfSEYBB|oh5pFOn&FwEOLpyEe1DAUpij< zMYFL*BzYMqWiPF;^L&{zGgWPElWfvgB1^VO6D|i - -``foveated_style="isotropic"`` instead places rings of samples evenly in :math:`w`, with as many samples around each -ring as keep neighbours about equally far apart in every direction, as in the -`fovi `__ model. The camera uses as many rings as keep the sample count at most -:math:`N^2`, and publishes the samples as a set, of shape ``(num_envs, num_samples, 1, channels)``; -:attr:`~sensors.FoveatedCameraCfg.isotropic_plotting_type` picks the cortical layout fovi gives them (``"v1like"``, -``"schwartz"`` or ``"warp"``). Sample sets render directly on Newton and are experimental on the RTX renderers, where -crowded samples can share a lens-texture texel. - Configure a foveated camera --------------------------- @@ -133,7 +115,7 @@ samples. foveated_res=64, ) -The camera computes its image size from the retina. With the default grid style it publishes an upright image of +The camera computes its image size from the retina. It publishes an upright image of shape ``(num_envs, foveated_res, foveated_res, channels)`` in :attr:`~isaaclab.sensors.Camera.data`, like any camera, and any output the renderer supports. @@ -183,9 +165,8 @@ at the fixation; the default, 0.591, is an estimate from human data. Neighbourin \Delta r \approx \frac{2}{N} \log\left(1 + \frac{r_{\max}}{a}\right) (r + a) apart at eccentricity :math:`r`. For the demo's 128 × 128 retina over a 90° field, that is 0.04° at the fixation -and 3.1° at the edge, where a uniform 128 × 128 image spaces its pixels 0.7° apart. A value of :math:`a` much larger -than the field of view samples nearly uniformly, which gives a matched non-foveated baseline with the same -resolution, field of view and gaze: +and 3.1° at the edge, compared with a uniform radial angular step of about 0.7°. A value of :math:`a` much larger +than the field of view gives nearly uniform radial angular spacing on the same lattice: .. code-block:: bash @@ -226,82 +207,12 @@ samples, so a policy meant for hardware should train with the mask. lies outside the image. Middle: without the mask, rays render beyond the camera's view. Right: with the mask, those samples are zero. -Pooling -------- - -A single ray per sample aliases where samples are sparse, in the periphery. With -:attr:`~sensors.FoveatedCameraCfg.pool_enabled`, the camera renders a denser photoreceptor grid with the same field -of view and CMF and pools it to the retina, as a retina's ganglion cells pool its photoreceptors. -``pool_res_mult`` sets how much denser the photoreceptor grid is: an integer for grid styles, and any value for -sample-set styles, where :math:`\sqrt{2}` doubles the number of samples. ``pool_mode`` sets how it pools: ``avg``, -``gaussian`` (with ``pool_gauss_sigma``) or ``max``, and for sample-set styles also ``sum``. - -.. figure:: ../../_static/overview/sensors/foveated_camera_pooling.jpg - :target: ../../_static/overview/sensors/foveated_camera_pooling.jpg - :align: center - :figwidth: 100% - :alt: A 32 x 32 retina without pooling and with 2x and 4x photoreceptor pooling, beside a 128 x 128 retina. - - A 32 × 32 retina in the demo scene. Pooling averages 4 or 16 photoreceptors into each sample, which smooths the - edges of the cubes and spheres while the published image keeps its size. - -Grid styles pool each sample over a square window of the photoreceptor grid, ``pool_k`` photoreceptors in all (the -window side squared; by default ``pool_res_mult`` squared), stepping by ``pool_res_mult``. Because the grid follows -the CMF, a window covers a tiny patch of the visual field at the fixation and a wide one in the periphery. -Photoreceptors outside the circular field are left out of the average. Sample-set styles such as ``isotropic`` pool -each sample over its ``pool_k`` nearest photoreceptors instead (by default the ratio of photoreceptors to samples, -about ``pool_res_mult`` squared), by distance along the cortex (``pool_sample_cortex="geodesic"``, the default), -straight-line distance on the cortex (``True``, faster to set up), or distance in the visual field (``False``). - -The viewer shows which photoreceptors each sample pools, for both styles. Its isotropic neighbourhoods are the ones -fovi computes for the camera. - -.. raw:: html - -

- -Segmentation outputs pool by modal label in their own dtype (``pool_int_mode="modal"``), -since averaging would mix labels into ones no object has. With the sensor mask, pooling leaves out the -photoreceptors the physical camera does not see, so a pooled sample at the edge of the camera's image pools only the -ones it sees, and is zero when it sees none. - -Further sampling options are passed to fovi's ``SamplingCoords``, whose -`documentation `__ describes them: ``fov_type`` and ``radius_norm`` set the -region the retina covers. - -Active gaze ------------ - -:mod:`isaaclab_fovi.mdp` holds the manager terms for a policy that moves the gaze: - -* :class:`~mdp.GazeActionCfg`: two actions that move the gaze by up to ``step_size`` field radii per step, within - ``gaze_limit`` of the optical axis. Make it the last action term. With the default ``mount="fixed"`` the teacher - aims from the camera's orientation when the action is created; ``mount="tracked"`` lets the camera ride a moving - body, such as a turning head (Newton and OVRTX). -* :func:`~mdp.gaze_state`: the gaze and its velocity. -* :class:`~mdp.gaze_teacher_labels`: a teacher's gaze action toward a point fixed to an asset, and whether that point - is a valid target. It is a training label, never a policy input. - -The ``IsaacContrib-Cartpole-Camera-Fovi`` task in :mod:`isaaclab_tasks.contrib.active_gaze` puts them together. It is -the stock Cartpole camera task with the camera foveated (a 32-sample retina), two gaze actions, and a teacher that looks -at the pole's tip. Its PPO adds a loss that pulls the gaze actions toward the teacher's, and its action head keeps -the gaze actions' noise fixed: - -.. code-block:: bash - - uv run --extra fovi isaaclab train --rl_library rsl_rl --task IsaacContrib-Cartpole-Camera-Fovi - -The task is registered when the ``fovi`` extra is installed. - -.. figure:: ../../_static/overview/sensors/foveated_camera_active_gaze.jpg - :target: ../../_static/overview/sensors/foveated_camera_active_gaze.jpg - :align: center - :figwidth: 100% - :alt: Cartpole frames with the retina following the pole tip, and the policy's 32 x 32 images. +Gaze actions +------------ - The Cartpole task with the teacher's labels as the gaze actions. Top: the scene from the task's camera, with the - retina's lattice and edge; the gaze follows the pole's tip. Bottom: the 32 × 32 image the policy receives, with - the pole large at the fixation. Black samples lie outside the camera's image. +For a manager-based environment, :class:`~mdp.GazeActionCfg` adds two bounded tilt and pan increments in units of +the retinal field radius. :func:`~mdp.gaze_state` reports the resulting angles and angular velocity. The action +resets the gaze to the optical axis at the start of each episode. Further reading --------------- diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst index 6fe806778a44..afc646183e82 100644 --- a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst +++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst @@ -1,7 +1,4 @@ * Introduced ``isaaclab_fovi`` and the ``fovi`` installation extra, providing :class:`~isaaclab_fovi.sensors.FoveatedCamera`, a foveated camera sensor for the Newton (Warp and OptiX), Isaac RTX and OVRTX renderers whose gaze moves inside a physical camera's field of view. -* Added active-gaze manager terms in :mod:`isaaclab_fovi.mdp`: a gaze action with a fixed or tracked camera mount, - a gaze observation, and teacher gaze labels. -* Added modal-label pooling for segmentation outputs, which keeps their native dtype (``pool_int_mode="modal"``, - the only accepted value); ``pool_mode`` pools the other outputs and accepts only fovi's modes. +* Added bounded tilt and pan actions and a gaze state observation in :mod:`isaaclab_fovi.mdp`. diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi index e78c9a3844e8..71c13e7dd674 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -7,12 +7,7 @@ __all__ = [ "GazeAction", "GazeActionCfg", "gaze_state", - "gaze_teacher_labels", ] -from .gaze import ( - GazeAction, - gaze_state, - gaze_teacher_labels, -) +from .gaze import GazeAction, gaze_state from .gaze_cfg import GazeActionCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index c51f08edfbdb..cc09d371f25c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -3,33 +3,20 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Active gaze for a foveated camera: a gaze action, its observation, and a teacher's gaze labels. - -Gaze angles are (tilt, pan) [deg] from the physical camera's optical axis: positive tilt looks up and positive pan -looks left, as for :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles`. The policy moves and observes the -gaze in field radii, half the retina's field of view. Camera-frame directions follow the ROS (OpenCV) convention: -x right, y down, z forward. -""" +"""Bounded tilt and pan actions for a foveated camera.""" from __future__ import annotations -import math from typing import TYPE_CHECKING, ClassVar import torch import warp as wp -from isaaclab.managers import ActionTerm, ManagerTermBase, ObservationTermCfg, SceneEntityCfg +from isaaclab.managers import ActionTerm from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.memory import resolve_1d_indices, resolve_ids -from ..sensors.gaze_kernels import ( - DEG_TO_RAD, - CameraParams, - project_direction, - project_directions, - record_launch, - warp_stream, -) +from ..sensors.gaze_kernels import record_launch, torch_stream, warp_stream if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv @@ -37,119 +24,6 @@ from ..sensors import FoveatedCamera from .gaze_cfg import GazeActionCfg -RAD_TO_DEG = 180.0 / math.pi - - -@wp.func -def teach( - point: wp.vec3f, - position: wp.vec3f, - mount: wp.quatf, - g: wp.vec2f, - frame: wp.mat33f, - field_radius_deg: wp.float32, - step_size: wp.float32, - gaze_limit: wp.float32, - camera: CameraParams, -) -> wp.vec4f: - """The teacher's action (x, y) toward a point, 1 for a valid target or else 0, and the gaze's error [deg]. - - ``frame`` carries the upright image frame, in which gazes are measured, into the physical camera's frame. - """ - d = wp.normalize(wp.quat_rotate_inv(mount, point - position)) - # The fixation reaches the physical camera at frame * gaze * z, so the gaze looks along frame^T d. - u = wp.transpose(frame) * d - tilt = -wp.atan2(u[1], wp.sqrt(u[0] * u[0] + u[2] * u[2])) * wp.float32(RAD_TO_DEG) - pan = -wp.atan2(u[0], u[2]) * wp.float32(RAD_TO_DEG) - desired = wp.vec2f(tilt, pan) / field_radius_deg - ok = project_direction(d, camera)[2] > 0.5 and wp.length(desired) <= gaze_limit - step = wp.vec2f(0.0, 0.0) - if ok: - step = wp.vec2f( - wp.clamp((desired[0] - g[0]) / step_size, -1.0, 1.0), wp.clamp((desired[1] - g[1]) / step_size, -1.0, 1.0) - ) - g_tilt = g[0] * field_radius_deg * wp.float32(DEG_TO_RAD) - g_pan = g[1] * field_radius_deg * wp.float32(DEG_TO_RAD) - looking = wp.vec3f(-wp.cos(g_tilt) * wp.sin(g_pan), -wp.sin(g_tilt), wp.cos(g_tilt) * wp.cos(g_pan)) - # atan2 stays accurate near perfect alignment, unlike acos of the dot product. - error = wp.atan2(wp.length(wp.cross(looking, u)), wp.dot(looking, u)) * wp.float32(RAD_TO_DEG) - return wp.vec4f(step[0], step[1], wp.where(ok, 1.0, 0.0), error) - - -@wp.kernel(enable_backward=False) -def teacher_labels_kernel( - targets: wp.array(dtype=wp.vec3f), - orientations: wp.array(dtype=wp.quatf), - offset: wp.vec3f, - positions: wp.array(dtype=wp.vec3f), - mounts: wp.array(dtype=wp.quatf), - angles_deg: wp.array(dtype=wp.vec2f), - frame: wp.mat33f, - field_radius_deg: wp.float32, - step_size: wp.float32, - gaze_limit: wp.float32, - camera: CameraParams, - labels: wp.array2d(dtype=wp.float32), - log: wp.array(dtype=wp.float32), -): - """Labels (action x, action y, valid) toward the point ``offset`` fixed to each target's frame; and the mean gaze - error to valid targets [deg] with the fraction of valid targets. - - ``mounts`` holds each camera's mount (ROS convention); ``angles_deg`` the camera's stored gaze angles [deg]. - One block labels every environment and reduces the logs itself, so the launch needs no zeroed accumulators. - """ - _block, lane = wp.tid() - count = targets.shape[0] - error_sum = wp.float32(0.0) - valid_count = wp.float32(0.0) - i = lane - while i < count: - point = targets[i] + wp.quat_rotate(orientations[i], offset) - gaze = angles_deg[i] / field_radius_deg - result = teach(point, positions[i], mounts[i], gaze, frame, field_radius_deg, step_size, gaze_limit, camera) - labels[i, 0] = result[0] - labels[i, 1] = result[1] - labels[i, 2] = result[2] - if result[2] > 0.5: - error_sum += result[3] - valid_count += 1.0 - i += wp.block_dim() - errors = wp.tile_sum(wp.tile(error_sum)) - valid = wp.tile_sum(wp.tile(valid_count)) - if lane == 0: - log[0] = errors[0] / wp.max(valid[0], 1.0) - log[1] = valid[0] / wp.float32(count) - - -def teacher_block_dim(device: torch.device | str) -> int: - """Threads of the one block that runs :func:`teacher_labels_kernel`; Warp runs CPU blocks as one thread.""" - return 1024 if torch.device(device).type == "cuda" else 1 - - -@wp.kernel(enable_backward=False) -def gaze_reset_kernel( - ids: wp.array(dtype=wp.int32), - use_ids: wp.int32, - start: wp.array(dtype=wp.vec2f), - use_start: wp.int32, - field_radius_deg: wp.float32, - angles_deg: wp.array(dtype=wp.vec2f), - state: wp.array(dtype=wp.vec4f), -): - """Put each reset environment's gaze at its start, or on the optical axis, at rest. - - ``state`` holds each gaze and its velocity, in field radii and field radii per second. - """ - k = wp.tid() - i = k - if use_ids != 0: - i = ids[k] - g = wp.vec2f(0.0, 0.0) - if use_start != 0: - g = start[k] - angles_deg[i] = g * field_radius_deg - state[i] = wp.vec4f(g[0], g[1], 0.0, 0.0) - @wp.kernel(enable_backward=False) def gaze_step_kernel( @@ -183,25 +57,14 @@ def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: class GazeAction(ActionTerm): - """Moves a foveated camera's gaze by bounded steps in (tilt, pan) order. + """Move gaze by clipped tilt and pan increments within a disk of permitted angles. - Actions, the limit and the observed gaze are in field radii. An action of 1 changes a coordinate by - ``step_size``, and the gaze stays within ``gaze_limit`` of the optical axis. The gaze starts each episode on the - optical axis, or anywhere the physical camera sees within the limit when ``random_reset`` is set. Gazes are measured - in the upright image frame, which :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.image_rotation_deg` rolls - against a rolled mount. - - With ``mount="fixed"`` the camera keeps the orientation it had when the term was created, and the teacher uses - that mount; turning the camera's mount afterwards raises. With ``mount="tracked"`` the camera may ride a moving - body, for example a robot's head, and the teacher reads each camera's current mount, so software gaze adds to - hardware gaze. - - The camera's stored gaze angles own the gaze: each step and the teacher start from them, so a gaze set directly - with :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles` carries on. :attr:`state`, the observation, is - the gaze and velocity as of the last step or reset. + Angles and increments are in units of the retina's field radius. Reset returns the gaze to the optical axis. + The camera owns the angles. The action reports the gaze and its angular velocity after the last action or reset. """ cfg: GazeActionCfg + _asset: FoveatedCamera is_graphable: ClassVar[bool] = True """The gaze moves in :meth:`process_actions`, once per environment step; :meth:`apply_actions` does nothing, so @@ -209,82 +72,31 @@ class GazeAction(ActionTerm): def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): super().__init__(cfg, env) - camera = self.camera - self.tracked_mount = cfg.mount == "tracked" - if self.tracked_mount and not camera.turns_pose_by_gaze: - raise ValueError( - "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX." - ) - if not self.tracked_mount and camera.cfg.prim_path.rpartition("/")[0] not in ( - "{ENV_REGEX_NS}", - env.scene.env_regex_ns, - ): - # A body's motion turns its camera without set_world_poses, which the fixed mount could not detect. - raise ValueError( - f"A fixed gaze mount needs a camera mounted on the environment, got {camera.cfg.prim_path!r};" - " use mount='tracked' for a camera on a moving body." - ) - # The camera's own geometry, so the teacher and the sensor mask share one projection. - frame = camera.image_frame - self._frame_torch = torch.tensor( - [[frame[row][col] for col in range(3)] for row in range(3)], device=self.device - ) - self.field_radius_deg = camera.sampling_coords.fov / 2 - """Half the retina's field of view [deg].""" - self._fixed_mount = None - if not self.tracked_mount: - # The fixed-mount teacher keeps the camera's mount as it is now; only later turns invalidate it. - mount = camera.ungazed_quat_w_ros() - self._fixed_mount = ProxyArray(wp.from_torch(mount.contiguous(), dtype=wp.quatf)) - self._mount_turns = camera.mount_turns + self.field_radius_deg = self._asset.sampling_coords.fov / 2 self._raw: torch.Tensor | None = None """Gaze actions of the last step, as supplied to :meth:`process_actions`.""" self._state = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec4f, device=self.device)) """Gaze and its velocity as of the last step or reset, the gaze observation.""" - self._velocity = self._state.torch[:, 2:] + self._all_ids = wp.from_torch(torch.arange(self.num_envs, dtype=torch.int32, device=self.device)) self._step_launch: tuple[tuple, wp.Launch] | None = None - # Each reset copies its environments, and their start gazes if random, into these and replays one launch. - self._reset_ids = ProxyArray(wp.zeros(self.num_envs, dtype=wp.int32, device=self.device)) - self._reset_start = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec2f, device=self.device)) - self._reset_launches: dict[tuple[bool, bool], wp.Launch] = {} @property def action_dim(self) -> int: return 2 - @property - def camera(self) -> FoveatedCamera: - """The foveated camera whose gaze the term moves.""" - return self._asset - @property def raw_actions(self) -> torch.Tensor: - return self._raw if self._raw is not None else torch.zeros_like(self._velocity) + return self._raw if self._raw is not None else torch.zeros_like(self._state.torch[:, :2]) @property def processed_actions(self) -> torch.Tensor: - return self.gaze - - @property - def gaze(self) -> torch.Tensor: - """Current gaze in field radii, from the camera's stored angles, shape (num_envs, 2).""" - return self.angles_deg / self.field_radius_deg - - @property - def velocity(self) -> torch.Tensor: - """Gaze velocity in field radii per second, shape (num_envs, 2).""" - return self._velocity + return self._asset.gaze_angles.torch / self.field_radius_deg @property def state(self) -> torch.Tensor: """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" return self._state.torch - @property - def angles_deg(self) -> torch.Tensor: - """Current gaze angles [deg], the camera's stored ones, shape (num_envs, 2).""" - return self.camera.gaze_angles.torch - def process_actions(self, actions: torch.Tensor): """Move the gaze by the supplied actions, shape (num_envs, 2). @@ -301,7 +113,7 @@ def process_actions(self, actions: torch.Tensor): [ wp.from_torch(actions, dtype=wp.vec2f), self._state, - self.camera.gaze_angles, + self._asset.gaze_angles, self.cfg.step_size, self.cfg.gaze_limit, self._env.step_dt, @@ -312,160 +124,20 @@ def process_actions(self, actions: torch.Tensor): self._step_launch = (key, launch) self._raw = actions self._step_launch[1].launch(warp_stream(self.device)) - self.camera.set_gaze_angles(self.camera.gaze_angles.torch) + self._asset.set_gaze_angles(self._asset.gaze_angles.torch) def apply_actions(self): pass def reset(self, env_ids=None): - # The action manager zeroes the reset environments' actions itself. - indexed = env_ids is not None - count = self.num_envs - if indexed: - if isinstance(env_ids, slice): - env_ids = torch.arange(*env_ids.indices(self.num_envs), device=self.device) - count = len(env_ids) - if count == 0: - return - self._reset_ids.torch[:count] = torch.as_tensor(env_ids, device=self.device) - random_start = self.cfg.random_reset - if random_start: - gaze = _random_gaze(count, self.cfg.gaze_limit, self.device) - visible = self.visible(_angles_to_direction(gaze * self.field_radius_deg)) - self._reset_start.torch[:count] = torch.where(visible[:, None], gaze, 0.0) - angles = self.camera.gaze_angles - launch = self._reset_launches.get((indexed, random_start)) - if launch is None: - launch = self._reset_launches[(indexed, random_start)] = record_launch( - gaze_reset_kernel, - self.num_envs, - [self._reset_ids, int(indexed), self._reset_start, int(random_start), self.field_radius_deg], - [angles, self._state], - self.device, - ) - launch.set_dim(count) - launch.launch(warp_stream(self.device)) - # The camera keeps reading the same buffer, which every other environment already holds. - self.camera.set_gaze_angles(angles.torch) - - def visible(self, direction: torch.Tensor) -> torch.Tensor: - """Whether directions in the upright gaze frame fall inside the physical camera's image.""" - return project_directions(direction @ self._frame_torch.T, self.camera.projection_params)[1] - - def teacher_mounts(self) -> ProxyArray: - """Each camera's mount (x, y, z, w), ROS convention, that the teacher aims from: the current one when - tracked, else the one captured when the term was created. - - Raises: - RuntimeError: The camera's mount turned while the gaze assumes a fixed mount. - """ - if self.tracked_mount: - return self.camera.mount_quat_w_ros - if self.camera.mount_turns != self._mount_turns: - raise RuntimeError( - "The gaze camera's mount turned, so the fixed-mount teacher would aim from its first orientation;" - " use GazeActionCfg.mount='tracked'." - ) - return self._fixed_mount - - -class gaze_teacher_labels(ManagerTermBase): - """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3). - - A training label, never a policy input. One launch labels every environment and logs the mean gaze error to valid - targets and the fraction of valid targets. - - Args: - target_cfg: The asset, and optionally one body by ``body_names``. - offset: The point in the root's or the body's frame [m]. - action_name: The gaze action term. - """ - - def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv): - super().__init__(cfg, env) - self._gaze: GazeAction = env.action_manager.get_term(cfg.params.get("action_name", "gaze")) - self._labels = ProxyArray(wp.zeros((env.num_envs, 3), dtype=wp.float32, device=env.device)) - self._log = ProxyArray(wp.zeros(2, dtype=wp.float32, device=env.device)) - """Mean gaze error to valid targets [deg] and the fraction of valid targets.""" - self._offset: tuple[tuple[float, ...], wp.vec3f] | None = None - self._sources = None - self._targets = self._orientations = None - self._launch: tuple[tuple, wp.Launch] | None = None - - def __call__( - self, - env: ManagerBasedEnv, - target_cfg: SceneEntityCfg, - offset: tuple[float, float, float] = (0.0, 0.0, 0.0), - action_name: str = "gaze", - ) -> torch.Tensor: - data = env.scene[target_cfg.name].data - # Reading the properties refreshes the asset's pose buffers; their Warp views are wrapped once. - if target_cfg.body_names is None: - positions, orientations = data.root_pos_w, data.root_quat_w - else: - positions, orientations = data.body_pos_w, data.body_quat_w - if self._sources != (id(positions), id(orientations)): - self._sources = (id(positions), id(orientations)) - if target_cfg.body_names is None: - self._targets, self._orientations = positions.warp, orientations.warp + """Return the selected cameras to the optical axis, at rest.""" + angles = self._asset.gaze_angles + with torch_stream(self.device): + if env_ids is None: + angles.warp.zero_() + self._state.warp.zero_() else: - body = target_cfg.body_ids[0] - self._targets = wp.from_torch(positions.torch[:, body], dtype=wp.vec3f) - self._orientations = wp.from_torch(orientations.torch[:, body], dtype=wp.quatf) - point = tuple(float(value) for value in offset) - if self._offset is None or self._offset[0] != point: - self._offset = (point, wp.vec3f(*point)) - gaze = self._gaze - mounts = gaze.teacher_mounts() - camera_positions = gaze.camera.data.pos_w.warp - # The launch is recorded once and recorded again only when one of its arrays or the point changes. - sources = (self._targets, self._orientations, camera_positions, mounts, self._offset[1]) - if self._launch is None or any(a is not b for a, b in zip(self._launch[0], sources)): - block = teacher_block_dim(env.device) - launch = record_launch( - teacher_labels_kernel, - (1, block), - [ - self._targets, - self._orientations, - self._offset[1], - camera_positions, - mounts, - gaze.camera.gaze_angles, - gaze.camera.image_frame, - gaze.field_radius_deg, - gaze.cfg.step_size, - gaze.cfg.gaze_limit, - gaze.camera.projection_params, - ], - [self._labels, self._log], - env.device, - block_dim=block, - ) - self._launch = (sources, launch) - self._launch[1].launch(warp_stream(env.device)) - _log_teacher(env, self._log.torch) - return self._labels.torch - - -def _log_teacher(env: ManagerBasedEnv, values: torch.Tensor) -> None: - """Log the mean gaze error to valid targets and the fraction of valid targets.""" - # Loggers keep each step's entries, so they get a copy rather than the buffer the next step overwrites. - error, fraction = values.clone() - log = env.extras.setdefault("log", {}) - log["Gaze/target_error_deg"] = error - log["Gaze/valid_target_fraction"] = fraction - - -def _angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: - """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3).""" - tilt, pan = angles_deg.deg2rad().unbind(-1) - return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) - - -def _random_gaze(count: int, limit: float, device: torch.device | str | None = None) -> torch.Tensor: - """Gazes drawn uniformly over the disc of radius ``limit``, shape (count, 2).""" - radius = limit * torch.rand(count, device=device).sqrt() - angle = 2 * math.pi * torch.rand(count, device=device) - return torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1) + indices = resolve_1d_indices(resolve_ids(ids=env_ids, all_ids=self._all_ids)) + wp.indexedarray(angles.warp, indices).zero_() + wp.indexedarray(self._state.warp, indices).zero_() + self._asset.set_gaze_angles(angles.torch) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py index 0318605a11fc..c038da8533e9 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py @@ -28,21 +28,11 @@ class GazeActionCfg(ActionTermCfg): step_size: float = 0.1 """Change of each gaze coordinate per step at an action of 1, in field radii. Positive and finite.""" gaze_limit: float = 1.0 - """Largest distance of the gaze from the camera's optical axis, in field radii. Positive and finite.""" - random_reset: bool = False - """Start episodes at a random gaze the camera sees; otherwise on the optical axis.""" - mount: str = "fixed" - """Teacher's mount: ``"fixed"`` at the action's creation, or ``"tracked"`` on a moving body (Newton, OVRTX).""" + """Radius of the allowed tilt/pan disk, in field radii. Positive and finite.""" def validate_config(self): - """Reject gaze bounds that would divide by zero and unknown mounts.""" - if not _positive_finite(self.step_size): + """Reject gaze bounds that would divide by zero.""" + if not math.isfinite(self.step_size) or self.step_size <= 0: raise ValueError(f"GazeActionCfg.step_size must be positive and finite, got {self.step_size!r}.") - if not _positive_finite(self.gaze_limit): + if not math.isfinite(self.gaze_limit) or self.gaze_limit <= 0: raise ValueError(f"GazeActionCfg.gaze_limit must be positive and finite, got {self.gaze_limit!r}.") - if self.mount not in ("fixed", "tracked"): - raise ValueError(f"GazeActionCfg.mount must be 'fixed' or 'tracked', got {self.mount!r}.") - - -def _positive_finite(value) -> bool: - return isinstance(value, (int, float)) and math.isfinite(value) and value > 0 diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index d499139eec0c..c2f417286094 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -8,13 +8,13 @@ from __future__ import annotations import math -from typing import Protocol -import torch -from fovi.sensing.projection import CameraCalibration, CameraModel, angular_directions +from fovi.sensing.projection import CameraCalibration, CameraModel from isaaclab.sim import PinholeCameraCfg +from .foveated_camera_cfg import FoveatedCameraCfg + IDEAL_IMAGE_WIDTH = 1024 """Pixel width [px] of the image assigned to a camera derived from ideal spawn optics. @@ -79,7 +79,7 @@ def camera_model_from_spawn(spawn: PinholeCameraCfg) -> CameraCalibration: ) -def resolve_camera_model(cfg: SamplingGeometryConfig) -> CameraModel: +def resolve_camera_model(cfg: FoveatedCameraCfg) -> CameraModel: """Return the physical camera the retina looks through. This is ``cfg.camera_model`` when set, otherwise the camera that ``cfg.spawn`` @@ -93,41 +93,3 @@ def resolve_camera_model(cfg: SamplingGeometryConfig) -> CameraModel: if cfg.spawn is None: raise ValueError("A foveated camera on an existing prim needs camera_model.") return CameraModel(**camera_model_from_spawn(cfg.spawn)) - - -def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: - """Return the retinal field of view and the CMF constant, both in degrees. - - The field of view is the angular span of the retinal window in the physical - camera. Both values are in the units :class:`fovi.sensing.coords.SamplingCoords` takes. - """ - fov = resolve_camera_model(cfg).field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_fraction) - return fov, cfg.cmf_a_deg - - -def retinal_directions(cartesian: torch.Tensor, fov_deg: float, image_rotation_deg: float = 0.0) -> torch.Tensor: - """Return OpenGL-frame angular rays, including the sensor mount roll.""" - rays = angular_directions(cartesian, fov_deg) - rays = rays * rays.new_tensor((1, -1, -1)) - angle = rays.new_tensor(image_rotation_deg * torch.pi / 180) - x, y, z = rays.unbind(-1) - return torch.stack((angle.cos() * x - angle.sin() * y, angle.sin() * x + angle.cos() * y, z), -1) - - -def compose_rotations(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor: - """Compose small rotation matrices without TF32 tensor-core rounding. - - Camera transforms need orthonormal rotations even when the surrounding - training process enables reduced-precision matrix multiplication. - """ - return (left[..., :, :, None] * right[..., None, :, :]).sum(dim=-2) - - -class SamplingGeometryConfig(Protocol): - """The configuration fields that place the retina in the physical camera.""" - - camera_model: CameraCalibration | None - cmf_a_deg: float - retinal_window_reference_side: str - retinal_window_fraction: float - spawn: PinholeCameraCfg | None diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 28af5b3b8ad7..1f95dc30d24c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -14,13 +14,15 @@ import torch import warp as wp +from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel from isaaclab.sensors.camera.camera import Camera -from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_error_magnitude +from isaaclab.utils import clone +from isaaclab.utils.math import convert_camera_frame_orientation_convention from isaaclab.utils.warp import ProxyArray -from .calibrated_geometry import resolve_camera_model, retinal_directions +from .calibrated_geometry import resolve_camera_model from .gaze_kernels import ( CameraParams, apply_gaze_indexed_kernel, @@ -28,24 +30,14 @@ camera_params, publish_grid_kernel, record_launch, - sensor_visibility_kernel, set_gaze_kernel, warp_stream, ) -from .native_grid import GRID_STYLE, buffer_tensor, native_grid_directions -from .pooling import ( - is_segmentation_output, - pool_hwc_buffer, - pool_segmentation_buffer, - segmentation_neighbor_indices, -) +from .native_grid import native_grid_directions if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg -MOUNT_TURN_TOLERANCE_RAD = 1e-5 -"""Smallest change of a camera's mount orientation [rad] that counts as a turn; smaller ones are float rounding.""" - OPENGL_TO_ROS_AXES = (1.0, -1.0, -1.0) """Axis signs between OpenGL camera-frame directions (x right, y up, -z forward) and ROS ones (x right, y down).""" @@ -105,67 +97,40 @@ def __init__(self, cfg: FoveatedCameraCfg): """ self._gaze_pose_reads_angles = self._pose_update_turns_gaze(cfg) """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses - when the gaze is set; see :attr:`turns_pose_by_gaze`.""" + when the gaze is set.""" if self._gaze_pose_reads_angles and not cfg.update_latest_camera_pose: raise ValueError( "Newton and OVRTX turn the rendered pose by the gaze in each pose update; set" " update_latest_camera_pose=True so the renderer sees the gaze." ) # The parent's initialisation updates poses before the gaze exists. - self._gaze_written = False self._gaze_angles: ProxyArray | None = None self._gaze_rotation: ProxyArray | None = None - self._visibility = None - self._grid_publish = None - self._published_shape: tuple[int, int] | None = None - self._segmentation_neighbors: torch.Tensor | None = None - self._sensor_fov_valid: torch.Tensor | None = None - self.mount_turns = 0 - """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount.""" + cfg = clone(cfg) + cfg.width = cfg.height = cfg.foveated_res + self._camera_model = resolve_camera_model(cfg) + fov = self._camera_model.field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_fraction) + self._sampling_coords = SamplingCoords( + fov=fov, + cmf_a=cfg.cmf_a_deg, + res=cfg.foveated_res, + style="warped_cartesian_as_grid", + field_geometry="spherical", + device="cpu", + ) + self._retinal_rays = native_grid_directions(self._sampling_coords, image_rotation_deg=cfg.image_rotation_deg) super().__init__(cfg) @property - def image_shape(self) -> tuple[int, int]: - """(height, width) of the published outputs: the retina's grid, or (num_samples, 1) for sample sets.""" - return self._published_shape if self._published_shape is not None else super().image_shape - - @property - def sampling_coords(self): + def sampling_coords(self) -> SamplingCoords: """The :class:`SamplingCoords` of the published samples.""" return self._sampling_coords - @property - def num_valid_samples(self) -> int: - """Number of published foveated samples.""" - return self._num_valid_samples - - @property - def sensor_fov_valid_fraction(self) -> torch.Tensor | None: - """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" - return None if self._sensor_fov_valid is None else self._sensor_fov_valid.float().mean(dim=1) - @property def camera_model(self) -> CameraModel: """The physical camera the retina looks through, as resolved at initialization.""" return self._camera_model - @property - def projection_params(self) -> CameraParams: - """:attr:`camera_model` as a Warp struct, for kernels that project camera-frame directions.""" - return self._gaze_camera - - @property - def image_frame(self) -> wp.mat33f: - """Rotation from the upright image frame, in which gazes are measured, to the physical camera's frame (ROS - convention); it undoes ``cfg.image_rotation_deg``.""" - return self._mask_frame - - @property - def turns_pose_by_gaze(self) -> bool: - """Whether each pose update turns the rendered pose by the stored gaze (Newton and OVRTX). A writer of - :attr:`gaze_angles` then needs no other launch.""" - return self._gaze_pose_reads_angles - @property def gaze_angles(self) -> ProxyArray: """The camera's stored gaze angles [deg], shape (num_envs,) of ``vec2f`` (Torch view (num_envs, 2)). @@ -177,20 +142,6 @@ def gaze_angles(self) -> ProxyArray: self._allocate_gaze() return self._gaze_angles - @property - def mount_quat_w_ros(self) -> ProxyArray: - """World orientation (x, y, z, w) of the physical camera before the gaze turns it, ROS convention, shape - (num_envs,) of ``quatf``. - - Refreshed by each pose update that turns the gaze, so it follows a mount that moves, for example a camera on - a robot's head. Only cameras whose pose update turns the gaze (Newton and OVRTX) record it. - """ - if not self._gaze_pose_reads_angles: - raise RuntimeError("Only cameras whose pose update turns the gaze (Newton, OVRTX) record their mount.") - if self._gaze_angles is None: - self._allocate_gaze() - return self._mount_quat_ros - def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. @@ -204,7 +155,7 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: ValueError: The angles do not hold one row per camera. """ stored = self._gaze_angles is not None and angles_deg is self._gaze_angles.torch - if stored and self.turns_pose_by_gaze: + if stored and self._gaze_pose_reads_angles: # The next pose update reads the stored angles; nothing has to happen now. return count = self._view.count @@ -224,43 +175,6 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: gaze.device, ) self._set_gaze_launch.launch(warp_stream(gaze.device)) - self._gaze_written = True - - def ungazed_quat_w_ros(self) -> torch.Tensor: - """World orientation (x, y, z, w) of the physical camera now, before the gaze turns it, ROS convention, shape - (num_envs, 4).""" - if self._gaze_pose_reads_angles and self._gaze_angles is not None: - # The record starts at the pose before any gaze and follows each pose update. - return self._mount_quat_ros.torch.clone() - if self._gaze_written: - # The prims hold the gaze (Isaac RTX); get_world_poses reports the mount without it. - return self.get_world_poses(convention="ros")[1] - return self._data.quat_w_ros.torch.clone() - - def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): - """Move the camera's mount; the gaze stays relative to the new mount. - - Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. - """ - if orientations is None: - # A position-only move keeps every mount's orientation. - super().set_world_poses(positions, orientations, env_ids, convention) - return - before = self._mount_orientations(env_ids) - super().set_world_poses(positions, orientations, env_ids, convention) - self._mount_written(env_ids) - self._count_mount_turn(before, env_ids) - - def set_world_poses_from_view(self, eyes, targets, env_ids=None): - """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. - - Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. - """ - before = self._mount_orientations(env_ids) - super().set_world_poses_from_view(eyes, targets, env_ids) - # Rows whose eye equals their target are skipped by the base method and keep their poses. - self._mount_written(self._env_indices(env_ids)[self._turned_by_view(eyes, targets)]) - self._count_mount_turn(before, env_ids) def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): """Keep the camera as configured and warn the caller. @@ -281,52 +195,35 @@ def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): ) def _initialize_gaze(self) -> None: - """Prepare the gaze geometry: the rendered rays in the physical camera's frame and the pose conversions.""" - self._camera_model = resolve_camera_model(self.cfg) - self._gaze_camera = camera_params(self._camera_model) - coords = self._sampling_coords_highres or self._sampling_coords - rotation_deg = self.cfg.image_rotation_deg - # The rays as rendered, mount roll included, in the ROS frame the camera model projects. - if coords.style == GRID_STYLE: - rays = native_grid_directions(coords, image_rotation_deg=rotation_deg) - else: - rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) - self._gaze_rays = (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() - # No gaze until one is set: the camera looks along its optical axis untouched. + """Move the canonical rays to the sensor device and prepare camera-frame conversions.""" + self._sampling_coords = self._sampling_coords.to(device=self._device) + self._retinal_rays = self._retinal_rays.to(device=self._device) self._gaze_angles = None self._gaze_rotation = None - self._visibility = None - device = self._gaze_rays.device - self._gaze_identity = torch.eye(3, device=device) + rotation_deg = self.cfg.image_rotation_deg angle = math.radians(rotation_deg) c, s = math.cos(angle), math.sin(angle) # Gaze is defined in the upright image frame; the basis carries it into the rolled OpenGL camera frame. - self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) + self._gaze_basis = self._retinal_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) # The same roll in the ROS frame: a rendered ray r reaches the physical camera at K gaze K^T r. self._mask_frame = wp.mat33f(c, s, 0.0, -s, c, 0.0, 0.0, 0.0, 1.0) # Fixed right-multiplied frame changes, on the CPU in float64, where no reduced-precision matmul applies. identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], dtype=torch.float64) to_opengl = convert_camera_frame_orientation_convention(identity, origin="world", target="opengl")[0].tolist() to_world = convert_camera_frame_orientation_convention(identity, origin="opengl", target="world")[0].tolist() - to_ros = convert_camera_frame_orientation_convention(identity, origin="world", target="ros")[0].tolist() self._gaze_frames = ( wp.mat33f(*self._gaze_basis.flatten().tolist()), wp.quatf(*to_opengl), wp.quatf(*to_world), - wp.quatf(*to_ros), ) def _allocate_gaze(self) -> None: - """Allocate one stored gaze per camera, on the optical axis, its rotation and the mount, on the sensor - device.""" + """Allocate one stored gaze per camera, on the optical axis, and its rotation on the sensor device.""" count, device = self._view.count, str(self._device) self._gaze_angles = ProxyArray(wp.zeros(count, dtype=wp.vec2f, device=device)) self._gaze_rotation = ProxyArray( wp.from_torch(torch.eye(3, device=device).repeat(count, 1, 1), dtype=wp.mat33f) ) - # No gaze has turned the pose yet, so the current orientation is the mount. - mount = self._data.quat_w_ros.torch.clone() - self._mount_quat_ros = ProxyArray(wp.from_torch(mount, dtype=wp.quatf)) self._gaze_angles_key = None self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=device) @@ -349,13 +246,13 @@ def _update_camera_state( def _apply_gaze_pose( self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None ) -> None: - """Turn the camera's world orientation by the stored gaze, and record the gaze rotations and the mount.""" + """Turn the camera's world orientation by the stored gaze, and record the gaze rotations.""" if self._gaze_angles is None: return orientation = self._data.quat_w_world.warp device = self._gaze_angles.torch.device frames = (self._gaze_angles, *self._gaze_frames) - outputs = [orientation, self._gaze_rotation, self._mount_quat_ros] + outputs = [orientation, self._gaze_rotation] indexed = env_ids is not None and env_mask is None if indexed: # The kernel takes contiguous int32 indices; this converts sequences, slices, tensors and Warp arrays. @@ -378,191 +275,62 @@ def _apply_gaze_pose( launch.set_dim(len(env_ids)) launch.launch(warp_stream(device)) - def _mount_orientations(self, env_ids) -> torch.Tensor: - """The selected cameras' mount orientations (x, y, z, w), world convention, as :meth:`get_world_poses` reports - them.""" - return self.get_world_poses(env_ids, convention="world")[1].clone() - - def _mount_written(self, env_ids) -> None: - """Called after a pose write turned the selected cameras' mounts, before the turn is measured. Cameras that - hold the gaze in their prims write it onto the new mounts here.""" - - def _count_mount_turn(self, before: torch.Tensor, env_ids) -> None: - """Count a mount turn if any selected camera's mount now differs from ``before``. - - The teachers read the camera's live position, so only orientation changes count, and writing back the reported - poses does not. - """ - turned = quat_error_magnitude(before, self._mount_orientations(env_ids)) > MOUNT_TURN_TOLERANCE_RAD - if bool(turned.any()): - self.mount_turns += 1 - - def _env_indices(self, env_ids) -> torch.Tensor: - """The camera indices that ``env_ids`` selects, as a tensor.""" - if env_ids is None: - return torch.arange(self._view.count, device=self._device) - if isinstance(env_ids, slice): - return torch.arange(self._view.count, device=self._device)[env_ids] - if isinstance(env_ids, wp.array): - env_ids = wp.to_torch(env_ids) - return torch.as_tensor(env_ids, device=self._device, dtype=torch.long).reshape(-1) - - def _turned_by_view(self, eyes, targets) -> torch.Tensor: - """Which rows :meth:`set_world_poses_from_view` turns: the base method skips an eye equal to its target.""" - return (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0 - - def _visibility_buffers(self) -> dict: - """The sensor mask's camera-owned buffers, allocated once: the rendered rays, an unturned rotation per camera, - each sample's visibility and, for the updated rows, which samples to hide.""" - if self._visibility is None: - count, device = self._view.count, self._gaze_rays.device - shape = (count, len(self._gaze_rays)) - self._visibility = { - "rays": wp.from_torch(self._gaze_rays, dtype=wp.vec3f), - "identity": wp.from_torch(self._gaze_identity.expand(count, -1, -1).contiguous(), dtype=wp.mat33f), - "every_env": wp.ones(count, dtype=wp.bool, device=str(device)), - "valid": ProxyArray(wp.zeros(shape, dtype=wp.bool, device=str(device))), - "hidden": ProxyArray(wp.zeros(shape, dtype=wp.bool, device=str(device))), - "launch": None, - } - return self._visibility - - def _gaze_validity(self, env_mask: wp.array | None = None) -> torch.Tensor: - """Which samples the physical camera sees at each updated environment's gaze, shape (num_envs, num_samples). - - Each rendered ray is tested by its center direction. Environments outside ``env_mask`` keep their last - visibility; None updates every one. - """ - buffers = self._visibility_buffers() - rotation = buffers["identity"] if self._gaze_rotation is None else self._gaze_rotation.warp - updated = buffers["every_env"] if env_mask is None else env_mask - cached = buffers["launch"] - if cached is None or cached[0] is not rotation or cached[1] is not updated: - launch = record_launch( - sensor_visibility_kernel, - buffers["valid"].warp.shape, - [buffers["rays"], rotation, self._mask_frame, self._gaze_camera, updated], - [buffers["valid"], buffers["hidden"]], - self._gaze_rays.device, - ) - buffers["launch"] = cached = (rotation, updated, launch) - cached[2].launch(warp_stream(self._gaze_rays.device)) - return buffers["valid"].torch - - def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor], env_mask: wp.array | None = None) -> None: - """Zero the samples outside the physical camera at the current gaze in the updated environments' (B, N, 1, C) - outputs; None updates every environment.""" - if not self.cfg.mask_to_sensor_fov: - return - tensors = {name: buffer_tensor(value) for name, value in outputs.items()} - self._sensor_fov_valid = self._gaze_validity(env_mask) - hidden = self._visibility["hidden"].torch[:, :, None, None] - for name, tensor in tensors.items(): - if name == "rgb" and "rgba" in tensors: - continue - tensor.masked_fill_(hidden, 0) - - def _prepare_segmentation_pooling(self, names) -> None: - """Take the modal-label neighbourhoods of pooled segmentation outputs among ``names`` from the main pooler.""" - self._segmentation_neighbors = None - if self._pooler is not None and any(is_segmentation_output(name) for name in names): - self._segmentation_neighbors = segmentation_neighbor_indices(self._pooler) - - def _pool_output(self, name: str, samples: torch.Tensor) -> torch.Tensor: - """Pool one output's high-resolution samples (B, N_hi, 1, C) to the retina's (B, N_lo, 1, C), in its dtype. - - Segmentation takes each sample's modal label in its native dtype; other outputs are pooled in float with - ``pool_mode``. With :attr:`~FoveatedCameraCfg.mask_to_sensor_fov`, photoreceptors outside the physical camera's - image at the current gaze are left out, so a pooled sample at the image edge is not darkened by them. - """ - visible = self._visibility["valid"].torch if self.cfg.mask_to_sensor_fov else None - if is_segmentation_output(name): - return pool_segmentation_buffer(self._segmentation_neighbors, samples, visible) - pooled = pool_hwc_buffer(self._pooler, samples.float(), visible) - if not samples.dtype.is_floating_point: - # Round to the nearest value the output can hold, e.g. 0-255 for RGB, rather than truncating. - limits = torch.iinfo(samples.dtype) - pooled = pooled.round().clamp(limits.min, limits.max) - return pooled.to(samples.dtype) - def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: - """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for - :func:`publish_grid_kernel`.""" - views = [] + """Allocate upright public buffers and bind byte views of the renderer's native grid.""" + coords = self._sampling_coords + indices = torch.arange(len(coords), dtype=torch.int32, device=self._device) + self._grid_indices_wp = wp.from_torch(coords.as_grid(indices).reshape(-1).contiguous()) + self._grid_footprint_wp = wp.from_torch(coords.valid_mask.contiguous()) + # Rendered OpenGL rays become physical-camera ROS rays for the calibrated mask. + rays = self._retinal_rays * self._retinal_rays.new_tensor(OPENGL_TO_ROS_AXES) + self._grid_rays_wp = wp.from_torch(rays, dtype=wp.vec3f) + self._grid_camera = camera_params(self._camera_model) if self.cfg.mask_to_sensor_fov else CameraParams() + self._grid_identity = wp.from_torch( + torch.eye(3, device=self._device).repeat(self._view.count, 1, 1), dtype=wp.mat33f + ) + + outputs = {} + self._grid_publish = [] for name, source in sources.items(): if name == "rgb" and "rgba" in sources: continue - target = self._grid_output[name].view(source.shape[0], -1, source.shape[-1]) - views.append((wp.from_torch(source.view(torch.uint8)), wp.from_torch(target.view(torch.uint8)))) - self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous()) - self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous()) - num_envs = views[0][1].shape[0] - if self.cfg.mask_to_sensor_fov: - buffers = self._visibility_buffers() - self._grid_every_env = buffers["every_env"] - self._grid_sensor = ( - buffers["rays"], - buffers["identity"], - self._mask_frame, - self._gaze_camera, - buffers["valid"].warp, - ) - else: - self._grid_every_env = wp.ones(num_envs, dtype=wp.bool, device=str(self._device)) - # Placeholders: the kernel reads none of these without the sensor mask. - self._grid_sensor = ( - wp.zeros(1, dtype=wp.vec3f, device=self._device), - wp.zeros(1, dtype=wp.mat33f, device=self._device), - wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0), - CameraParams(), - wp.zeros((1, 1), dtype=wp.bool, device=self._device), + count, _, _, channels = source.shape + target = torch.zeros_like(source, memory_format=torch.contiguous_format) + self._grid_publish.append( + ( + wp.from_torch(source.view(count, -1, channels).view(torch.uint8)), + wp.from_torch(target.view(count, -1, channels).view(torch.uint8)), + ) ) - self._grid_publish = views + outputs[name] = target + if "rgb" in sources and "rgba" in sources: + outputs["rgb"] = outputs["rgba"][..., :3] + self._data._output = {name: ProxyArray(wp.from_torch(value)) for name, value in outputs.items()} self._grid_launches = None - def _publish_grid(self, env_mask: wp.array | None = None) -> None: - """Mask and lay out every output of the updated environments in one launch each; the result equals masking, - then copying to the grid. The other environments keep their last published frame; None updates every one.""" - mask = self.cfg.mask_to_sensor_fov - env_mask = self._grid_every_env if env_mask is None else env_mask - rays, identity, frame, camera, visible = self._grid_sensor - rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation.warp + def _publish_grid(self, env_mask: wp.array) -> None: + """Mask and publish the upright grid for the updated environments.""" + rotation = self._grid_identity if self._gaze_rotation is None else self._gaze_rotation.warp cached = self._grid_launches - if cached is None or cached[0][0] is not rotation or cached[0][1] is not env_mask: + if cached is None or cached[0] is not rotation or cached[1] is not env_mask: + inputs = [ + self._grid_indices_wp, + self._grid_footprint_wp, + env_mask, + self._grid_rays_wp, + rotation, + self._mask_frame, + self._grid_camera, + int(self.cfg.mask_to_sensor_fov), + ] launches = [ - record_launch( - publish_grid_kernel, - (target.shape[0], target.shape[1]), - [ - source, - self._grid_indices_wp, - self._grid_footprint_wp, - env_mask, - rays, - rotation, - frame, - camera, - int(mask), - int(mask and index == 0), - visible, - ], - [target], - self._device, - ) - for index, (source, target) in enumerate(self._grid_publish) + record_launch(publish_grid_kernel, target.shape[:2], [source, *inputs], [target], self._device) + for source, target in self._grid_publish ] - self._grid_launches = ((rotation, env_mask), launches) + self._grid_launches = cached = (rotation, env_mask, launches) stream = warp_stream(self._device) - for launch in self._grid_launches[1]: + for launch in cached[2]: launch.launch(stream) - if mask: - self._sensor_fov_valid = self._visibility["valid"].torch - - def _set_published_shape(self, outputs: Mapping[str, torch.Tensor]) -> None: - """Report the (height, width) of the published outputs, which differ from the rendered ones.""" - tensor = next(iter(outputs.values())).torch - self._published_shape = (int(tensor.shape[1]), int(tensor.shape[2])) - self._data.image_shape = self._published_shape @staticmethod def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index c4039eabcee6..9cbdf77391ce 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -7,10 +7,8 @@ from __future__ import annotations -import math from typing import TYPE_CHECKING -from fovi.sensing.coords import RADIUS_NORMS, WARPED_CARTESIAN_STYLES from fovi.sensing.projection import CameraCalibration from isaaclab.sensors.camera.camera_cfg import CameraCfg @@ -20,23 +18,6 @@ from .foveated_camera import FoveatedCamera -POOL_MODES = ("avg", "gaussian", "max", "sum") -"""fovi pooling modes for the outputs other than segmentation.""" - -SEGMENTATION_POOL_MODES = ("modal",) -"""Pooling modes for segmentation outputs: the modal label only.""" - - -def validate_radius_norm(radius_norm: float, style: str, fov_type: str) -> None: - """Reject warped-grid radius norms that fovi cannot sample, before renderer startup.""" - if radius_norm not in RADIUS_NORMS: - raise ValueError(f"radius_norm must be one of {RADIUS_NORMS}, got {radius_norm!r}.") - if radius_norm != 2.0 and style not in WARPED_CARTESIAN_STYLES: - raise ValueError("Non-default radius_norm requires a warped_cartesian style.") - if radius_norm == math.inf and fov_type == "wang": - raise ValueError("radius_norm=inf does not support fov_type='wang'.") - - @configclass class FoveatedCameraCfg(CameraCfg): """Configuration for a foveated camera, whose retina samples densely where it looks and sparsely in the periphery. @@ -55,19 +36,7 @@ class FoveatedCameraCfg(CameraCfg): """The physical camera as ``CameraModel`` fields; None uses the camera that :attr:`spawn` creates.""" foveated_res: int = 60 - """Grid side of the retina; isotropic retinas use as many rings as keep at most its square of samples.""" - - foveated_style: str = "warped_cartesian_as_grid" - """Sampling style: the default grid publishes an upright image; sample-set styles publish a list of samples.""" - - fov_type: str = "circular" - """Region of the visual field the retina covers: ``"circular"``, ``"square"`` or ``"wang"``.""" - - radius_norm: float = 2.0 - """Norm of the warped-Cartesian sampling shells: 2.0 for circular shells, infinity for square ones.""" - - isotropic_plotting_type: str = "v1like" - """Cortical layout of an isotropic retina's samples: ``"v1like"``, ``"schwartz"`` or ``"warp"``.""" + """Side length of the published warped-Cartesian grid.""" image_rotation_deg: float = 0.0 """Counter-clockwise roll [deg] of the rays about the optical axis that undoes a rolled mount.""" @@ -81,29 +50,6 @@ class FoveatedCameraCfg(CameraCfg): retinal_window_reference_side: str = "short" """Image side defining the retinal window diameter: ``short`` or ``long``.""" - # -- Optional retinal pooling (photoreceptor -> RGC two-layer sampling) -- - - pool_enabled: bool = False - """Render a denser photoreceptor grid and pool it to the retina.""" - - pool_res_mult: float = 2 - """How many times denser the photoreceptor grid is than the retina; an integer for grid styles.""" - - pool_k: int | None = None - """Photoreceptors each sample pools: a square window's area for grid styles, else nearest neighbours.""" - - pool_mode: str = "avg" - """Pooling of non-segmentation outputs: ``"avg"``, ``"gaussian"``, ``"max"``, or ``"sum"`` for sample sets.""" - - pool_sample_cortex: bool | str = "geodesic" - """Neighbour distance for sample sets: ``"geodesic"`` on the cortex, ``True`` cortical, ``False`` visual.""" - - pool_gauss_sigma: float = 10.0 - """Gaussian sigma for ``pool_mode="gaussian"``.""" - - pool_int_mode: str = "modal" - """Pooling of segmentation outputs: ``"modal"``, each sample's most common label among its neighbours.""" - # -- RTX-specific parameters (ignored by Newton backend) ---------------- exit_texture_size: int | None = None @@ -116,17 +62,3 @@ class FoveatedCameraCfg(CameraCfg): update_latest_camera_pose: bool = True """Update the camera pose every frame. Newton and OVRTX require it: their pose update applies the gaze.""" - - def __post_init__(self): - # Resolves the default renderer and forwards deprecated renderer fields. - super().__post_init__() - validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) - if self.pool_mode not in POOL_MODES: - raise ValueError( - f"pool_mode must be one of {POOL_MODES}, got {self.pool_mode!r}; segmentation pools with pool_int_mode." - ) - if self.pool_int_mode not in SEGMENTATION_POOL_MODES: - raise ValueError( - f"pool_int_mode must be one of {SEGMENTATION_POOL_MODES}, got {self.pool_int_mode!r}: segmentation" - " pools by modal label, since other modes would mix labels into ones no object has." - ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index f86bfeb479a9..5df9df3f4a22 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -3,259 +3,49 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Newton foveated camera: Newton's Warp renderer casts one ray per retinal sample.""" +"""Explicit foveated ray grids for Newton Warp and OptiX.""" from __future__ import annotations -import logging -from collections.abc import Sequence -from typing import TYPE_CHECKING - -import torch import warp as wp -from isaaclab.sensors.camera.camera import Camera -from isaaclab.utils.warp import ProxyArray - -from .foveated_camera import OPENGL_TO_ROS_AXES, FoveatedCamera -from .native_grid import ( - GRID_STYLE, - allocate_grid_outputs, - copy_grid_outputs, - copy_updated_rows, - grid_output_shape, - grid_sample_indices, - mask_grid_samples, - proxy_outputs, -) -from .pooling import build_highres_coords, build_lowres_coords, build_pooler - -if TYPE_CHECKING: - from .foveated_camera_cfg import FoveatedCameraCfg - -logger = logging.getLogger(__name__) - - -def explicit_rays(directions: torch.Tensor, height: int, width: int) -> wp.array: - """Newton's ray array, shape (height, width, 1, 2): a zero origin and a unit direction per ray, shared by every - camera. - - Args: - directions: Unit ray directions in the OpenGL camera frame, in sample order, shape (N, 3). - height: Rendered rows. - width: Rendered columns; ``height * width`` must cover the N rays. Padding repeats the last ray. - """ - if directions.ndim != 2 or directions.shape[1] != 3: - raise ValueError(f"Ray directions must have shape (N, 3), got {tuple(directions.shape)}.") - if height * width < len(directions): - raise ValueError(f"A {height}x{width} render cannot hold {len(directions)} rays.") - index = torch.arange(height * width, device=directions.device).clamp_max(len(directions) - 1) - rays = directions.new_zeros(height, width, 1, 2, 3, dtype=torch.float32) - rays[..., 1, :] = directions.float()[index].reshape(height, width, 1, 3) - # The Warp view keeps the tensor alive. - return wp.from_torch(rays, dtype=wp.vec3f) +from .foveated_camera import FoveatedCamera +from .foveated_camera_cfg import FoveatedCameraCfg class FoveatedNewtonCamera(FoveatedCamera): - """Newton camera that renders with foveated (CMF-distributed) rays. - - Instead of a uniform pixel grid, this sensor shoots *N* rays whose - directions are derived from :class:`fovi.sensing.coords.SamplingCoords` - and injected into Newton's renderer, with Warp or OptiX traversal. Vector sensors publish - ``(B, N, 1, C)``; native grid sensors publish upright ``(B, H, W, C)``. - - The samples cover the retinal window of the physical camera; the gaze turns the rendered camera pose. - """ - - cfg: FoveatedCameraCfg - - def __init__(self, cfg: FoveatedCameraCfg): - # The parent's initialisation updates poses before the rays exist. - self._foveated_rays: wp.array | None = None - super().__init__(cfg) + """Render the shared retinal grid with Newton's explicit ray buffer.""" def _initialize_impl(self): - # The pooler's KNN tensors are plain attributes that nn.Module.to() does not move, so the coordinates start on - # the CPU and the pooler is built on the sensor device after the parent initializes. - self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") - self._native_grid = self.cfg.foveated_style == GRID_STYLE - self._sampling_coords_highres = build_highres_coords(self.cfg, self._sampling_coords, matched_res) - self._num_valid_samples = len(self._sampling_coords) - self._num_ray_samples = len(self._sampling_coords_highres or self._sampling_coords) - logger.info( - "FoveatedNewtonCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg", - self._num_valid_samples, - self._num_ray_samples, - self.cfg.foveated_style, - self._sampling_coords.cmf_a, - self._sampling_coords.fov, - ) - - # The parent allocates render buffers for the rendered rays: the high-resolution ones when pooling. - ray_coords = self._sampling_coords_highres or self._sampling_coords - self.cfg.height, self.cfg.width = grid_output_shape(ray_coords) renderer = self.cfg.renderer_cfg if renderer.render_order == "tiled": - tile_width = renderer.tile_rendering_width - tile_height = renderer.tile_rendering_height + tile_width, tile_height = renderer.tile_rendering_width, renderer.tile_rendering_height if tile_width <= 0 or tile_height <= 0: raise ValueError("Newton render tile dimensions must be positive.") - if self._native_grid: - self._validate_native_render_layout(tile_width, tile_height) - else: - # Pack consecutive vector rays into complete tiles. Padding is - # private renderer storage and never enters masking or pooling. - self.cfg.width = tile_width - self.cfg.height = ( - (self._num_ray_samples + tile_width * tile_height - 1) // (tile_width * tile_height) * tile_height + if self.cfg.width % tile_width or self.cfg.height % tile_height: + raise ValueError( + f"Foveated grid {self.cfg.width}x{self.cfg.height} must be divisible by Newton tile size " + f"{tile_width}x{tile_height}; adjust foveated_res or use a non-tiled render order." ) super()._initialize_impl() - - self._sampling_coords = self._sampling_coords.to(device=self._device) - if self._sampling_coords_highres is not None: - self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) - self._ray_coords = self._sampling_coords_highres or self._sampling_coords self._initialize_gaze() - self._pooler, self._pool_k = build_pooler( - self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) - ) - - # The gaze geometry's rendered rays, in canonical sample order and rolled by image_rotation_deg, back in the - # OpenGL frame Newton traces. - self._ray_directions = self._gaze_rays * self._gaze_rays.new_tensor(OPENGL_TO_ROS_AXES) - self._foveated_rays = explicit_rays(self._ray_directions, self.cfg.height, self.cfg.width) - render_samples = self.cfg.height * self.cfg.width - # Renderer buffers remain whole tiles; zero-copy canonical views hide - # trailing padding and preserve every output's dtype and sample order. - self._render_output = dict(self._data.output) - self._flat_render_output = {} - for name, value in self._render_output.items(): - tensor = value.torch - flat = tensor.view(tensor.shape[0], render_samples, 1, tensor.shape[-1]) - self._flat_render_output[name] = ProxyArray(wp.from_torch(flat[:, : self._num_ray_samples])) - self._data.output.clear() - self._data.output.update(self._flat_render_output) - - self._allocate_pooled_buffers() - source = self._pooled_output if self._pooler is not None else self._flat_render_output - self._sample_output = None - if self._pooler is None and not self._native_grid: - # Newton redraws every environment, so sample sets publish a copy that changes only on update. - self._sample_output = { - name: torch.zeros_like(value.torch) - for name, value in self._flat_render_output.items() - if not (name == "rgb" and "rgba" in self._flat_render_output) - } - if "rgba" in self._sample_output and "rgb" in self._flat_render_output: - self._sample_output["rgb"] = self._sample_output["rgba"][..., :3] - source = self._sample_output - if self._native_grid: - self._grid_output = allocate_grid_outputs(source, self._sampling_coords) - self._grid_indices = grid_sample_indices(self._sampling_coords) - source = self._grid_output - # The buffers the camera publishes: stable for the camera's lifetime and refilled each frame. - self._public_output = proxy_outputs(source) - self._data.output.clear() - self._data.output.update(self._public_output) - self._set_published_shape(self._public_output) - if self._native_grid and self._pooler is None: - self._prepare_grid_publish( - {name: value.torch.squeeze(2) for name, value in self._flat_render_output.items()} - ) - self._render_data.camera_rays = self._foveated_rays - - def _validate_native_render_layout(self, tile_width: int, tile_height: int) -> None: - """Reject a native grid that Newton's tiles cannot cover, before the parent allocates render buffers.""" - if self.cfg.width % tile_width or self.cfg.height % tile_height: - raise ValueError( - f"Native-grid Newton render size {self.cfg.width}x{self.cfg.height} " - f"must be divisible by renderer tile size {tile_width}x{tile_height}. " - "Choose foveated_res and pool_res_mult so the rendered grid satisfies " - "these dimensions, or select a non-tiled Newton render_order." - ) - - def _allocate_pooled_buffers(self) -> None: - """Allocate pooled output tensors; the renderer keeps writing the high-resolution buffers.""" - if self._pooler is None: - return - self._highres_output: dict[str, ProxyArray] = dict(self._data.output) - self._pooled_output: dict[str, torch.Tensor] = {} - for name, tex in self._highres_output.items(): - if name == "rgb" and "rgba" in self._highres_output: - continue # an alias of rgba, below - tensor = tex.torch - B, _, _, C = tensor.shape - self._pooled_output[name] = torch.zeros( - (B, self._num_valid_samples, 1, C), dtype=tensor.dtype, device=tensor.device - ) - # The renderer publishes rgb as a view of rgba whenever either is requested; so does the pooled output. - if "rgb" in self._highres_output and "rgba" in self._pooled_output: - self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] - self._prepare_segmentation_pooling(self._highres_output) - dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} - logger.info( - "FoveatedNewtonCamera: %s pooling (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) outputs=%s", - type(self._pooler).__name__, - self.cfg.pool_mode, - self._pool_k, - self.cfg.pool_sample_cortex, - self._num_ray_samples, - self._num_valid_samples, - dtypes_summary, - ) - - def _update_poses( - self, - env_ids: Sequence[int] | wp.array | None = None, - env_mask: wp.array | None = None, - frame_op: int = 0, - ) -> None: - """Read base poses, turn them by the gaze, update the renderer once, and inject the foveated rays. - - The scene pose is read even without a gaze: the camera may inherit - motion from a parent body. - """ - # The base update turns the poses by the gaze in _update_camera_state, then hands them to the renderer. - Camera._update_poses(self, env_ids, env_mask=env_mask, frame_op=frame_op) - if self._foveated_rays is not None: - self._render_data.camera_rays = self._foveated_rays + rays = self._retinal_rays.new_zeros((self.cfg.height, self.cfg.width, 1, 2, 3)) + rays[..., 1, :] = self._retinal_rays.view(self.cfg.height, self.cfg.width, 1, 3) + # Newton allocates its default rays only once. Replace them before the first capture. + self._render_data.camera_rays = wp.from_torch(rays, dtype=wp.vec3f) + self._render_output = self._data.output + self._prepare_grid_publish({name: value.torch for name, value in self._render_output.items()}) def _update_buffers_impl(self, env_mask: wp.array): - """Render, then mask and publish the updated environments, pooling high-resolution samples if enabled. - - Newton redraws every environment's render buffer, each at the pose and gaze it last received. The sensor mask, - its visibility record and the published buffers, which the camera owns, change only for the updated - environments. - """ - self._data.output.clear() - self._data.output.update(self._render_output) + # Newton's render may redraw every environment. Only publish the rows due for update. + published = self._data.output + self._data._output = self._render_output try: super()._update_buffers_impl(env_mask) finally: - self._data.output.clear() - self._data.output.update(self._public_output) - if not self._env_mask_has_any(env_mask): - return - if self._pooler is None: - if self._grid_publish: - self._publish_grid(env_mask) - else: - self._apply_sensor_fov_mask(self._flat_render_output, env_mask) - for name, samples in self._sample_output.items(): - if name == "rgb" and "rgba" in self._sample_output: - continue # rgba alias - copy_updated_rows(self._flat_render_output[name].torch, samples, env_mask) - return - mask_grid_samples(self._highres_output, self._ray_coords) - self._apply_sensor_fov_mask(self._highres_output, env_mask) - for name, hi in self._highres_output.items(): - if name == "rgb" and "rgba" in self._highres_output: - continue # rgba alias - # Pooling covers every environment; only the updated ones are published. - copy_updated_rows(self._pool_output(name, hi.torch), self._pooled_output[name], env_mask) - if self._native_grid: - copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) + self._data._output = published + self._publish_grid(env_mask) @staticmethod def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 2a6887d041f8..b9136e1bb02c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -3,19 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""RTX foveated tiled camera sensor. - -Subclasses :class:`isaaclab.sensors.Camera` to render foveated images -via the RTX path tracer using ``OmniLensDistortionLutAPI`` textures. -Per-sample values are extracted from the rendered 2D texture to produce -vector ``(B, N, 1, C)`` or upright native-grid ``(B, H, W, C)`` output buffers, -identical to :class:`FoveatedNewtonCamera`. -""" +"""Native foveated lens textures for Isaac RTX and OVRTX.""" from __future__ import annotations import logging -import math import tempfile from collections.abc import Sequence from typing import TYPE_CHECKING @@ -25,45 +17,25 @@ from isaaclab import sim as sim_utils from isaaclab.sensors.camera.camera import Camera -from isaaclab.utils import clone -from isaaclab.utils.math import convert_camera_frame_orientation_convention, matrix_from_quat, quat_from_matrix +from isaaclab.utils.math import ( + convert_camera_frame_orientation_convention, + normalize, + quat_conjugate, + quat_from_matrix, + quat_mul, +) from . import lens_lut -from .calibrated_geometry import compose_rotations, retinal_directions from .foveated_camera import FoveatedCamera -from .native_grid import ( - GRID_STYLE, - allocate_grid_outputs, - copy_grid_outputs, - copy_updated_rows, - grid_sample_indices, - mask_grid_samples, - native_grid_directions, - proxy_outputs, -) -from .pooling import build_highres_coords, build_lowres_coords, build_pooler if TYPE_CHECKING: - from isaaclab.utils.warp import ProxyArray - from .foveated_camera_cfg import FoveatedCameraCfg logger = logging.getLogger(__name__) class FoveatedRTXCamera(FoveatedCamera): - """RTX camera that renders with foveated (CMF-distributed) rays. - - Instead of Newton's Warp ray arrays, this sensor creates - ``OmniLensDistortionLutAPI`` Camera prims with LUT textures that define - per-texel ray directions. The RTX path tracer renders a 2D texture - which is then sampled at pre-computed UV positions to extract per-sample - values, producing ``(B, N, 1, C)`` output buffers. - - Grid styles render straight into their native grid. Sample-set styles are - packed onto a cortical disc, which keeps neighbouring samples adjacent for - DLSS denoising. Camera motion comes from the prim's parent and from the gaze. - """ + """Render the shared retinal grid through an RTX lens lookup texture.""" cfg: FoveatedCameraCfg @@ -74,16 +46,8 @@ def __init__(self, cfg: FoveatedCameraCfg): "OVRTX async_rendering returns the previous capture, which the sensor mask would cut with the current" " gaze. Disable async_rendering or mask_to_sensor_fov." ) - # The parent ``Camera`` allocates the renderer-bound texture buffers; the published ones follow from them. - self._texture_output: dict[str, ProxyArray] = {} - self._foveated_output: dict[str, torch.Tensor] = {} - self._pooled_output: dict[str, torch.Tensor] | None = None - # The projection sets the texture size on the configuration before the parent allocates for it; the caller's - # configuration stays untouched. - cfg = clone(cfg) - self.cfg = cfg - self._prepare_projection() super().__init__(cfg) + self._prepare_projection() # The lens belongs to the camera prims from construction: OVRTX snapshots the stage when the renderer starts. for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): # A locked camera may be treated as static, which skips the motion vectors that DLSS reprojection needs; @@ -120,128 +84,56 @@ def get_world_poses(self, env_ids=None, convention="ros"): """ positions, orientations = super().get_world_poses(env_ids, convention="opengl") if not self._gaze_pose_reads_angles and self._gaze_rotation is not None: - # The prims hold the mount turned by the gaze's rotation in their own (OpenGL) frame. - basis = self._gaze_basis - gaze = self._gaze_rotation.torch[self._env_indices(env_ids)] - with torch.autocast(basis.device.type, enabled=False): - relative = compose_rotations(compose_rotations(basis, gaze), basis.T) - orientations = quat_from_matrix( - compose_rotations(matrix_from_quat(orientations), relative.transpose(-1, -2)) - ) + ids = self._resolve_env_ids_wp(env_ids) + rotation = self._relative_gaze() + if ids is not None: + rotation = rotation[wp.to_torch(ids).long()] + orientations = quat_mul(orientations, quat_conjugate(rotation)) return positions, convert_camera_frame_orientation_convention(orientations, origin="opengl", target=convention) def process_rendered_frame(self) -> None: - """Mask and publish the frame of the environments that scalar or batched rendering updated.""" - if not self._env_mask_has_any(self._is_outdated): - return - if self._grid_publish: - self._publish_grid(self._is_outdated) + """Publish the grid after scalar or batched rendering.""" + env_mask = self._is_outdated + if not self._env_mask_has_any(env_mask): return - # Only the updated environments' samples change, so pooling and the grid layout reproduce every other - # environment's last frame. - self._extract_foveated_samples(self._is_outdated) - mask_grid_samples(self._foveated_output, self._ray_coords) - self._apply_sensor_fov_mask(self._foveated_output, self._is_outdated) - - if self._pooled_output is not None: - for name, hi in self._foveated_output.items(): - if name == "rgb" and "rgba" in self._foveated_output: - continue # rgba alias - self._pooled_output[name].copy_(self._pool_output(name, hi)) - if self._native_grid: - source = self._pooled_output if self._pooled_output is not None else self._foveated_output - copy_grid_outputs(source, self._grid_output, self._grid_indices) + if self._near_clip is not None: + # OVRTX measures distance from the near-clipped ray origin. The scratch is a publication + # source, so this leaves the renderer's bound buffer and unselected public rows untouched. + torch.add(self._distance_source, self._near_clip, out=self._distance_corrected) + self._publish_grid(env_mask) def _prepare_projection(self) -> None: - # The lens textures and sample extraction use the rendered samples: the high-resolution ones when pooling. - self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") - self._sampling_coords_highres = build_highres_coords(self.cfg, self._sampling_coords, matched_res) - ray_coords = self._sampling_coords_highres or self._sampling_coords - self._ray_coords = ray_coords - self._native_grid = self.cfg.foveated_style == GRID_STYLE - self._num_valid_samples = len(self._sampling_coords) - self._num_ray_samples = len(ray_coords) - - # image_rotation_deg rolls each ray's polar angle before its direction is computed; see its configuration. - theta_rad = ray_coords.polar[:, 1].to(torch.float64) - if self.cfg.image_rotation_deg: - theta_rad = theta_rad + math.radians(float(self.cfg.image_rotation_deg)) - if self._native_grid: - dirs = native_grid_directions(ray_coords, image_rotation_deg=self.cfg.image_rotation_deg) - else: - dirs = retinal_directions(ray_coords.cartesian, ray_coords.fov, self.cfg.image_rotation_deg) - - # Grid styles render straight into their native grid; sample-set styles are packed onto a cortical disc, - # which keeps neighbouring samples adjacent for the renderer's spatial filtering. - if self._native_grid: - tw = th = ray_coords.resolution - axis = (torch.arange(tw, dtype=torch.float32) + 0.5) / tw - row, col = torch.meshgrid(axis, axis, indexing="ij") - uv = torch.stack((col, row), -1).reshape(-1, 2) - else: - tw = th = max(64, math.ceil(math.sqrt(4 * self._num_ray_samples / math.pi))) - # Eccentricity [deg] of each sample; the disc is laid out with the same - # field of view and CMF constant the samples were generated with. - eccentricity = ray_coords.polar[:, 0].to(torch.float64) * (ray_coords.fov / 2.0) - uv = lens_lut.samples_uv_cortical_disc( - eccentricity, theta_rad, ray_coords.fov, ray_coords.cmf_a, device="cpu" - ) - self._texture_width = tw - self._texture_height = th - self._sample_uv = uv - - # The exit texture is an octahedral inverse map (ray direction -> sensor NDC) over the hemisphere, of which - # only the camera's field of view is populated. Four times the direction texture's size gives each sample a - # distinct exit texel for the nearest-neighbour lookup. - if self.cfg.exit_texture_size is not None: - EW = EH = self.cfg.exit_texture_size - else: - EW = EH = max(128, 4 * max(tw, th)) - if self._native_grid: - dir_tex, exit_tex = lens_lut.build_native_grid_textures( - ray_coords, image_rotation_deg=self.cfg.image_rotation_deg, exit_size=EW - ) - else: - dir_tex, exit_tex = lens_lut.build_lut_textures(uv, dirs, tw, th, EW, EH, device="cpu") - # The camera owns its textures' directory, which is removed when the camera is released. + exit_size = self.cfg.exit_texture_size + if exit_size is None: + exit_size = max(128, 4 * self.cfg.foveated_res) + direction, exit_texture = lens_lut.build_native_grid_textures( + self._sampling_coords, + self._retinal_rays, + image_rotation_deg=self.cfg.image_rotation_deg, + exit_size=exit_size, + ) self._lut_dir = tempfile.TemporaryDirectory(prefix="rtx_foveated_luts_") self._dir_tex_path, self._exit_tex_path = lens_lut.save_lut_textures( - dir_tex, exit_tex, self._lut_dir.name, "foveated" - ) - logger.info( - "FoveatedRTXCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg, " - "texture %dx%d, exit lookup %dx%d, lookup textures in %s", - self._num_valid_samples, - self._num_ray_samples, - self.cfg.foveated_style, - ray_coords.cmf_a, - ray_coords.fov, - tw, - th, - EW, - EH, - self._lut_dir.name, + direction, exit_texture, self._lut_dir.name, "foveated" ) - # The parent allocates (B, th, tw, C) texture buffers. - self.cfg.height = th - self.cfg.width = tw def _initialize_impl(self) -> None: - tw, th = self._texture_width, self._texture_height - # OVRTX measures distance_to_camera from each camera's near-clipped ray origin, so it needs the near clips. - self._offset_distance = ( - self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self.cfg.data_types - ) - near_clips = None - if self._offset_distance: - prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) - near_clips = [self._near_clipping_distance(prim) for prim in prims] - super()._initialize_impl() + self._initialize_gaze() + if not self._gaze_pose_reads_angles: + _, local_orientation = self._view.get_local_poses() + self._base_local_orientation = local_orientation.torch.clone() + self._gaze_basis_quat = quat_from_matrix(self._gaze_basis) + sources = {name: value.torch for name, value in self._data.output.items()} self._near_clip = None - if near_clips is not None: - self._near_clip = torch.tensor(near_clips, dtype=torch.float32, device=self._device).view(-1, 1, 1, 1) + if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in sources: + near_clips = [self._near_clipping_distance(camera.GetPrim()) for camera in self._sensor_prims] + self._distance_source = sources["distance_to_camera"] + self._near_clip = self._distance_source.new_tensor(near_clips).view(-1, 1, 1, 1) + self._distance_corrected = torch.empty_like(self._distance_source) + sources["distance_to_camera"] = self._distance_corrected + self._prepare_grid_publish(sources) # OVRTX owns its runtime; Kit extensions belong only to Isaac RTX. if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": @@ -252,45 +144,6 @@ def _initialize_impl(self) -> None: if not ext_manager.set_extension_enabled_immediate(ext_name, True): logger.warning("Could not enable Kit extension '%s'; the lens lookup may not render.", ext_name) - self._sampling_coords = self._sampling_coords.to(device=self._device) - if self._sampling_coords_highres is not None: - self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) - self._ray_coords = self._sampling_coords_highres or self._sampling_coords - self._initialize_gaze() - _, local_orientation = self._view.get_local_poses() - self._base_local_orientation = matrix_from_quat(local_orientation.torch).clone() - self._pooler, self._pool_k = build_pooler( - self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) - ) - - # The renderer keeps writing the texture buffers the parent bound to it; the camera publishes others. - self._texture_output = self._data.output - textures = {name: tex.torch for name, tex in self._texture_output.items()} - # A native grid texture already holds the samples in order, so one kernel per output masks it and lays it - # out. OVRTX's camera distance needs its near-plane offset first, and keeps the step-by-step path. - fused = self._native_grid and self._pooler is None and not self._offset_distance - if fused: - count = self._num_ray_samples - samples = {name: tex.reshape(tex.shape[0], count, tex.shape[-1]) for name, tex in textures.items()} - self._grid_output = allocate_grid_outputs(samples, self._sampling_coords) - self._grid_indices = grid_sample_indices(self._sampling_coords) - self._prepare_grid_publish(samples) - published = self._grid_output - else: - if not self._native_grid: - uv_gpu = self._sample_uv.to(self._device) - self._extract_px = (uv_gpu[:, 0] * tw).long().clamp(0, tw - 1) - self._extract_py = (uv_gpu[:, 1] * th).long().clamp(0, th - 1) - self._allocate_foveated_buffers() - published = self._pooled_output if self._pooled_output is not None else self._foveated_output - if self._native_grid: - self._grid_output = allocate_grid_outputs(published, self._sampling_coords) - self._grid_indices = grid_sample_indices(self._sampling_coords) - published = self._grid_output - # ``CameraData.output`` is read-only, so its backing field is replaced. - self._data._output = proxy_outputs(published) - self._set_published_shape(self._data._output) - def _near_clipping_distance(self, prim) -> float: """Near clipping distance [m] of the camera, from its spawn configuration or else its prim.""" if self.cfg.spawn is not None: @@ -300,64 +153,37 @@ def _near_clipping_distance(self, prim) -> float: clipping = UsdGeom.Camera(prim).GetClippingRangeAttr().Get() return float(clipping[0]) if clipping is not None else 0.0 - def _allocate_foveated_buffers(self): - """Allocate (B, N_hi, 1, C) and, when pooling, (B, N_lo, 1, C) buffers from the texture buffers' shapes.""" - has_rgba_alias = "rgba" in self._texture_output - self._foveated_output = {} - for name, buf in self._texture_output.items(): - if name == "rgb" and has_rgba_alias: - continue # an alias of rgba, below - # Texture buffers are ProxyArrays; their Torch view carries the dtype and device. - buf_t = buf.torch - self._foveated_output[name] = torch.zeros( - (self._view.count, self._num_ray_samples, 1, buf_t.shape[-1]), device=buf_t.device, dtype=buf_t.dtype - ) - # The renderer publishes rgb as a view of rgba whenever either is requested; so do the foveated outputs. - if "rgb" in self._texture_output and "rgba" in self._foveated_output: - self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] + def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): + """Move the mount while retaining its relative gaze.""" + super().set_world_poses(positions, orientations, env_ids, convention) + if orientations is not None and not self._gaze_pose_reads_angles: + ids = self._resolve_env_ids_wp(env_ids) + self._mount_written(slice(None) if ids is None else wp.to_torch(ids).long()) - if self._pooler is None: - self._pooled_output = None - return - self._pooled_output = {} - for name, buf in self._foveated_output.items(): - if name == "rgb" and has_rgba_alias: - continue - self._pooled_output[name] = torch.zeros( - (self._view.count, self._num_valid_samples, 1, buf.shape[-1]), device=self._device, dtype=buf.dtype - ) - if "rgb" in self._texture_output and "rgba" in self._pooled_output: - self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] - self._prepare_segmentation_pooling(self._pooled_output) - logger.info( - "FoveatedRTXCamera: %s pooling (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", - type(self._pooler).__name__, - self.cfg.pool_mode, - self._pool_k, - self.cfg.pool_sample_cortex, - self._num_ray_samples, - self._num_valid_samples, - ) + def set_world_poses_from_view(self, eyes, targets, env_ids=None): + """Point the mount at a target while retaining its relative gaze.""" + super().set_world_poses_from_view(eyes, targets, env_ids) + if not self._gaze_pose_reads_angles: + # The base setter leaves rows with a degenerate look-at direction untouched. + moved = (self._as_device_tensor(eyes, 3) != self._as_device_tensor(targets, 3)).any(dim=-1) + ids = self._resolve_env_ids_wp(env_ids) + self._mount_written(moved if ids is None else wp.to_torch(ids).long()[moved]) - def _mount_written(self, env_ids) -> None: - """Save the moved prims' orientations as their bare mounts and write the gaze on top of them again.""" - if self._gaze_pose_reads_angles: - return # The pose update turns the new mount by the gaze. - ids = self._env_indices(env_ids) + def _mount_written(self, ids) -> None: _, local_orientation = self._view.get_local_poses() - self._base_local_orientation[ids] = matrix_from_quat(local_orientation.torch[ids]) + self._base_local_orientation[ids] = local_orientation.torch[ids] if self._gaze_rotation is not None: self._write_gaze_local_pose() + def _relative_gaze(self) -> torch.Tensor: + basis = self._gaze_basis_quat.expand(self._view.count, -1) + gaze = quat_from_matrix(self._gaze_rotation.torch) + return quat_mul(quat_mul(basis, gaze), quat_conjugate(basis)) + def _write_gaze_local_pose(self) -> None: - # Replicator reads camera prims, not update_camera's pose arguments. - # Write when the command arrives, before a visualizer can render the step. - # The saved local base prevents accumulation and preserves parent motion. - basis = self._gaze_basis - with torch.autocast(basis.device.type, enabled=False): - relative = compose_rotations(compose_rotations(basis, self._gaze_rotation.torch), basis.T) - local_orientation = quat_from_matrix(compose_rotations(self._base_local_orientation, relative)) - self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f)) + # Replicator reads camera prims. Write the gaze onto the bare local mount so parent motion is preserved. + orientation = normalize(quat_mul(self._base_local_orientation, self._relative_gaze())) + self._view.set_local_poses(orientations=wp.from_torch(orientation.contiguous(), dtype=wp.vec4f)) def _update_buffers_impl(self, env_mask: wp.array): if not self._env_mask_has_any(env_mask): @@ -366,24 +192,6 @@ def _update_buffers_impl(self, env_mask: wp.array): super()._update_buffers_impl(env_mask) self.process_rendered_frame() - def _extract_foveated_samples(self, env_mask: wp.array): - """Extract the updated environments' per-sample values from the rendered 2D textures into the (B, N, 1, C) - buffers; the other environments keep their last samples.""" - for name in self._texture_output: - if name == "rgb" and "rgba" in self._texture_output: - continue # rgba alias - tex = self._texture_output[name] # (B, th, tw, C) - fov = self._foveated_output[name] # (B, N, 1, C) - tensor = tex.torch - if self._native_grid: - samples = tensor.reshape_as(fov) - else: - samples = tensor[:, self._extract_py, self._extract_px, :].unsqueeze(2) - if self._offset_distance and name == "distance_to_camera": - # OVRTX measures the distance from the near-clipped ray origin. - samples = samples + self._near_clip.to(samples.dtype) - copy_updated_rows(samples, fov, env_mask) - @staticmethod def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: # OVRTX renders the poses the camera hands it, so its pose update turns the gaze. Replicator reads camera diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py index 1f90730b1ec4..c8fccd044385 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -178,43 +178,23 @@ def set_gaze_kernel( rotation[i] = gaze_rotation(angles) -@wp.func -def turn_pose( - i: wp.int32, - gaze: wp.mat33f, - basis: wp.mat33f, - to_opengl: wp.quatf, - to_world: wp.quatf, - to_ros: wp.quatf, - orientation: wp.array(dtype=wp.quatf), - mount: wp.array(dtype=wp.quatf), -): - """Record camera ``i``'s mount in the ROS convention, then turn its world orientation by its gaze.""" - base = orientation[i] - mount[i] = wp.normalize(base * to_ros) - orientation[i] = gaze_pose(base, gaze, basis, to_opengl, to_world) - - @wp.kernel(enable_backward=False) def apply_gaze_kernel( angles_deg: wp.array(dtype=wp.vec2f), basis: wp.mat33f, to_opengl: wp.quatf, to_world: wp.quatf, - to_ros: wp.quatf, mask: wp.array(dtype=wp.bool), use_mask: wp.int32, orientation: wp.array(dtype=wp.quatf), rotation: wp.array(dtype=wp.mat33f), - mount: wp.array(dtype=wp.quatf), ): - """Turn each camera's world orientation by its gaze, or only the masked ones, and record their mounts and gaze - rotations; every other camera keeps the rotation its pose was turned by.""" + """Turn each updated camera and save the rotation used for its capture.""" i = wp.tid() if use_mask == 0 or mask[i]: gaze = gaze_rotation(angles_deg[i]) rotation[i] = gaze - turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount) + orientation[i] = gaze_pose(orientation[i], gaze, basis, to_opengl, to_world) @wp.kernel(enable_backward=False) @@ -223,17 +203,15 @@ def apply_gaze_indexed_kernel( basis: wp.mat33f, to_opengl: wp.quatf, to_world: wp.quatf, - to_ros: wp.quatf, indices: wp.array(dtype=wp.int32), orientation: wp.array(dtype=wp.quatf), rotation: wp.array(dtype=wp.mat33f), - mount: wp.array(dtype=wp.quatf), ): - """Turn the indexed cameras' world orientations by their gaze, and record their mounts and gaze rotations.""" + """Turn the indexed cameras' world orientations by their gaze, and record their gaze rotations.""" i = indices[wp.tid()] gaze = gaze_rotation(angles_deg[i]) rotation[i] = gaze - turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount) + orientation[i] = gaze_pose(orientation[i], gaze, basis, to_opengl, to_world) @wp.func @@ -242,27 +220,6 @@ def sees(ray: wp.vec3f, gaze: wp.mat33f, frame: wp.mat33f, camera: CameraParams) return project_direction(frame * gaze * wp.transpose(frame) * ray, camera)[2] > 0.5 -@wp.kernel(enable_backward=False) -def sensor_visibility_kernel( - rays: wp.array(dtype=wp.vec3f), - rotation: wp.array(dtype=wp.mat33f), - frame: wp.mat33f, - camera: CameraParams, - updated: wp.array(dtype=wp.bool), - valid: wp.array2d(dtype=wp.bool), - hidden: wp.array2d(dtype=wp.bool), -): - """Whether the physical camera sees each rendered ray turned by each updated environment's gaze, and which - updated samples it does not see; other environments keep their last visibility and hide nothing.""" - env, sample = wp.tid() - if not updated[env]: - hidden[env, sample] = False - return - seen = sees(rays[sample], rotation[env], frame, camera) - valid[env, sample] = seen - hidden[env, sample] = not seen - - @wp.kernel(enable_backward=False) def publish_grid_kernel( source: wp.array3d(dtype=wp.uint8), @@ -274,8 +231,6 @@ def publish_grid_kernel( frame: wp.mat33f, camera: CameraParams, mask_to_sensor: wp.int32, - record_visible: wp.int32, - visible: wp.array2d(dtype=wp.bool), target: wp.array3d(dtype=wp.uint8), ): """Copy the updated environments' rendered samples into the upright grid, zeroing samples outside the footprint @@ -288,42 +243,10 @@ def publish_grid_kernel( return sample = indices[cell] keep = footprint[sample] - if mask_to_sensor != 0: - seen = sees(rays[sample], rotation[env], frame, camera) - if record_visible != 0: - visible[env, sample] = seen - keep = keep and seen + if keep and mask_to_sensor != 0: + keep = sees(rays[sample], rotation[env], frame, camera) for k in range(target.shape[2]): if keep: target[env, cell, k] = source[env, sample, k] else: target[env, cell, k] = wp.uint8(0) - - -@wp.kernel(enable_backward=False) -def project_directions_kernel( - directions: wp.array(dtype=wp.vec3f), - camera: CameraParams, - pixels: wp.array(dtype=wp.vec2f), - valid: wp.array(dtype=wp.bool), -): - i = wp.tid() - result = project_direction(directions[i], camera) - pixels[i] = wp.vec2f(result[0], result[1]) - valid[i] = result[2] > 0.5 - - -def project_directions(directions: torch.Tensor, camera: CameraParams) -> tuple[torch.Tensor, torch.Tensor]: - """Project (..., 3) camera-frame directions to (..., 2) pixels and (...,) validity, in one launch.""" - flat = directions.detach().reshape(-1, 3).float().contiguous() - pixels = torch.empty(len(flat), 2, dtype=torch.float32, device=flat.device) - valid = torch.empty(len(flat), dtype=torch.bool, device=flat.device) - if len(flat): - with torch_stream(flat.device): - wp.launch( - project_directions_kernel, - dim=len(flat), - inputs=[wp.from_torch(flat, dtype=wp.vec3f), camera], - outputs=[wp.from_torch(pixels, dtype=wp.vec2f), wp.from_torch(valid, dtype=wp.bool)], - ) - return pixels.reshape(*directions.shape[:-1], 2), valid.reshape(directions.shape[:-1]) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index 383c4f12f14b..520ac075cb39 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -13,7 +13,7 @@ * **rayExitPositionTexture** ``(EW × EH, RG float32)`` Inverse map: given a ray direction (octahedral-encoded over ``[0,1]²``), - returns the sensor NDC ``(u, v)`` of the nearest sample. + returns sensor NDC ``(u, v)`` in the native grid. Isaac RTX and OVRTX both render through this API; the legacy generalized-projection camera attributes are not used. @@ -27,7 +27,6 @@ from __future__ import annotations -import math import os from typing import TYPE_CHECKING @@ -35,7 +34,7 @@ import torch from fovi.sensing.coords import SamplingCoords -from .native_grid import native_grid_directions, native_grid_exit_uv +from .native_grid import native_grid_exit_uv if TYPE_CHECKING: from pxr import Usd @@ -62,96 +61,14 @@ def save_exr(path: str, data: torch.Tensor) -> None: def build_native_grid_textures( - coords: SamplingCoords, *, image_rotation_deg: float, exit_size: int + coords: SamplingCoords, rays: torch.Tensor, *, image_rotation_deg: float, exit_size: int ) -> tuple[torch.Tensor, torch.Tensor]: """Build native direction texels and an analytic octahedral inverse map.""" - directions = native_grid_directions(coords, image_rotation_deg=image_rotation_deg).reshape( - coords.resolution, coords.resolution, 3 - ) decoded = torch.stack(_octahedral_decode(exit_size, exit_size, device=coords.device), -1) uv, valid = native_grid_exit_uv(decoded, coords, image_rotation_deg=image_rotation_deg) # Out-of-sensor rays must not be projected into the fovea by the inverse LUT. exit_texture = torch.where(valid[..., None], uv, torch.full_like(uv, -1)) - return directions, exit_texture - - -def build_lut_textures( - samples_uv: torch.Tensor, - ray_directions: torch.Tensor, - texture_width: int, - texture_height: int, - exit_width: int, - exit_height: int, - chunk: int = 8192, - *, - device: torch.device | str, -) -> tuple[torch.Tensor, torch.Tensor]: - """Build direction and exit LUT tensors from a labelled set of sensor samples. - - Both tensors are filled by **nearest-neighbour assignment**. - - Args: - samples_uv: ``(N, 2)`` float32. NDC ``(u, v)`` per sample. - ray_directions: ``(N, 3)`` float32. Unit ray direction per sample. - texture_width, texture_height: Direction LUT dimensions. - exit_width, exit_height: Exit LUT dimensions. - chunk: NN search batch size. - device: Torch device. - - Returns: - ``(direction_texture, exit_texture)`` — - ``(H, W, 3)`` and ``(EH, EW, 2)`` float32 tensors. - """ - uv_t = _t(samples_uv, torch.float32, device) - dirs_t = _t(ray_directions, torch.float32, device) - N = uv_t.shape[0] - - # Direction texture. - dir_out = torch.zeros(texture_height, texture_width, 3, dtype=torch.float32, device=device) - dir_out[:, :, 2] = -1.0 - - if N > 0: - # Each texel takes the ray of the sample nearest it in UV, whatever order the samples come in. - u_t = (torch.arange(texture_width, dtype=torch.float32, device=device) + 0.5) / texture_width - v_t = (torch.arange(texture_height, dtype=torch.float32, device=device) + 0.5) / texture_height - U = u_t.unsqueeze(0).expand(texture_height, texture_width) - V = v_t.unsqueeze(1).expand(texture_height, texture_width) - texel_uv = torch.stack([U.reshape(-1), V.reshape(-1)], dim=1) - k_nn = _nn_chunk(texel_uv, uv_t, chunk) - dir_out.reshape(-1, 3)[:] = dirs_t[k_nn] - - # Exit texture: only texels whose direction lies within the samples' field (r <= max_r) map to a sample; the rest - # hold the invalid UV (-1, -1), as in native-grid LUTs, so rays outside the field never reach the fovea. - d = dirs_t.to(torch.float64) - r_s = (torch.atan2((d[:, 0] ** 2 + d[:, 1] ** 2).sqrt(), (-d[:, 2]).clamp(min=1e-20)) * (180.0 / math.pi)).float() - th_s = torch.atan2(d[:, 1], d[:, 0]).float() - xs = r_s * th_s.cos() - ys = r_s * th_s.sin() - max_r = float(r_s.max().item()) if N > 0 else 0.0 - - oct_x, oct_y, oct_z = _octahedral_decode(exit_width, exit_height, device=device) - r_q = (torch.atan2((oct_x**2 + oct_y**2).sqrt(), (-oct_z).clamp(min=1e-20)) * (180.0 / math.pi)).float() - th_q = torch.atan2(oct_y.float(), oct_x.float()) - xq = r_q * th_q.cos() - yq = r_q * th_q.sin() - - odz_f = oct_z.float() - valid = (r_q <= max_r) & (odz_f < -1e-9) - - exit_u = torch.full((exit_height, exit_width), -1.0, dtype=torch.float32, device=device) - exit_v = torch.full((exit_height, exit_width), -1.0, dtype=torch.float32, device=device) - - if N > 0 and valid.any(): - sample_cart = torch.stack([xs, ys], dim=1) - vf = valid.reshape(-1) - query_cart = torch.stack([xq.reshape(-1)[vf], yq.reshape(-1)[vf]], dim=1) - k_exit = _nn_chunk(query_cart, sample_cart, chunk) - eu_flat = exit_u.reshape(-1) - ev_flat = exit_v.reshape(-1) - eu_flat[vf] = uv_t[k_exit, 0] - ev_flat[vf] = uv_t[k_exit, 1] - - return dir_out, torch.stack([exit_u, exit_v], dim=2) + return rays.reshape(coords.resolution, coords.resolution, 3), exit_texture def save_lut_textures( @@ -192,37 +109,6 @@ def apply_lens_lut_to_prim( ) -def samples_uv_cortical_disc( - r_deg, - theta_rad, - fov_deg: float, - cmf_a: float, - device: torch.device | str, -) -> torch.Tensor: - """Map samples to NDC using the cortical polar disc layout. - - ``ρ = log((r + a) / a)``, mapped to a centered disc. - Foveal centre ``r=0`` → disc centre ``(0.5, 0.5)``. - - Returns: - ``(N, 2)`` float32 NDC tensor. - """ - rho_max = math.log((fov_deg / 2.0 + cmf_a) / cmf_a) - r = _t(r_deg, torch.float64, device) - th = _t(theta_rad, torch.float64, device) - rho = ((r + cmf_a) / cmf_a).clamp(min=1e-30).log() - u = (rho * th.cos() / (2.0 * rho_max) + 0.5).float() - v = (-rho * th.sin() / (2.0 * rho_max) + 0.5).float() - return torch.stack([u, v], dim=1) - - -def _t(x, dtype: torch.dtype, device) -> torch.Tensor: - """Convert array-like or tensor *x* to a ``torch.Tensor`` on *device*.""" - if isinstance(x, torch.Tensor): - return x.to(dtype=dtype, device=device) - return torch.as_tensor(np.asarray(x), dtype=dtype, device=device) - - def _octahedral_decode( width: int, height: int, @@ -244,22 +130,3 @@ def _octahedral_decode( dy = torch.where(dz <= 0.0, (1.0 - px.abs()) * sy, py) n = torch.clamp((dx**2 + dy**2 + dz**2).sqrt(), min=1e-20) return dx / n, dy / n, -dz / n - - -def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tensor: - """Chunked nearest-neighbour search via ``torch.cdist``. - - Chunk size is capped so the float32 distance matrix stays within 2 GiB. - - Returns: - ``(M,)`` int64 index of the closest key for each query row. - """ - N = keys.shape[0] - safe_chunk = max(1, (2 << 30) // (4 * max(N, 1))) - effective = min(chunk, safe_chunk) - M = query.shape[0] - idx = torch.empty(M, dtype=torch.long, device=query.device) - for s in range(0, M, effective): - e = min(s + effective, M) - idx[s:e] = torch.cdist(query[s:e], keys).argmin(dim=1) - return idx diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py index 459bdb690094..de7c5a9c76f0 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py @@ -8,54 +8,10 @@ from __future__ import annotations import math -from collections.abc import Mapping -from typing import Protocol import torch -import warp as wp from fovi.sensing.coords import SamplingCoords - -from isaaclab.utils.warp import ProxyArray -from isaaclab.utils.warp.memory import make_masked_copy - -from .gaze_kernels import warp_stream - -GRID_STYLE = "warped_cartesian_as_grid" - - -def buffer_tensor(value: torch.Tensor | TorchBuffer) -> torch.Tensor: - """Get a renderer or public tensor without copying.""" - return value if isinstance(value, torch.Tensor) else value.torch - - -def proxy_outputs(outputs: Mapping[str, torch.Tensor | ProxyArray]) -> dict[str, ProxyArray]: - """Wrap output buffers as zero-copy :class:`ProxyArray` values, as :class:`CameraData` publishes them.""" - return { - name: ProxyArray(wp.from_torch(value)) if isinstance(value, torch.Tensor) else value - for name, value in outputs.items() - } - - -def copy_updated_rows(source: torch.Tensor, target: torch.Tensor, rows: wp.array) -> None: - """Copy the environments that ``rows`` selects from ``source`` into ``target``, shape (num_envs, N, 1, C). - - The other environments keep their values. The masked copy needs no full-batch temporary and no host sync. - - Args: - source: The new samples; may be a strided view. - target: The published samples, written in place. - rows: Which environments to copy, shape (num_envs,) of ``bool``. - """ - source3, target3 = source.squeeze(2), target.squeeze(2) - dtype = wp.dtype_from_torch(target.dtype) - wp.launch( - make_masked_copy(dtype, 3), - dim=tuple(target3.shape), - inputs=[wp.from_torch(source3, dtype=dtype), rows, None], - outputs=[wp.from_torch(target3, dtype=dtype)], - device=str(target.device), - stream=warp_stream(target.device), - ) +from fovi.sensing.projection import angular_directions def bounded_angular_radius(radius: torch.Tensor, half_fov_rad: float) -> torch.Tensor: @@ -86,21 +42,17 @@ def native_grid_directions(coords: SamplingCoords, *, image_rotation_deg: float Grid radius is proportional to visual angle, and the padding outside the nominal field continues toward the antipode without wrapping. """ - _require_spherical(coords) + cartesian = coords.cartesian.to(torch.float64) radius = torch.linalg.vector_norm(cartesian, dim=-1) - boundary_radius, boundary_angle = _angular_padding_boundary(coords) - angle = bounded_angular_radius(radius / boundary_radius, boundary_angle) - scale = torch.where(radius > 0, angle.sin() / radius.clamp_min(1e-30), angle.new_zeros(())) - xy = cartesian * scale[:, None] - z = -angle.cos() + half_fov = math.radians(coords.fov) / 2 + padded_radius = bounded_angular_radius(radius, half_fov) / half_fov + scale = torch.where(radius > 0, padded_radius / radius.clamp_min(1e-30), 1.0) + rays = angular_directions(cartesian * scale[:, None], coords.fov) + x, y, z = rays.unbind(-1) angle = math.radians(image_rotation_deg) - x, y = xy.unbind(-1) - rays = torch.stack( - (math.cos(angle) * x - math.sin(angle) * y, math.sin(angle) * x + math.cos(angle) * y, z), - -1, - ) - return torch.nn.functional.normalize(rays, dim=-1).float() + c, s = math.cos(angle), math.sin(angle) + return torch.stack((c * x + s * y, s * x - c * y, -z), -1).float() def native_grid_exit_uv( @@ -111,99 +63,15 @@ def native_grid_exit_uv( Texture rows and columns follow canonical vector order: native x then y. The public image applies Fovi's upright grid permutation after rendering. """ - _require_spherical(coords) angle = math.radians(image_rotation_deg) x, y, z = directions.to(torch.float64).unbind(-1) xy = torch.stack((math.cos(angle) * x + math.sin(angle) * y, -math.sin(angle) * x + math.cos(angle) * y), -1) lateral = torch.linalg.vector_norm(xy, dim=-1) theta = torch.atan2(lateral, -z) - boundary_radius, boundary_angle = _angular_padding_boundary(coords) - radius = unbounded_angular_radius(theta, boundary_angle) * boundary_radius + radius = unbounded_angular_radius(theta, math.radians(coords.fov) / 2) cartesian = xy * (radius / lateral.clamp_min(1e-30))[..., None] visible = theta < math.pi - 1e-8 native = coords.visual_to_native(cartesian) uv = (native.flip(-1) + 1) / 2 visible = visible & (uv >= 0).all(-1) & (uv <= 1).all(-1) return uv.float(), visible - - -def grid_output_shape(coords: SamplingCoords) -> tuple[int, int]: - """Resolve public image dimensions, preserving vector cameras' shape.""" - if coords.style == GRID_STYLE: - return coords.resolution, coords.resolution - return len(coords), 1 - - -def mask_grid_samples(outputs: Mapping[str, torch.Tensor | TorchBuffer], coords: SamplingCoords) -> None: - """Zero samples outside the configured footprint before pooling or publication.""" - if coords.style != GRID_STYLE: - return - invalid = ~coords.valid_mask[None, :, None, None] - for name, value in outputs.items(): - if name == "rgb" and "rgba" in outputs: - continue - tensor = buffer_tensor(value) - tensor.masked_fill_(invalid, 0) - - -def allocate_grid_outputs( - outputs: Mapping[str, torch.Tensor | TorchBuffer], coords: SamplingCoords -) -> dict[str, torch.Tensor]: - """Allocate stable public BHWC buffers from flat renderer outputs.""" - result: dict[str, torch.Tensor] = {} - for name, value in outputs.items(): - if name == "rgb" and "rgba" in outputs: - continue - tensor = buffer_tensor(value) - result[name] = tensor.new_zeros((tensor.shape[0], coords.resolution, coords.resolution, tensor.shape[-1])) - if "rgb" in outputs and "rgba" in result: - result["rgb"] = result["rgba"][..., :3] - return result - - -def grid_sample_indices(coords: SamplingCoords) -> torch.Tensor: - """Resolve the public image permutation once, outside rendering updates.""" - return coords.as_grid(torch.arange(len(coords), device=coords.device)).reshape(-1) - - -def copy_grid_outputs( - source: Mapping[str, torch.Tensor | TorchBuffer], - target: dict[str, torch.Tensor], - indices: torch.Tensor, -) -> None: - """Update stable public image buffers without changing sample ordering.""" - for name, value in source.items(): - if name == "rgb" and "rgba" in source: - continue - tensor = buffer_tensor(value) - flat_source = tensor.reshape(tensor.shape[0], -1, tensor.shape[-1]) - flat_target = target[name].view(tensor.shape[0], -1, tensor.shape[-1]) - torch.index_select(flat_source, 1, indices, out=flat_target) - - -class TorchBuffer(Protocol): - """Renderer buffer exposing a Torch view.""" - - @property - def torch(self) -> torch.Tensor: ... - - -def _require_spherical(coords: SamplingCoords) -> None: - if coords.field_geometry != "spherical": - raise ValueError(f"Foveated cameras sample spherical coordinates, got {coords.field_geometry!r}.") - - -def _angular_padding_boundary(coords: SamplingCoords) -> tuple[float, float]: - if coords.fov_type == "circular": - radius = 1.0 - elif coords.fov_type == "square": - radius = math.sqrt(2) - elif coords.fov_type == "wang": - corner = coords.cartesian.new_tensor([[1.0, 1.0]]) - radius = float(torch.linalg.vector_norm(coords.native_to_visual(corner)).item()) - else: - raise ValueError(f"Unsupported native grid footprint {coords.fov_type!r}.") - angle = radius * math.radians(coords.fov) / 2 - if angle >= math.pi: - raise ValueError("Spherical native grid footprint reaches the antipode; reduce FoV or use circular coverage.") - return radius, angle diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py deleted file mode 100644 index c7093b517c9b..000000000000 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ /dev/null @@ -1,282 +0,0 @@ -# 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 - -"""Shared retinal-pooling helpers for FoveatedCamera backends. - -Builds a pair of (lowres, highres) :class:`SamplingCoords` and a retinal -pooler analogous to :class:`fovi.sensing.samplers.PoolingGridSampler`, but driven by a -:class:`FoveatedCameraCfg` and operating on rays rather than images. - -Key deviation from ``PoolingGridSampler``: the highres grid shares ``cmf_a`` with -the lowres grid (no ``cmf_a_mult``). Only ``res`` is scaled by -``pool_res_mult`` so the photoreceptor and RGC layers represent the same -visual-field geometry at different densities. - -Construction happens in two stages to accommodate Isaac's sensor init order: -1. ``build_lowres_coords`` + ``build_highres_coords`` run *before* - ``super()._initialize_impl()`` (CPU) so the backend can size its render - buffers from the highres sample count. -2. ``build_pooler`` runs *after* coords have been moved to the sensor's - device, so the KNN indices/distances/Gaussian weights materialise on the - correct device (they are plain tensor attributes and are not moved by - ``nn.Module.to``). -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -import torch -from fovi.arch.knn import KNNPoolingLayer -from fovi.arch.pooling import GridPoolingLayer, build_retinal_pooler -from fovi.sensing.coords import SamplingCoords, auto_match_num_coords - -from .calibrated_geometry import sampling_geometry - -if TYPE_CHECKING: - from .foveated_camera_cfg import FoveatedCameraCfg - - -# Upper bound on ``batch * outputs * k`` elements per modal-pooling chunk. Each chunk holds about ten -# int64 tensors of this size, so peak scratch memory stays near 300 MB regardless of the batch size. -_MODAL_CHUNK_ELEMENTS = 2**22 - - -def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCoords, int]: - """Build the lowres (RGC / public output) SamplingCoords. - - Returns ``(lowres_coords, matched_res)`` where ``matched_res`` is the - auto-matched radial resolution also needed for the highres grid. - """ - fov, cmf_a = sampling_geometry(cfg) - - matched_res, _ = auto_match_num_coords( - fov, - cmf_a, - cfg.foveated_res, - cfg.foveated_style, - 1, - device, - quiet=True, - fov_type=cfg.fov_type, - radius_norm=cfg.radius_norm, - field_geometry="spherical", - ) - lowres = SamplingCoords( - fov=fov, - cmf_a=cmf_a, - res=matched_res, - device=device, - style=cfg.foveated_style, - isotropic_plotting_type=cfg.isotropic_plotting_type, - fov_type=cfg.fov_type, - radius_norm=cfg.radius_norm, - field_geometry="spherical", - ) - return lowres, matched_res - - -def build_highres_coords(cfg: FoveatedCameraCfg, lowres: SamplingCoords, matched_res: int) -> SamplingCoords | None: - """Build the highres (photoreceptor) SamplingCoords when pooling is on: the lowres retina's geometry at - ``pool_res_mult`` times its resolution, on the same device.""" - if not cfg.pool_enabled: - return None - # pool_res_mult is a float to support fractional ratios (e.g. sqrt(2) for - # a 2× N_hi/N_lo ratio). SamplingCoords requires an integer radial res. - return lowres.clone(resolution=int(round(cfg.pool_res_mult * matched_res))) - - -def build_pooler( - cfg: FoveatedCameraCfg, - lowres: SamplingCoords, - highres: SamplingCoords | None, - device: str, -) -> tuple[KNNPoolingLayer | GridPoolingLayer | None, int | None]: - """Build the retinal pooling layer of ``cfg.pool_mode``, which pools every output except segmentation. Both coord - sets must already be on ``device``. - - Segmentation pools by modal label over this pooler's neighbourhoods: pass :func:`segmentation_neighbor_indices` of - it to :func:`pool_segmentation_buffer`. - """ - if highres is None: - return None, None - return build_retinal_pooler( - highres, - lowres, - k=cfg.pool_k, - mode=cfg.pool_mode, - device=device, - sample_cortex=cfg.pool_sample_cortex, - gauss_sigma=cfg.pool_gauss_sigma, - ) - - -def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer) -> torch.Tensor: - """Return a pooler's ``(k, N_lo)`` neighbour table in tie-break order. - - Entries are input-sample indices; ``N_hi`` (the number of input samples) - marks a neighbour excluded by the pooler (spatial padding or a masked input - sample), and every slot of a masked output sample is excluded. - - * :class:`KNNPoolingLayer`: its padded KNN indices, nearest neighbour first. - * :class:`GridPoolingLayer`: the samples in each pooling window (same - padding, stride and masks as the pooler), ordered by distance from the - window centre and then in row-major window order. - """ - if isinstance(pooler, KNNPoolingLayer): - return pooler.knn_indices_pad_token - if not isinstance(pooler, GridPoolingLayer): - raise TypeError(f"Modal pooling needs a KNN or grid pooler, got {type(pooler).__name__}") - - num_inputs = len(pooler.in_coords) - device = pooler.input_mask.device - # Pool sample indices (float64 is exact for any realistic count) with the pooler's own padding; - # -1 marks padding and masked samples. - grid = pooler.in_coords.as_grid(torch.arange(num_inputs, device=device, dtype=torch.float64)[None, None]) - grid = pooler._pad(torch.where(pooler.input_mask, grid, -1.0), -1.0) - side, stride = pooler.kernel_size, pooler.stride - windows = grid[0, 0].unfold(0, side, stride).unfold(1, side, stride) # (H_lo, W_lo, side, side) - windows = windows.flatten(-2).permute(2, 0, 1) # (k, H_lo, W_lo) - axis = torch.arange(side, device=device, dtype=torch.float64) - (side - 1) / 2 - radius = (axis[:, None].square() + axis[None, :].square()).flatten() - windows = windows[torch.sort(radius, stable=True).indices] - windows = torch.where(pooler.output_mask[0], windows, -1.0) - if not pooler.polar: - # Invert the upright Cartesian layout produced by ``as_grid``, as GridPoolingLayer.forward does. - windows = windows.flip(-2).transpose(-2, -1) - indices = windows.flatten(-2).long() - return torch.where(indices < 0, num_inputs, indices) - - -def is_segmentation_output(name: str) -> bool: - """Whether a sensor output holds segmentation labels, which pool with ``pool_int_mode``, the modal label - (:func:`pool_segmentation_buffer`). - - Uses the key name (``"segmentation" in name``) rather than the dtype: every Isaac Lab segmentation variant - (``semantic_segmentation``, ``instance_segmentation_fast``, ``instance_id_segmentation_fast``) holds labels that - averaging would corrupt, whether stored as integer IDs or colorized RGBA. - """ - return "segmentation" in name - - -def pool_hwc_buffer( - pooler: KNNPoolingLayer | GridPoolingLayer, buf: torch.Tensor, visible: torch.Tensor | None = None -) -> torch.Tensor: - """Pool a ``(B, N_hi, 1, C)`` sensor buffer into ``(B, N_lo, 1, C)``. - - Both poolers expect ``(B, C, N)`` inputs, so we permute in and out. - - Args: - pooler: The retinal pooler. - buf: ``(B, N_hi, 1, C)`` floating-point samples. - visible: ``(B, N_hi)`` photoreceptors the physical camera sees, or None for all. The others are left out of - each pooled sample, as the pooler leaves out photoreceptors outside the retina, and a pooled sample that - sees none is zero. - """ - B, N_hi, one, C = buf.shape - assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}" - x = buf[:, :, 0, :].transpose(1, 2).contiguous() # (B, C, N_hi) - if visible is None: - y = pooler(x) # (B, C, N_lo) - else: - seen = visible[:, None, :] - weight = seen.to(x.dtype) - if pooler.mode == "sum": - y = pooler(x * weight) - else: - # Pool the samples with their visibility in one call: a weighted mean over the visible photoreceptors is - # the pooled masked samples over the pooled mask, and a max over them ignores -inf. - masked = torch.where(seen, x, -torch.inf) if pooler.mode == "max" else x * weight - pooled = pooler(torch.cat((masked, weight), dim=1)) - values, coverage = pooled[:, :C], pooled[:, C:] - if pooler.mode != "max": - values = values / coverage.clamp_min(torch.finfo(x.dtype).tiny) - y = torch.where(coverage > 0, values, 0) - return y.transpose(1, 2).unsqueeze(2).contiguous() # (B, N_lo, 1, C) - - -def pool_segmentation_buffer( - neighbors: torch.Tensor, buf: torch.Tensor, visible: torch.Tensor | None = None -) -> torch.Tensor: - """Pool a ``(B, N_hi, 1, C)`` segmentation buffer into ``(B, N_lo, 1, C)`` by majority vote. - - Each output sample takes the most common full channel vector among its - pooling neighbours (so neighbours ``[0, 0, 0]``, ``[0, 0, 0]``, - ``[0, 0, 1]`` give ``[0, 0, 0]``), keeping the buffer's dtype: values are - compared bitwise and copied from an input sample, never converted or mixed. - This holds for integer IDs of any width and for colorized RGBA vectors. - - Ties go to the value whose first occurrence comes earliest in the pooler's - neighbour order (see :func:`segmentation_neighbor_indices`; the nearest - neighbour wins for KNN pooling). Neighbours the pooler excludes, or the - physical camera does not see, do not vote, and outputs without any valid - neighbour are zero, as in fovi. - - Args: - neighbors: ``(k, N_lo)`` neighbour table from :func:`segmentation_neighbor_indices`, on the buffer's device. - buf: ``(B, N_hi, 1, C)`` buffer of any dtype. - visible: ``(B, N_hi)`` photoreceptors the physical camera sees, or None for all. - - Returns: - ``(B, N_lo, 1, C)`` pooled buffer with the dtype of ``buf``. - """ - B, N_hi, one, C = buf.shape - assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}" - indices = neighbors # (k, N_lo), N_hi = excluded - k, N_lo = indices.shape - values = buf[:, :, 0, :].contiguous() # (B, N_hi, C) - # Equality keys, padded with one never-voting sample at index N_hi. - keys = torch.nn.functional.pad(_equality_keys(values), (0, 1)) # (B, N_hi + 1) - valid = (indices != N_hi).T # (N_lo, k) - table = indices.T # (N_lo, k) - chunk_size = max(1, _MODAL_CHUNK_ELEMENTS // max(1, N_lo * k)) - # Visibility, padded like the keys; the never-voting sample is unseen. - seen = None if visible is None else torch.nn.functional.pad(visible, (0, 1)).split(chunk_size) - slots = [] - for index, chunk in enumerate(keys.split(chunk_size)): - chunk_valid = valid if seen is None else valid & seen[index][:, table] # (N_lo, k) or (b, N_lo, k) - slots.append(_modal_slot(chunk[:, table], chunk_valid)) - slot = torch.cat(slots) # (B, N_lo); k where no neighbour is valid - has_value = slot < k - # (B, N_lo) input sample index; outputs without a value read sample 0 and are zeroed below. - source = table.gather(1, slot.clamp(max=k - 1).T).T.clamp(max=N_hi - 1) - pooled = values.gather(1, source.unsqueeze(-1).expand(-1, -1, C)) - pooled = torch.where(has_value.unsqueeze(-1), pooled, torch.zeros((), dtype=buf.dtype, device=buf.device)) - return pooled.unsqueeze(2) - - -def _equality_keys(values: torch.Tensor) -> torch.Tensor: - """Map ``(B, N, C)`` channel vectors to ``(B, N)`` int64 keys that are equal iff the vectors are bitwise equal. - - Vectors of at most 8 bytes are packed into the key directly; wider vectors - fall back to dense ranks from :func:`torch.unique`. - """ - B, N, _ = values.shape - raw = values.view(torch.uint8) if values.dtype != torch.bool else values.to(torch.uint8) - num_bytes = raw.shape[-1] - if num_bytes <= 8: - return torch.nn.functional.pad(raw, (0, 8 - num_bytes)).view(torch.int64).reshape(B, N) - return torch.unique(raw.reshape(B * N, num_bytes), dim=0, return_inverse=True)[1].reshape(B, N) - - -def _modal_slot(keys: torch.Tensor, valid: torch.Tensor) -> torch.Tensor: - """Pick the modal neighbour slot of ``(B, N_lo, k)`` keys; ``valid`` is the ``(N_lo, k)`` or ``(B, N_lo, k)`` - voting mask. - - Returns the ``(B, N_lo)`` earliest slot holding the most common valid key, - or ``k`` where no slot is valid. - """ - k = keys.shape[-1] - sorted_keys, order = torch.sort(keys, dim=-1) - # Label equal-key runs in sorted order, then count valid votes and find the earliest valid slot per run. - new_run = torch.ones_like(sorted_keys, dtype=torch.bool) - new_run[..., 1:] = sorted_keys[..., 1:] != sorted_keys[..., :-1] - run = new_run.cumsum(-1) - 1 - valid_sorted = valid.expand_as(order).gather(-1, order) - votes = torch.zeros_like(run).scatter_add_(-1, run, valid_sorted.long()) - earliest = torch.full_like(run, k).scatter_reduce_(-1, run, torch.where(valid_sorted, order, k), "amin") - # Most votes first, then earliest slot; runs without valid votes score zero. - best = (votes * (k + 1) + (k - earliest)).argmax(-1, keepdim=True) - return earliest.gather(-1, best).squeeze(-1) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 001403d620f1..df6b8c4c88fa 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""The gaze action, its observation and its teacher, without a simulator.""" +"""The gaze action, its observation, without a simulator.""" import math from types import SimpleNamespace @@ -11,38 +11,14 @@ import pytest import torch import warp as wp -from fovi.sensing.projection import CameraModel -from isaaclab_fovi.mdp.gaze import ( - GazeAction, - gaze_reset_kernel, - gaze_state, - gaze_step_kernel, - teacher_block_dim, - teacher_labels_kernel, -) +from isaaclab_fovi.mdp.gaze import GazeAction, gaze_state, gaze_step_kernel from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg -from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream +from isaaclab_fovi.sensors.gaze_kernels import torch_stream -from isaaclab.test.utils import DeviceScope, test_devices -from isaaclab.utils.math import quat_apply, quat_apply_inverse from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless -DEVICES = test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA) - - -def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: - """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3): up and left are positive.""" - tilt, pan = angles_deg.deg2rad().unbind(-1) - return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) - - -def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: - """Gaze angles [deg] of camera-frame directions, shape (..., 3) to (..., 2): the reference for the kernels.""" - x, y, z = direction.unbind(-1) - return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg() - def clamp_gaze(gaze: torch.Tensor, limit: float) -> torch.Tensor: """Gazes scaled back onto the circle of radius ``limit`` when they leave it: the reference for the step kernel.""" @@ -79,131 +55,9 @@ def test_gaze_step_kernel_matches_the_torch_update(): torch.testing.assert_close(angles, expected * radius, atol=1e-5, rtol=1e-6) -def mount_frame(rotation_deg: float) -> torch.Tensor: - """The camera's ``_mask_frame`` for an image rolled by ``rotation_deg``: upright gaze frame to physical frame.""" - angle = torch.tensor(rotation_deg).deg2rad() - c, s = float(angle.cos()), float(angle.sin()) - return torch.tensor([[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]]) - - -# The kernel's block size depends on the device; the image roll is rotated across the two. -TEACHER_CASES = [("cpu", 0.0)] + [(device, 35.0) for device in DEVICES if device != "cpu"] - - -@pytest.mark.parametrize(("device", "rotation_deg"), TEACHER_CASES) -def test_teacher_labels_kernel_matches_the_torch_labels(device, rotation_deg): - camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5), distortion=(-0.1, 0.02, 0.0, 0.0)) - field_radius, step, limit = 30.0, 0.1, 1.0 - frame = mount_frame(rotation_deg) - generator = torch.Generator().manual_seed(5) - count = 4099 - # Each camera has its own mount, as on a moving head. - mount = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1) - positions = torch.randn(count, 3, generator=generator) - lateral = torch.randn(count, 2, generator=generator) * 0.6 - local = torch.cat((lateral, torch.rand(count, 1, generator=generator) + 0.2), -1) - targets = positions + quat_apply(mount, local) - orientations = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1) - offset = torch.tensor([0.0, 0.0, 0.3]) - gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.7 - - # The torch path the kernel replaces: the point fixed to each target, the teacher, then the labels and logs. - points = targets + quat_apply(orientations, offset.expand(count, -1)) - direction = torch.nn.functional.normalize(quat_apply_inverse(mount, points - positions), dim=-1) - - def teachable(direction: torch.Tensor) -> torch.Tensor: - # Gazes are measured in the upright image frame, which the frame carries into the physical camera's. - desired = direction_to_angles(direction @ frame) / field_radius - return camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) - - upright = direction @ frame - desired = direction_to_angles(upright) / field_radius - valid = teachable(direction) - # A target within 1e-4 rad of the image edge, the lens's widest angle or the gaze limit may land on either side - # in float32; every other target must agree exactly. - nudges = 1e-4 * torch.cat((torch.eye(3), -torch.eye(3))) - decisive = torch.stack( - [teachable(torch.nn.functional.normalize(direction + nudge, dim=-1)) == valid for nudge in nudges] - ).all(0) - action = torch.where(valid[:, None], ((desired - gaze) / step).clamp(-1, 1), 0.0) - looking = angles_to_direction(gaze * field_radius) - error = torch.atan2(torch.cross(looking, upright, dim=-1).norm(dim=-1), (looking * upright).sum(-1)).rad2deg() - expected = torch.cat((action, valid[:, None].float()), dim=-1) - - labels = torch.empty(count, 3, device=device) - log = torch.full((2,), float("nan"), device=device) - block = teacher_block_dim(device) - with torch_stream(device): - wp.launch( - teacher_labels_kernel, - dim=(1, block), - inputs=[ - wp.from_torch(targets.to(device), dtype=wp.vec3f), - wp.from_torch(orientations.to(device), dtype=wp.quatf), - wp.vec3f(*offset.tolist()), - wp.from_torch(positions.to(device), dtype=wp.vec3f), - wp.from_torch(mount.to(device), dtype=wp.quatf), - wp.from_torch((gaze * field_radius).to(device), dtype=wp.vec2f), - wp.mat33f(*frame.flatten().tolist()), - field_radius, - step, - limit, - camera_params(camera), - ], - outputs=[wp.from_torch(labels), wp.from_torch(log)], - block_dim=block, - ) - labels, log = labels.cpu(), log.cpu() - assert valid[decisive].any() and (~valid[decisive]).any() and decisive.float().mean() > 0.99 - torch.testing.assert_close(labels[decisive], expected[decisive], atol=1e-4, rtol=0) - labelled = labels[:, 2] > 0.5 - assert float(log[1]) == pytest.approx(float(labelled.float().mean())) - assert float(log[0]) == pytest.approx(float(error[labelled].mean()), rel=1e-4) - - -def test_teacher_gaze_fixates_the_target_through_a_rolled_mount(): - """Following a teacher label puts the fixation, which reaches the physical camera at frame * gaze * z, on the - target.""" - rotation_deg = 120.0 - camera = CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5)) - field_radius, step = 40.0, 10.0 - frame = mount_frame(rotation_deg) - direction = torch.nn.functional.normalize(torch.tensor([[0.25, -0.15, 1.0], [-0.3, 0.2, 1.0]]), dim=-1) - count = len(direction) - identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]]).repeat(count, 1) - labels, log = torch.empty(count, 3), torch.empty(2) - with torch_stream("cpu"): - wp.launch( - teacher_labels_kernel, - dim=(1, 1), - inputs=[ - wp.from_torch(direction, dtype=wp.vec3f), - wp.from_torch(identity, dtype=wp.quatf), - wp.vec3f(0.0, 0.0, 0.0), - wp.zeros(count, dtype=wp.vec3f), - wp.from_torch(identity, dtype=wp.quatf), - wp.zeros(count, dtype=wp.vec2f), - wp.mat33f(*frame.flatten().tolist()), - field_radius, - step, - 1.0, - camera_params(camera), - ], - outputs=[wp.from_torch(labels), wp.from_torch(log)], - block_dim=1, - ) - assert (labels[:, 2] == 1).all() - gaze = labels[:, :2] * step - fixation = angles_to_direction(gaze * field_radius) @ frame.T - torch.testing.assert_close(fixation, direction, atol=1e-5, rtol=0) - # The error is the gaze's angle from the target before the step: the gaze starts on the optical axis. - torch.testing.assert_close(log[0], direction[:, 2].acos().rad2deg().mean(), atol=1e-3, rtol=0) - - -def test_gaze_config_rejects_bounds_that_divide_by_zero_and_unknown_mounts(): +def test_gaze_config_rejects_invalid_bounds(): GazeActionCfg(asset_name="camera").validate_config() - GazeActionCfg(asset_name="camera", mount="tracked").validate_config() - for field, value in (("step_size", 0.0), ("step_size", float("nan")), ("gaze_limit", math.inf), ("mount", "head")): + for field, value in (("step_size", 0.0), ("step_size", float("nan")), ("gaze_limit", math.inf)): cfg = GazeActionCfg(asset_name="camera") setattr(cfg, field, value) with pytest.raises(ValueError, match=field): @@ -224,22 +78,22 @@ def test_process_actions_moves_the_gaze_by_the_supplied_actions(): term._asset = camera term.field_radius_deg = 20.0 term._state = ProxyArray(wp.zeros(num_envs, dtype=wp.vec4f, device="cpu")) - term._velocity = term._state.torch[:, 2:] + term._all_ids = wp.array(list(range(num_envs)), dtype=wp.int32, device="cpu") term._step_launch = term._raw = None manager_actions = torch.zeros(num_envs, 5) manager_actions[:, 2:4] = torch.tensor([[1.0, 0.0], [0.0, -1.0], [0.5, 0.5], [3.0, 0.0]]) term.process_actions(manager_actions[:, 2:4]) expected = clamp_gaze(manager_actions[:, 2:4].clamp(-1, 1) * 0.1, 1.0) - torch.testing.assert_close(term.gaze, expected) - torch.testing.assert_close(term.velocity, expected / 0.5) + torch.testing.assert_close(term.processed_actions, expected) + torch.testing.assert_close(term.state[:, 2:], expected / 0.5) torch.testing.assert_close(angles.torch, expected * 20.0) assert set_angles[-1] is angles.torch assert term.raw_actions.data_ptr() == manager_actions[:, 2:4].data_ptr() supplied = torch.tensor([[-1.0, 0.0]]).repeat(num_envs, 1) term.process_actions(supplied) - torch.testing.assert_close(term.gaze, clamp_gaze(expected - 0.1 * supplied.abs(), 1.0)) + torch.testing.assert_close(term.processed_actions, clamp_gaze(expected - 0.1 * supplied.abs(), 1.0)) assert term.raw_actions is supplied torch.testing.assert_close( gaze_state(SimpleNamespace(action_manager=SimpleNamespace(get_term=lambda name: term))), term.state @@ -248,47 +102,11 @@ def test_process_actions_moves_the_gaze_by_the_supplied_actions(): # A gaze set on the camera directly is where the next step starts. angles.torch.copy_(torch.tensor([[10.0, 0.0]]).repeat(num_envs, 1)) term.process_actions(torch.zeros(num_envs, 2)) - torch.testing.assert_close(term.gaze, torch.tensor([[0.5, 0.0]]).repeat(num_envs, 1)) - - -@pytest.mark.parametrize(("ids", "random_start"), [(None, False), ([3, 0, 7], True)]) -def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): - count, radius = 10, 23.6 - generator = torch.Generator().manual_seed(6) - angles, state = (torch.randn(count, size, generator=generator) for size in (2, 4)) - selected = torch.arange(count) if ids is None else torch.tensor(ids) - start = torch.randn(len(selected), 2, generator=generator) if random_start else torch.zeros(len(selected), 2) - expected_angles, expected_state = angles.clone(), state.clone() - # The torch reset the kernel replaces: the gaze at its start, at rest. - expected_state[selected] = torch.cat((start, torch.zeros_like(start)), dim=-1) - expected_angles[selected] = start * radius - - with torch_stream("cpu"): - wp.launch( - gaze_reset_kernel, - dim=len(selected), - inputs=[ - wp.from_torch(selected.to(torch.int32)) if ids is not None else wp.zeros(1, dtype=wp.int32), - int(ids is not None), - wp.from_torch(start, dtype=wp.vec2f) if random_start else wp.zeros(1, dtype=wp.vec2f), - int(random_start), - radius, - ], - outputs=[wp.from_torch(angles, dtype=wp.vec2f), wp.from_torch(state, dtype=wp.vec4f)], - ) - torch.testing.assert_close(angles, expected_angles, atol=0, rtol=0) - torch.testing.assert_close(state, expected_state, atol=0, rtol=0) - - -def test_fixed_mount_teacher_rejects_only_turns_after_capture(): - """The fixed-mount teacher aims from the captured mount while the camera has turned its mount as many times as - when the term captured it, and refuses once a later turn makes the capture stale.""" - term = object.__new__(GazeAction) - term.tracked_mount = False - term._mount_turns = 2 - term._fixed_mount = "captured" - term._asset = SimpleNamespace(mount_turns=2) - assert GazeAction.teacher_mounts(term) == "captured" - term._asset.mount_turns = 3 - with pytest.raises(RuntimeError, match="mount='tracked'"): - GazeAction.teacher_mounts(term) + torch.testing.assert_close(term.processed_actions, torch.tensor([[0.5, 0.0]]).repeat(num_envs, 1)) + + previous = term.state.clone() + term.reset([3, 1]) + torch.testing.assert_close(term.state[[0, 2]], previous[[0, 2]]) + assert not term.state[[1, 3]].any() and not angles.torch[[1, 3]].any() + term.reset() + assert not term.state.any() and not angles.torch.any() diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py index aa783bcb2330..a3c1e0d712ef 100644 --- a/source/isaaclab_fovi/test/test_camera_cfg.py +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -14,7 +14,7 @@ import pytest import torch from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg -from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry +from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_newton.renderers import NewtonWarpRendererCfg @@ -48,24 +48,22 @@ def ray_angle_deg(camera, pixel: tuple[float, float]) -> float: def test_defaults_are_grid_sampling_at_the_human_cmf_estimate() -> None: cfg = FoveatedCameraCfg() - assert cfg.foveated_style == "warped_cartesian_as_grid" assert cfg.cmf_a_deg == 0.591 assert cfg.camera_model is None def test_pinhole_spawn_describes_an_ideal_pinhole_across_its_short_side() -> None: spawn = PinholeCameraCfg() - fov, cmf_a = sampling_geometry(make_cfg(spawn=spawn)) + camera = resolve_camera_model(make_cfg(spawn=spawn)) + fov = camera.field_of_view("short") expected = math.degrees(2 * math.atan(spawn.horizontal_aperture / (2 * spawn.focal_length))) assert fov == pytest.approx(expected, rel=1e-6) - assert cmf_a == 0.591 - camera = resolve_camera_model(make_cfg(spawn=spawn)) assert camera.model == "pinhole" assert camera.distortion == () # Without a vertical aperture the image is square; with one, the retina spans the short (vertical) side. assert camera.image_size[0] == camera.image_size[1] spawn = PinholeCameraCfg(focal_length=10.0, horizontal_aperture=20.0, vertical_aperture=10.0) - fov, _ = sampling_geometry(make_cfg(spawn=spawn)) + fov = resolve_camera_model(make_cfg(spawn=spawn)).field_of_view("short") assert fov == pytest.approx(math.degrees(2 * math.atan(0.5)), rel=1e-6) @@ -96,7 +94,7 @@ def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> No # Equidistant: the angle off the optical axis grows linearly with image radius. for radius in (50.0, 150.0, 310.0): assert ray_angle_deg(camera, (319.5 + radius, 319.5)) == pytest.approx(math.degrees(radius / focal), rel=1e-6) - fov, _ = sampling_geometry(cfg) + fov = camera.field_of_view("short") assert fov == pytest.approx(math.degrees(640 / focal), rel=1e-6) @@ -120,25 +118,10 @@ def test_cameras_fovi_cannot_model_are_rejected() -> None: resolve_camera_model(make_cfg(spawn=spawn)) -def test_config_validates_pooling_and_shell_settings() -> None: - assert make_cfg(pool_mode="gaussian").pool_mode == "gaussian" - with pytest.raises(ValueError, match="pool_mode must be one of"): - make_cfg(pool_mode="median") - # Segmentation pools only by modal label: other modes would mix labels into ones no object has. - assert make_cfg().pool_int_mode == "modal" - with pytest.raises(ValueError, match="pool_int_mode must be one of"): - make_cfg(pool_int_mode="avg") - # Square shells need a square or circular footprint and a grid style. - grid = dict(foveated_style="warped_cartesian_as_grid", radius_norm=math.inf) - assert make_cfg(**grid, fov_type="square").fov_type == "square" - with pytest.raises(ValueError, match="wang"): - make_cfg(**grid, fov_type="wang") - for kwargs in ( - dict(radius_norm=1.0, foveated_style="warped_cartesian_as_grid"), - dict(radius_norm=math.inf, foveated_style="isotropic"), - ): - with pytest.raises(ValueError, match="radius_norm"): - make_cfg(**kwargs) +@pytest.mark.parametrize("option", [{"pool_enabled": True}, {"foveated_style": "isotropic"}]) +def test_camera_config_rejects_deferred_sampling_options(option) -> None: + with pytest.raises(TypeError, match=next(iter(option))): + make_cfg(**option) @dataclass @@ -151,7 +134,9 @@ class CameraSelection: renderer_cfg: RendererSelection -def test_renderer_selects_the_implementation() -> None: +def test_renderer_selects_the_implementation(monkeypatch) -> None: + monkeypatch.setattr(Camera, "__del__", lambda self: None) + def dispatch(cfg) -> type: return type(FoveatedCamera.__new__(FoveatedCamera, cfg)) @@ -170,7 +155,12 @@ def dispatch(cfg) -> type: def test_cameras_that_turn_their_pose_by_the_gaze_need_per_frame_pose_updates(monkeypatch) -> None: """Newton and OVRTX turn the rendered pose by the gaze in each pose update, so without pose updates the renderer would never see the gaze; Isaac RTX writes the gaze into its camera prims instead.""" - monkeypatch.setattr(Camera, "__init__", lambda self, cfg: setattr(self, "stage", None)) + + def construct(self, cfg): + self.cfg = cfg + self.stage = None + + monkeypatch.setattr(Camera, "__init__", construct) monkeypatch.setattr(Camera, "__del__", lambda self: None) monkeypatch.setattr(FoveatedRTXCamera, "_prepare_projection", lambda self: None) monkeypatch.setattr(sim_utils, "find_matching_prims", lambda *args: []) @@ -180,14 +170,16 @@ def cfg(renderer_cfg) -> FoveatedCameraCfg: with pytest.raises(ValueError, match="update_latest_camera_pose=True"): FoveatedCamera(cfg(NewtonWarpRendererCfg())) - assert not FoveatedCamera(cfg(IsaacRtxRendererCfg())).turns_pose_by_gaze + assert isinstance(FoveatedCamera(cfg(IsaacRtxRendererCfg())), FoveatedRTXCamera) IMPORT_BOUNDARY = """ import importlib, importlib.abc, sys # Kit, fovi's research modules and training frameworks must not load with the sensor package. -BLOCKED = ("isaacsim", "omni", "fovi.models", "fovi.training", "ffcv", "wandb", "lightning", "timm") +BLOCKED = ( + "isaacsim", "omni", "fovi.arch", "fovi.models", "fovi.training", "rsl_rl", "ffcv", "wandb", "lightning", "timm", +) class Block(importlib.abc.MetaPathFinder): @@ -197,7 +189,11 @@ def find_spec(self, fullname, path=None, target=None): sys.meta_path.insert(0, Block()) -for module in ("isaaclab_fovi", "isaaclab_fovi.sensors", "isaaclab_fovi.sensors.pooling", "isaaclab_fovi.mdp"): +for module in ( + "isaaclab_fovi.sensors.foveated_newton_camera", + "isaaclab_fovi.sensors.foveated_rtx_camera", + "isaaclab_fovi.mdp.gaze", +): importlib.import_module(module) print("import boundary passed") """ diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index ae6ac139a472..a1110ae5cc49 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -15,18 +15,17 @@ from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel, angular_directions, gaze_rotation from fovi.sensing.retina import RetinalTransform -from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions, sampling_geometry +from isaaclab_fovi.sensors import FoveatedCameraCfg from isaaclab_fovi.sensors.foveated_camera import FoveatedCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.gaze_kernels import ( + CameraParams, camera_params, - project_directions, - publish_grid_kernel, + project_direction, set_gaze_kernel, torch_stream, ) -from isaaclab_fovi.sensors.native_grid import GRID_STYLE, grid_sample_indices, native_grid_directions -from isaaclab_fovi.sensors.pooling import build_lowres_coords +from isaaclab_fovi.sensors.native_grid import native_grid_directions from isaaclab.sensors.camera.camera import Camera from isaaclab.sensors.camera.camera_data import CameraData @@ -37,7 +36,6 @@ matrix_from_quat, quat_apply, quat_from_matrix, - quat_mul, ) from isaaclab.utils.warp import ProxyArray @@ -66,31 +64,32 @@ def camera_config() -> SimpleNamespace: retinal_window_reference_side="long", retinal_window_fraction=0.75, foveated_res=12, - foveated_style="isotropic", - fov_type="circular", - radius_norm=2.0, - isotropic_plotting_type="v1like", + mask_to_sensor_fov=True, image_rotation_deg=0.0, ) -def test_rendering_and_software_sampling_share_window_and_nodes() -> None: - cfg = camera_config() - fov, a = sampling_geometry(cfg) - camera = CameraModel(**cfg.camera_model) - assert fov == pytest.approx(camera.field_of_view("long", 0.75)) - assert a == 2.5 - coords, _ = build_lowres_coords(cfg, "cpu") - retina = RetinalTransform( - fov=fov, - cmf_a=a, +def test_camera_sampling_matches_software_sampling(monkeypatch) -> None: + data = camera_config() + model = CameraModel(**data.camera_model) + cfg = FoveatedCameraCfg(prim_path="/World/Camera", **vars(data)) + monkeypatch.setattr(Camera, "__init__", lambda self, cfg: setattr(self, "cfg", cfg)) + monkeypatch.setattr(Camera, "__del__", lambda self: None) + camera = FoveatedCamera.__new__(FoveatedCamera, cfg) + FoveatedCamera.__init__(camera, cfg) + software = RetinalTransform( + fov=model.field_of_view("long", 0.75), + cmf_a=2.5, resolution=12, device="cpu", + style="warped_cartesian_as_grid", field_geometry="spherical", - camera_model=camera, + camera_model=model, gaze_convention="pan_tilt", ) - torch.testing.assert_close(coords.cartesian, retina.sampler.coords.cartesian) + torch.testing.assert_close(camera.sampling_coords.cartesian, software.sampler.coords.cartesian) + assert (camera.cfg.width, camera.cfg.height) == (12, 12) + assert (cfg.width, cfg.height) == (1, 1) class GazeHarness(FoveatedCamera): @@ -106,15 +105,20 @@ def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None: self._view = SimpleNamespace(count=count) self._device = device self._ALL_INDICES = wp.array(list(range(count)), dtype=wp.int32, device=device) - self._sampling_coords, _ = build_lowres_coords(self.cfg, device) - self._sampling_coords_highres = None + self._camera_model = CameraModel(**self.cfg.camera_model) + fov = self._camera_model.field_of_view(self.cfg.retinal_window_reference_side, self.cfg.retinal_window_fraction) + self._sampling_coords = SamplingCoords( + fov, self.cfg.cmf_a_deg, self.cfg.foveated_res, style="warped_cartesian_as_grid", field_geometry="spherical" + ) + self._retinal_rays = native_grid_directions( + self._sampling_coords, image_rotation_deg=self.cfg.image_rotation_deg + ) # The camera's own pose buffers, at the identity orientation, with their world-to-ROS conversion. self._data = CameraData() self._data.create_buffers(count, device) self._data.quat_w_world.torch[:, 3] = 1.0 # Isaac RTX's behaviour; Newton and OVRTX turn the pose by the gaze in their pose update. self._gaze_pose_reads_angles = False - self._gaze_written = False self._initialize_gaze() @property @@ -151,11 +155,11 @@ def set_local_poses(self, *, orientations) -> None: class RtxGazeHarness(GazeHarness, FoveatedRTXCamera): """The Isaac RTX camera's prim-writing gaze on stand-in camera prims.""" - def __init__(self, mount_opengl: torch.Tensor) -> None: - super().__init__(count=len(mount_opengl)) + def __init__(self, mount_opengl: torch.Tensor, device="cpu") -> None: + super().__init__(count=len(mount_opengl), device=device) self._view = PrimView(mount_opengl) - self._base_local_orientation = matrix_from_quat(mount_opengl) - self.mount_turns = 0 + self._base_local_orientation = mount_opengl.clone() + self._gaze_basis_quat = quat_from_matrix(self._gaze_basis) MOUNT = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) @@ -167,7 +171,7 @@ def write_view(camera, eyes, targets, env_ids=None): looks at it; the others keep their poses.""" rotation = create_rotation_matrix_from_view(eyes, targets, "Z") looks = ~torch.isnan(rotation).any(dim=(-2, -1)) - ids = camera._env_indices(env_ids)[looks] + ids = (torch.arange(camera._view.count) if env_ids is None else torch.as_tensor(env_ids))[looks] camera._view.local[ids] = quat_from_matrix(rotation[looks]) @@ -184,23 +188,6 @@ def gaze_direction(angles_deg: torch.Tensor) -> torch.Tensor: return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) -def angles_toward(camera: CameraModel, pixel: tuple[float, float]) -> torch.Tensor: - """(tilt, pan) gaze angles [deg] that look along the ray through a source pixel (x, y).""" - direction, _ = camera.unproject(torch.tensor([pixel])) - x, y, z = direction.unbind(-1) - return torch.stack((-torch.atan2(y, torch.sqrt(x * x + z * z)), -torch.atan2(x, z)), -1).rad2deg() - - -def test_sensor_mask_keeps_what_the_camera_sees_at_an_edge_gaze() -> None: - """Looking just past an image edge keeps the part of the retina the camera still sees; looking away keeps none.""" - camera = GazeHarness(count=2) - edge = angles_toward(camera._camera_model, (120.5, 39.5)) - camera.set_gaze_angles(torch.cat((edge, torch.tensor([[0.0, 180.0]])))) - valid = camera._gaze_validity() - assert valid[0].any() and not valid[0].all() - assert not valid[1].any() - - @pytest.mark.parametrize("device", CUDA) @pytest.mark.parametrize( "mode, autocast", @@ -254,65 +241,54 @@ def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, m assert torch.get_float32_matmul_precision() == "high" -def test_sensor_mask_checks_the_rendered_rays_of_a_rolled_mount() -> None: - """The mask sees exactly the rays the turned camera renders, found here through the camera pose instead.""" - rotation_deg = 30.0 - # An off-center, wide image makes a roll change which samples the camera sees. - model = CameraModel("pinhole", (80, 120), (60.0, 60.0, 45.0, 30.0)) - camera = GazeHarness(camera_model=asdict(model), image_rotation_deg=rotation_deg) - camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) +@pytest.mark.parametrize("model_name", ["distorted pinhole", "fisheye with image circle"]) +def test_camera_publishes_only_visible_samples_in_updated_rows(model_name): + model = KERNEL_CAMERAS[model_name] + camera = GazeHarness( + device=KERNEL_DEVICE, + camera_model=asdict(model), + image_rotation_deg=37.0, + retinal_window_reference_side="short", + retinal_window_fraction=0.7, + ) + coords = camera.sampling_coords + n = coords.resolution + rgba = torch.arange(2 * n * n * 4, device=KERNEL_DEVICE).reshape(2, n, n, 4).to(torch.uint8) + depth = torch.arange(1, 2 * n * n + 1, device=KERNEL_DEVICE, dtype=torch.float32).reshape(2, n, n, 1) + camera._prepare_grid_publish({"rgba": rgba, "rgb": rgba[..., :3], "distance_to_camera": depth}) + outputs = camera._data.output + angles = torch.tensor([[6.0, -11.0], [-9.0, 17.0]], device=KERNEL_DEVICE) + camera.set_gaze_angles(angles) mount = camera.orientation.clone() camera._apply_gaze_pose() - # Rendered rays leave the turned camera along its OpenGL frame; express them in the mount's OpenGL frame. - def opengl(orientation: torch.Tensor) -> torch.Tensor: + def opengl(orientation): return matrix_from_quat(convert_camera_frame_orientation_convention(orientation, "world", "opengl")) - turn = opengl(mount).transpose(-1, -2) @ opengl(camera.orientation) - coords = camera._sampling_coords - rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) - seen = (turn[:, None] @ rays[None, :, :, None]).squeeze(-1) * torch.tensor([1.0, -1.0, -1.0]) - expected = model.project(seen)[1] - assert expected.any() and (~expected).any() - assert (camera._gaze_validity() == expected).float().mean() > 0.999 - - -def test_only_a_turned_mount_is_recorded(monkeypatch) -> None: - """The fixed-mount teacher reads the live camera position, so only writes that turn a mount count: not a position - move, and not writing back the reported mount (of either quaternion sign), even with a gaze held in the prims.""" - monkeypatch.setattr(Camera, "set_world_poses", write_prims) - monkeypatch.setattr(Camera, "set_world_poses_from_view", write_view) - eyes = torch.zeros(2, 3) - targets = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) - - def view_twice(camera): - # Looking again from the same eye at the same target leaves the mount where the first view put it. - camera.set_world_poses_from_view(eyes, targets) - camera.mount_turns = 0 - camera.set_world_poses_from_view(eyes, targets) - - def reported(camera, env_ids=None): - return camera.get_world_poses(env_ids, convention="ros")[1] - - def turn_second(camera): - # One degree about the second camera's optical axis. - half = torch.tensor(math.radians(1.0) / 2) - roll = torch.tensor([[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, float(half.sin()), float(half.cos())]]) - camera.set_world_poses(orientations=quat_mul(reported(camera), roll)) - - for move, turned in ( - (lambda camera: camera.set_world_poses(positions=torch.zeros(2, 3)), False), - (lambda camera: camera.set_world_poses(orientations=reported(camera)), False), - (lambda camera: camera.set_world_poses(orientations=-reported(camera, [1]), env_ids=[1]), False), - (turn_second, True), - (lambda camera: camera.set_world_poses_from_view(eyes, eyes), False), - (lambda camera: camera.set_world_poses_from_view(eyes, targets), True), - (view_twice, False), - ): - camera = RtxGazeHarness(MOUNT) - camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) - move(camera) - assert camera.mount_turns == int(turned) + rotation = opengl(mount).transpose(-1, -2) @ opengl(camera.orientation) + # fovi's direction generation in the physical frame, independently of the publication kernel. + ray = angular_directions(coords.cartesian, coords.fov) + x, y, z = ray.unbind(-1) + c, s = math.cos(math.radians(37)), math.sin(math.radians(37)) + gl = torch.stack((c * x + s * y, s * x - c * y, -z), -1) + turned_ray = (gl @ rotation.transpose(-1, -2)) * gl.new_tensor((1.0, -1.0, -1.0)) + keep = model.project(turned_ray)[1] & coords.valid_mask[None] + assert keep.any() and (~keep).any() + + all_rows = wp.ones(2, dtype=wp.bool, device=KERNEL_DEVICE) + camera._publish_grid(all_rows) + for name, values in (("rgba", rgba), ("distance_to_camera", depth)): + canonical = values.reshape(2, n * n, -1) + expected = coords.as_grid(canonical * keep[..., None], sample_dim=1) + torch.testing.assert_close(outputs[name].torch, expected) + assert outputs["rgb"].warp.ptr == outputs["rgba"].warp.ptr + + last = outputs["distance_to_camera"].torch.clone() + depth.add_(1) + camera._publish_grid(wp.array([False, True], dtype=wp.bool, device=KERNEL_DEVICE)) + assert camera._data.output["distance_to_camera"] is outputs["distance_to_camera"] + assert torch.equal(last[0], outputs["distance_to_camera"].torch[0]) + assert not torch.equal(last[1], outputs["distance_to_camera"].torch[1]) def test_gaze_angles_need_one_row_per_camera() -> None: @@ -322,68 +298,12 @@ def test_gaze_angles_need_one_row_per_camera() -> None: assert camera._gaze_angles is None -def test_mount_record_starts_at_the_current_pose() -> None: - """Allocating the gaze before any pose update records the camera's current, ungazed mount, not zeros.""" - camera = GazeHarness() - camera._gaze_pose_reads_angles = True - mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) - camera.orientation.copy_(mount) - camera.gaze_angles - expected = convert_camera_frame_orientation_convention(mount, "world", "ros") - torch.testing.assert_close( - matrix_from_quat(camera.ungazed_quat_w_ros()), matrix_from_quat(expected), atol=1e-6, rtol=0 - ) - - -def test_prim_writing_camera_reads_its_mount_before_and_after_a_gaze() -> None: - """Isaac RTX writes the gaze into its prims; its mount reads the same before and after a gaze is set, so a - fixed-mount teacher created after a gaze aims from the real mount.""" - camera = RtxGazeHarness(MOUNT) - # The last pose update read the bare mount. - camera.orientation.copy_(convert_camera_frame_orientation_convention(MOUNT, "opengl", "world")) - expected = matrix_from_quat(convert_camera_frame_orientation_convention(MOUNT, "opengl", "ros")) - torch.testing.assert_close(matrix_from_quat(camera.ungazed_quat_w_ros()), expected, atol=1e-6, rtol=0) - camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) - assert not torch.allclose(matrix_from_quat(camera._view.local), matrix_from_quat(MOUNT), atol=1e-3) - torch.testing.assert_close(matrix_from_quat(camera.ungazed_quat_w_ros()), expected, atol=1e-6, rtol=0) - - -def test_sensor_mask_reuses_its_buffer_and_keeps_rows_that_were_not_updated() -> None: - camera = GazeHarness() - camera.cfg.mask_to_sensor_fov = True - camera.set_gaze_angles(torch.tensor([[0.0, 0.0], [0.0, 0.0]])) - first = camera._gaze_validity() - kept = first[0].clone() - output = {"distance_to_camera": torch.ones(2, len(camera._gaze_rays), 1, 1)} - camera.set_gaze_angles(torch.tensor([[0.0, 180.0], [0.0, 180.0]])) - camera._apply_sensor_fov_mask(output, wp.array([False, True], dtype=wp.bool, device="cpu")) - assert camera._visibility["valid"].torch is first - # The environment that was not updated keeps its samples and its last visibility. - torch.testing.assert_close(first[0], kept) - assert bool(output["distance_to_camera"][0].all()) - assert not output["distance_to_camera"][1].any() - - -def test_pose_update_records_the_mount_before_the_gaze() -> None: - camera = GazeHarness() - mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) - camera.orientation.copy_(mount) - camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) - camera._apply_gaze_pose() - expected = convert_camera_frame_orientation_convention(mount, "world", "ros") - torch.testing.assert_close( - matrix_from_quat(camera._mount_quat_ros.torch), matrix_from_quat(expected), atol=1e-6, rtol=0 - ) - assert not torch.allclose(camera.orientation, mount) - - def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pose() -> None: camera = GazeHarness() angles = torch.tensor([[6.0, -11.0], [-9.0, 17.0]]) camera.set_gaze_angles(angles) camera._apply_gaze_pose() forward = quat_apply(camera.orientation, torch.tensor([[1.0, 0.0, 0.0]]).expand(2, -1)) - source = CameraModel(**camera.cfg.camera_model) # The world camera frame looks along +X with +Z up; OpenCV looks along +Z with +Y down. directions = gaze_direction(angles) expected = torch.stack((directions[:, 2], -directions[:, 0], -directions[:, 1]), -1) @@ -393,28 +313,12 @@ def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pos camera.orientation[0] = torch.tensor([0.0, 0.0, 0.0, 1.0]) camera._apply_gaze_pose([0]) torch.testing.assert_close(camera.orientation[1], untouched) - torch.testing.assert_close( - camera._gaze_validity(), - source.project( - angular_directions(camera._sampling_coords.cartesian, camera._sampling_coords.fov) - @ camera._gaze_rotation.torch.transpose(-1, -2) - )[1], - ) - - -def test_renderer_ray_frame_matches_cv_frame() -> None: - coords = torch.tensor([[0.0, 0.0], [0.3, -0.4], [-1.0, 0.0]]) - rendered = retinal_directions(coords, 120) - cv = angular_directions(coords, 120) - torch.testing.assert_close(rendered, cv * torch.tensor([1, -1, -1])) @pytest.mark.parametrize("device", CUDA) def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_enabled) -> None: - camera = GazeHarness(count=48, device=device) - camera._gaze_basis = camera._gaze_basis.to(device) - camera._base_local_orientation = matrix_from_quat( - torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(48, 1) + camera = RtxGazeHarness( + torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(48, 1), device=device ) written = [] camera._view = SimpleNamespace( @@ -426,7 +330,6 @@ def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_ for enabled in [False, True]: with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled): camera.set_gaze_angles(angles) - FoveatedRTXCamera._write_gaze_local_pose(camera) assert torch.isfinite(written[1]).all() assert written[1].dtype == torch.float32 torch.testing.assert_close(written[1].norm(dim=-1), torch.ones(48, device=device)) @@ -437,6 +340,7 @@ def test_rtx_world_poses_are_the_mount_so_a_round_trip_keeps_mount_and_gaze(monk """Isaac RTX holds the gaze in its prims; its world poses still report the bare mount, as the other renderers' do, so writing them back (as a viewer navigating the camera does) neither moves the mount nor doubles the gaze.""" monkeypatch.setattr(Camera, "set_world_poses", write_prims) + monkeypatch.setattr(Camera, "set_world_poses_from_view", write_view) camera = RtxGazeHarness(MOUNT) mount = MOUNT camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) @@ -447,11 +351,23 @@ def test_rtx_world_poses_are_the_mount_so_a_round_trip_keeps_mount_and_gaze(monk expected = convert_camera_frame_orientation_convention(mount[1:], "opengl", "ros") torch.testing.assert_close(matrix_from_quat(orientations), matrix_from_quat(expected), atol=1e-6, rtol=0) + camera.set_world_poses(positions=torch.zeros(2, 3)) + torch.testing.assert_close(matrix_from_quat(camera._view.local), matrix_from_quat(gazed), atol=1e-6, rtol=0) _, orientations = camera.get_world_poses(convention="world") camera.set_world_poses(orientations=orientations, convention="world") - torch.testing.assert_close(camera._base_local_orientation, matrix_from_quat(mount), atol=1e-6, rtol=0) + torch.testing.assert_close( + matrix_from_quat(camera._base_local_orientation), matrix_from_quat(mount), atol=1e-6, rtol=0 + ) torch.testing.assert_close(matrix_from_quat(camera._view.local), matrix_from_quat(gazed), atol=1e-6, rtol=0) + eyes = torch.zeros(2, 3) + targets = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) + camera.set_world_poses_from_view(eyes, targets) + torch.testing.assert_close(matrix_from_quat(camera._view.local[:1]), matrix_from_quat(gazed[:1]), atol=1e-6, rtol=0) + _, pose = camera.get_world_poses(convention="opengl") + expected = create_rotation_matrix_from_view(eyes[1:], targets[1:], "Z") + torch.testing.assert_close(matrix_from_quat(pose[1:]), expected, atol=1e-6, rtol=0) + @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) def test_gaze_kernels_preserve_shared_stream_for_warp_capture(device: str) -> None: @@ -460,14 +376,17 @@ def test_gaze_kernels_preserve_shared_stream_for_warp_capture(device: str) -> No with wp.ScopedStream(stream), torch.cuda.stream(wp.stream_to_torch(stream)): camera = GazeHarness(device=device) camera.set_gaze_angles(torch.tensor([[5.0, -8.0], [0.0, 0.0]], device=device)) - valid = camera._gaze_validity() - target = wp.zeros(valid.shape, dtype=wp.bool, device=device) + n = camera.sampling_coords.resolution + camera._prepare_grid_publish({"rgb": torch.ones(2, n, n, 3, dtype=torch.uint8, device=device)}) + camera._publish_grid(wp.ones(2, dtype=wp.bool, device=device)) + output = camera._data.output["rgb"].warp + target = wp.zeros_like(output) # Physics must still be able to capture after the camera's temporary stream scopes exit. with wp.ScopedCapture(stream=stream) as capture: - wp.copy(target, wp.from_torch(valid)) + wp.copy(target, output) wp.capture_launch(capture.graph) - torch.testing.assert_close(wp.to_torch(target), valid) - assert valid[1].any() + torch.testing.assert_close(wp.to_torch(target), wp.to_torch(output)) + assert wp.to_torch(output)[1].any() # -- The gaze kernels against fovi's camera geometry ------------------------------------------------------------------ @@ -507,6 +426,19 @@ def set_gaze(angles: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: return stored, rotation +@wp.kernel +def _probe_projection( + directions: wp.array(dtype=wp.vec3f), + camera: CameraParams, + pixels: wp.array(dtype=wp.vec2f), + valid: wp.array(dtype=wp.bool), +): + i = wp.tid() + result = project_direction(directions[i], camera) + pixels[i] = wp.vec2f(result[0], result[1]) + valid[i] = result[2] > 0.5 + + @pytest.mark.parametrize("name", KERNEL_CAMERAS) def test_projection_kernel_matches_fovi(name: str) -> None: """The sensor mask projects with fovi's camera model, as the software sampler does on a real camera.""" @@ -517,7 +449,19 @@ def test_projection_kernel_matches_fovi(name: str) -> None: directions[:2000, 2] *= -1 directions = torch.nn.functional.normalize(directions, dim=-1).to(KERNEL_DEVICE) expected_pixels, expected_valid = camera.project(directions) - pixels, valid = project_directions(directions, camera_params(camera)) + pixels = torch.empty_like(expected_pixels) + valid = torch.empty_like(expected_valid) + with torch_stream(KERNEL_DEVICE): + wp.launch( + _probe_projection, + len(directions), + [ + wp.from_torch(directions, dtype=wp.vec3f), + camera_params(camera), + wp.from_torch(pixels, dtype=wp.vec2f), + wp.from_torch(valid), + ], + ) # Float32 rounding may flip a sample that lies on the image edge, nothing more. assert (valid == expected_valid).float().mean() > 0.9995 assert expected_valid.any() and (~expected_valid).any() @@ -533,60 +477,3 @@ def test_gaze_rotation_follows_fovis_pan_tilt_convention() -> None: direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) torch.testing.assert_close(stored, angles, atol=0, rtol=0) torch.testing.assert_close(rotation, gaze_rotation(direction, "pan_tilt"), atol=1e-5, rtol=0) - - -def test_publish_kernel_matches_masking_then_copying_to_the_grid() -> None: - camera = KERNEL_CAMERAS["distorted pinhole"] - coords = SamplingCoords( - camera.field_of_view("short"), 0.591, 24, style=GRID_STYLE, field_geometry="spherical", device=KERNEL_DEVICE - ) - rays = (native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1))).float().contiguous() - generator = torch.Generator().manual_seed(2) - angles = ((torch.rand(6, 2, generator=generator) * 2 - 1) * 25).to(KERNEL_DEVICE) - _, rotation = set_gaze(angles) - count = len(coords) - outputs = { - "rgba": torch.randint(1, 255, (6, count, 1, 4), generator=generator, dtype=torch.uint8).to(KERNEL_DEVICE), - "depth": (torch.rand(6, count, 1, 1, generator=generator) + 0.5).to(KERNEL_DEVICE), - } - valid = camera.project(rays @ rotation.transpose(-1, -2))[1] - # Environments 1 and 4 were not rendered this frame and keep their previous image. - updated = torch.tensor([True, False, True, True, False, True], device=KERNEL_DEVICE) - - # The sequence the kernel replaces: footprint mask, sensor mask, then the upright layout. The layout comes from - # fovi's own grid reshaping rather than the index permutation the kernel uses. - keep = valid & coords.valid_mask[None] - expected_grid = { - name: coords.as_grid(value.squeeze(2) * keep[..., None], sample_dim=1) for name, value in outputs.items() - } - indices = grid_sample_indices(coords).to(torch.int32).contiguous() - visible = torch.zeros(6, count, dtype=torch.bool, device=KERNEL_DEVICE) - identity = wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) - for name, value in outputs.items(): - previous = torch.full_like(expected_grid[name], 7) - target = previous.clone() - with torch_stream(KERNEL_DEVICE): - wp.launch( - publish_grid_kernel, - dim=(6, count), - inputs=[ - wp.from_torch(value.squeeze(2).view(torch.uint8)), - wp.from_torch(indices), - wp.from_torch(coords.valid_mask.contiguous()), - wp.from_torch(updated), - wp.from_torch(rays, dtype=wp.vec3f), - wp.from_torch(rotation, dtype=wp.mat33f), - identity, - camera_params(camera), - 1, - int(name == "rgba"), - wp.from_torch(visible), - ], - outputs=[wp.from_torch(target.view(6, count, -1).view(torch.uint8))], - ) - # Float32 rounding may flip a sample on the image edge, nothing more. - assert (target[updated] == expected_grid[name][updated]).all(-1).float().mean() > 0.999 - assert torch.equal(target[~updated], previous[~updated]) - assert (visible[updated] == valid[updated]).float().mean() > 0.999 - assert not visible[~updated].any() - assert valid.any() and (~valid).any() diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py index fce1bef4556f..bdd383d28d7e 100644 --- a/source/isaaclab_fovi/test/test_native_grid.py +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -3,47 +3,20 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""The native grid's rays, lens textures and published layout agree with independent geometry.""" +"""The analytic lens textures use the software sampler's directions and invert the native grid.""" import math import pytest import torch from fovi.sensing.coords import SamplingCoords -from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions +from fovi.sensing.projection import angular_directions from isaaclab_fovi.sensors.lens_lut import build_native_grid_textures -from isaaclab_fovi.sensors.native_grid import ( - allocate_grid_outputs, - bounded_angular_radius, - copy_grid_outputs, - grid_sample_indices, - mask_grid_samples, - native_grid_directions, - native_grid_exit_uv, - unbounded_angular_radius, -) - -from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab_fovi.sensors.native_grid import bounded_angular_radius, native_grid_directions, native_grid_exit_uv pytestmark = pytest.mark.kitless -def make_coords(resolution: int = 64, coverage: str = "circular", field: str = "spherical") -> SamplingCoords: - """A wide grid; ``"square_shells"`` is the square footprint with square (infinity-norm) shells.""" - fov = 80.0 if coverage == "wang" else 170.0 - square_shells = coverage == "square_shells" - return SamplingCoords( - fov=fov, - cmf_a=0.036021 * fov, - res=resolution, - style="warped_cartesian_as_grid", - fov_type="square" if square_shells else coverage, - radius_norm=math.inf if square_shells else 2.0, - field_geometry=field, - device="cpu", - ) - - def texel_centers(resolution: int) -> torch.Tensor: """Native texture UV of each canonical sample: columns follow native x, rows native y.""" axis = (torch.arange(resolution) + 0.5) / resolution @@ -51,133 +24,31 @@ def texel_centers(resolution: int) -> torch.Tensor: return torch.stack((col, row), -1).reshape(-1, 2) -def eccentricity_rays(visual: torch.Tensor, fov_deg: float, rotation_deg: float = 0.0) -> torch.Tensor: - """OpenGL rays for visual-chart points: angle off the axis is the visual radius times the half field of view.""" - visual = visual.to(torch.float64) - theta = torch.linalg.vector_norm(visual, dim=-1) * math.radians(fov_deg) / 2 - phi = torch.atan2(visual[..., 1], visual[..., 0]) + math.radians(rotation_deg) - return torch.stack((theta.sin() * phi.cos(), theta.sin() * phi.sin(), -theta.cos()), -1) - - -@pytest.mark.parametrize( - ("coverage", "resolution", "rotation"), - # Circular padding outside the field, and odd square-shell grids with a texel on the axis, under a roll. - [("circular", 64, 0.0), ("square_shells", 15, 37.0)], -) -def test_every_texel_roundtrips(coverage: str, resolution: int, rotation: float) -> None: - coords = make_coords(resolution, coverage) - rays = native_grid_directions(coords, image_rotation_deg=rotation) - uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) - assert valid.all() - torch.testing.assert_close(uv, texel_centers(resolution), atol=2e-6, rtol=0) - torch.testing.assert_close(rays.norm(dim=-1), torch.ones(len(coords)), atol=1e-6, rtol=0) - - -@pytest.mark.parametrize(("coverage", "rotation"), [("wang", 180.0), ("square_shells", 37.0)]) -def test_inverse_maps_independent_rays_to_their_texels(coverage: str, rotation: float) -> None: - coords = make_coords(64, coverage) - half_fov = math.radians(coords.fov) / 2 - # Rays through fovi's own sample positions inside the field land on those samples' texels. - inside = torch.linalg.vector_norm(coords.cartesian, dim=-1) <= (math.sqrt(2) if coverage == "square_shells" else 1) - rays = eccentricity_rays(coords.cartesian[inside], coords.fov, rotation) - uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) - assert inside.sum() > len(coords) // 2 - assert valid.all() - torch.testing.assert_close(uv, texel_centers(64)[inside], atol=2e-6, rtol=0) - # The optical axis is the texture centre and the nominal rim along each rolled native axis is its edge. - roll = math.radians(rotation) - rim = [ - (math.sin(half_fov) * math.cos(angle), math.sin(half_fov) * math.sin(angle), -math.cos(half_fov)) - for angle in (roll, roll + math.pi / 2) - ] - hand_rays = torch.tensor([(0.0, 0.0, -1.0), *rim], dtype=torch.float64) - uv, _ = native_grid_exit_uv(hand_rays, coords, image_rotation_deg=rotation) - torch.testing.assert_close(uv, torch.tensor([[0.5, 0.5], [0.5, 1.0], [1.0, 0.5]]), atol=1e-6, rtol=0) +def test_rolled_grid_matches_fovi_and_inverts_every_texel(): + coords = SamplingCoords(170.0, 6.0, 65, style="warped_cartesian_as_grid", field_geometry="spherical") + roll = math.radians(37.0) + rendered = native_grid_directions(coords, image_rotation_deg=37.0) + valid = coords.valid_mask + cv_rays = angular_directions(coords.cartesian[valid], coords.fov) + x, y, z = cv_rays.unbind(-1) + reference = torch.stack((math.cos(roll) * x + math.sin(roll) * y, math.sin(roll) * x - math.cos(roll) * y, -z), -1) + torch.testing.assert_close(rendered[valid], reference, atol=3e-7, rtol=0) + uv, visible = native_grid_exit_uv(rendered, coords, image_rotation_deg=37.0) + assert visible.all() + torch.testing.assert_close(uv, texel_centers(coords.resolution), atol=2e-6, rtol=0) -def test_valid_samples_match_the_software_sampler_rays() -> None: - """The renderer's rays are the ones fovi's software sampler uses on a real camera's images.""" - coords = make_coords() - actual = native_grid_directions(coords) - expected = retinal_directions(coords.cartesian[coords.valid_mask], coords.fov) - torch.testing.assert_close(actual[coords.valid_mask], expected, atol=3e-7, rtol=0) - with pytest.raises(ValueError, match="spherical"): - native_grid_directions(make_coords(16, field="planar")) + directions, exit_uv = build_native_grid_textures(coords, rendered, image_rotation_deg=37.0, exit_size=129) + torch.testing.assert_close(directions.reshape(-1, 3), rendered) + torch.testing.assert_close(exit_uv[64, 64], torch.tensor([0.5, 0.5])) + torch.testing.assert_close(exit_uv[0, 0], torch.tensor([-1.0, -1.0])) -def test_spherical_padding_matches_rim_slope_and_does_not_wrap() -> None: - radius = torch.tensor([0.0, 0.99999, 1.0, 1.00001, 2.0, 10.0], dtype=torch.float64) +def test_spherical_padding_matches_rim_slope_and_does_not_wrap(): + radius = torch.tensor([0.99999, 1.0, 1.00001, 2.0, 10.0], dtype=torch.float64) half_fov = math.radians(170) / 2 angles = bounded_angular_radius(radius, half_fov) - assert (angles[1:] > angles[:-1]).all() - assert (angles < math.pi).all() - left = (angles[2] - angles[1]) / (radius[2] - radius[1]) - right = (angles[3] - angles[2]) / (radius[3] - radius[2]) + assert (angles[1:] > angles[:-1]).all() and (angles < math.pi).all() + left = (angles[1] - angles[0]) / (radius[1] - radius[0]) + right = (angles[2] - angles[1]) / (radius[2] - radius[1]) torch.testing.assert_close(left, right, atol=2e-5, rtol=0) - torch.testing.assert_close(unbounded_angular_radius(angles, half_fov), radius, atol=1e-10, rtol=0) - - -@pytest.mark.parametrize(("coverage", "rotation"), [("circular", 0.0), ("square_shells", 37.0)]) -def test_textures_match_independent_geometry(coverage: str, rotation: float) -> None: - coords = make_coords(64, coverage) - size = 256 - direction, inverse = build_native_grid_textures(coords, image_rotation_deg=rotation, exit_size=size) - assert direction.shape == (64, 64, 3) and inverse.shape == (size, size, 2) - inside = coords.valid_mask & (torch.linalg.vector_norm(coords.cartesian, dim=-1) <= math.sqrt(2)) - expected = eccentricity_rays(coords.cartesian[inside], coords.fov, rotation).float() - torch.testing.assert_close(direction.reshape(-1, 3)[inside], expected, atol=1e-6, rtol=0) - # Forward-hemisphere octahedral texel centres decode to (x, y, -(1 - |x| - |y|)) before normalization. - axis = (torch.arange(size, dtype=torch.float64) + 0.5) / size * 2 - 1 - y, x = torch.meshgrid(axis, axis, indexing="ij") - forward = x.abs() + y.abs() < 1 - texel_rays = torch.nn.functional.normalize(torch.stack((x, y, x.abs() + y.abs() - 1), -1), dim=-1) - # Each stored UV, mapped back through fovi's native-to-visual warp, must look along its texel's ray. - stored = forward & (inverse[..., 0] >= 0) - native = (inverse[stored].to(torch.float64) * 2 - 1).flip(-1) - visual = coords.native_to_visual(native) - # Circular grids pad outside the nominal field on another curve; square shells reach their corners linearly. - linear = torch.ones(len(visual), dtype=torch.bool) - if coverage == "circular": - linear = torch.linalg.vector_norm(visual, dim=-1) <= 1 - assert linear.sum() > 1000 - torch.testing.assert_close( - eccentricity_rays(visual[linear], coords.fov, rotation), texel_rays[stored][linear], atol=1e-5, rtol=0 - ) - # The antipode lies outside every grid. - assert (inverse[0, 0] == -1).all() and (inverse[-1, -1] == -1).all() - assert torch.isfinite(inverse).all() - - -def test_upright_grid_masks_and_channel_aliases() -> None: - coords = make_coords(16) - # Coordinate channels make rotation/transposition failures observable. - values = torch.cat((coords.cartesian, torch.ones(len(coords), 2)), -1)[None, :, None] - source = {"rgba": values.clone()} - source["rgb"] = source["rgba"][..., :3] - mask_grid_samples(source, coords) - target = allocate_grid_outputs(source, coords) - copy_grid_outputs(source, target, grid_sample_indices(coords)) - expected = coords.as_grid(source["rgba"][:, :, 0], sample_dim=1) - torch.testing.assert_close(target["rgba"], expected) - assert target["rgb"].untyped_storage().data_ptr() == target["rgba"].untyped_storage().data_ptr() - assert target["rgba"][0, :, :, 0][8, 4] < target["rgba"][0, :, :, 0][8, 11] - assert target["rgba"][0, :, :, 1][4, 8] > target["rgba"][0, :, :, 1][11, 8] - assert (target["rgba"][0][~coords.as_grid(coords.valid_mask)] == 0).all() - - -@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_published_grid_copy_is_graph_capturable(device: str) -> None: - coords = make_coords(16).to(device=device) - source = {"value": torch.arange(3 * len(coords) * 4, device=device).to(torch.uint8).reshape(3, len(coords), 1, 4)} - target = allocate_grid_outputs(source, coords) - indices = grid_sample_indices(coords) - copy_grid_outputs(source, target, indices) - torch.testing.assert_close(target["value"], coords.as_grid(source["value"][:, :, 0], sample_dim=1), atol=0, rtol=0) - torch.cuda.synchronize() - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - copy_grid_outputs(source, target, indices) - source["value"].zero_() - graph.replay() - torch.cuda.synchronize() - assert torch.count_nonzero(target["value"]) == 0 diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index b04505672812..42d849230856 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -3,360 +3,29 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""The Newton foveated camera's render layout and publication, on stand-in renderer buffers.""" +"""Newton's renderer requires whole native-grid tiles.""" -from dataclasses import asdict from types import SimpleNamespace import pytest import torch -import warp as wp -from fovi.sensing.coords import SamplingCoords -from fovi.sensing.projection import CameraModel -from isaaclab_fovi.sensors import foveated_camera as base_camera -from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera -from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions -from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera, explicit_rays -from isaaclab_fovi.sensors.native_grid import native_grid_directions +from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera -from isaaclab.utils.warp import ProxyArray +from isaaclab.sensors.camera.camera import Camera pytestmark = pytest.mark.kitless -def rendered_rays_only(camera) -> None: - """Stand-in for the gaze geometry: only the rendered rays, in the ROS frame the camera keeps them in.""" - coords = camera._ray_coords - if coords.style == "warped_cartesian_as_grid": - rays = native_grid_directions(coords, image_rotation_deg=0) - else: - rays = retinal_directions(coords.cartesian, coords.fov, 0) - camera._gaze_rays = (rays * rays.new_tensor((1.0, -1.0, -1.0))).float() - - -def new_camera() -> FoveatedNewtonCamera: - """A Newton camera without its constructor: the state its constructor sets and the handles its destructor reads.""" - camera = object.__new__(FoveatedNewtonCamera) - camera._gaze_angles = camera._gaze_rotation = camera._visibility = camera._grid_publish = None - camera._published_shape = camera._segmentation_neighbors = None - camera._initialize_handle = None - camera._invalidate_initialize_handle = None - camera._prim_deletion_handle = None - camera._view = None - camera._renderer = None - camera._device = "cpu" - return camera - - -@pytest.mark.parametrize("pooled", [False, True]) -def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatch, pooled) -> None: - coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") - highres = coords.clone(resolution=32) if pooled else None - ray_coords = highres if pooled else coords - pooler = torch.nn.AdaptiveAvgPool1d(len(coords)) if pooled else None - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) - monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (pooler, 4)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) - - def initialize_renderer(camera): - # Newton launches image tiles; a vector-shaped width of one is not valid. - assert camera.cfg.height == camera.cfg.width == ray_coords.resolution - rgba = torch.zeros((2, camera.cfg.height, camera.cfg.width, 4), dtype=torch.uint8) - camera._data = SimpleNamespace( - output={ - "rgba": ProxyArray(wp.from_torch(rgba)), - "rgb": ProxyArray(wp.from_torch(rgba[..., :3])), - } - ) - camera._render_data = SimpleNamespace(camera_rays=None) - camera._renderer = SimpleNamespace( - cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), - cleanup=lambda render_data: None, - ) - camera.renderer_rgba = rgba - - def render(camera, env_mask): - assert camera._data.output["rgba"].torch.shape == camera.renderer_rgba.shape - values = torch.arange(camera.renderer_rgba.numel()).reshape(camera.renderer_rgba.shape) + camera.frame_offset - camera.renderer_rgba.copy_(values.to(torch.uint8)) - - monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) - monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) - camera = new_camera() - camera.cfg = SimpleNamespace( - foveated_style="warped_cartesian_as_grid", - mask_to_sensor_fov=False, - cmf_a_deg=0.591, - pool_enabled=pooled, - pool_mode="avg", - pool_sample_cortex=False, - image_rotation_deg=0, - update_period=0.0, - data_types=["rgba", "rgb"], - renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), - ) - camera._initialize_impl() - - rays = wp.to_torch(camera._foveated_rays) - assert rays.shape == (ray_coords.resolution, ray_coords.resolution, 1, 2, 3) - expected_rays = native_grid_directions(ray_coords, image_rotation_deg=0).float() - torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], expected_rays) - public_rgba = camera._data.output["rgba"] - camera.frame_offset = 0 - camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) - expected = camera.renderer_rgba.reshape(2, len(ray_coords), 1, 4).clone() - expected[:, ~ray_coords.valid_mask] = 0 - if pooled: - # AdaptiveAvgPool1d maps the 4 * N_lo canonical samples to N_lo by averaging each run of four, which the - # camera rounds to the nearest uint8 value. - expected = expected.reshape(2, len(coords), 4, 1, 4).float().mean(dim=2).round().to(torch.uint8) - expected = coords.as_grid(expected.squeeze(2), sample_dim=1) - torch.testing.assert_close(camera._data.output["rgba"].torch, expected, rtol=0, atol=0) - # The published buffers are stable across frames, and rgb shares rgba's memory. - assert camera._data.output["rgba"] is public_rgba - torch.testing.assert_close(camera._data.output["rgb"].torch, expected[..., :3], rtol=0, atol=0) - assert camera._data.output["rgb"].warp.ptr == public_rgba.warp.ptr - - # Newton redraws every row, but only the updated environment's publication changes. - camera.frame_offset = 1 - camera._update_buffers_impl(wp.array([False, True], dtype=wp.bool, device="cpu")) - published = camera._data.output["rgba"].torch - torch.testing.assert_close(published[0], expected[0], rtol=0, atol=0) - assert not torch.equal(published[1], expected[1]) - - -def test_sample_set_publication_keeps_environments_that_were_not_updated(monkeypatch) -> None: - """A sample-set camera publishes its own buffers: Newton redraws every row, but only updated rows change.""" - coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu") - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 8)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: None) - monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (None, None)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) - - def initialize_renderer(camera): - depth = torch.zeros((2, camera.cfg.height, camera.cfg.width, 1)) - camera._data = SimpleNamespace(output={"distance_to_camera": ProxyArray(wp.from_torch(depth))}) - camera._render_data = SimpleNamespace(camera_rays=None) - camera.renderer_depth = depth - - def render(camera, env_mask): - camera.renderer_depth.fill_(camera.frame_value) - - monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) - monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) - camera = new_camera() - camera.cfg = SimpleNamespace( - foveated_style="isotropic", - mask_to_sensor_fov=False, - pool_enabled=False, - image_rotation_deg=0, - update_period=0.0, - data_types=["distance_to_camera"], - renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), - ) - camera._initialize_impl() - published = camera._data.output["distance_to_camera"] - assert published.torch.shape == (2, len(coords), 1, 1) - assert published.warp.ptr != camera._flat_render_output["distance_to_camera"].warp.ptr - - camera.frame_value = 1.0 - camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) - camera.frame_value = 2.0 - camera._update_buffers_impl(wp.array([False, True], dtype=wp.bool, device="cpu")) - assert camera._data.output["distance_to_camera"] is published - assert bool((published.torch[0] == 1.0).all()) and bool((published.torch[1] == 2.0).all()) - - -def test_sample_set_sensor_mask_follows_the_published_frame(monkeypatch) -> None: - """An environment that was not updated keeps its published samples and the sensor visibility that masked them.""" - coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu") - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 8)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: None) - monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (None, None)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) - - def initialize_renderer(camera): - camera.renderer_depth = torch.ones((2, camera.cfg.height, camera.cfg.width, 1)) - camera._data = SimpleNamespace(output={"distance_to_camera": ProxyArray(wp.from_torch(camera.renderer_depth))}) - camera._render_data = SimpleNamespace(camera_rays=None) - - monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) - monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", lambda camera, env_mask: None) - camera = new_camera() - camera.cfg = SimpleNamespace( - foveated_style="isotropic", - mask_to_sensor_fov=True, - camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), - spawn=None, - pool_enabled=False, - image_rotation_deg=0, - update_period=0.0, - data_types=["distance_to_camera"], - renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), - ) - camera._initialize_impl() - # The real gaze geometry, on stand-in pose buffers. - base_camera.FoveatedCamera._initialize_gaze(camera) - camera._view = SimpleNamespace(count=2, close=lambda: None) - camera._data.quat_w_ros = ProxyArray(wp.from_torch(torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2), dtype=wp.quatf)) - - # The second camera looks away from the physical camera's image, so it sees nothing. - camera.set_gaze_angles(torch.tensor([[0.0, 0.0], [0.0, 180.0]])) - camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) - seen = camera.sensor_fov_valid_fraction.clone() - assert seen[0] > 0.5 and seen[1] == 0 - # Both look ahead now, but only the first camera's frame is published. - camera.set_gaze_angles(torch.zeros(2, 2)) - camera._update_buffers_impl(wp.array([True, False], dtype=wp.bool, device="cpu")) - assert not camera._data.output["distance_to_camera"].torch[1].any() - torch.testing.assert_close(camera.sensor_fov_valid_fraction, seen) - - -def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatch) -> None: - """A pooled camera's segmentation output holds each sample's majority label exactly, IDs above 2**24 included.""" - coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") - highres = coords.clone(resolution=32) - runs = torch.arange(len(coords)) - # Each pooled sample's neighbours are a run of four rendered samples, nearest first. - neighbors = torch.stack([4 * runs + j for j in range(4)]) - average = torch.nn.AdaptiveAvgPool1d(len(coords)) - - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) - monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (average, 4)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) - # The camera reads the modal neighbourhoods from its standard pooler. - monkeypatch.setattr(base_camera, "segmentation_neighbor_indices", lambda pooler: neighbors) - - def initialize_renderer(camera): - size = (2, camera.cfg.height, camera.cfg.width) - camera.renderer_rgba = torch.zeros((*size, 4), dtype=torch.uint8) - camera.renderer_labels = torch.zeros((*size, 1), dtype=torch.int32) - camera._data = SimpleNamespace( - output={ - "rgba": ProxyArray(wp.from_torch(camera.renderer_rgba)), - "semantic_segmentation": ProxyArray(wp.from_torch(camera.renderer_labels)), - } +def test_native_grid_render_size_must_fill_newton_tiles(): + camera = SimpleNamespace( + cfg=SimpleNamespace( + width=83, + height=83, + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=16, tile_rendering_height=8), ) - camera._render_data = SimpleNamespace(camera_rays=None) - camera._renderer = SimpleNamespace(cleanup=lambda render_data: None) - - # In each run, three samples share a label above 2**24 and one differs; float32 would merge neighbouring labels. - majority = 2**24 + 1 + 2 * runs - labels = majority[:, None].repeat(1, 4) - labels[:, 2] = 2**30 + runs - labels = torch.stack((labels.reshape(-1), (labels + 7).reshape(-1))) - - def render(camera, env_mask): - camera.renderer_labels.copy_(labels.to(torch.int32).reshape(camera.renderer_labels.shape)) - - monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) - monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) - camera = new_camera() - camera.cfg = SimpleNamespace( - foveated_style="warped_cartesian_as_grid", - mask_to_sensor_fov=False, - update_period=0.0, - pool_enabled=True, - pool_mode="avg", - pool_sample_cortex=False, - image_rotation_deg=0, - data_types=["rgba", "semantic_segmentation"], - renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), - ) - camera._initialize_impl() - camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) - - # The modal label of each run after the footprint mask zeroes samples outside the retina, ties to the nearest. - rendered = labels.clone() - rendered[:, ~highres.valid_mask] = 0 - expected = torch.zeros(2, len(coords), dtype=torch.int64) - for env in range(2): - for sample in range(len(coords)): - run = rendered[env, 4 * sample : 4 * sample + 4].tolist() - expected[env, sample] = max(run, key=lambda label: (run.count(label), -run.index(label))) - published = camera._data.output["semantic_segmentation"].torch - assert published.dtype == torch.int32 - torch.testing.assert_close(published[..., 0].long(), coords.as_grid(expected, sample_dim=1), rtol=0, atol=0) - assert camera.image_shape == (16, 16) and camera._data.image_shape == (16, 16) - - -def test_native_grid_render_size_must_fill_newton_tiles() -> None: - """A fractional pool_res_mult can give a grid that Newton's tiles do not divide; the camera rejects it.""" - FoveatedNewtonCamera._validate_native_render_layout( - SimpleNamespace(cfg=SimpleNamespace(width=128, height=128)), 16, 8 ) with pytest.raises(ValueError, match="83x83.*16x8"): - FoveatedNewtonCamera._validate_native_render_layout( - SimpleNamespace(cfg=SimpleNamespace(width=83, height=83)), 16, 8 - ) - - -def test_explicit_rays_keep_sample_order_and_pad_whole_tiles() -> None: - """Newton receives one ray per sample from the optical centre, in sample order, padded to whole tiles.""" - wp.init() - directions = torch.nn.functional.normalize(torch.randn(5, 3, generator=torch.Generator().manual_seed(0)), dim=-1) - rays = explicit_rays(directions, 2, 4) - assert rays.shape == (2, 4, 1, 2) and rays.dtype == wp.vec3f - rays = wp.to_torch(rays).reshape(8, 2, 3) - torch.testing.assert_close(rays[:5, 1], directions) - torch.testing.assert_close(rays[5:, 1], directions[-1].expand(3, -1)) - assert not rays[:, 0].any() - with pytest.raises(ValueError, match="shape"): - explicit_rays(torch.zeros(3, 2), 3, 1) - with pytest.raises(ValueError, match="cannot hold"): - explicit_rays(torch.zeros(5, 3), 2, 2) - - -def test_pooled_rgb_is_the_view_of_pooled_rgba(monkeypatch) -> None: - """The renderer publishes rgb as a view of rgba even when only rgba is requested, and so do pooled sample sets.""" - style = "isotropic" - coords = SamplingCoords(60.0, 0.591, 16, style=style, field_geometry="spherical", device="cpu") - highres = coords.clone(resolution=32) - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) - monkeypatch.setattr( - newton_camera, "build_pooler", lambda *args, **kwargs: (torch.nn.AdaptiveAvgPool1d(len(coords)), 4) - ) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) - - def initialize_renderer(camera): - camera.renderer_rgba = torch.zeros((2, camera.cfg.height, camera.cfg.width, 4), dtype=torch.uint8) - rgba = ProxyArray(wp.from_torch(camera.renderer_rgba)) - camera._data = SimpleNamespace( - output={"rgba": rgba, "rgb": ProxyArray(wp.from_torch(camera.renderer_rgba[..., :3]))} - ) - camera._render_data = SimpleNamespace(camera_rays=None) - camera._renderer = SimpleNamespace(cleanup=lambda render_data: None) - - def render(camera, env_mask): - camera.renderer_rgba.copy_(torch.tensor([10, 20, 30, 255], dtype=torch.uint8)) - - monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) - monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) - camera = new_camera() - camera.cfg = SimpleNamespace( - foveated_style=style, - mask_to_sensor_fov=False, - update_period=0.0, - pool_enabled=True, - pool_mode="avg", - pool_sample_cortex=False, - image_rotation_deg=0, - data_types=["rgba"], - renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), - ) - camera._initialize_impl() - camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) - - rgb, rgba = camera._data.output["rgb"].torch, camera._data.output["rgba"].torch - assert rgb.any() - torch.testing.assert_close(rgb, rgba[..., :3], rtol=0, atol=0) - # rgb is a view of rgba, not a copy: a write to rgba shows through it. - assert rgb.data_ptr() == rgba.data_ptr() - rgba[..., 0] = 7 - assert bool((rgb[..., 0] == 7).all()) + FoveatedNewtonCamera._initialize_impl(camera) def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch) -> None: @@ -367,8 +36,9 @@ def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch) -> None: def replace_rays(*args, **kwargs): raise AssertionError("the stock setter replaces the renderer's rays") - monkeypatch.setattr(newton_camera.Camera, "set_intrinsic_matrices", replace_rays) - camera = new_camera() + monkeypatch.setattr(Camera, "set_intrinsic_matrices", replace_rays) + monkeypatch.setattr(Camera, "__del__", lambda self: None) + camera = object.__new__(FoveatedNewtonCamera) with pytest.warns(UserWarning, match="leaves a foveated camera as configured") as caught: camera.set_intrinsic_matrices(torch.eye(3).repeat(2, 1, 1)) # The warning points at the caller's line. diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py deleted file mode 100644 index d8cda0eb5880..000000000000 --- a/source/isaaclab_fovi/test/test_pooling.py +++ /dev/null @@ -1,172 +0,0 @@ -# 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 - -"""The camera's pooling of its sensor buffers, segmentation and sensor mask, without a simulator. - -fovi's poolers are tested in fovi; these tests cover what the camera builds on them. -""" - -import pytest -import torch -from isaaclab_fovi.sensors import FoveatedCameraCfg, pooling -from isaaclab_fovi.sensors.pooling import ( - build_highres_coords, - build_lowres_coords, - build_pooler, - pool_hwc_buffer, - pool_segmentation_buffer, - segmentation_neighbor_indices, -) - -from isaaclab.sim import PinholeCameraCfg -from isaaclab.test.utils import DeviceScope, test_devices - -pytestmark = pytest.mark.kitless - -DEVICE = next(iter(test_devices(DeviceScope.DEFAULT_CUDA)), "cpu") -"""The modal pooling runs the same tensor operations on every device; the default GPU is what simulations use.""" - - -def pooling_cfg(**overrides) -> FoveatedCameraCfg: - """A pooled foveated camera configuration for the pooling helpers, with ``overrides`` applied. - - A 90 degree pinhole window (focal length 1, aperture 2) with a CMF constant of a tenth of it, and a small isotropic - retina pooled from three visual-field neighbours. - """ - values = dict( - prim_path="/World/Camera", - spawn=PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0), - cmf_a_deg=9.0, - foveated_res=8, - foveated_style="isotropic", - pool_enabled=True, - pool_k=3, - pool_sample_cortex=False, - ) - return FoveatedCameraCfg(**{**values, **overrides}) - - -def test_camera_pools_its_buffers_by_its_config() -> None: - cfg = pooling_cfg(pool_mode="max") - lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, lowres, matched) - # The photoreceptor grid shares the retina's geometry at a higher resolution, and the pooler takes the config. - assert len(highres) > len(lowres) and highres.cmf_a == lowres.cmf_a and highres.fov == lowres.fov - pooler, neighbors = build_pooler(cfg, lowres, highres, "cpu") - assert neighbors == 3 and pooler.mode == "max" - # Pooling keeps each environment's channels apart and in order. - constants = torch.tensor([[0.25, 0.5, 0.75], [3.0, 6.0, 9.0]]) - rendered = constants[:, None, None, :].expand(2, len(highres), 1, 3).clone() - actual = pool_hwc_buffer(pooler, rendered) - assert actual.dtype == rendered.dtype - torch.testing.assert_close(actual, constants[:, None, None, :].expand(2, len(lowres), 1, 3)) - # Without pooling there is no photoreceptor grid. - cfg = pooling_cfg(pool_enabled=False) - lowres, matched = build_lowres_coords(cfg, "cpu") - assert build_highres_coords(cfg, lowres, matched) is None - - -# Three output samples over five input samples; 5 marks an excluded neighbour. Columns are outputs, rows are -# neighbour slots nearest first. -HAND_TABLE = torch.tensor([[0, 3, 5], [1, 4, 5], [2, 5, 5]]) - - -def test_modal_pooling_keeps_majority_color_vector() -> None: - # Output 0 sees [0,0,0,255] twice and [0,0,1,255] once; a per-channel max would give [0,0,1,255]. - # Output 1 sees one vote each for two colors (its third slot is excluded): the nearest neighbour wins. - # Output 2 has no valid neighbour and is zero. - colors = torch.tensor( - [[0, 0, 0, 255], [0, 0, 0, 255], [0, 0, 1, 255], [10, 20, 30, 255], [200, 100, 0, 255]], dtype=torch.uint8 - ) - rendered = colors[None, :, None, :].to(DEVICE) - pooled = pool_segmentation_buffer(HAND_TABLE.to(DEVICE), rendered) - expected = torch.tensor([[0, 0, 0, 255], [10, 20, 30, 255], [0, 0, 0, 0]], dtype=torch.uint8) - assert pooled.dtype == torch.uint8 - assert torch.equal(pooled.cpu(), expected[None, :, None, :]) - # Swapping the tied neighbours' order flips the winner. - swapped = HAND_TABLE[[1, 0, 2]].to(DEVICE) - assert torch.equal(pool_segmentation_buffer(swapped, rendered)[0, 1, 0].cpu(), colors[4]) - - -def test_modal_pooling_preserves_ids_above_float_precision() -> None: - # 2**24 + 1 and 2**24 + 3 round to other values in float32; the IDs must come back exactly. - big = 2**40 - ids = torch.tensor([2**24 + 1, 2**24 + 1, 2**24 + 3, big + 7, big + 7], dtype=torch.int64) - batch = torch.stack([ids, ids.flip(0)])[:, :, None, None].to(DEVICE) - pooled = pool_segmentation_buffer(HAND_TABLE.to(DEVICE), batch) - expected = torch.tensor([[2**24 + 1, big + 7, 0], [big + 7, 2**24 + 1, 0]], dtype=torch.int64) - assert pooled.dtype == torch.int64 - assert torch.equal(pooled[..., 0, 0].cpu(), expected) - # Two int64 channels exceed the 8-byte packed key; vectors differing only in the second channel stay distinct. - vectors = torch.tensor([[1, 2**40], [1, 2**40 + 1], [1, 2**40 + 1], [5, 6], [7, 8]], dtype=torch.int64) - pooled = pool_segmentation_buffer(HAND_TABLE.to(DEVICE), vectors[None, :, None, :].to(DEVICE)) - assert torch.equal(pooled[0, :, 0].cpu(), torch.tensor([[1, 2**40 + 1], [5, 6], [0, 0]])) - - -def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Tensor: - """Brute-force modal pooling of ``(B, N_hi, C)`` values over a ``(k, N_lo)`` neighbour table.""" - batch, num_inputs, channels = values.shape - out = torch.zeros(batch, table.shape[1], channels, dtype=values.dtype) - for b in range(batch): - for n in range(table.shape[1]): - neighbours = [tuple(values[b, i].tolist()) for i in table[:, n].tolist() if i != num_inputs] - if neighbours: - # max() keeps the first of equally common values, i.e. the earliest neighbour slot. - out[b, n] = torch.tensor(max(neighbours, key=neighbours.count), dtype=values.dtype) - return out - - -@pytest.mark.parametrize( - ("style", "pool_k", "sample_cortex"), [("warped_cartesian_as_grid", 9, False), ("isotropic", 3, False)] -) -def test_modal_pooling_uses_the_poolers_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex) -> None: - """Segmentation pools over the same neighbourhoods as the camera's other outputs: grid windows or KNN.""" - cfg = pooling_cfg(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex, pool_mode="max") - lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, lowres, matched) - pooler, k = build_pooler(cfg, lowres, highres, "cpu") - table = segmentation_neighbor_indices(pooler) - assert table.shape == (k, len(lowres)) - # The table holds exactly the samples the max pooler reduces over: a max over the table matches it. - values = torch.rand(1, len(highres), 1, 1, generator=torch.Generator().manual_seed(0)) + 1 - padded = torch.cat([values[0, :, 0, 0], torch.zeros(1)]) - torch.testing.assert_close(padded[table].max(dim=0).values, pool_hwc_buffer(pooler, values)[0, :, 0, 0]) - - # Few labels so neighbourhoods hold repeats and ties; tiny chunks exercise the batched loop. - monkeypatch.setattr(pooling, "_MODAL_CHUNK_ELEMENTS", 1) - labels = torch.randint(0, 3, (3, len(highres), 1, 2), generator=torch.Generator().manual_seed(1)).to(torch.uint8) - pooled = pool_segmentation_buffer(table, labels) - assert torch.equal(pooled[:, :, 0], reference_modal_pool(table, labels[:, :, 0])) - - -@pytest.mark.parametrize(("style", "pool_k", "mode"), [("warped_cartesian_as_grid", 9, "avg"), ("isotropic", 6, "max")]) -def test_pooling_leaves_out_photoreceptors_the_camera_does_not_see(style: str, pool_k: int, mode: str) -> None: - cfg = pooling_cfg(foveated_style=style, pool_mode=mode, pool_k=pool_k) - lowres, matched = build_lowres_coords(cfg, DEVICE) - highres = build_highres_coords(cfg, lowres, matched) - pooler, _ = build_pooler(cfg, lowres, highres, DEVICE) - # The camera's image edge cuts the retina at x = 0.3 in the first environment; the second sees everything. - visible = torch.stack([highres.cartesian[:, 0] < 0.3, torch.ones(len(highres), dtype=torch.bool, device=DEVICE)]) - # The camera zeroes unseen photoreceptors before pooling. A negative value lets those zeros win a plain max. - value = -0.7 if mode == "max" else 0.7 - values = torch.where(visible, value, 0.0)[:, :, None, None] - pooled = pool_hwc_buffer(pooler, values, visible)[:, :, 0, 0] - unseen = pool_hwc_buffer(pooler, visible.float()[:, :, None, None], visible)[:, :, 0, 0] == 0 - # Some outputs straddle the edge: plain pooling lets the mask's zeros into them. - straddling = (pool_hwc_buffer(pooler, values)[0, :, 0, 0] - value).abs() > 0.01 - assert (straddling & ~unseen[0] & lowres.valid_mask).any() - # Each output pools only what the camera sees: the constant where it sees any photoreceptor, zero where it sees - # none or lies outside the retina. - expected = torch.where(unseen | ~lowres.valid_mask, 0.0, value) - torch.testing.assert_close(pooled, expected) - assert unseen[0].any() and not unseen[1, lowres.valid_mask].any() - - -def test_modal_pooling_leaves_out_labels_the_camera_does_not_see() -> None: - # Output 0 sees labels [1, 1, 2]; hiding the two 1s leaves 2. Output 1 sees [4, 5]; hiding both leaves nothing. - labels = torch.tensor([1, 1, 2, 4, 5], dtype=torch.int32)[None, :, None, None].expand(2, -1, -1, -1) - visible = torch.tensor([[False, False, True, False, False], [True, True, True, True, True]]) - pooled = pool_segmentation_buffer(HAND_TABLE, labels, visible)[..., 0, 0] - assert torch.equal(pooled, torch.tensor([[2, 0, 0], [1, 4, 0]], dtype=torch.int32)) diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index 475536832e13..02594a411ab5 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -5,22 +5,18 @@ """RTX camera contracts that need no renderer: construction, lens textures and their USD schema, and capture.""" -import math import tempfile from pathlib import Path from types import SimpleNamespace import pytest -import torch -import warp as wp from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera -from isaaclab_fovi.sensors.lens_lut import apply_lens_lut_to_prim, build_lut_textures +from isaaclab_fovi.sensors.lens_lut import apply_lens_lut_to_prim from isaaclab_ov.renderers import OVRTXRendererCfg from isaaclab.sensors.camera.camera import Camera from isaaclab.sim import PinholeCameraCfg -from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless @@ -46,37 +42,6 @@ def test_near_clip_comes_from_spawn_or_else_the_camera_prim() -> None: assert FoveatedRTXCamera._near_clipping_distance(spawned, prim) == pytest.approx(0.01) -@pytest.mark.parametrize("native_grid", [False, True]) -def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> None: - """Environments outside the update mask keep their samples, and each camera's near-plane offset is added once.""" - height, width = 4, 5 - texture = torch.arange(3 * height * width, dtype=torch.float32).reshape(3, height, width, 1) - if native_grid: - texels = [(py, px) for py in range(height) for px in range(width)] - else: - texels = [(3, 1), (0, 4), (2, 0), (1, 3), (3, 4), (0, 2), (2, 2)] - camera = SimpleNamespace( - cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")), - # An OVRTX camera with distance_to_camera output adds each camera's near clip. - _offset_distance=True, - _native_grid=native_grid, - _near_clip=torch.tensor([0.25, 0.5, 0.75]).view(-1, 1, 1, 1), - # The renderer-bound texture buffers are ProxyArrays, as the parent camera allocates them. - _texture_output={"distance_to_camera": ProxyArray(wp.from_torch(texture))}, - _foveated_output={"distance_to_camera": torch.full((3, len(texels), 1, 1), -1.0)}, - _extract_py=torch.tensor([py for py, _ in texels]), - _extract_px=torch.tensor([px for _, px in texels]), - ) - updated = wp.array([True, False, True], dtype=wp.bool, device="cpu") - for _ in range(2): - FoveatedRTXCamera._extract_foveated_samples(camera, updated) - samples = camera._foveated_output["distance_to_camera"] - for env, near_clip in ((0, 0.25), (2, 0.75)): - expected = torch.tensor([float(texture[env, py, px, 0]) + near_clip for py, px in texels]) - torch.testing.assert_close(samples[env, :, 0, 0], expected, atol=0, rtol=0) - assert bool((samples[1] == -1.0).all()) - - def test_releasing_the_camera_removes_its_lens_textures(monkeypatch, tmp_path) -> None: monkeypatch.setattr(Camera, "__del__", lambda self, *args, **kwargs: None) camera = object.__new__(FoveatedRTXCamera) @@ -101,7 +66,6 @@ def construct(self, cfg): self.stage = stage def prepare(self): - self.cfg.height = self.cfg.width = 64 self._dir_tex_path, self._exit_tex_path = "/textures/enter.exr", "/textures/exit.exr" monkeypatch.setattr(Camera, "__init__", construct) @@ -112,6 +76,7 @@ def prepare(self): spawn=PinholeCameraCfg(), renderer_cfg=OVRTXRendererCfg(), data_types=["rgb"], + foveated_res=64, ) assert cfg.spawn.lock_camera camera = FoveatedRTXCamera(cfg) @@ -141,32 +106,3 @@ def test_lens_lut_survives_usd_export_without_schema_registration() -> None: "generalizedProjectionNDCTexturePath", ): assert not prim.HasProperty(name), name - - -def test_sample_set_lens_textures_place_samples_and_mark_rays_outside_the_field() -> None: - # A sample set with one sample per texel, in shuffled order, puts each sample's ray at its own texel. - size = 4 - axis = (torch.arange(size) + 0.5) / size - row, col = torch.meshgrid(axis, axis, indexing="ij") - centres = torch.stack((col, row), -1).reshape(-1, 2) - order = torch.randperm(size * size, generator=torch.Generator().manual_seed(0)) - directions = torch.nn.functional.normalize(torch.randn(size * size, 3, generator=torch.Generator().manual_seed(1))) - direction_texture, _ = build_lut_textures(centres[order], directions, size, size, 16, 16, device="cpu") - texels = (centres[order] * size).long() - torch.testing.assert_close(direction_texture[texels[:, 1], texels[:, 0]], directions) - - # The inverse lookup sends each in-field ray to its nearest sample, and every other ray to the invalid UV, never - # to the fovea. Three samples: the optical axis (OpenGL -z) and two rays 10 degrees off it. - angle = math.radians(10.0) - directions = torch.tensor( - [[0.0, 0.0, -1.0], [math.sin(angle), 0.0, -math.cos(angle)], [0.0, math.sin(angle), -math.cos(angle)]] - ) - uv = torch.tensor([[0.5, 0.5], [0.9, 0.5], [0.5, 0.9]]) - _, exit_texture = build_lut_textures(uv, directions, 8, 8, 32, 32, device="cpu") - texels = exit_texture.reshape(-1, exit_texture.shape[-1])[:, :2] - invalid = (texels == -1.0).all(dim=-1) - # Rays outside the 10 degree field outnumber those inside it on the hemisphere's octahedral grid. - assert invalid.float().mean() > 0.5 and (~invalid).any() - assert all(any(torch.equal(texel, sample) for sample in uv) for texel in texels[~invalid]) - # The octahedral centre is the optical axis, which reaches the axis sample. - torch.testing.assert_close(exit_texture[exit_texture.shape[0] // 2, exit_texture.shape[1] // 2, :2], uv[0]) diff --git a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst deleted file mode 100644 index 94b3efa5d3dc..000000000000 --- a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst +++ /dev/null @@ -1,3 +0,0 @@ -* Added the ``IsaacContrib-Cartpole-Camera-Fovi`` task in :mod:`isaaclab_tasks.contrib.active_gaze`: the Cartpole - camera task with a foveated camera whose gaze the policy moves, trained with gaze-supervised PPO and a fixed gaze - action noise. It is registered when the ``fovi`` extra is installed. diff --git a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py deleted file mode 100644 index 9d0c06d83e82..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# 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 - -"""Active vision with a foveated camera: the policy moves the camera's gaze. - -The camera is :class:`isaaclab_fovi.sensors.FoveatedCamera`, from the optional ``fovi`` extra -(``uv sync --extra fovi``). The task is registered only when that extra is installed. -""" - -from importlib.util import find_spec - -import gymnasium as gym - -ISAACLAB_FOVI_AVAILABLE = find_spec("isaaclab_fovi") is not None and find_spec("fovi") is not None -"""Whether the ``fovi`` extra is installed: the foveated camera package and the fovi library it builds on.""" - -if ISAACLAB_FOVI_AVAILABLE: - gym.register( - id="IsaacContrib-Cartpole-Camera-Fovi", - entry_point="isaaclab.envs:ManagerBasedRLEnv", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.cartpole_camera_fovi_env_cfg:CartpoleCameraFoviEnvCfg", - "rsl_rl_cfg_entry_point": f"{__name__}.agents:CartpoleCameraFoviPPORunnerCfg", - "default_agent": "rsl_rl", - }, - ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py deleted file mode 100644 index 3544c85a35fb..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py +++ /dev/null @@ -1,85 +0,0 @@ -# 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 - -"""Building blocks of active-gaze camera tasks: a foveated version of a stock camera, and the gaze observations.""" - -from __future__ import annotations - -from dataclasses import MISSING, fields - -from isaaclab_fovi import mdp -from isaaclab_fovi.sensors import FoveatedCameraCfg - -from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg -from isaaclab.sensors import CameraCfg -from isaaclab.utils import configclass - -from isaaclab_tasks.utils import PresetCfg, preset - - -def foveated_camera(camera: CameraCfg, foveated_res: int | None = None) -> FoveatedCameraCfg: - """A foveated camera at the camera's mount, with its optics, data types and renderer. - - The retina covers the camera's short side and is ``foveated_res`` samples across, by default the camera's width, - so the number of rendered rays stays close to the camera's pixels. Samples the camera does not see are zero. - The foveated camera keeps its own image size and per-frame pose updates, which render each new gaze. - """ - # A copy, so the foveated camera shares no nested configuration (spawn, renderer, offset) with the preset's. - camera = camera.copy() - own = {"class_type", "width", "height", "update_latest_camera_pose"} - values = {field.name: getattr(camera, field.name) for field in fields(CameraCfg) if field.name not in own} - resolution = camera.width if foveated_res is None else foveated_res - return FoveatedCameraCfg(**values, foveated_res=resolution, mask_to_sensor_fov=True) - - -def foveated_presets(cameras: PresetCfg, foveated_res: int | None = None) -> PresetCfg: - """The foveated version of every camera preset, under the same names. Other sensors are left out. - - ``foveated_res`` applies to every preset; by default each keeps its camera's width. - """ - options = {} - for name in cameras.__dataclass_fields__: - camera = getattr(cameras, name) - if not name.startswith("_") and isinstance(camera, CameraCfg): - options[name] = foveated_camera(camera, foveated_res) - return preset(**options) - - -def select_presets(options: PresetCfg, names) -> PresetCfg: - """The options of a preset whose names are in ``names``, plus its default.""" - return preset( - **{name: getattr(options, name) for name in options.__dataclass_fields__ if name in {*names, "default"}} - ) - - -def oracle_observations( - target_cfg: SceneEntityCfg, offset: tuple[float, float, float] = (0.0, 0.0, 0.0) -) -> OracleObservationsCfg: - """The teacher's gaze labels toward a point fixed to an asset.""" - return OracleObservationsCfg( - labels=ObservationTermCfg(func=mdp.gaze_teacher_labels, params={"target_cfg": target_cfg, "offset": offset}) - ) - - -@configclass -class GazeObservationsCfg(ObservationGroupCfg): - """The gaze, in field radii, and its velocity, in field radii per second.""" - - state = ObservationTermCfg(func=mdp.gaze_state) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - -@configclass -class OracleObservationsCfg(ObservationGroupCfg): - """The teacher's gaze labels. Training labels, never a policy input.""" - - labels: ObservationTermCfg = MISSING - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py deleted file mode 100644 index 409c686b00e5..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py +++ /dev/null @@ -1,40 +0,0 @@ -# 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 - -"""RSL-RL agents of the active-gaze tasks: the stock PPO with gaze supervision and a fixed gaze noise.""" - -from dataclasses import fields - -from isaaclab.utils import configclass, replace - -from isaaclab_rl.rsl_rl import RslRlMLPModelCfg, RslRlPpoAlgorithmCfg - -from isaaclab_tasks.core.cartpole.agents.rsl_rl_ppo_cfg import CartpoleCameraPPORunnerCfg - -from .gaze_distribution_cfg import GazeGaussianDistributionCfg -from .gaze_supervised_ppo_cfg import GazeSupervisedPPOCfg - - -def gaze_supervised(algorithm: RslRlPpoAlgorithmCfg, **kwargs) -> GazeSupervisedPPOCfg: - """The PPO settings of ``algorithm`` with gaze supervision by the teacher.""" - values = {field.name: getattr(algorithm, field.name) for field in fields(algorithm) if field.name != "class_name"} - return GazeSupervisedPPOCfg(**values, **kwargs) - - -def gaze_actor(actor: RslRlMLPModelCfg) -> RslRlMLPModelCfg: - """The stock actor with a fixed, small noise on its gaze actions, the last two.""" - stock = actor.distribution_cfg - head = GazeGaussianDistributionCfg(init_std=stock.init_std, std_type=stock.std_type, std_range=stock.std_range) - return replace(actor, distribution_cfg=head) - - -@configclass -class CartpoleCameraFoviPPORunnerCfg(CartpoleCameraPPORunnerCfg): - """The stock Cartpole camera PPO with gaze supervision; the actor and critic also see the gaze.""" - - experiment_name = "cartpole_camera_fovi" - obs_groups = {"actor": ["policy", "gaze"], "critic": ["critic", "gaze"]} - actor = gaze_actor(CartpoleCameraPPORunnerCfg().actor) - algorithm = gaze_supervised(CartpoleCameraPPORunnerCfg().algorithm) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py deleted file mode 100644 index da42ff2226c3..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py +++ /dev/null @@ -1,85 +0,0 @@ -# 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 - -"""Cartpole with a foveated camera, in RGB or depth. - -The stock camera task with the camera foveated and two gaze actions. The teacher looks at the pole's tip. The retina -is :data:`RETINA_RES` samples across, enough for a task that only needs to see a bar. The policy gets two gaze actions, -whose noise is fixed, and the teacher's gaze labels supervise them during training. -""" - -from isaaclab_fovi import mdp - -from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg -from isaaclab.utils import configclass - -from isaaclab_tasks.core.cartpole import mdp as cartpole_mdp -from isaaclab_tasks.core.cartpole.cartpole_common import CartpoleTiledCameraCfg -from isaaclab_tasks.core.cartpole.cartpole_manager_camera_env_cfg import CartpoleCameraEnvCfg, CartpoleCameraSceneCfg -from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ActionsCfg as CartpoleActionsCfg -from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ObservationsCfg as CartpoleObservationsCfg -from isaaclab_tasks.utils import PresetCfg - -from .active_gaze_cfg import GazeObservationsCfg, foveated_presets, oracle_observations, select_presets - -POLE_TIP = (0.0, 0.0, 1.0) -"""The pole's tip in the pole's frame [m].""" - -RETINA_RES = 32 -"""Retina samples across; the stock camera is 96 pixels across.""" - - -def observations(data_type: str, image_term) -> object: - """The stock camera observations of ``data_type``, the gaze, and the teacher's labels.""" - - @configclass - class ObservationsCfg: - @configclass - class PolicyCfg(ObservationGroupCfg): - image = ObservationTermCfg( - func=image_term, - params={ - "sensor_cfg": SceneEntityCfg("tiled_camera"), - "data_type": data_type, - "channel_first": True, - "frame_stack": 2, - }, - ) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - policy: ObservationGroupCfg = PolicyCfg() - critic: ObservationGroupCfg = CartpoleObservationsCfg.PolicyCfg() - gaze: ObservationGroupCfg = GazeObservationsCfg() - oracle: ObservationGroupCfg = oracle_observations(SceneEntityCfg("robot", body_names="pole"), POLE_TIP) - - return ObservationsCfg() - - -@configclass -class SceneCfg(CartpoleCameraSceneCfg): - tiled_camera = select_presets(foveated_presets(CartpoleTiledCameraCfg(), RETINA_RES), ("rgb", "depth")) - - -@configclass -class ActionsCfg(CartpoleActionsCfg): - # The gaze must be the last action term. - gaze = mdp.GazeActionCfg(asset_name="tiled_camera") - - -@configclass -class CartpoleCameraFoviEnvCfg(PresetCfg): - """Cartpole with a foveated camera; ``presets=depth`` selects depth images.""" - - @configclass - class BaseCfg(CartpoleCameraEnvCfg.BaseCartpoleCameraEnvCfg): - scene: SceneCfg = SceneCfg(num_envs=512, env_spacing=20.0) - actions: ActionsCfg = ActionsCfg() - - rgb = BaseCfg(observations=observations("rgb", cartpole_mdp.image_rgb)) - depth = BaseCfg(observations=observations("depth", cartpole_mdp.image_depth)) - default = rgb diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py deleted file mode 100644 index 9829707c282f..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py +++ /dev/null @@ -1,61 +0,0 @@ -# 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 - -"""Gaussian action head whose gaze actions have a fixed standard deviation.""" - -from __future__ import annotations - -import math - -import torch -from rsl_rl.modules.distribution import GaussianDistribution -from torch.distributions import Normal - -GAZE_ACTIONS = 2 -"""The gaze actions (tilt, pan) are the policy's last two actions.""" - - -class GazeGaussianDistribution(GaussianDistribution): - """Gaussian action head with a learned standard deviation for every action but the gaze, the last two, whose - standard deviation is fixed at ``gaze_std``. - - The gaze step clamps each gaze action to [-1, 1], so beyond that range a wider gaze distribution changes neither - the reward nor PPO's surrogate, and the entropy bonus grows a learned standard deviation without bound; the sampled - gaze then random-walks however well its mean follows the teacher. - - Args: - output_dim: Number of actions, the two gaze actions included. - init_std: Initial standard deviation of the other actions. - std_range: (min, max) clamp of the other actions' standard deviation. - std_type: Parameterization of the other actions' standard deviation: ``"scalar"`` or ``"log"``. - learn_std: Whether the other actions' standard deviation is learned. - gaze_std: Fixed standard deviation of the gaze actions. - """ - - def __init__( - self, - output_dim: int, - init_std: float = 1.0, - std_range: tuple[float, float] = (1e-6, 1e6), - std_type: str = "scalar", - learn_std: bool = True, - gaze_std: float = 0.1, - ) -> None: - if output_dim <= GAZE_ACTIONS: - raise ValueError(f"The gaze head needs actions besides the {GAZE_ACTIONS} gaze actions, got {output_dim}.") - if not (math.isfinite(gaze_std) and gaze_std > 0): - raise ValueError(f"gaze_std must be positive and finite, got {gaze_std!r}.") - # The learned parameter covers the other actions only. - super().__init__(output_dim - GAZE_ACTIONS, init_std, std_range, std_type, learn_std) - self.output_dim = output_dim - self.register_buffer("gaze_std", torch.full((GAZE_ACTIONS,), float(gaze_std))) - - def update(self, mlp_output: torch.Tensor) -> None: - """Update the distribution from the MLP output: learned noise for the other actions, fixed for the gaze.""" - if self.std_type == "scalar": - std = self.std_param.clamp(self.std_range[0], self.std_range[1]) - else: - std = self.log_std_param.clamp(self.log_std_range[0], self.log_std_range[1]).exp() - self._distribution = Normal(mlp_output, torch.cat((std, self.gaze_std))) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py deleted file mode 100644 index fac45da54582..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py +++ /dev/null @@ -1,24 +0,0 @@ -# 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 - -"""Configuration of :class:`~isaaclab_tasks.contrib.active_gaze.gaze_distribution.GazeGaussianDistribution`.""" - -from __future__ import annotations - -from isaaclab.utils import configclass - -from isaaclab_rl.rsl_rl import RslRlMLPModelCfg - - -@configclass -class GazeGaussianDistributionCfg(RslRlMLPModelCfg.GaussianDistributionCfg): - """Gaussian action head whose gaze actions, the last two, have a fixed standard deviation. - - ``init_std``, ``std_type`` and ``std_range`` apply to the other actions. - """ - - class_name: str = "isaaclab_tasks.contrib.active_gaze.gaze_distribution:GazeGaussianDistribution" - gaze_std: float = 0.1 - """Fixed standard deviation of the gaze actions. One action moves the gaze by the gaze action's ``step_size``.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py deleted file mode 100644 index 3e1990dfdeb7..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py +++ /dev/null @@ -1,134 +0,0 @@ -# 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 - -"""PPO with gaze supervision by a teacher, for RSL-RL. - -The update follows :meth:`rsl_rl.algorithms.PPO.update` (BSD-3-Clause) for feedforward models without RND or -symmetry, and adds the teacher's gaze loss to the PPO loss. -""" - -from __future__ import annotations - -import math - -import torch -from rsl_rl.algorithms import PPO -from torch import nn - -from .gaze_distribution import GAZE_ACTIONS - - -def gaze_loss(mean: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: - """Mean distance between the policy's gaze-action means and the teacher's, over valid labels. - - Args: - mean: The policy's gaze-action means, shape (batch, 2). - labels: The teacher's gaze actions and their validity, shape (batch, 3). - """ - valid = labels[:, 2] > 0.5 - # Invalid rows may hold NaN; replacing it keeps their (discarded) residuals finite, so no NaN reaches the gradients. - residual = torch.where(valid[:, None], mean - torch.nan_to_num(labels[:, :2]), 0.0) - return residual.norm(dim=-1).sum() / valid.sum().clamp_min(1) - - -class GazeSupervisedPPO(PPO): - """PPO whose loss also pulls the policy's gaze toward a teacher's. - - The gaze is the last two actions. The teacher's labels are the observation group ``oracle_group``, as - :class:`isaaclab_fovi.mdp.gaze_teacher_labels` computes them; they never enter the actor or the critic. Only the - means of the gaze actions are supervised; pair it with - :class:`~isaaclab_tasks.contrib.active_gaze.gaze_distribution.GazeGaussianDistribution`, which fixes their noise. - - Args: - oracle_loss_coef: Weight of the gaze loss. Zero trains plain PPO. - oracle_group: Observation group of the teacher's labels. - """ - - def __init__( - self, - actor, - critic, - storage, - *, - oracle_loss_coef: float = 1.0, - oracle_group: str = "oracle", - **kwargs, - ): - if actor.is_recurrent or critic.is_recurrent or kwargs.get("rnd_cfg") or kwargs.get("symmetry_cfg"): - raise ValueError("GazeSupervisedPPO supports feedforward models without RND or symmetry.") - if not math.isfinite(oracle_loss_coef) or oracle_loss_coef < 0: - raise ValueError("oracle_loss_coef must be finite and nonnegative.") - super().__init__(actor, critic, storage, **kwargs) - self.oracle_loss_coef = oracle_loss_coef - self.oracle_group = oracle_group - - def update(self) -> dict[str, float]: - totals = torch.zeros(5, device=self.device) - generator = self.storage.mini_batch_generator(self.num_mini_batches, self.num_learning_epochs) - for batch in generator: - if self.normalize_advantage_per_mini_batch: - with torch.no_grad(): - batch.advantages = (batch.advantages - batch.advantages.mean()) / (batch.advantages.std() + 1e-8) - with torch.amp.autocast( - device_type=torch.device(self.device).type, enabled=self.use_mixed_precision, dtype=torch.bfloat16 - ): - self.actor(batch.observations, stochastic_output=True) - log_prob = self.actor.get_output_log_prob(batch.actions) - values = self.critic(batch.observations) - entropy = self.actor.output_entropy.mean() - if self.desired_kl is not None and self.schedule == "adaptive": - self._adapt_learning_rate(batch.old_distribution_params, self.actor.output_distribution_params) - ratio = torch.exp(log_prob - batch.old_actions_log_prob.squeeze(-1)) - advantages = batch.advantages.squeeze(-1) - surrogate = torch.max( - -advantages * ratio, -advantages * ratio.clamp(1.0 - self.clip_param, 1.0 + self.clip_param) - ).mean() - value_error = (values - batch.returns).pow(2) - if self.use_clipped_value_loss: - clipped = batch.values + (values - batch.values).clamp(-self.clip_param, self.clip_param) - value_error = torch.max(value_error, (clipped - batch.returns).pow(2)) - value_loss = value_error.mean() - loss = surrogate + self.value_loss_coef * value_loss - self.entropy_coef * entropy - if self.oracle_loss_coef > 0: - labels = batch.observations[self.oracle_group].float() - oracle = gaze_loss(self.actor.output_mean[:, -GAZE_ACTIONS:].float(), labels) - valid = (labels[:, 2] > 0.5).float().mean() - loss = loss + self.oracle_loss_coef * oracle - else: - # Plain PPO: the teacher's labels are neither needed nor read. - oracle = valid = torch.zeros((), device=self.device) - self.optimizer.zero_grad() - loss.backward() - if self.is_multi_gpu: - self.reduce_parameters() - nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm) - nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm) - self.optimizer.step() - totals += torch.stack((value_loss, surrogate, entropy, oracle, valid)).detach().float() - obs = self.storage.observations.flatten(0, 1) - self.actor.update_normalization(obs) - self.critic.update_normalization(obs) - self.storage.clear() - means = (totals / (self.num_learning_epochs * self.num_mini_batches)).tolist() - return dict(zip(("value", "surrogate", "entropy", "oracle", "oracle_valid"), means, strict=True)) - - def _adapt_learning_rate(self, old_params, new_params): - """Adapt the learning rate to the policy's KL divergence, as PPO's adaptive schedule does.""" - with torch.inference_mode(): - kl = self.actor.get_kl_divergence(old_params, new_params).mean() - if self.is_multi_gpu: - torch.distributed.all_reduce(kl, op=torch.distributed.ReduceOp.SUM) - kl /= self.gpu_world_size - if self.gpu_global_rank == 0: - if kl > self.desired_kl * 2.0: - self.learning_rate = max(1e-5, self.learning_rate / 1.5) - elif 0.0 < kl < self.desired_kl / 2.0: - self.learning_rate = min(1e-2, self.learning_rate * 1.5) - if self.is_multi_gpu: - rate = torch.tensor(self.learning_rate, device=self.device) - torch.distributed.broadcast(rate, src=0) - self.learning_rate = rate.item() - for group in self.optimizer.param_groups: - group["lr"] = self.learning_rate diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py deleted file mode 100644 index 907dc6773afb..000000000000 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py +++ /dev/null @@ -1,26 +0,0 @@ -# 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 - -"""Configuration of :class:`~isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo.GazeSupervisedPPO`.""" - -from __future__ import annotations - -from isaaclab.utils import configclass - -from isaaclab_rl.rsl_rl import RslRlPpoAlgorithmCfg - - -@configclass -class GazeSupervisedPPOCfg(RslRlPpoAlgorithmCfg): - """PPO whose loss also pulls the policy's gaze toward a teacher's. - - See :class:`~isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo.GazeSupervisedPPO`. - """ - - class_name: str = "isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo:GazeSupervisedPPO" - oracle_loss_coef: float = 1.0 - """Weight of the gaze loss. Zero trains plain PPO.""" - oracle_group: str = "oracle" - """Observation group of the teacher's labels.""" diff --git a/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py b/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py deleted file mode 100644 index 3ed040c4f789..000000000000 --- a/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py +++ /dev/null @@ -1,129 +0,0 @@ -# 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 - -"""Gaze-supervised PPO and the fixed-noise gaze head of the active-gaze tasks, without a simulator.""" - -import pytest -import torch -from rsl_rl.algorithms import PPO -from rsl_rl.models import MLPModel -from rsl_rl.storage import RolloutStorage -from tensordict import TensorDict - -from isaaclab_tasks.contrib.active_gaze.gaze_distribution import GazeGaussianDistribution -from isaaclab_tasks.contrib.active_gaze.gaze_distribution_cfg import GazeGaussianDistributionCfg -from isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss - -pytestmark = pytest.mark.kitless - -NUM_ENVS = 64 -STEPS = 8 - - -def test_gaze_loss_ignores_invalid_labels(): - mean = torch.tensor([[0.0, 0.0], [1.0, 1.0]], requires_grad=True) - labels = torch.tensor([[0.3, 0.4, 1.0], [float("nan"), float("nan"), 0.0]]) - loss = gaze_loss(mean, labels) - loss.backward() - assert float(loss.detach()) == pytest.approx(0.5) - assert torch.isfinite(mean.grad).all() and not mean.grad[1].any() - - -def _algorithm( - oracle_loss_coef: float = 1.0, with_labels: bool = True, stock: bool = False, gaze_head: bool = False -) -> tuple[PPO | GazeSupervisedPPO, TensorDict]: - torch.manual_seed(0) - labels = torch.rand(NUM_ENVS, 3) * 2 - 1 - labels[:, 2] = (torch.arange(NUM_ENVS) % 4 != 0).float() - labels[labels[:, 2] == 0, :2] = float("nan") - groups = {"policy": torch.randn(NUM_ENVS, 6)} | ({"oracle": labels} if with_labels else {}) - obs = TensorDict(groups, batch_size=[NUM_ENVS]) - model_groups = {"actor": ["policy"], "critic": ["policy"]} - distribution = {"class_name": "GaussianDistribution", "init_std": 1.0} - if gaze_head: - head = GazeGaussianDistributionCfg(init_std=1.0, gaze_std=0.1) - distribution = {"class_name": head.class_name, "init_std": 1.0, "gaze_std": head.gaze_std} - actor = MLPModel(obs, model_groups, "actor", 3, hidden_dims=[32], distribution_cfg=distribution) - critic = MLPModel(obs, model_groups, "critic", 1, hidden_dims=[32]) - storage = RolloutStorage("rl", NUM_ENVS, STEPS, obs, [3], "cpu") - settings = dict(num_learning_epochs=4, num_mini_batches=4, learning_rate=3e-3, schedule="fixed", device="cpu") - if stock: - return PPO(actor, critic, storage, **settings), obs - return GazeSupervisedPPO(actor, critic, storage, oracle_loss_coef=oracle_loss_coef, **settings), obs - - -def _train(algorithm: PPO, obs: TensorDict, iterations: int) -> dict[str, float]: - for _ in range(iterations): - for _ in range(STEPS): - with torch.inference_mode(): - algorithm.act(obs) - algorithm.process_env_step(obs, torch.zeros(NUM_ENVS), torch.zeros(NUM_ENVS), {}) - algorithm.compute_returns(obs) - losses = algorithm.update() - return losses - - -def test_update_pulls_the_gaze_toward_the_teacher(): - algorithm, obs = _algorithm() - valid = obs["oracle"][:, 2] > 0.5 - - def distance() -> float: - with torch.no_grad(): - mean = algorithm.actor(obs)[:, -2:] - return float((mean - obs["oracle"][:, :2])[valid].norm(dim=-1).mean()) - - before = distance() - losses = _train(algorithm, obs, 40) - assert losses["oracle_valid"] == pytest.approx(0.75) - assert all(torch.isfinite(p).all() for p in algorithm.actor.parameters()) - assert distance() < 0.7 * before - - -def test_zero_coefficient_update_matches_stock_ppo_without_labels(): - def updated(stock: bool) -> tuple[list[torch.Tensor], list[torch.Tensor], dict[str, float]]: - algorithm, obs = _algorithm(oracle_loss_coef=0.0, with_labels=False, stock=stock) - modules = (algorithm.actor, algorithm.critic) - initial = [p.detach().clone() for module in modules for p in module.parameters()] - torch.manual_seed(1) - losses = _train(algorithm, obs, 1) - return initial, [p.detach().clone() for module in modules for p in module.parameters()], losses - - initial, gaze_params, losses = updated(stock=False) - stock_initial, stock_params, stock_losses = updated(stock=True) - assert losses["oracle"] == 0.0 and losses["oracle_valid"] == 0.0 - for name in ("value", "surrogate", "entropy"): - assert losses[name] == pytest.approx(stock_losses[name], rel=1e-6, abs=1e-7) - for start, stock_start in zip(initial, stock_initial, strict=True): - torch.testing.assert_close(start, stock_start, atol=0, rtol=0) - for param, stock_param in zip(gaze_params, stock_params, strict=True): - torch.testing.assert_close(param, stock_param, atol=0, rtol=0) - assert all(not torch.equal(param, start) for param, start in zip(gaze_params, initial, strict=True)) - - -def test_gaze_head_keeps_the_gaze_noise_fixed_while_ppo_learns_the_rest(): - """The entropy bonus and the surrogate move the other actions' noise, never the gaze's.""" - algorithm, obs = _algorithm(gaze_head=True) - algorithm.entropy_coef = 0.5 - head = algorithm.actor.distribution - assert isinstance(head, GazeGaussianDistribution) - assert head.std_param.shape == (1,) - _train(algorithm, obs, iterations=3) - with torch.no_grad(): - head.update(torch.zeros(1, 3)) - std = head.std[0] - torch.testing.assert_close(std[1:], torch.full((2,), 0.1)) - assert abs(float(std[0]) - 1.0) > 1e-3 - # The gaze noise is part of the saved policy, so a checkpoint restores it. - assert torch.equal(head.state_dict()["gaze_std"], torch.full((2,), 0.1)) - - -def test_gaze_head_fixes_the_last_two_actions_noise_and_rejects_invalid_settings(): - head = GazeGaussianDistribution(5, init_std=2.0, std_type="log", gaze_std=0.05) - assert head.input_dim == 5 - head.update(torch.zeros(3, 5)) - torch.testing.assert_close(head.std, torch.tensor([[2.0, 2.0, 2.0, 0.05, 0.05]]).expand(3, -1)) - for output_dim, gaze_std in ((5, 0.0), (5, float("inf")), (2, 0.1)): - with pytest.raises(ValueError, match="gaze"): - GazeGaussianDistribution(output_dim, gaze_std=gaze_std) From daef1154554317f4e9010461754a5e0c35b1d3f9 Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Thu, 19 Nov 2026 15:59:24 -0800 Subject: [PATCH 46/81] Keep Cartpole with stock PPO and concise foveation docs --- .../source/_static/css/environment-browser.js | 1 + .../concepts/sensors/foveated_camera.rst | 230 +++--------------- .../active-gaze-cartpole.added.rst | 2 + .../changelog.d/active-gaze-cartpole.minor | 0 .../contrib/active_gaze/__init__.py | 29 +++ .../contrib/active_gaze/agents.py | 18 ++ .../cartpole_camera_fovi_env_cfg.py | 86 +++++++ .../test/core/test_cartpole_camera_presets.py | 22 ++ 8 files changed, 194 insertions(+), 194 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst create mode 100644 source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py diff --git a/docs/source/_static/css/environment-browser.js b/docs/source/_static/css/environment-browser.js index 66bbc79dd875..f1793a6e0d33 100644 --- a/docs/source/_static/css/environment-browser.js +++ b/docs/source/_static/css/environment-browser.js @@ -69,6 +69,7 @@ ["IsaacContrib-Assemble-Trocar-G129-Dex3", "rlinf", "isaacsim_physx,newton_mjwarp", "", "", "environments/previews/manipulation/g1_assemble_trocar.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "newton_mjwarp||"]], ["IsaacContrib-AutoMate-Assembly-Direct", "rl_games", "", "", "", "environment-previews/automate_assembly.jpg"], ["IsaacContrib-AutoMate-Disassembly-Direct", "rl_games", "", "", "", "environment-previews/automate_disassembly.jpg"], + ["IsaacContrib-Cartpole-Camera-Fovi", "rsl_rl", "isaacsim_physx,newton_kamino,newton_mjwarp,newton_steel,ovphysx", "isaacsim_rtx,newton_optix,newton_warp,ovrtx", "depth,rgb", "", false, {}, {}, "", null, ["||", "||depth", "||rgb", "|isaacsim_rtx|", "|isaacsim_rtx|depth", "|isaacsim_rtx|rgb", "|newton_optix|", "|newton_optix|depth", "|newton_optix|rgb", "|newton_warp|", "|newton_warp|depth", "|newton_warp|rgb", "|ovrtx|", "|ovrtx|depth", "|ovrtx|rgb", "isaacsim_physx||", "isaacsim_physx||depth", "isaacsim_physx||rgb", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|isaacsim_rtx|depth", "isaacsim_physx|isaacsim_rtx|rgb", "isaacsim_physx|newton_optix|", "isaacsim_physx|newton_optix|depth", "isaacsim_physx|newton_optix|rgb", "isaacsim_physx|newton_warp|", "isaacsim_physx|newton_warp|depth", "isaacsim_physx|newton_warp|rgb", "newton_kamino||", "newton_kamino||depth", "newton_kamino||rgb", "newton_kamino|isaacsim_rtx|", "newton_kamino|isaacsim_rtx|depth", "newton_kamino|isaacsim_rtx|rgb", "newton_kamino|newton_optix|", "newton_kamino|newton_optix|depth", "newton_kamino|newton_optix|rgb", "newton_kamino|newton_warp|", "newton_kamino|newton_warp|depth", "newton_kamino|newton_warp|rgb", "newton_kamino|ovrtx|", "newton_kamino|ovrtx|depth", "newton_kamino|ovrtx|rgb", "newton_mjwarp||", "newton_mjwarp||depth", "newton_mjwarp||rgb", "newton_mjwarp|isaacsim_rtx|", "newton_mjwarp|isaacsim_rtx|depth", "newton_mjwarp|isaacsim_rtx|rgb", "newton_mjwarp|newton_optix|", "newton_mjwarp|newton_optix|depth", "newton_mjwarp|newton_optix|rgb", "newton_mjwarp|newton_warp|", "newton_mjwarp|newton_warp|depth", "newton_mjwarp|newton_warp|rgb", "newton_mjwarp|ovrtx|", "newton_mjwarp|ovrtx|depth", "newton_mjwarp|ovrtx|rgb", "newton_steel||", "newton_steel||depth", "newton_steel||rgb", "newton_steel|isaacsim_rtx|", "newton_steel|isaacsim_rtx|depth", "newton_steel|isaacsim_rtx|rgb", "newton_steel|newton_optix|", "newton_steel|newton_optix|depth", "newton_steel|newton_optix|rgb", "newton_steel|newton_warp|", "newton_steel|newton_warp|depth", "newton_steel|newton_warp|rgb", "newton_steel|ovrtx|", "newton_steel|ovrtx|depth", "newton_steel|ovrtx|rgb", "ovphysx||", "ovphysx||depth", "ovphysx||rgb", "ovphysx|newton_optix|", "ovphysx|newton_optix|depth", "ovphysx|newton_optix|rgb", "ovphysx|newton_warp|", "ovphysx|newton_warp|depth", "ovphysx|newton_warp|rgb", "ovphysx|ovrtx|", "ovphysx|ovrtx|depth", "ovphysx|ovrtx|rgb"]], ["IsaacContrib-Cartpole-Camera-Showcase-Direct", "skrl", "", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete"]], ["IsaacContrib-Cartpole-Showcase-Direct", "skrl", "isaacsim_physx,newton_kamino,newton_mjwarp,newton_steel,ovphysx", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,discrete_box,discrete_discrete,discrete_multidiscrete,multidiscrete_box,multidiscrete_discrete,multidiscrete_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "environment-previews/cartpole.jpg", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||discrete_box", "||discrete_discrete", "||discrete_multidiscrete", "||multidiscrete_box", "||multidiscrete_discrete", "||multidiscrete_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete", "isaacsim_physx||", "isaacsim_physx||box_box", "isaacsim_physx||box_discrete", "isaacsim_physx||box_multidiscrete", "isaacsim_physx||dict_box", "isaacsim_physx||dict_discrete", "isaacsim_physx||dict_multidiscrete", "isaacsim_physx||discrete_box", "isaacsim_physx||discrete_discrete", "isaacsim_physx||discrete_multidiscrete", "isaacsim_physx||multidiscrete_box", "isaacsim_physx||multidiscrete_discrete", "isaacsim_physx||multidiscrete_multidiscrete", "isaacsim_physx||tuple_box", "isaacsim_physx||tuple_discrete", "isaacsim_physx||tuple_multidiscrete", "newton_kamino||", "newton_kamino||box_box", "newton_kamino||box_discrete", "newton_kamino||box_multidiscrete", "newton_kamino||dict_box", "newton_kamino||dict_discrete", "newton_kamino||dict_multidiscrete", "newton_kamino||discrete_box", "newton_kamino||discrete_discrete", "newton_kamino||discrete_multidiscrete", "newton_kamino||multidiscrete_box", "newton_kamino||multidiscrete_discrete", "newton_kamino||multidiscrete_multidiscrete", "newton_kamino||tuple_box", "newton_kamino||tuple_discrete", "newton_kamino||tuple_multidiscrete", "newton_mjwarp||", "newton_mjwarp||box_box", "newton_mjwarp||box_discrete", "newton_mjwarp||box_multidiscrete", "newton_mjwarp||dict_box", "newton_mjwarp||dict_discrete", "newton_mjwarp||dict_multidiscrete", "newton_mjwarp||discrete_box", "newton_mjwarp||discrete_discrete", "newton_mjwarp||discrete_multidiscrete", "newton_mjwarp||multidiscrete_box", "newton_mjwarp||multidiscrete_discrete", "newton_mjwarp||multidiscrete_multidiscrete", "newton_mjwarp||tuple_box", "newton_mjwarp||tuple_discrete", "newton_mjwarp||tuple_multidiscrete", "newton_steel||", "newton_steel||box_box", "newton_steel||box_discrete", "newton_steel||box_multidiscrete", "newton_steel||dict_box", "newton_steel||dict_discrete", "newton_steel||dict_multidiscrete", "newton_steel||discrete_box", "newton_steel||discrete_discrete", "newton_steel||discrete_multidiscrete", "newton_steel||multidiscrete_box", "newton_steel||multidiscrete_discrete", "newton_steel||multidiscrete_multidiscrete", "newton_steel||tuple_box", "newton_steel||tuple_discrete", "newton_steel||tuple_multidiscrete", "ovphysx||", "ovphysx||box_box", "ovphysx||box_discrete", "ovphysx||box_multidiscrete", "ovphysx||dict_box", "ovphysx||dict_discrete", "ovphysx||dict_multidiscrete", "ovphysx||discrete_box", "ovphysx||discrete_discrete", "ovphysx||discrete_multidiscrete", "ovphysx||multidiscrete_box", "ovphysx||multidiscrete_discrete", "ovphysx||multidiscrete_multidiscrete", "ovphysx||tuple_box", "ovphysx||tuple_discrete", "ovphysx||tuple_multidiscrete"]], ["IsaacContrib-Deploy-GearAssembly-Rizon4s-Grav", "rsl_rl", "", "", "", "environment-previews/rizon4s_gear_assembly.jpg"], diff --git a/docs/source/concepts/sensors/foveated_camera.rst b/docs/source/concepts/sensors/foveated_camera.rst index f88dbe881771..69dff45ce20e 100644 --- a/docs/source/concepts/sensors/foveated_camera.rst +++ b/docs/source/concepts/sensors/foveated_camera.rst @@ -5,219 +5,61 @@ Foveated Camera =============== -A :class:`~sensors.FoveatedCamera` samples the scene densely where it looks and sparsely in the periphery, as a -retina does, instead of on a uniform pixel grid. It is a :class:`~isaaclab.sensors.Camera` whose rays are laid out -by the `fovi `__ library, and its gaze moves inside the field of view of the -physical camera it looks through. The camera implements the foveated rendering of -`FOVI-Dex `__. +A :class:`~sensors.FoveatedCamera` samples densely at its fixation and sparsely in the periphery. +The `fovi `__ library maps each cell of an upright square grid to a viewing ray. +Moving the gaze rotates these rays relative to the physical camera's mount. .. figure:: ../../_static/overview/sensors/foveated_camera_overview.jpg - :target: ../../_static/overview/sensors/foveated_camera_overview.jpg - :align: center - :figwidth: 100% - :alt: The retina's rays on a viewing sphere and the image the camera publishes, at two fixations. + :alt: The foveated ray grid and the published images at two fixations. - The demo scene through a foveated camera, fixating two objects. Left of each pair: the viewing sphere seen from - behind the camera, textured with the physical camera's 90° pinhole image (green outline). The blue lattice is - every 16th row and column of the 128 × 128 retina, and the blue circle its edge; grey lines fall outside the - physical camera's image. Right: the image the camera publishes, dense at the fixation and sparse in the - periphery. + Each pair shows the retinal rays on the viewing sphere and the image published at that fixation. -The camera comes with the ``fovi`` extra: +Sampling +-------- -.. code-block:: bash - - uv sync --extra fovi - -The demo moves the gaze from object to object while the viewer shows the retina: - -.. code-block:: bash - - uv run --extra fovi isaaclab demo foveated-camera - -How the retina samples the scene --------------------------------- - -The retina places its samples by visual angle, with a density that falls off from the fixation as the cortical -magnification function (CMF) of human vision does. At eccentricity :math:`r` from the fixation, in degrees, +At an angular distance :math:`r` from fixation, the cortical magnification is :math:`M(r)=1/(r+a)`. +For a normalized grid radius :math:`\rho` and retinal half-field angle :math:`h`, the ray's angular distance is .. math:: - M(r) = \frac{1}{r + a}, \qquad w(r) = \int_0^r M(t)\,dt = \log\left(1 + \frac{r}{a}\right), - -where :math:`a` is :attr:`~sensors.FoveatedCameraCfg.cmf_a_deg`, :math:`M` is the cortical distance per degree of -visual angle, and :math:`w` is the cortical distance from the fixation. Samples spaced evenly in :math:`w` are dense -near the fixation and sparse far from it. - -The camera lays an :math:`N \times N` lattice over this cortical -space, with :math:`N` = :attr:`~sensors.FoveatedCameraCfg.foveated_res`. Lattice point -:math:`\mathbf{c}_{ij} = (\xi_i, \xi_j)`, with :math:`\xi_i = -1 + (2i + 1)/N`, samples at angle -:math:`\theta = \operatorname{atan2}(c_y, c_x)` around the fixation and eccentricity - -.. math:: - - r(\rho) = a\left[\left(1 + \frac{r_{\max}}{a}\right)^{\rho} - 1\right], \qquad \rho = \lVert \mathbf{c}_{ij} \rVert_2, - -so the lattice's radius is proportional to :math:`w`. :math:`r_{\max}` is half the retina's field of view. Lattice -points with :math:`\rho > 1` lie outside the circular field and publish zero. The camera casts each sample's ray - -.. math:: - - \mathbf{d} = (\sin r \cos\theta,\; -\sin r \sin\theta,\; \cos r)^\top - -in the camera frame (:math:`x` right, :math:`y` down, :math:`z` forward), turns it by the gaze, and renders it. The -published image keeps the lattice's layout, so it is an upright :math:`N \times N` image that convolutional networks -take as is. - -Configure a foveated camera ---------------------------- - -Add a :class:`~sensors.FoveatedCameraCfg` to a scene like any camera configuration. The renderer selects how the -retina is rendered: - -.. list-table:: - :header-rows: 1 - :widths: 45 55 - - * - Renderer configuration - - Rendering - * - :class:`~isaaclab_newton.renderers.NewtonWarpRendererCfg` - - One ray per retinal sample. - * - :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg`, - :class:`~isaaclab_ov.renderers.OVRTXRendererCfg` - - A lens lookup texture on the camera prim maps the image to the retina's rays. - -The camera also accepts the Newton OptiX renderer (``optix`` extra), which receives the same rays as Newton Warp. On -the RTX renderers, :attr:`~sensors.FoveatedCameraCfg.exit_texture_size` sets the side of the inverse lens texture, -which maps rays back to samples; the default, four times the grid side and at least 128, separates neighbouring -samples. - -.. figure:: ../../_static/overview/sensors/foveated_camera_renderers.jpg - :target: ../../_static/overview/sensors/foveated_camera_renderers.jpg - :align: center - :figwidth: 80% - :alt: The same retina and fixation rendered by Newton Warp, Isaac RTX and OVRTX. + r(\rho) = a\left[\left(1 + h/a\right)^\rho - 1\right]. - The demo's first fixation on each renderer. Newton Warp shades one ray per sample; the RTX renderers render - through the lens texture with their own anti-aliasing, so their edges are softer. +Smaller :attr:`~sensors.FoveatedCameraCfg.cmf_a_deg` concentrates more samples near fixation. A large value gives +nearly uniform radial angular spacing on the same grid. For a grid of side +:attr:`~sensors.FoveatedCameraCfg.foveated_res`, the camera publishes ``(num_envs, N, N, channels)``. +Cells outside the circular retinal footprint are zero. -.. code-block:: python +Camera setup and gaze +--------------------- - import isaaclab.sim as sim_utils - from isaaclab_fovi.sensors import FoveatedCameraCfg - from isaaclab_newton.renderers import NewtonWarpRendererCfg - - eye = FoveatedCameraCfg( - prim_path="{ENV_REGEX_NS}/Eye", - data_types=["rgb"], - renderer_cfg=NewtonWarpRendererCfg(), - spawn=sim_utils.PinholeCameraCfg(), - foveated_res=64, - ) - -The camera computes its image size from the retina. It publishes an upright image of -shape ``(num_envs, foveated_res, foveated_res, channels)`` in :attr:`~isaaclab.sensors.Camera.data`, like any -camera, and any output the renderer supports. - -The physical camera -~~~~~~~~~~~~~~~~~~~ - -The retina places its samples by visual angle inside the image of a physical camera, and its rays are cast at those -angles, so no pinhole image is resampled. Its field of view, :math:`2 r_{\max}`, is the angle the camera's image -spans across its short side. By default that camera is the one ``spawn`` creates: - -* :class:`~isaaclab.sim.PinholeCameraCfg` optics give an ideal pinhole. -* An OpenCV model in ``spawn.distortion`` gives that calibrated camera. An - :class:`~isaaclab.sim.OpenCvFisheyeDistortionCfg` with zero coefficients is an ideal equidistant fisheye. - -For any other calibrated camera, or a camera prim without spawn configuration, set -:attr:`~sensors.FoveatedCameraCfg.camera_model` to the fields of a ``fovi.sensing.projection.CameraModel``: - -.. code-block:: python - - camera_model = { - "model": "pinhole", # or "fisheye" - "image_size": (480, 640), # (height, width) - "intrinsics": (550.0, 550.0, 319.5, 239.5), # fx, fy, cx, cy [px] - } - -The same fields configure fovi's software sampler on images from a real camera: it samples the camera's image at -the pixels :math:`\Pi(R\,\mathbf{d})` the rendered rays project to, where :math:`\Pi` is the camera's projection -and :math:`R` the gaze rotation, so a policy sees the same retina in simulation and on hardware. - -The projection is set in the configuration. :meth:`~sensors.FoveatedCamera.set_intrinsic_matrices` leaves a -foveated camera as configured and warns, as cameras with an OpenCV lens model do. - -:attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` shrinks the retina's window to a fraction of the image's -short side, or of its long side with :attr:`~sensors.FoveatedCameraCfg.retinal_window_reference_side` set to -``"long"``. For a camera mounted rolled, :attr:`~sensors.FoveatedCameraCfg.image_rotation_deg` turns the rays back -about the optical axis (180 for an upside-down sensor), so the published image, the sensor mask and the gaze stay -upright. - -Foveation strength -~~~~~~~~~~~~~~~~~~ - -:attr:`~sensors.FoveatedCameraCfg.cmf_a_deg` is the CMF constant :math:`a`. Smaller values concentrate more samples -at the fixation; the default, 0.591, is an estimate from human data. Neighbouring grid samples lie about - -.. math:: - - \Delta r \approx \frac{2}{N} \log\left(1 + \frac{r_{\max}}{a}\right) (r + a) - -apart at eccentricity :math:`r`. For the demo's 128 × 128 retina over a 90° field, that is 0.04° at the fixation -and 3.1° at the edge, compared with a uniform radial angular step of about 0.7°. A value of :math:`a` much larger -than the field of view gives nearly uniform radial angular spacing on the same lattice: +Install the ``fovi`` extra to run the camera demo. .. code-block:: bash - uv run --extra fovi isaaclab demo foveated-camera env.scene.eye.cmf_a_deg=1000 - -.. figure:: ../../_static/overview/sensors/foveated_camera_strength.jpg - :target: ../../_static/overview/sensors/foveated_camera_strength.jpg - :align: center - :figwidth: 100% - :alt: The physical camera's image and the 128 x 128 retina at four CMF constants. - - The demo scene with the gaze on the optical axis. Left: the physical camera's pinhole image, with the retina's - field circled. Right: the published 128 × 128 image at four values of ``cmf_a_deg``. - -Move the gaze -------------- - -The gaze turns the retina relative to the physical camera's optical axis: - -.. code-block:: python + uv run --extra fovi isaaclab demo foveated-camera - # (tilt, pan) [deg] from the optical axis, shape (num_envs, 2): positive tilt looks up, positive pan looks left. - camera.set_gaze_angles(angles) +Add a :class:`~sensors.FoveatedCameraCfg` to a scene like any camera configuration. Newton Warp and OptiX render +the sample rays directly. Isaac RTX and OVRTX use lens lookup textures. -The gaze stays relative to the camera's mount when the mount moves, and -:meth:`~sensors.FoveatedCamera.get_world_poses` reports the mount without the gaze. Set -:attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero the samples that fall outside the physical camera's -image at the current gaze, so that the retina only sees what the camera could. A real camera cannot provide those -samples, so a policy meant for hardware should train with the mask. +The retinal field of view defaults to the angle spanned by the short side of the physical camera's image. +The camera reads ideal pinhole optics or supported OpenCV distortion from ``spawn``. Supply +:attr:`~sensors.FoveatedCameraCfg.camera_model` for explicit calibration, including when using an existing +camera prim. The :attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` setting shrinks the retinal window. -.. figure:: ../../_static/overview/sensors/foveated_camera_gaze_mask.jpg - :target: ../../_static/overview/sensors/foveated_camera_gaze_mask.jpg - :align: center - :figwidth: 80% - :alt: The retina in the camera image at a gaze 38 degrees to the left, without and with the sensor mask. +Call ``camera.set_gaze_angles(angles)`` with an array shaped ``(num_envs, 2)`` in tilt, pan order and in degrees. +Positive tilt looks up and positive pan looks left. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` +to zero rays that land outside the physical image at the current gaze. This mask moves relative to the retinal grid +as the gaze changes. - The gaze 38° left of the optical axis. Left: the retina's lattice in the physical camera's image; its grey part - lies outside the image. Middle: without the mask, rays render beyond the camera's view. Right: with the mask, those - samples are zero. +Cartpole example +---------------- -Gaze actions ------------- +``IsaacContrib-Cartpole-Camera-Fovi`` uses a 32 × 32 retina and two bounded gaze actions. The actor observes the camera +image and the gaze state. Use ``presets=depth`` to select depth instead of RGB. -For a manager-based environment, :class:`~mdp.GazeActionCfg` adds two bounded tilt and pan increments in units of -the retinal field radius. :func:`~mdp.gaze_state` reports the resulting angles and angular velocity. The action -resets the gaze to the optical axis at the start of each episode. +.. code-block:: bash -Further reading ---------------- + uv run --extra fovi --extra rsl-rl isaaclab train --rl_library rsl_rl --task IsaacContrib-Cartpole-Camera-Fovi -* `FOVI-Dex `__: foveated rendering and active gaze for perceptive reinforcement - learning of dexterous manipulation, with interactive demos. -* `fovi `__: the foveated sampling library, its sampling styles, and foveated vision - networks. +For other manager-based tasks, use :class:`~mdp.GazeActionCfg` to add the tilt and pan actions and +:func:`~mdp.gaze_state` to observe the angles and angular velocity in units of the retinal field radius. diff --git a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst new file mode 100644 index 000000000000..6a26475420f2 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst @@ -0,0 +1,2 @@ +* Added the ``IsaacContrib-Cartpole-Camera-Fovi`` task with foveated RGB and depth presets, policy-controlled + gaze, and the stock RSL-RL PPO runner. The task is available with the ``fovi`` extra. diff --git a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py new file mode 100644 index 000000000000..9d0c06d83e82 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py @@ -0,0 +1,29 @@ +# 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 + +"""Active vision with a foveated camera: the policy moves the camera's gaze. + +The camera is :class:`isaaclab_fovi.sensors.FoveatedCamera`, from the optional ``fovi`` extra +(``uv sync --extra fovi``). The task is registered only when that extra is installed. +""" + +from importlib.util import find_spec + +import gymnasium as gym + +ISAACLAB_FOVI_AVAILABLE = find_spec("isaaclab_fovi") is not None and find_spec("fovi") is not None +"""Whether the ``fovi`` extra is installed: the foveated camera package and the fovi library it builds on.""" + +if ISAACLAB_FOVI_AVAILABLE: + gym.register( + id="IsaacContrib-Cartpole-Camera-Fovi", + entry_point="isaaclab.envs:ManagerBasedRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.cartpole_camera_fovi_env_cfg:CartpoleCameraFoviEnvCfg", + "rsl_rl_cfg_entry_point": f"{__name__}.agents:CartpoleCameraFoviPPORunnerCfg", + "default_agent": "rsl_rl", + }, + ) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py new file mode 100644 index 000000000000..b3ba0ba05bb2 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py @@ -0,0 +1,18 @@ +# 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 + +"""Stock Cartpole camera PPO with gaze state in the actor and critic observations.""" + +from isaaclab.utils import configclass + +from isaaclab_tasks.core.cartpole.agents.rsl_rl_ppo_cfg import CartpoleCameraPPORunnerCfg + + +@configclass +class CartpoleCameraFoviPPORunnerCfg(CartpoleCameraPPORunnerCfg): + """Train the camera policy and gaze actions with the stock PPO runner.""" + + experiment_name = "cartpole_camera_fovi" + obs_groups = {"actor": ["policy", "gaze"], "critic": ["critic", "gaze"]} diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py new file mode 100644 index 000000000000..afe967165329 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py @@ -0,0 +1,86 @@ +# 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 + +"""Camera Cartpole with a foveated view and policy-controlled gaze.""" + +from dataclasses import MISSING + +from isaaclab_fovi import mdp +from isaaclab_fovi.sensors import FoveatedCameraCfg + +from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg +from isaaclab.sensors import CameraCfg +from isaaclab.utils import configclass + +from isaaclab_tasks.core.cartpole.cartpole_common import CartpoleTiledCameraCfg +from isaaclab_tasks.core.cartpole.cartpole_manager_camera_env_cfg import ( + CartpoleCameraEnvCfg, + CartpoleCameraSceneCfg, + image_observations_cfg, +) +from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ActionsCfg as CartpoleActionsCfg +from isaaclab_tasks.utils import PresetCfg + + +def _foveated_camera(camera: CameraCfg) -> FoveatedCameraCfg: + """Apply the retina to the stock Cartpole camera's mount, optics, and renderer.""" + return FoveatedCameraCfg( + prim_path=camera.prim_path, + offset=camera.offset, + spawn=camera.spawn, + data_types=camera.data_types, + renderer_cfg=camera.renderer_cfg, + foveated_res=32, + mask_to_sensor_fov=True, + ) + + +@configclass +class CameraPresetsCfg(PresetCfg): + """Select the foveated RGB or depth output.""" + + rgb = _foveated_camera(CartpoleTiledCameraCfg().rgb) + depth = _foveated_camera(CartpoleTiledCameraCfg().depth) + default = rgb + + +@configclass +class SceneCfg(CartpoleCameraSceneCfg): + tiled_camera: CameraPresetsCfg = CameraPresetsCfg() + + +@configclass +class ActionsCfg(CartpoleActionsCfg): + gaze = mdp.GazeActionCfg(asset_name="tiled_camera") + + +@configclass +class ObservationsCfg: + @configclass + class GazeCfg(ObservationGroupCfg): + state = ObservationTermCfg(func=mdp.gaze_state) + + policy: ObservationGroupCfg = MISSING + critic: ObservationGroupCfg = MISSING + gaze: GazeCfg = GazeCfg() + + +def _observations(data_type: str) -> ObservationsCfg: + images = image_observations_cfg(data_type) + return ObservationsCfg(policy=images.policy, critic=images.critic) + + +@configclass +class CartpoleCameraFoviEnvCfg(PresetCfg): + """Cartpole with gaze control and RGB or depth retinal observations.""" + + @configclass + class BaseCfg(CartpoleCameraEnvCfg.BaseCartpoleCameraEnvCfg): + scene: SceneCfg = SceneCfg(num_envs=512, env_spacing=20.0) + actions: ActionsCfg = ActionsCfg() + + rgb = BaseCfg(observations=_observations("rgb")) + depth = BaseCfg(observations=_observations("depth")) + default = rgb diff --git a/source/isaaclab_tasks/test/core/test_cartpole_camera_presets.py b/source/isaaclab_tasks/test/core/test_cartpole_camera_presets.py index b8235943b28f..d72497bacbcb 100644 --- a/source/isaaclab_tasks/test/core/test_cartpole_camera_presets.py +++ b/source/isaaclab_tasks/test/core/test_cartpole_camera_presets.py @@ -21,6 +21,7 @@ CartpoleCameraEnvCfg as CartpoleManagerCameraEnvCfg, ) from isaaclab_tasks.utils.hydra import resolve_presets +from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry _ENV_CFG_CLASSES = [ pytest.param(CartpoleDirectCameraEnvCfg, id="direct"), @@ -49,3 +50,24 @@ def test_newton_renderer_accepts_supported_data_types(cfg_cls): """The guard must not reject data types the Newton Warp renderer does publish.""" cfg = resolve_presets(cfg_cls(), {"newton_warp", "rgb"}) validate(cfg) # must not raise + + +def test_foveated_cartpole_presets_connect_the_camera_and_stock_ppo(): + """The registered task selects matching image data and runs without teacher-specific inputs or training code.""" + pytest.importorskip("isaaclab_fovi") + pytest.importorskip("fovi") + task = "IsaacContrib-Cartpole-Camera-Fovi" + for data_type in ("rgb", "depth"): + raw_cfg = load_cfg_from_registry(task, "env_cfg_entry_point") + cfg = resolve_presets(raw_cfg, {data_type, "newton_warp"}) + validate(cfg) + image = cfg.observations.policy.image.params + assert image["data_type"] == data_type + assert cfg.scene.tiled_camera.data_types == [data_type] + assert image["sensor_cfg"].name == cfg.actions.gaze.asset_name + assert not hasattr(cfg.observations, "oracle") + + agent = load_cfg_from_registry(task, "rsl_rl_cfg_entry_point") + assert agent.obs_groups == {"actor": ["policy", "gaze"], "critic": ["critic", "gaze"]} + assert agent.algorithm.class_name == "PPO" + assert agent.actor.distribution_cfg.class_name == "GaussianDistribution" From 19b9afadc762bb48fceea3c7e73bc1637182b964 Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Thu, 19 Nov 2026 16:08:20 -0800 Subject: [PATCH 47/81] Preserve FOVI behavior while simplifying RTX lens setup --- docs/conf.py | 3 + .../css/foveation-pooling-isotropic.json | 1 + docs/source/_static/css/foveation-viewer.css | 206 ++++ docs/source/_static/css/foveation-viewer.js | 987 ++++++++++++++++++ .../sensors/foveated_camera_active_gaze.jpg | Bin 0 -> 115472 bytes .../sensors/foveated_camera_pooling.jpg | Bin 0 -> 68546 bytes .../source/api/lab_fovi/isaaclab_fovi.mdp.rst | 4 + .../concepts/sensors/foveated_camera.rst | 81 +- .../changelog.d/fovi-rtx-lens-setup.skip | 0 .../changelog.d/isaaclab-fovi.added.rst | 5 +- .../isaaclab_fovi/mdp/__init__.pyi | 7 +- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 376 ++++++- .../isaaclab_fovi/mdp/gaze_cfg.py | 18 +- .../sensors/calibrated_geometry.py | 46 +- .../isaaclab_fovi/sensors/foveated_camera.py | 378 +++++-- .../sensors/foveated_camera_cfg.py | 70 +- .../sensors/foveated_newton_camera.py | 250 ++++- .../sensors/foveated_rtx_camera.py | 309 ++++-- .../isaaclab_fovi/sensors/gaze_kernels.py | 89 +- .../isaaclab_fovi/sensors/lens_lut.py | 141 ++- .../isaaclab_fovi/sensors/native_grid.py | 152 ++- .../isaaclab_fovi/sensors/pooling.py | 282 +++++ source/isaaclab_fovi/test/test_active_gaze.py | 216 +++- source/isaaclab_fovi/test/test_camera_cfg.py | 58 +- source/isaaclab_fovi/test/test_camera_gaze.py | 367 ++++--- source/isaaclab_fovi/test/test_native_grid.py | 177 +++- .../isaaclab_fovi/test/test_newton_buffers.py | 356 ++++++- source/isaaclab_fovi/test/test_pooling.py | 172 +++ source/isaaclab_fovi/test/test_rtx_camera.py | 87 +- .../active-gaze-cartpole.added.rst | 5 +- .../contrib/active_gaze/active_gaze_cfg.py | 85 ++ .../contrib/active_gaze/agents.py | 28 +- .../cartpole_camera_fovi_env_cfg.py | 93 +- .../contrib/active_gaze/gaze_distribution.py | 61 ++ .../active_gaze/gaze_distribution_cfg.py | 24 + .../active_gaze/gaze_supervised_ppo.py | 134 +++ .../active_gaze/gaze_supervised_ppo_cfg.py | 26 + .../test/contrib/test_active_gaze_ppo.py | 129 +++ .../test/core/test_cartpole_camera_presets.py | 22 - 39 files changed, 4911 insertions(+), 534 deletions(-) create mode 100644 docs/source/_static/css/foveation-pooling-isotropic.json create mode 100644 docs/source/_static/css/foveation-viewer.css create mode 100644 docs/source/_static/css/foveation-viewer.js create mode 100644 docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg create mode 100644 docs/source/_static/overview/sensors/foveated_camera_pooling.jpg create mode 100644 source/isaaclab_fovi/changelog.d/fovi-rtx-lens-setup.skip create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py create mode 100644 source/isaaclab_fovi/test/test_pooling.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py create mode 100644 source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py diff --git a/docs/conf.py b/docs/conf.py index dc83014e7029..f68ddf96c4b6 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -48,6 +48,7 @@ sys.path.insert(0, os.path.abspath("../source/isaaclab_ov/isaaclab_ov")) sys.path.insert(0, os.path.abspath("../source/isaaclab_visualizers")) sys.path.insert(0, os.path.abspath("../source/isaaclab_visualizers/isaaclab_visualizers")) +# Only the package root: the package's ``rsl_rl`` subpackage would shadow RSL-RL as a top-level module. sys.path.insert(0, os.path.abspath("../source/isaaclab_fovi")) # -- Project information ----------------------------------------------------- @@ -351,11 +352,13 @@ def _read_pinned_versions() -> dict: "css/environment-browser.css", "css/demo-browser.css", "css/guide-browser.css", + "css/foveation-viewer.css", ] html_js_files = [ "css/environment-browser.js", "css/demo-browser.js", "css/guide-browser.js", + "css/foveation-viewer.js", ] html_theme_options = { diff --git a/docs/source/_static/css/foveation-pooling-isotropic.json b/docs/source/_static/css/foveation-pooling-isotropic.json new file mode 100644 index 000000000000..90d14b291e94 --- /dev/null +++ b/docs/source/_static/css/foveation-pooling-isotropic.json @@ -0,0 +1 @@ +{"fov":90,"cmfA":2.0,"res":16,"rings":14,"count":243,"mult":{"2":{"rings":28,"count":1026,"defaultK":4,"kMax":8,"geodesic":[0,1,4,2,3,5,6,8,7,18,8,1,19,34,20,2,9,10,8,2,22,21,23,3,11,12,10,3,24,25,23,2,13,14,12,4,27,28,26,5,15,14,16,5,30,29,31,4,17,16,18,6,32,33,31,5,35,55,36,19,56,79,57,34,37,38,36,58,21,20,59,57,39,38,40,22,61,60,23,21,41,40,42,63,24,23,62,64,43,42,44,25,65,66,26,64,46,47,45,69,27,68,28,70,48,49,47,29,71,70,28,72,50,51,49,73,30,31,74,72,52,51,53,32,75,76,31,33,54,53,55,78,33,34,77,79,80,107,81,56,108,109,137,79,82,81,83,110,58,57,111,109,84,83,85,112,59,60,113,111,86,87,85,61,114,115,62,60,88,87,89,63,117,116,62,64,90,89,91,119,65,64,118,120,92,93,91,121,66,67,120,122,94,95,93,68,123,124,122,67,96,95,97,125,70,69,126,124,98,99,97,127,71,72,128,126,100,101,99,73,129,130,74,72,102,101,103,75,132,131,74,76,104,105,103,134,77,76,133,135,106,105,107,136,78,79,135,137,138,170,139,108,171,172,205,109,140,141,139,173,110,174,109,172,142,141,143,175,112,111,176,174,144,145,143,177,113,114,178,176,146,147,145,115,179,180,116,114,148,147,149,117,182,181,118,116,150,151,149,119,184,183,118,120,152,153,151,186,121,120,185,187,154,153,155,188,123,122,187,189,157,158,156,191,125,126,192,190,159,158,160,127,193,194,128,126,161,160,162,129,195,196,128,130,163,162,164,131,198,197,130,132,165,164,166,200,133,132,199,201,167,168,166,202,134,135,201,203,169,168,170,204,136,203,137,205,206,207,242,171,243,244,281,205,208,209,207,245,173,246,172,244,210,209,211,247,175,248,174,246,212,211,213,249,177,250,176,248,214,215,213,251,179,252,178,250,216,217,215,254,180,253,181,255,218,217,219,256,182,255,183,257,220,221,219,258,184,257,185,259,222,223,221,260,186,259,187,261,225,226,224,263,189,264,262,188,227,228,226,265,191,266,190,264,229,230,228,267,193,268,192,266,231,232,230,269,195,270,194,268,233,234,232,271,197,272,196,270,235,234,236,274,198,273,199,275,237,236,238,276,200,275,201,277,239,240,238,278,202,277,203,279,241,242,240,280,204,279,205,281,282,322,283,243,323,364,324,244,284,285,283,325,245,244,326,324,286,287,285,327,247,246,328,326,288,289,287,329,249,248,330,328,290,289,291,331,251,250,332,330,292,293,291,333,253,252,334,332,294,295,293,335,254,255,336,334,296,295,297,256,337,338,257,336,340,339,341,383,299,298,382,384,342,341,343,385,301,300,384,386,344,343,345,387,303,302,388,386,346,347,345,389,304,305,390,388,348,349,347,391,306,307,392,390,309,308,310,269,351,350,268,352,311,310,312,353,271,270,352,354,313,312,314,355,272,273,354,356,315,316,314,357,274,275,356,358,317,318,316,359,276,277,358,360,319,318,320,361,278,279,360,362,321,322,320,363,280,281,362,364,409,410,453,365,454,499,455,366,411,410,412,456,367,457,366,455,413,414,412,458,369,459,368,457,371,370,372,415,329,328,416,414,418,419,417,463,374,464,373,462,420,421,419,465,376,466,375,464,422,421,423,467,378,468,377,466,424,425,423,469,380,470,379,468,426,425,427,471,382,472,381,470,428,429,427,473,384,474,383,472,386,385,387,343,430,431,344,342,388,389,387,345,433,432,344,346,435,434,436,481,390,480,391,482,437,438,436,483,392,482,393,484,439,440,438,485,394,484,395,486,441,440,442,487,396,486,397,488,443,442,444,489,398,488,399,490,445,446,444,491,400,490,401,492,403,404,402,448,359,360,447,449,450,449,451,496,405,495,406,497,452,451,453,498,407,497,408,499,500,545,501,454,546,592,547,499,502,501,503,456,548,549,455,457,504,503,505,458,550,551,457,459,506,507,505,460,552,553,461,459,508,507,509,462,554,555,461,463,510,509,511,464,556,557,463,465,513,514,512,467,559,560,468,466,515,516,514,469,561,562,470,468,517,518,516,471,563,564,470,472,519,518,520,473,565,566,474,472,521,522,520,475,567,568,476,474,523,524,522,477,570,569,478,476,525,524,526,479,572,571,478,480,527,528,526,481,574,573,482,480,529,528,530,483,576,575,484,482,531,532,530,485,578,577,486,484,533,534,532,487,580,579,486,488,536,535,537,490,583,582,489,491,538,539,537,492,585,584,493,491,540,539,541,494,587,586,493,495,542,543,541,496,589,588,495,497,544,543,545,498,591,590,499,497,593,594,640,641,546,642,688,592,595,594,596,643,548,547,642,644,597,596,598,645,550,549,644,646,599,598,600,647,552,551,646,648,601,602,600,649,554,553,650,648,603,602,604,651,556,555,650,652,606,605,607,654,559,558,653,655,608,607,609,656,561,560,657,655,610,611,609,658,563,562,657,659,612,611,613,660,565,564,661,659,614,615,613,662,567,566,663,661,616,615,617,664,569,568,663,665,618,617,619,666,570,571,667,665,620,619,621,668,572,573,669,667,622,623,621,670,574,575,671,669,624,623,625,672,576,577,671,673,626,627,625,674,578,579,675,673,628,629,627,676,580,581,677,675,631,630,632,679,583,584,678,680,633,632,634,681,585,586,680,682,635,636,634,683,587,588,684,682,637,638,636,685,589,590,686,684,639,640,638,687,591,592,688,686,689,690,736,737,641,785,738,642,691,690,692,643,739,740,642,644,693,694,692,645,741,742,644,646,695,694,696,647,743,744,646,648,697,698,696,649,745,746,650,648,699,698,700,651,747,748,650,652,702,701,703,654,750,751,653,655,704,703,705,656,752,753,655,657,706,707,705,658,754,755,659,657,708,707,709,660,756,757,659,661,710,711,709,662,758,759,663,661,712,711,713,664,760,761,663,665,714,715,713,666,763,762,667,665,716,715,717,668,765,764,669,667,718,719,717,670,767,766,671,669,720,719,721,672,769,768,671,673,722,723,721,674,771,770,675,673,724,725,723,676,773,772,677,675,727,726,728,679,776,775,678,680,729,728,730,681,778,777,680,682,731,732,730,683,780,779,684,682,733,734,732,685,782,781,686,684,735,736,734,687,784,783,688,686,786,834,787,835,737,785,738,836,788,789,787,739,837,836,740,738,790,791,789,741,839,838,740,742,792,793,791,743,841,840,744,742,795,796,794,746,844,843,745,747,797,796,798,748,846,845,749,747,799,800,798,750,848,847,749,751,801,802,800,752,850,849,753,751,803,802,804,754,852,851,753,755,805,804,806,756,854,853,755,757,807,806,808,758,856,855,757,759,809,810,808,760,858,857,761,759,812,813,811,763,860,861,764,762,814,813,815,765,862,863,764,766,816,817,815,767,864,865,766,768,818,819,817,769,866,867,770,768,820,819,821,771,868,869,770,772,822,823,821,773,870,871,774,772,824,823,825,775,872,873,774,776,826,827,825,777,874,875,778,776,829,830,828,780,877,878,781,779,831,830,832,782,879,880,781,783,833,834,832,784,881,882,785,783,883,884,930,931,835,932,978,836,885,884,886,933,837,932,934,836,887,886,888,935,839,934,936,838,889,888,890,937,841,936,938,840,891,890,892,939,843,940,938,844,893,892,894,941,845,940,942,844,896,895,897,944,848,943,945,847,898,897,899,946,850,945,947,849,900,901,899,948,852,949,947,853,902,901,903,950,854,949,951,853,904,905,903,952,856,953,951,857,906,905,907,954,858,953,955,857,908,909,907,956,860,957,955,861,910,909,911,958,862,957,959,861,912,913,911,960,864,961,959,865,914,913,915,962,866,963,961,865,916,917,915,964,868,965,963,869,918,919,917,966,870,967,965,871,921,920,922,969,873,968,970,872,923,922,924,971,875,970,972,874,925,926,924,973,877,974,972,878,927,928,926,975,879,976,974,880,929,930,928,977,881,978,976,882,979,-1,1025,980,-1,931,-1,932,981,-1,980,982,933,-1,934,932,983,-1,984,982,935,-1,936,-1,985,-1,984,986,937,-1,-1,938,987,-1,988,986,939,-1,940,-1,989,-1,990,988,941,-1,942,-1,991,-1,990,992,943,-1,944,-1,993,-1,992,994,945,-1,946,-1,995,-1,994,996,-1,947,948,-1,997,-1,996,998,949,-1,950,-1,999,-1,1000,998,951,-1,952,-1,1001,-1,1000,1002,-1,953,954,-1,1004,-1,1005,1003,957,956,-1,-1,1006,-1,1007,1005,-1,959,958,-1,1008,-1,1009,1007,-1,961,960,-1,1010,-1,1011,1009,963,962,-1,-1,1012,-1,1011,1013,965,-1,964,-1,1014,-1,1015,1013,-1,967,966,-1,1016,-1,1017,1015,969,-1,968,-1,1018,-1,1017,1019,971,-1,970,-1,1020,-1,1021,1019,973,-1,972,974,1022,-1,1023,1021,975,-1,-1,974,1024,-1,1023,1025,977,-1,-1,976],"visual":[0,3,4,1,5,2,6,8,7,18,8,19,1,20,34,2,9,8,10,2,22,21,23,3,11,12,10,3,24,25,23,4,13,12,14,27,4,28,26,3,15,14,16,5,30,29,31,6,17,16,18,6,32,33,31,5,35,56,55,36,19,79,57,34,37,38,58,59,36,21,20,57,39,40,61,22,38,60,23,62,41,42,63,24,64,40,23,62,43,44,66,65,25,26,42,45,45,46,68,27,67,69,44,47,48,47,70,71,29,28,49,46,50,49,73,30,72,51,31,74,52,51,75,32,53,76,31,74,54,53,78,77,55,33,34,79,80,108,107,81,56,137,109,79,82,110,81,83,111,58,57,109,84,112,83,85,113,59,60,111,86,114,115,87,85,61,62,60,88,117,116,87,89,63,62,64,90,119,91,89,118,65,64,120,92,121,93,91,120,66,67,122,94,123,95,93,68,122,124,67,96,125,97,95,126,70,69,124,98,127,99,97,128,71,72,126,100,129,130,99,101,73,74,72,102,132,131,101,103,75,74,76,104,134,105,103,133,77,76,135,106,136,107,105,135,78,79,137,138,171,170,139,108,205,172,137,140,173,141,139,174,110,172,109,142,175,143,176,141,112,111,174,144,178,145,177,143,114,113,179,146,180,147,179,145,115,116,181,148,182,149,181,117,183,147,118,150,151,184,185,119,183,149,120,152,153,186,187,121,151,122,185,154,155,188,189,123,153,156,124,157,156,191,190,125,158,124,192,159,158,193,192,127,194,160,126,161,195,160,196,129,194,162,128,163,197,162,198,164,130,131,196,165,199,164,200,166,132,133,198,167,202,166,201,168,134,135,203,169,204,168,170,203,136,205,137,206,243,242,207,244,281,171,205,208,245,209,246,207,173,244,172,210,247,248,211,209,175,246,174,212,249,250,213,211,177,176,251,214,252,215,251,213,179,178,253,216,254,217,253,181,215,255,180,218,256,219,257,255,183,217,182,220,258,221,259,185,257,184,219,222,223,260,261,187,186,221,259,224,225,262,263,188,189,226,223,227,226,265,264,190,191,228,266,229,267,228,266,192,268,193,230,231,269,230,270,268,194,232,195,233,271,232,272,196,234,270,197,235,273,234,274,236,198,199,272,237,275,276,236,238,200,201,274,239,278,277,238,240,202,279,203,241,280,240,279,242,204,281,205,282,323,322,283,364,324,243,244,284,325,285,326,283,324,245,244,286,327,287,328,285,326,247,246,288,329,330,289,287,249,328,248,290,331,332,291,289,251,330,250,292,333,334,293,291,253,252,332,294,336,295,335,293,255,254,337,296,338,297,337,295,257,339,256,340,298,299,339,341,259,297,258,342,300,301,341,343,261,260,299,344,303,302,343,345,263,262,301,346,305,304,347,345,264,265,306,348,307,306,349,347,266,308,267,309,350,308,351,310,268,349,269,311,352,310,353,312,270,271,351,313,354,355,312,314,272,273,353,315,357,356,314,316,274,358,275,317,359,358,316,318,276,360,277,319,361,318,360,320,362,278,279,321,363,320,362,322,364,280,281,409,365,366,408,410,453,323,454,411,367,412,368,366,410,325,456,369,413,414,370,368,412,327,458,371,415,416,372,370,329,414,417,373,418,417,374,331,372,419,463,420,375,376,419,421,333,374,377,422,378,377,421,423,335,379,376,424,380,379,425,423,381,337,469,426,382,381,427,425,383,339,472,384,428,429,383,385,427,341,474,386,430,431,385,387,343,429,476,388,433,432,389,387,345,434,478,390,435,434,391,389,436,347,480,437,392,393,436,438,391,349,482,439,394,395,440,438,393,351,485,441,396,397,442,440,353,395,398,443,399,398,444,442,355,400,397,401,445,446,400,357,402,444,491,403,448,447,402,404,359,449,446,405,450,449,404,406,451,361,496,452,407,451,406,408,453,363,498,500,454,545,501,455,499,409,546,502,456,503,457,501,455,411,548,504,458,505,459,503,457,413,550,506,460,507,461,459,505,415,552,508,462,509,463,461,507,417,555,510,511,464,465,419,463,557,509,513,512,467,466,421,468,559,514,515,469,514,468,470,516,423,561,517,471,516,470,472,518,563,425,519,473,518,472,520,474,427,565,521,475,520,474,522,476,429,567,523,477,522,524,476,478,432,431,525,479,526,480,524,478,434,572,527,481,528,482,526,480,436,574,529,483,530,484,482,528,576,438,531,485,532,486,484,530,440,578,533,534,487,488,442,486,580,532,536,535,490,489,444,491,582,537,538,492,537,491,493,539,446,584,540,494,539,493,495,541,448,587,542,496,541,495,543,497,450,589,544,498,543,497,545,499,452,591,593,546,640,594,592,547,641,500,595,548,596,549,594,547,643,502,597,550,598,551,596,549,645,504,599,552,600,553,551,598,647,506,601,554,602,555,553,600,649,508,603,604,556,557,555,602,651,510,606,605,558,559,557,654,653,607,608,607,560,561,559,609,656,514,610,562,609,563,611,658,561,516,612,564,611,565,613,660,563,518,614,566,567,613,615,662,520,565,616,568,569,615,617,664,522,567,618,571,570,619,617,666,524,572,620,573,572,621,619,668,526,574,622,575,623,574,621,670,576,528,624,577,625,576,623,672,578,530,626,627,579,578,580,625,674,532,628,629,581,580,582,676,677,627,631,630,583,582,584,632,679,536,633,585,632,584,586,634,681,538,635,587,634,586,588,636,683,540,637,589,636,588,638,590,685,542,639,591,638,590,640,592,687,544,689,641,690,736,688,642,737,593,691,643,692,690,644,642,739,595,693,645,694,646,692,741,644,742,695,647,696,648,694,743,646,744,697,698,649,650,696,746,745,648,699,700,651,652,748,747,698,650,702,701,654,653,750,703,749,700,704,703,656,655,752,705,657,608,706,705,658,657,754,707,659,610,708,660,707,659,709,756,661,757,710,662,709,661,711,663,758,759,712,664,711,713,663,665,760,761,714,666,715,713,667,665,763,762,716,668,717,669,715,667,765,764,718,670,719,671,717,767,669,766,720,721,672,673,769,719,671,624,722,723,674,675,771,721,673,626,724,725,676,677,773,723,774,726,727,726,679,678,775,776,728,680,729,728,681,680,730,777,778,682,731,683,730,682,732,780,684,779,733,685,732,684,734,782,686,781,735,687,734,736,686,688,784,639,786,737,834,787,835,785,738,689,788,739,789,740,787,837,738,838,790,791,741,742,839,789,740,840,792,793,743,744,841,791,842,742,795,794,746,745,843,844,796,793,797,796,748,747,845,846,798,749,799,798,750,749,800,848,847,751,801,752,800,802,751,850,753,849,803,754,804,802,755,852,753,851,805,756,806,757,804,854,755,853,807,808,758,759,856,806,757,855,809,810,760,761,858,808,759,811,812,811,763,762,860,813,764,810,814,813,765,764,862,815,766,863,816,767,815,766,817,864,768,865,818,769,817,819,768,866,770,867,820,771,821,819,772,868,770,869,822,823,773,774,821,870,871,772,824,825,775,776,873,872,823,774,826,827,777,778,875,874,825,828,829,828,780,779,877,830,876,781,831,830,782,781,879,832,783,878,833,784,832,783,834,881,785,880,883,835,930,884,931,882,836,932,885,837,886,933,884,838,836,934,887,888,839,935,840,886,838,936,889,890,841,842,937,888,938,840,891,892,843,844,939,940,890,842,893,894,845,846,941,942,892,895,896,895,848,847,944,943,897,894,898,897,850,849,946,945,899,851,900,899,852,851,948,901,947,853,902,901,854,853,950,903,949,855,904,856,903,952,905,855,857,951,906,858,905,907,954,857,859,953,908,860,909,907,956,861,859,957,910,862,911,958,909,863,861,959,912,913,864,865,960,911,961,863,914,915,866,867,962,913,963,865,916,917,868,869,964,965,915,867,918,919,870,871,966,967,917,920,921,920,873,872,969,968,922,919,923,922,875,874,971,970,924,876,925,924,877,876,973,926,972,878,927,926,879,975,878,928,880,974,929,881,928,977,930,880,882,976,979,931,-1,-1,1025,980,-1,978,981,933,-1,982,-1,980,934,932,983,935,-1,984,982,-1,936,934,985,-1,986,937,938,984,-1,-1,987,988,939,-1,-1,940,986,938,989,990,-1,941,942,-1,988,-1,991,992,-1,944,943,-1,990,-1,993,994,946,-1,-1,945,992,947,995,996,-1,948,947,-1,-1,994,997,998,950,-1,-1,949,996,951,999,1000,952,-1,-1,951,953,998,1001,1002,954,-1,-1,953,955,-1,1004,1003,956,-1,-1,957,955,1005,1006,1005,958,-1,-1,959,957,-1,1008,1007,-1,960,961,-1,-1,1009,1010,1009,962,-1,-1,963,1011,961,1012,1011,-1,964,965,-1,1013,-1,1014,1013,-1,966,967,-1,1015,-1,1016,1015,-1,969,968,-1,1017,-1,1018,1017,-1,971,970,1019,-1,-1,1020,1019,973,-1,-1,972,1021,974,1022,975,-1,1021,1023,-1,974,976,1024,977,-1,1023,1025,-1,976,978]},"3":{"rings":42,"count":2340,"defaultK":10,"kMax":18,"geodesic":[0,6,3,4,2,7,1,5,14,9,19,12,16,17,11,10,18,15,20,21,36,8,37,38,58,19,9,22,35,39,57,1,59,60,85,7,23,24,22,41,10,40,42,11,9,39,21,25,64,2,43,63,65,3,26,27,25,45,12,44,13,46,11,43,24,28,69,68,3,4,47,14,28,27,29,47,14,48,13,46,49,15,30,26,72,4,71,12,73,5,31,30,32,51,16,52,15,50,17,53,33,29,76,77,6,5,49,14,34,35,33,55,18,56,54,17,19,57,36,32,81,7,53,82,80,6,86,116,87,59,117,150,118,60,85,115,88,37,151,119,149,188,152,84,89,90,88,120,62,61,121,119,63,122,91,87,60,39,155,154,40,156,92,93,91,64,124,123,65,63,125,122,90,94,41,158,159,66,42,157,95,96,94,127,67,126,66,128,68,97,93,162,125,43,44,65,163,161,98,97,99,130,69,70,131,129,68,71,96,100,132,166,46,45,165,128,102,103,101,73,135,134,72,74,136,133,104,100,171,48,170,49,71,172,105,104,106,138,76,75,137,139,77,74,103,107,136,174,50,51,175,140,108,109,107,141,78,142,79,140,77,106,110,178,143,53,52,80,177,179,111,112,110,81,144,145,80,82,143,146,113,109,55,182,181,79,54,183,114,115,113,148,83,84,147,149,82,146,112,116,85,57,185,186,56,184,189,229,190,151,230,231,273,188,152,228,191,117,274,232,272,320,275,150,192,191,193,233,154,234,153,232,155,235,194,190,277,278,119,120,152,231,195,194,196,236,157,237,156,235,158,238,155,197,193,122,281,280,282,121,198,197,199,240,159,239,160,241,158,238,161,196,200,284,124,125,285,283,201,200,202,243,162,242,163,244,161,199,203,127,288,241,287,164,126,245,204,205,203,246,165,247,164,245,166,206,202,291,129,248,130,292,163,244,249,250,248,294,207,295,206,293,208,296,251,247,205,343,167,342,168,344,252,251,253,297,298,209,210,296,299,208,211,250,254,170,346,345,347,169,255,256,254,301,212,300,213,302,211,299,257,253,214,349,173,350,172,348,215,214,216,258,175,257,176,259,174,213,217,304,139,256,138,303,177,260,218,217,219,261,178,262,177,260,179,220,216,141,307,263,308,176,142,259,221,222,220,264,181,265,180,263,182,266,179,223,219,311,144,143,310,312,224,225,223,268,183,267,184,269,182,266,185,226,222,146,314,315,313,147,227,228,226,271,186,270,187,272,185,269,229,225,318,317,149,148,188,273,371,372,422,321,423,476,424,370,322,421,373,274,477,425,475,478,532,369,374,375,373,426,324,427,323,425,325,376,372,480,277,428,481,276,322,424,377,378,376,429,327,430,326,428,328,379,375,431,325,279,483,484,280,427,381,382,380,433,331,434,330,432,332,435,329,379,383,283,488,487,284,282,384,383,385,436,437,333,334,435,438,332,335,382,386,491,286,285,490,492,387,388,386,440,336,439,337,441,335,438,338,385,389,494,288,289,495,493,391,392,390,444,340,443,341,445,339,393,389,442,292,342,499,498,293,291,394,395,393,447,343,446,344,448,342,396,392,295,502,445,501,345,294,449,397,396,398,346,450,449,451,345,347,395,399,505,297,298,448,452,504,506,400,401,399,453,349,454,348,452,350,402,398,300,508,455,509,347,301,451,404,405,403,457,353,458,352,456,354,459,406,402,304,351,513,512,303,305,407,408,406,460,356,461,355,459,357,462,354,409,405,516,307,306,515,517,410,409,411,463,464,358,359,462,465,357,360,408,412,519,309,310,518,520,413,412,414,467,361,466,362,468,360,465,363,411,415,312,522,523,311,313,417,416,418,471,365,470,366,472,364,415,419,469,367,316,527,526,315,473,420,419,421,474,368,473,369,475,367,422,418,530,318,472,529,319,370,476,533,534,590,477,591,650,592,532,478,535,589,423,651,593,649,652,712,476,536,535,537,594,480,595,479,593,481,538,534,654,426,596,655,425,478,592,539,538,540,597,483,598,482,596,484,537,541,599,657,429,481,658,428,595,543,542,544,601,487,602,486,600,488,603,485,541,545,662,432,661,433,663,546,547,545,604,490,605,489,603,491,606,488,544,548,665,435,664,436,666,549,550,548,608,492,607,493,609,491,606,494,551,547,668,438,669,437,667,552,551,553,611,495,610,496,612,494,609,497,550,554,671,441,672,440,670,556,555,557,615,499,614,500,616,498,554,558,613,676,444,501,675,445,617,559,560,558,618,502,617,503,619,501,561,557,679,447,616,678,448,504,620,562,561,563,505,621,620,622,504,506,560,564,450,682,619,623,681,683,449,565,564,566,624,508,625,507,623,509,563,567,685,453,626,686,452,506,622,568,569,567,627,511,628,510,626,512,570,566,629,688,456,509,689,455,625,572,573,571,631,515,632,514,630,516,633,513,574,570,693,459,692,460,694,575,576,574,634,518,635,517,633,519,636,516,577,573,696,462,695,463,697,578,579,577,638,520,637,521,639,519,636,522,580,576,699,465,700,464,698,581,582,580,641,523,640,524,642,522,639,525,583,579,702,468,703,467,701,585,584,586,645,527,644,528,646,526,587,583,643,707,471,529,706,472,647,588,587,589,648,530,647,531,649,529,586,590,710,474,646,709,475,532,650,713,714,775,651,776,839,777,712,652,774,715,591,840,838,778,841,905,711,716,715,717,779,654,780,653,778,655,718,714,843,594,844,781,593,652,777,719,718,720,782,657,783,656,781,658,717,721,846,597,847,596,784,655,780,722,721,723,785,660,786,659,784,661,724,720,849,600,850,599,787,658,783,726,727,725,789,664,790,663,788,665,724,728,854,791,603,662,853,604,787,729,728,730,792,667,793,666,791,668,731,727,794,665,857,606,856,607,858,732,731,733,795,670,796,669,794,671,797,668,730,734,860,609,859,610,861,735,736,734,798,673,799,672,797,674,800,671,737,733,863,612,864,611,862,738,739,737,801,676,802,675,800,677,803,674,736,740,866,615,867,614,865,741,740,742,804,679,805,678,803,680,806,677,743,739,869,618,870,617,868,744,743,745,807,682,808,681,806,683,809,680,742,746,872,621,873,620,871,748,749,747,812,685,811,686,813,684,810,687,746,750,877,624,876,625,878,751,750,752,815,688,814,689,816,687,813,690,753,749,880,627,879,628,881,754,753,755,818,691,817,692,819,690,816,693,752,756,883,630,882,631,884,757,758,756,821,694,820,695,822,693,819,696,759,755,886,633,887,632,885,760,761,759,824,697,823,698,825,696,758,762,822,699,889,636,890,635,888,763,762,764,827,700,826,701,828,699,765,761,892,825,639,702,893,638,829,767,766,768,831,704,830,705,832,703,765,769,897,642,896,643,829,706,833,770,771,769,834,707,833,708,835,706,772,768,900,645,899,646,832,709,836,773,772,774,837,710,836,711,838,709,775,771,903,648,902,835,649,712,839,906,907,972,840,973,974,1040,841,905,971,908,776,1041,1039,975,1042,1109,904,909,910,908,976,843,977,842,975,844,911,907,1044,779,978,778,1045,841,974,912,911,913,979,846,980,845,978,847,910,914,1047,782,981,781,844,1048,977,916,917,915,983,850,984,849,982,851,914,918,1051,786,985,785,848,1052,981,919,920,918,986,853,987,852,985,854,921,917,1054,988,788,851,789,1055,984,922,923,921,989,856,990,855,988,857,924,920,991,854,791,1057,1058,792,790,925,924,926,992,859,993,858,991,860,994,927,923,857,794,1061,1060,795,793,928,927,929,995,862,996,861,994,863,997,860,926,930,797,1064,1063,798,796,932,931,933,999,866,1000,865,998,867,1001,864,930,934,801,1068,1067,800,802,935,936,934,1002,869,1003,868,1001,870,1004,867,937,933,1071,804,803,1070,1072,938,937,939,1005,872,1006,871,1004,873,1007,870,936,940,1074,807,806,1073,1075,941,940,942,1009,874,1008,875,1010,873,1007,876,939,943,1077,809,810,1078,1076,944,943,945,1012,877,1011,878,1013,876,1010,879,942,946,1080,812,813,1081,1079,947,946,948,1015,880,1014,881,1016,879,1013,882,945,949,815,1083,1084,816,814,951,952,950,1019,884,1018,885,1020,883,1017,886,953,949,819,1087,1088,818,820,954,955,953,1022,887,1021,888,1023,886,1020,952,956,889,822,1090,1091,821,823,957,956,958,1025,890,1024,891,1026,889,955,959,1023,892,825,1094,1093,824,826,960,959,961,1028,893,1027,894,1029,892,958,962,1097,1026,828,895,827,1096,1030,963,962,964,1031,896,1030,897,1032,895,961,965,1100,830,1029,831,898,1099,1033,967,966,968,1035,900,1034,901,1036,899,969,965,1104,834,1033,835,902,1103,1037,970,969,971,1038,903,1037,904,1039,902,968,972,1107,837,1036,838,1106,905,1040,1110,1179,1111,1180,1041,1249,1181,1042,1109,1178,1112,973,1250,1248,1182,1251,1320,1043,1113,1112,1114,1183,1044,1043,1182,1184,1045,1111,1115,1253,976,1042,975,1254,1181,1185,1116,1115,1117,1186,1047,1046,1185,1187,1048,1114,1118,1256,979,1045,978,1257,1184,1188,1120,1121,1119,1190,1051,1050,1191,1189,1052,1122,1118,1260,983,1049,982,1261,1192,1188,1123,1122,1124,1193,1054,1053,1192,1194,1055,1125,1121,1263,986,1052,985,1264,1195,1191,1126,1125,1127,1196,1057,1056,1195,1197,1058,1128,1124,1266,1055,989,988,1267,1194,1198,1129,1130,1128,1199,1060,1059,1200,1198,1061,1131,1127,1058,1269,991,992,1270,1201,1197,1132,1133,1131,1202,1063,1062,1203,1201,1064,1061,1130,1134,1272,994,995,1273,1204,1200,1135,1134,1136,1205,1066,1065,1206,1204,1067,1064,1137,1133,997,1275,1276,998,1207,1203,1139,1138,1140,1209,1070,1069,1208,1210,1071,1068,1137,1141,1001,1279,1280,1002,1207,1211,1142,1143,1141,1212,1073,1072,1213,1211,1074,1071,1144,1140,1004,1282,1283,1005,1214,1210,1145,1146,1144,1215,1076,1075,1216,1214,1077,1074,1147,1143,1007,1286,1285,1217,1213,1008,1148,1147,1149,1218,1078,1079,1217,1219,1077,1080,1150,1146,1010,1289,1288,1009,1216,1220,1151,1152,1150,1221,1081,1082,1222,1220,1080,1083,1153,1149,1013,1292,1291,1012,1223,1219,1155,1154,1156,1225,1085,1086,1224,1226,1084,1087,1153,1157,1017,1296,1295,1016,1223,1227,1158,1159,1157,1228,1088,1089,1227,1229,1087,1090,1160,1156,1299,1020,1019,1298,1230,1226,1161,1160,1162,1231,1091,1092,1230,1232,1090,1159,1163,1093,1302,1023,1022,1301,1229,1233,1164,1163,1165,1234,1094,1095,1233,1235,1093,1162,1166,1305,1096,1025,1026,1304,1232,1236,1167,1168,1166,1237,1097,1098,1238,1236,1096,1169,1165,1308,1028,1099,1029,1307,1239,1235,1170,1171,1169,1240,1100,1101,1241,1239,1099,1168,1172,1311,1031,1102,1032,1310,1242,1238,1174,1173,1175,1244,1104,1105,1245,1243,1103,1172,1176,1315,1035,1106,1036,1314,1246,1242,1177,1176,1178,1247,1107,1108,1246,1248,1106,1175,1179,1318,1038,1109,1039,1317,1245,1249,1321,1322,1392,1393,1250,1394,1464,1251,1320,1323,1391,1465,1180,1395,1463,1466,1537,1252,1324,1325,1323,1396,1253,1252,1397,1395,1254,1326,1322,1468,1183,1251,1182,1469,1398,1394,1327,1328,1326,1399,1256,1255,1400,1398,1257,1329,1325,1471,1186,1254,1185,1472,1401,1397,1330,1329,1331,1402,1259,1258,1401,1403,1260,1328,1332,1474,1189,1257,1188,1475,1404,1400,1334,1333,1335,1406,1263,1262,1405,1407,1264,1336,1332,1478,1193,1261,1192,1479,1408,1404,1337,1336,1338,1409,1266,1265,1410,1408,1267,1339,1335,1481,1264,1196,1195,1482,1407,1411,1340,1339,1341,1412,1269,1268,1413,1411,1270,1338,1342,1267,1484,1198,1199,1485,1410,1414,1343,1344,1342,1415,1272,1271,1414,1416,1273,1270,1341,1345,1487,1201,1202,1488,1413,1417,1346,1347,1345,1418,1275,1274,1419,1417,1276,1273,1348,1344,1204,1490,1491,1205,1420,1416,1349,1350,1348,1421,1278,1277,1422,1420,1279,1276,1347,1351,1207,1493,1494,1208,1419,1423,1352,1351,1353,1424,1281,1280,1423,1425,1282,1279,1354,1350,1210,1496,1497,1211,1426,1422,1355,1356,1354,1427,1284,1283,1428,1426,1285,1282,1353,1357,1213,1499,1500,1214,1429,1425,1359,1360,1358,1431,1287,1288,1432,1430,1286,1289,1361,1357,1217,1504,1503,1216,1433,1429,1362,1363,1361,1434,1290,1291,1435,1433,1289,1292,1364,1360,1220,1507,1506,1219,1436,1432,1365,1364,1366,1437,1293,1294,1436,1438,1292,1295,1367,1363,1223,1510,1509,1222,1439,1435,1368,1367,1369,1440,1296,1297,1439,1441,1295,1298,1366,1370,1226,1513,1512,1225,1438,1442,1371,1370,1372,1443,1299,1300,1442,1444,1298,1301,1373,1369,1516,1229,1228,1515,1445,1441,1374,1375,1373,1446,1302,1303,1447,1445,1301,1376,1372,1304,1519,1232,1231,1518,1444,1448,1377,1378,1376,1449,1305,1306,1450,1448,1304,1379,1375,1522,1307,1234,1235,1521,1451,1447,1380,1379,1381,1452,1308,1309,1451,1453,1307,1378,1382,1525,1237,1310,1238,1524,1450,1454,1384,1383,1385,1456,1312,1313,1455,1457,1311,1382,1386,1529,1241,1314,1242,1528,1454,1458,1387,1386,1388,1459,1315,1316,1460,1458,1314,1389,1385,1532,1244,1317,1245,1531,1461,1457,1390,1391,1389,1462,1318,1319,1463,1461,1317,1392,1388,1535,1247,1320,1248,1534,1464,1460,1611,1612,1683,1684,1538,1757,1685,1539,1610,1613,1682,1758,1465,1686,1756,1540,1609,1831,1614,1613,1615,1541,1687,1688,1540,1542,1686,1612,1616,1468,1761,1689,1762,1539,1543,1467,1617,1618,1616,1544,1690,1691,1545,1543,1689,1619,1615,1471,1764,1692,1765,1542,1546,1472,1621,1620,1622,1548,1694,1695,1547,1549,1693,1619,1623,1475,1768,1696,1769,1546,1550,1474,1624,1623,1625,1551,1697,1698,1550,1552,1696,1626,1622,1478,1771,1699,1772,1549,1553,1477,1627,1628,1626,1554,1700,1701,1553,1555,1699,1629,1625,1481,1774,1702,1775,1556,1552,1482,1630,1631,1629,1557,1703,1704,1556,1558,1702,1705,1628,1632,1484,1777,1778,1555,1559,1485,1633,1632,1634,1560,1706,1707,1559,1561,1705,1708,1631,1635,1487,1780,1781,1558,1562,1486,1636,1637,1635,1563,1709,1710,1564,1562,1708,1711,1638,1634,1490,1783,1784,1565,1561,1491,1640,1641,1639,1567,1713,1714,1568,1566,1712,1715,1642,1638,1494,1787,1788,1565,1569,1495,1643,1644,1642,1570,1716,1717,1571,1569,1715,1718,1645,1641,1497,1790,1791,1572,1568,1498,1646,1645,1647,1573,1719,1720,1572,1574,1718,1721,1644,1648,1500,1793,1794,1571,1575,1501,1649,1650,1648,1576,1723,1722,1575,1577,1724,1721,1651,1647,1503,1797,1796,1578,1574,1502,1652,1653,1651,1579,1726,1725,1580,1578,1727,1724,1654,1650,1506,1800,1799,1581,1577,1507,1655,1654,1656,1582,1729,1728,1583,1581,1730,1727,1657,1653,1509,1803,1802,1584,1580,1510,1659,1658,1660,1586,1733,1732,1585,1587,1734,1731,1657,1661,1513,1807,1806,1584,1588,1512,1662,1663,1661,1589,1736,1735,1588,1590,1737,1734,1660,1664,1516,1810,1809,1591,1587,1517,1665,1666,1664,1592,1739,1738,1593,1591,1740,1737,1663,1667,1519,1813,1812,1594,1590,1520,1668,1667,1669,1595,1742,1741,1594,1596,1743,1666,1670,1522,1816,1740,1815,1593,1597,1521,1671,1672,1670,1598,1745,1744,1599,1597,1746,1669,1673,1525,1819,1743,1818,1596,1600,1524,1674,1673,1675,1601,1748,1747,1602,1600,1749,1676,1672,1528,1822,1746,1821,1603,1599,1527,1678,1679,1677,1605,1752,1751,1606,1604,1753,1676,1680,1532,1826,1750,1825,1607,1603,1533,1681,1680,1682,1608,1755,1754,1609,1607,1756,1683,1679,1535,1829,1753,1828,1606,1610,1534,1832,1905,1833,1906,1758,1831,1759,1907,1978,1834,1904,1979,1684,1760,1830,1757,1685,1980,1835,1836,1834,1761,1909,1908,1762,1760,1910,1833,1837,1687,1982,1907,1759,1763,1981,1688,1838,1837,1839,1764,1912,1911,1765,1763,1913,1836,1840,1690,1985,1910,1984,1766,1762,1691,1842,1841,1843,1768,1916,1915,1767,1769,1917,1844,1840,1694,1989,1914,1988,1770,1766,1695,1845,1844,1846,1771,1919,1918,1770,1772,1920,1843,1847,1697,1992,1917,1991,1769,1773,1696,1848,1849,1847,1774,1922,1921,1773,1775,1923,1850,1846,1700,1995,1920,1994,1776,1772,1701,1851,1852,1850,1777,1925,1924,1778,1776,1926,1853,1849,1703,1923,1998,1997,1779,1775,1704,1855,1854,1856,1781,1929,1928,1780,1782,1930,1927,1853,1857,1707,2002,2001,1779,1783,1708,1858,1857,1859,1784,1932,1931,1783,1785,1933,1930,1856,1860,1710,2005,2004,1782,1786,1709,1861,1860,1862,1787,1935,1934,1786,1788,1936,1933,1859,1863,1713,2008,2007,1785,1789,1712,1864,1865,1863,1790,1938,1937,1789,1791,1939,1936,1866,1862,1716,2011,2010,1792,1788,1717,1867,1868,1866,1793,1941,1940,1794,1792,1942,1939,1865,1869,1719,2014,2013,1795,1791,1720,1871,1870,1872,1797,1944,1945,1796,1798,1943,1946,1869,1873,1723,2017,2018,1795,1799,1722,1874,1875,1873,1800,1947,1948,1801,1799,1946,1949,1876,1872,1726,2020,2021,1802,1798,1727,1877,1876,1878,1803,1950,1951,1802,1804,1949,1952,1875,1879,1729,2023,2024,1801,1805,1728,1880,1879,1881,1806,1953,1954,1805,1807,1952,1955,1878,1882,1732,2026,2027,1804,1808,1731,1883,1884,1882,1809,1956,1957,1810,1808,1955,1958,1885,1881,1735,2029,2030,1811,1807,1736,1887,1888,1886,1813,1960,1961,1814,1812,1959,1889,1885,1739,1962,2033,2034,1815,1811,1740,1890,1891,1889,1816,1963,1964,1815,1817,1962,1888,1892,1742,2036,1965,2037,1814,1818,1741,1893,1894,1892,1819,1966,1967,1820,1818,1965,1895,1891,1745,2039,1968,2040,1821,1817,1746,1896,1895,1897,1822,1969,1970,1821,1823,1968,1894,1898,1748,2042,1971,2043,1820,1824,1747,1900,1901,1899,1826,1973,1974,1825,1827,1972,1898,1902,1752,2046,1975,2047,1824,1828,1753,1903,1904,1902,1829,1976,1977,1830,1828,1975,1905,1901,1755,2049,1978,1831,1827,2050,1756,2052,2053,2124,1979,2125,1980,2051,2126,2196,2054,2123,2197,1906,1981,2050,1907,1978,2198,2055,2056,2054,1982,2128,2127,1983,1981,2129,2057,2053,1909,2200,2126,2199,1984,1980,1908,2058,2059,2057,1985,2131,2130,1986,1984,2132,2060,2056,1912,2203,2129,2202,1987,1983,1911,2062,2061,2063,1989,2135,2134,1988,1990,2136,2060,2064,1916,2207,2133,2206,1987,1991,1917,2065,2064,2066,1992,2138,2137,1991,1993,2139,2067,2063,1919,2210,2136,2209,1994,1990,1918,2068,2069,2067,1995,2141,2140,1994,1996,2142,2070,2066,1922,2213,2139,2212,1997,1993,1921,2071,2072,2070,1998,2144,2143,1999,1997,2145,2069,2073,1925,2142,2216,2215,1996,2000,1926,2074,2073,2075,2001,2147,2146,2002,2000,2148,2145,2072,2076,1928,2219,2218,1999,2003,1927,2077,2078,2076,2004,2150,2149,2005,2003,2151,2148,2079,2075,1931,2222,2221,2006,2002,1932,2081,2082,2080,2008,2154,2153,2009,2007,2155,2152,2079,2083,1935,2226,2225,2006,2010,1936,2084,2085,2083,2011,2157,2156,2012,2010,2158,2155,2086,2082,1938,2229,2228,2013,2009,1939,2087,2086,2088,2014,2160,2159,2013,2015,2161,2158,2085,2089,1941,2232,2231,2012,2016,1940,2090,2089,2091,2017,2162,2163,2016,2018,2161,2164,2092,2088,1944,2234,2235,2019,2015,1945,2093,2094,2092,2020,2165,2166,2021,2019,2164,2167,2095,2091,1947,2237,2238,2022,2018,1946,2096,2095,2097,2023,2168,2169,2022,2024,2167,2170,2098,2094,1950,2240,2241,2021,2025,1949,2100,2099,2101,2027,2172,2173,2026,2028,2171,2174,2098,2102,1954,2244,2245,2025,2029,1953,2103,2102,2104,2030,2175,2176,2029,2031,2174,2177,2101,2105,1957,2247,2248,2032,2028,1956,2106,2107,2105,2033,2178,2179,2034,2032,2177,2108,2104,1960,2180,2250,2251,2035,2031,1959,2109,2108,2110,2036,2181,2182,2035,2037,2180,2107,2111,1963,2253,2183,2254,2034,2038,1962,2112,2113,2111,2039,2184,2185,2040,2038,2183,2114,2110,1966,2256,2186,2257,2041,2037,1967,2115,2116,2114,2042,2187,2188,2043,2041,2186,2113,2117,1969,2259,2189,2260,2040,2044,1968,2119,2118,2120,2046,2191,2192,2045,2047,2190,2117,2121,1973,2263,2193,2264,2048,2044,1972,2122,2121,2123,2049,2194,2195,2048,2050,2193,2120,2124,1976,2266,2196,2267,2047,2051,1975,2269,-1,-1,2339,2270,2197,-1,-1,2198,2268,-1,-1,-1,2271,2338,-1,2125,-1,2272,2273,2271,-1,2200,-1,2201,2199,-1,-1,-1,-1,2270,2274,2128,2202,-1,2129,2275,-1,2276,2274,2203,-1,2204,-1,2202,-1,-1,-1,2277,2273,2131,-1,-1,2205,2278,-1,2279,2277,2206,-1,2207,-1,2205,-1,-1,-1,2280,2276,2134,2208,-1,-1,2281,-1,2282,2280,2209,-1,2210,-1,2208,-1,-1,-1,2283,2279,2137,2211,-1,2138,2284,-1,2283,2285,2212,-1,2213,-1,2211,-1,-1,-1,2282,2286,2140,2214,-1,-1,2288,-1,2289,2287,2216,-1,2217,-1,2215,-1,-1,-1,2218,2290,2286,2144,-1,2145,2291,-1,2290,2292,2219,-1,2220,-1,2218,-1,-1,-1,2221,2289,2293,2147,-1,-1,2294,2293,2295,-1,-1,2222,2223,-1,-1,2221,-1,-1,2224,2296,2292,2150,2151,-1,2297,-1,2298,2296,2225,2226,-1,-1,2224,-1,2227,-1,-1,2299,2295,-1,-1,2153,2300,2301,2299,-1,-1,2228,2229,-1,-1,2227,2230,-1,-1,2302,2298,2156,2157,-1,2303,-1,2304,2302,2231,2232,-1,-1,2230,-1,2233,-1,-1,2305,2301,-1,-1,2159,2306,-1,2307,2305,2235,-1,2234,-1,-1,2236,2233,-1,-1,2308,2304,2163,2162,-1,2309,-1,2308,2310,2238,-1,2237,-1,2239,-1,-1,2236,-1,2307,2311,2166,2165,-1,2312,-1,2311,2313,2241,2240,-1,-1,2242,-1,-1,2239,-1,2310,2314,2169,-1,-1,2315,2314,2316,-1,2244,-1,2243,-1,-1,2245,-1,-1,2242,2317,2313,2172,2171,-1,2318,-1,2317,2319,2247,2246,-1,-1,2248,-1,-1,2245,-1,-1,2316,2320,-1,2175,2321,2320,2322,-1,2250,-1,2249,-1,2251,-1,-1,-1,2248,2319,2323,2178,2177,-1,2325,-1,2326,2324,2254,-1,2253,-1,2255,-1,-1,-1,-1,2327,2323,-1,2182,2252,2328,2329,2327,-1,2257,-1,2256,2258,-1,-1,-1,-1,2330,2326,2185,2255,2184,-1,2331,-1,2332,2330,2260,-1,2259,-1,2261,-1,-1,-1,2333,2329,2188,-1,-1,2258,2334,-1,2335,2333,2263,-1,2262,2264,-1,-1,-1,-1,2336,2332,2191,-1,2261,2190,2337,-1,2338,2336,2266,-1,2265,-1,2267,-1,-1,-1,2339,2335,2194,-1,-1,2264],"visual":[0,5,4,3,1,7,6,2,16,8,17,9,10,15,11,18,14,12,20,37,36,21,8,38,58,19,9,22,35,59,1,39,57,60,85,7,23,22,41,40,10,24,42,9,11,39,21,2,64,63,25,3,43,65,26,25,44,45,12,27,43,13,11,24,46,68,3,69,67,4,42,28,29,28,48,14,49,47,30,27,15,13,50,46,72,73,4,5,74,71,31,32,52,51,16,30,53,15,17,33,50,77,6,78,76,5,54,29,34,35,55,56,18,33,54,17,19,57,36,7,81,82,32,6,53,83,86,117,116,87,150,118,59,85,60,151,115,88,188,152,119,149,37,84,89,120,121,90,88,62,61,119,122,63,155,91,154,87,60,39,156,40,92,124,93,123,91,64,125,65,94,159,63,158,122,66,41,90,42,160,95,127,96,128,67,94,126,68,66,97,162,163,129,44,43,161,93,69,98,99,131,130,70,97,69,132,100,129,71,166,167,46,165,68,45,96,101,102,134,133,135,73,72,100,103,170,74,71,169,171,136,132,48,49,105,104,137,138,75,106,76,136,103,139,74,174,173,50,175,77,51,107,108,141,107,140,78,109,142,77,79,106,178,177,139,52,53,179,110,76,111,144,110,145,112,81,143,80,109,181,82,182,146,79,55,113,54,180,114,148,147,113,115,83,84,149,146,82,185,112,186,116,85,57,184,56,189,230,229,190,273,231,151,274,152,188,320,275,228,191,232,272,117,187,192,233,234,191,193,232,154,153,277,278,155,235,190,194,276,152,231,119,195,236,237,194,196,235,156,157,281,280,238,193,155,158,282,197,122,234,198,239,240,197,199,159,238,160,284,241,158,196,285,283,200,124,161,125,201,243,242,200,202,162,244,161,241,287,288,199,163,286,127,289,160,203,204,246,203,245,247,205,165,164,291,202,244,290,166,292,163,129,248,206,249,207,206,248,250,167,208,168,205,294,295,166,247,293,169,251,132,131,252,209,210,253,251,170,208,211,171,169,297,298,250,254,296,299,134,168,255,212,213,256,254,173,211,172,214,301,300,174,257,302,171,253,136,137,215,258,216,259,257,214,175,176,304,217,260,305,174,303,177,139,256,213,218,261,262,219,217,178,260,179,263,308,307,220,177,309,141,306,180,216,221,265,264,222,220,181,266,180,311,263,182,223,310,312,219,144,179,143,224,268,267,225,223,269,184,183,314,315,266,226,185,182,313,222,146,270,227,271,270,228,226,272,186,187,318,317,185,269,229,225,319,188,273,149,371,321,372,422,370,322,423,274,476,424,320,275,373,421,369,323,230,276,374,324,375,325,323,373,426,277,427,276,376,278,326,425,322,428,372,233,377,378,327,328,326,430,280,376,379,429,279,329,281,431,325,428,278,235,381,330,380,331,382,433,329,283,332,282,434,379,432,284,383,281,238,328,384,333,334,383,385,286,437,436,332,335,285,287,386,382,438,435,284,241,387,337,388,336,386,440,338,289,288,335,439,389,441,290,287,385,244,339,391,390,340,339,341,443,392,389,292,291,444,338,442,293,290,342,445,246,394,343,393,342,344,395,447,295,446,294,392,341,448,296,293,345,445,396,397,346,398,396,345,347,450,297,298,449,451,395,399,344,348,296,299,252,400,349,401,350,348,399,453,300,454,301,402,351,452,299,302,347,455,398,403,404,352,353,351,457,405,402,303,304,456,354,458,302,305,350,455,258,407,355,406,356,408,460,354,306,307,357,461,405,459,305,308,409,260,353,410,359,358,409,411,309,463,464,357,360,310,308,412,408,462,465,311,263,413,362,414,361,412,467,363,312,360,313,466,415,468,311,411,314,266,364,416,417,365,364,366,470,315,418,415,471,316,363,314,469,367,472,317,269,420,368,419,367,369,421,474,318,473,319,418,317,366,475,370,472,422,271,533,477,534,590,532,478,591,650,592,423,476,424,535,589,531,479,593,649,536,480,537,481,535,479,594,595,426,538,593,425,427,482,596,478,534,654,539,540,483,484,598,482,597,538,541,429,599,485,430,428,596,481,658,537,543,542,486,487,601,544,485,600,602,432,541,488,433,431,545,484,599,603,546,489,545,490,547,604,605,488,435,491,603,544,434,436,548,606,665,487,549,493,550,492,548,608,607,494,438,491,609,551,437,439,547,606,668,495,552,553,496,495,611,551,497,612,610,441,554,494,440,442,550,498,613,609,556,555,499,498,614,500,615,557,554,444,613,497,443,445,616,501,675,558,559,502,558,501,560,503,618,617,447,557,619,448,446,500,616,504,561,679,562,505,563,561,506,504,621,622,620,450,449,451,560,564,507,503,619,623,565,508,566,509,564,507,624,625,453,567,623,452,454,510,626,506,563,685,568,569,511,512,628,510,627,567,570,456,629,513,455,457,626,509,689,566,572,571,514,515,631,573,513,630,632,459,570,516,458,460,574,512,633,629,575,517,574,518,576,634,635,516,462,519,633,573,461,463,577,636,696,515,578,521,579,520,577,638,637,522,465,519,639,580,464,466,576,636,699,523,581,582,524,523,641,580,525,642,640,468,583,522,467,469,579,526,639,643,585,584,527,526,644,528,645,586,583,471,643,525,470,472,646,529,706,587,588,530,587,529,589,531,648,647,474,586,649,475,473,528,646,532,590,710,713,651,714,775,776,652,712,839,777,591,774,715,592,650,711,653,840,778,716,717,654,779,715,655,653,780,778,594,718,593,595,656,714,781,652,843,719,720,657,658,782,783,718,656,721,597,781,659,784,598,596,717,847,655,722,723,660,661,786,785,721,659,724,600,787,662,784,599,601,850,658,720,726,725,663,664,789,788,727,724,662,790,665,603,602,604,787,853,728,854,729,728,667,666,792,730,791,793,665,668,727,606,607,605,731,857,856,790,732,731,670,669,733,795,796,671,794,668,609,730,610,608,734,797,860,859,735,673,736,734,672,798,799,674,612,797,671,737,800,611,613,733,863,675,738,739,676,675,802,737,801,677,615,740,803,674,800,616,614,736,866,678,741,742,679,805,678,740,680,804,743,806,618,619,617,677,803,681,870,739,745,744,682,808,681,683,746,743,807,809,621,622,620,680,684,873,806,810,748,747,685,811,686,749,684,812,746,810,624,623,625,687,813,683,876,750,751,750,688,689,814,752,815,687,627,749,813,690,816,628,626,753,880,686,754,691,753,755,692,818,817,690,630,819,693,752,816,629,631,756,883,689,757,758,694,695,756,821,820,693,822,696,633,759,632,634,755,819,886,887,760,761,697,698,824,759,823,825,696,699,762,636,637,635,758,890,889,826,763,764,701,700,827,828,762,765,702,826,699,639,638,640,829,893,761,892,767,766,704,703,830,831,768,705,765,642,829,702,832,643,641,896,706,769,770,769,707,706,834,833,771,708,768,645,835,705,832,644,646,772,899,709,773,772,710,837,774,709,711,836,838,648,771,649,647,708,775,835,712,903,906,973,972,907,840,1040,974,841,905,776,971,908,1041,839,777,904,842,1039,909,910,976,843,908,977,844,842,975,911,779,978,845,1044,780,778,907,1045,912,913,846,979,980,847,911,914,845,978,981,782,848,783,1048,1047,781,910,916,915,983,849,850,982,917,914,984,848,851,785,981,1051,786,784,1050,1052,919,918,986,853,852,920,985,987,854,917,851,788,789,1054,984,921,787,1055,922,921,989,923,856,855,990,988,857,791,920,854,924,792,991,1057,1058,790,925,926,859,992,993,924,858,860,991,927,994,794,795,857,1061,923,1060,793,928,929,996,862,995,927,863,861,930,997,797,994,798,1064,864,860,796,926,932,931,999,865,866,998,933,1000,864,930,800,801,867,1067,997,1068,863,799,935,934,1002,868,869,936,1003,1001,867,933,870,803,804,1071,1004,1070,937,802,938,937,1005,939,871,1006,872,1004,870,873,936,1007,806,807,940,1074,1073,805,941,942,1009,940,875,1008,874,1010,876,873,943,1007,810,809,939,1077,1078,811,944,945,1012,878,877,943,1011,1013,879,946,876,813,812,1080,1010,1081,942,814,947,948,1015,881,880,1016,946,1014,882,949,816,815,879,1084,1017,1083,883,817,951,950,1018,884,1019,952,885,883,949,1017,819,1020,818,1087,886,882,820,953,954,953,887,1022,1021,955,888,886,1023,952,1020,822,821,889,1090,956,1091,823,957,958,1025,956,890,891,1024,1026,889,825,959,892,955,824,1023,1094,1093,826,960,961,1028,893,894,959,1029,1027,892,962,895,828,827,1097,1030,958,829,1096,963,964,1031,897,896,1032,962,965,1030,898,895,831,1033,1100,830,832,1101,1099,967,966,900,1035,1034,899,968,965,901,1036,1033,834,898,833,1103,1104,835,969,970,969,1038,903,971,1037,902,904,1039,968,837,1036,901,1107,836,838,972,1106,1110,1180,1111,1179,1041,1249,1181,1042,1109,1250,1178,1112,973,1320,1251,1248,1182,1043,1113,1183,1114,1184,1044,1112,1045,1182,1043,1115,1253,1185,976,1254,1046,1111,977,975,1116,1117,1186,1187,1047,1048,1115,1185,1118,1046,1188,1256,1257,1049,979,980,978,1114,1120,1119,1190,1189,1050,1051,1121,1118,1191,1188,1049,1052,1260,1259,982,983,1261,981,1123,1122,1193,1192,1054,1124,1053,1194,1121,1055,1052,1263,1191,985,1262,986,1264,1125,1126,1196,1125,1127,1057,1195,1056,1197,1058,1124,1266,1055,1128,988,1267,989,1194,1265,1129,1199,1130,1128,1060,1200,1198,1059,1061,1131,1269,1270,1127,992,1058,991,1201,1197,1132,1133,1202,1203,1063,1131,1062,1201,1064,1134,1273,1204,1272,995,994,1061,1130,1065,1135,1136,1205,1206,1066,1134,1067,1137,1065,1204,1207,1276,998,1275,997,1068,1277,1064,1139,1138,1209,1208,1069,1140,1070,1210,1137,1068,1207,1279,1001,1071,1280,1000,1278,1002,1142,1212,1141,1211,1143,1072,1073,1213,1071,1140,1282,1074,1210,1283,1004,1144,1003,1005,1145,1215,1144,1146,1075,1076,1216,1214,1077,1074,1286,1285,1147,1143,1007,1217,1213,1006,1148,1218,1149,1219,1147,1079,1078,1217,1080,1150,1289,1077,1220,1288,1010,1146,1011,1009,1151,1152,1221,1222,1082,1150,1081,1220,1153,1083,1223,1292,1013,1080,1291,1014,1293,1012,1155,1154,1225,1224,1085,1156,1084,1153,1086,1226,1223,1295,1016,1296,1017,1083,1294,1087,1158,1157,1228,1227,1088,1159,1089,1229,1087,1156,1298,1226,1299,1019,1020,1090,1160,1086,1161,1231,1160,1162,1091,1230,1232,1092,1090,1159,1302,1301,1163,1022,1093,1023,1229,1233,1164,1234,1165,1163,1094,1235,1095,1233,1093,1166,1305,1096,1162,1026,1304,1025,1236,1306,1167,1168,1237,1238,1097,1166,1098,1236,1169,1096,1099,1308,1239,1029,1309,1028,1307,1165,1170,1171,1240,1241,1101,1100,1169,1172,1239,1242,1102,1099,1311,1312,1032,1031,1310,1033,1174,1173,1244,1243,1104,1103,1175,1245,1172,1105,1242,1315,1314,1102,1035,1034,1036,1176,1177,1247,1176,1246,1107,1178,1106,1248,1108,1175,1318,1245,1038,1317,1105,1179,1037,1039,1321,1393,1322,1392,1464,1394,1250,1251,1320,1465,1323,1391,1537,1466,1395,1463,1180,1319,1324,1396,1325,1397,1323,1253,1395,1254,1252,1468,1326,1469,1398,1467,1322,1183,1255,1394,1327,1399,1328,1400,1326,1256,1398,1257,1255,1471,1329,1472,1401,1186,1258,1470,1325,1187,1330,1331,1402,1403,1259,1329,1260,1401,1332,1404,1258,1475,1474,1261,1189,1190,1476,1473,1334,1333,1406,1405,1262,1263,1335,1332,1407,1404,1478,1261,1477,1264,1192,1479,1193,1191,1337,1409,1336,1408,1265,1338,1266,1410,1335,1481,1407,1264,1480,1267,1482,1195,1196,1339,1340,1412,1339,1411,1341,1269,1268,1413,1484,1338,1270,1410,1267,1485,1483,1198,1342,1199,1343,1415,1342,1414,1344,1416,1272,1271,1487,1273,1488,1341,1270,1413,1345,1486,1201,1417,1346,1418,1347,1345,1419,1417,1275,1274,1490,1276,1491,1348,1344,1273,1420,1416,1204,1205,1349,1421,1350,1422,1348,1278,1420,1277,1279,1494,1493,1351,1423,1276,1347,1207,1208,1495,1352,1424,1353,1425,1281,1351,1423,1280,1282,1354,1497,1426,1496,1498,1210,1279,1211,1350,1355,1356,1427,1428,1284,1354,1357,1283,1426,1285,1500,1429,1499,1501,1213,1214,1282,1286,1359,1358,1431,1430,1287,1360,1357,1288,1432,1286,1503,1429,1504,1502,1217,1216,1289,1285,1362,1434,1361,1433,1290,1363,1435,1291,1289,1360,1506,1432,1507,1505,1220,1292,1219,1364,1365,1437,1364,1436,1366,1293,1438,1294,1292,1509,1510,1363,1435,1295,1367,1223,1222,1508,1368,1440,1367,1369,1439,1441,1296,1297,1513,1295,1512,1366,1370,1298,1438,1442,1226,1225,1371,1443,1372,1444,1370,1442,1299,1300,1516,1298,1515,1373,1301,1445,1369,1517,1229,1441,1374,1446,1375,1447,1373,1302,1303,1445,1519,1376,1301,1448,1304,1518,1520,1232,1372,1231,1377,1449,1378,1450,1306,1376,1305,1448,1379,1522,1451,1307,1523,1304,1521,1235,1234,1375,1380,1381,1452,1453,1309,1308,1379,1382,1451,1454,1525,1310,1526,1307,1238,1524,1237,1239,1384,1383,1456,1455,1312,1385,1311,1457,1382,1454,1313,1528,1529,1310,1241,1240,1527,1530,1387,1459,1386,1458,1388,1315,1460,1314,1316,1532,1385,1531,1457,1244,1313,1533,1389,1243,1390,1462,1389,1461,1391,1318,1463,1317,1319,1535,1388,1534,1460,1536,1392,1247,1316,1464,1611,1538,1539,1610,1612,1683,1465,1684,1466,1537,1685,1757,1540,1609,1613,1682,1393,1467,1614,1541,1542,1615,1540,1613,1468,1687,1469,1688,1467,1543,1616,1686,1539,1470,1612,1396,1617,1544,1618,1545,1543,1616,1471,1472,1690,1691,1546,1619,1470,1473,1689,1692,1399,1542,1621,1548,1620,1547,1475,1474,1549,1694,1546,1622,1619,1693,1476,1473,1695,1402,1692,1403,1624,1551,1623,1550,1552,1625,1478,1697,1477,1549,1696,1622,1479,1698,1476,1406,1553,1405,1627,1554,1553,1626,1555,1628,1481,1700,1480,1482,1701,1552,1699,1625,1556,1629,1479,1409,1630,1557,1558,1631,1556,1629,1484,1703,1485,1704,1483,1559,1702,1632,1555,1628,1412,1486,1633,1560,1634,1561,1559,1632,1487,1707,1488,1706,1562,1486,1635,1708,1489,1705,1558,1415,1636,1563,1637,1564,1562,1490,1635,1491,1710,1565,1638,1709,1489,1711,1492,1418,1708,1561,1640,1567,1639,1566,1494,1568,1713,1493,1641,1565,1638,1712,1714,1495,1492,1421,1422,1569,1643,1570,1642,1569,1571,1644,1497,1716,1496,1717,1568,1641,1498,1715,1495,1572,1424,1645,1646,1573,1572,1645,1574,1647,1500,1719,1720,1499,1501,1571,1644,1575,1718,1648,1721,1498,1649,1576,1577,1650,1575,1648,1503,1723,1722,1504,1502,1578,1651,1574,1724,1647,1721,1505,1652,1579,1653,1580,1578,1651,1506,1726,1507,1725,1581,1654,1505,1727,1508,1577,1434,1650,1655,1582,1656,1583,1509,1581,1729,1510,1654,1584,1657,1730,1728,1508,1511,1437,1436,1580,1659,1586,1658,1585,1587,1513,1660,1512,1732,1584,1657,1733,1514,1731,1511,1440,1734,1588,1662,1589,1661,1588,1590,1663,1516,1735,1515,1736,1587,1517,1660,1734,1514,1737,1591,1443,1665,1592,1591,1664,1593,1666,1519,1739,1518,1738,1520,1590,1740,1663,1594,1667,1446,1517,1668,1595,1596,1669,1594,1667,1522,1742,1523,1521,1741,1597,1743,1670,1593,1666,1524,1449,1671,1598,1672,1599,1597,1670,1525,1745,1526,1600,1746,1673,1524,1744,1527,1452,1596,1453,1674,1601,1675,1602,1528,1529,1600,1748,1603,1673,1676,1749,1527,1530,1747,1456,1750,1455,1678,1605,1677,1604,1606,1679,1532,1531,1752,1751,1603,1676,1533,1530,1753,1750,1459,1607,1681,1608,1607,1680,1609,1682,1535,1755,1534,1754,1536,1606,1679,1756,1610,1533,1683,1462,1832,1758,1833,1905,1759,1831,1906,1684,1978,1907,1685,1757,1834,1904,1830,1760,1611,1756,1835,1761,1836,1762,1834,1760,1909,1687,1910,1688,1837,1908,1763,1686,1759,1833,1689,1911,1838,1839,1764,1765,1912,1837,1913,1763,1690,1840,1691,1766,1911,1689,1692,1914,1617,1618,1842,1841,1768,1767,1843,1916,1915,1769,1694,1693,1840,1766,1695,1917,1914,1692,1770,1844,1845,1771,1844,1770,1846,1772,1919,1918,1697,1696,1698,1843,1769,1920,1773,1847,1917,1695,1848,1774,1849,1775,1847,1773,1922,1700,1921,1701,1923,1699,1850,1776,1772,1846,1702,1627,1851,1777,1852,1778,1925,1850,1776,1703,1704,1926,1853,1924,1779,1702,1705,1775,1849,1630,1855,1854,1781,1780,1928,1856,1853,1782,1929,1707,1779,1706,1927,1708,1705,1930,1633,2001,1858,1784,1857,1783,1859,1785,1931,1932,1710,1709,1856,1782,1711,1930,1933,1708,1786,1860,1861,1787,1860,1862,1786,1788,1935,1934,1713,1712,1714,1859,1785,1936,1789,1863,1933,1711,1864,1790,1865,1791,1863,1789,1938,1716,1937,1717,1866,1792,1715,1939,1788,1862,1936,1718,1867,1868,1793,1794,1941,1866,1792,1719,1720,1869,1940,1795,1942,1718,1721,1646,1791,1865,1871,1870,1797,1796,1944,1872,1798,1723,1722,1869,1945,1795,1943,1724,1721,1649,1799,1873,1874,1800,1873,1799,1875,1801,1947,1726,1948,1725,1872,1798,1727,1946,1802,1876,1949,1724,1877,1803,1878,1876,1804,1802,1950,1951,1729,1730,1728,1879,1805,1949,1801,1875,1952,1731,1880,1806,1881,1807,1879,1805,1954,1953,1732,1733,1882,1808,1731,1955,1952,1734,1804,1878,1883,1884,1809,1810,1957,1882,1885,1808,1956,1735,1811,1736,1958,1734,1737,1955,1662,2030,1887,1813,1886,1812,1960,1888,1814,1739,1738,1959,1885,1961,1811,1740,1737,1815,1889,1665,1890,1816,1889,1815,1891,1817,1963,1742,1964,1741,1962,1743,1888,1814,1818,1892,1740,1668,1893,1819,1894,1820,1892,1818,1966,1967,1745,1746,1744,1895,1821,1965,1817,1891,1968,1747,1896,1897,1822,1823,1895,1969,1970,1821,1748,1749,1898,1824,1747,1968,1971,1750,1820,1894,1900,1899,1826,1825,1973,1901,1972,1827,1752,1898,1751,1824,1974,1753,1750,1971,1678,1677,1903,1829,1902,1828,1904,1830,1976,1755,1975,1754,1901,1977,1827,1756,1831,1905,1753,1974,2052,1979,2053,2124,2125,1980,2051,2126,2196,1906,1907,1978,2054,2123,2050,1981,2197,2127,2055,1982,2056,1983,2128,2054,1981,2129,1909,2127,1910,2057,1984,1908,2053,2200,1980,2130,2058,2059,1985,1986,2131,2057,2132,1984,1912,2060,1913,2130,1987,1911,2133,1914,2203,2204,2062,2061,1989,1988,2134,2135,2063,2060,1990,1987,1916,1915,2133,2136,1917,1914,2206,2207,2065,2064,1992,1991,2138,2137,2066,1993,1919,2063,1918,1990,2139,2136,1920,1917,2210,2209,2068,1995,2067,1994,2069,2141,2140,1996,1922,1921,2142,2066,1923,1993,2139,2070,1997,2213,2071,1998,2072,2070,2144,1999,1997,2143,1925,2145,1926,1924,2073,2000,2069,1996,2142,2216,2074,2075,2001,2002,2147,2073,2000,2146,2148,1928,1929,2076,2003,1927,2219,2072,1999,1930,2077,2078,2004,2005,2150,2076,2151,2003,2149,2079,1931,1932,2006,1930,1933,2222,2152,2075,2081,2080,2008,2007,2153,2154,2082,2079,2009,1935,2152,2006,1934,1936,1933,2225,2155,2226,2084,2083,2011,2010,2156,2085,2157,2012,1938,2082,1937,2155,2009,1939,2158,2228,2086,1936,2087,2014,2086,2088,2013,2159,2160,2015,1941,1940,2158,1942,2085,2012,2161,2089,2016,2231,2090,2017,2091,2089,2018,2163,2162,2016,1944,1945,2164,1943,2092,2019,2161,2088,2015,2235,2093,2094,2020,2021,2166,2092,2165,2019,1947,2095,1948,2167,2022,1946,2164,2238,2091,1949,2096,2097,2023,2024,2169,2168,2095,2098,2022,1950,2170,2025,1951,1949,1952,2241,2167,2240,2100,2099,2027,2026,2172,2101,2171,2028,2173,2098,1954,1953,2025,1955,1952,2244,2170,2102,2103,2102,2030,2029,2175,2104,2031,2176,2174,1957,1956,2101,2028,1958,2247,2105,2032,1955,2106,2033,2105,2107,2178,2032,2034,2179,1960,2177,1959,1961,2104,2031,2108,2035,2180,2250,2109,2036,2110,2037,2108,2181,2182,2035,1963,1964,2180,2111,1962,2038,2183,2107,2034,2253,2112,2113,2039,2040,2184,2185,2111,2038,1966,2114,1967,2041,2183,2186,1965,1968,2256,2257,2115,2116,2042,2043,2188,2187,2114,2117,2041,2044,1969,1970,2189,2186,1968,1971,2260,2259,2119,2118,2046,2045,2191,2120,2190,2047,1973,2117,1972,2192,2044,1974,2189,1971,2263,2262,2122,2049,2121,2048,2194,2123,2050,2193,1976,2195,1975,2120,2047,1977,2124,2266,2051,2192,2269,2197,-1,-1,2270,2339,-1,2198,2268,-1,2125,-1,-1,2126,2196,-1,2338,2271,2272,2200,2273,-1,-1,2271,2201,2199,-1,-1,2128,-1,-1,2129,2274,2202,2127,2270,2275,2276,-1,2203,2204,2274,-1,-1,2202,2131,-1,2132,2277,2205,-1,-1,-1,2130,2278,2279,2206,-1,-1,2207,2277,-1,2205,-1,2134,2280,2208,2135,-1,-1,2133,-1,2281,2282,-1,2210,2209,-1,-1,2280,2211,2283,2208,2138,2137,-1,-1,-1,-1,-1,2284,2285,-1,2213,-1,2212,2283,-1,2214,2286,2141,-1,-1,2140,2211,-1,2142,-1,2288,2287,-1,2216,2215,-1,-1,2217,2289,2286,2144,-1,2143,-1,2214,-1,2145,-1,2291,2290,2219,-1,-1,2218,2220,2292,-1,2289,2147,-1,-1,-1,2146,2148,2217,-1,2294,2293,2222,-1,-1,2223,2295,2221,-1,2150,2292,-1,-1,-1,2151,2149,2224,-1,2297,2296,2225,-1,-1,2226,2298,2224,-1,2153,-1,2295,-1,2154,-1,2227,2152,-1,2300,2299,-1,2228,-1,2229,2301,-1,2227,2156,-1,-1,2157,2230,2298,-1,2155,2302,2303,-1,2302,2231,2232,2304,-1,-1,2230,2233,2159,-1,2160,-1,-1,2301,2305,-1,2306,-1,2307,2235,2234,2305,-1,-1,2236,2233,2163,-1,2162,-1,-1,2308,2304,2164,2309,2310,-1,2238,2237,2308,-1,-1,2239,2166,-1,2165,2236,2311,-1,-1,-1,2167,2312,2313,2241,-1,-1,2240,2311,2242,-1,-1,2169,2314,-1,-1,2168,2239,2170,-1,2315,2316,2244,-1,-1,2243,-1,2314,2245,2172,2317,-1,2171,2173,-1,-1,-1,2242,2318,2319,2247,-1,-1,2248,2246,2317,-1,2320,-1,2175,-1,-1,2176,2174,2249,2245,2321,2322,-1,2250,2251,-1,-1,2249,2320,2323,2178,-1,2179,2252,-1,-1,-1,-1,2325,2324,2253,-1,-1,2254,2326,2252,2323,-1,-1,2181,2182,2255,-1,-1,2180,-1,2328,2327,-1,2256,2257,-1,-1,2329,2255,2326,2258,2184,2185,-1,-1,-1,-1,-1,2331,2330,2260,-1,-1,2259,2332,-1,2261,-1,2188,2329,2258,2187,-1,-1,2189,-1,2334,2333,-1,2263,2262,2335,-1,-1,2264,2191,-1,2190,2332,2261,-1,-1,2192,-1,2337,2266,2336,-1,-1,2338,2265,2267,-1,2194,-1,-1,-1,2193,2335,2264,2195,2339]},"4":{"rings":56,"count":4187,"defaultK":17,"kMax":32,"geodesic":[0,5,4,1,2,6,3,7,14,9,19,16,12,17,11,10,18,15,13,8,24,34,21,37,31,27,36,22,29,28,30,32,38,60,39,20,61,88,62,21,37,59,40,8,89,87,63,90,120,22,36,19,9,91,119,64,86,41,58,1,121,122,157,92,42,43,41,66,23,65,24,67,22,64,40,44,10,95,94,68,25,96,11,93,9,21,63,97,39,45,69,92,127,2,128,126,46,47,45,71,26,70,27,72,25,69,44,48,100,12,101,28,99,73,13,102,11,68,24,98,43,49,134,74,133,3,29,103,49,50,48,74,29,75,28,73,76,30,51,47,27,104,14,105,13,103,72,106,77,15,31,102,52,46,26,107,139,138,4,12,53,52,54,79,32,80,31,78,33,81,55,51,110,16,109,30,111,77,15,108,17,82,34,112,56,50,145,76,146,6,29,107,57,58,56,84,35,85,34,83,36,86,59,55,18,115,116,82,33,114,17,117,19,37,87,113,60,54,81,118,152,7,151,153,158,198,159,121,199,200,243,157,122,197,160,89,244,201,242,245,291,156,123,120,90,290,246,196,161,241,202,61,292,119,91,293,162,163,161,203,125,204,124,202,126,205,123,164,160,92,249,248,93,250,91,201,247,206,127,122,94,251,165,159,297,64,90,298,166,165,167,208,128,207,129,209,127,206,164,168,95,253,254,130,96,210,252,94,126,255,205,97,163,169,251,302,131,66,67,303,170,169,171,212,132,213,131,211,133,172,168,214,258,98,99,130,259,257,210,134,97,260,100,256,215,173,167,307,69,129,308,209,217,218,216,263,174,175,264,262,173,176,219,215,265,313,136,312,135,314,261,137,311,172,134,315,177,266,214,220,366,102,138,367,179,178,180,222,140,223,139,221,141,181,177,269,105,268,224,106,220,138,142,270,267,104,107,225,182,176,271,319,219,75,318,266,226,225,227,273,183,182,272,274,184,181,224,228,271,323,143,324,144,322,275,142,325,185,145,321,180,270,229,223,377,108,141,376,187,186,188,231,147,230,148,232,146,185,189,229,278,112,111,149,277,279,233,145,113,276,110,280,228,184,190,329,81,150,328,234,191,192,190,235,151,236,150,234,152,237,193,189,115,283,282,149,114,233,284,116,153,281,238,113,194,188,285,334,148,84,83,333,195,194,196,240,154,239,155,241,153,238,156,193,197,118,287,288,117,286,119,242,289,237,152,157,116,285,192,198,339,86,120,338,399,400,456,344,457,517,458,345,398,401,455,292,518,516,459,581,519,293,343,346,397,580,520,342,294,402,454,244,582,515,460,583,403,402,404,461,348,462,347,460,349,405,401,463,522,296,523,346,295,459,521,350,297,524,294,464,406,400,345,247,520,587,586,248,407,406,408,465,352,466,351,464,353,467,350,409,405,527,299,526,300,528,298,463,525,354,468,301,349,529,404,410,591,297,251,250,411,410,412,470,355,469,356,471,354,468,357,409,413,531,303,532,302,530,304,472,533,353,301,467,358,529,408,414,254,596,595,305,416,415,417,475,360,474,361,476,359,414,418,537,307,473,536,308,362,477,538,358,306,535,309,539,472,413,419,258,601,602,305,363,420,421,419,479,364,480,363,478,365,422,418,541,311,481,542,310,362,477,540,312,366,543,309,539,423,417,482,606,313,261,262,605,424,423,425,483,368,484,367,482,369,485,422,426,366,546,314,545,315,547,481,313,544,370,316,486,365,421,427,265,548,610,611,264,428,427,429,487,488,371,372,486,489,370,373,426,430,318,550,549,551,317,319,485,490,369,374,548,552,316,320,425,431,268,615,614,432,431,433,492,375,491,376,493,374,490,430,434,377,554,322,555,321,553,494,323,556,373,320,489,378,429,435,271,552,620,619,272,436,435,437,496,379,495,380,497,378,434,438,559,325,494,558,326,381,498,560,324,377,557,327,561,433,439,493,624,323,275,274,625,440,439,441,500,383,501,382,499,384,438,442,563,329,502,564,328,381,498,562,385,330,565,327,561,503,443,437,278,629,628,331,380,445,446,444,505,388,506,387,504,389,507,386,447,443,569,333,568,334,570,332,503,567,390,335,508,385,571,442,448,282,634,635,331,449,448,450,510,391,509,392,511,390,508,393,447,451,573,337,574,336,572,338,512,575,389,507,335,394,571,446,452,639,339,285,286,453,452,454,514,395,513,396,515,394,451,455,512,578,340,577,397,341,516,579,393,339,576,342,511,450,456,398,289,580,643,644,288,648,649,716,582,717,787,718,647,583,650,715,518,788,719,786,789,860,581,519,646,584,790,859,580,520,651,714,457,861,785,720,862,652,651,653,721,586,585,722,720,587,650,654,792,522,723,584,521,793,719,791,523,588,794,520,790,655,649,724,865,583,461,460,866,657,656,658,726,591,590,727,725,592,589,728,655,659,526,798,797,527,724,525,799,796,528,593,588,729,654,660,465,871,870,800,524,661,660,662,730,594,595,731,729,593,732,596,663,659,530,802,801,531,529,803,728,800,592,733,597,532,528,804,664,658,875,468,469,665,664,666,598,734,735,599,597,733,736,663,667,806,534,600,533,805,807,535,596,732,737,532,804,808,601,662,668,472,879,536,880,670,669,671,603,740,739,604,602,741,738,668,672,811,538,539,812,605,601,810,537,742,540,813,737,667,673,809,885,476,477,884,606,674,673,675,607,744,743,606,608,745,672,676,742,542,816,815,605,543,541,609,746,817,814,544,741,540,677,671,480,889,604,890,818,678,679,677,748,611,610,747,749,612,680,676,609,546,820,746,819,545,750,547,821,613,818,544,608,822,681,675,745,548,894,484,483,683,684,682,753,615,616,754,752,614,617,685,681,825,550,551,755,751,826,824,549,552,613,618,827,823,686,680,488,899,756,750,900,687,688,686,757,619,620,758,756,618,685,689,621,554,829,759,830,555,755,553,828,617,831,556,622,827,684,690,760,552,903,491,492,691,692,690,623,761,762,624,622,760,693,689,763,558,833,834,625,557,559,621,759,832,835,556,764,560,694,688,495,908,626,907,831,695,694,696,627,765,766,626,628,764,767,693,697,838,562,561,837,625,629,839,563,763,560,836,768,692,698,840,912,499,498,913,624,700,699,701,632,771,770,631,633,772,769,698,702,843,566,630,567,844,842,565,634,773,768,568,845,841,629,697,703,503,918,564,917,704,705,703,775,636,635,774,776,637,773,634,706,702,570,847,848,569,571,846,777,849,638,772,633,568,572,845,707,701,922,507,506,708,709,707,779,639,640,778,780,638,641,777,710,706,574,851,852,573,781,575,850,853,572,637,642,776,711,705,510,926,927,849,576,713,714,712,784,644,645,783,785,643,715,711,857,578,782,646,579,856,786,858,577,642,855,580,859,716,710,781,932,647,514,515,931,936,937,1012,861,1013,1014,1091,862,935,938,1011,788,1092,1090,1015,1172,1093,789,860,863,934,1171,1094,790,859,1010,939,717,1173,1016,1089,1254,940,941,939,1017,865,1018,864,1016,866,942,938,1096,792,1019,1097,863,791,1015,1095,867,793,1098,790,1094,943,937,1020,1177,794,721,720,1178,945,946,944,1022,870,1023,869,1021,871,947,943,1024,868,1101,797,1102,796,1020,1100,872,1103,798,795,1025,867,948,942,725,1183,1182,726,1099,949,950,948,1026,874,1027,873,1025,875,1028,872,951,947,1106,800,1105,801,1107,799,1024,876,1104,802,1029,871,952,946,729,1187,1108,798,1186,953,954,952,1030,878,1031,877,1029,879,1032,876,955,951,1110,804,1109,805,1111,803,1028,880,1033,1108,875,806,1112,802,956,950,1191,733,732,957,958,956,1035,881,1034,882,1036,880,1033,883,959,955,1114,808,1115,807,1113,809,1037,879,1032,1116,884,806,1112,810,954,960,1195,736,1196,962,963,961,1040,886,1039,887,1041,885,1038,888,964,960,1119,813,1120,812,1118,814,1042,884,1121,811,1037,889,965,959,741,1201,1117,1200,815,966,965,967,1044,890,1043,891,1045,889,968,964,1042,1124,816,892,1123,817,1046,1125,888,815,1122,818,1041,893,963,969,1205,745,744,1126,1204,970,971,969,1048,894,1047,895,1049,893,972,968,1128,820,1046,1127,896,821,1050,1129,892,819,1126,822,1130,973,967,1045,1209,748,818,897,749,975,976,974,1053,899,1054,1052,898,900,977,973,1133,825,1055,1134,1051,1132,824,897,826,901,1135,1131,823,827,978,972,753,1215,1214,1056,1050,979,978,980,1057,903,1058,902,1056,904,977,981,1137,829,1059,1138,901,828,1055,1136,905,830,1139,827,1135,976,982,1060,1219,757,831,900,756,983,984,982,1061,907,1062,906,1060,908,985,981,1063,1141,833,905,1142,832,1059,1140,909,834,1143,831,1064,904,986,980,1223,760,761,1139,1224,987,986,988,1065,911,1066,910,1064,912,1067,909,985,989,1146,836,1145,837,1147,835,1063,913,1144,838,1068,908,984,990,764,1227,1148,1228,834,992,991,993,1070,916,1071,915,1069,917,1072,914,990,994,1151,841,1150,842,1152,840,1068,918,1073,1149,913,843,1153,839,989,995,1233,769,1232,996,997,995,1075,919,1074,920,1076,918,1073,921,994,998,1155,845,1156,844,1154,846,1077,917,1072,1157,922,843,1153,847,993,999,1237,772,773,1000,1001,999,1079,923,1078,924,1080,922,1077,925,998,1002,1159,849,1160,848,1158,850,1081,921,1161,847,1076,926,1003,997,776,1241,1157,851,1242,1004,1005,1003,1083,927,1082,928,1084,926,1006,1002,1081,929,1164,852,1163,853,1085,1165,925,1162,851,854,1080,930,1007,1001,780,1245,1246,779,1166,1009,1010,1008,1088,932,1087,933,1089,931,1011,1007,1169,857,1086,1168,934,858,1090,1170,930,856,1167,859,1171,1012,1006,1085,1251,855,784,785,1250,1255,1338,1256,1339,1173,1340,1423,1254,1174,1337,1257,1092,1424,1341,1422,1425,1509,1172,1093,1253,1175,1508,1426,1171,1094,1336,1258,1013,1510,1342,1421,1511,1259,1260,1258,1343,1177,1176,1344,1342,1178,1261,1257,1428,1096,1175,1345,1095,1429,1341,1427,1097,1179,1094,1430,1426,1098,1262,1256,1514,1017,1346,1174,1016,1263,1264,1262,1347,1181,1180,1348,1346,1182,1265,1261,1432,1100,1179,1099,1349,1433,1345,1431,1101,1183,1098,1434,1430,1266,1260,1178,1518,1350,1021,1020,1102,1268,1269,1267,1352,1186,1185,1353,1351,1187,1184,1270,1266,1437,1105,1104,1354,1438,1350,1436,1106,1188,1103,1439,1183,1271,1265,1355,1025,1524,1435,1523,1026,1272,1271,1273,1356,1190,1189,1357,1355,1191,1188,1270,1274,1358,1108,1441,1442,1109,1354,1440,1107,1443,1110,1192,1187,1359,1269,1275,1029,1528,1439,1527,1106,1276,1275,1277,1360,1193,1194,1361,1359,1192,1195,1274,1278,1362,1112,1446,1445,1113,1111,1358,1444,1447,1114,1191,1196,1363,1279,1273,1532,1033,1110,1032,1533,1280,1281,1279,1364,1197,1198,1365,1363,1196,1199,1366,1278,1282,1116,1450,1449,1117,1115,1451,1362,1448,1195,1118,1200,1367,1114,1277,1283,1536,1037,1036,1452,1284,1283,1285,1201,1368,1369,1202,1200,1367,1370,1203,1282,1286,1120,1454,1453,1119,1121,1455,1366,1199,1452,1371,1118,1122,1204,1287,1281,1040,1540,1456,1541,1289,1288,1290,1206,1373,1374,1207,1205,1372,1375,1287,1291,1459,1125,1208,1124,1458,1460,1126,1204,1371,1457,1123,1376,1461,1286,1292,1209,1127,1045,1546,1545,1293,1292,1294,1210,1377,1378,1211,1209,1376,1379,1291,1295,1463,1129,1128,1212,1462,1464,1208,1130,1127,1375,1380,1461,1465,1290,1296,1550,1049,1213,1048,1549,1297,1298,1296,1214,1382,1381,1215,1213,1383,1380,1295,1299,1467,1132,1133,1468,1466,1212,1216,1131,1134,1384,1379,1469,1465,1294,1300,1554,1053,1052,1553,1555,1301,1302,1300,1218,1386,1385,1217,1219,1387,1384,1303,1299,1471,1136,1137,1216,1472,1470,1220,1135,1138,1388,1383,1473,1469,1304,1298,1558,1056,1215,1057,1559,1305,1306,1304,1222,1390,1389,1221,1223,1391,1388,1307,1303,1475,1140,1220,1141,1476,1474,1139,1224,1392,1477,1142,1387,1473,1308,1302,1219,1138,1060,1562,1563,1310,1311,1309,1227,1395,1394,1226,1228,1396,1393,1225,1312,1308,1145,1480,1481,1146,1144,1479,1397,1229,1482,1392,1147,1143,1224,1313,1307,1065,1568,1478,1567,1314,1313,1315,1399,1231,1230,1398,1400,1232,1229,1397,1312,1316,1149,1484,1485,1148,1150,1483,1401,1486,1233,1147,1228,1396,1151,1311,1317,1572,1068,1069,1482,1318,1317,1319,1403,1234,1235,1402,1404,1233,1236,1316,1320,1401,1153,1488,1489,1152,1154,1405,1490,1487,1151,1232,1237,1400,1315,1321,1576,1072,1155,1073,1575,1322,1323,1321,1407,1238,1239,1406,1408,1237,1240,1324,1320,1405,1157,1493,1492,1156,1409,1494,1158,1491,1155,1236,1241,1404,1325,1319,1076,1580,1495,1581,1159,1326,1325,1327,1411,1242,1243,1410,1412,1241,1244,1328,1324,1497,1160,1161,1409,1496,1413,1498,1159,1240,1162,1495,1245,1329,1323,1408,1080,1584,1499,1585,1079,1331,1330,1332,1416,1247,1248,1415,1417,1246,1329,1333,1502,1165,1249,1166,1414,1501,1418,1503,1164,1245,1167,1500,1504,1328,1334,1250,1590,1413,1084,1085,1163,1335,1336,1334,1420,1251,1252,1419,1421,1250,1333,1337,1506,1169,1253,1418,1170,1505,1422,1507,1168,1249,1171,1504,1508,1167,1332,1338,1594,1088,1417,1254,1089,1687,1776,1688,1777,1598,1778,1867,1686,1599,1775,1689,1868,1510,1779,1866,1959,1869,1685,1600,1511,1597,1958,1870,1596,1512,1690,1774,1424,1960,1780,1865,2052,1691,1692,1690,1781,1602,1782,1601,1780,1603,1689,1693,1872,1514,1783,1873,1600,1513,1779,1871,1604,1515,1874,1512,1870,1516,1688,1694,1964,1428,1784,1427,1965,1696,1695,1697,1786,1607,1787,1606,1785,1608,1694,1698,1877,1519,1788,1605,1878,1518,1784,1876,1609,1520,1879,1517,1875,1521,1693,1699,1969,1433,1789,1432,1604,1700,1699,1701,1790,1611,1791,1610,1789,1612,1698,1702,1881,1523,1792,1609,1882,1522,1788,1613,1880,1524,1883,1521,1697,1703,1793,1879,1608,1973,1436,1525,1974,1704,1703,1705,1794,1615,1795,1614,1793,1616,1702,1706,1885,1527,1796,1613,1886,1526,1792,1617,1884,1528,1887,1525,1797,1612,1701,1707,1440,1978,1977,1883,1441,1708,1709,1707,1798,1619,1799,1618,1797,1620,1710,1706,1800,1617,1889,1531,1890,1530,1796,1621,1888,1532,1891,1529,1801,1616,1711,1705,1444,1982,1981,1887,1445,1713,1714,1712,1803,1624,1804,1623,1802,1625,1805,1622,1711,1715,1895,1535,1894,1536,1896,1534,1801,1626,1893,1537,1806,1621,1710,1716,1987,1449,1897,1986,1448,1717,1718,1716,1807,1628,1808,1627,1806,1629,1809,1626,1719,1715,1899,1539,1898,1540,1900,1538,1805,1630,1897,1541,1810,1625,1714,1720,1991,1453,1901,1452,1537,1721,1720,1722,1811,1632,1812,1631,1810,1633,1813,1630,1719,1723,1903,1543,1902,1544,1904,1542,1809,1634,1901,1545,1814,1629,1905,1718,1724,1995,1541,1456,1457,1726,1727,1725,1816,1637,1817,1636,1815,1638,1818,1635,1728,1724,1908,1548,1907,1549,1909,1547,1814,1639,1906,1819,1550,1634,1910,1546,1729,1723,1461,2000,2001,1730,1729,1731,1820,1641,1821,1640,1819,1642,1822,1639,1728,1732,1912,1552,1911,1553,1913,1551,1818,1643,1823,1638,1910,1554,1914,1550,1727,1733,1465,2004,2005,1734,1735,1733,1825,1644,1824,1645,1826,1643,1823,1646,1736,1732,1916,1556,1917,1555,1915,1557,1827,1642,1822,1647,1918,1554,1914,1558,1737,1731,1469,2009,2008,1738,1737,1739,1829,1648,1828,1649,1830,1647,1827,1650,1736,1740,1920,1560,1921,1559,1919,1561,1831,1646,1922,1826,1558,1651,1918,1562,1735,1741,1473,2013,2012,1743,1744,1742,1834,1653,1833,1654,1835,1652,1832,1655,1745,1741,1925,1565,1926,1564,1924,1566,1836,1651,1927,1563,1831,1656,1923,1746,1740,2018,1567,1478,1477,1747,1748,1746,1838,1657,1837,1658,1839,1656,1836,1659,1749,1745,1929,1569,1930,1568,1928,1570,1840,1655,1931,1567,1835,1660,1750,1744,2022,1481,1927,1482,1571,1751,1750,1752,1842,1661,1841,1662,1843,1660,1840,1663,1753,1749,1933,1573,1934,1572,1932,1574,1844,1659,1935,1571,1839,1664,1748,1754,2026,1485,1931,2027,1486,1756,1755,1757,1847,1666,1846,1667,1848,1665,1754,1758,1845,1668,1939,1577,1938,1578,1849,1664,1940,1576,1937,1579,1844,1669,1753,1759,1490,2031,2032,1941,1489,1760,1759,1761,1851,1670,1850,1671,1852,1669,1758,1762,1943,1581,1849,1672,1942,1582,1853,1668,1944,1580,1941,1583,1848,1673,1757,1763,1494,2035,2036,1945,1493,1764,1763,1765,1855,1674,1854,1675,1856,1673,1766,1762,1947,1585,1853,1676,1946,1586,1857,1672,1948,1584,1945,1587,1767,1761,1852,1949,1677,2040,1498,1583,2039,1768,1769,1767,1859,1678,1858,1679,1860,1677,1770,1766,1951,1589,1857,1680,1950,1590,1861,1952,1676,1588,1949,1591,1953,1587,1765,1771,2044,1501,1856,1502,1681,1773,1774,1772,1864,1683,1863,1684,1865,1682,1771,1775,1956,1594,1862,1955,1685,1595,1866,1957,1681,1593,1954,1596,1958,1592,1770,1776,2049,1506,1861,1507,2048,2053,2146,2054,2147,1960,2240,2148,2052,1961,2145,2055,1868,2241,2239,2149,2242,2335,2051,1962,1959,1869,2243,2334,1958,1870,2144,2056,1777,2336,2238,2150,2050,2057,2056,2058,2151,1964,1963,2152,2150,1965,2059,2055,2245,1872,1962,1871,2246,2149,2153,2244,1966,1873,1870,2247,2243,1874,2054,2060,2340,1781,1961,1780,2341,2062,2061,2063,2156,1969,1968,2155,2157,1970,2060,2064,2250,1877,1967,1876,2251,2154,2158,2249,1971,1878,1875,2252,2248,1879,2065,2059,2345,1786,1966,1785,2346,2066,2065,2067,2160,1973,1972,2159,2161,1974,2064,2068,2254,1881,1971,1880,2255,2158,2162,2253,1975,1882,1879,2256,2252,2063,2069,2349,1970,1790,1883,1789,2350,2070,2071,2069,2164,1977,1976,2165,2163,1978,2072,2068,2258,1885,1975,1884,2259,2166,2162,2257,1979,1886,1883,2260,2256,2067,2073,1974,2353,1793,1794,2354,1887,2074,2073,2075,2168,1981,1980,2167,2169,1982,2072,2076,2262,1979,1889,1888,2263,2166,2170,2261,1983,1890,1887,2264,1978,2260,2071,2077,1797,2357,2358,1798,2165,2079,2080,2078,2173,1986,1985,2174,2172,1987,2081,2077,1984,2267,1893,1894,2268,2175,2171,2266,1892,1988,1895,2269,1983,2082,2076,1802,2265,2363,2362,1803,2176,2083,2082,2084,2177,1990,1989,2176,2178,1991,1988,2081,2085,2271,1897,1898,2272,2179,2175,2270,1896,1992,1899,2273,1987,2080,2086,1806,2367,2269,2366,1895,2174,2087,2086,2088,2181,1994,1993,2180,2182,1995,1992,2089,2085,1901,2275,2276,1902,2183,2179,1900,2274,1996,2277,1903,1991,2090,2084,1810,2371,1899,2273,2370,1809,2091,2092,2090,2185,1998,1997,2186,2184,1999,1996,2089,2093,1905,2279,2280,1906,2183,2187,1904,2278,2281,2000,1907,1995,1903,2088,2094,2375,1814,2374,1813,2277,2096,2097,2095,2190,2003,2002,2191,2189,2004,2001,2098,2094,1910,2284,2285,1911,2192,2188,1909,2283,2286,2005,2000,1912,1908,2093,2099,2380,1819,1818,2379,2282,2100,2101,2099,2194,2007,2006,2195,2193,2008,2005,2102,2098,1914,2289,2288,2196,2192,1915,1913,2290,2287,2009,2004,1916,1912,2103,2097,2384,1823,1822,2197,2191,2104,2105,2103,2198,2010,2011,2199,2197,2009,2012,2106,2102,1918,2293,2292,1917,2200,2196,1919,2294,2291,2008,2013,1916,1920,2107,2101,2388,1826,1827,2389,2295,2109,2108,2110,2203,2015,2016,2202,2204,2014,2017,2111,2107,1923,2298,2297,1922,2205,2201,1924,2299,2296,2013,1921,2018,1925,2112,2106,2393,1831,2394,1832,2300,2113,2112,2114,2207,2019,2020,2206,2208,2018,2021,2111,2115,1927,2302,2301,1926,2205,2209,1928,2303,2017,2300,1925,2022,2110,2116,1835,2397,1929,2304,2398,1836,2117,2118,2116,2211,2023,2024,2212,2210,2022,2025,2119,2115,2306,1931,1930,2305,2213,2209,2307,1932,2021,1929,2304,2026,2120,2114,1839,2401,2308,2402,1933,2214,2121,2122,2120,2215,2027,2028,2216,2214,2026,2123,2119,2029,2310,1935,1934,2309,2217,2213,2311,1936,2025,1933,2308,2030,2124,2118,1843,2312,2405,2406,1842,2218,2126,2125,2127,2220,2032,2033,2219,2221,2031,2124,2128,2315,2034,1939,1940,2314,2218,2222,2316,2030,1938,1941,2313,2035,2317,2123,2129,1848,2411,2410,1847,2217,2130,2131,2129,2224,2036,2037,2225,2223,2035,2132,2128,2319,1943,2038,1944,2318,2226,2222,2320,2034,1942,1945,2317,2321,2133,2127,2039,2415,1852,1851,2414,1941,2134,2133,2135,2228,2040,2041,2227,2229,2039,2132,2136,2323,1947,2042,1948,2322,2226,2230,2324,2038,1946,1949,2321,2325,2131,2137,2419,2043,1855,1945,1856,2418,2138,2139,2137,2232,2044,2045,2233,2231,2043,2140,2136,2327,1951,2046,1952,2326,2234,2230,2328,2042,1950,1953,2325,2329,1949,2135,2141,2423,1859,2047,1860,2422,2143,2142,2144,2237,2049,2050,2236,2238,2048,2141,2145,2332,1956,2051,1957,2331,2235,2239,2333,2047,1955,1958,2330,2334,1954,2146,2140,2428,1864,2052,1865,2427,2432,2527,2433,2336,2528,2624,2529,2431,2337,2434,2526,2241,2625,2623,2530,2338,2430,2721,2626,2335,2242,2720,2627,2243,2334,2525,2435,2147,2722,2622,2531,2429,2436,2437,2435,2340,2532,2533,2339,2341,2531,2434,2438,2245,2629,2534,2630,2244,2338,2342,2628,2246,2530,2631,2243,2627,2247,2433,2439,2726,2151,2535,2727,2150,2440,2439,2441,2344,2536,2537,2343,2345,2535,2442,2438,2633,2249,2538,2634,2248,2342,2346,2632,2250,2534,2635,2247,2631,2251,2437,2443,2730,2155,2539,2731,2154,2445,2444,2446,2349,2541,2542,2348,2350,2540,2443,2447,2638,2254,2543,2639,2253,2347,2351,2637,2255,2539,2640,2252,2636,2256,2442,2448,2544,2735,2160,2736,2159,2449,2450,2448,2353,2545,2546,2352,2354,2544,2447,2451,2642,2258,2547,2643,2257,2351,2355,2641,2259,2543,2644,2256,2640,2260,2548,2446,2452,2739,2164,2740,2163,2453,2454,2452,2357,2549,2550,2358,2356,2548,2455,2451,2646,2262,2551,2647,2261,2359,2355,2645,2263,2547,2648,2260,2552,2644,2264,2456,2450,2743,2168,2744,2167,2457,2458,2456,2361,2553,2554,2362,2360,2552,2555,2455,2459,2650,2266,2651,2265,2359,2363,2649,2267,2551,2652,2264,2556,2454,2460,2648,2268,2748,2171,2747,2172,2461,2460,2462,2365,2557,2558,2364,2366,2556,2559,2463,2459,2654,2270,2655,2269,2367,2363,2653,2271,2555,2656,2268,2560,2464,2458,2752,2175,2652,2272,2751,2176,2465,2466,2464,2369,2561,2562,2370,2368,2560,2563,2467,2463,2658,2274,2659,2273,2371,2367,2657,2275,2559,2660,2272,2564,2468,2462,2756,2179,2656,2755,2180,2276,2470,2469,2471,2374,2566,2567,2373,2375,2565,2568,2468,2472,2663,2279,2664,2278,2372,2376,2662,2280,2665,2277,2564,2569,2467,2473,2761,2184,2760,2185,2661,2281,2474,2475,2473,2378,2570,2571,2379,2377,2569,2572,2476,2472,2667,2283,2668,2282,2380,2376,2666,2284,2669,2281,2568,2573,2477,2471,2765,2188,2764,2189,2665,2381,2478,2479,2477,2382,2574,2575,2383,2381,2573,2576,2476,2480,2671,2287,2672,2286,2380,2384,2670,2288,2673,2285,2572,2577,2475,2481,2769,2192,2768,2379,2385,2193,2482,2481,2483,2386,2579,2578,2385,2387,2580,2577,2480,2484,2676,2290,2675,2291,2388,2384,2677,2289,2674,2292,2581,2576,2485,2479,2773,2196,2774,2383,2389,2195,2486,2485,2487,2390,2583,2582,2389,2391,2584,2581,2484,2488,2680,2294,2679,2295,2388,2392,2681,2293,2678,2296,2585,2580,2483,2489,2777,2200,2778,2199,2682,2387,2490,2491,2489,2394,2587,2586,2395,2393,2588,2585,2492,2488,2684,2298,2683,2299,2396,2392,2685,2297,2682,2300,2589,2584,2493,2487,2781,2204,2782,2203,2686,2296,2495,2496,2494,2399,2592,2591,2400,2398,2593,2590,2497,2493,2689,2303,2688,2304,2401,2397,2690,2302,2594,2687,2305,2589,2492,2498,2786,2209,2691,2787,2208,2301,2499,2498,2500,2403,2596,2595,2402,2404,2597,2594,2501,2497,2693,2307,2692,2308,2405,2401,2694,2306,2598,2691,2309,2593,2502,2496,2790,2213,2695,2305,2791,2212,2503,2504,2502,2407,2600,2599,2408,2406,2601,2598,2501,2505,2697,2311,2696,2312,2405,2409,2698,2310,2602,2695,2313,2597,2506,2500,2699,2309,2794,2217,2795,2216,2507,2506,2508,2411,2604,2603,2410,2412,2605,2505,2509,2701,2315,2602,2700,2316,2409,2413,2702,2314,2606,2699,2317,2601,2703,2313,2510,2504,2799,2220,2798,2221,2511,2512,2510,2415,2608,2607,2416,2414,2609,2509,2513,2705,2319,2606,2704,2320,2413,2417,2706,2318,2610,2703,2321,2707,2317,2605,2514,2508,2803,2224,2802,2225,2515,2514,2516,2419,2612,2611,2418,2420,2613,2513,2517,2709,2323,2610,2708,2324,2417,2421,2710,2322,2614,2707,2325,2711,2321,2512,2518,2609,2807,2228,2806,2229,2520,2521,2519,2424,2617,2616,2425,2423,2618,2522,2518,2714,2328,2615,2713,2329,2426,2422,2715,2327,2619,2712,2330,2716,2326,2523,2517,2812,2233,2614,2811,2234,2524,2523,2525,2428,2621,2620,2427,2429,2622,2526,2522,2332,2718,2619,2717,2333,2430,2426,2719,2331,2623,2716,2334,2720,2330,2521,2527,2816,2237,2618,2815,2238,2820,2917,2821,2722,2918,2819,2723,3015,2919,2916,2822,2625,3016,2818,2724,3014,2920,3113,3017,2721,2626,3112,3018,2720,2627,2915,2823,3114,2528,2817,2725,3013,2824,2825,2823,2726,2922,2727,2725,2923,2921,2826,2822,3020,2629,2628,2728,2724,2924,2920,3019,3021,2630,2627,3022,3018,2631,2827,2821,3118,2532,2729,2723,3119,2829,2830,2828,2731,2927,2730,2732,2928,2926,2827,2831,3025,2634,2633,2729,2733,2925,2929,3026,3024,2635,2632,3027,3023,2636,2826,2832,3123,2537,3124,2536,2728,2833,2832,2834,2735,2931,2734,2736,2930,2932,2831,2835,3029,2638,2637,2733,2737,2929,2933,3028,3030,2639,2636,3027,3031,2640,2830,2836,3127,2541,3128,2540,2732,2837,2836,2838,2739,2935,2740,2738,2934,2936,2835,2839,3033,2642,2641,2737,2741,2933,2937,3032,3034,2643,2640,3031,3035,2644,2834,2840,3131,2545,3132,2544,2736,2841,2842,2840,2743,2939,2742,2744,2938,2940,2843,2839,3037,2646,2645,2745,2741,2937,2941,3038,3036,2647,2644,3039,3035,2838,2844,2648,3135,2549,3136,2548,2746,2846,2847,2845,2748,2944,2749,2747,2945,2943,2848,2844,3042,2651,2650,2750,2746,2946,2942,3043,3041,2652,2649,3044,3040,2849,2843,3140,2554,2653,3141,2553,2751,2850,2849,2851,2752,2948,2753,2751,2947,2949,2848,2852,3046,2655,2654,2750,2754,2950,2946,3045,3047,2656,2653,3044,3048,2847,2853,3144,2558,2657,3145,2557,2749,2854,2853,2855,2756,2952,2755,2757,2951,2953,2852,2856,3050,2659,2658,2754,2758,2950,2954,3049,3051,2660,2657,3048,3052,2851,2857,3148,2562,3149,2561,2661,2753,2858,2857,2859,2760,2956,2759,2761,2955,2957,2856,2860,3054,2663,2662,2758,2762,2954,2958,3055,3053,2664,2661,3052,3056,2855,2861,3152,2566,3153,2565,2665,2757,2863,2864,2862,2765,2961,2766,2764,2962,2960,2865,2861,3059,2668,2667,2767,2763,2963,2959,3058,3060,2669,2666,3061,3057,2860,2866,3157,2571,3158,2570,2762,2768,2867,2866,2868,2769,2965,2768,2770,2966,2964,2869,2865,3063,2672,2671,2771,2767,2967,2963,3062,3064,2673,2670,3065,3061,2870,2864,3161,2575,3162,2574,2772,2766,2871,2872,2870,2773,2969,2774,2772,2968,2970,2873,2869,3067,2675,2676,2775,2771,2971,2967,3068,3066,2674,2677,3069,3065,2874,2868,3166,2578,3165,2579,2776,2770,2875,2876,2874,2777,2973,2778,2776,2972,2974,2873,2877,3071,2679,2680,2775,2779,2971,2975,3070,3072,2678,2681,3069,3073,2872,2878,3170,2582,3169,2583,2774,2780,2880,2881,2879,2782,2978,2781,2783,2977,2979,2878,2882,3076,2684,2685,2780,2784,2976,2980,3077,3075,2683,2686,3074,3078,2877,2883,3175,2587,3174,2588,2682,2785,2884,2885,2883,2786,2982,2787,2785,2983,2981,2886,2882,3080,2688,2689,2788,2784,2984,2980,3081,3079,2687,2690,3082,3078,2887,2881,3179,2591,3178,2592,2686,2789,2888,2887,2889,2790,2986,2791,2789,2985,2987,2886,2890,3084,2692,2693,2788,2792,2984,2988,3083,3085,2691,2694,3082,3086,2885,2891,3183,2595,2690,3182,2596,2787,2892,2893,2891,2794,2990,2793,2795,2991,2989,2894,2890,3088,2696,2697,2796,2792,2992,2988,3089,3087,2695,2698,3090,3086,2895,2889,3187,2599,2694,3186,2600,2797,2897,2896,2898,2799,2995,2798,2800,2994,2996,2895,2899,3093,2701,2702,2797,2801,2993,2997,3092,3094,2700,2703,3091,3095,2894,2900,2699,3192,2604,3191,2605,2796,2901,2900,2902,2803,2999,2802,2804,2998,3000,2903,2899,3097,2705,2706,2805,2801,3001,2997,3096,3098,2704,2707,3099,3095,2703,2904,2898,3196,2608,3195,2609,2806,2905,2904,2906,3003,2807,2806,2808,3002,3004,2903,2907,3101,2709,2710,2805,2809,3005,3001,3102,3100,2708,2711,3103,3099,2707,2908,2902,3200,2612,3199,2613,2810,2909,2910,2908,2811,3007,2812,2810,3008,3006,2907,2911,3105,2713,2714,2809,2813,3005,3009,3106,3104,2712,2715,3103,3107,2711,2906,2912,3204,2616,3203,2617,2808,2914,2915,2913,3012,2816,2817,2815,3013,3011,2916,2912,3110,2718,2719,2818,2814,3014,3010,3109,3111,2717,2720,3112,3108,2716,2917,2911,3209,2621,2819,2813,3208,3312,3410,3313,3411,3213,3214,3311,3508,3412,3409,3314,3509,3114,3310,3215,3212,3115,3606,3510,3507,3413,3211,3116,3605,3511,3408,3315,3607,3016,3309,3216,3608,3316,3317,3315,3217,3415,3414,3218,3216,3416,3318,3314,3118,3513,3413,3512,3219,3215,3117,3119,3514,3417,3511,3120,3116,3515,3319,3313,3611,3020,3412,3214,3220,3321,3320,3322,3222,3420,3419,3221,3223,3421,3323,3319,3123,3518,3418,3517,3224,3220,3124,3122,3519,3422,3516,3125,3121,3520,3318,3324,3616,3025,3417,3615,3024,3325,3324,3326,3226,3424,3423,3227,3225,3425,3327,3323,3127,3522,3422,3521,3228,3224,3128,3126,3523,3426,3520,3129,3125,3524,3328,3322,3620,3029,3421,3619,3028,3329,3328,3330,3230,3428,3427,3229,3231,3429,3331,3327,3131,3526,3426,3525,3232,3228,3130,3132,3527,3430,3524,3133,3129,3528,3326,3332,3425,3624,3033,3623,3032,3334,3333,3335,3235,3433,3432,3234,3236,3434,3332,3336,3136,3531,3431,3530,3233,3237,3135,3137,3532,3435,3529,3134,3138,3430,3331,3337,3533,3629,3038,3628,3037,3338,3339,3337,3239,3437,3436,3240,3238,3438,3340,3336,3140,3435,3535,3534,3241,3237,3141,3139,3536,3439,3533,3142,3138,3434,3341,3335,3633,3042,3537,3632,3041,3342,3341,3343,3243,3441,3440,3242,3244,3442,3439,3340,3344,3144,3539,3538,3241,3245,3143,3145,3540,3443,3537,3142,3146,3438,3339,3345,3637,3046,3541,3636,3045,3346,3347,3345,3247,3445,3444,3248,3246,3446,3443,3348,3344,3148,3543,3542,3249,3245,3149,3147,3544,3447,3541,3150,3146,3442,3349,3343,3641,3050,3640,3049,3545,3351,3350,3352,3252,3450,3449,3251,3253,3451,3448,3349,3353,3153,3548,3547,3250,3254,3152,3154,3549,3546,3452,3447,3151,3155,3348,3354,3646,3055,3645,3054,3550,3355,3356,3354,3256,3454,3453,3257,3255,3455,3452,3357,3353,3157,3552,3551,3258,3254,3158,3156,3553,3550,3456,3451,3159,3155,3358,3352,3650,3059,3649,3058,3259,3359,3360,3358,3260,3458,3457,3259,3261,3459,3456,3357,3361,3161,3556,3555,3258,3262,3162,3160,3557,3554,3460,3455,3159,3163,3356,3362,3654,3063,3653,3062,3257,3364,3365,3363,3265,3462,3463,3266,3264,3461,3464,3366,3362,3166,3560,3561,3267,3263,3167,3165,3559,3562,3460,3465,3168,3164,3367,3361,3658,3067,3659,3068,3268,3368,3369,3367,3269,3466,3467,3270,3268,3465,3468,3370,3366,3170,3564,3565,3271,3267,3171,3169,3563,3566,3464,3469,3172,3168,3371,3365,3662,3071,3663,3072,3272,3372,3371,3373,3273,3470,3471,3274,3272,3469,3472,3374,3370,3174,3568,3569,3275,3271,3175,3173,3567,3570,3468,3473,3176,3172,3375,3369,3666,3075,3667,3076,3566,3377,3376,3378,3278,3475,3476,3277,3279,3474,3477,3375,3379,3179,3573,3574,3276,3280,3178,3180,3572,3473,3575,3177,3181,3478,3374,3380,3671,3080,3672,3081,3571,3381,3382,3380,3282,3479,3480,3283,3281,3478,3481,3383,3379,3183,3577,3578,3280,3284,3184,3182,3576,3477,3579,3185,3181,3482,3384,3378,3675,3084,3575,3676,3085,3385,3384,3386,3286,3483,3484,3285,3287,3482,3383,3387,3187,3485,3581,3582,3284,3288,3186,3188,3580,3481,3583,3185,3189,3486,3382,3388,3679,3088,3579,3680,3089,3389,3390,3388,3290,3487,3488,3291,3289,3486,3391,3387,3191,3585,3489,3586,3292,3288,3192,3190,3584,3485,3587,3193,3189,3490,3386,3392,3583,3683,3092,3684,3093,3394,3395,3393,3295,3492,3493,3296,3294,3491,3392,3396,3196,3590,3494,3591,3297,3293,3197,3195,3589,3490,3592,3198,3194,3588,3397,3391,3495,3688,3097,3689,3098,3398,3397,3399,3299,3496,3497,3298,3300,3495,3400,3396,3200,3594,3498,3595,3301,3297,3201,3199,3593,3494,3596,3202,3198,3592,3401,3395,3692,3101,3499,3693,3102,3402,3401,3403,3303,3500,3501,3302,3304,3499,3400,3404,3204,3598,3502,3599,3301,3305,3203,3205,3597,3498,3600,3202,3206,3596,3399,3405,3696,3105,3503,3697,3106,3407,3408,3406,3308,3505,3506,3309,3307,3504,3409,3405,3209,3603,3507,3604,3310,3306,3210,3208,3602,3503,3605,3211,3207,3601,3410,3404,3701,3110,3508,3311,3305,3705,3802,3706,3803,3607,3704,3608,3899,3804,3801,3707,3900,3509,3703,3609,3606,3510,3898,3805,3995,3901,3605,3511,3994,3902,3800,3708,3996,3411,3702,3610,3897,3709,3708,3710,3611,3807,3806,3610,3612,3808,3711,3707,3513,3904,3805,3903,3609,3613,3512,3514,3809,3905,3902,3515,3511,3906,3706,3712,3415,4000,3804,3999,3608,3714,3713,3715,3616,3812,3811,3615,3617,3813,3712,3716,3518,3909,3810,3908,3614,3618,3519,3517,3814,3910,3907,3516,3520,3911,3717,3711,3420,4005,3809,4004,3619,3718,3717,3719,3620,3816,3815,3619,3621,3817,3716,3720,3522,3913,3814,3912,3618,3622,3523,3521,3818,3914,3911,3524,3520,3715,3721,3424,4009,3915,3813,4008,3617,3722,3721,3723,3624,3820,3819,3623,3625,3821,3720,3724,3526,3917,3818,3916,3622,3626,3525,3527,3822,3918,3915,3524,3528,3719,3725,3817,3428,4013,4012,3919,3621,3726,3727,3725,3628,3824,3823,3629,3627,3825,3728,3724,3530,3822,3921,3920,3630,3626,3531,3529,3826,3922,3919,3532,3528,3821,3723,3729,3432,4017,4016,3631,3625,3731,3732,3730,3633,3829,3828,3634,3632,3830,3733,3729,3535,3827,3925,3926,3635,3631,3536,3534,3831,3924,3927,3537,3533,3826,3734,3728,3437,4021,4022,3636,3630,3735,3734,3736,3637,3833,3832,3636,3638,3834,3831,3733,3737,3539,3929,3930,3635,3639,3540,3538,3928,3835,3931,3541,3537,3830,3732,3738,3441,4025,4026,3927,3634,3739,3738,3740,3641,3837,3836,3640,3642,3838,3835,3737,3741,3543,3933,3934,3639,3643,3544,3542,3932,3839,3935,3541,3545,3834,3736,3742,3445,4029,3931,4030,3638,3743,3742,3744,3645,3841,3840,3644,3646,3842,3839,3741,3745,3547,3937,3938,3643,3647,3546,3548,3936,3843,3939,3838,3545,3549,3740,3746,3449,3935,4033,4034,3642,3748,3747,3749,3650,3846,3845,3649,3651,3847,3844,3750,3746,3552,3942,3943,3652,3648,3553,3551,3941,3848,3843,3944,3554,3550,3940,3745,3751,3454,4038,4039,3647,3752,3751,3753,3654,3850,3849,3653,3655,3851,3848,3754,3750,3556,3946,3947,3656,3652,3555,3557,3945,3852,3847,3948,3554,3558,3944,3755,3749,3458,4042,3657,3651,3756,3757,3755,3658,3853,3854,3659,3657,3852,3855,3758,3754,3560,3950,3949,3660,3656,3561,3559,3951,3851,3856,3948,3562,3558,3952,3759,3753,3462,4046,3661,3655,3760,3761,3759,3662,3857,3858,3663,3661,3856,3859,3758,3762,3564,3954,3953,3660,3664,3565,3563,3955,3855,3860,3952,3562,3566,3956,3757,3763,3466,4050,4049,3659,3765,3764,3766,3667,3862,3863,3666,3668,3861,3864,3763,3767,3569,3959,3958,3665,3669,3568,3570,3960,3860,3957,3865,3567,3571,3762,3768,3471,3961,4055,4054,3664,3769,3770,3768,3671,3866,3867,3672,3670,3865,3868,3771,3767,3573,3963,3962,3673,3669,3574,3572,3964,3864,3961,3571,3575,3869,3772,3766,3475,4059,3965,4058,3674,3773,3772,3774,3675,3870,3871,3676,3674,3869,3872,3771,3775,3577,3967,3966,3673,3677,3578,3576,3968,3868,3965,3575,3579,3873,3770,3776,3479,4063,4062,3969,3672,3777,3776,3778,3679,3874,3875,3680,3678,3873,3779,3775,3581,3876,3971,3970,3681,3677,3582,3580,3872,3972,3969,3579,3583,3877,3780,3774,3483,4067,4066,3682,3676,3782,3781,3783,3684,3879,3880,3683,3685,3878,3780,3784,3586,3881,3975,3976,3682,3686,3585,3587,3877,3974,3977,3588,3584,3882,3779,3785,3488,4071,4072,3681,3687,3786,3785,3787,3688,3883,3884,3687,3689,3882,3788,3784,3590,3979,3885,3980,3690,3686,3591,3589,3881,3978,3981,3592,3588,3789,3783,3886,3492,4075,4076,3977,3691,3790,3791,3789,3692,3887,3888,3691,3693,3886,3792,3788,3594,3983,3889,3984,3694,3690,3595,3593,3885,3982,3985,3596,3592,3793,3787,3496,4079,3981,3890,4080,3695,3794,3793,3795,3696,3891,3892,3695,3697,3890,3792,3796,3598,3987,3893,3988,3694,3698,3599,3597,3889,3986,3989,3596,3600,3985,3791,3797,3500,4083,3894,4084,3693,3799,3798,3800,3701,3896,3897,3702,3700,3895,3801,3797,3603,3992,3898,3993,3703,3699,3604,3602,3894,3991,3994,3605,3601,3990,3796,3802,3505,4088,3899,4089,3704,4092,-1,4093,4186,3996,-1,-1,4091,3997,-1,-1,-1,-1,4094,4185,3900,-1,3998,4090,3995,3901,-1,-1,-1,-1,-1,-1,3902,3994,-1,4095,4184,4096,4095,4097,4000,-1,-1,4001,3999,-1,-1,-1,-1,4094,4098,3904,4002,3905,-1,3998,3903,-1,-1,-1,-1,-1,3906,-1,3902,-1,-1,4093,4099,4100,-1,4099,4101,4004,-1,-1,4005,4003,-1,-1,4098,4102,3908,-1,-1,-1,4006,3909,3907,4002,-1,-1,-1,-1,3910,-1,-1,-1,3906,4097,4103,4104,4103,4105,-1,4008,-1,4009,4007,-1,-1,-1,-1,4106,4102,3912,4010,3913,-1,-1,3911,-1,4006,-1,-1,3914,-1,-1,3910,-1,-1,4107,4101,4109,-1,4108,4110,4013,-1,4014,-1,4012,-1,-1,-1,4107,4111,3917,4015,-1,3918,-1,3916,-1,4011,-1,3919,-1,-1,-1,-1,3915,4016,-1,4106,4113,-1,4114,4112,4017,-1,4018,-1,4016,-1,-1,-1,4115,4111,3921,4019,-1,-1,3922,3920,4015,-1,-1,-1,3923,-1,-1,-1,-1,4020,3919,4116,4117,4116,4118,-1,4021,-1,4022,-1,4020,-1,-1,-1,4023,4115,4119,3925,3926,-1,-1,-1,3924,4019,-1,3927,-1,-1,-1,4024,-1,-1,4114,4120,4121,-1,4122,4120,4025,4026,-1,-1,4024,-1,-1,4027,4119,4123,-1,3929,-1,-1,3930,3928,-1,4023,-1,3931,-1,-1,-1,-1,4028,-1,4118,4124,4125,4124,4126,-1,-1,4029,4030,-1,-1,4028,-1,-1,4031,4123,4127,3933,3934,-1,-1,-1,-1,3932,4027,3935,-1,-1,4032,-1,-1,-1,4122,4128,4129,-1,4130,4128,4033,4034,-1,-1,4032,-1,4035,-1,-1,4127,4131,-1,-1,3937,3938,3936,-1,-1,3939,4031,-1,4036,-1,-1,-1,-1,4126,4132,4133,4132,4134,-1,-1,4037,4038,-1,-1,4036,4039,-1,-1,4135,4131,3941,3942,-1,-1,-1,-1,3940,3943,4035,-1,4040,-1,-1,-1,-1,4136,4130,4137,-1,4136,4138,4041,4042,-1,-1,4040,4043,-1,-1,4135,4139,-1,-1,3945,3946,-1,3944,-1,3947,-1,4039,4044,-1,-1,-1,-1,-1,4134,4140,4142,-1,4141,4143,4047,4046,-1,-1,4048,-1,4045,-1,-1,4140,4144,3951,3950,-1,-1,-1,3952,3949,-1,4049,-1,4044,-1,-1,-1,-1,4139,4145,4146,-1,4147,4145,4051,-1,4050,-1,4052,-1,4049,-1,-1,4148,4144,3955,3954,-1,-1,-1,3956,-1,3953,4053,-1,-1,4048,-1,-1,-1,4143,4149,4150,-1,4151,4149,4055,4054,-1,-1,4056,-1,-1,4053,-1,4152,4148,3959,3958,-1,-1,3960,-1,3957,4057,-1,-1,-1,4052,-1,-1,-1,4153,4147,4154,4155,4153,-1,4059,-1,4058,-1,4060,-1,-1,4057,-1,4156,4152,3963,3962,-1,-1,-1,3964,-1,4061,3961,-1,-1,-1,4056,-1,-1,4157,4151,4158,-1,4157,4159,4063,4062,-1,-1,4064,-1,-1,4061,4156,4160,-1,3967,-1,-1,3966,3968,-1,4065,-1,3965,-1,-1,-1,-1,4060,-1,4155,4161,4162,4163,4161,-1,4067,-1,4066,-1,4068,-1,-1,-1,4065,4164,4160,3971,3970,-1,-1,-1,3972,-1,4069,3969,-1,-1,-1,-1,4064,-1,4165,4159,4166,-1,4165,4167,4071,4070,-1,-1,4072,-1,-1,-1,4164,4168,3975,4069,-1,-1,3974,3976,4073,-1,-1,3973,-1,-1,-1,-1,-1,4068,3977,4163,4170,4169,4171,4075,-1,-1,4074,4076,-1,-1,-1,-1,4168,4172,3979,4073,3978,-1,-1,3980,-1,4077,-1,3977,-1,-1,-1,-1,3981,4072,-1,4167,4175,-1,4176,4174,4080,-1,4079,-1,4081,-1,-1,-1,4177,4173,3984,4078,-1,-1,3983,3985,4082,-1,-1,-1,-1,3982,-1,-1,3986,-1,4178,4172,4179,-1,4178,4180,4084,-1,4083,-1,4085,-1,-1,-1,4177,4181,3988,-1,4082,-1,3987,3989,4086,-1,-1,-1,-1,3986,-1,3990,-1,-1,4182,4176,4183,-1,4184,4182,4088,-1,4087,4089,-1,-1,-1,-1,4185,4181,3992,-1,4086,3991,-1,4090,3993,-1,-1,-1,-1,-1,3990,3994,-1,-1,4186,4180],"visual":[0,7,4,2,1,3,6,5,9,10,16,15,8,18,19,17,11,12,13,14,31,20,21,22,23,24,25,26,27,28,29,30,38,61,60,39,20,88,62,21,37,89,59,40,63,87,120,90,8,22,36,19,9,91,119,64,86,41,58,1,121,157,122,118,42,66,41,65,43,23,67,24,22,64,40,94,95,10,44,93,68,96,25,21,9,11,63,39,92,2,127,97,45,128,69,126,46,45,70,71,26,47,69,27,25,44,72,100,99,12,101,68,48,98,28,24,13,11,73,43,102,3,133,97,134,67,4,49,50,49,75,29,74,76,48,51,30,28,105,73,77,106,104,14,31,27,52,47,15,13,107,103,78,72,139,140,4,5,108,102,53,54,80,79,32,52,81,33,31,55,78,110,111,16,109,82,51,112,34,30,15,17,77,56,108,6,146,113,145,83,5,50,57,84,58,85,56,35,83,36,34,86,59,116,115,18,55,117,82,114,33,37,17,19,87,60,118,7,152,113,54,151,81,153,158,199,198,159,200,243,121,244,157,122,245,291,201,242,197,160,89,156,123,290,246,120,90,292,293,343,241,202,196,161,91,119,162,204,203,163,161,125,202,205,124,249,248,126,164,250,160,123,92,247,93,201,206,91,251,127,297,298,165,296,94,122,159,64,166,208,167,209,207,165,128,129,254,253,168,127,206,210,255,130,164,252,95,96,94,302,126,169,303,256,97,205,211,131,251,301,170,212,213,171,169,132,211,214,258,133,259,172,131,257,260,168,99,134,98,215,210,130,173,100,308,307,256,97,261,309,306,69,217,174,175,218,216,136,173,135,263,176,264,137,262,219,215,134,102,265,172,101,177,138,103,261,313,312,220,214,314,100,133,72,178,179,222,221,139,140,177,180,220,223,268,267,269,141,138,105,224,219,176,181,266,270,104,106,318,137,142,319,317,103,107,75,226,183,182,227,225,143,184,144,273,181,272,142,274,228,224,145,108,271,185,109,180,141,107,275,323,324,229,223,322,110,146,78,187,231,230,186,188,147,229,232,278,146,277,185,148,279,276,189,111,145,112,228,233,149,184,110,328,329,280,113,275,327,330,81,191,235,190,234,236,192,151,150,282,283,189,152,237,233,281,149,193,284,115,114,116,334,153,188,333,280,113,238,232,148,285,335,195,240,239,194,196,154,241,238,155,287,288,153,193,286,197,156,118,289,117,242,237,119,285,152,339,338,192,340,116,157,198,86,399,344,400,456,398,345,457,292,517,458,293,343,455,401,397,346,516,459,518,244,294,342,581,519,245,291,402,454,347,396,580,520,403,348,404,347,402,349,461,462,296,295,405,460,346,297,463,401,350,294,523,247,522,248,459,298,406,524,246,521,249,464,345,351,407,352,408,351,406,353,466,465,299,300,409,467,350,298,464,354,301,405,527,251,528,250,468,410,526,252,297,349,302,463,529,249,411,412,356,355,470,357,410,413,303,471,469,304,354,302,358,472,409,305,468,532,254,414,531,255,301,533,253,353,530,256,473,306,416,415,360,359,474,361,417,475,414,307,306,358,473,308,476,362,418,305,536,258,413,537,257,309,357,472,535,259,477,538,256,304,420,364,419,363,421,479,365,478,311,310,418,362,480,312,477,309,422,366,541,261,481,540,262,361,417,542,260,313,308,476,539,263,424,368,367,423,425,483,369,484,314,366,315,482,422,313,426,485,316,370,545,481,265,546,264,365,312,421,544,266,547,263,317,427,428,372,371,429,427,487,488,318,373,370,317,319,430,426,486,489,550,268,316,320,374,369,549,551,267,269,490,485,431,425,548,552,432,375,376,433,431,492,374,491,322,377,321,493,434,323,430,490,320,373,555,494,271,554,272,378,324,435,556,270,553,273,319,429,436,379,437,380,435,496,378,497,325,326,438,381,495,324,498,327,434,377,559,275,494,560,274,382,439,558,276,323,328,499,561,273,440,441,383,384,501,382,439,500,442,329,330,385,502,328,499,381,438,331,564,278,443,563,279,327,386,503,565,277,498,562,280,332,445,444,387,388,505,386,446,443,333,504,506,332,389,334,385,503,447,331,507,568,282,442,569,281,335,567,283,390,570,280,502,330,449,391,448,392,450,390,509,510,337,336,447,508,393,338,511,389,335,451,573,285,572,286,507,446,574,284,339,394,334,512,571,287,453,395,452,396,454,394,514,513,340,341,451,515,397,339,512,455,393,342,577,289,578,288,516,338,450,576,290,579,287,511,398,392,648,582,649,716,717,647,583,787,718,518,650,715,581,519,584,646,788,786,719,789,860,520,580,457,517,458,651,714,859,790,645,585,652,653,586,721,587,722,651,585,654,522,720,723,588,521,523,793,584,792,650,794,655,520,524,719,461,791,724,460,462,589,583,459,657,656,590,726,591,658,725,589,727,655,526,592,525,527,724,797,659,798,588,728,796,654,524,528,465,464,593,799,466,723,795,463,661,660,594,662,595,730,731,593,729,530,596,659,732,663,531,529,802,801,592,728,803,528,532,468,597,469,800,658,733,664,467,470,665,666,599,598,735,664,734,736,600,597,667,534,533,535,733,806,663,807,737,805,596,601,532,536,472,668,473,808,471,732,474,804,670,669,603,602,739,740,671,668,604,738,538,601,537,539,741,811,810,672,737,605,812,667,536,540,476,600,477,809,475,742,813,478,674,673,607,675,606,744,743,608,745,542,672,605,742,543,541,676,815,816,609,814,746,544,540,480,817,479,671,604,741,481,677,478,678,679,611,748,677,610,612,749,747,680,546,609,545,547,676,820,750,613,746,819,821,548,544,484,483,681,818,608,485,822,675,482,683,682,615,753,752,616,614,684,681,550,751,754,549,551,617,613,825,824,685,680,548,552,826,823,487,488,750,755,486,489,618,612,687,686,619,757,688,620,618,756,758,685,554,621,553,555,689,829,755,617,759,830,828,556,552,491,492,684,831,622,490,827,690,493,691,692,623,690,624,761,762,622,760,558,693,625,763,557,559,689,834,833,621,835,759,560,556,495,832,496,694,626,764,494,688,497,695,696,627,628,766,765,694,697,626,767,562,629,563,561,764,838,839,693,768,625,837,698,564,560,499,630,498,840,500,763,836,497,700,699,631,632,770,701,771,769,630,633,698,566,565,567,772,843,702,842,768,844,634,629,568,564,503,697,502,841,504,773,501,845,704,705,636,703,635,775,774,637,776,570,634,706,773,702,571,569,847,848,638,777,846,572,568,507,633,506,849,707,772,701,508,505,708,709,640,779,639,707,780,641,778,710,574,638,575,573,781,852,706,851,642,777,853,711,576,572,510,511,637,850,509,782,854,512,713,712,644,784,643,783,714,645,711,578,785,782,642,579,577,856,646,857,715,855,710,580,576,786,514,858,781,515,513,641,647,516,936,1013,937,1012,861,1014,1091,935,862,1092,938,1011,788,1090,1015,1172,1093,789,860,863,934,790,859,1171,1094,717,1010,939,787,718,1173,864,940,941,1017,1018,865,939,866,864,1016,942,1019,1097,1096,792,867,793,938,791,863,1095,1098,1015,943,794,1020,790,721,868,720,722,1178,1177,945,944,1022,869,1021,870,946,1023,943,868,1101,871,1020,796,797,1100,1102,795,1024,947,867,942,798,1099,1103,872,794,725,1019,724,726,1182,949,948,1026,950,1027,874,873,1025,947,875,872,1106,1105,800,1028,951,801,799,1024,1107,1104,876,871,802,946,729,798,1029,728,730,1187,952,953,954,1031,1030,952,878,877,1032,879,1029,955,1110,876,804,951,805,1109,1111,803,880,1033,806,1028,1108,1112,875,956,733,802,732,950,1191,957,958,1035,882,1034,1036,881,956,883,959,1114,1115,808,880,1033,809,1037,807,955,884,1113,1116,960,810,737,736,879,806,1032,1196,738,1038,962,961,1039,1040,886,963,887,885,1038,960,1041,1119,812,813,1118,1120,888,884,964,811,1037,814,959,1042,1117,1121,741,740,810,1200,889,883,966,1044,965,967,890,1043,891,1045,889,964,1042,1124,1123,968,816,817,892,888,815,1046,1122,1125,818,1041,745,963,744,893,969,814,1205,746,970,971,1048,894,969,1049,895,1047,893,972,1128,896,820,1050,821,1129,1127,968,1046,819,822,892,973,1130,1126,897,749,748,1051,818,1209,1210,975,974,1052,1053,898,899,973,976,1051,1054,897,900,1132,1133,825,824,1131,1134,972,977,826,823,1050,1055,896,901,752,753,1214,827,822,1130,979,978,1057,903,980,1056,902,1058,904,977,1137,901,829,1055,828,1136,1138,981,1059,830,827,905,976,1135,1139,900,756,757,1054,831,1219,1218,983,1061,984,982,907,1062,906,1060,908,985,1063,1142,1141,981,833,832,905,909,834,1059,1140,1143,831,1064,760,986,761,904,980,835,1223,759,987,988,1066,1065,911,986,910,912,1067,989,1064,1146,837,836,1145,1147,913,909,985,838,1068,835,990,1063,1144,1148,764,765,839,1228,914,908,992,991,1070,915,1071,1069,916,993,914,990,1150,1151,841,917,1072,840,1068,842,994,913,1149,1152,989,839,768,769,918,843,1073,1232,767,1067,996,995,1074,1075,997,919,920,1073,918,1076,994,1155,921,845,998,844,1154,1156,846,917,1072,843,1077,1153,1157,922,993,772,847,773,999,1237,1000,1001,1079,999,1078,924,923,1080,1002,922,925,1159,1160,849,1077,998,848,850,1081,1161,1158,921,926,847,1003,776,851,1076,777,775,1241,997,1004,1005,1083,928,1084,927,1003,1082,1006,929,1164,926,1085,853,852,1163,1165,854,1081,1002,930,1007,851,1162,1166,925,855,780,1086,781,779,1246,1009,1008,1088,1087,932,1010,931,933,1089,1007,1086,1169,1168,857,930,856,1011,858,934,1167,1170,1090,1006,855,1085,859,784,929,785,783,1250,1251,1255,1339,1338,1256,1340,1423,1173,1174,1254,1424,1425,1509,1257,1337,1341,1422,1092,1175,1253,1172,1093,1508,1426,1510,1171,1094,1258,1336,1511,1597,1013,1342,1259,1343,1260,1344,1258,1177,1342,1178,1176,1428,1261,1429,1345,1427,1257,1096,1179,1341,1097,1175,1095,1430,1262,1346,1514,1515,1098,1426,1094,1017,1180,1256,1263,1264,1347,1348,1181,1262,1182,1265,1346,1349,1433,1180,1432,1183,1434,1100,1431,1101,1261,1099,1179,1266,1350,1345,1519,1102,1518,1098,1435,1184,1021,1520,1268,1352,1267,1351,1185,1353,1269,1186,1266,1437,1184,1350,1436,1438,1187,1104,1354,1105,1270,1103,1265,1435,1183,1439,1523,1106,1349,1188,1524,1102,1025,1522,1272,1356,1271,1357,1355,1273,1189,1190,1441,1270,1442,1188,1191,1440,1354,1358,1274,1108,1109,1107,1443,1187,1269,1110,1439,1192,1528,1527,1106,1029,1353,1359,1276,1360,1361,1277,1275,1359,1194,1193,1446,1445,1362,1192,1195,1274,1278,1112,1444,1447,1113,1358,1111,1191,1196,1114,1532,1363,1279,1273,1533,1531,1110,1033,1280,1365,1364,1281,1279,1198,1197,1366,1363,1450,1282,1449,1199,1196,1451,1278,1116,1117,1448,1115,1362,1367,1200,1118,1283,1452,1195,1536,1537,1037,1114,1036,1284,1369,1285,1368,1202,1370,1283,1201,1286,1454,1203,1367,1455,1453,1200,1120,1121,1371,1282,1119,1287,1456,1204,1122,1452,1541,1366,1199,1540,1542,1041,1040,1289,1373,1288,1374,1372,1206,1290,1205,1287,1458,1207,1459,1375,1371,1204,1457,1124,1125,1460,1291,1208,1286,1123,1126,1545,1546,1456,1203,1376,1370,1544,1045,1293,1377,1292,1378,1294,1210,1376,1209,1211,1463,1291,1462,1379,1464,1295,1128,1208,1129,1375,1212,1461,1127,1130,1290,1380,1550,1549,1465,1049,1207,1048,1296,1297,1382,1381,1296,1298,1214,1383,1380,1215,1213,1467,1466,1468,1295,1299,1132,1133,1212,1216,1384,1379,1131,1134,1465,1469,1554,1294,1300,1553,1555,1052,1053,1301,1386,1302,1385,1300,1218,1387,1219,1217,1471,1303,1472,1384,1470,1299,1137,1220,1136,1388,1216,1473,1138,1135,1304,1383,1558,1559,1469,1056,1221,1057,1298,1305,1390,1306,1391,1389,1222,1304,1223,1307,1476,1221,1475,1392,1388,1224,1477,1141,1140,1474,1303,1220,1308,1142,1139,1563,1562,1478,1225,1393,1387,1564,1060,1310,1394,1309,1395,1226,1393,1311,1227,1308,1480,1225,1396,1479,1481,1228,1145,1144,1392,1312,1146,1307,1478,1224,1143,1482,1567,1397,1229,1568,1566,1064,1065,1314,1399,1398,1313,1315,1230,1231,1397,1400,1484,1312,1485,1229,1232,1483,1316,1149,1148,1486,1150,1396,1401,1228,1147,1311,1482,1233,1572,1571,1068,1151,1069,1318,1403,1402,1317,1319,1404,1234,1235,1488,1489,1401,1233,1236,1316,1320,1153,1490,1487,1152,1405,1154,1232,1237,1151,1576,1400,1315,1321,1577,1575,1155,1072,1322,1407,1323,1408,1406,1321,1239,1238,1493,1324,1492,1240,1237,1494,1409,1405,1320,1157,1156,1158,1491,1241,1325,1155,1495,1236,1580,1581,1159,1076,1410,1404,1326,1411,1327,1412,1243,1410,1325,1242,1328,1497,1244,1413,1498,1496,1241,1161,1409,1160,1324,1162,1329,1499,1245,1495,1585,1159,1414,1240,1584,1163,1080,1586,1331,1330,1416,1415,1247,1332,1246,1329,1417,1414,1501,1248,1502,1245,1500,1165,1503,1164,1333,1166,1249,1328,1418,1413,1589,1163,1590,1167,1499,1244,1084,1588,1335,1420,1334,1419,1336,1251,1421,1250,1252,1506,1333,1505,1418,1507,1337,1169,1249,1422,1168,1253,1170,1504,1332,1417,1594,1593,1167,1508,1171,1088,1248,1338,1687,1598,1688,1776,1599,1686,1777,1510,1867,1778,1597,1511,1689,1775,1685,1600,1424,1512,1596,1779,1866,1868,1425,1509,1959,1869,1684,1601,1690,1774,1508,1426,1691,1602,1692,1603,1690,1601,1781,1514,1782,1515,1693,1604,1513,1780,1783,1600,1516,1689,1428,1429,1872,1512,1873,1427,1694,1605,1779,1871,1430,1874,1784,1517,1696,1695,1606,1607,1786,1697,1605,1518,1785,1608,1694,1519,1787,1517,1520,1784,1432,1698,1604,1433,1609,1877,1693,1431,1876,1516,1788,1878,1521,1434,1783,1875,1700,1611,1610,1699,1701,1612,1790,1523,1522,1791,1789,1609,1698,1524,1521,1702,1613,1436,1792,1788,1437,1881,1882,1435,1608,1525,1880,1697,1520,1438,1703,1883,1704,1615,1705,1614,1616,1703,1794,1527,1795,1526,1706,1528,1793,1613,1617,1702,1796,1525,1440,1441,1886,1885,1529,1439,1792,1442,1707,1612,1887,1884,1618,1524,1708,1619,1709,1620,1618,1799,1707,1531,1798,1710,1530,1532,1621,1800,1617,1797,1529,1444,1706,1445,1533,1890,1711,1889,1443,1801,1891,1622,1446,1796,1616,1528,1713,1623,1712,1624,1714,1803,1622,1535,1625,1536,1711,1802,1804,1534,1715,1537,1621,1449,1448,1805,1801,1533,1894,1626,1895,1710,1450,1447,1893,1896,1538,1363,1717,1628,1627,1718,1716,1629,1807,1539,1808,1540,1626,1806,1538,1719,1715,1541,1809,1630,1453,1452,1899,1898,1625,1537,1454,1805,1451,1900,1542,1714,1720,1810,1721,1632,1722,1631,1633,1720,1812,1811,1544,1543,1723,1630,1813,1545,1542,1634,1810,1719,1457,1456,1903,1458,1904,1724,1902,1814,1546,1541,1629,1455,1635,1809,1726,1636,1725,1637,1635,1816,1727,1548,1724,1547,1815,1817,1638,1549,1634,1546,1461,1728,1818,1814,1460,1907,1723,1908,1462,1550,1639,1906,1459,1545,1909,1633,1730,1640,1641,1729,1731,1820,1639,1552,1821,1642,1551,1553,1728,1819,1732,1822,1550,1638,1465,1554,1912,1464,1466,1643,1911,1818,1913,1727,1463,1823,1467,1549,1734,1645,1644,1735,1733,1825,1646,1556,1824,1643,1557,1555,1736,1826,1732,1823,1558,1647,1469,1554,1916,1470,1468,1642,1917,1827,1915,1737,1471,1822,1467,1559,1738,1649,1739,1648,1650,1829,1737,1560,1740,1561,1830,1828,1647,1559,1651,1562,1473,1736,1831,1827,1474,1921,1741,1920,1472,1558,1646,1922,1475,1563,1919,1652,1743,1653,1742,1654,1652,1744,1833,1834,1564,1565,1741,1655,1832,1563,1566,1651,1835,1745,1477,1478,1925,1476,1924,1740,1926,1831,1562,1567,1656,1479,1650,1836,1747,1657,1658,1748,1746,1656,1838,1569,1837,1568,1659,1839,1570,1749,1745,1567,1836,1655,1481,1482,1929,1930,1660,1571,1480,1840,1483,1928,1566,1750,1744,1835,1751,1662,1752,1661,1750,1842,1663,1573,1660,1572,1753,1843,1841,1574,1749,1571,1664,1485,1486,1844,1840,1575,1934,1659,1933,1754,1484,1487,1935,1932,1570,1400,1756,1666,1755,1665,1667,1846,1757,1577,1847,1754,1578,1576,1664,1845,1668,1848,1579,1490,1758,1489,1575,1938,1753,1939,1491,1844,1937,1663,1488,1849,1669,1580,1760,1670,1759,1671,1669,1761,1851,1581,1850,1582,1758,1580,1852,1672,1668,1762,1849,1583,1494,1493,1942,1943,1579,1495,1853,1492,1757,1673,1941,1944,1667,1584,1764,1674,1675,1765,1763,1673,1855,1585,1586,1856,1854,1676,1766,1584,1587,1762,1672,1498,1857,1853,1497,1947,1946,1499,1677,1583,1948,1767,1588,1496,1761,1945,1768,1769,1679,1678,1859,1767,1680,1590,1860,1677,1770,1589,1858,1591,1588,1861,1502,1766,1681,1501,1676,1951,1771,1503,1952,1592,1857,1950,1587,1500,1862,1953,1773,1683,1772,1682,1774,1684,1864,1594,1863,1593,1771,1681,1595,1865,1862,1685,1592,1775,1506,1505,1956,1596,1955,1507,1770,1680,1866,1957,1504,1954,1861,1591,2053,1960,2054,2146,2147,2052,1961,2148,2240,1868,1869,1959,2145,2055,2051,1962,2241,2239,2149,2335,2242,1870,1958,1777,1778,1867,2144,2056,2050,1963,2334,2243,2057,2058,1964,1965,2151,2056,2152,1963,2059,1872,2150,1873,1966,1871,2153,2055,2245,1962,2246,1874,1781,2149,2244,1870,2060,1782,1780,1967,2247,2154,1783,1875,2062,2061,1968,1969,2156,2155,2063,2060,1967,1970,1876,1877,2157,2154,1875,2250,1878,2249,2064,1966,2059,1971,1785,2251,1786,2158,1874,2248,1784,2153,1879,1787,2066,2065,1973,1972,2067,2160,2159,1974,2161,1881,1880,2064,1971,2068,2158,1882,1879,2254,1975,2253,2255,2162,1789,1790,1970,2063,1883,1788,1878,1791,2252,2157,2070,1977,2071,2069,2164,1976,1978,2165,2163,1885,1884,2072,1975,2068,1886,1979,2166,2258,1883,2259,2162,1794,2257,1793,1887,2073,2260,1795,1974,1792,2067,1980,2074,2075,1981,1982,2168,2169,2073,1980,2076,1889,2167,1888,1983,1890,2170,1979,2263,2072,2262,1887,1798,2077,1891,1797,2166,2264,2261,1799,1984,2171,1796,1978,2079,2078,1985,1986,2173,2172,2080,1984,2077,1893,1987,2174,1894,1892,2171,2267,2081,1983,2266,1895,2268,1802,2076,1891,1988,2175,1801,1803,2170,2265,1800,2269,2083,1990,2082,1989,2084,2177,2176,1991,2178,1988,1897,1898,2081,2085,1896,2271,2175,1899,2272,2179,1992,1806,2270,1987,1805,1895,1807,2080,2273,2086,1900,1804,2087,2088,1994,1993,2086,2181,1995,2182,2180,1901,1902,2089,1992,2085,2183,1900,1996,1903,2276,2275,2179,1810,1811,2277,1809,2274,2090,1991,1899,1904,2184,1812,2091,2092,1998,1999,2185,1997,2186,2090,2093,1906,1905,2184,2187,2000,1996,1907,2280,1904,2089,2279,2094,2281,1814,1815,2183,1908,1813,2188,2001,2278,1903,1995,2096,2095,2002,2003,2190,2097,2189,2001,2094,1910,2191,2004,1909,1911,2188,2098,2284,2000,2285,1908,2283,2192,1818,1819,1912,2093,2005,1817,2286,1820,2187,1907,2100,2007,2006,2101,2099,2194,2195,2193,2005,2008,1914,1913,1915,2098,2102,2289,2288,2192,2196,2009,2004,1916,1912,1822,1823,2287,2290,1824,1821,2097,2103,2191,2104,2105,2011,2010,2198,2103,2199,2012,2106,1918,2197,2009,1919,1917,2200,2102,2293,2013,2292,1920,2294,2196,1827,1826,1916,2107,2008,1828,2291,1825,2201,1921,2109,2108,2015,2014,2203,2016,2202,2110,2107,1922,1923,2204,2201,2013,2017,1921,2297,1924,2111,2298,2106,2296,1831,1830,2205,1920,1832,2200,2012,2299,1925,2018,2113,2112,2019,2020,2114,2207,2018,2206,2208,1927,1926,2111,2021,2115,2205,1928,2017,1925,2301,2302,2209,1835,1834,2300,1836,2303,2110,2022,1929,1924,2204,1833,2117,2023,2118,2024,2116,2211,2212,2022,2210,2025,1931,1930,2119,2115,1932,2306,2213,1929,2305,2209,2021,1839,2307,2026,1840,1933,1838,2120,2304,2114,1928,1841,2121,2122,2028,2027,2215,2216,2120,2029,2123,1935,2026,2214,1934,1936,2217,2310,2119,2030,2311,1933,2309,1843,2124,1937,2025,2213,1844,1842,2218,2312,1845,2308,2126,2125,2032,2031,2220,2219,2127,2033,2124,1939,2221,1940,2030,1938,2218,2034,2314,2128,2315,1941,1847,2123,1937,1848,2222,2313,2316,1846,2029,2217,1849,2035,2130,2036,2129,2131,2224,2037,2035,2223,2225,1943,1944,2128,2038,2132,1942,2034,2222,2319,1945,2318,2226,1851,2320,1852,1941,2127,2317,1850,2039,1853,2133,2033,2134,2135,2040,2041,2133,2228,2229,2039,2227,1947,1948,2136,2042,2132,2230,1946,1949,2323,2038,2324,2322,2226,1856,1855,2043,2137,1945,1857,1950,1854,2325,2231,2138,2139,2045,2044,2232,2233,2137,2140,2046,2043,1952,1951,2231,2234,1953,2327,1950,2328,2136,2047,2141,2042,1860,2326,1859,2230,1954,2329,1861,2235,1949,1858,2143,2142,2049,2048,2237,2144,2236,2050,2141,1956,2238,1955,2047,1957,2235,2145,2332,2051,2331,1954,1864,2239,2333,1958,2140,1863,1865,2046,2330,2234,1862,1953,2432,2528,2527,2433,2336,2529,2624,2337,2431,2241,2434,2526,2625,2242,2335,2338,2430,2623,2530,2626,2721,2334,2243,2147,2720,2627,2240,2148,2435,2525,2429,2339,2436,2437,2532,2340,2435,2533,2341,2339,2531,2438,2245,2629,2342,2534,2246,2434,2630,2244,2338,2628,2530,2247,2631,2151,2243,2439,2152,2343,2150,2535,2627,2726,2440,2441,2536,2344,2537,2345,2439,2442,2343,2535,2538,2346,2249,2250,2633,2634,2248,2438,2342,2632,2251,2635,2443,2534,2347,2539,2155,2247,2156,2154,2731,2730,2445,2444,2541,2349,2348,2540,2446,2443,2542,2350,2347,2539,2253,2254,2638,2637,2252,2639,2255,2447,2442,2543,2351,2346,2636,2159,2538,2160,2251,2158,2256,2735,2449,2448,2545,2353,2352,2544,2450,2546,2354,2447,2351,2258,2257,2642,2543,2641,2451,2643,2547,2259,2256,2355,2446,2350,2163,2640,2164,2644,2260,2162,2255,2542,2453,2452,2549,2357,2454,2550,2356,2548,2358,2451,2262,2646,2261,2355,2455,2551,2647,2359,2645,2263,2547,2260,2167,2168,2648,2450,2264,2354,2644,2166,2552,2456,2457,2458,2553,2361,2456,2554,2362,2360,2552,2266,2459,2555,2650,2455,2265,2651,2363,2359,2267,2649,2551,2264,2652,2172,2171,2268,2556,2460,2364,2454,2173,2358,2461,2462,2365,2558,2557,2460,2366,2364,2559,2463,2556,2270,2367,2655,2654,2269,2271,2459,2363,2656,2653,2268,2560,2555,2272,2464,2176,2175,2368,2177,2752,2174,2465,2466,2562,2369,2370,2561,2464,2563,2467,2368,2371,2274,2560,2659,2275,2658,2273,2463,2660,2564,2367,2468,2276,2657,2372,2272,2180,2179,2559,2181,2661,2756,2470,2469,2566,2374,2373,2565,2567,2471,2468,2375,2372,2278,2663,2279,2564,2277,2662,2568,2664,2472,2467,2376,2280,2371,2184,2276,2661,2183,2665,2185,2563,2760,2474,2473,2570,2378,2377,2571,2475,2569,2379,2472,2282,2376,2667,2283,2572,2668,2476,2281,2666,2568,2380,2284,2471,2669,2188,2375,2187,2280,2189,2573,2665,2765,2478,2477,2574,2382,2479,2575,2381,2383,2573,2576,2476,2286,2287,2671,2480,2672,2380,2384,2285,2288,2670,2572,2673,2192,2577,2475,2191,2193,2379,2284,2481,2289,2482,2483,2579,2386,2481,2578,2387,2385,2580,2577,2484,2291,2290,2676,2480,2675,2388,2384,2292,2289,2677,2581,2674,2196,2576,2485,2197,2195,2389,2293,2479,2288,2486,2487,2583,2390,2391,2582,2485,2584,2389,2488,2295,2392,2680,2294,2581,2679,2484,2296,2681,2585,2388,2293,2489,2678,2200,2393,2201,2297,2199,2580,2682,2777,2490,2491,2587,2394,2395,2588,2586,2489,2492,2393,2396,2299,2684,2298,2589,2300,2685,2585,2683,2488,2493,2392,2297,2397,2204,2301,2686,2205,2682,2203,2590,2782,2495,2494,2591,2399,2398,2592,2496,2590,2493,2400,2397,2303,2593,2688,2302,2689,2304,2497,2687,2589,2401,2492,2301,2690,2396,2305,2208,2209,2594,2207,2686,2786,2499,2498,2403,2595,2596,2500,2402,2404,2594,2497,2597,2307,2401,2692,2693,2308,2306,2501,2405,2691,2694,2309,2593,2598,2305,2496,2212,2213,2400,2211,2790,2214,2503,2502,2600,2407,2504,2599,2406,2408,2601,2311,2501,2598,2697,2505,2312,2696,2405,2409,2310,2698,2602,2313,2695,2216,2217,2309,2597,2500,2404,2506,2215,2410,2507,2508,2604,2411,2506,2603,2412,2605,2410,2509,2315,2701,2316,2413,2505,2602,2700,2409,2702,2314,2606,2317,2221,2220,2699,2510,2313,2414,2703,2222,2601,2504,2511,2512,2608,2415,2416,2609,2510,2607,2414,2513,2417,2319,2320,2705,2610,2706,2509,2704,2606,2318,2321,2413,2514,2418,2225,2707,2224,2703,2317,2226,2322,2611,2515,2516,2612,2419,2420,2613,2514,2517,2611,2418,2421,2614,2324,2323,2709,2710,2325,2708,2322,2513,2518,2610,2417,2422,2711,2229,2615,2228,2326,2230,2321,2807,2520,2519,2617,2424,2616,2423,2521,2518,2425,2618,2615,2422,2328,2327,2714,2713,2329,2522,2426,2715,2326,2712,2517,2619,2421,2614,2233,2330,2232,2234,2811,2812,2524,2523,2621,2428,2525,2620,2427,2429,2622,2522,2332,2718,2426,2619,2331,2526,2717,2333,2430,2719,2623,2330,2716,2237,2334,2521,2236,2425,2238,2618,2720,2816,2820,2918,2821,2917,3015,2919,2722,2819,2723,3016,2916,2822,3113,3017,2625,3014,2920,2724,2818,2626,2721,3112,3018,2720,2627,3114,2528,2915,2823,3212,3115,2624,2824,2922,2825,2923,2726,2823,2727,2921,2725,2826,3020,2924,3021,2728,2629,3019,2630,2822,2628,2920,2724,3022,2631,2827,3118,2925,2729,3018,3119,2532,2627,2533,2829,2828,2927,2926,2731,2730,2830,2827,2928,2925,3025,3024,2732,2729,2633,2634,3026,3023,2831,2826,2632,2635,2929,2924,2733,2728,3123,3122,2536,2537,2631,3027,2833,2931,2832,2930,2834,2735,2932,2734,2736,3029,2831,3028,2929,2733,2638,3030,2637,2835,2933,2737,2639,3027,2636,2830,3127,3031,2928,2732,2541,2540,3126,2640,2837,2935,2838,2836,2936,2739,2934,2740,2738,3033,2839,3034,2835,3032,2937,2642,2933,2741,2641,2737,2643,3035,2640,3031,3131,2644,2840,2545,3132,2834,2544,2742,2841,2842,2939,2940,2743,2840,2744,2938,2843,2742,3037,2941,3038,2745,2646,3036,2647,2839,2645,2937,3039,2741,2844,2648,2942,2746,2644,3136,3135,2549,3035,2550,2846,2845,2944,2943,2748,2747,2847,2844,2945,2942,3042,3041,2749,2746,2650,2651,3043,3040,2848,2649,2843,2946,2750,2652,2941,2745,3140,2553,3139,2554,2648,3044,2850,2948,2849,2947,2851,2752,2949,2751,2753,3046,2848,3045,2946,3047,2750,2655,2852,2654,2950,2754,2656,2653,3044,2847,3144,3048,2945,2749,2558,2557,3145,3143,2854,2952,2855,2853,2953,2756,2951,2757,2755,3050,2856,3051,2954,2852,3049,2659,2758,2658,2950,2754,2660,3052,2657,3048,2857,3148,3149,2562,2661,2561,2955,2759,2858,2859,2956,2957,2760,2857,2761,2955,2860,3054,2759,2958,3055,2762,2663,3053,2662,2664,2856,3056,2954,2758,2861,2959,2661,2763,2665,3153,2566,3152,3052,2565,2863,2862,2961,2960,2765,2764,2864,2962,2861,2959,3059,2766,3058,2763,2667,2668,3060,2865,2666,3057,2963,2860,2767,2669,2958,2762,3157,2665,2570,3158,2571,3061,2867,2965,2866,2964,2868,2769,2966,2768,2770,3063,2865,3062,2963,3064,2869,2671,2767,2672,2967,2771,2670,2673,3061,3065,2864,3161,3162,2574,2575,2962,2766,2669,2871,2969,2872,2970,2870,2773,2968,2774,2772,3067,2873,3068,2971,3066,2869,2676,2775,2675,2967,2771,2677,2674,3069,3065,2874,3166,3165,2579,2578,2972,2776,2678,2875,2876,2973,2974,2777,2778,2874,2972,2877,2975,3071,2776,3072,2779,2680,2679,3070,2873,2681,3073,2971,2878,2775,2678,2976,2780,3170,2682,2583,3169,2582,3069,2880,2879,2978,2977,2782,2881,2781,2979,2878,3076,2783,2976,3075,2780,2684,3077,2685,2683,2882,3074,2980,2784,2877,2975,2686,2779,2682,3174,2587,3175,3078,2588,2884,2982,2883,2885,2981,2786,2983,2785,2787,3080,2882,3079,2980,2886,3081,2688,2784,2689,2984,2788,2687,3078,2690,3082,2881,3179,3178,2591,2686,2592,2979,2783,2888,2986,2889,2987,2887,2790,2985,2791,2789,3084,2890,3085,2988,3083,2792,2692,2886,2693,2984,2788,2691,2694,3086,2891,3183,3082,2989,2793,2595,2596,3182,3184,2892,2893,2990,2991,2794,2795,2891,2894,2989,2992,3088,3089,2793,2796,2697,2696,3087,3090,2890,2698,2895,2988,2792,2695,2993,2797,3187,2600,3188,2599,2699,3086,2897,2896,2995,2994,2799,2898,2798,2996,2895,2800,3093,2993,3092,2797,2701,3094,2700,2899,2702,2997,3091,2801,2894,2699,2992,2796,2703,3191,3192,2604,3095,2603,2901,2999,2900,2902,2998,2803,3000,2802,2804,3097,2899,3096,2903,3098,2997,2705,3001,2801,2706,2805,2704,3095,2707,3099,3196,2703,2898,2608,3195,2904,2609,2800,2905,3003,2906,3004,2904,2807,3002,2808,2806,3101,2907,3102,3005,2809,2709,3100,2710,2903,3001,2805,2708,3103,2711,2908,3200,3099,3006,2810,2612,2613,3201,2707,2909,2910,3007,3008,2811,2812,2908,2911,3006,3009,3105,3106,2810,2813,2714,2713,3104,3107,2907,2912,2715,2712,3005,3010,2809,2814,3204,3205,2617,2616,2716,3103,2914,3012,2913,3011,2816,2915,2815,3013,2817,2912,3110,3010,3109,2814,2718,3111,2717,2916,2719,3014,2818,3108,2716,2911,3209,3009,2813,3112,3208,2621,2720,2620,3312,3213,3311,3214,3410,3313,3114,3411,3212,3115,3412,3508,3215,3310,3314,3409,3016,3211,3116,3113,3017,3509,3507,3413,3606,3510,3112,3018,3216,3309,3408,3315,3316,3217,3317,3218,3216,3315,3118,3415,3119,3416,3219,3318,3117,3414,3120,3020,3215,3417,3314,3021,3019,3513,3116,3514,3220,3319,3413,3022,3512,3121,3018,2922,3321,3222,3320,3221,3223,3123,3322,3122,3420,3419,3220,3319,3124,3121,3421,3418,3025,3024,3224,3323,3219,3518,3517,3026,3318,3125,3023,3120,3422,3519,3417,3516,3325,3226,3324,3225,3227,3326,3127,3424,3126,3423,3128,3224,3425,3323,3228,3327,3029,3125,3422,3028,3129,3030,3522,3521,3426,3027,3523,3223,3322,3229,3031,2931,3329,3230,3330,3231,3229,3328,3131,3428,3132,3429,3232,3130,3427,3331,3133,3228,3327,3033,3034,3032,3430,3129,3526,3426,3527,3233,3525,3332,3035,3031,3134,2935,3334,3333,3235,3234,3136,3135,3432,3236,3335,3233,3332,3433,3137,3431,3134,3037,3434,3038,3237,3232,3336,3530,3331,3036,3531,3138,3039,3133,3430,3529,2939,3035,3338,3239,3337,3238,3240,3339,3140,3437,3436,3139,3141,3237,3336,3438,3241,3435,3340,3138,3042,3041,3142,3535,3534,3043,3040,3236,3335,3439,3536,3137,3533,3434,3342,3243,3343,3244,3242,3341,3144,3441,3145,3440,3143,3245,3442,3344,3241,3340,3146,3046,3045,3439,3142,3047,3539,3538,3443,3044,3246,3540,3345,3048,3147,2948,3346,3247,3347,3248,3445,3148,3246,3345,3149,3249,3348,3446,3444,3147,3150,3050,3245,3051,3447,3344,3049,3543,3250,3349,3443,3146,3544,3542,3151,3052,3048,2952,3351,3252,3350,3251,3253,3352,3153,3449,3152,3450,3250,3349,3154,3448,3151,3254,3451,3054,3353,3055,3155,3547,3053,3548,3249,3056,3348,3447,3546,3150,2956,3549,3355,3256,3356,3257,3255,3354,3157,3454,3453,3158,3156,3258,3357,3254,3455,3353,3452,3059,3159,3058,3155,3552,3060,3551,3057,3456,3259,3553,3358,3253,3550,3352,3359,3260,3360,3261,3259,3358,3161,3458,3162,3262,3361,3457,3459,3160,3163,3063,3258,3357,3062,3456,3064,3556,3159,3263,3460,3362,3555,3557,3061,3164,3065,2965,3364,3265,3363,3264,3266,3365,3166,3462,3165,3263,3362,3463,3461,3167,3164,3067,3267,3366,3068,3464,3066,3560,3168,3262,3460,3361,3561,3559,3069,3163,3065,2969,3368,3269,3367,3268,3270,3369,3170,3466,3467,3169,3171,3267,3366,3271,3465,3370,3468,3071,3168,3072,3172,3564,3070,3565,3073,3464,3266,3563,3365,3272,3566,3371,3372,3273,3373,3274,3272,3371,3174,3471,3175,3470,3275,3374,3173,3472,3176,3271,3469,3076,3370,3075,3172,3569,3077,3568,3276,3074,3375,3473,3570,3177,2978,3567,3377,3278,3376,3277,3475,3179,3279,3378,3178,3276,3375,3474,3476,3180,3177,3080,3280,3079,3473,3379,3081,3573,3275,3374,3477,3181,3572,3574,3176,3078,3082,2982,3381,3282,3380,3281,3283,3382,3183,3479,3182,3480,3184,3280,3478,3379,3284,3383,3181,3084,3085,3481,3185,3083,3577,3578,3477,3086,3279,3576,3378,3082,3180,2986,3385,3286,3386,3287,3285,3384,3187,3483,3484,3188,3186,3288,3387,3482,3284,3485,3383,3189,3088,3089,3185,3581,3582,3087,3090,3289,3388,3481,3580,3190,3583,3486,3389,3390,3290,3291,3191,3192,3488,3289,3388,3292,3391,3487,3190,3489,3193,3093,3486,3092,3288,3293,3387,3586,3392,3094,3585,3189,3091,3194,3490,3587,2995,3095,3394,3295,3393,3294,3296,3395,3196,3492,3195,3491,3293,3197,3493,3392,3194,3297,3396,3097,3096,3098,3490,3198,3590,3494,3589,3292,3591,3391,3095,3099,3193,2999,3398,3299,3399,3300,3298,3397,3200,3496,3201,3497,3199,3301,3495,3400,3297,3396,3101,3202,3498,3102,3198,3100,3594,3595,3494,3103,3593,3302,3401,3296,3099,3003,3402,3303,3403,3304,3302,3204,3401,3205,3500,3501,3305,3404,3203,3206,3499,3502,3105,3106,3301,3400,3306,3598,3599,3104,3405,3202,3107,3207,3498,3597,3503,3600,3407,3308,3406,3307,3309,3408,3209,3505,3208,3504,3306,3405,3210,3506,3207,3110,3310,3503,3409,3109,3111,3603,3211,3602,3305,3404,3507,3108,3604,3206,3112,3012,3705,3607,3706,3802,3803,3704,3608,3509,3899,3804,3606,3510,3801,3707,3703,3609,3900,3898,3805,3411,3605,3511,3995,3901,3508,3412,3702,3610,3800,3708,3413,3507,3709,3611,3710,3612,3807,3708,3610,3808,3513,3514,3806,3711,3613,3512,3809,3904,3707,3515,3609,3905,3415,3416,3903,3805,3511,3414,3712,3614,3417,3906,3516,3810,3714,3713,3616,3615,3811,3812,3715,3712,3617,3614,3518,3517,3810,3813,3519,3516,3908,3909,3420,3419,3716,3618,3711,3613,3907,3421,3418,3809,3520,3515,3910,3814,3718,3620,3717,3619,3719,3816,3621,3815,3522,3521,3716,3817,3618,3523,3814,3720,3622,3913,3520,3912,3424,3423,3524,3425,3818,3914,3911,3617,3715,3422,3813,3519,3722,3624,3723,3721,3625,3820,3623,3819,3526,3821,3527,3525,3724,3626,3720,3622,3917,3818,3916,3428,3528,3524,3822,3429,3427,3918,3915,3627,3725,3430,3621,3426,3726,3727,3628,3629,3824,3725,3627,3825,3530,3823,3728,3531,3630,3529,3921,3532,3724,3826,3626,3432,3920,3822,3433,3922,3528,3431,3729,3631,3434,3533,3919,3430,3731,3730,3633,3632,3828,3829,3732,3634,3729,3535,3534,3631,3827,3536,3830,3533,3925,3437,3733,3436,3635,3926,3924,3728,3630,3826,3438,3537,3435,3532,3831,3927,3735,3637,3734,3636,3736,3833,3832,3638,3539,3538,3733,3635,3540,3834,3831,3737,3639,3929,3537,3930,3441,3440,3541,3928,3442,3634,3732,3835,3830,3439,3931,3536,3739,3641,3740,3738,3642,3837,3640,3836,3543,3838,3544,3542,3741,3643,3737,3639,3835,3933,3934,3545,3445,3541,3446,3444,3839,3932,3935,3644,3742,3447,3443,3638,3743,3744,3645,3646,3841,3742,3644,3840,3547,3842,3745,3548,3647,3546,3549,3938,3937,3741,3839,3643,3449,3843,3450,3746,3648,3448,3545,3939,3936,3451,3550,3351,3748,3747,3650,3649,3845,3749,3846,3651,3746,3552,3551,3844,3648,3553,3550,3847,3942,3941,3750,3652,3454,3453,3843,3745,3943,3647,3455,3554,3452,3549,3940,3848,3752,3654,3751,3653,3753,3849,3655,3850,3556,3555,3848,3750,3557,3652,3851,3754,3656,3946,3554,3458,3945,3947,3457,3558,3459,3847,3651,3749,3456,3852,3944,3460,3756,3658,3757,3659,3755,3854,3657,3853,3560,3561,3855,3758,3559,3660,3852,3754,3656,3950,3562,3462,3951,3949,3463,3558,3461,3856,3661,3759,3464,3851,3952,3460,3760,3761,3662,3663,3858,3759,3857,3661,3762,3564,3565,3859,3664,3563,3566,3856,3954,3955,3758,3660,3466,3467,3860,3763,3953,3665,3465,3562,3468,3567,3956,3855,3765,3764,3667,3666,3862,3766,3668,3863,3569,3861,3763,3568,3665,3570,3567,3958,3959,3767,3864,3669,3471,3860,3470,3762,3664,3472,3571,3957,3960,3469,3566,3372,3769,3671,3768,3770,3670,3866,3672,3867,3573,3865,3572,3574,3767,3669,3771,3673,3868,3963,3962,3571,3475,3575,3474,3476,3864,3964,3961,3668,3766,3473,3477,3674,3773,3675,3774,3676,3772,3870,3871,3674,3577,3578,3775,3677,3576,3869,3872,3771,3673,3967,3579,3966,3479,3480,3575,3968,3478,3678,3776,3868,3873,3481,3965,3580,3777,3778,3679,3680,3875,3874,3776,3678,3779,3581,3582,3681,3876,3580,3873,3583,3971,3483,3775,3484,3677,3970,3972,3780,3682,3877,3482,3579,3485,3584,3872,3969,3782,3781,3684,3683,3879,3783,3685,3878,3586,3880,3780,3585,3682,3587,3975,3584,3784,3877,3686,3488,3976,3881,3487,3974,3588,3489,3779,3681,3486,3583,3977,3490,3786,3688,3785,3787,3687,3883,3689,3884,3590,3882,3589,3591,3784,3686,3788,3690,3979,3885,3980,3492,3588,3592,3881,3491,3493,3978,3981,3685,3783,3490,3691,3494,3790,3692,3791,3693,3789,3887,3691,3888,3594,3595,3792,3886,3694,3593,3889,3788,3690,3983,3596,3984,3496,3497,3592,3495,3885,3982,3985,3695,3793,3498,3890,3597,3794,3795,3696,3697,3892,3891,3793,3796,3695,3698,3598,3599,3893,3890,3597,3600,3988,3987,3500,3501,3792,3694,3797,3699,3989,3499,3502,3894,3596,3601,3986,3889,3799,3701,3798,3700,3896,3800,3702,3895,3603,3602,3897,3797,3699,3604,3894,3992,3801,3601,3703,3991,3505,3504,3993,3898,3605,3506,3796,3698,3503,3990,3600,3893,4092,3996,-1,4093,4186,-1,-1,4091,3997,3900,-1,-1,-1,3995,3901,-1,4094,4185,-1,4090,3998,-1,3803,3902,3994,-1,-1,3899,3804,-1,-1,-1,4096,4097,4000,-1,-1,4095,4001,3999,-1,3904,-1,-1,4098,-1,3905,4002,3903,4094,-1,3998,-1,-1,3906,3807,-1,3808,3902,-1,-1,3806,-1,4003,4100,4101,4004,-1,-1,4005,4099,-1,4003,-1,4102,3908,-1,4006,3909,-1,3907,-1,4098,3910,-1,-1,4002,3811,-1,3812,-1,4007,-1,4103,3906,3810,4104,4105,-1,4009,4008,-1,-1,4103,4106,4010,4007,-1,3913,3912,-1,-1,-1,-1,3914,3911,4102,3816,-1,4011,3815,4006,4107,-1,-1,3817,-1,-1,4109,4108,-1,4013,4012,-1,-1,4110,4107,4014,3917,-1,-1,3916,4011,-1,3918,-1,-1,3915,4015,-1,4111,3820,4106,3819,-1,-1,3821,4010,-1,-1,4113,4112,4017,-1,-1,4016,4114,4018,-1,4111,-1,3921,-1,-1,3920,4015,3922,-1,4019,-1,4115,-1,3919,-1,3824,3923,3825,4110,-1,3823,-1,-1,4117,4116,4021,-1,-1,4118,4022,4020,-1,3925,-1,4115,-1,3926,-1,3924,-1,4023,-1,4019,4119,-1,3927,3828,3923,3829,-1,-1,-1,3827,-1,4114,4121,-1,4025,4120,4122,-1,4026,-1,4024,3929,-1,3930,-1,4119,-1,4027,3928,-1,4123,-1,4023,3931,-1,3833,3832,-1,3927,-1,-1,-1,4028,3834,4125,4126,4029,-1,-1,4124,4030,4028,-1,-1,3933,4031,3934,-1,-1,4127,4123,3932,-1,-1,3935,-1,-1,4027,3837,3836,4032,-1,-1,3838,3931,-1,4129,4130,-1,4034,4033,-1,4128,-1,4035,4032,3938,-1,3937,4131,-1,-1,-1,4127,3939,-1,3936,-1,4036,3841,4031,3840,-1,3842,-1,-1,-1,4132,4133,4134,-1,4038,4037,-1,4132,-1,4039,4135,3942,-1,3941,4036,-1,-1,-1,3943,-1,4131,4040,3940,-1,3845,3846,-1,-1,4136,3844,3944,-1,4035,4137,4138,4042,-1,-1,4041,4043,4136,-1,4139,-1,3946,-1,-1,3945,3947,4040,4044,-1,-1,-1,4135,3944,-1,3849,3850,4140,3948,-1,-1,3848,-1,4142,4141,4046,-1,-1,4047,4045,4143,-1,4140,3950,-1,-1,-1,3951,3949,4048,-1,4044,-1,-1,4144,3952,3854,3853,4139,3948,-1,-1,-1,-1,3855,4146,4145,-1,4050,4051,-1,-1,4147,4049,4144,3954,-1,3955,4052,-1,-1,-1,-1,3953,4148,4048,3956,3858,-1,-1,3857,-1,4143,3859,3952,4053,-1,4150,4149,-1,4054,4055,-1,4151,-1,4053,-1,4056,3958,3959,-1,4148,-1,-1,4152,3957,3960,-1,-1,4052,3862,-1,4057,3863,-1,3861,-1,-1,4147,4154,-1,4153,4059,4155,4058,-1,-1,4060,-1,3963,4057,-1,3962,-1,4152,4156,3964,-1,3961,-1,-1,4061,3866,-1,3867,4056,-1,-1,3865,-1,3965,4158,-1,4063,4159,4157,4062,-1,-1,4064,3967,-1,3966,4160,4061,-1,-1,-1,-1,3968,4156,4065,3965,3870,3871,-1,-1,-1,3969,-1,4060,-1,3869,4162,4163,4067,-1,-1,4161,4066,4068,-1,3971,-1,4164,-1,-1,3970,3972,4065,-1,4069,4160,-1,-1,3969,3875,3973,3874,-1,-1,-1,3876,-1,4165,4166,4167,4071,-1,-1,4072,4165,4070,-1,4168,-1,3975,-1,-1,3976,4073,3974,-1,4069,-1,-1,4164,3977,3879,-1,3973,3878,4169,-1,3880,-1,-1,4170,4171,-1,4075,4076,-1,-1,4169,4172,4074,3979,-1,3980,4077,-1,-1,-1,-1,3978,3981,4073,4168,3883,-1,4173,3884,-1,-1,3882,4078,3977,-1,4175,4174,-1,4079,4080,-1,4176,-1,4173,4078,4081,3983,-1,3984,-1,-1,-1,3982,-1,3985,4177,-1,3887,4077,3888,4082,4172,-1,-1,-1,-1,3886,4179,4178,4084,-1,-1,4083,4180,4085,-1,-1,4177,3988,-1,4082,3987,-1,3989,-1,4181,-1,3986,-1,4086,-1,3892,3891,-1,-1,4081,4176,3990,3893,4183,4182,-1,4088,4184,-1,4087,-1,4089,3992,-1,4181,3991,-1,-1,4086,3993,-1,4185,-1,4090,3990,-1,3896,3895,-1,3994,-1,-1,3897,-1,4085]}}} diff --git a/docs/source/_static/css/foveation-viewer.css b/docs/source/_static/css/foveation-viewer.css new file mode 100644 index 000000000000..8d12840598d8 --- /dev/null +++ b/docs/source/_static/css/foveation-viewer.css @@ -0,0 +1,206 @@ +/* + * Copyright (c) 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 + */ + +/* Interactive sampling-grid and pooling viewers on the Foveated Camera page. */ + +.fovi-viewer { + --fovi-ink: #1f2a37; + --fovi-muted: #8a96a8; + --fovi-faint: #d7dee8; + --fovi-surface: #ffffff; + --fovi-panel: #f6f8fb; + --fovi-border: #dfe5ec; + --fovi-accent: #2458d3; + --fovi-camera: #167d72; + --fovi-highlight: #d47b00; + --fovi-body: #29364b; + margin: 1.25rem 0 1.75rem; + padding: 1rem; + border: 1px solid var(--fovi-border); + border-radius: 8px; + background: var(--fovi-panel); + color: var(--fovi-ink); +} + +html[data-theme="dark"] .fovi-viewer { + --fovi-ink: #e3e8ef; + --fovi-muted: #7d8899; + --fovi-faint: #3a4556; + --fovi-surface: #11161d; + --fovi-panel: #1a2029; + --fovi-border: #343d4b; + --fovi-accent: #6d9cff; + --fovi-camera: #3cc2ad; + --fovi-highlight: #f0a33a; + --fovi-body: #5b6f8c; +} + +.fovi-controls { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(12.5rem, 1fr)); + gap: 0.6rem 1.2rem; + align-items: end; +} + +.fovi-control { + display: grid; + grid-template-columns: 1fr auto; + gap: 0.15rem 0.5rem; + margin: 0; + font-size: 0.85rem; +} + +.fovi-viewer [hidden] { + display: none; +} + +.fovi-control-name { + grid-column: 1 / -1; +} + +.fovi-control input[type="range"], +.fovi-control select { + width: 100%; + min-width: 0; + accent-color: var(--fovi-accent); +} + +.fovi-control select { + padding: 0.15rem 0.3rem; + border: 1px solid var(--fovi-border); + border-radius: 4px; + background: var(--fovi-surface); + color: var(--fovi-ink); +} + +.fovi-control-value { + min-width: 3.5rem; + font-variant-numeric: tabular-nums; + text-align: right; +} + +.fovi-reset { + justify-self: start; + padding: 0.25rem 0.9rem; + border: 1px solid var(--fovi-border); + border-radius: 4px; + background: var(--fovi-surface); + color: var(--fovi-ink); + font-size: 0.85rem; + cursor: pointer; +} + +.fovi-summary { + margin: 0.9rem 0 0.6rem; + font-size: 0.9rem; +} + +.fovi-panels { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr)); + gap: 1rem; +} + +.fovi-panels-stacked { + grid-template-columns: 1fr; +} + +.fovi-panels-three { + grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); +} + +.fovi-panel { + margin: 0; + padding: 0.6rem; + border: 1px solid var(--fovi-border); + border-radius: 6px; + background: var(--fovi-surface); +} + +.fovi-panel-control { + max-width: 22rem; + margin-bottom: 0.4rem; +} + +.fovi-panel figcaption { + margin-bottom: 0.4rem; + font-weight: 600; + font-size: 0.9rem; +} + +.fovi-views { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.4rem; +} + +.fovi-canvas { + display: block; + width: 100%; + aspect-ratio: 1; + touch-action: none; +} + +.fovi-sphere { + cursor: grab; +} + +.fovi-panel-labels { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.4rem; + color: var(--fovi-muted); + font-size: 0.75rem; + text-align: center; +} + +.fovi-panel-note { + margin: 0.4rem 0 0; + font-size: 0.8rem; +} + +.fovi-legend { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.3rem 0.5rem; + margin: 0.7rem 0 0; + font-size: 0.8rem; +} + +.fovi-key { + display: inline-block; + width: 0.7rem; + height: 0.7rem; + margin-left: 0.6rem; + border-radius: 50%; +} + +.fovi-key:first-child { + margin-left: 0; +} + +.fovi-key-accent { + background: var(--fovi-accent); +} + +.fovi-key-muted { + background: var(--fovi-muted); +} + +.fovi-key-camera { + background: var(--fovi-camera); +} + +.fovi-key-highlight { + background: var(--fovi-highlight); +} + +.fovi-legend-note { + margin-left: auto; + color: var(--fovi-muted); +} diff --git a/docs/source/_static/css/foveation-viewer.js b/docs/source/_static/css/foveation-viewer.js new file mode 100644 index 000000000000..1e7bdda1d9b3 --- /dev/null +++ b/docs/source/_static/css/foveation-viewer.js @@ -0,0 +1,987 @@ +/* + * Copyright (c) 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 + */ + +// Interactive sampling-grid and pooling viewers for the Foveated Camera page. +// The sampling follows fovi's SamplingCoords with spherical field geometry, as the camera configures it. +(() => { + "use strict"; + + const DEG = Math.PI / 180; + const TAU = 2 * Math.PI; + // fovi's isotropic pooling neighbourhoods for the pooling viewer, beside this script; fetched only when used. + const SCRIPT_URL = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : null; + const TABLES_URL = SCRIPT_URL ? new URL("foveation-pooling-isotropic.json", SCRIPT_URL).href : null; + + // -- Sampling geometry ------------------------------------------------------------------------------------------- + + // Warped Cartesian grid: an N x N lattice in the native plane, mapped radially by the integrated CMF. + // Returns samples in canonical order (x index major), each with normalized visual coordinates s = (x, y) / r_max. + const warpedGrid = (fov, a, res) => { + const half = fov / 2; + const growth = 1 + half / a; + const samples = []; + for (let i = 0; i < res; i++) { + for (let j = 0; j < res; j++) { + const cx = -1 + (2 * i + 1) / res; + const cy = -1 + (2 * j + 1) / res; + const rho = Math.hypot(cx, cy); + const r = a * (Math.pow(growth, rho) - 1); + const theta = Math.atan2(cy, cx); + samples.push({i, j, native: [cx, cy], s: [(r / half) * Math.cos(theta), (r / half) * Math.sin(theta)], valid: rho <= 1 + 1e-12}); + } + } + return samples; + }; + + // Isotropic rings: radii even in cortical distance w = log(r + a), angles per ring matched to the radial step. + const isotropicRings = (fov, a, res) => { + if (res === 1) { + return {radius: [0], count: [1]}; + } + const half = fov / 2; + const wMin = Math.log(a); + const wDelta = (Math.log(half + a) - wMin) / (res - 1); + const radius = Array.from({length: res + 1}, (_, k) => Math.exp(wMin + k * wDelta) - a); + const count = [1]; + for (let k = 1; k < res; k++) { + const step = (radius[k + 1] - radius[k - 1]) / 2; + const tangential = Math.sin(radius[k] * DEG) / DEG; // spherical field geometry + count.push(Math.ceil((TAU * tangential) / step)); + } + return {radius: radius.slice(0, res).map((r) => r / half), count}; + }; + + const isotropicCount = (fov, a, res) => isotropicRings(fov, a, res).count.reduce((sum, n) => sum + n, 0); + + // The camera matches an isotropic retina to foveated_res^2 samples (fovi's auto_match_num_coords). + const matchedIsotropicRes = (fov, a, target) => { + let left = 1; + let right = 1000; + let best = 1; + let bestDiff = Infinity; + while (left <= right) { + const mid = (left + right) >> 1; + const n = isotropicCount(fov, a, mid); + const diff = Math.abs(n - target); + if (diff < bestDiff) { + bestDiff = diff; + best = mid; + } + if (n < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + while (best > 1 && isotropicCount(fov, a, best) > target) { + best -= 1; + } + return best; + }; + + const isotropicSamples = (fov, a, rings) => { + const {radius, count} = isotropicRings(fov, a, rings); + const samples = []; + radius.forEach((r, ring) => { + for (let k = 0; k < count[ring]; k++) { + const angle = (k * TAU) / count[ring]; + samples.push({ring, s: [r * Math.cos(angle), r * Math.sin(angle)], valid: true}); + } + }); + return samples; + }; + + // Unit ray of a normalized visual coordinate, in the image frame: x right, y down, z forward. + const ray = (s, fov) => { + const e = Math.hypot(s[0], s[1]) * (fov / 2) * DEG; + const theta = Math.atan2(s[1], s[0]); + return [Math.sin(e) * Math.cos(theta), -Math.sin(e) * Math.sin(theta), Math.cos(e)]; + }; + + // Pan-then-tilt gaze rotation (row-major), as isaaclab_fovi's gaze kernels: positive tilt looks up, pan left. + const gazeRotation = (tilt, pan) => { + const x = -Math.cos(tilt * DEG) * Math.sin(pan * DEG); + const y = -Math.sin(tilt * DEG); + const z = Math.cos(tilt * DEG) * Math.cos(pan * DEG); + const pitch = Math.atan2(x, z); + const roll = Math.atan2(-y, Math.hypot(x, z)); + const [cp, sp, cr, sr] = [Math.cos(pitch), Math.sin(pitch), Math.cos(roll), Math.sin(roll)]; + return [[cp, sp * sr, sp * cr], [0, cr, -sr], [-sp, cp * sr, cp * cr]]; + }; + + const rotate = (m, v) => m.map((row) => row[0] * v[0] + row[1] * v[1] + row[2] * v[2]); + + // An ideal square camera whose field of view spans its side; the retina spans the same angle. + const SIDE = 1000; + const cameraModels = { + fisheye: { + label: "Equidistant fisheye", + fov: {min: 40, max: 240, initial: 180}, + focal: (fov) => SIDE / 2 / ((fov / 2) * DEG), + project(d, f) { + const lateral = Math.hypot(d[0], d[1]); + const theta = Math.atan2(lateral, d[2]); + if (lateral < 1e-12) { + return [SIDE / 2, SIDE / 2]; + } + return [SIDE / 2 + (f * theta * d[0]) / lateral, SIDE / 2 + (f * theta * d[1]) / lateral]; + }, + unproject(p, f) { + const dx = p[0] - SIDE / 2; + const dy = p[1] - SIDE / 2; + const theta = Math.hypot(dx, dy) / f; + const lateral = Math.hypot(dx, dy) || 1; + return [(Math.sin(theta) * dx) / lateral, (Math.sin(theta) * dy) / lateral, Math.cos(theta)]; + }, + }, + pinhole: { + label: "Pinhole", + fov: {min: 20, max: 170, initial: 80}, + focal: (fov) => SIDE / 2 / Math.tan((fov / 2) * DEG), + project(d, f) { + if (d[2] <= 1e-9) { + return null; + } + return [SIDE / 2 + (f * d[0]) / d[2], SIDE / 2 + (f * d[1]) / d[2]]; + }, + unproject(p, f) { + return normalize([(p[0] - SIDE / 2) / f, (p[1] - SIDE / 2) / f, 1]); + }, + }, + }; + + const normalize = (v) => { + const n = Math.hypot(v[0], v[1], v[2]); + return [v[0] / n, v[1] / n, v[2] / n]; + }; + + const inImage = (p) => p !== null && p[0] >= 0 && p[0] < SIDE && p[1] >= 0 && p[1] < SIDE; + + const imageBorder = (model, f) => { + const points = []; + const corners = [[0, 0], [SIDE, 0], [SIDE, SIDE], [0, SIDE], [0, 0]]; + for (let k = 0; k < 4; k++) { + for (let t = 0; t < 40; t++) { + const [a, b] = [corners[k], corners[k + 1]]; + points.push(model.unproject([a[0] + ((b[0] - a[0]) * t) / 40, a[1] + ((b[1] - a[1]) * t) / 40], f)); + } + } + points.push(points[0]); + return points; + }; + + // Spacing of neighbouring samples [deg] at the fixation and at the edge of the field. + const spacing = (style, fov, a, res) => { + const half = fov / 2; + if (style === "isotropic") { + const step = (Math.log(half + a) - Math.log(a)) / Math.max(res - 1, 1); + return [a * (Math.exp(step) - 1), (half + a) * (1 - Math.exp(-step))]; + } + const rate = Math.log(1 + half / a) * (2 / res); + return [a * rate, (half + a) * rate]; + }; + + // -- Drawing helpers --------------------------------------------------------------------------------------------- + + const palette = (element) => { + const style = getComputedStyle(element); + const get = (name, fallback) => style.getPropertyValue(name).trim() || fallback; + return { + ink: get("--fovi-ink", "#1f2a37"), + muted: get("--fovi-muted", "#8a96a8"), + faint: get("--fovi-faint", "#d7dee8"), + surface: get("--fovi-surface", "#ffffff"), + accent: get("--fovi-accent", "#2458d3"), + camera: get("--fovi-camera", "#167d72"), + highlight: get("--fovi-highlight", "#d47b00"), + body: get("--fovi-body", "#29364b"), + }; + }; + + const fitCanvas = (canvas) => { + const box = canvas.getBoundingClientRect(); + const ratio = Math.min(window.devicePixelRatio || 1, 2); + canvas.width = Math.max(1, Math.round(box.width * ratio)); + canvas.height = Math.max(1, Math.round(box.height * ratio)); + const ctx = canvas.getContext("2d"); + ctx.setTransform(ratio, 0, 0, ratio, 0, 0); + return {ctx, w: box.width, h: box.height}; + }; + + const polyline = (ctx, points, color, width, dash = []) => { + if (points.length < 2) { + return; + } + ctx.beginPath(); + ctx.setLineDash(dash); + ctx.strokeStyle = color; + ctx.lineWidth = width; + points.forEach((p, k) => (k === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]))); + ctx.stroke(); + ctx.setLineDash([]); + }; + + const dots = (ctx, points, color, radius, alpha = 1) => { + ctx.globalAlpha = alpha; + ctx.fillStyle = color; + ctx.beginPath(); + for (const p of points) { + ctx.moveTo(p[0] + radius, p[1]); + ctx.arc(p[0], p[1], radius, 0, TAU); + } + ctx.fill(); + ctx.globalAlpha = 1; + }; + + // Orbiting orthographic view of the viewing sphere; the camera sits at its centre looking along +z. + const sphereProjector = (view, w, h) => { + const scale = Math.min(w, h) * 0.4; + const [cy, sy, cp, sp] = [Math.cos(view.yaw), Math.sin(view.yaw), Math.cos(view.pitch), Math.sin(view.pitch)]; + return ([x, y, z]) => { + const rx = cy * x - sy * z; + const rz = sy * x + cy * z; + const ry = cp * y - sp * rz; + const depth = sp * y + cp * rz; + return [w / 2 + rx * scale, h / 2 + ry * scale, depth]; + }; + }; + + const bindOrbit = (canvas, view, redraw, initial) => { + let last = null; + canvas.addEventListener("pointerdown", (event) => { + last = [event.clientX, event.clientY]; + canvas.setPointerCapture(event.pointerId); + }); + canvas.addEventListener("pointermove", (event) => { + if (!last) { + return; + } + view.yaw += (event.clientX - last[0]) * 0.01; + view.pitch = Math.max(-1.5, Math.min(1.5, view.pitch - (event.clientY - last[1]) * 0.01)); + last = [event.clientX, event.clientY]; + redraw(); + }); + for (const name of ["pointerup", "pointercancel"]) { + canvas.addEventListener(name, () => (last = null)); + } + canvas.addEventListener("dblclick", () => { + Object.assign(view, initial); + redraw(); + }); + }; + + const drawSphere = (canvas, view, scene, colors) => { + const {ctx, w, h} = fitCanvas(canvas); + const project = sphereProjector(view, w, h); + // The viewer looks from behind the camera, so smaller depths are nearer; nothing is opaque but the camera. + const segment = (points, color, width) => polyline(ctx, points.map(project), color, width); + const circle = (polar) => Array.from({length: 121}, (_, k) => { + const az = (k * TAU) / 120; + return [Math.sin(polar) * Math.cos(az), Math.sin(polar) * Math.sin(az), Math.cos(polar)]; + }); + for (const polar of [30, 60, 90, 120, 150]) { + segment(circle(polar * DEG), colors.faint, polar === 90 ? 1.2 : 0.7); + } + for (let k = 0; k < 12; k++) { + const az = (k * TAU) / 12; + segment(Array.from({length: 61}, (_, t) => { + const polar = (t * Math.PI) / 60; + return [Math.sin(polar) * Math.cos(az), Math.sin(polar) * Math.sin(az), Math.cos(polar)]; + }), colors.faint, 0.7); + } + segment(scene.border, colors.camera, 2); + const radius = scene.dotRadius; + dots(ctx, scene.rays.filter((r) => !r.valid).map((r) => project(r.dir)), colors.muted, radius, 0.5); + dots(ctx, scene.rays.filter((r) => r.valid).map((r) => project(r.dir)), colors.accent, radius, 0.7); + for (const line of scene.lines) { + segment(line, colors.accent, 0.8); + } + segment(scene.retinaEdge, colors.accent, 1.6); + const gaze = project(scene.gaze); + dots(ctx, [gaze], colors.surface, 4.5); + ctx.beginPath(); + ctx.arc(gaze[0], gaze[1], 4.5, 0, TAU); + ctx.strokeStyle = colors.accent; + ctx.lineWidth = 2; + ctx.stroke(); + // Camera housing at the centre. + const body = [[-0.09, -0.06, -0.22], [0.09, -0.06, -0.22], [0.09, 0.06, -0.22], [-0.09, 0.06, -0.22], + [-0.09, -0.06, -0.06], [0.09, -0.06, -0.06], [0.09, 0.06, -0.06], [-0.09, 0.06, -0.06]]; + const faces = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]] + .map((face) => face.map((k) => project(body[k]))) + .sort((a, b) => b.reduce((s, p) => s + p[2], 0) - a.reduce((s, p) => s + p[2], 0)); + for (const face of faces) { + ctx.beginPath(); + face.forEach((p, k) => (k === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1]))); + ctx.closePath(); + ctx.fillStyle = colors.body; + ctx.fill(); + ctx.strokeStyle = colors.faint; + ctx.lineWidth = 0.6; + ctx.stroke(); + } + }; + + // -- Sampling viewer --------------------------------------------------------------------------------------------- + + const control = (label, input, output) => { + const wrapper = document.createElement("label"); + wrapper.className = "fovi-control"; + const name = document.createElement("span"); + name.className = "fovi-control-name"; + name.innerHTML = label; + wrapper.append(name, input); + if (output) { + wrapper.append(output); + } + return wrapper; + }; + + const slider = (min, max, step, value) => { + const input = document.createElement("input"); + Object.assign(input, {type: "range", min, max, step, value}); + return input; + }; + + const select = (options, value) => { + const input = document.createElement("select"); + for (const [key, text] of options) { + input.append(new Option(text, key)); + } + input.value = value; + return input; + }; + + const readout = () => { + const output = document.createElement("output"); + output.className = "fovi-control-value"; + return output; + }; + + const formatA = (a) => (a >= 100 ? a.toFixed(0) : a >= 10 ? a.toFixed(1) : a >= 1 ? a.toFixed(2) : a.toFixed(3)); + + const initSamplingViewer = (root) => { + const defaults = {style: "warped_cartesian_as_grid", logA: Math.log10(0.591), res: 32, tilt: 0, pan: 0}; + const state = {...defaults}; + const inputs = { + style: select([["warped_cartesian_as_grid", "warped_cartesian_as_grid"], ["isotropic", "isotropic"]], state.style), + logA: slider(-2, 3, 0.01, state.logA), + res: slider(8, 128, 1, state.res), + tilt: slider(-60, 60, 1, state.tilt), + pan: slider(-60, 60, 1, state.pan), + }; + const outputs = {logA: readout(), res: readout(), tilt: readout(), pan: readout()}; + const controls = document.createElement("div"); + controls.className = "fovi-controls"; + controls.append( + control("foveated_style", inputs.style), + control("cmf_a_deg", inputs.logA, outputs.logA), + control("foveated_res", inputs.res, outputs.res), + control("Gaze tilt", inputs.tilt, outputs.tilt), + control("Gaze pan", inputs.pan, outputs.pan), + ); + const reset = document.createElement("button"); + reset.type = "button"; + reset.className = "fovi-reset"; + reset.textContent = "Reset"; + controls.append(reset); + const summary = document.createElement("p"); + summary.className = "fovi-summary"; + summary.setAttribute("aria-live", "polite"); + const panels = document.createElement("div"); + panels.className = "fovi-panels fovi-panels-stacked"; + const initialView = {yaw: -0.6, pitch: 0.35}; + const cameras = Object.entries(cameraModels).map(([key, model]) => { + const panel = document.createElement("figure"); + panel.className = "fovi-panel"; + const title = document.createElement("figcaption"); + title.textContent = model.label; + const sphere = document.createElement("canvas"); + sphere.className = "fovi-canvas fovi-sphere"; + sphere.setAttribute("aria-label", `${model.label}: the retina's rays on the viewing sphere. Drag to rotate; double-click to reset.`); + const image = document.createElement("canvas"); + image.className = "fovi-canvas fovi-image"; + image.setAttribute("aria-label", `${model.label}: where the retina's samples land in the camera image.`); + const labels = document.createElement("div"); + labels.className = "fovi-panel-labels"; + labels.innerHTML = "Viewing sphere (drag to rotate)Camera image"; + const views = document.createElement("div"); + views.className = "fovi-views"; + views.append(sphere, image); + const note = document.createElement("p"); + note.className = "fovi-panel-note"; + // Each camera has its own field of view; the retina spans it. + const fovInput = slider(model.fov.min, model.fov.max, 1, model.fov.initial); + const fovOutput = readout(); + const fovControl = control("Field of view", fovInput, fovOutput); + fovControl.classList.add("fovi-panel-control"); + panel.append(title, fovControl, views, labels, note); + panels.append(panel); + const view = {...initialView}; + const camera = {key, model, sphere, image, note, view, fov: model.fov.initial, fovInput, fovOutput}; + fovInput.addEventListener("input", () => { + camera.fov = Number(fovInput.value); + sync(); + }); + return camera; + }); + const legend = document.createElement("p"); + legend.className = "fovi-legend"; + legend.innerHTML = 'retinal sample' + + 'outside the camera image (masked with mask_to_sensor_fov)' + + 'camera image border'; + root.append(controls, summary, panels, legend); + + const samplesCache = new Map(); + const samplesFor = (fov) => { + const a = Math.pow(10, state.logA); + const key = `${state.style}/${a}/${state.res}/${fov}`; + if (samplesCache.has(key)) { + return samplesCache.get(key); + } + let samples; + let description; + let resolution = state.res; + if (state.style === "isotropic") { + resolution = matchedIsotropicRes(fov, a, state.res * state.res); + samples = isotropicSamples(fov, a, resolution); + description = `${samples.length.toLocaleString("en-US")} samples on ${resolution} rings, published as (num_envs, ${samples.length}, 1, C)`; + } else { + samples = warpedGrid(fov, a, state.res); + const valid = samples.filter((s) => s.valid).length; + description = `${state.res} × ${state.res} grid, ${valid.toLocaleString("en-US")} samples inside the circular field, published as (num_envs, ${state.res}, ${state.res}, C)`; + } + const [centre, edge] = spacing(state.style, fov, a, resolution); + const entry = {samples: samples.filter((s) => s.valid), all: samples, description, centre, edge}; + samplesCache.set(key, entry); + if (samplesCache.size > 4) { + samplesCache.delete(samplesCache.keys().next().value); // keep the recent settings of both cameras + } + return entry; + }; + + // The retina's rays, outline and warped-grid lattice lines (every few rows and columns) for a field of view. + const retinaFor = (fov, rotation) => { + const data = samplesFor(fov); + const rays = data.samples.map((s) => rotate(rotation, ray(s.s, fov))); + const edge = Array.from({length: 181}, (_, k) => rotate(rotation, ray([Math.cos((k * TAU) / 180), Math.sin((k * TAU) / 180)], fov))); + const lines = []; + if (state.style !== "isotropic") { + const every = Math.max(1, Math.round(state.res / 16)); + const index = new Map(data.all.map((s) => [s.i * state.res + s.j, s])); + for (let fixed = Math.floor(every / 2); fixed < state.res; fixed += every) { + for (const transpose of [false, true]) { + let run = []; + for (let moving = 0; moving < state.res; moving++) { + const s = index.get(transpose ? moving * state.res + fixed : fixed * state.res + moving); + if (s && s.valid) { + run.push(rotate(rotation, ray(s.s, fov))); + } else if (run.length) { + lines.push(run); + run = []; + } + } + if (run.length) { + lines.push(run); + } + } + } + } + return {data, rays, edge, lines}; + }; + + const redraw = () => { + const colors = palette(root); + const rotation = gazeRotation(state.tilt, state.pan); + const gaze = rotate(rotation, [0, 0, 1]); + summary.textContent = "Each camera's retina spans that camera's field of view; move its slider to compare fields."; + for (const camera of cameras) { + const {data, rays, edge, lines} = retinaFor(camera.fov, rotation); + const count = rays.length; + const dotRadius = Math.max(0.6, Math.min(2.4, 70 / Math.sqrt(count))); + const f = camera.model.focal(camera.fov); + const projected = rays.map((d) => camera.model.project(d, f)); + const valid = projected.map(inImage); + const inside = valid.filter(Boolean).length; + drawSphere(camera.sphere, camera.view, { + rays: rays.map((dir, k) => ({dir, valid: valid[k]})), + border: imageBorder(camera.model, f), + lines, + retinaEdge: edge, + gaze, + dotRadius, + }, colors); + drawImagePlane(camera.image, projected, valid, edge.map((d) => camera.model.project(d, f)), camera.model.project(gaze, f), dotRadius, colors); + camera.note.innerHTML = `${data.description}. Sample spacing: ${data.centre.toPrecision(2)}° at the fixation, ` + + `${data.edge.toPrecision(2)}° at the edge of the ${camera.fov}° field. ` + + `${inside.toLocaleString("en-US")} of ${count.toLocaleString("en-US")} samples inside the image (${((100 * inside) / count).toFixed(0)}%).`; + } + }; + + const drawImagePlane = (canvas, projected, valid, edge, gaze, radius, colors) => { + const {ctx, w, h} = fitCanvas(canvas); + const margin = 0.18; + const scale = Math.min(w, h) / (SIDE * (1 + 2 * margin)); + const ox = (w - SIDE * scale) / 2; + const oy = (h - SIDE * scale) / 2; + const map = (p) => [ox + p[0] * scale, oy + p[1] * scale]; + ctx.fillStyle = colors.surface; + ctx.fillRect(ox, oy, SIDE * scale, SIDE * scale); + ctx.strokeStyle = colors.camera; + ctx.lineWidth = 2; + ctx.strokeRect(ox, oy, SIDE * scale, SIDE * scale); + polyline(ctx, [map([SIDE / 2, 0]), map([SIDE / 2, SIDE])], colors.faint, 0.7); + polyline(ctx, [map([0, SIDE / 2]), map([SIDE, SIDE / 2])], colors.faint, 0.7); + const visible = (p) => p !== null && p[0] > -SIDE && p[0] < 2 * SIDE && p[1] > -SIDE && p[1] < 2 * SIDE; + ctx.save(); + ctx.beginPath(); + ctx.rect(0, 0, w, h); + ctx.clip(); + dots(ctx, projected.filter((p, k) => !valid[k] && visible(p)).map(map), colors.muted, radius, 0.5); + dots(ctx, projected.filter((p, k) => valid[k]).map(map), colors.accent, radius, 0.75); + const edgeRuns = []; + let run = []; + for (const p of edge) { + if (visible(p)) { + run.push(map(p)); + } else if (run.length) { + edgeRuns.push(run); + run = []; + } + } + edgeRuns.push(run); + for (const r of edgeRuns) { + polyline(ctx, r, colors.accent, 1.4); + } + if (gaze && visible(gaze)) { + const g = map(gaze); + ctx.beginPath(); + ctx.arc(g[0], g[1], 4.5, 0, TAU); + ctx.fillStyle = colors.surface; + ctx.fill(); + ctx.strokeStyle = colors.accent; + ctx.lineWidth = 2; + ctx.stroke(); + } + ctx.restore(); + }; + + const sync = () => { + const a = Math.pow(10, state.logA); + outputs.logA.textContent = `${formatA(a)}°`; + outputs.res.textContent = state.res; + for (const camera of cameras) { + camera.fovOutput.textContent = `${camera.fov}°`; + } + outputs.tilt.textContent = `${state.tilt}°`; + outputs.pan.textContent = `${state.pan}°`; + redraw(); + }; + for (const [name, input] of Object.entries(inputs)) { + input.addEventListener("input", () => { + state[name] = name === "style" ? input.value : Number(input.value); + sync(); + }); + } + reset.addEventListener("click", () => { + Object.assign(state, defaults); + for (const [name, input] of Object.entries(inputs)) { + input.value = state[name]; + } + for (const camera of cameras) { + Object.assign(camera.view, initialView); + camera.fov = camera.model.fov.initial; + camera.fovInput.value = camera.fov; + } + sync(); + }); + for (const camera of cameras) { + bindOrbit(camera.sphere, camera.view, redraw, initialView); + } + new ResizeObserver(() => redraw()).observe(panels); + sync(); + }; + + // -- Pooling viewer ---------------------------------------------------------------------------------------------- + + // Upright layout of a canonical warped grid (fovi's sampling_as_grid): row = res - 1 - j, column = i. + // Pooling windows follow fovi's GridPoolingLayer: stride = resolution multiple, SAME-style padding. + const poolingWindow = (lowRes, mult, side, row, col) => { + const stride = mult; + const before = Math.floor((side - stride) / 2); + const cells = []; + for (let dr = 0; dr < side; dr++) { + for (let dc = 0; dc < side; dc++) { + const r = row * stride - before + dr; + const c = col * stride - before + dc; + if (r >= 0 && r < lowRes * mult && c >= 0 && c < lowRes * mult) { + cells.push([r, c]); + } + } + } + return cells; + }; + + const initPoolingViewer = (root) => { + const FOV = Number(root.dataset.fov || 90); + const A = Number(root.dataset.cmfA || 2); + const LOW = Number(root.dataset.res || 16); + const defaults = {style: "warped_cartesian_as_grid", mult: 2, side: 2, row: 8, col: 11, k: 4, space: "geodesic", unit: 120}; + const state = {...defaults}; + const inputs = { + style: select([["warped_cartesian_as_grid", "warped_cartesian_as_grid"], ["isotropic", "isotropic"]], state.style), + mult: select([["2", "2"], ["3", "3"], ["4", "4"]], String(state.mult)), + side: slider(1, 9, 1, state.side), + row: slider(0, LOW - 1, 1, state.row), + col: slider(0, LOW - 1, 1, state.col), + k: slider(1, 32, 1, state.k), + space: select([["geodesic", "geodesic (default)"], ["visual", "visual field (False)"]], state.space), + unit: slider(0, 1, 1, state.unit), + }; + const outputs = {side: readout(), row: readout(), col: readout(), k: readout(), unit: readout()}; + const controls = document.createElement("div"); + controls.className = "fovi-controls"; + const gridControls = [ + control("Window side (pool_k = side²)", inputs.side, outputs.side), + control("Pooled sample row", inputs.row, outputs.row), + control("Pooled sample column", inputs.col, outputs.col), + ]; + const isotropicControls = [ + control("pool_k (neighbours)", inputs.k, outputs.k), + control("pool_sample_cortex", inputs.space), + control("Pooled sample", inputs.unit, outputs.unit), + ]; + controls.append(control("foveated_style", inputs.style), control("pool_res_mult", inputs.mult), ...gridControls, ...isotropicControls); + const reset = document.createElement("button"); + reset.type = "button"; + reset.className = "fovi-reset"; + reset.textContent = "Reset"; + controls.append(reset); + const summary = document.createElement("p"); + summary.className = "fovi-summary"; + summary.setAttribute("aria-live", "polite"); + const panels = document.createElement("div"); + panels.className = "fovi-panels fovi-panels-three"; + const makePanel = (title, label) => { + const panel = document.createElement("figure"); + panel.className = "fovi-panel"; + const caption = document.createElement("figcaption"); + caption.textContent = title; + const canvas = document.createElement("canvas"); + canvas.className = "fovi-canvas fovi-square"; + canvas.setAttribute("aria-label", label); + panel.append(caption, canvas); + panels.append(panel); + return {panel, canvas}; + }; + const nativeView = makePanel("Published grid (click a sample)", "The pooled grid and its photoreceptor grid in the published image layout. Click a pooled sample to select it."); + const fieldView = makePanel("Visual field (click a sample)", "Photoreceptor and pooled samples by visual angle. Click a pooled sample to select it."); + const zoomView = makePanel("Around the selected sample", "The selected pooled sample's neighbourhood, enlarged."); + const legend = document.createElement("p"); + legend.className = "fovi-legend"; + legend.innerHTML = 'photoreceptor' + + 'pooled into the selected sample' + + 'pooled sample' + + `Fixed: ${FOV}° field, cmf_a_deg=${A}, foveated_res=${LOW}.`; + root.append(controls, summary, panels, legend); + + // fovi's pooling neighbourhoods for the isotropic retina, exported with the camera's own helpers. + let isotropicTables = null; + if (TABLES_URL) { + fetch(TABLES_URL) + .then((response) => (response.ok ? response.json() : Promise.reject(new Error(response.statusText)))) + .then((data) => { + if (data.fov !== FOV || data.cmfA !== A || data.res !== LOW) { + throw new Error("the exported tables describe another retina"); + } + isotropicTables = data; + if (state.style === "isotropic") { + sync(); + } + }) + .catch((error) => { + isotropicTables = {error: String(error.message || error)}; + if (state.style === "isotropic") { + sync(); + } + }); + } + + // Grid retina: samples keyed by their upright (row, column) in the published image. + const gridLayout = (res) => { + const samples = warpedGrid(FOV, A, res).map((s) => ({...s, row: res - 1 - s.j, col: s.i})); + return {samples, at: new Map(samples.map((s) => [`${s.row},${s.col}`, s]))}; + }; + const layouts = new Map(); + const layoutFor = () => { + const key = `${state.style}/${state.mult}`; + if (layouts.has(key)) { + return layouts.get(key); + } + let layout; + if (state.style === "isotropic") { + const rings = matchedIsotropicRes(FOV, A, LOW * LOW); + const highRings = Math.round(state.mult * rings); + layout = { + rings, + highRings, + low: isotropicSamples(FOV, A, rings), + high: isotropicSamples(FOV, A, highRings), + }; + } else { + layout = {low: gridLayout(LOW), high: gridLayout(LOW * state.mult)}; + } + layouts.set(key, layout); + return layout; + }; + + // The selected pooled sample, the photoreceptors it pools, and a description, for the current style. + const selection = (layout) => { + if (state.style !== "isotropic") { + const unit = layout.low.at.get(`${state.row},${state.col}`); + const cells = poolingWindow(LOW, state.mult, state.side, state.row, state.col); + const members = cells.map(([r, c]) => layout.high.at.get(`${r},${c}`)).filter((s) => s.valid); + const k = state.side * state.side; + const text = `pool_k=${k} (window side ${state.side}, stride ${state.mult}); the photoreceptor grid is ` + + `${LOW * state.mult} × ${LOW * state.mult}` + + (k < state.mult * state.mult ? "; a window smaller than the stride skips photoreceptors." : "."); + return {unit, members, valid: unit.valid && members.length > 0, text, label: `(${state.row}, ${state.col})`}; + } + const unit = layout.low[state.unit]; + const table = isotropicTable(layout); + if (!table) { + return {unit, members: [], valid: false, pending: true, text: "", label: `${state.unit}`}; + } + const members = table.slice(0, state.k).filter((index) => index >= 0).map((index) => layout.high[index]); + const text = `pool_k=${state.k} nearest photoreceptors ${state.space === "geodesic" ? "along the cortex" : "in the visual field"}; ` + + `${layout.high.length.toLocaleString("en-US")} photoreceptors on ${layout.highRings} rings pool into ${layout.low.length} samples on ${layout.rings} rings` + + ` (default pool_k ${Math.round(layout.high.length / layout.low.length)}).`; + return {unit, members, valid: members.length > 0, text, label: `${state.unit}`}; + }; + + // The selected sample's neighbours, nearest first, from fovi's table for the chosen space. + const isotropicTable = (layout) => { + const entry = isotropicTables && !isotropicTables.error && isotropicTables.mult[String(state.mult)]; + if (!entry) { + return null; + } + if (entry.count !== layout.high.length || isotropicTables.count !== layout.low.length) { + isotropicTables = {error: "the exported tables do not match this retina"}; + return null; + } + return entry[state.space].slice(state.unit * entry.kMax, (state.unit + 1) * entry.kMax); + }; + + const fieldTransform = (w, h, centre, radius) => { + const scale = (Math.min(w, h) / 2 - 8) / radius; + return (s) => [w / 2 + (s[0] - centre[0]) * scale, h / 2 - (s[1] - centre[1]) * scale]; + }; + + const redraw = () => { + const colors = palette(root); + const layout = layoutFor(); + const isotropic = state.style === "isotropic"; + const lowSamples = isotropic ? layout.low : layout.low.samples; + const highSamples = isotropic ? layout.high : layout.high.samples; + const chosen = selection(layout); + const members = new Set(chosen.members); + const {unit} = chosen; + nativeView.panel.hidden = isotropic; + // Published-grid view: photoreceptor cells, pooled cell borders, and the window. + if (!isotropic) { + const highRes = LOW * state.mult; + const {ctx, w, h} = fitCanvas(nativeView.canvas); + const size = Math.min(w, h) - 8; + const ox = (w - size) / 2; + const oy = (h - size) / 2; + const cell = size / highRes; + const windowCells = new Set(poolingWindow(LOW, state.mult, state.side, state.row, state.col).map(([r, c]) => `${r},${c}`)); + for (const s of highSamples) { + const member = windowCells.has(`${s.row},${s.col}`); + ctx.fillStyle = member ? colors.highlight : s.valid ? colors.faint : colors.surface; + ctx.globalAlpha = member && !s.valid ? 0.35 : 1; + ctx.fillRect(ox + s.col * cell + 0.5, oy + s.row * cell + 0.5, Math.max(cell - 1, 0.5), Math.max(cell - 1, 0.5)); + } + ctx.globalAlpha = 1; + for (let k = 0; k <= LOW; k++) { + polyline(ctx, [[ox + (k * size) / LOW, oy], [ox + (k * size) / LOW, oy + size]], colors.muted, 0.6); + polyline(ctx, [[ox, oy + (k * size) / LOW], [ox + size, oy + (k * size) / LOW]], colors.muted, 0.6); + } + ctx.strokeStyle = colors.accent; + ctx.lineWidth = 2.4; + ctx.strokeRect(ox + (state.col * size) / LOW, oy + (state.row * size) / LOW, size / LOW, size / LOW); + nativeView.canvas.onclick = (event) => { + const box = nativeView.canvas.getBoundingClientRect(); + const col = Math.floor(((event.clientX - box.left - ox) / size) * LOW); + const row = Math.floor(((event.clientY - box.top - oy) / size) * LOW); + if (row >= 0 && row < LOW && col >= 0 && col < LOW) { + choose({row, col}); + } + }; + } + const zoomRegion = () => { + const points = chosen.members.map((s) => s.s); + points.push(unit.s); + const xs = points.map((p) => p[0]); + const ys = points.map((p) => p[1]); + const centre = [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2]; + const extent = Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys), 0.002); + return [centre, extent * 1.1]; + }; + // Visual-field views: the whole retina, and the selected sample's neighbourhood. + const drawField = (canvas, centre, radius, showZoomBox) => { + const {ctx, w, h} = fitCanvas(canvas); + const map = fieldTransform(w, h, centre, radius); + const scale = (Math.min(w, h) / 2 - 8) / radius; + const dotHigh = Math.max(0.7, Math.min(3, scale * 0.004 * Math.sqrt(1024 / highSamples.length) * 6)); + const highPoints = highSamples.filter((s) => s.valid); + dots(ctx, highPoints.filter((s) => !members.has(s)).map((s) => map(s.s)), colors.muted, dotHigh, 0.55); + dots(ctx, highPoints.filter((s) => members.has(s)).map((s) => map(s.s)), colors.highlight, dotHigh * 1.4, 1); + dots(ctx, lowSamples.filter((s) => s.valid).map((s) => map(s.s)), colors.accent, dotHigh * 1.2, 0.9); + const u = map(unit.s); + ctx.beginPath(); + ctx.arc(u[0], u[1], dotHigh * 1.2 + 4, 0, TAU); + ctx.strokeStyle = colors.accent; + ctx.lineWidth = 2; + ctx.stroke(); + polyline(ctx, Array.from({length: 181}, (_, k) => map([Math.cos((k * TAU) / 180), Math.sin((k * TAU) / 180)])), colors.camera, 1.2); + if (showZoomBox) { + const [zc, zr] = zoomRegion(); + const corner = map([zc[0] - zr, zc[1] + zr]); + ctx.strokeStyle = colors.ink; + ctx.setLineDash([3, 3]); + ctx.lineWidth = 1; + ctx.strokeRect(corner[0], corner[1], 2 * zr * scale, 2 * zr * scale); + ctx.setLineDash([]); + } + return map; + }; + const map = drawField(fieldView.canvas, [0, 0], 1, true); + fieldView.canvas.onclick = (event) => { + const box = fieldView.canvas.getBoundingClientRect(); + const x = event.clientX - box.left; + const y = event.clientY - box.top; + let best = null; + lowSamples.forEach((s, index) => { + if (!s.valid) { + return; + } + const p = map(s.s); + const d = Math.hypot(p[0] - x, p[1] - y); + if (!best || d < best.d) { + best = {d, s, index}; + } + }); + if (best) { + choose(isotropic ? {unit: best.index} : {row: best.s.row, col: best.s.col}); + } + }; + const [zc, zr] = zoomRegion(); + drawField(zoomView.canvas, zc, zr, false); + const ecc = Math.hypot(unit.s[0], unit.s[1]) * (FOV / 2); + const span = chosen.members.length + ? Math.max(...chosen.members.map((s) => Math.hypot(s.s[0] - unit.s[0], s.s[1] - unit.s[1]))) * (FOV / 2) * 2 + : 0; + if (chosen.pending) { + const reason = isotropicTables && isotropicTables.error ? `could not be loaded (${isotropicTables.error})` : "are loading"; + summary.innerHTML = `fovi's pooling neighbourhoods ${reason}.`; + return; + } + summary.innerHTML = `Pooled sample ${chosen.label} at ${ecc.toFixed(2)}° eccentricity` + + (chosen.valid + ? ` averages ${chosen.members.length} photoreceptors spanning about ${span.toPrecision(2)}°. ` + : " lies outside the retina, so the camera publishes zero there. ") + + chosen.text; + }; + + const choose = (selected) => { + Object.assign(state, selected); + for (const name of Object.keys(selected)) { + inputs[name].value = state[name]; + } + sync(); + }; + + const sync = () => { + const isotropic = state.style === "isotropic"; + for (const element of gridControls) { + element.hidden = isotropic; + } + for (const element of isotropicControls) { + element.hidden = !isotropic; + } + if (isotropic) { + const layout = layoutFor(); + inputs.unit.max = layout.low.length - 1; + state.unit = Math.min(state.unit, layout.low.length - 1); + inputs.unit.value = state.unit; + inputs.k.max = 2 * state.mult * state.mult; + state.k = Math.min(state.k, Number(inputs.k.max)); + inputs.k.value = state.k; + } + outputs.side.textContent = `${state.side} (pool_k=${state.side * state.side})`; + outputs.row.textContent = state.row; + outputs.col.textContent = state.col; + outputs.k.textContent = state.k; + outputs.unit.textContent = state.unit; + redraw(); + }; + inputs.style.addEventListener("input", () => { + state.style = inputs.style.value; + sync(); + }); + inputs.space.addEventListener("input", () => { + state.space = inputs.space.value; + sync(); + }); + inputs.mult.addEventListener("input", () => { + // Keep the default neighbourhood when it was in use: pool_res_mult squared photoreceptors. + const defaultSide = state.side === state.mult; + const defaultK = state.k === state.mult * state.mult; + state.mult = Number(inputs.mult.value); + if (defaultSide) { + state.side = state.mult; + inputs.side.value = state.side; + } + if (defaultK) { + state.k = state.mult * state.mult; + } + sync(); + }); + for (const name of ["side", "row", "col", "k", "unit"]) { + inputs[name].addEventListener("input", () => { + state[name] = Number(inputs[name].value); + sync(); + }); + } + reset.addEventListener("click", () => { + Object.assign(state, defaults); + for (const [name, input] of Object.entries(inputs)) { + input.value = state[name]; + } + sync(); + }); + new ResizeObserver(() => redraw()).observe(panels); + sync(); + }; + + const initialize = () => { + document.querySelectorAll("[data-fovi-sampling-viewer]").forEach(initSamplingViewer); + document.querySelectorAll("[data-fovi-pooling-viewer]").forEach(initPoolingViewer); + }; + + // Exposed for the documentation's geometry checks. + window.FoviViewerGeometry = {warpedGrid, isotropicRings, matchedIsotropicRes, isotropicSamples, ray, gazeRotation, poolingWindow}; + + if (typeof document !== "undefined") { + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", initialize); + } else { + initialize(); + } + } +})(); diff --git a/docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg b/docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg new file mode 100644 index 0000000000000000000000000000000000000000..40d6786c3d163c6288466ef92c1c2a22eededbca GIT binary patch literal 115472 zcmb@t1y~$SmoPd=a3{D0w_w5DJxFjTxVt+9OK>LycZcBa?yiFbcXtTn4kUT^`*!!= zXYYS+^~`j4$+0?BN4n?N{I4GX6e%%DF#s4C000I$0Kb3$VE`lqsDMBJLPA2mf`WsB zdi4ql0R|Qt4haDn2?+ra5g8Q|9T^1!6%i2~7aao&8wUpm84ZsB51RlJ8wdLt2pDK6 z)GH`>C@6Sr6hsv4|JUVLCjb=&9Q~Cm1Q-bb92E=#73^0x0RNfHSI^}BQy?K;K|#ZS zfrDDH!CuNgO`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svL@WI2dsBBG2=uU9Q)L9j2?;QDKy@SDdPSdOY~#Ch)NrGg zn-fU>NQwK4sTmUEDbH_WUbu90mhPNI_N8<1wb~o%r&gfi8}(358Vt<`v>yu>3DlO{ zO;v(LAd|zX3+eaE%|6ldsKt~l<95D);U6W+M3!>op*9mz*svouP!+~B!g@9NgH59R z^3B7Le=^-Z705s1rV7GO`Bb!|Tnv2?am_}F9~*mce>Gypx(Q=%rgdGXw*Kn_8xtmT zf$?@ee_ZwWCWisbyP`ZLys%+0Y0H2o72M<;bXPOq@BD9oO5r{lo%u$+^E-FtB)F>1{C{6^;T^q z!iU+sHQyIRj_kk#`Rx=A9drP~WJCKR-{2(@~$-eN}KSFpI_J!bhq#JQU*G;i8 z(FQjUjOfcg8u?hC|D^=jHj49T$(n!tnYU!CPt5_GidLIfviVy<`p9)vxQc68tfL|? l)5ELR)Zb4(bW8mFZ|9`{>FX}2HxBB5!{I@vix2-j_aAAP$(H~C literal 0 HcmV?d00001 diff --git a/docs/source/_static/overview/sensors/foveated_camera_pooling.jpg b/docs/source/_static/overview/sensors/foveated_camera_pooling.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d5c0ac8ef1bd3e3899eda804ffdf345a00b62c27 GIT binary patch literal 68546 zcmbSy1ymi&((c9y?k)-L?gY2swt?UwxVvjYfZ)O1-GjRXcXti$?*2AO&b{|P|6OmL z_hxGK>^)syb=6Eyb#?X3^X&6a0E(2jq&NT!3;+NF?SSV6fCvB*0JAW%S-wzmBR{{KDt(MTsHUX{u7Zi>Fsj~UL- z3a%gG$8y+f%rV?6oLDQb%*TjLVU(u{l}W4TuFU>1SaC6)S8}iiBk(Z=E9Y9>nO(d5 z+g(Y5pke5x#*)gHMz4wV(d)G7AO28drF2+`icdjZ6^<%QqJ*+p0?Z&a$Bi9Lh01zqU z72TJ>Z{%lL`bd7`g-erj9Eb3p(Rm*&S_m%TjpYjwNpxbxCD$Y5gbc$4sme0X?H50_ zu8Ik&H(4*PIt*0O9NaqJF?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{OYMN)rr+_)-c5io({2_q>46+|R{nT2`>8V%IfZX1 z07XwxB0GoS*!|wNn!g1eN>8ZJ2+)IAXUt&g0~~^>Dwy%OR}dvdj0-$iRVs9VFkXDF zJWq>PfSEYBB|oh5pFOn&FwEOLpyEe1DAUpij< zMYFL*BzYMqWiPF;^L&{zGgWPElWfvgB1^VO6D|i`__ library maps each cell of an upright square grid to a viewing ray. -Moving the gaze rotates these rays relative to the physical camera's mount. +The `fovi `__ library places the viewing rays. Moving the gaze rotates them +relative to the physical camera's mount. .. figure:: ../../_static/overview/sensors/foveated_camera_overview.jpg - :alt: The foveated ray grid and the published images at two fixations. + :alt: The foveated ray grid and its published images at two fixations. - Each pair shows the retinal rays on the viewing sphere and the image published at that fixation. + Each pair shows the retinal rays on the viewing sphere and the image at that fixation. Sampling -------- -At an angular distance :math:`r` from fixation, the cortical magnification is :math:`M(r)=1/(r+a)`. -For a normalized grid radius :math:`\rho` and retinal half-field angle :math:`h`, the ray's angular distance is +The cortical magnification at angular distance :math:`r` from fixation is :math:`M(r) = 1/(r+a)`. +On the default warped Cartesian grid, a lattice point at normalized radius :math:`\rho` samples the eccentricity .. math:: - r(\rho) = a\left[\left(1 + h/a\right)^\rho - 1\right]. + r(\rho) = a\left[\left(1 + h/a\right)^\rho - 1\right], -Smaller :attr:`~sensors.FoveatedCameraCfg.cmf_a_deg` concentrates more samples near fixation. A large value gives -nearly uniform radial angular spacing on the same grid. For a grid of side -:attr:`~sensors.FoveatedCameraCfg.foveated_res`, the camera publishes ``(num_envs, N, N, channels)``. -Cells outside the circular retinal footprint are zero. +where :math:`h` is half the retinal field of view. Smaller :attr:`~sensors.FoveatedCameraCfg.cmf_a_deg` +concentrates more samples near fixation. A large value approaches uniform radial spacing on the same grid. -Camera setup and gaze ---------------------- +The default grid publishes an upright ``(num_envs, N, N, channels)`` image with +``N = foveated_res``. Its circular footprint zeros the unused corners. An isotropic retina places samples +on rings and publishes ``(num_envs, num_samples, 1, channels)``; sample sets are experimental on RTX. +The camera options describe alternate footprints and sampling shells. -Install the ``fovi`` extra to run the camera demo. +.. raw:: html + +

+ +Camera and gaze +--------------- + +Run the demo with the ``fovi`` extra. .. code-block:: bash uv run --extra fovi isaaclab demo foveated-camera -Add a :class:`~sensors.FoveatedCameraCfg` to a scene like any camera configuration. Newton Warp and OptiX render -the sample rays directly. Isaac RTX and OVRTX use lens lookup textures. +Add :class:`~sensors.FoveatedCameraCfg` to a scene like any other camera. Newton Warp and OptiX render the +retinal rays directly. Isaac RTX and OVRTX use lens lookup textures. + +The retinal field of view defaults to the angle across the short side of the physical image. The camera +uses ideal pinhole optics or supported OpenCV distortion from ``spawn``. Supply +:attr:`~sensors.FoveatedCameraCfg.camera_model` for explicit calibration or an existing camera prim. +Use :attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` to shrink this window and +:attr:`~sensors.FoveatedCameraCfg.image_rotation_deg` to compensate for mount roll. + +Call ``camera.set_gaze_angles(angles)`` with shape ``(num_envs, 2)`` in tilt, pan order and in degrees. +Positive tilt looks up and positive pan looks left. :meth:`~sensors.FoveatedCamera.get_world_poses` +reports the mount pose. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero rays that fall +outside the physical image as the gaze moves. + +Pooling +------- + +Enable :attr:`~sensors.FoveatedCameraCfg.pool_enabled` to render a denser set of rays and pool their values +into the published retina. Grid styles pool windows, while sample sets pool nearest neighbours. +The sensor mask excludes rays outside the physical image from the reduction. Segmentation selects the +modal label in its original dtype. -The retinal field of view defaults to the angle spanned by the short side of the physical camera's image. -The camera reads ideal pinhole optics or supported OpenCV distortion from ``spawn``. Supply -:attr:`~sensors.FoveatedCameraCfg.camera_model` for explicit calibration, including when using an existing -camera prim. The :attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` setting shrinks the retinal window. +.. raw:: html -Call ``camera.set_gaze_angles(angles)`` with an array shaped ``(num_envs, 2)`` in tilt, pan order and in degrees. -Positive tilt looks up and positive pan looks left. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` -to zero rays that land outside the physical image at the current gaze. This mask moves relative to the retinal grid -as the gaze changes. +
-Cartpole example ----------------- +Active gaze Cartpole +-------------------- -``IsaacContrib-Cartpole-Camera-Fovi`` uses a 32 × 32 retina and two bounded gaze actions. The actor observes the camera -image and the gaze state. Use ``presets=depth`` to select depth instead of RGB. +``IsaacContrib-Cartpole-Camera-Fovi`` uses a 32 × 32 retina and two bounded gaze actions. A pole-tip teacher +supervises the gaze-action means during training. The gaze dimensions use fixed exploration noise. +Select ``presets=depth`` for depth images. .. code-block:: bash uv run --extra fovi --extra rsl-rl isaaclab train --rl_library rsl_rl --task IsaacContrib-Cartpole-Camera-Fovi -For other manager-based tasks, use :class:`~mdp.GazeActionCfg` to add the tilt and pan actions and -:func:`~mdp.gaze_state` to observe the angles and angular velocity in units of the retinal field radius. +For other manager-based tasks, use :class:`~mdp.GazeActionCfg` to move gaze, :func:`~mdp.gaze_state` to +observe it, and :class:`~mdp.gaze_teacher_labels` for optional supervision. diff --git a/source/isaaclab_fovi/changelog.d/fovi-rtx-lens-setup.skip b/source/isaaclab_fovi/changelog.d/fovi-rtx-lens-setup.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst index afc646183e82..6fe806778a44 100644 --- a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst +++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst @@ -1,4 +1,7 @@ * Introduced ``isaaclab_fovi`` and the ``fovi`` installation extra, providing :class:`~isaaclab_fovi.sensors.FoveatedCamera`, a foveated camera sensor for the Newton (Warp and OptiX), Isaac RTX and OVRTX renderers whose gaze moves inside a physical camera's field of view. -* Added bounded tilt and pan actions and a gaze state observation in :mod:`isaaclab_fovi.mdp`. +* Added active-gaze manager terms in :mod:`isaaclab_fovi.mdp`: a gaze action with a fixed or tracked camera mount, + a gaze observation, and teacher gaze labels. +* Added modal-label pooling for segmentation outputs, which keeps their native dtype (``pool_int_mode="modal"``, + the only accepted value); ``pool_mode`` pools the other outputs and accepts only fovi's modes. diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi index 71c13e7dd674..e78c9a3844e8 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -7,7 +7,12 @@ __all__ = [ "GazeAction", "GazeActionCfg", "gaze_state", + "gaze_teacher_labels", ] -from .gaze import GazeAction, gaze_state +from .gaze import ( + GazeAction, + gaze_state, + gaze_teacher_labels, +) from .gaze_cfg import GazeActionCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index cc09d371f25c..c51f08edfbdb 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -3,20 +3,33 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Bounded tilt and pan actions for a foveated camera.""" +"""Active gaze for a foveated camera: a gaze action, its observation, and a teacher's gaze labels. + +Gaze angles are (tilt, pan) [deg] from the physical camera's optical axis: positive tilt looks up and positive pan +looks left, as for :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles`. The policy moves and observes the +gaze in field radii, half the retina's field of view. Camera-frame directions follow the ROS (OpenCV) convention: +x right, y down, z forward. +""" from __future__ import annotations +import math from typing import TYPE_CHECKING, ClassVar import torch import warp as wp -from isaaclab.managers import ActionTerm +from isaaclab.managers import ActionTerm, ManagerTermBase, ObservationTermCfg, SceneEntityCfg from isaaclab.utils.warp import ProxyArray -from isaaclab.utils.warp.memory import resolve_1d_indices, resolve_ids -from ..sensors.gaze_kernels import record_launch, torch_stream, warp_stream +from ..sensors.gaze_kernels import ( + DEG_TO_RAD, + CameraParams, + project_direction, + project_directions, + record_launch, + warp_stream, +) if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv @@ -24,6 +37,119 @@ from ..sensors import FoveatedCamera from .gaze_cfg import GazeActionCfg +RAD_TO_DEG = 180.0 / math.pi + + +@wp.func +def teach( + point: wp.vec3f, + position: wp.vec3f, + mount: wp.quatf, + g: wp.vec2f, + frame: wp.mat33f, + field_radius_deg: wp.float32, + step_size: wp.float32, + gaze_limit: wp.float32, + camera: CameraParams, +) -> wp.vec4f: + """The teacher's action (x, y) toward a point, 1 for a valid target or else 0, and the gaze's error [deg]. + + ``frame`` carries the upright image frame, in which gazes are measured, into the physical camera's frame. + """ + d = wp.normalize(wp.quat_rotate_inv(mount, point - position)) + # The fixation reaches the physical camera at frame * gaze * z, so the gaze looks along frame^T d. + u = wp.transpose(frame) * d + tilt = -wp.atan2(u[1], wp.sqrt(u[0] * u[0] + u[2] * u[2])) * wp.float32(RAD_TO_DEG) + pan = -wp.atan2(u[0], u[2]) * wp.float32(RAD_TO_DEG) + desired = wp.vec2f(tilt, pan) / field_radius_deg + ok = project_direction(d, camera)[2] > 0.5 and wp.length(desired) <= gaze_limit + step = wp.vec2f(0.0, 0.0) + if ok: + step = wp.vec2f( + wp.clamp((desired[0] - g[0]) / step_size, -1.0, 1.0), wp.clamp((desired[1] - g[1]) / step_size, -1.0, 1.0) + ) + g_tilt = g[0] * field_radius_deg * wp.float32(DEG_TO_RAD) + g_pan = g[1] * field_radius_deg * wp.float32(DEG_TO_RAD) + looking = wp.vec3f(-wp.cos(g_tilt) * wp.sin(g_pan), -wp.sin(g_tilt), wp.cos(g_tilt) * wp.cos(g_pan)) + # atan2 stays accurate near perfect alignment, unlike acos of the dot product. + error = wp.atan2(wp.length(wp.cross(looking, u)), wp.dot(looking, u)) * wp.float32(RAD_TO_DEG) + return wp.vec4f(step[0], step[1], wp.where(ok, 1.0, 0.0), error) + + +@wp.kernel(enable_backward=False) +def teacher_labels_kernel( + targets: wp.array(dtype=wp.vec3f), + orientations: wp.array(dtype=wp.quatf), + offset: wp.vec3f, + positions: wp.array(dtype=wp.vec3f), + mounts: wp.array(dtype=wp.quatf), + angles_deg: wp.array(dtype=wp.vec2f), + frame: wp.mat33f, + field_radius_deg: wp.float32, + step_size: wp.float32, + gaze_limit: wp.float32, + camera: CameraParams, + labels: wp.array2d(dtype=wp.float32), + log: wp.array(dtype=wp.float32), +): + """Labels (action x, action y, valid) toward the point ``offset`` fixed to each target's frame; and the mean gaze + error to valid targets [deg] with the fraction of valid targets. + + ``mounts`` holds each camera's mount (ROS convention); ``angles_deg`` the camera's stored gaze angles [deg]. + One block labels every environment and reduces the logs itself, so the launch needs no zeroed accumulators. + """ + _block, lane = wp.tid() + count = targets.shape[0] + error_sum = wp.float32(0.0) + valid_count = wp.float32(0.0) + i = lane + while i < count: + point = targets[i] + wp.quat_rotate(orientations[i], offset) + gaze = angles_deg[i] / field_radius_deg + result = teach(point, positions[i], mounts[i], gaze, frame, field_radius_deg, step_size, gaze_limit, camera) + labels[i, 0] = result[0] + labels[i, 1] = result[1] + labels[i, 2] = result[2] + if result[2] > 0.5: + error_sum += result[3] + valid_count += 1.0 + i += wp.block_dim() + errors = wp.tile_sum(wp.tile(error_sum)) + valid = wp.tile_sum(wp.tile(valid_count)) + if lane == 0: + log[0] = errors[0] / wp.max(valid[0], 1.0) + log[1] = valid[0] / wp.float32(count) + + +def teacher_block_dim(device: torch.device | str) -> int: + """Threads of the one block that runs :func:`teacher_labels_kernel`; Warp runs CPU blocks as one thread.""" + return 1024 if torch.device(device).type == "cuda" else 1 + + +@wp.kernel(enable_backward=False) +def gaze_reset_kernel( + ids: wp.array(dtype=wp.int32), + use_ids: wp.int32, + start: wp.array(dtype=wp.vec2f), + use_start: wp.int32, + field_radius_deg: wp.float32, + angles_deg: wp.array(dtype=wp.vec2f), + state: wp.array(dtype=wp.vec4f), +): + """Put each reset environment's gaze at its start, or on the optical axis, at rest. + + ``state`` holds each gaze and its velocity, in field radii and field radii per second. + """ + k = wp.tid() + i = k + if use_ids != 0: + i = ids[k] + g = wp.vec2f(0.0, 0.0) + if use_start != 0: + g = start[k] + angles_deg[i] = g * field_radius_deg + state[i] = wp.vec4f(g[0], g[1], 0.0, 0.0) + @wp.kernel(enable_backward=False) def gaze_step_kernel( @@ -57,14 +183,25 @@ def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: class GazeAction(ActionTerm): - """Move gaze by clipped tilt and pan increments within a disk of permitted angles. + """Moves a foveated camera's gaze by bounded steps in (tilt, pan) order. - Angles and increments are in units of the retina's field radius. Reset returns the gaze to the optical axis. - The camera owns the angles. The action reports the gaze and its angular velocity after the last action or reset. + Actions, the limit and the observed gaze are in field radii. An action of 1 changes a coordinate by + ``step_size``, and the gaze stays within ``gaze_limit`` of the optical axis. The gaze starts each episode on the + optical axis, or anywhere the physical camera sees within the limit when ``random_reset`` is set. Gazes are measured + in the upright image frame, which :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.image_rotation_deg` rolls + against a rolled mount. + + With ``mount="fixed"`` the camera keeps the orientation it had when the term was created, and the teacher uses + that mount; turning the camera's mount afterwards raises. With ``mount="tracked"`` the camera may ride a moving + body, for example a robot's head, and the teacher reads each camera's current mount, so software gaze adds to + hardware gaze. + + The camera's stored gaze angles own the gaze: each step and the teacher start from them, so a gaze set directly + with :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles` carries on. :attr:`state`, the observation, is + the gaze and velocity as of the last step or reset. """ cfg: GazeActionCfg - _asset: FoveatedCamera is_graphable: ClassVar[bool] = True """The gaze moves in :meth:`process_actions`, once per environment step; :meth:`apply_actions` does nothing, so @@ -72,31 +209,82 @@ class GazeAction(ActionTerm): def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): super().__init__(cfg, env) - self.field_radius_deg = self._asset.sampling_coords.fov / 2 + camera = self.camera + self.tracked_mount = cfg.mount == "tracked" + if self.tracked_mount and not camera.turns_pose_by_gaze: + raise ValueError( + "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX." + ) + if not self.tracked_mount and camera.cfg.prim_path.rpartition("/")[0] not in ( + "{ENV_REGEX_NS}", + env.scene.env_regex_ns, + ): + # A body's motion turns its camera without set_world_poses, which the fixed mount could not detect. + raise ValueError( + f"A fixed gaze mount needs a camera mounted on the environment, got {camera.cfg.prim_path!r};" + " use mount='tracked' for a camera on a moving body." + ) + # The camera's own geometry, so the teacher and the sensor mask share one projection. + frame = camera.image_frame + self._frame_torch = torch.tensor( + [[frame[row][col] for col in range(3)] for row in range(3)], device=self.device + ) + self.field_radius_deg = camera.sampling_coords.fov / 2 + """Half the retina's field of view [deg].""" + self._fixed_mount = None + if not self.tracked_mount: + # The fixed-mount teacher keeps the camera's mount as it is now; only later turns invalidate it. + mount = camera.ungazed_quat_w_ros() + self._fixed_mount = ProxyArray(wp.from_torch(mount.contiguous(), dtype=wp.quatf)) + self._mount_turns = camera.mount_turns self._raw: torch.Tensor | None = None """Gaze actions of the last step, as supplied to :meth:`process_actions`.""" self._state = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec4f, device=self.device)) """Gaze and its velocity as of the last step or reset, the gaze observation.""" - self._all_ids = wp.from_torch(torch.arange(self.num_envs, dtype=torch.int32, device=self.device)) + self._velocity = self._state.torch[:, 2:] self._step_launch: tuple[tuple, wp.Launch] | None = None + # Each reset copies its environments, and their start gazes if random, into these and replays one launch. + self._reset_ids = ProxyArray(wp.zeros(self.num_envs, dtype=wp.int32, device=self.device)) + self._reset_start = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec2f, device=self.device)) + self._reset_launches: dict[tuple[bool, bool], wp.Launch] = {} @property def action_dim(self) -> int: return 2 + @property + def camera(self) -> FoveatedCamera: + """The foveated camera whose gaze the term moves.""" + return self._asset + @property def raw_actions(self) -> torch.Tensor: - return self._raw if self._raw is not None else torch.zeros_like(self._state.torch[:, :2]) + return self._raw if self._raw is not None else torch.zeros_like(self._velocity) @property def processed_actions(self) -> torch.Tensor: - return self._asset.gaze_angles.torch / self.field_radius_deg + return self.gaze + + @property + def gaze(self) -> torch.Tensor: + """Current gaze in field radii, from the camera's stored angles, shape (num_envs, 2).""" + return self.angles_deg / self.field_radius_deg + + @property + def velocity(self) -> torch.Tensor: + """Gaze velocity in field radii per second, shape (num_envs, 2).""" + return self._velocity @property def state(self) -> torch.Tensor: """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4).""" return self._state.torch + @property + def angles_deg(self) -> torch.Tensor: + """Current gaze angles [deg], the camera's stored ones, shape (num_envs, 2).""" + return self.camera.gaze_angles.torch + def process_actions(self, actions: torch.Tensor): """Move the gaze by the supplied actions, shape (num_envs, 2). @@ -113,7 +301,7 @@ def process_actions(self, actions: torch.Tensor): [ wp.from_torch(actions, dtype=wp.vec2f), self._state, - self._asset.gaze_angles, + self.camera.gaze_angles, self.cfg.step_size, self.cfg.gaze_limit, self._env.step_dt, @@ -124,20 +312,160 @@ def process_actions(self, actions: torch.Tensor): self._step_launch = (key, launch) self._raw = actions self._step_launch[1].launch(warp_stream(self.device)) - self._asset.set_gaze_angles(self._asset.gaze_angles.torch) + self.camera.set_gaze_angles(self.camera.gaze_angles.torch) def apply_actions(self): pass def reset(self, env_ids=None): - """Return the selected cameras to the optical axis, at rest.""" - angles = self._asset.gaze_angles - with torch_stream(self.device): - if env_ids is None: - angles.warp.zero_() - self._state.warp.zero_() + # The action manager zeroes the reset environments' actions itself. + indexed = env_ids is not None + count = self.num_envs + if indexed: + if isinstance(env_ids, slice): + env_ids = torch.arange(*env_ids.indices(self.num_envs), device=self.device) + count = len(env_ids) + if count == 0: + return + self._reset_ids.torch[:count] = torch.as_tensor(env_ids, device=self.device) + random_start = self.cfg.random_reset + if random_start: + gaze = _random_gaze(count, self.cfg.gaze_limit, self.device) + visible = self.visible(_angles_to_direction(gaze * self.field_radius_deg)) + self._reset_start.torch[:count] = torch.where(visible[:, None], gaze, 0.0) + angles = self.camera.gaze_angles + launch = self._reset_launches.get((indexed, random_start)) + if launch is None: + launch = self._reset_launches[(indexed, random_start)] = record_launch( + gaze_reset_kernel, + self.num_envs, + [self._reset_ids, int(indexed), self._reset_start, int(random_start), self.field_radius_deg], + [angles, self._state], + self.device, + ) + launch.set_dim(count) + launch.launch(warp_stream(self.device)) + # The camera keeps reading the same buffer, which every other environment already holds. + self.camera.set_gaze_angles(angles.torch) + + def visible(self, direction: torch.Tensor) -> torch.Tensor: + """Whether directions in the upright gaze frame fall inside the physical camera's image.""" + return project_directions(direction @ self._frame_torch.T, self.camera.projection_params)[1] + + def teacher_mounts(self) -> ProxyArray: + """Each camera's mount (x, y, z, w), ROS convention, that the teacher aims from: the current one when + tracked, else the one captured when the term was created. + + Raises: + RuntimeError: The camera's mount turned while the gaze assumes a fixed mount. + """ + if self.tracked_mount: + return self.camera.mount_quat_w_ros + if self.camera.mount_turns != self._mount_turns: + raise RuntimeError( + "The gaze camera's mount turned, so the fixed-mount teacher would aim from its first orientation;" + " use GazeActionCfg.mount='tracked'." + ) + return self._fixed_mount + + +class gaze_teacher_labels(ManagerTermBase): + """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3). + + A training label, never a policy input. One launch labels every environment and logs the mean gaze error to valid + targets and the fraction of valid targets. + + Args: + target_cfg: The asset, and optionally one body by ``body_names``. + offset: The point in the root's or the body's frame [m]. + action_name: The gaze action term. + """ + + def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._gaze: GazeAction = env.action_manager.get_term(cfg.params.get("action_name", "gaze")) + self._labels = ProxyArray(wp.zeros((env.num_envs, 3), dtype=wp.float32, device=env.device)) + self._log = ProxyArray(wp.zeros(2, dtype=wp.float32, device=env.device)) + """Mean gaze error to valid targets [deg] and the fraction of valid targets.""" + self._offset: tuple[tuple[float, ...], wp.vec3f] | None = None + self._sources = None + self._targets = self._orientations = None + self._launch: tuple[tuple, wp.Launch] | None = None + + def __call__( + self, + env: ManagerBasedEnv, + target_cfg: SceneEntityCfg, + offset: tuple[float, float, float] = (0.0, 0.0, 0.0), + action_name: str = "gaze", + ) -> torch.Tensor: + data = env.scene[target_cfg.name].data + # Reading the properties refreshes the asset's pose buffers; their Warp views are wrapped once. + if target_cfg.body_names is None: + positions, orientations = data.root_pos_w, data.root_quat_w + else: + positions, orientations = data.body_pos_w, data.body_quat_w + if self._sources != (id(positions), id(orientations)): + self._sources = (id(positions), id(orientations)) + if target_cfg.body_names is None: + self._targets, self._orientations = positions.warp, orientations.warp else: - indices = resolve_1d_indices(resolve_ids(ids=env_ids, all_ids=self._all_ids)) - wp.indexedarray(angles.warp, indices).zero_() - wp.indexedarray(self._state.warp, indices).zero_() - self._asset.set_gaze_angles(angles.torch) + body = target_cfg.body_ids[0] + self._targets = wp.from_torch(positions.torch[:, body], dtype=wp.vec3f) + self._orientations = wp.from_torch(orientations.torch[:, body], dtype=wp.quatf) + point = tuple(float(value) for value in offset) + if self._offset is None or self._offset[0] != point: + self._offset = (point, wp.vec3f(*point)) + gaze = self._gaze + mounts = gaze.teacher_mounts() + camera_positions = gaze.camera.data.pos_w.warp + # The launch is recorded once and recorded again only when one of its arrays or the point changes. + sources = (self._targets, self._orientations, camera_positions, mounts, self._offset[1]) + if self._launch is None or any(a is not b for a, b in zip(self._launch[0], sources)): + block = teacher_block_dim(env.device) + launch = record_launch( + teacher_labels_kernel, + (1, block), + [ + self._targets, + self._orientations, + self._offset[1], + camera_positions, + mounts, + gaze.camera.gaze_angles, + gaze.camera.image_frame, + gaze.field_radius_deg, + gaze.cfg.step_size, + gaze.cfg.gaze_limit, + gaze.camera.projection_params, + ], + [self._labels, self._log], + env.device, + block_dim=block, + ) + self._launch = (sources, launch) + self._launch[1].launch(warp_stream(env.device)) + _log_teacher(env, self._log.torch) + return self._labels.torch + + +def _log_teacher(env: ManagerBasedEnv, values: torch.Tensor) -> None: + """Log the mean gaze error to valid targets and the fraction of valid targets.""" + # Loggers keep each step's entries, so they get a copy rather than the buffer the next step overwrites. + error, fraction = values.clone() + log = env.extras.setdefault("log", {}) + log["Gaze/target_error_deg"] = error + log["Gaze/valid_target_fraction"] = fraction + + +def _angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3).""" + tilt, pan = angles_deg.deg2rad().unbind(-1) + return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + + +def _random_gaze(count: int, limit: float, device: torch.device | str | None = None) -> torch.Tensor: + """Gazes drawn uniformly over the disc of radius ``limit``, shape (count, 2).""" + radius = limit * torch.rand(count, device=device).sqrt() + angle = 2 * math.pi * torch.rand(count, device=device) + return torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py index c038da8533e9..0318605a11fc 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py @@ -28,11 +28,21 @@ class GazeActionCfg(ActionTermCfg): step_size: float = 0.1 """Change of each gaze coordinate per step at an action of 1, in field radii. Positive and finite.""" gaze_limit: float = 1.0 - """Radius of the allowed tilt/pan disk, in field radii. Positive and finite.""" + """Largest distance of the gaze from the camera's optical axis, in field radii. Positive and finite.""" + random_reset: bool = False + """Start episodes at a random gaze the camera sees; otherwise on the optical axis.""" + mount: str = "fixed" + """Teacher's mount: ``"fixed"`` at the action's creation, or ``"tracked"`` on a moving body (Newton, OVRTX).""" def validate_config(self): - """Reject gaze bounds that would divide by zero.""" - if not math.isfinite(self.step_size) or self.step_size <= 0: + """Reject gaze bounds that would divide by zero and unknown mounts.""" + if not _positive_finite(self.step_size): raise ValueError(f"GazeActionCfg.step_size must be positive and finite, got {self.step_size!r}.") - if not math.isfinite(self.gaze_limit) or self.gaze_limit <= 0: + if not _positive_finite(self.gaze_limit): raise ValueError(f"GazeActionCfg.gaze_limit must be positive and finite, got {self.gaze_limit!r}.") + if self.mount not in ("fixed", "tracked"): + raise ValueError(f"GazeActionCfg.mount must be 'fixed' or 'tracked', got {self.mount!r}.") + + +def _positive_finite(value) -> bool: + return isinstance(value, (int, float)) and math.isfinite(value) and value > 0 diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index c2f417286094..d499139eec0c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -8,13 +8,13 @@ from __future__ import annotations import math +from typing import Protocol -from fovi.sensing.projection import CameraCalibration, CameraModel +import torch +from fovi.sensing.projection import CameraCalibration, CameraModel, angular_directions from isaaclab.sim import PinholeCameraCfg -from .foveated_camera_cfg import FoveatedCameraCfg - IDEAL_IMAGE_WIDTH = 1024 """Pixel width [px] of the image assigned to a camera derived from ideal spawn optics. @@ -79,7 +79,7 @@ def camera_model_from_spawn(spawn: PinholeCameraCfg) -> CameraCalibration: ) -def resolve_camera_model(cfg: FoveatedCameraCfg) -> CameraModel: +def resolve_camera_model(cfg: SamplingGeometryConfig) -> CameraModel: """Return the physical camera the retina looks through. This is ``cfg.camera_model`` when set, otherwise the camera that ``cfg.spawn`` @@ -93,3 +93,41 @@ def resolve_camera_model(cfg: FoveatedCameraCfg) -> CameraModel: if cfg.spawn is None: raise ValueError("A foveated camera on an existing prim needs camera_model.") return CameraModel(**camera_model_from_spawn(cfg.spawn)) + + +def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: + """Return the retinal field of view and the CMF constant, both in degrees. + + The field of view is the angular span of the retinal window in the physical + camera. Both values are in the units :class:`fovi.sensing.coords.SamplingCoords` takes. + """ + fov = resolve_camera_model(cfg).field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_fraction) + return fov, cfg.cmf_a_deg + + +def retinal_directions(cartesian: torch.Tensor, fov_deg: float, image_rotation_deg: float = 0.0) -> torch.Tensor: + """Return OpenGL-frame angular rays, including the sensor mount roll.""" + rays = angular_directions(cartesian, fov_deg) + rays = rays * rays.new_tensor((1, -1, -1)) + angle = rays.new_tensor(image_rotation_deg * torch.pi / 180) + x, y, z = rays.unbind(-1) + return torch.stack((angle.cos() * x - angle.sin() * y, angle.sin() * x + angle.cos() * y, z), -1) + + +def compose_rotations(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor: + """Compose small rotation matrices without TF32 tensor-core rounding. + + Camera transforms need orthonormal rotations even when the surrounding + training process enables reduced-precision matrix multiplication. + """ + return (left[..., :, :, None] * right[..., None, :, :]).sum(dim=-2) + + +class SamplingGeometryConfig(Protocol): + """The configuration fields that place the retina in the physical camera.""" + + camera_model: CameraCalibration | None + cmf_a_deg: float + retinal_window_reference_side: str + retinal_window_fraction: float + spawn: PinholeCameraCfg | None diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 1f95dc30d24c..28af5b3b8ad7 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -14,15 +14,13 @@ import torch import warp as wp -from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel from isaaclab.sensors.camera.camera import Camera -from isaaclab.utils import clone -from isaaclab.utils.math import convert_camera_frame_orientation_convention +from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_error_magnitude from isaaclab.utils.warp import ProxyArray -from .calibrated_geometry import resolve_camera_model +from .calibrated_geometry import resolve_camera_model, retinal_directions from .gaze_kernels import ( CameraParams, apply_gaze_indexed_kernel, @@ -30,14 +28,24 @@ camera_params, publish_grid_kernel, record_launch, + sensor_visibility_kernel, set_gaze_kernel, warp_stream, ) -from .native_grid import native_grid_directions +from .native_grid import GRID_STYLE, buffer_tensor, native_grid_directions +from .pooling import ( + is_segmentation_output, + pool_hwc_buffer, + pool_segmentation_buffer, + segmentation_neighbor_indices, +) if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg +MOUNT_TURN_TOLERANCE_RAD = 1e-5 +"""Smallest change of a camera's mount orientation [rad] that counts as a turn; smaller ones are float rounding.""" + OPENGL_TO_ROS_AXES = (1.0, -1.0, -1.0) """Axis signs between OpenGL camera-frame directions (x right, y up, -z forward) and ROS ones (x right, y down).""" @@ -97,40 +105,67 @@ def __init__(self, cfg: FoveatedCameraCfg): """ self._gaze_pose_reads_angles = self._pose_update_turns_gaze(cfg) """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses - when the gaze is set.""" + when the gaze is set; see :attr:`turns_pose_by_gaze`.""" if self._gaze_pose_reads_angles and not cfg.update_latest_camera_pose: raise ValueError( "Newton and OVRTX turn the rendered pose by the gaze in each pose update; set" " update_latest_camera_pose=True so the renderer sees the gaze." ) # The parent's initialisation updates poses before the gaze exists. + self._gaze_written = False self._gaze_angles: ProxyArray | None = None self._gaze_rotation: ProxyArray | None = None - cfg = clone(cfg) - cfg.width = cfg.height = cfg.foveated_res - self._camera_model = resolve_camera_model(cfg) - fov = self._camera_model.field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_fraction) - self._sampling_coords = SamplingCoords( - fov=fov, - cmf_a=cfg.cmf_a_deg, - res=cfg.foveated_res, - style="warped_cartesian_as_grid", - field_geometry="spherical", - device="cpu", - ) - self._retinal_rays = native_grid_directions(self._sampling_coords, image_rotation_deg=cfg.image_rotation_deg) + self._visibility = None + self._grid_publish = None + self._published_shape: tuple[int, int] | None = None + self._segmentation_neighbors: torch.Tensor | None = None + self._sensor_fov_valid: torch.Tensor | None = None + self.mount_turns = 0 + """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount.""" super().__init__(cfg) @property - def sampling_coords(self) -> SamplingCoords: + def image_shape(self) -> tuple[int, int]: + """(height, width) of the published outputs: the retina's grid, or (num_samples, 1) for sample sets.""" + return self._published_shape if self._published_shape is not None else super().image_shape + + @property + def sampling_coords(self): """The :class:`SamplingCoords` of the published samples.""" return self._sampling_coords + @property + def num_valid_samples(self) -> int: + """Number of published foveated samples.""" + return self._num_valid_samples + + @property + def sensor_fov_valid_fraction(self) -> torch.Tensor | None: + """Per-environment fraction of samples inside the physical camera, or None before the first masked frame.""" + return None if self._sensor_fov_valid is None else self._sensor_fov_valid.float().mean(dim=1) + @property def camera_model(self) -> CameraModel: """The physical camera the retina looks through, as resolved at initialization.""" return self._camera_model + @property + def projection_params(self) -> CameraParams: + """:attr:`camera_model` as a Warp struct, for kernels that project camera-frame directions.""" + return self._gaze_camera + + @property + def image_frame(self) -> wp.mat33f: + """Rotation from the upright image frame, in which gazes are measured, to the physical camera's frame (ROS + convention); it undoes ``cfg.image_rotation_deg``.""" + return self._mask_frame + + @property + def turns_pose_by_gaze(self) -> bool: + """Whether each pose update turns the rendered pose by the stored gaze (Newton and OVRTX). A writer of + :attr:`gaze_angles` then needs no other launch.""" + return self._gaze_pose_reads_angles + @property def gaze_angles(self) -> ProxyArray: """The camera's stored gaze angles [deg], shape (num_envs,) of ``vec2f`` (Torch view (num_envs, 2)). @@ -142,6 +177,20 @@ def gaze_angles(self) -> ProxyArray: self._allocate_gaze() return self._gaze_angles + @property + def mount_quat_w_ros(self) -> ProxyArray: + """World orientation (x, y, z, w) of the physical camera before the gaze turns it, ROS convention, shape + (num_envs,) of ``quatf``. + + Refreshed by each pose update that turns the gaze, so it follows a mount that moves, for example a camera on + a robot's head. Only cameras whose pose update turns the gaze (Newton and OVRTX) record it. + """ + if not self._gaze_pose_reads_angles: + raise RuntimeError("Only cameras whose pose update turns the gaze (Newton, OVRTX) record their mount.") + if self._gaze_angles is None: + self._allocate_gaze() + return self._mount_quat_ros + def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. @@ -155,7 +204,7 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: ValueError: The angles do not hold one row per camera. """ stored = self._gaze_angles is not None and angles_deg is self._gaze_angles.torch - if stored and self._gaze_pose_reads_angles: + if stored and self.turns_pose_by_gaze: # The next pose update reads the stored angles; nothing has to happen now. return count = self._view.count @@ -175,6 +224,43 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: gaze.device, ) self._set_gaze_launch.launch(warp_stream(gaze.device)) + self._gaze_written = True + + def ungazed_quat_w_ros(self) -> torch.Tensor: + """World orientation (x, y, z, w) of the physical camera now, before the gaze turns it, ROS convention, shape + (num_envs, 4).""" + if self._gaze_pose_reads_angles and self._gaze_angles is not None: + # The record starts at the pose before any gaze and follows each pose update. + return self._mount_quat_ros.torch.clone() + if self._gaze_written: + # The prims hold the gaze (Isaac RTX); get_world_poses reports the mount without it. + return self.get_world_poses(convention="ros")[1] + return self._data.quat_w_ros.torch.clone() + + def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): + """Move the camera's mount; the gaze stays relative to the new mount. + + Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. + """ + if orientations is None: + # A position-only move keeps every mount's orientation. + super().set_world_poses(positions, orientations, env_ids, convention) + return + before = self._mount_orientations(env_ids) + super().set_world_poses(positions, orientations, env_ids, convention) + self._mount_written(env_ids) + self._count_mount_turn(before, env_ids) + + def set_world_poses_from_view(self, eyes, targets, env_ids=None): + """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. + + Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. + """ + before = self._mount_orientations(env_ids) + super().set_world_poses_from_view(eyes, targets, env_ids) + # Rows whose eye equals their target are skipped by the base method and keep their poses. + self._mount_written(self._env_indices(env_ids)[self._turned_by_view(eyes, targets)]) + self._count_mount_turn(before, env_ids) def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): """Keep the camera as configured and warn the caller. @@ -195,35 +281,52 @@ def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): ) def _initialize_gaze(self) -> None: - """Move the canonical rays to the sensor device and prepare camera-frame conversions.""" - self._sampling_coords = self._sampling_coords.to(device=self._device) - self._retinal_rays = self._retinal_rays.to(device=self._device) + """Prepare the gaze geometry: the rendered rays in the physical camera's frame and the pose conversions.""" + self._camera_model = resolve_camera_model(self.cfg) + self._gaze_camera = camera_params(self._camera_model) + coords = self._sampling_coords_highres or self._sampling_coords + rotation_deg = self.cfg.image_rotation_deg + # The rays as rendered, mount roll included, in the ROS frame the camera model projects. + if coords.style == GRID_STYLE: + rays = native_grid_directions(coords, image_rotation_deg=rotation_deg) + else: + rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) + self._gaze_rays = (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() + # No gaze until one is set: the camera looks along its optical axis untouched. self._gaze_angles = None self._gaze_rotation = None - rotation_deg = self.cfg.image_rotation_deg + self._visibility = None + device = self._gaze_rays.device + self._gaze_identity = torch.eye(3, device=device) angle = math.radians(rotation_deg) c, s = math.cos(angle), math.sin(angle) # Gaze is defined in the upright image frame; the basis carries it into the rolled OpenGL camera frame. - self._gaze_basis = self._retinal_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) + self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1))) # The same roll in the ROS frame: a rendered ray r reaches the physical camera at K gaze K^T r. self._mask_frame = wp.mat33f(c, s, 0.0, -s, c, 0.0, 0.0, 0.0, 1.0) # Fixed right-multiplied frame changes, on the CPU in float64, where no reduced-precision matmul applies. identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], dtype=torch.float64) to_opengl = convert_camera_frame_orientation_convention(identity, origin="world", target="opengl")[0].tolist() to_world = convert_camera_frame_orientation_convention(identity, origin="opengl", target="world")[0].tolist() + to_ros = convert_camera_frame_orientation_convention(identity, origin="world", target="ros")[0].tolist() self._gaze_frames = ( wp.mat33f(*self._gaze_basis.flatten().tolist()), wp.quatf(*to_opengl), wp.quatf(*to_world), + wp.quatf(*to_ros), ) def _allocate_gaze(self) -> None: - """Allocate one stored gaze per camera, on the optical axis, and its rotation on the sensor device.""" + """Allocate one stored gaze per camera, on the optical axis, its rotation and the mount, on the sensor + device.""" count, device = self._view.count, str(self._device) self._gaze_angles = ProxyArray(wp.zeros(count, dtype=wp.vec2f, device=device)) self._gaze_rotation = ProxyArray( wp.from_torch(torch.eye(3, device=device).repeat(count, 1, 1), dtype=wp.mat33f) ) + # No gaze has turned the pose yet, so the current orientation is the mount. + mount = self._data.quat_w_ros.torch.clone() + self._mount_quat_ros = ProxyArray(wp.from_torch(mount, dtype=wp.quatf)) self._gaze_angles_key = None self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {} self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=device) @@ -246,13 +349,13 @@ def _update_camera_state( def _apply_gaze_pose( self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None ) -> None: - """Turn the camera's world orientation by the stored gaze, and record the gaze rotations.""" + """Turn the camera's world orientation by the stored gaze, and record the gaze rotations and the mount.""" if self._gaze_angles is None: return orientation = self._data.quat_w_world.warp device = self._gaze_angles.torch.device frames = (self._gaze_angles, *self._gaze_frames) - outputs = [orientation, self._gaze_rotation] + outputs = [orientation, self._gaze_rotation, self._mount_quat_ros] indexed = env_ids is not None and env_mask is None if indexed: # The kernel takes contiguous int32 indices; this converts sequences, slices, tensors and Warp arrays. @@ -275,62 +378,191 @@ def _apply_gaze_pose( launch.set_dim(len(env_ids)) launch.launch(warp_stream(device)) - def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: - """Allocate upright public buffers and bind byte views of the renderer's native grid.""" - coords = self._sampling_coords - indices = torch.arange(len(coords), dtype=torch.int32, device=self._device) - self._grid_indices_wp = wp.from_torch(coords.as_grid(indices).reshape(-1).contiguous()) - self._grid_footprint_wp = wp.from_torch(coords.valid_mask.contiguous()) - # Rendered OpenGL rays become physical-camera ROS rays for the calibrated mask. - rays = self._retinal_rays * self._retinal_rays.new_tensor(OPENGL_TO_ROS_AXES) - self._grid_rays_wp = wp.from_torch(rays, dtype=wp.vec3f) - self._grid_camera = camera_params(self._camera_model) if self.cfg.mask_to_sensor_fov else CameraParams() - self._grid_identity = wp.from_torch( - torch.eye(3, device=self._device).repeat(self._view.count, 1, 1), dtype=wp.mat33f - ) + def _mount_orientations(self, env_ids) -> torch.Tensor: + """The selected cameras' mount orientations (x, y, z, w), world convention, as :meth:`get_world_poses` reports + them.""" + return self.get_world_poses(env_ids, convention="world")[1].clone() + + def _mount_written(self, env_ids) -> None: + """Called after a pose write turned the selected cameras' mounts, before the turn is measured. Cameras that + hold the gaze in their prims write it onto the new mounts here.""" + + def _count_mount_turn(self, before: torch.Tensor, env_ids) -> None: + """Count a mount turn if any selected camera's mount now differs from ``before``. + + The teachers read the camera's live position, so only orientation changes count, and writing back the reported + poses does not. + """ + turned = quat_error_magnitude(before, self._mount_orientations(env_ids)) > MOUNT_TURN_TOLERANCE_RAD + if bool(turned.any()): + self.mount_turns += 1 + + def _env_indices(self, env_ids) -> torch.Tensor: + """The camera indices that ``env_ids`` selects, as a tensor.""" + if env_ids is None: + return torch.arange(self._view.count, device=self._device) + if isinstance(env_ids, slice): + return torch.arange(self._view.count, device=self._device)[env_ids] + if isinstance(env_ids, wp.array): + env_ids = wp.to_torch(env_ids) + return torch.as_tensor(env_ids, device=self._device, dtype=torch.long).reshape(-1) + + def _turned_by_view(self, eyes, targets) -> torch.Tensor: + """Which rows :meth:`set_world_poses_from_view` turns: the base method skips an eye equal to its target.""" + return (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0 + + def _visibility_buffers(self) -> dict: + """The sensor mask's camera-owned buffers, allocated once: the rendered rays, an unturned rotation per camera, + each sample's visibility and, for the updated rows, which samples to hide.""" + if self._visibility is None: + count, device = self._view.count, self._gaze_rays.device + shape = (count, len(self._gaze_rays)) + self._visibility = { + "rays": wp.from_torch(self._gaze_rays, dtype=wp.vec3f), + "identity": wp.from_torch(self._gaze_identity.expand(count, -1, -1).contiguous(), dtype=wp.mat33f), + "every_env": wp.ones(count, dtype=wp.bool, device=str(device)), + "valid": ProxyArray(wp.zeros(shape, dtype=wp.bool, device=str(device))), + "hidden": ProxyArray(wp.zeros(shape, dtype=wp.bool, device=str(device))), + "launch": None, + } + return self._visibility + + def _gaze_validity(self, env_mask: wp.array | None = None) -> torch.Tensor: + """Which samples the physical camera sees at each updated environment's gaze, shape (num_envs, num_samples). + + Each rendered ray is tested by its center direction. Environments outside ``env_mask`` keep their last + visibility; None updates every one. + """ + buffers = self._visibility_buffers() + rotation = buffers["identity"] if self._gaze_rotation is None else self._gaze_rotation.warp + updated = buffers["every_env"] if env_mask is None else env_mask + cached = buffers["launch"] + if cached is None or cached[0] is not rotation or cached[1] is not updated: + launch = record_launch( + sensor_visibility_kernel, + buffers["valid"].warp.shape, + [buffers["rays"], rotation, self._mask_frame, self._gaze_camera, updated], + [buffers["valid"], buffers["hidden"]], + self._gaze_rays.device, + ) + buffers["launch"] = cached = (rotation, updated, launch) + cached[2].launch(warp_stream(self._gaze_rays.device)) + return buffers["valid"].torch + + def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor], env_mask: wp.array | None = None) -> None: + """Zero the samples outside the physical camera at the current gaze in the updated environments' (B, N, 1, C) + outputs; None updates every environment.""" + if not self.cfg.mask_to_sensor_fov: + return + tensors = {name: buffer_tensor(value) for name, value in outputs.items()} + self._sensor_fov_valid = self._gaze_validity(env_mask) + hidden = self._visibility["hidden"].torch[:, :, None, None] + for name, tensor in tensors.items(): + if name == "rgb" and "rgba" in tensors: + continue + tensor.masked_fill_(hidden, 0) + + def _prepare_segmentation_pooling(self, names) -> None: + """Take the modal-label neighbourhoods of pooled segmentation outputs among ``names`` from the main pooler.""" + self._segmentation_neighbors = None + if self._pooler is not None and any(is_segmentation_output(name) for name in names): + self._segmentation_neighbors = segmentation_neighbor_indices(self._pooler) + + def _pool_output(self, name: str, samples: torch.Tensor) -> torch.Tensor: + """Pool one output's high-resolution samples (B, N_hi, 1, C) to the retina's (B, N_lo, 1, C), in its dtype. - outputs = {} - self._grid_publish = [] + Segmentation takes each sample's modal label in its native dtype; other outputs are pooled in float with + ``pool_mode``. With :attr:`~FoveatedCameraCfg.mask_to_sensor_fov`, photoreceptors outside the physical camera's + image at the current gaze are left out, so a pooled sample at the image edge is not darkened by them. + """ + visible = self._visibility["valid"].torch if self.cfg.mask_to_sensor_fov else None + if is_segmentation_output(name): + return pool_segmentation_buffer(self._segmentation_neighbors, samples, visible) + pooled = pool_hwc_buffer(self._pooler, samples.float(), visible) + if not samples.dtype.is_floating_point: + # Round to the nearest value the output can hold, e.g. 0-255 for RGB, rather than truncating. + limits = torch.iinfo(samples.dtype) + pooled = pooled.round().clamp(limits.min, limits.max) + return pooled.to(samples.dtype) + + def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None: + """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for + :func:`publish_grid_kernel`.""" + views = [] for name, source in sources.items(): if name == "rgb" and "rgba" in sources: continue - count, _, _, channels = source.shape - target = torch.zeros_like(source, memory_format=torch.contiguous_format) - self._grid_publish.append( - ( - wp.from_torch(source.view(count, -1, channels).view(torch.uint8)), - wp.from_torch(target.view(count, -1, channels).view(torch.uint8)), - ) + target = self._grid_output[name].view(source.shape[0], -1, source.shape[-1]) + views.append((wp.from_torch(source.view(torch.uint8)), wp.from_torch(target.view(torch.uint8)))) + self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous()) + self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous()) + num_envs = views[0][1].shape[0] + if self.cfg.mask_to_sensor_fov: + buffers = self._visibility_buffers() + self._grid_every_env = buffers["every_env"] + self._grid_sensor = ( + buffers["rays"], + buffers["identity"], + self._mask_frame, + self._gaze_camera, + buffers["valid"].warp, + ) + else: + self._grid_every_env = wp.ones(num_envs, dtype=wp.bool, device=str(self._device)) + # Placeholders: the kernel reads none of these without the sensor mask. + self._grid_sensor = ( + wp.zeros(1, dtype=wp.vec3f, device=self._device), + wp.zeros(1, dtype=wp.mat33f, device=self._device), + wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0), + CameraParams(), + wp.zeros((1, 1), dtype=wp.bool, device=self._device), ) - outputs[name] = target - if "rgb" in sources and "rgba" in sources: - outputs["rgb"] = outputs["rgba"][..., :3] - self._data._output = {name: ProxyArray(wp.from_torch(value)) for name, value in outputs.items()} + self._grid_publish = views self._grid_launches = None - def _publish_grid(self, env_mask: wp.array) -> None: - """Mask and publish the upright grid for the updated environments.""" - rotation = self._grid_identity if self._gaze_rotation is None else self._gaze_rotation.warp + def _publish_grid(self, env_mask: wp.array | None = None) -> None: + """Mask and lay out every output of the updated environments in one launch each; the result equals masking, + then copying to the grid. The other environments keep their last published frame; None updates every one.""" + mask = self.cfg.mask_to_sensor_fov + env_mask = self._grid_every_env if env_mask is None else env_mask + rays, identity, frame, camera, visible = self._grid_sensor + rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation.warp cached = self._grid_launches - if cached is None or cached[0] is not rotation or cached[1] is not env_mask: - inputs = [ - self._grid_indices_wp, - self._grid_footprint_wp, - env_mask, - self._grid_rays_wp, - rotation, - self._mask_frame, - self._grid_camera, - int(self.cfg.mask_to_sensor_fov), - ] + if cached is None or cached[0][0] is not rotation or cached[0][1] is not env_mask: launches = [ - record_launch(publish_grid_kernel, target.shape[:2], [source, *inputs], [target], self._device) - for source, target in self._grid_publish + record_launch( + publish_grid_kernel, + (target.shape[0], target.shape[1]), + [ + source, + self._grid_indices_wp, + self._grid_footprint_wp, + env_mask, + rays, + rotation, + frame, + camera, + int(mask), + int(mask and index == 0), + visible, + ], + [target], + self._device, + ) + for index, (source, target) in enumerate(self._grid_publish) ] - self._grid_launches = cached = (rotation, env_mask, launches) + self._grid_launches = ((rotation, env_mask), launches) stream = warp_stream(self._device) - for launch in cached[2]: + for launch in self._grid_launches[1]: launch.launch(stream) + if mask: + self._sensor_fov_valid = self._visibility["valid"].torch + + def _set_published_shape(self, outputs: Mapping[str, torch.Tensor]) -> None: + """Report the (height, width) of the published outputs, which differ from the rendered ones.""" + tensor = next(iter(outputs.values())).torch + self._published_shape = (int(tensor.shape[1]), int(tensor.shape[2])) + self._data.image_shape = self._published_shape @staticmethod def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 9cbdf77391ce..c4039eabcee6 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -7,8 +7,10 @@ from __future__ import annotations +import math from typing import TYPE_CHECKING +from fovi.sensing.coords import RADIUS_NORMS, WARPED_CARTESIAN_STYLES from fovi.sensing.projection import CameraCalibration from isaaclab.sensors.camera.camera_cfg import CameraCfg @@ -18,6 +20,23 @@ from .foveated_camera import FoveatedCamera +POOL_MODES = ("avg", "gaussian", "max", "sum") +"""fovi pooling modes for the outputs other than segmentation.""" + +SEGMENTATION_POOL_MODES = ("modal",) +"""Pooling modes for segmentation outputs: the modal label only.""" + + +def validate_radius_norm(radius_norm: float, style: str, fov_type: str) -> None: + """Reject warped-grid radius norms that fovi cannot sample, before renderer startup.""" + if radius_norm not in RADIUS_NORMS: + raise ValueError(f"radius_norm must be one of {RADIUS_NORMS}, got {radius_norm!r}.") + if radius_norm != 2.0 and style not in WARPED_CARTESIAN_STYLES: + raise ValueError("Non-default radius_norm requires a warped_cartesian style.") + if radius_norm == math.inf and fov_type == "wang": + raise ValueError("radius_norm=inf does not support fov_type='wang'.") + + @configclass class FoveatedCameraCfg(CameraCfg): """Configuration for a foveated camera, whose retina samples densely where it looks and sparsely in the periphery. @@ -36,7 +55,19 @@ class FoveatedCameraCfg(CameraCfg): """The physical camera as ``CameraModel`` fields; None uses the camera that :attr:`spawn` creates.""" foveated_res: int = 60 - """Side length of the published warped-Cartesian grid.""" + """Grid side of the retina; isotropic retinas use as many rings as keep at most its square of samples.""" + + foveated_style: str = "warped_cartesian_as_grid" + """Sampling style: the default grid publishes an upright image; sample-set styles publish a list of samples.""" + + fov_type: str = "circular" + """Region of the visual field the retina covers: ``"circular"``, ``"square"`` or ``"wang"``.""" + + radius_norm: float = 2.0 + """Norm of the warped-Cartesian sampling shells: 2.0 for circular shells, infinity for square ones.""" + + isotropic_plotting_type: str = "v1like" + """Cortical layout of an isotropic retina's samples: ``"v1like"``, ``"schwartz"`` or ``"warp"``.""" image_rotation_deg: float = 0.0 """Counter-clockwise roll [deg] of the rays about the optical axis that undoes a rolled mount.""" @@ -50,6 +81,29 @@ class FoveatedCameraCfg(CameraCfg): retinal_window_reference_side: str = "short" """Image side defining the retinal window diameter: ``short`` or ``long``.""" + # -- Optional retinal pooling (photoreceptor -> RGC two-layer sampling) -- + + pool_enabled: bool = False + """Render a denser photoreceptor grid and pool it to the retina.""" + + pool_res_mult: float = 2 + """How many times denser the photoreceptor grid is than the retina; an integer for grid styles.""" + + pool_k: int | None = None + """Photoreceptors each sample pools: a square window's area for grid styles, else nearest neighbours.""" + + pool_mode: str = "avg" + """Pooling of non-segmentation outputs: ``"avg"``, ``"gaussian"``, ``"max"``, or ``"sum"`` for sample sets.""" + + pool_sample_cortex: bool | str = "geodesic" + """Neighbour distance for sample sets: ``"geodesic"`` on the cortex, ``True`` cortical, ``False`` visual.""" + + pool_gauss_sigma: float = 10.0 + """Gaussian sigma for ``pool_mode="gaussian"``.""" + + pool_int_mode: str = "modal" + """Pooling of segmentation outputs: ``"modal"``, each sample's most common label among its neighbours.""" + # -- RTX-specific parameters (ignored by Newton backend) ---------------- exit_texture_size: int | None = None @@ -62,3 +116,17 @@ class FoveatedCameraCfg(CameraCfg): update_latest_camera_pose: bool = True """Update the camera pose every frame. Newton and OVRTX require it: their pose update applies the gaze.""" + + def __post_init__(self): + # Resolves the default renderer and forwards deprecated renderer fields. + super().__post_init__() + validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) + if self.pool_mode not in POOL_MODES: + raise ValueError( + f"pool_mode must be one of {POOL_MODES}, got {self.pool_mode!r}; segmentation pools with pool_int_mode." + ) + if self.pool_int_mode not in SEGMENTATION_POOL_MODES: + raise ValueError( + f"pool_int_mode must be one of {SEGMENTATION_POOL_MODES}, got {self.pool_int_mode!r}: segmentation" + " pools by modal label, since other modes would mix labels into ones no object has." + ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 5df9df3f4a22..f86bfeb479a9 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -3,49 +3,259 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Explicit foveated ray grids for Newton Warp and OptiX.""" +"""Newton foveated camera: Newton's Warp renderer casts one ray per retinal sample.""" from __future__ import annotations +import logging +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch import warp as wp -from .foveated_camera import FoveatedCamera -from .foveated_camera_cfg import FoveatedCameraCfg +from isaaclab.sensors.camera.camera import Camera +from isaaclab.utils.warp import ProxyArray + +from .foveated_camera import OPENGL_TO_ROS_AXES, FoveatedCamera +from .native_grid import ( + GRID_STYLE, + allocate_grid_outputs, + copy_grid_outputs, + copy_updated_rows, + grid_output_shape, + grid_sample_indices, + mask_grid_samples, + proxy_outputs, +) +from .pooling import build_highres_coords, build_lowres_coords, build_pooler + +if TYPE_CHECKING: + from .foveated_camera_cfg import FoveatedCameraCfg + +logger = logging.getLogger(__name__) + + +def explicit_rays(directions: torch.Tensor, height: int, width: int) -> wp.array: + """Newton's ray array, shape (height, width, 1, 2): a zero origin and a unit direction per ray, shared by every + camera. + + Args: + directions: Unit ray directions in the OpenGL camera frame, in sample order, shape (N, 3). + height: Rendered rows. + width: Rendered columns; ``height * width`` must cover the N rays. Padding repeats the last ray. + """ + if directions.ndim != 2 or directions.shape[1] != 3: + raise ValueError(f"Ray directions must have shape (N, 3), got {tuple(directions.shape)}.") + if height * width < len(directions): + raise ValueError(f"A {height}x{width} render cannot hold {len(directions)} rays.") + index = torch.arange(height * width, device=directions.device).clamp_max(len(directions) - 1) + rays = directions.new_zeros(height, width, 1, 2, 3, dtype=torch.float32) + rays[..., 1, :] = directions.float()[index].reshape(height, width, 1, 3) + # The Warp view keeps the tensor alive. + return wp.from_torch(rays, dtype=wp.vec3f) class FoveatedNewtonCamera(FoveatedCamera): - """Render the shared retinal grid with Newton's explicit ray buffer.""" + """Newton camera that renders with foveated (CMF-distributed) rays. + + Instead of a uniform pixel grid, this sensor shoots *N* rays whose + directions are derived from :class:`fovi.sensing.coords.SamplingCoords` + and injected into Newton's renderer, with Warp or OptiX traversal. Vector sensors publish + ``(B, N, 1, C)``; native grid sensors publish upright ``(B, H, W, C)``. + + The samples cover the retinal window of the physical camera; the gaze turns the rendered camera pose. + """ + + cfg: FoveatedCameraCfg + + def __init__(self, cfg: FoveatedCameraCfg): + # The parent's initialisation updates poses before the rays exist. + self._foveated_rays: wp.array | None = None + super().__init__(cfg) def _initialize_impl(self): + # The pooler's KNN tensors are plain attributes that nn.Module.to() does not move, so the coordinates start on + # the CPU and the pooler is built on the sensor device after the parent initializes. + self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") + self._native_grid = self.cfg.foveated_style == GRID_STYLE + self._sampling_coords_highres = build_highres_coords(self.cfg, self._sampling_coords, matched_res) + self._num_valid_samples = len(self._sampling_coords) + self._num_ray_samples = len(self._sampling_coords_highres or self._sampling_coords) + logger.info( + "FoveatedNewtonCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg", + self._num_valid_samples, + self._num_ray_samples, + self.cfg.foveated_style, + self._sampling_coords.cmf_a, + self._sampling_coords.fov, + ) + + # The parent allocates render buffers for the rendered rays: the high-resolution ones when pooling. + ray_coords = self._sampling_coords_highres or self._sampling_coords + self.cfg.height, self.cfg.width = grid_output_shape(ray_coords) renderer = self.cfg.renderer_cfg if renderer.render_order == "tiled": - tile_width, tile_height = renderer.tile_rendering_width, renderer.tile_rendering_height + tile_width = renderer.tile_rendering_width + tile_height = renderer.tile_rendering_height if tile_width <= 0 or tile_height <= 0: raise ValueError("Newton render tile dimensions must be positive.") - if self.cfg.width % tile_width or self.cfg.height % tile_height: - raise ValueError( - f"Foveated grid {self.cfg.width}x{self.cfg.height} must be divisible by Newton tile size " - f"{tile_width}x{tile_height}; adjust foveated_res or use a non-tiled render order." + if self._native_grid: + self._validate_native_render_layout(tile_width, tile_height) + else: + # Pack consecutive vector rays into complete tiles. Padding is + # private renderer storage and never enters masking or pooling. + self.cfg.width = tile_width + self.cfg.height = ( + (self._num_ray_samples + tile_width * tile_height - 1) // (tile_width * tile_height) * tile_height ) super()._initialize_impl() + + self._sampling_coords = self._sampling_coords.to(device=self._device) + if self._sampling_coords_highres is not None: + self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) + self._ray_coords = self._sampling_coords_highres or self._sampling_coords self._initialize_gaze() - rays = self._retinal_rays.new_zeros((self.cfg.height, self.cfg.width, 1, 2, 3)) - rays[..., 1, :] = self._retinal_rays.view(self.cfg.height, self.cfg.width, 1, 3) - # Newton allocates its default rays only once. Replace them before the first capture. - self._render_data.camera_rays = wp.from_torch(rays, dtype=wp.vec3f) - self._render_output = self._data.output - self._prepare_grid_publish({name: value.torch for name, value in self._render_output.items()}) + self._pooler, self._pool_k = build_pooler( + self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) + ) + + # The gaze geometry's rendered rays, in canonical sample order and rolled by image_rotation_deg, back in the + # OpenGL frame Newton traces. + self._ray_directions = self._gaze_rays * self._gaze_rays.new_tensor(OPENGL_TO_ROS_AXES) + self._foveated_rays = explicit_rays(self._ray_directions, self.cfg.height, self.cfg.width) + render_samples = self.cfg.height * self.cfg.width + # Renderer buffers remain whole tiles; zero-copy canonical views hide + # trailing padding and preserve every output's dtype and sample order. + self._render_output = dict(self._data.output) + self._flat_render_output = {} + for name, value in self._render_output.items(): + tensor = value.torch + flat = tensor.view(tensor.shape[0], render_samples, 1, tensor.shape[-1]) + self._flat_render_output[name] = ProxyArray(wp.from_torch(flat[:, : self._num_ray_samples])) + self._data.output.clear() + self._data.output.update(self._flat_render_output) + + self._allocate_pooled_buffers() + source = self._pooled_output if self._pooler is not None else self._flat_render_output + self._sample_output = None + if self._pooler is None and not self._native_grid: + # Newton redraws every environment, so sample sets publish a copy that changes only on update. + self._sample_output = { + name: torch.zeros_like(value.torch) + for name, value in self._flat_render_output.items() + if not (name == "rgb" and "rgba" in self._flat_render_output) + } + if "rgba" in self._sample_output and "rgb" in self._flat_render_output: + self._sample_output["rgb"] = self._sample_output["rgba"][..., :3] + source = self._sample_output + if self._native_grid: + self._grid_output = allocate_grid_outputs(source, self._sampling_coords) + self._grid_indices = grid_sample_indices(self._sampling_coords) + source = self._grid_output + # The buffers the camera publishes: stable for the camera's lifetime and refilled each frame. + self._public_output = proxy_outputs(source) + self._data.output.clear() + self._data.output.update(self._public_output) + self._set_published_shape(self._public_output) + if self._native_grid and self._pooler is None: + self._prepare_grid_publish( + {name: value.torch.squeeze(2) for name, value in self._flat_render_output.items()} + ) + self._render_data.camera_rays = self._foveated_rays + + def _validate_native_render_layout(self, tile_width: int, tile_height: int) -> None: + """Reject a native grid that Newton's tiles cannot cover, before the parent allocates render buffers.""" + if self.cfg.width % tile_width or self.cfg.height % tile_height: + raise ValueError( + f"Native-grid Newton render size {self.cfg.width}x{self.cfg.height} " + f"must be divisible by renderer tile size {tile_width}x{tile_height}. " + "Choose foveated_res and pool_res_mult so the rendered grid satisfies " + "these dimensions, or select a non-tiled Newton render_order." + ) + + def _allocate_pooled_buffers(self) -> None: + """Allocate pooled output tensors; the renderer keeps writing the high-resolution buffers.""" + if self._pooler is None: + return + self._highres_output: dict[str, ProxyArray] = dict(self._data.output) + self._pooled_output: dict[str, torch.Tensor] = {} + for name, tex in self._highres_output.items(): + if name == "rgb" and "rgba" in self._highres_output: + continue # an alias of rgba, below + tensor = tex.torch + B, _, _, C = tensor.shape + self._pooled_output[name] = torch.zeros( + (B, self._num_valid_samples, 1, C), dtype=tensor.dtype, device=tensor.device + ) + # The renderer publishes rgb as a view of rgba whenever either is requested; so does the pooled output. + if "rgb" in self._highres_output and "rgba" in self._pooled_output: + self._pooled_output["rgb"] = self._pooled_output["rgba"][..., :3] + self._prepare_segmentation_pooling(self._highres_output) + dtypes_summary = {n: str(t.dtype).removeprefix("torch.") for n, t in self._highres_output.items()} + logger.info( + "FoveatedNewtonCamera: %s pooling (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) outputs=%s", + type(self._pooler).__name__, + self.cfg.pool_mode, + self._pool_k, + self.cfg.pool_sample_cortex, + self._num_ray_samples, + self._num_valid_samples, + dtypes_summary, + ) + + def _update_poses( + self, + env_ids: Sequence[int] | wp.array | None = None, + env_mask: wp.array | None = None, + frame_op: int = 0, + ) -> None: + """Read base poses, turn them by the gaze, update the renderer once, and inject the foveated rays. + + The scene pose is read even without a gaze: the camera may inherit + motion from a parent body. + """ + # The base update turns the poses by the gaze in _update_camera_state, then hands them to the renderer. + Camera._update_poses(self, env_ids, env_mask=env_mask, frame_op=frame_op) + if self._foveated_rays is not None: + self._render_data.camera_rays = self._foveated_rays def _update_buffers_impl(self, env_mask: wp.array): - # Newton's render may redraw every environment. Only publish the rows due for update. - published = self._data.output - self._data._output = self._render_output + """Render, then mask and publish the updated environments, pooling high-resolution samples if enabled. + + Newton redraws every environment's render buffer, each at the pose and gaze it last received. The sensor mask, + its visibility record and the published buffers, which the camera owns, change only for the updated + environments. + """ + self._data.output.clear() + self._data.output.update(self._render_output) try: super()._update_buffers_impl(env_mask) finally: - self._data._output = published - self._publish_grid(env_mask) + self._data.output.clear() + self._data.output.update(self._public_output) + if not self._env_mask_has_any(env_mask): + return + if self._pooler is None: + if self._grid_publish: + self._publish_grid(env_mask) + else: + self._apply_sensor_fov_mask(self._flat_render_output, env_mask) + for name, samples in self._sample_output.items(): + if name == "rgb" and "rgba" in self._sample_output: + continue # rgba alias + copy_updated_rows(self._flat_render_output[name].torch, samples, env_mask) + return + mask_grid_samples(self._highres_output, self._ray_coords) + self._apply_sensor_fov_mask(self._highres_output, env_mask) + for name, hi in self._highres_output.items(): + if name == "rgb" and "rgba" in self._highres_output: + continue # rgba alias + # Pooling covers every environment; only the updated ones are published. + copy_updated_rows(self._pool_output(name, hi.torch), self._pooled_output[name], env_mask) + if self._native_grid: + copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) @staticmethod def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index b9136e1bb02c..7260df107eed 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -3,11 +3,19 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Native foveated lens textures for Isaac RTX and OVRTX.""" +"""RTX foveated tiled camera sensor. + +Subclasses :class:`isaaclab.sensors.Camera` to render foveated images +via the RTX path tracer using ``OmniLensDistortionLutAPI`` textures. +Per-sample values are extracted from the rendered 2D texture to produce +vector ``(B, N, 1, C)`` or upright native-grid ``(B, H, W, C)`` output buffers, +identical to :class:`FoveatedNewtonCamera`. +""" from __future__ import annotations import logging +import math import tempfile from collections.abc import Sequence from typing import TYPE_CHECKING @@ -17,25 +25,44 @@ from isaaclab import sim as sim_utils from isaaclab.sensors.camera.camera import Camera -from isaaclab.utils.math import ( - convert_camera_frame_orientation_convention, - normalize, - quat_conjugate, - quat_from_matrix, - quat_mul, -) +from isaaclab.utils import clone +from isaaclab.utils.math import convert_camera_frame_orientation_convention, matrix_from_quat, quat_from_matrix from . import lens_lut +from .calibrated_geometry import compose_rotations, retinal_directions from .foveated_camera import FoveatedCamera +from .native_grid import ( + GRID_STYLE, + allocate_grid_outputs, + copy_grid_outputs, + copy_updated_rows, + grid_sample_indices, + mask_grid_samples, + proxy_outputs, +) +from .pooling import build_highres_coords, build_lowres_coords, build_pooler if TYPE_CHECKING: + from isaaclab.utils.warp import ProxyArray + from .foveated_camera_cfg import FoveatedCameraCfg logger = logging.getLogger(__name__) class FoveatedRTXCamera(FoveatedCamera): - """Render the shared retinal grid through an RTX lens lookup texture.""" + """RTX camera that renders with foveated (CMF-distributed) rays. + + Instead of Newton's Warp ray arrays, this sensor creates + ``OmniLensDistortionLutAPI`` Camera prims with LUT textures that define + per-texel ray directions. The RTX path tracer renders a 2D texture + which is then sampled at pre-computed UV positions to extract per-sample + values, producing ``(B, N, 1, C)`` output buffers. + + Grid styles render straight into their native grid. Sample-set styles are + packed onto a cortical disc, which keeps neighbouring samples adjacent for + DLSS denoising. Camera motion comes from the prim's parent and from the gaze. + """ cfg: FoveatedCameraCfg @@ -46,8 +73,16 @@ def __init__(self, cfg: FoveatedCameraCfg): "OVRTX async_rendering returns the previous capture, which the sensor mask would cut with the current" " gaze. Disable async_rendering or mask_to_sensor_fov." ) - super().__init__(cfg) + # The parent ``Camera`` allocates the renderer-bound texture buffers; the published ones follow from them. + self._texture_output: dict[str, ProxyArray] = {} + self._foveated_output: dict[str, torch.Tensor] = {} + self._pooled_output: dict[str, torch.Tensor] | None = None + # The projection sets the texture size on the configuration before the parent allocates for it; the caller's + # configuration stays untouched. + cfg = clone(cfg) + self.cfg = cfg self._prepare_projection() + super().__init__(cfg) # The lens belongs to the camera prims from construction: OVRTX snapshots the stage when the renderer starts. for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage): # A locked camera may be treated as static, which skips the motion vectors that DLSS reprojection needs; @@ -84,56 +119,110 @@ def get_world_poses(self, env_ids=None, convention="ros"): """ positions, orientations = super().get_world_poses(env_ids, convention="opengl") if not self._gaze_pose_reads_angles and self._gaze_rotation is not None: - ids = self._resolve_env_ids_wp(env_ids) - rotation = self._relative_gaze() - if ids is not None: - rotation = rotation[wp.to_torch(ids).long()] - orientations = quat_mul(orientations, quat_conjugate(rotation)) + # The prims hold the mount turned by the gaze's rotation in their own (OpenGL) frame. + basis = self._gaze_basis + gaze = self._gaze_rotation.torch[self._env_indices(env_ids)] + with torch.autocast(basis.device.type, enabled=False): + relative = compose_rotations(compose_rotations(basis, gaze), basis.T) + orientations = quat_from_matrix( + compose_rotations(matrix_from_quat(orientations), relative.transpose(-1, -2)) + ) return positions, convert_camera_frame_orientation_convention(orientations, origin="opengl", target=convention) def process_rendered_frame(self) -> None: - """Publish the grid after scalar or batched rendering.""" - env_mask = self._is_outdated - if not self._env_mask_has_any(env_mask): + """Mask and publish the frame of the environments that scalar or batched rendering updated.""" + if not self._env_mask_has_any(self._is_outdated): + return + if self._grid_publish: + self._publish_grid(self._is_outdated) return - if self._near_clip is not None: - # OVRTX measures distance from the near-clipped ray origin. The scratch is a publication - # source, so this leaves the renderer's bound buffer and unselected public rows untouched. - torch.add(self._distance_source, self._near_clip, out=self._distance_corrected) - self._publish_grid(env_mask) + # Only the updated environments' samples change, so pooling and the grid layout reproduce every other + # environment's last frame. + self._extract_foveated_samples(self._is_outdated) + mask_grid_samples(self._foveated_output, self._ray_coords) + self._apply_sensor_fov_mask(self._foveated_output, self._is_outdated) + + if self._pooled_output is not None: + for name, hi in self._foveated_output.items(): + if name == "rgb" and "rgba" in self._foveated_output: + continue # rgba alias + self._pooled_output[name].copy_(self._pool_output(name, hi)) + if self._native_grid: + source = self._pooled_output if self._pooled_output is not None else self._foveated_output + copy_grid_outputs(source, self._grid_output, self._grid_indices) def _prepare_projection(self) -> None: + # The lens textures and sample extraction use the rendered samples: the high-resolution ones when pooling. + self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") + self._sampling_coords_highres = build_highres_coords(self.cfg, self._sampling_coords, matched_res) + ray_coords = self._sampling_coords_highres or self._sampling_coords + self._ray_coords = ray_coords + self._native_grid = self.cfg.foveated_style == GRID_STYLE + self._num_valid_samples = len(self._sampling_coords) + self._num_ray_samples = len(ray_coords) + + size = ray_coords.resolution + if not self._native_grid: + size = max(64, math.ceil(math.sqrt(4 * self._num_ray_samples / math.pi))) exit_size = self.cfg.exit_texture_size if exit_size is None: - exit_size = max(128, 4 * self.cfg.foveated_res) - direction, exit_texture = lens_lut.build_native_grid_textures( - self._sampling_coords, - self._retinal_rays, - image_rotation_deg=self.cfg.image_rotation_deg, - exit_size=exit_size, - ) + exit_size = max(128, 4 * size) + if self._native_grid: + dir_tex, exit_tex = lens_lut.build_native_grid_textures( + ray_coords, image_rotation_deg=self.cfg.image_rotation_deg, exit_size=exit_size + ) + else: + # Pack sample sets on the cortical disc so nearby samples stay adjacent for RTX filtering. + theta = ray_coords.polar[:, 1].to(torch.float64) + if self.cfg.image_rotation_deg: + theta = theta + math.radians(float(self.cfg.image_rotation_deg)) + eccentricity = ray_coords.polar[:, 0].to(torch.float64) * (ray_coords.fov / 2.0) + self._sample_uv = lens_lut.samples_uv_cortical_disc( + eccentricity, theta, ray_coords.fov, ray_coords.cmf_a, device="cpu" + ) + dirs = retinal_directions(ray_coords.cartesian, ray_coords.fov, self.cfg.image_rotation_deg) + dir_tex, exit_tex = lens_lut.build_lut_textures( + self._sample_uv, dirs, size, size, exit_size, exit_size, device="cpu" + ) + self._texture_width = self._texture_height = size + + # The camera owns its textures' directory, which is removed when the camera is released. self._lut_dir = tempfile.TemporaryDirectory(prefix="rtx_foveated_luts_") self._dir_tex_path, self._exit_tex_path = lens_lut.save_lut_textures( - direction, exit_texture, self._lut_dir.name, "foveated" + dir_tex, exit_tex, self._lut_dir.name, "foveated" + ) + logger.info( + "FoveatedRTXCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg, " + "texture %dx%d, exit lookup %dx%d, lookup textures in %s", + self._num_valid_samples, + self._num_ray_samples, + self.cfg.foveated_style, + ray_coords.cmf_a, + ray_coords.fov, + size, + size, + exit_size, + exit_size, + self._lut_dir.name, ) + self.cfg.height = self.cfg.width = size def _initialize_impl(self) -> None: + tw, th = self._texture_width, self._texture_height + # OVRTX measures distance_to_camera from each camera's near-clipped ray origin, so it needs the near clips. + self._offset_distance = ( + self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self.cfg.data_types + ) + near_clips = None + if self._offset_distance: + prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage) + near_clips = [self._near_clipping_distance(prim) for prim in prims] + super()._initialize_impl() - self._initialize_gaze() - if not self._gaze_pose_reads_angles: - _, local_orientation = self._view.get_local_poses() - self._base_local_orientation = local_orientation.torch.clone() - self._gaze_basis_quat = quat_from_matrix(self._gaze_basis) - sources = {name: value.torch for name, value in self._data.output.items()} self._near_clip = None - if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in sources: - near_clips = [self._near_clipping_distance(camera.GetPrim()) for camera in self._sensor_prims] - self._distance_source = sources["distance_to_camera"] - self._near_clip = self._distance_source.new_tensor(near_clips).view(-1, 1, 1, 1) - self._distance_corrected = torch.empty_like(self._distance_source) - sources["distance_to_camera"] = self._distance_corrected - self._prepare_grid_publish(sources) + if near_clips is not None: + self._near_clip = torch.tensor(near_clips, dtype=torch.float32, device=self._device).view(-1, 1, 1, 1) # OVRTX owns its runtime; Kit extensions belong only to Isaac RTX. if self.cfg.renderer_cfg.renderer_type == "isaac_rtx": @@ -144,6 +233,45 @@ def _initialize_impl(self) -> None: if not ext_manager.set_extension_enabled_immediate(ext_name, True): logger.warning("Could not enable Kit extension '%s'; the lens lookup may not render.", ext_name) + self._sampling_coords = self._sampling_coords.to(device=self._device) + if self._sampling_coords_highres is not None: + self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) + self._ray_coords = self._sampling_coords_highres or self._sampling_coords + self._initialize_gaze() + _, local_orientation = self._view.get_local_poses() + self._base_local_orientation = matrix_from_quat(local_orientation.torch).clone() + self._pooler, self._pool_k = build_pooler( + self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) + ) + + # The renderer keeps writing the texture buffers the parent bound to it; the camera publishes others. + self._texture_output = self._data.output + textures = {name: tex.torch for name, tex in self._texture_output.items()} + # A native grid texture already holds the samples in order, so one kernel per output masks it and lays it + # out. OVRTX's camera distance needs its near-plane offset first, and keeps the step-by-step path. + fused = self._native_grid and self._pooler is None and not self._offset_distance + if fused: + count = self._num_ray_samples + samples = {name: tex.reshape(tex.shape[0], count, tex.shape[-1]) for name, tex in textures.items()} + self._grid_output = allocate_grid_outputs(samples, self._sampling_coords) + self._grid_indices = grid_sample_indices(self._sampling_coords) + self._prepare_grid_publish(samples) + published = self._grid_output + else: + if not self._native_grid: + uv_gpu = self._sample_uv.to(self._device) + self._extract_px = (uv_gpu[:, 0] * tw).long().clamp(0, tw - 1) + self._extract_py = (uv_gpu[:, 1] * th).long().clamp(0, th - 1) + self._allocate_foveated_buffers() + published = self._pooled_output if self._pooled_output is not None else self._foveated_output + if self._native_grid: + self._grid_output = allocate_grid_outputs(published, self._sampling_coords) + self._grid_indices = grid_sample_indices(self._sampling_coords) + published = self._grid_output + # ``CameraData.output`` is read-only, so its backing field is replaced. + self._data._output = proxy_outputs(published) + self._set_published_shape(self._data._output) + def _near_clipping_distance(self, prim) -> float: """Near clipping distance [m] of the camera, from its spawn configuration or else its prim.""" if self.cfg.spawn is not None: @@ -153,37 +281,64 @@ def _near_clipping_distance(self, prim) -> float: clipping = UsdGeom.Camera(prim).GetClippingRangeAttr().Get() return float(clipping[0]) if clipping is not None else 0.0 - def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): - """Move the mount while retaining its relative gaze.""" - super().set_world_poses(positions, orientations, env_ids, convention) - if orientations is not None and not self._gaze_pose_reads_angles: - ids = self._resolve_env_ids_wp(env_ids) - self._mount_written(slice(None) if ids is None else wp.to_torch(ids).long()) + def _allocate_foveated_buffers(self): + """Allocate (B, N_hi, 1, C) and, when pooling, (B, N_lo, 1, C) buffers from the texture buffers' shapes.""" + has_rgba_alias = "rgba" in self._texture_output + self._foveated_output = {} + for name, buf in self._texture_output.items(): + if name == "rgb" and has_rgba_alias: + continue # an alias of rgba, below + # Texture buffers are ProxyArrays; their Torch view carries the dtype and device. + buf_t = buf.torch + self._foveated_output[name] = torch.zeros( + (self._view.count, self._num_ray_samples, 1, buf_t.shape[-1]), device=buf_t.device, dtype=buf_t.dtype + ) + # The renderer publishes rgb as a view of rgba whenever either is requested; so do the foveated outputs. + if "rgb" in self._texture_output and "rgba" in self._foveated_output: + self._foveated_output["rgb"] = self._foveated_output["rgba"][:, :, :, :3] - def set_world_poses_from_view(self, eyes, targets, env_ids=None): - """Point the mount at a target while retaining its relative gaze.""" - super().set_world_poses_from_view(eyes, targets, env_ids) - if not self._gaze_pose_reads_angles: - # The base setter leaves rows with a degenerate look-at direction untouched. - moved = (self._as_device_tensor(eyes, 3) != self._as_device_tensor(targets, 3)).any(dim=-1) - ids = self._resolve_env_ids_wp(env_ids) - self._mount_written(moved if ids is None else wp.to_torch(ids).long()[moved]) + if self._pooler is None: + self._pooled_output = None + return + self._pooled_output = {} + for name, buf in self._foveated_output.items(): + if name == "rgb" and has_rgba_alias: + continue + self._pooled_output[name] = torch.zeros( + (self._view.count, self._num_valid_samples, 1, buf.shape[-1]), device=self._device, dtype=buf.dtype + ) + if "rgb" in self._texture_output and "rgba" in self._pooled_output: + self._pooled_output["rgb"] = self._pooled_output["rgba"][:, :, :, :3] + self._prepare_segmentation_pooling(self._pooled_output) + logger.info( + "FoveatedRTXCamera: %s pooling (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)", + type(self._pooler).__name__, + self.cfg.pool_mode, + self._pool_k, + self.cfg.pool_sample_cortex, + self._num_ray_samples, + self._num_valid_samples, + ) - def _mount_written(self, ids) -> None: + def _mount_written(self, env_ids) -> None: + """Save the moved prims' orientations as their bare mounts and write the gaze on top of them again.""" + if self._gaze_pose_reads_angles: + return # The pose update turns the new mount by the gaze. + ids = self._env_indices(env_ids) _, local_orientation = self._view.get_local_poses() - self._base_local_orientation[ids] = local_orientation.torch[ids] + self._base_local_orientation[ids] = matrix_from_quat(local_orientation.torch[ids]) if self._gaze_rotation is not None: self._write_gaze_local_pose() - def _relative_gaze(self) -> torch.Tensor: - basis = self._gaze_basis_quat.expand(self._view.count, -1) - gaze = quat_from_matrix(self._gaze_rotation.torch) - return quat_mul(quat_mul(basis, gaze), quat_conjugate(basis)) - def _write_gaze_local_pose(self) -> None: - # Replicator reads camera prims. Write the gaze onto the bare local mount so parent motion is preserved. - orientation = normalize(quat_mul(self._base_local_orientation, self._relative_gaze())) - self._view.set_local_poses(orientations=wp.from_torch(orientation.contiguous(), dtype=wp.vec4f)) + # Replicator reads camera prims, not update_camera's pose arguments. + # Write when the command arrives, before a visualizer can render the step. + # The saved local base prevents accumulation and preserves parent motion. + basis = self._gaze_basis + with torch.autocast(basis.device.type, enabled=False): + relative = compose_rotations(compose_rotations(basis, self._gaze_rotation.torch), basis.T) + local_orientation = quat_from_matrix(compose_rotations(self._base_local_orientation, relative)) + self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f)) def _update_buffers_impl(self, env_mask: wp.array): if not self._env_mask_has_any(env_mask): @@ -192,6 +347,24 @@ def _update_buffers_impl(self, env_mask: wp.array): super()._update_buffers_impl(env_mask) self.process_rendered_frame() + def _extract_foveated_samples(self, env_mask: wp.array): + """Extract the updated environments' per-sample values from the rendered 2D textures into the (B, N, 1, C) + buffers; the other environments keep their last samples.""" + for name in self._texture_output: + if name == "rgb" and "rgba" in self._texture_output: + continue # rgba alias + tex = self._texture_output[name] # (B, th, tw, C) + fov = self._foveated_output[name] # (B, N, 1, C) + tensor = tex.torch + if self._native_grid: + samples = tensor.reshape_as(fov) + else: + samples = tensor[:, self._extract_py, self._extract_px, :].unsqueeze(2) + if self._offset_distance and name == "distance_to_camera": + # OVRTX measures the distance from the near-clipped ray origin. + samples = samples + self._near_clip.to(samples.dtype) + copy_updated_rows(samples, fov, env_mask) + @staticmethod def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: # OVRTX renders the poses the camera hands it, so its pose update turns the gaze. Replicator reads camera diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py index c8fccd044385..1f90730b1ec4 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -178,23 +178,43 @@ def set_gaze_kernel( rotation[i] = gaze_rotation(angles) +@wp.func +def turn_pose( + i: wp.int32, + gaze: wp.mat33f, + basis: wp.mat33f, + to_opengl: wp.quatf, + to_world: wp.quatf, + to_ros: wp.quatf, + orientation: wp.array(dtype=wp.quatf), + mount: wp.array(dtype=wp.quatf), +): + """Record camera ``i``'s mount in the ROS convention, then turn its world orientation by its gaze.""" + base = orientation[i] + mount[i] = wp.normalize(base * to_ros) + orientation[i] = gaze_pose(base, gaze, basis, to_opengl, to_world) + + @wp.kernel(enable_backward=False) def apply_gaze_kernel( angles_deg: wp.array(dtype=wp.vec2f), basis: wp.mat33f, to_opengl: wp.quatf, to_world: wp.quatf, + to_ros: wp.quatf, mask: wp.array(dtype=wp.bool), use_mask: wp.int32, orientation: wp.array(dtype=wp.quatf), rotation: wp.array(dtype=wp.mat33f), + mount: wp.array(dtype=wp.quatf), ): - """Turn each updated camera and save the rotation used for its capture.""" + """Turn each camera's world orientation by its gaze, or only the masked ones, and record their mounts and gaze + rotations; every other camera keeps the rotation its pose was turned by.""" i = wp.tid() if use_mask == 0 or mask[i]: gaze = gaze_rotation(angles_deg[i]) rotation[i] = gaze - orientation[i] = gaze_pose(orientation[i], gaze, basis, to_opengl, to_world) + turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount) @wp.kernel(enable_backward=False) @@ -203,15 +223,17 @@ def apply_gaze_indexed_kernel( basis: wp.mat33f, to_opengl: wp.quatf, to_world: wp.quatf, + to_ros: wp.quatf, indices: wp.array(dtype=wp.int32), orientation: wp.array(dtype=wp.quatf), rotation: wp.array(dtype=wp.mat33f), + mount: wp.array(dtype=wp.quatf), ): - """Turn the indexed cameras' world orientations by their gaze, and record their gaze rotations.""" + """Turn the indexed cameras' world orientations by their gaze, and record their mounts and gaze rotations.""" i = indices[wp.tid()] gaze = gaze_rotation(angles_deg[i]) rotation[i] = gaze - orientation[i] = gaze_pose(orientation[i], gaze, basis, to_opengl, to_world) + turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount) @wp.func @@ -220,6 +242,27 @@ def sees(ray: wp.vec3f, gaze: wp.mat33f, frame: wp.mat33f, camera: CameraParams) return project_direction(frame * gaze * wp.transpose(frame) * ray, camera)[2] > 0.5 +@wp.kernel(enable_backward=False) +def sensor_visibility_kernel( + rays: wp.array(dtype=wp.vec3f), + rotation: wp.array(dtype=wp.mat33f), + frame: wp.mat33f, + camera: CameraParams, + updated: wp.array(dtype=wp.bool), + valid: wp.array2d(dtype=wp.bool), + hidden: wp.array2d(dtype=wp.bool), +): + """Whether the physical camera sees each rendered ray turned by each updated environment's gaze, and which + updated samples it does not see; other environments keep their last visibility and hide nothing.""" + env, sample = wp.tid() + if not updated[env]: + hidden[env, sample] = False + return + seen = sees(rays[sample], rotation[env], frame, camera) + valid[env, sample] = seen + hidden[env, sample] = not seen + + @wp.kernel(enable_backward=False) def publish_grid_kernel( source: wp.array3d(dtype=wp.uint8), @@ -231,6 +274,8 @@ def publish_grid_kernel( frame: wp.mat33f, camera: CameraParams, mask_to_sensor: wp.int32, + record_visible: wp.int32, + visible: wp.array2d(dtype=wp.bool), target: wp.array3d(dtype=wp.uint8), ): """Copy the updated environments' rendered samples into the upright grid, zeroing samples outside the footprint @@ -243,10 +288,42 @@ def publish_grid_kernel( return sample = indices[cell] keep = footprint[sample] - if keep and mask_to_sensor != 0: - keep = sees(rays[sample], rotation[env], frame, camera) + if mask_to_sensor != 0: + seen = sees(rays[sample], rotation[env], frame, camera) + if record_visible != 0: + visible[env, sample] = seen + keep = keep and seen for k in range(target.shape[2]): if keep: target[env, cell, k] = source[env, sample, k] else: target[env, cell, k] = wp.uint8(0) + + +@wp.kernel(enable_backward=False) +def project_directions_kernel( + directions: wp.array(dtype=wp.vec3f), + camera: CameraParams, + pixels: wp.array(dtype=wp.vec2f), + valid: wp.array(dtype=wp.bool), +): + i = wp.tid() + result = project_direction(directions[i], camera) + pixels[i] = wp.vec2f(result[0], result[1]) + valid[i] = result[2] > 0.5 + + +def project_directions(directions: torch.Tensor, camera: CameraParams) -> tuple[torch.Tensor, torch.Tensor]: + """Project (..., 3) camera-frame directions to (..., 2) pixels and (...,) validity, in one launch.""" + flat = directions.detach().reshape(-1, 3).float().contiguous() + pixels = torch.empty(len(flat), 2, dtype=torch.float32, device=flat.device) + valid = torch.empty(len(flat), dtype=torch.bool, device=flat.device) + if len(flat): + with torch_stream(flat.device): + wp.launch( + project_directions_kernel, + dim=len(flat), + inputs=[wp.from_torch(flat, dtype=wp.vec3f), camera], + outputs=[wp.from_torch(pixels, dtype=wp.vec2f), wp.from_torch(valid, dtype=wp.bool)], + ) + return pixels.reshape(*directions.shape[:-1], 2), valid.reshape(directions.shape[:-1]) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index 520ac075cb39..383c4f12f14b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -13,7 +13,7 @@ * **rayExitPositionTexture** ``(EW × EH, RG float32)`` Inverse map: given a ray direction (octahedral-encoded over ``[0,1]²``), - returns sensor NDC ``(u, v)`` in the native grid. + returns the sensor NDC ``(u, v)`` of the nearest sample. Isaac RTX and OVRTX both render through this API; the legacy generalized-projection camera attributes are not used. @@ -27,6 +27,7 @@ from __future__ import annotations +import math import os from typing import TYPE_CHECKING @@ -34,7 +35,7 @@ import torch from fovi.sensing.coords import SamplingCoords -from .native_grid import native_grid_exit_uv +from .native_grid import native_grid_directions, native_grid_exit_uv if TYPE_CHECKING: from pxr import Usd @@ -61,14 +62,96 @@ def save_exr(path: str, data: torch.Tensor) -> None: def build_native_grid_textures( - coords: SamplingCoords, rays: torch.Tensor, *, image_rotation_deg: float, exit_size: int + coords: SamplingCoords, *, image_rotation_deg: float, exit_size: int ) -> tuple[torch.Tensor, torch.Tensor]: """Build native direction texels and an analytic octahedral inverse map.""" + directions = native_grid_directions(coords, image_rotation_deg=image_rotation_deg).reshape( + coords.resolution, coords.resolution, 3 + ) decoded = torch.stack(_octahedral_decode(exit_size, exit_size, device=coords.device), -1) uv, valid = native_grid_exit_uv(decoded, coords, image_rotation_deg=image_rotation_deg) # Out-of-sensor rays must not be projected into the fovea by the inverse LUT. exit_texture = torch.where(valid[..., None], uv, torch.full_like(uv, -1)) - return rays.reshape(coords.resolution, coords.resolution, 3), exit_texture + return directions, exit_texture + + +def build_lut_textures( + samples_uv: torch.Tensor, + ray_directions: torch.Tensor, + texture_width: int, + texture_height: int, + exit_width: int, + exit_height: int, + chunk: int = 8192, + *, + device: torch.device | str, +) -> tuple[torch.Tensor, torch.Tensor]: + """Build direction and exit LUT tensors from a labelled set of sensor samples. + + Both tensors are filled by **nearest-neighbour assignment**. + + Args: + samples_uv: ``(N, 2)`` float32. NDC ``(u, v)`` per sample. + ray_directions: ``(N, 3)`` float32. Unit ray direction per sample. + texture_width, texture_height: Direction LUT dimensions. + exit_width, exit_height: Exit LUT dimensions. + chunk: NN search batch size. + device: Torch device. + + Returns: + ``(direction_texture, exit_texture)`` — + ``(H, W, 3)`` and ``(EH, EW, 2)`` float32 tensors. + """ + uv_t = _t(samples_uv, torch.float32, device) + dirs_t = _t(ray_directions, torch.float32, device) + N = uv_t.shape[0] + + # Direction texture. + dir_out = torch.zeros(texture_height, texture_width, 3, dtype=torch.float32, device=device) + dir_out[:, :, 2] = -1.0 + + if N > 0: + # Each texel takes the ray of the sample nearest it in UV, whatever order the samples come in. + u_t = (torch.arange(texture_width, dtype=torch.float32, device=device) + 0.5) / texture_width + v_t = (torch.arange(texture_height, dtype=torch.float32, device=device) + 0.5) / texture_height + U = u_t.unsqueeze(0).expand(texture_height, texture_width) + V = v_t.unsqueeze(1).expand(texture_height, texture_width) + texel_uv = torch.stack([U.reshape(-1), V.reshape(-1)], dim=1) + k_nn = _nn_chunk(texel_uv, uv_t, chunk) + dir_out.reshape(-1, 3)[:] = dirs_t[k_nn] + + # Exit texture: only texels whose direction lies within the samples' field (r <= max_r) map to a sample; the rest + # hold the invalid UV (-1, -1), as in native-grid LUTs, so rays outside the field never reach the fovea. + d = dirs_t.to(torch.float64) + r_s = (torch.atan2((d[:, 0] ** 2 + d[:, 1] ** 2).sqrt(), (-d[:, 2]).clamp(min=1e-20)) * (180.0 / math.pi)).float() + th_s = torch.atan2(d[:, 1], d[:, 0]).float() + xs = r_s * th_s.cos() + ys = r_s * th_s.sin() + max_r = float(r_s.max().item()) if N > 0 else 0.0 + + oct_x, oct_y, oct_z = _octahedral_decode(exit_width, exit_height, device=device) + r_q = (torch.atan2((oct_x**2 + oct_y**2).sqrt(), (-oct_z).clamp(min=1e-20)) * (180.0 / math.pi)).float() + th_q = torch.atan2(oct_y.float(), oct_x.float()) + xq = r_q * th_q.cos() + yq = r_q * th_q.sin() + + odz_f = oct_z.float() + valid = (r_q <= max_r) & (odz_f < -1e-9) + + exit_u = torch.full((exit_height, exit_width), -1.0, dtype=torch.float32, device=device) + exit_v = torch.full((exit_height, exit_width), -1.0, dtype=torch.float32, device=device) + + if N > 0 and valid.any(): + sample_cart = torch.stack([xs, ys], dim=1) + vf = valid.reshape(-1) + query_cart = torch.stack([xq.reshape(-1)[vf], yq.reshape(-1)[vf]], dim=1) + k_exit = _nn_chunk(query_cart, sample_cart, chunk) + eu_flat = exit_u.reshape(-1) + ev_flat = exit_v.reshape(-1) + eu_flat[vf] = uv_t[k_exit, 0] + ev_flat[vf] = uv_t[k_exit, 1] + + return dir_out, torch.stack([exit_u, exit_v], dim=2) def save_lut_textures( @@ -109,6 +192,37 @@ def apply_lens_lut_to_prim( ) +def samples_uv_cortical_disc( + r_deg, + theta_rad, + fov_deg: float, + cmf_a: float, + device: torch.device | str, +) -> torch.Tensor: + """Map samples to NDC using the cortical polar disc layout. + + ``ρ = log((r + a) / a)``, mapped to a centered disc. + Foveal centre ``r=0`` → disc centre ``(0.5, 0.5)``. + + Returns: + ``(N, 2)`` float32 NDC tensor. + """ + rho_max = math.log((fov_deg / 2.0 + cmf_a) / cmf_a) + r = _t(r_deg, torch.float64, device) + th = _t(theta_rad, torch.float64, device) + rho = ((r + cmf_a) / cmf_a).clamp(min=1e-30).log() + u = (rho * th.cos() / (2.0 * rho_max) + 0.5).float() + v = (-rho * th.sin() / (2.0 * rho_max) + 0.5).float() + return torch.stack([u, v], dim=1) + + +def _t(x, dtype: torch.dtype, device) -> torch.Tensor: + """Convert array-like or tensor *x* to a ``torch.Tensor`` on *device*.""" + if isinstance(x, torch.Tensor): + return x.to(dtype=dtype, device=device) + return torch.as_tensor(np.asarray(x), dtype=dtype, device=device) + + def _octahedral_decode( width: int, height: int, @@ -130,3 +244,22 @@ def _octahedral_decode( dy = torch.where(dz <= 0.0, (1.0 - px.abs()) * sy, py) n = torch.clamp((dx**2 + dy**2 + dz**2).sqrt(), min=1e-20) return dx / n, dy / n, -dz / n + + +def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tensor: + """Chunked nearest-neighbour search via ``torch.cdist``. + + Chunk size is capped so the float32 distance matrix stays within 2 GiB. + + Returns: + ``(M,)`` int64 index of the closest key for each query row. + """ + N = keys.shape[0] + safe_chunk = max(1, (2 << 30) // (4 * max(N, 1))) + effective = min(chunk, safe_chunk) + M = query.shape[0] + idx = torch.empty(M, dtype=torch.long, device=query.device) + for s in range(0, M, effective): + e = min(s + effective, M) + idx[s:e] = torch.cdist(query[s:e], keys).argmin(dim=1) + return idx diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py index de7c5a9c76f0..459bdb690094 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py @@ -8,10 +8,54 @@ from __future__ import annotations import math +from collections.abc import Mapping +from typing import Protocol import torch +import warp as wp from fovi.sensing.coords import SamplingCoords -from fovi.sensing.projection import angular_directions + +from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.memory import make_masked_copy + +from .gaze_kernels import warp_stream + +GRID_STYLE = "warped_cartesian_as_grid" + + +def buffer_tensor(value: torch.Tensor | TorchBuffer) -> torch.Tensor: + """Get a renderer or public tensor without copying.""" + return value if isinstance(value, torch.Tensor) else value.torch + + +def proxy_outputs(outputs: Mapping[str, torch.Tensor | ProxyArray]) -> dict[str, ProxyArray]: + """Wrap output buffers as zero-copy :class:`ProxyArray` values, as :class:`CameraData` publishes them.""" + return { + name: ProxyArray(wp.from_torch(value)) if isinstance(value, torch.Tensor) else value + for name, value in outputs.items() + } + + +def copy_updated_rows(source: torch.Tensor, target: torch.Tensor, rows: wp.array) -> None: + """Copy the environments that ``rows`` selects from ``source`` into ``target``, shape (num_envs, N, 1, C). + + The other environments keep their values. The masked copy needs no full-batch temporary and no host sync. + + Args: + source: The new samples; may be a strided view. + target: The published samples, written in place. + rows: Which environments to copy, shape (num_envs,) of ``bool``. + """ + source3, target3 = source.squeeze(2), target.squeeze(2) + dtype = wp.dtype_from_torch(target.dtype) + wp.launch( + make_masked_copy(dtype, 3), + dim=tuple(target3.shape), + inputs=[wp.from_torch(source3, dtype=dtype), rows, None], + outputs=[wp.from_torch(target3, dtype=dtype)], + device=str(target.device), + stream=warp_stream(target.device), + ) def bounded_angular_radius(radius: torch.Tensor, half_fov_rad: float) -> torch.Tensor: @@ -42,17 +86,21 @@ def native_grid_directions(coords: SamplingCoords, *, image_rotation_deg: float Grid radius is proportional to visual angle, and the padding outside the nominal field continues toward the antipode without wrapping. """ - + _require_spherical(coords) cartesian = coords.cartesian.to(torch.float64) radius = torch.linalg.vector_norm(cartesian, dim=-1) - half_fov = math.radians(coords.fov) / 2 - padded_radius = bounded_angular_radius(radius, half_fov) / half_fov - scale = torch.where(radius > 0, padded_radius / radius.clamp_min(1e-30), 1.0) - rays = angular_directions(cartesian * scale[:, None], coords.fov) - x, y, z = rays.unbind(-1) + boundary_radius, boundary_angle = _angular_padding_boundary(coords) + angle = bounded_angular_radius(radius / boundary_radius, boundary_angle) + scale = torch.where(radius > 0, angle.sin() / radius.clamp_min(1e-30), angle.new_zeros(())) + xy = cartesian * scale[:, None] + z = -angle.cos() angle = math.radians(image_rotation_deg) - c, s = math.cos(angle), math.sin(angle) - return torch.stack((c * x + s * y, s * x - c * y, -z), -1).float() + x, y = xy.unbind(-1) + rays = torch.stack( + (math.cos(angle) * x - math.sin(angle) * y, math.sin(angle) * x + math.cos(angle) * y, z), + -1, + ) + return torch.nn.functional.normalize(rays, dim=-1).float() def native_grid_exit_uv( @@ -63,15 +111,99 @@ def native_grid_exit_uv( Texture rows and columns follow canonical vector order: native x then y. The public image applies Fovi's upright grid permutation after rendering. """ + _require_spherical(coords) angle = math.radians(image_rotation_deg) x, y, z = directions.to(torch.float64).unbind(-1) xy = torch.stack((math.cos(angle) * x + math.sin(angle) * y, -math.sin(angle) * x + math.cos(angle) * y), -1) lateral = torch.linalg.vector_norm(xy, dim=-1) theta = torch.atan2(lateral, -z) - radius = unbounded_angular_radius(theta, math.radians(coords.fov) / 2) + boundary_radius, boundary_angle = _angular_padding_boundary(coords) + radius = unbounded_angular_radius(theta, boundary_angle) * boundary_radius cartesian = xy * (radius / lateral.clamp_min(1e-30))[..., None] visible = theta < math.pi - 1e-8 native = coords.visual_to_native(cartesian) uv = (native.flip(-1) + 1) / 2 visible = visible & (uv >= 0).all(-1) & (uv <= 1).all(-1) return uv.float(), visible + + +def grid_output_shape(coords: SamplingCoords) -> tuple[int, int]: + """Resolve public image dimensions, preserving vector cameras' shape.""" + if coords.style == GRID_STYLE: + return coords.resolution, coords.resolution + return len(coords), 1 + + +def mask_grid_samples(outputs: Mapping[str, torch.Tensor | TorchBuffer], coords: SamplingCoords) -> None: + """Zero samples outside the configured footprint before pooling or publication.""" + if coords.style != GRID_STYLE: + return + invalid = ~coords.valid_mask[None, :, None, None] + for name, value in outputs.items(): + if name == "rgb" and "rgba" in outputs: + continue + tensor = buffer_tensor(value) + tensor.masked_fill_(invalid, 0) + + +def allocate_grid_outputs( + outputs: Mapping[str, torch.Tensor | TorchBuffer], coords: SamplingCoords +) -> dict[str, torch.Tensor]: + """Allocate stable public BHWC buffers from flat renderer outputs.""" + result: dict[str, torch.Tensor] = {} + for name, value in outputs.items(): + if name == "rgb" and "rgba" in outputs: + continue + tensor = buffer_tensor(value) + result[name] = tensor.new_zeros((tensor.shape[0], coords.resolution, coords.resolution, tensor.shape[-1])) + if "rgb" in outputs and "rgba" in result: + result["rgb"] = result["rgba"][..., :3] + return result + + +def grid_sample_indices(coords: SamplingCoords) -> torch.Tensor: + """Resolve the public image permutation once, outside rendering updates.""" + return coords.as_grid(torch.arange(len(coords), device=coords.device)).reshape(-1) + + +def copy_grid_outputs( + source: Mapping[str, torch.Tensor | TorchBuffer], + target: dict[str, torch.Tensor], + indices: torch.Tensor, +) -> None: + """Update stable public image buffers without changing sample ordering.""" + for name, value in source.items(): + if name == "rgb" and "rgba" in source: + continue + tensor = buffer_tensor(value) + flat_source = tensor.reshape(tensor.shape[0], -1, tensor.shape[-1]) + flat_target = target[name].view(tensor.shape[0], -1, tensor.shape[-1]) + torch.index_select(flat_source, 1, indices, out=flat_target) + + +class TorchBuffer(Protocol): + """Renderer buffer exposing a Torch view.""" + + @property + def torch(self) -> torch.Tensor: ... + + +def _require_spherical(coords: SamplingCoords) -> None: + if coords.field_geometry != "spherical": + raise ValueError(f"Foveated cameras sample spherical coordinates, got {coords.field_geometry!r}.") + + +def _angular_padding_boundary(coords: SamplingCoords) -> tuple[float, float]: + if coords.fov_type == "circular": + radius = 1.0 + elif coords.fov_type == "square": + radius = math.sqrt(2) + elif coords.fov_type == "wang": + corner = coords.cartesian.new_tensor([[1.0, 1.0]]) + radius = float(torch.linalg.vector_norm(coords.native_to_visual(corner)).item()) + else: + raise ValueError(f"Unsupported native grid footprint {coords.fov_type!r}.") + angle = radius * math.radians(coords.fov) / 2 + if angle >= math.pi: + raise ValueError("Spherical native grid footprint reaches the antipode; reduce FoV or use circular coverage.") + return radius, angle diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py new file mode 100644 index 000000000000..c7093b517c9b --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -0,0 +1,282 @@ +# 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 + +"""Shared retinal-pooling helpers for FoveatedCamera backends. + +Builds a pair of (lowres, highres) :class:`SamplingCoords` and a retinal +pooler analogous to :class:`fovi.sensing.samplers.PoolingGridSampler`, but driven by a +:class:`FoveatedCameraCfg` and operating on rays rather than images. + +Key deviation from ``PoolingGridSampler``: the highres grid shares ``cmf_a`` with +the lowres grid (no ``cmf_a_mult``). Only ``res`` is scaled by +``pool_res_mult`` so the photoreceptor and RGC layers represent the same +visual-field geometry at different densities. + +Construction happens in two stages to accommodate Isaac's sensor init order: +1. ``build_lowres_coords`` + ``build_highres_coords`` run *before* + ``super()._initialize_impl()`` (CPU) so the backend can size its render + buffers from the highres sample count. +2. ``build_pooler`` runs *after* coords have been moved to the sensor's + device, so the KNN indices/distances/Gaussian weights materialise on the + correct device (they are plain tensor attributes and are not moved by + ``nn.Module.to``). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from fovi.arch.knn import KNNPoolingLayer +from fovi.arch.pooling import GridPoolingLayer, build_retinal_pooler +from fovi.sensing.coords import SamplingCoords, auto_match_num_coords + +from .calibrated_geometry import sampling_geometry + +if TYPE_CHECKING: + from .foveated_camera_cfg import FoveatedCameraCfg + + +# Upper bound on ``batch * outputs * k`` elements per modal-pooling chunk. Each chunk holds about ten +# int64 tensors of this size, so peak scratch memory stays near 300 MB regardless of the batch size. +_MODAL_CHUNK_ELEMENTS = 2**22 + + +def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCoords, int]: + """Build the lowres (RGC / public output) SamplingCoords. + + Returns ``(lowres_coords, matched_res)`` where ``matched_res`` is the + auto-matched radial resolution also needed for the highres grid. + """ + fov, cmf_a = sampling_geometry(cfg) + + matched_res, _ = auto_match_num_coords( + fov, + cmf_a, + cfg.foveated_res, + cfg.foveated_style, + 1, + device, + quiet=True, + fov_type=cfg.fov_type, + radius_norm=cfg.radius_norm, + field_geometry="spherical", + ) + lowres = SamplingCoords( + fov=fov, + cmf_a=cmf_a, + res=matched_res, + device=device, + style=cfg.foveated_style, + isotropic_plotting_type=cfg.isotropic_plotting_type, + fov_type=cfg.fov_type, + radius_norm=cfg.radius_norm, + field_geometry="spherical", + ) + return lowres, matched_res + + +def build_highres_coords(cfg: FoveatedCameraCfg, lowres: SamplingCoords, matched_res: int) -> SamplingCoords | None: + """Build the highres (photoreceptor) SamplingCoords when pooling is on: the lowres retina's geometry at + ``pool_res_mult`` times its resolution, on the same device.""" + if not cfg.pool_enabled: + return None + # pool_res_mult is a float to support fractional ratios (e.g. sqrt(2) for + # a 2× N_hi/N_lo ratio). SamplingCoords requires an integer radial res. + return lowres.clone(resolution=int(round(cfg.pool_res_mult * matched_res))) + + +def build_pooler( + cfg: FoveatedCameraCfg, + lowres: SamplingCoords, + highres: SamplingCoords | None, + device: str, +) -> tuple[KNNPoolingLayer | GridPoolingLayer | None, int | None]: + """Build the retinal pooling layer of ``cfg.pool_mode``, which pools every output except segmentation. Both coord + sets must already be on ``device``. + + Segmentation pools by modal label over this pooler's neighbourhoods: pass :func:`segmentation_neighbor_indices` of + it to :func:`pool_segmentation_buffer`. + """ + if highres is None: + return None, None + return build_retinal_pooler( + highres, + lowres, + k=cfg.pool_k, + mode=cfg.pool_mode, + device=device, + sample_cortex=cfg.pool_sample_cortex, + gauss_sigma=cfg.pool_gauss_sigma, + ) + + +def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer) -> torch.Tensor: + """Return a pooler's ``(k, N_lo)`` neighbour table in tie-break order. + + Entries are input-sample indices; ``N_hi`` (the number of input samples) + marks a neighbour excluded by the pooler (spatial padding or a masked input + sample), and every slot of a masked output sample is excluded. + + * :class:`KNNPoolingLayer`: its padded KNN indices, nearest neighbour first. + * :class:`GridPoolingLayer`: the samples in each pooling window (same + padding, stride and masks as the pooler), ordered by distance from the + window centre and then in row-major window order. + """ + if isinstance(pooler, KNNPoolingLayer): + return pooler.knn_indices_pad_token + if not isinstance(pooler, GridPoolingLayer): + raise TypeError(f"Modal pooling needs a KNN or grid pooler, got {type(pooler).__name__}") + + num_inputs = len(pooler.in_coords) + device = pooler.input_mask.device + # Pool sample indices (float64 is exact for any realistic count) with the pooler's own padding; + # -1 marks padding and masked samples. + grid = pooler.in_coords.as_grid(torch.arange(num_inputs, device=device, dtype=torch.float64)[None, None]) + grid = pooler._pad(torch.where(pooler.input_mask, grid, -1.0), -1.0) + side, stride = pooler.kernel_size, pooler.stride + windows = grid[0, 0].unfold(0, side, stride).unfold(1, side, stride) # (H_lo, W_lo, side, side) + windows = windows.flatten(-2).permute(2, 0, 1) # (k, H_lo, W_lo) + axis = torch.arange(side, device=device, dtype=torch.float64) - (side - 1) / 2 + radius = (axis[:, None].square() + axis[None, :].square()).flatten() + windows = windows[torch.sort(radius, stable=True).indices] + windows = torch.where(pooler.output_mask[0], windows, -1.0) + if not pooler.polar: + # Invert the upright Cartesian layout produced by ``as_grid``, as GridPoolingLayer.forward does. + windows = windows.flip(-2).transpose(-2, -1) + indices = windows.flatten(-2).long() + return torch.where(indices < 0, num_inputs, indices) + + +def is_segmentation_output(name: str) -> bool: + """Whether a sensor output holds segmentation labels, which pool with ``pool_int_mode``, the modal label + (:func:`pool_segmentation_buffer`). + + Uses the key name (``"segmentation" in name``) rather than the dtype: every Isaac Lab segmentation variant + (``semantic_segmentation``, ``instance_segmentation_fast``, ``instance_id_segmentation_fast``) holds labels that + averaging would corrupt, whether stored as integer IDs or colorized RGBA. + """ + return "segmentation" in name + + +def pool_hwc_buffer( + pooler: KNNPoolingLayer | GridPoolingLayer, buf: torch.Tensor, visible: torch.Tensor | None = None +) -> torch.Tensor: + """Pool a ``(B, N_hi, 1, C)`` sensor buffer into ``(B, N_lo, 1, C)``. + + Both poolers expect ``(B, C, N)`` inputs, so we permute in and out. + + Args: + pooler: The retinal pooler. + buf: ``(B, N_hi, 1, C)`` floating-point samples. + visible: ``(B, N_hi)`` photoreceptors the physical camera sees, or None for all. The others are left out of + each pooled sample, as the pooler leaves out photoreceptors outside the retina, and a pooled sample that + sees none is zero. + """ + B, N_hi, one, C = buf.shape + assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}" + x = buf[:, :, 0, :].transpose(1, 2).contiguous() # (B, C, N_hi) + if visible is None: + y = pooler(x) # (B, C, N_lo) + else: + seen = visible[:, None, :] + weight = seen.to(x.dtype) + if pooler.mode == "sum": + y = pooler(x * weight) + else: + # Pool the samples with their visibility in one call: a weighted mean over the visible photoreceptors is + # the pooled masked samples over the pooled mask, and a max over them ignores -inf. + masked = torch.where(seen, x, -torch.inf) if pooler.mode == "max" else x * weight + pooled = pooler(torch.cat((masked, weight), dim=1)) + values, coverage = pooled[:, :C], pooled[:, C:] + if pooler.mode != "max": + values = values / coverage.clamp_min(torch.finfo(x.dtype).tiny) + y = torch.where(coverage > 0, values, 0) + return y.transpose(1, 2).unsqueeze(2).contiguous() # (B, N_lo, 1, C) + + +def pool_segmentation_buffer( + neighbors: torch.Tensor, buf: torch.Tensor, visible: torch.Tensor | None = None +) -> torch.Tensor: + """Pool a ``(B, N_hi, 1, C)`` segmentation buffer into ``(B, N_lo, 1, C)`` by majority vote. + + Each output sample takes the most common full channel vector among its + pooling neighbours (so neighbours ``[0, 0, 0]``, ``[0, 0, 0]``, + ``[0, 0, 1]`` give ``[0, 0, 0]``), keeping the buffer's dtype: values are + compared bitwise and copied from an input sample, never converted or mixed. + This holds for integer IDs of any width and for colorized RGBA vectors. + + Ties go to the value whose first occurrence comes earliest in the pooler's + neighbour order (see :func:`segmentation_neighbor_indices`; the nearest + neighbour wins for KNN pooling). Neighbours the pooler excludes, or the + physical camera does not see, do not vote, and outputs without any valid + neighbour are zero, as in fovi. + + Args: + neighbors: ``(k, N_lo)`` neighbour table from :func:`segmentation_neighbor_indices`, on the buffer's device. + buf: ``(B, N_hi, 1, C)`` buffer of any dtype. + visible: ``(B, N_hi)`` photoreceptors the physical camera sees, or None for all. + + Returns: + ``(B, N_lo, 1, C)`` pooled buffer with the dtype of ``buf``. + """ + B, N_hi, one, C = buf.shape + assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}" + indices = neighbors # (k, N_lo), N_hi = excluded + k, N_lo = indices.shape + values = buf[:, :, 0, :].contiguous() # (B, N_hi, C) + # Equality keys, padded with one never-voting sample at index N_hi. + keys = torch.nn.functional.pad(_equality_keys(values), (0, 1)) # (B, N_hi + 1) + valid = (indices != N_hi).T # (N_lo, k) + table = indices.T # (N_lo, k) + chunk_size = max(1, _MODAL_CHUNK_ELEMENTS // max(1, N_lo * k)) + # Visibility, padded like the keys; the never-voting sample is unseen. + seen = None if visible is None else torch.nn.functional.pad(visible, (0, 1)).split(chunk_size) + slots = [] + for index, chunk in enumerate(keys.split(chunk_size)): + chunk_valid = valid if seen is None else valid & seen[index][:, table] # (N_lo, k) or (b, N_lo, k) + slots.append(_modal_slot(chunk[:, table], chunk_valid)) + slot = torch.cat(slots) # (B, N_lo); k where no neighbour is valid + has_value = slot < k + # (B, N_lo) input sample index; outputs without a value read sample 0 and are zeroed below. + source = table.gather(1, slot.clamp(max=k - 1).T).T.clamp(max=N_hi - 1) + pooled = values.gather(1, source.unsqueeze(-1).expand(-1, -1, C)) + pooled = torch.where(has_value.unsqueeze(-1), pooled, torch.zeros((), dtype=buf.dtype, device=buf.device)) + return pooled.unsqueeze(2) + + +def _equality_keys(values: torch.Tensor) -> torch.Tensor: + """Map ``(B, N, C)`` channel vectors to ``(B, N)`` int64 keys that are equal iff the vectors are bitwise equal. + + Vectors of at most 8 bytes are packed into the key directly; wider vectors + fall back to dense ranks from :func:`torch.unique`. + """ + B, N, _ = values.shape + raw = values.view(torch.uint8) if values.dtype != torch.bool else values.to(torch.uint8) + num_bytes = raw.shape[-1] + if num_bytes <= 8: + return torch.nn.functional.pad(raw, (0, 8 - num_bytes)).view(torch.int64).reshape(B, N) + return torch.unique(raw.reshape(B * N, num_bytes), dim=0, return_inverse=True)[1].reshape(B, N) + + +def _modal_slot(keys: torch.Tensor, valid: torch.Tensor) -> torch.Tensor: + """Pick the modal neighbour slot of ``(B, N_lo, k)`` keys; ``valid`` is the ``(N_lo, k)`` or ``(B, N_lo, k)`` + voting mask. + + Returns the ``(B, N_lo)`` earliest slot holding the most common valid key, + or ``k`` where no slot is valid. + """ + k = keys.shape[-1] + sorted_keys, order = torch.sort(keys, dim=-1) + # Label equal-key runs in sorted order, then count valid votes and find the earliest valid slot per run. + new_run = torch.ones_like(sorted_keys, dtype=torch.bool) + new_run[..., 1:] = sorted_keys[..., 1:] != sorted_keys[..., :-1] + run = new_run.cumsum(-1) - 1 + valid_sorted = valid.expand_as(order).gather(-1, order) + votes = torch.zeros_like(run).scatter_add_(-1, run, valid_sorted.long()) + earliest = torch.full_like(run, k).scatter_reduce_(-1, run, torch.where(valid_sorted, order, k), "amin") + # Most votes first, then earliest slot; runs without valid votes score zero. + best = (votes * (k + 1) + (k - earliest)).argmax(-1, keepdim=True) + return earliest.gather(-1, best).squeeze(-1) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index df6b8c4c88fa..001403d620f1 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""The gaze action, its observation, without a simulator.""" +"""The gaze action, its observation and its teacher, without a simulator.""" import math from types import SimpleNamespace @@ -11,14 +11,38 @@ import pytest import torch import warp as wp -from isaaclab_fovi.mdp.gaze import GazeAction, gaze_state, gaze_step_kernel +from fovi.sensing.projection import CameraModel +from isaaclab_fovi.mdp.gaze import ( + GazeAction, + gaze_reset_kernel, + gaze_state, + gaze_step_kernel, + teacher_block_dim, + teacher_labels_kernel, +) from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg -from isaaclab_fovi.sensors.gaze_kernels import torch_stream +from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream +from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab.utils.math import quat_apply, quat_apply_inverse from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless +DEVICES = test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA) + + +def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor: + """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3): up and left are positive.""" + tilt, pan = angles_deg.deg2rad().unbind(-1) + return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) + + +def direction_to_angles(direction: torch.Tensor) -> torch.Tensor: + """Gaze angles [deg] of camera-frame directions, shape (..., 3) to (..., 2): the reference for the kernels.""" + x, y, z = direction.unbind(-1) + return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg() + def clamp_gaze(gaze: torch.Tensor, limit: float) -> torch.Tensor: """Gazes scaled back onto the circle of radius ``limit`` when they leave it: the reference for the step kernel.""" @@ -55,9 +79,131 @@ def test_gaze_step_kernel_matches_the_torch_update(): torch.testing.assert_close(angles, expected * radius, atol=1e-5, rtol=1e-6) -def test_gaze_config_rejects_invalid_bounds(): +def mount_frame(rotation_deg: float) -> torch.Tensor: + """The camera's ``_mask_frame`` for an image rolled by ``rotation_deg``: upright gaze frame to physical frame.""" + angle = torch.tensor(rotation_deg).deg2rad() + c, s = float(angle.cos()), float(angle.sin()) + return torch.tensor([[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]]) + + +# The kernel's block size depends on the device; the image roll is rotated across the two. +TEACHER_CASES = [("cpu", 0.0)] + [(device, 35.0) for device in DEVICES if device != "cpu"] + + +@pytest.mark.parametrize(("device", "rotation_deg"), TEACHER_CASES) +def test_teacher_labels_kernel_matches_the_torch_labels(device, rotation_deg): + camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5), distortion=(-0.1, 0.02, 0.0, 0.0)) + field_radius, step, limit = 30.0, 0.1, 1.0 + frame = mount_frame(rotation_deg) + generator = torch.Generator().manual_seed(5) + count = 4099 + # Each camera has its own mount, as on a moving head. + mount = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1) + positions = torch.randn(count, 3, generator=generator) + lateral = torch.randn(count, 2, generator=generator) * 0.6 + local = torch.cat((lateral, torch.rand(count, 1, generator=generator) + 0.2), -1) + targets = positions + quat_apply(mount, local) + orientations = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1) + offset = torch.tensor([0.0, 0.0, 0.3]) + gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.7 + + # The torch path the kernel replaces: the point fixed to each target, the teacher, then the labels and logs. + points = targets + quat_apply(orientations, offset.expand(count, -1)) + direction = torch.nn.functional.normalize(quat_apply_inverse(mount, points - positions), dim=-1) + + def teachable(direction: torch.Tensor) -> torch.Tensor: + # Gazes are measured in the upright image frame, which the frame carries into the physical camera's. + desired = direction_to_angles(direction @ frame) / field_radius + return camera.project(direction)[1] & (desired.norm(dim=-1) <= limit) + + upright = direction @ frame + desired = direction_to_angles(upright) / field_radius + valid = teachable(direction) + # A target within 1e-4 rad of the image edge, the lens's widest angle or the gaze limit may land on either side + # in float32; every other target must agree exactly. + nudges = 1e-4 * torch.cat((torch.eye(3), -torch.eye(3))) + decisive = torch.stack( + [teachable(torch.nn.functional.normalize(direction + nudge, dim=-1)) == valid for nudge in nudges] + ).all(0) + action = torch.where(valid[:, None], ((desired - gaze) / step).clamp(-1, 1), 0.0) + looking = angles_to_direction(gaze * field_radius) + error = torch.atan2(torch.cross(looking, upright, dim=-1).norm(dim=-1), (looking * upright).sum(-1)).rad2deg() + expected = torch.cat((action, valid[:, None].float()), dim=-1) + + labels = torch.empty(count, 3, device=device) + log = torch.full((2,), float("nan"), device=device) + block = teacher_block_dim(device) + with torch_stream(device): + wp.launch( + teacher_labels_kernel, + dim=(1, block), + inputs=[ + wp.from_torch(targets.to(device), dtype=wp.vec3f), + wp.from_torch(orientations.to(device), dtype=wp.quatf), + wp.vec3f(*offset.tolist()), + wp.from_torch(positions.to(device), dtype=wp.vec3f), + wp.from_torch(mount.to(device), dtype=wp.quatf), + wp.from_torch((gaze * field_radius).to(device), dtype=wp.vec2f), + wp.mat33f(*frame.flatten().tolist()), + field_radius, + step, + limit, + camera_params(camera), + ], + outputs=[wp.from_torch(labels), wp.from_torch(log)], + block_dim=block, + ) + labels, log = labels.cpu(), log.cpu() + assert valid[decisive].any() and (~valid[decisive]).any() and decisive.float().mean() > 0.99 + torch.testing.assert_close(labels[decisive], expected[decisive], atol=1e-4, rtol=0) + labelled = labels[:, 2] > 0.5 + assert float(log[1]) == pytest.approx(float(labelled.float().mean())) + assert float(log[0]) == pytest.approx(float(error[labelled].mean()), rel=1e-4) + + +def test_teacher_gaze_fixates_the_target_through_a_rolled_mount(): + """Following a teacher label puts the fixation, which reaches the physical camera at frame * gaze * z, on the + target.""" + rotation_deg = 120.0 + camera = CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5)) + field_radius, step = 40.0, 10.0 + frame = mount_frame(rotation_deg) + direction = torch.nn.functional.normalize(torch.tensor([[0.25, -0.15, 1.0], [-0.3, 0.2, 1.0]]), dim=-1) + count = len(direction) + identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]]).repeat(count, 1) + labels, log = torch.empty(count, 3), torch.empty(2) + with torch_stream("cpu"): + wp.launch( + teacher_labels_kernel, + dim=(1, 1), + inputs=[ + wp.from_torch(direction, dtype=wp.vec3f), + wp.from_torch(identity, dtype=wp.quatf), + wp.vec3f(0.0, 0.0, 0.0), + wp.zeros(count, dtype=wp.vec3f), + wp.from_torch(identity, dtype=wp.quatf), + wp.zeros(count, dtype=wp.vec2f), + wp.mat33f(*frame.flatten().tolist()), + field_radius, + step, + 1.0, + camera_params(camera), + ], + outputs=[wp.from_torch(labels), wp.from_torch(log)], + block_dim=1, + ) + assert (labels[:, 2] == 1).all() + gaze = labels[:, :2] * step + fixation = angles_to_direction(gaze * field_radius) @ frame.T + torch.testing.assert_close(fixation, direction, atol=1e-5, rtol=0) + # The error is the gaze's angle from the target before the step: the gaze starts on the optical axis. + torch.testing.assert_close(log[0], direction[:, 2].acos().rad2deg().mean(), atol=1e-3, rtol=0) + + +def test_gaze_config_rejects_bounds_that_divide_by_zero_and_unknown_mounts(): GazeActionCfg(asset_name="camera").validate_config() - for field, value in (("step_size", 0.0), ("step_size", float("nan")), ("gaze_limit", math.inf)): + GazeActionCfg(asset_name="camera", mount="tracked").validate_config() + for field, value in (("step_size", 0.0), ("step_size", float("nan")), ("gaze_limit", math.inf), ("mount", "head")): cfg = GazeActionCfg(asset_name="camera") setattr(cfg, field, value) with pytest.raises(ValueError, match=field): @@ -78,22 +224,22 @@ def test_process_actions_moves_the_gaze_by_the_supplied_actions(): term._asset = camera term.field_radius_deg = 20.0 term._state = ProxyArray(wp.zeros(num_envs, dtype=wp.vec4f, device="cpu")) - term._all_ids = wp.array(list(range(num_envs)), dtype=wp.int32, device="cpu") + term._velocity = term._state.torch[:, 2:] term._step_launch = term._raw = None manager_actions = torch.zeros(num_envs, 5) manager_actions[:, 2:4] = torch.tensor([[1.0, 0.0], [0.0, -1.0], [0.5, 0.5], [3.0, 0.0]]) term.process_actions(manager_actions[:, 2:4]) expected = clamp_gaze(manager_actions[:, 2:4].clamp(-1, 1) * 0.1, 1.0) - torch.testing.assert_close(term.processed_actions, expected) - torch.testing.assert_close(term.state[:, 2:], expected / 0.5) + torch.testing.assert_close(term.gaze, expected) + torch.testing.assert_close(term.velocity, expected / 0.5) torch.testing.assert_close(angles.torch, expected * 20.0) assert set_angles[-1] is angles.torch assert term.raw_actions.data_ptr() == manager_actions[:, 2:4].data_ptr() supplied = torch.tensor([[-1.0, 0.0]]).repeat(num_envs, 1) term.process_actions(supplied) - torch.testing.assert_close(term.processed_actions, clamp_gaze(expected - 0.1 * supplied.abs(), 1.0)) + torch.testing.assert_close(term.gaze, clamp_gaze(expected - 0.1 * supplied.abs(), 1.0)) assert term.raw_actions is supplied torch.testing.assert_close( gaze_state(SimpleNamespace(action_manager=SimpleNamespace(get_term=lambda name: term))), term.state @@ -102,11 +248,47 @@ def test_process_actions_moves_the_gaze_by_the_supplied_actions(): # A gaze set on the camera directly is where the next step starts. angles.torch.copy_(torch.tensor([[10.0, 0.0]]).repeat(num_envs, 1)) term.process_actions(torch.zeros(num_envs, 2)) - torch.testing.assert_close(term.processed_actions, torch.tensor([[0.5, 0.0]]).repeat(num_envs, 1)) - - previous = term.state.clone() - term.reset([3, 1]) - torch.testing.assert_close(term.state[[0, 2]], previous[[0, 2]]) - assert not term.state[[1, 3]].any() and not angles.torch[[1, 3]].any() - term.reset() - assert not term.state.any() and not angles.torch.any() + torch.testing.assert_close(term.gaze, torch.tensor([[0.5, 0.0]]).repeat(num_envs, 1)) + + +@pytest.mark.parametrize(("ids", "random_start"), [(None, False), ([3, 0, 7], True)]) +def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start): + count, radius = 10, 23.6 + generator = torch.Generator().manual_seed(6) + angles, state = (torch.randn(count, size, generator=generator) for size in (2, 4)) + selected = torch.arange(count) if ids is None else torch.tensor(ids) + start = torch.randn(len(selected), 2, generator=generator) if random_start else torch.zeros(len(selected), 2) + expected_angles, expected_state = angles.clone(), state.clone() + # The torch reset the kernel replaces: the gaze at its start, at rest. + expected_state[selected] = torch.cat((start, torch.zeros_like(start)), dim=-1) + expected_angles[selected] = start * radius + + with torch_stream("cpu"): + wp.launch( + gaze_reset_kernel, + dim=len(selected), + inputs=[ + wp.from_torch(selected.to(torch.int32)) if ids is not None else wp.zeros(1, dtype=wp.int32), + int(ids is not None), + wp.from_torch(start, dtype=wp.vec2f) if random_start else wp.zeros(1, dtype=wp.vec2f), + int(random_start), + radius, + ], + outputs=[wp.from_torch(angles, dtype=wp.vec2f), wp.from_torch(state, dtype=wp.vec4f)], + ) + torch.testing.assert_close(angles, expected_angles, atol=0, rtol=0) + torch.testing.assert_close(state, expected_state, atol=0, rtol=0) + + +def test_fixed_mount_teacher_rejects_only_turns_after_capture(): + """The fixed-mount teacher aims from the captured mount while the camera has turned its mount as many times as + when the term captured it, and refuses once a later turn makes the capture stale.""" + term = object.__new__(GazeAction) + term.tracked_mount = False + term._mount_turns = 2 + term._fixed_mount = "captured" + term._asset = SimpleNamespace(mount_turns=2) + assert GazeAction.teacher_mounts(term) == "captured" + term._asset.mount_turns = 3 + with pytest.raises(RuntimeError, match="mount='tracked'"): + GazeAction.teacher_mounts(term) diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py index a3c1e0d712ef..aa783bcb2330 100644 --- a/source/isaaclab_fovi/test/test_camera_cfg.py +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -14,7 +14,7 @@ import pytest import torch from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg -from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model +from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_newton.renderers import NewtonWarpRendererCfg @@ -48,22 +48,24 @@ def ray_angle_deg(camera, pixel: tuple[float, float]) -> float: def test_defaults_are_grid_sampling_at_the_human_cmf_estimate() -> None: cfg = FoveatedCameraCfg() + assert cfg.foveated_style == "warped_cartesian_as_grid" assert cfg.cmf_a_deg == 0.591 assert cfg.camera_model is None def test_pinhole_spawn_describes_an_ideal_pinhole_across_its_short_side() -> None: spawn = PinholeCameraCfg() - camera = resolve_camera_model(make_cfg(spawn=spawn)) - fov = camera.field_of_view("short") + fov, cmf_a = sampling_geometry(make_cfg(spawn=spawn)) expected = math.degrees(2 * math.atan(spawn.horizontal_aperture / (2 * spawn.focal_length))) assert fov == pytest.approx(expected, rel=1e-6) + assert cmf_a == 0.591 + camera = resolve_camera_model(make_cfg(spawn=spawn)) assert camera.model == "pinhole" assert camera.distortion == () # Without a vertical aperture the image is square; with one, the retina spans the short (vertical) side. assert camera.image_size[0] == camera.image_size[1] spawn = PinholeCameraCfg(focal_length=10.0, horizontal_aperture=20.0, vertical_aperture=10.0) - fov = resolve_camera_model(make_cfg(spawn=spawn)).field_of_view("short") + fov, _ = sampling_geometry(make_cfg(spawn=spawn)) assert fov == pytest.approx(math.degrees(2 * math.atan(0.5)), rel=1e-6) @@ -94,7 +96,7 @@ def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> No # Equidistant: the angle off the optical axis grows linearly with image radius. for radius in (50.0, 150.0, 310.0): assert ray_angle_deg(camera, (319.5 + radius, 319.5)) == pytest.approx(math.degrees(radius / focal), rel=1e-6) - fov = camera.field_of_view("short") + fov, _ = sampling_geometry(cfg) assert fov == pytest.approx(math.degrees(640 / focal), rel=1e-6) @@ -118,10 +120,25 @@ def test_cameras_fovi_cannot_model_are_rejected() -> None: resolve_camera_model(make_cfg(spawn=spawn)) -@pytest.mark.parametrize("option", [{"pool_enabled": True}, {"foveated_style": "isotropic"}]) -def test_camera_config_rejects_deferred_sampling_options(option) -> None: - with pytest.raises(TypeError, match=next(iter(option))): - make_cfg(**option) +def test_config_validates_pooling_and_shell_settings() -> None: + assert make_cfg(pool_mode="gaussian").pool_mode == "gaussian" + with pytest.raises(ValueError, match="pool_mode must be one of"): + make_cfg(pool_mode="median") + # Segmentation pools only by modal label: other modes would mix labels into ones no object has. + assert make_cfg().pool_int_mode == "modal" + with pytest.raises(ValueError, match="pool_int_mode must be one of"): + make_cfg(pool_int_mode="avg") + # Square shells need a square or circular footprint and a grid style. + grid = dict(foveated_style="warped_cartesian_as_grid", radius_norm=math.inf) + assert make_cfg(**grid, fov_type="square").fov_type == "square" + with pytest.raises(ValueError, match="wang"): + make_cfg(**grid, fov_type="wang") + for kwargs in ( + dict(radius_norm=1.0, foveated_style="warped_cartesian_as_grid"), + dict(radius_norm=math.inf, foveated_style="isotropic"), + ): + with pytest.raises(ValueError, match="radius_norm"): + make_cfg(**kwargs) @dataclass @@ -134,9 +151,7 @@ class CameraSelection: renderer_cfg: RendererSelection -def test_renderer_selects_the_implementation(monkeypatch) -> None: - monkeypatch.setattr(Camera, "__del__", lambda self: None) - +def test_renderer_selects_the_implementation() -> None: def dispatch(cfg) -> type: return type(FoveatedCamera.__new__(FoveatedCamera, cfg)) @@ -155,12 +170,7 @@ def dispatch(cfg) -> type: def test_cameras_that_turn_their_pose_by_the_gaze_need_per_frame_pose_updates(monkeypatch) -> None: """Newton and OVRTX turn the rendered pose by the gaze in each pose update, so without pose updates the renderer would never see the gaze; Isaac RTX writes the gaze into its camera prims instead.""" - - def construct(self, cfg): - self.cfg = cfg - self.stage = None - - monkeypatch.setattr(Camera, "__init__", construct) + monkeypatch.setattr(Camera, "__init__", lambda self, cfg: setattr(self, "stage", None)) monkeypatch.setattr(Camera, "__del__", lambda self: None) monkeypatch.setattr(FoveatedRTXCamera, "_prepare_projection", lambda self: None) monkeypatch.setattr(sim_utils, "find_matching_prims", lambda *args: []) @@ -170,16 +180,14 @@ def cfg(renderer_cfg) -> FoveatedCameraCfg: with pytest.raises(ValueError, match="update_latest_camera_pose=True"): FoveatedCamera(cfg(NewtonWarpRendererCfg())) - assert isinstance(FoveatedCamera(cfg(IsaacRtxRendererCfg())), FoveatedRTXCamera) + assert not FoveatedCamera(cfg(IsaacRtxRendererCfg())).turns_pose_by_gaze IMPORT_BOUNDARY = """ import importlib, importlib.abc, sys # Kit, fovi's research modules and training frameworks must not load with the sensor package. -BLOCKED = ( - "isaacsim", "omni", "fovi.arch", "fovi.models", "fovi.training", "rsl_rl", "ffcv", "wandb", "lightning", "timm", -) +BLOCKED = ("isaacsim", "omni", "fovi.models", "fovi.training", "ffcv", "wandb", "lightning", "timm") class Block(importlib.abc.MetaPathFinder): @@ -189,11 +197,7 @@ def find_spec(self, fullname, path=None, target=None): sys.meta_path.insert(0, Block()) -for module in ( - "isaaclab_fovi.sensors.foveated_newton_camera", - "isaaclab_fovi.sensors.foveated_rtx_camera", - "isaaclab_fovi.mdp.gaze", -): +for module in ("isaaclab_fovi", "isaaclab_fovi.sensors", "isaaclab_fovi.sensors.pooling", "isaaclab_fovi.mdp"): importlib.import_module(module) print("import boundary passed") """ diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index a1110ae5cc49..ae6ac139a472 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -15,17 +15,18 @@ from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel, angular_directions, gaze_rotation from fovi.sensing.retina import RetinalTransform -from isaaclab_fovi.sensors import FoveatedCameraCfg +from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions, sampling_geometry from isaaclab_fovi.sensors.foveated_camera import FoveatedCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.gaze_kernels import ( - CameraParams, camera_params, - project_direction, + project_directions, + publish_grid_kernel, set_gaze_kernel, torch_stream, ) -from isaaclab_fovi.sensors.native_grid import native_grid_directions +from isaaclab_fovi.sensors.native_grid import GRID_STYLE, grid_sample_indices, native_grid_directions +from isaaclab_fovi.sensors.pooling import build_lowres_coords from isaaclab.sensors.camera.camera import Camera from isaaclab.sensors.camera.camera_data import CameraData @@ -36,6 +37,7 @@ matrix_from_quat, quat_apply, quat_from_matrix, + quat_mul, ) from isaaclab.utils.warp import ProxyArray @@ -64,32 +66,31 @@ def camera_config() -> SimpleNamespace: retinal_window_reference_side="long", retinal_window_fraction=0.75, foveated_res=12, - mask_to_sensor_fov=True, + foveated_style="isotropic", + fov_type="circular", + radius_norm=2.0, + isotropic_plotting_type="v1like", image_rotation_deg=0.0, ) -def test_camera_sampling_matches_software_sampling(monkeypatch) -> None: - data = camera_config() - model = CameraModel(**data.camera_model) - cfg = FoveatedCameraCfg(prim_path="/World/Camera", **vars(data)) - monkeypatch.setattr(Camera, "__init__", lambda self, cfg: setattr(self, "cfg", cfg)) - monkeypatch.setattr(Camera, "__del__", lambda self: None) - camera = FoveatedCamera.__new__(FoveatedCamera, cfg) - FoveatedCamera.__init__(camera, cfg) - software = RetinalTransform( - fov=model.field_of_view("long", 0.75), - cmf_a=2.5, +def test_rendering_and_software_sampling_share_window_and_nodes() -> None: + cfg = camera_config() + fov, a = sampling_geometry(cfg) + camera = CameraModel(**cfg.camera_model) + assert fov == pytest.approx(camera.field_of_view("long", 0.75)) + assert a == 2.5 + coords, _ = build_lowres_coords(cfg, "cpu") + retina = RetinalTransform( + fov=fov, + cmf_a=a, resolution=12, device="cpu", - style="warped_cartesian_as_grid", field_geometry="spherical", - camera_model=model, + camera_model=camera, gaze_convention="pan_tilt", ) - torch.testing.assert_close(camera.sampling_coords.cartesian, software.sampler.coords.cartesian) - assert (camera.cfg.width, camera.cfg.height) == (12, 12) - assert (cfg.width, cfg.height) == (1, 1) + torch.testing.assert_close(coords.cartesian, retina.sampler.coords.cartesian) class GazeHarness(FoveatedCamera): @@ -105,20 +106,15 @@ def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None: self._view = SimpleNamespace(count=count) self._device = device self._ALL_INDICES = wp.array(list(range(count)), dtype=wp.int32, device=device) - self._camera_model = CameraModel(**self.cfg.camera_model) - fov = self._camera_model.field_of_view(self.cfg.retinal_window_reference_side, self.cfg.retinal_window_fraction) - self._sampling_coords = SamplingCoords( - fov, self.cfg.cmf_a_deg, self.cfg.foveated_res, style="warped_cartesian_as_grid", field_geometry="spherical" - ) - self._retinal_rays = native_grid_directions( - self._sampling_coords, image_rotation_deg=self.cfg.image_rotation_deg - ) + self._sampling_coords, _ = build_lowres_coords(self.cfg, device) + self._sampling_coords_highres = None # The camera's own pose buffers, at the identity orientation, with their world-to-ROS conversion. self._data = CameraData() self._data.create_buffers(count, device) self._data.quat_w_world.torch[:, 3] = 1.0 # Isaac RTX's behaviour; Newton and OVRTX turn the pose by the gaze in their pose update. self._gaze_pose_reads_angles = False + self._gaze_written = False self._initialize_gaze() @property @@ -155,11 +151,11 @@ def set_local_poses(self, *, orientations) -> None: class RtxGazeHarness(GazeHarness, FoveatedRTXCamera): """The Isaac RTX camera's prim-writing gaze on stand-in camera prims.""" - def __init__(self, mount_opengl: torch.Tensor, device="cpu") -> None: - super().__init__(count=len(mount_opengl), device=device) + def __init__(self, mount_opengl: torch.Tensor) -> None: + super().__init__(count=len(mount_opengl)) self._view = PrimView(mount_opengl) - self._base_local_orientation = mount_opengl.clone() - self._gaze_basis_quat = quat_from_matrix(self._gaze_basis) + self._base_local_orientation = matrix_from_quat(mount_opengl) + self.mount_turns = 0 MOUNT = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) @@ -171,7 +167,7 @@ def write_view(camera, eyes, targets, env_ids=None): looks at it; the others keep their poses.""" rotation = create_rotation_matrix_from_view(eyes, targets, "Z") looks = ~torch.isnan(rotation).any(dim=(-2, -1)) - ids = (torch.arange(camera._view.count) if env_ids is None else torch.as_tensor(env_ids))[looks] + ids = camera._env_indices(env_ids)[looks] camera._view.local[ids] = quat_from_matrix(rotation[looks]) @@ -188,6 +184,23 @@ def gaze_direction(angles_deg: torch.Tensor) -> torch.Tensor: return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) +def angles_toward(camera: CameraModel, pixel: tuple[float, float]) -> torch.Tensor: + """(tilt, pan) gaze angles [deg] that look along the ray through a source pixel (x, y).""" + direction, _ = camera.unproject(torch.tensor([pixel])) + x, y, z = direction.unbind(-1) + return torch.stack((-torch.atan2(y, torch.sqrt(x * x + z * z)), -torch.atan2(x, z)), -1).rad2deg() + + +def test_sensor_mask_keeps_what_the_camera_sees_at_an_edge_gaze() -> None: + """Looking just past an image edge keeps the part of the retina the camera still sees; looking away keeps none.""" + camera = GazeHarness(count=2) + edge = angles_toward(camera._camera_model, (120.5, 39.5)) + camera.set_gaze_angles(torch.cat((edge, torch.tensor([[0.0, 180.0]])))) + valid = camera._gaze_validity() + assert valid[0].any() and not valid[0].all() + assert not valid[1].any() + + @pytest.mark.parametrize("device", CUDA) @pytest.mark.parametrize( "mode, autocast", @@ -241,54 +254,65 @@ def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, m assert torch.get_float32_matmul_precision() == "high" -@pytest.mark.parametrize("model_name", ["distorted pinhole", "fisheye with image circle"]) -def test_camera_publishes_only_visible_samples_in_updated_rows(model_name): - model = KERNEL_CAMERAS[model_name] - camera = GazeHarness( - device=KERNEL_DEVICE, - camera_model=asdict(model), - image_rotation_deg=37.0, - retinal_window_reference_side="short", - retinal_window_fraction=0.7, - ) - coords = camera.sampling_coords - n = coords.resolution - rgba = torch.arange(2 * n * n * 4, device=KERNEL_DEVICE).reshape(2, n, n, 4).to(torch.uint8) - depth = torch.arange(1, 2 * n * n + 1, device=KERNEL_DEVICE, dtype=torch.float32).reshape(2, n, n, 1) - camera._prepare_grid_publish({"rgba": rgba, "rgb": rgba[..., :3], "distance_to_camera": depth}) - outputs = camera._data.output - angles = torch.tensor([[6.0, -11.0], [-9.0, 17.0]], device=KERNEL_DEVICE) - camera.set_gaze_angles(angles) +def test_sensor_mask_checks_the_rendered_rays_of_a_rolled_mount() -> None: + """The mask sees exactly the rays the turned camera renders, found here through the camera pose instead.""" + rotation_deg = 30.0 + # An off-center, wide image makes a roll change which samples the camera sees. + model = CameraModel("pinhole", (80, 120), (60.0, 60.0, 45.0, 30.0)) + camera = GazeHarness(camera_model=asdict(model), image_rotation_deg=rotation_deg) + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) mount = camera.orientation.clone() camera._apply_gaze_pose() - def opengl(orientation): + # Rendered rays leave the turned camera along its OpenGL frame; express them in the mount's OpenGL frame. + def opengl(orientation: torch.Tensor) -> torch.Tensor: return matrix_from_quat(convert_camera_frame_orientation_convention(orientation, "world", "opengl")) - rotation = opengl(mount).transpose(-1, -2) @ opengl(camera.orientation) - # fovi's direction generation in the physical frame, independently of the publication kernel. - ray = angular_directions(coords.cartesian, coords.fov) - x, y, z = ray.unbind(-1) - c, s = math.cos(math.radians(37)), math.sin(math.radians(37)) - gl = torch.stack((c * x + s * y, s * x - c * y, -z), -1) - turned_ray = (gl @ rotation.transpose(-1, -2)) * gl.new_tensor((1.0, -1.0, -1.0)) - keep = model.project(turned_ray)[1] & coords.valid_mask[None] - assert keep.any() and (~keep).any() - - all_rows = wp.ones(2, dtype=wp.bool, device=KERNEL_DEVICE) - camera._publish_grid(all_rows) - for name, values in (("rgba", rgba), ("distance_to_camera", depth)): - canonical = values.reshape(2, n * n, -1) - expected = coords.as_grid(canonical * keep[..., None], sample_dim=1) - torch.testing.assert_close(outputs[name].torch, expected) - assert outputs["rgb"].warp.ptr == outputs["rgba"].warp.ptr - - last = outputs["distance_to_camera"].torch.clone() - depth.add_(1) - camera._publish_grid(wp.array([False, True], dtype=wp.bool, device=KERNEL_DEVICE)) - assert camera._data.output["distance_to_camera"] is outputs["distance_to_camera"] - assert torch.equal(last[0], outputs["distance_to_camera"].torch[0]) - assert not torch.equal(last[1], outputs["distance_to_camera"].torch[1]) + turn = opengl(mount).transpose(-1, -2) @ opengl(camera.orientation) + coords = camera._sampling_coords + rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) + seen = (turn[:, None] @ rays[None, :, :, None]).squeeze(-1) * torch.tensor([1.0, -1.0, -1.0]) + expected = model.project(seen)[1] + assert expected.any() and (~expected).any() + assert (camera._gaze_validity() == expected).float().mean() > 0.999 + + +def test_only_a_turned_mount_is_recorded(monkeypatch) -> None: + """The fixed-mount teacher reads the live camera position, so only writes that turn a mount count: not a position + move, and not writing back the reported mount (of either quaternion sign), even with a gaze held in the prims.""" + monkeypatch.setattr(Camera, "set_world_poses", write_prims) + monkeypatch.setattr(Camera, "set_world_poses_from_view", write_view) + eyes = torch.zeros(2, 3) + targets = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) + + def view_twice(camera): + # Looking again from the same eye at the same target leaves the mount where the first view put it. + camera.set_world_poses_from_view(eyes, targets) + camera.mount_turns = 0 + camera.set_world_poses_from_view(eyes, targets) + + def reported(camera, env_ids=None): + return camera.get_world_poses(env_ids, convention="ros")[1] + + def turn_second(camera): + # One degree about the second camera's optical axis. + half = torch.tensor(math.radians(1.0) / 2) + roll = torch.tensor([[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, float(half.sin()), float(half.cos())]]) + camera.set_world_poses(orientations=quat_mul(reported(camera), roll)) + + for move, turned in ( + (lambda camera: camera.set_world_poses(positions=torch.zeros(2, 3)), False), + (lambda camera: camera.set_world_poses(orientations=reported(camera)), False), + (lambda camera: camera.set_world_poses(orientations=-reported(camera, [1]), env_ids=[1]), False), + (turn_second, True), + (lambda camera: camera.set_world_poses_from_view(eyes, eyes), False), + (lambda camera: camera.set_world_poses_from_view(eyes, targets), True), + (view_twice, False), + ): + camera = RtxGazeHarness(MOUNT) + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) + move(camera) + assert camera.mount_turns == int(turned) def test_gaze_angles_need_one_row_per_camera() -> None: @@ -298,12 +322,68 @@ def test_gaze_angles_need_one_row_per_camera() -> None: assert camera._gaze_angles is None +def test_mount_record_starts_at_the_current_pose() -> None: + """Allocating the gaze before any pose update records the camera's current, ungazed mount, not zeros.""" + camera = GazeHarness() + camera._gaze_pose_reads_angles = True + mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) + camera.orientation.copy_(mount) + camera.gaze_angles + expected = convert_camera_frame_orientation_convention(mount, "world", "ros") + torch.testing.assert_close( + matrix_from_quat(camera.ungazed_quat_w_ros()), matrix_from_quat(expected), atol=1e-6, rtol=0 + ) + + +def test_prim_writing_camera_reads_its_mount_before_and_after_a_gaze() -> None: + """Isaac RTX writes the gaze into its prims; its mount reads the same before and after a gaze is set, so a + fixed-mount teacher created after a gaze aims from the real mount.""" + camera = RtxGazeHarness(MOUNT) + # The last pose update read the bare mount. + camera.orientation.copy_(convert_camera_frame_orientation_convention(MOUNT, "opengl", "world")) + expected = matrix_from_quat(convert_camera_frame_orientation_convention(MOUNT, "opengl", "ros")) + torch.testing.assert_close(matrix_from_quat(camera.ungazed_quat_w_ros()), expected, atol=1e-6, rtol=0) + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) + assert not torch.allclose(matrix_from_quat(camera._view.local), matrix_from_quat(MOUNT), atol=1e-3) + torch.testing.assert_close(matrix_from_quat(camera.ungazed_quat_w_ros()), expected, atol=1e-6, rtol=0) + + +def test_sensor_mask_reuses_its_buffer_and_keeps_rows_that_were_not_updated() -> None: + camera = GazeHarness() + camera.cfg.mask_to_sensor_fov = True + camera.set_gaze_angles(torch.tensor([[0.0, 0.0], [0.0, 0.0]])) + first = camera._gaze_validity() + kept = first[0].clone() + output = {"distance_to_camera": torch.ones(2, len(camera._gaze_rays), 1, 1)} + camera.set_gaze_angles(torch.tensor([[0.0, 180.0], [0.0, 180.0]])) + camera._apply_sensor_fov_mask(output, wp.array([False, True], dtype=wp.bool, device="cpu")) + assert camera._visibility["valid"].torch is first + # The environment that was not updated keeps its samples and its last visibility. + torch.testing.assert_close(first[0], kept) + assert bool(output["distance_to_camera"][0].all()) + assert not output["distance_to_camera"][1].any() + + +def test_pose_update_records_the_mount_before_the_gaze() -> None: + camera = GazeHarness() + mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1) + camera.orientation.copy_(mount) + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) + camera._apply_gaze_pose() + expected = convert_camera_frame_orientation_convention(mount, "world", "ros") + torch.testing.assert_close( + matrix_from_quat(camera._mount_quat_ros.torch), matrix_from_quat(expected), atol=1e-6, rtol=0 + ) + assert not torch.allclose(camera.orientation, mount) + + def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pose() -> None: camera = GazeHarness() angles = torch.tensor([[6.0, -11.0], [-9.0, 17.0]]) camera.set_gaze_angles(angles) camera._apply_gaze_pose() forward = quat_apply(camera.orientation, torch.tensor([[1.0, 0.0, 0.0]]).expand(2, -1)) + source = CameraModel(**camera.cfg.camera_model) # The world camera frame looks along +X with +Z up; OpenCV looks along +Z with +Y down. directions = gaze_direction(angles) expected = torch.stack((directions[:, 2], -directions[:, 0], -directions[:, 1]), -1) @@ -313,12 +393,28 @@ def test_virtual_pose_aims_rays_without_translation_and_preserves_unselected_pos camera.orientation[0] = torch.tensor([0.0, 0.0, 0.0, 1.0]) camera._apply_gaze_pose([0]) torch.testing.assert_close(camera.orientation[1], untouched) + torch.testing.assert_close( + camera._gaze_validity(), + source.project( + angular_directions(camera._sampling_coords.cartesian, camera._sampling_coords.fov) + @ camera._gaze_rotation.torch.transpose(-1, -2) + )[1], + ) + + +def test_renderer_ray_frame_matches_cv_frame() -> None: + coords = torch.tensor([[0.0, 0.0], [0.3, -0.4], [-1.0, 0.0]]) + rendered = retinal_directions(coords, 120) + cv = angular_directions(coords, 120) + torch.testing.assert_close(rendered, cv * torch.tensor([1, -1, -1])) @pytest.mark.parametrize("device", CUDA) def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_enabled) -> None: - camera = RtxGazeHarness( - torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(48, 1), device=device + camera = GazeHarness(count=48, device=device) + camera._gaze_basis = camera._gaze_basis.to(device) + camera._base_local_orientation = matrix_from_quat( + torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(48, 1) ) written = [] camera._view = SimpleNamespace( @@ -330,6 +426,7 @@ def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_ for enabled in [False, True]: with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled): camera.set_gaze_angles(angles) + FoveatedRTXCamera._write_gaze_local_pose(camera) assert torch.isfinite(written[1]).all() assert written[1].dtype == torch.float32 torch.testing.assert_close(written[1].norm(dim=-1), torch.ones(48, device=device)) @@ -340,7 +437,6 @@ def test_rtx_world_poses_are_the_mount_so_a_round_trip_keeps_mount_and_gaze(monk """Isaac RTX holds the gaze in its prims; its world poses still report the bare mount, as the other renderers' do, so writing them back (as a viewer navigating the camera does) neither moves the mount nor doubles the gaze.""" monkeypatch.setattr(Camera, "set_world_poses", write_prims) - monkeypatch.setattr(Camera, "set_world_poses_from_view", write_view) camera = RtxGazeHarness(MOUNT) mount = MOUNT camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) @@ -351,23 +447,11 @@ def test_rtx_world_poses_are_the_mount_so_a_round_trip_keeps_mount_and_gaze(monk expected = convert_camera_frame_orientation_convention(mount[1:], "opengl", "ros") torch.testing.assert_close(matrix_from_quat(orientations), matrix_from_quat(expected), atol=1e-6, rtol=0) - camera.set_world_poses(positions=torch.zeros(2, 3)) - torch.testing.assert_close(matrix_from_quat(camera._view.local), matrix_from_quat(gazed), atol=1e-6, rtol=0) _, orientations = camera.get_world_poses(convention="world") camera.set_world_poses(orientations=orientations, convention="world") - torch.testing.assert_close( - matrix_from_quat(camera._base_local_orientation), matrix_from_quat(mount), atol=1e-6, rtol=0 - ) + torch.testing.assert_close(camera._base_local_orientation, matrix_from_quat(mount), atol=1e-6, rtol=0) torch.testing.assert_close(matrix_from_quat(camera._view.local), matrix_from_quat(gazed), atol=1e-6, rtol=0) - eyes = torch.zeros(2, 3) - targets = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) - camera.set_world_poses_from_view(eyes, targets) - torch.testing.assert_close(matrix_from_quat(camera._view.local[:1]), matrix_from_quat(gazed[:1]), atol=1e-6, rtol=0) - _, pose = camera.get_world_poses(convention="opengl") - expected = create_rotation_matrix_from_view(eyes[1:], targets[1:], "Z") - torch.testing.assert_close(matrix_from_quat(pose[1:]), expected, atol=1e-6, rtol=0) - @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) def test_gaze_kernels_preserve_shared_stream_for_warp_capture(device: str) -> None: @@ -376,17 +460,14 @@ def test_gaze_kernels_preserve_shared_stream_for_warp_capture(device: str) -> No with wp.ScopedStream(stream), torch.cuda.stream(wp.stream_to_torch(stream)): camera = GazeHarness(device=device) camera.set_gaze_angles(torch.tensor([[5.0, -8.0], [0.0, 0.0]], device=device)) - n = camera.sampling_coords.resolution - camera._prepare_grid_publish({"rgb": torch.ones(2, n, n, 3, dtype=torch.uint8, device=device)}) - camera._publish_grid(wp.ones(2, dtype=wp.bool, device=device)) - output = camera._data.output["rgb"].warp - target = wp.zeros_like(output) + valid = camera._gaze_validity() + target = wp.zeros(valid.shape, dtype=wp.bool, device=device) # Physics must still be able to capture after the camera's temporary stream scopes exit. with wp.ScopedCapture(stream=stream) as capture: - wp.copy(target, output) + wp.copy(target, wp.from_torch(valid)) wp.capture_launch(capture.graph) - torch.testing.assert_close(wp.to_torch(target), wp.to_torch(output)) - assert wp.to_torch(output)[1].any() + torch.testing.assert_close(wp.to_torch(target), valid) + assert valid[1].any() # -- The gaze kernels against fovi's camera geometry ------------------------------------------------------------------ @@ -426,19 +507,6 @@ def set_gaze(angles: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: return stored, rotation -@wp.kernel -def _probe_projection( - directions: wp.array(dtype=wp.vec3f), - camera: CameraParams, - pixels: wp.array(dtype=wp.vec2f), - valid: wp.array(dtype=wp.bool), -): - i = wp.tid() - result = project_direction(directions[i], camera) - pixels[i] = wp.vec2f(result[0], result[1]) - valid[i] = result[2] > 0.5 - - @pytest.mark.parametrize("name", KERNEL_CAMERAS) def test_projection_kernel_matches_fovi(name: str) -> None: """The sensor mask projects with fovi's camera model, as the software sampler does on a real camera.""" @@ -449,19 +517,7 @@ def test_projection_kernel_matches_fovi(name: str) -> None: directions[:2000, 2] *= -1 directions = torch.nn.functional.normalize(directions, dim=-1).to(KERNEL_DEVICE) expected_pixels, expected_valid = camera.project(directions) - pixels = torch.empty_like(expected_pixels) - valid = torch.empty_like(expected_valid) - with torch_stream(KERNEL_DEVICE): - wp.launch( - _probe_projection, - len(directions), - [ - wp.from_torch(directions, dtype=wp.vec3f), - camera_params(camera), - wp.from_torch(pixels, dtype=wp.vec2f), - wp.from_torch(valid), - ], - ) + pixels, valid = project_directions(directions, camera_params(camera)) # Float32 rounding may flip a sample that lies on the image edge, nothing more. assert (valid == expected_valid).float().mean() > 0.9995 assert expected_valid.any() and (~expected_valid).any() @@ -477,3 +533,60 @@ def test_gaze_rotation_follows_fovis_pan_tilt_convention() -> None: direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) torch.testing.assert_close(stored, angles, atol=0, rtol=0) torch.testing.assert_close(rotation, gaze_rotation(direction, "pan_tilt"), atol=1e-5, rtol=0) + + +def test_publish_kernel_matches_masking_then_copying_to_the_grid() -> None: + camera = KERNEL_CAMERAS["distorted pinhole"] + coords = SamplingCoords( + camera.field_of_view("short"), 0.591, 24, style=GRID_STYLE, field_geometry="spherical", device=KERNEL_DEVICE + ) + rays = (native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1))).float().contiguous() + generator = torch.Generator().manual_seed(2) + angles = ((torch.rand(6, 2, generator=generator) * 2 - 1) * 25).to(KERNEL_DEVICE) + _, rotation = set_gaze(angles) + count = len(coords) + outputs = { + "rgba": torch.randint(1, 255, (6, count, 1, 4), generator=generator, dtype=torch.uint8).to(KERNEL_DEVICE), + "depth": (torch.rand(6, count, 1, 1, generator=generator) + 0.5).to(KERNEL_DEVICE), + } + valid = camera.project(rays @ rotation.transpose(-1, -2))[1] + # Environments 1 and 4 were not rendered this frame and keep their previous image. + updated = torch.tensor([True, False, True, True, False, True], device=KERNEL_DEVICE) + + # The sequence the kernel replaces: footprint mask, sensor mask, then the upright layout. The layout comes from + # fovi's own grid reshaping rather than the index permutation the kernel uses. + keep = valid & coords.valid_mask[None] + expected_grid = { + name: coords.as_grid(value.squeeze(2) * keep[..., None], sample_dim=1) for name, value in outputs.items() + } + indices = grid_sample_indices(coords).to(torch.int32).contiguous() + visible = torch.zeros(6, count, dtype=torch.bool, device=KERNEL_DEVICE) + identity = wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) + for name, value in outputs.items(): + previous = torch.full_like(expected_grid[name], 7) + target = previous.clone() + with torch_stream(KERNEL_DEVICE): + wp.launch( + publish_grid_kernel, + dim=(6, count), + inputs=[ + wp.from_torch(value.squeeze(2).view(torch.uint8)), + wp.from_torch(indices), + wp.from_torch(coords.valid_mask.contiguous()), + wp.from_torch(updated), + wp.from_torch(rays, dtype=wp.vec3f), + wp.from_torch(rotation, dtype=wp.mat33f), + identity, + camera_params(camera), + 1, + int(name == "rgba"), + wp.from_torch(visible), + ], + outputs=[wp.from_torch(target.view(6, count, -1).view(torch.uint8))], + ) + # Float32 rounding may flip a sample on the image edge, nothing more. + assert (target[updated] == expected_grid[name][updated]).all(-1).float().mean() > 0.999 + assert torch.equal(target[~updated], previous[~updated]) + assert (visible[updated] == valid[updated]).float().mean() > 0.999 + assert not visible[~updated].any() + assert valid.any() and (~valid).any() diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py index bdd383d28d7e..fce1bef4556f 100644 --- a/source/isaaclab_fovi/test/test_native_grid.py +++ b/source/isaaclab_fovi/test/test_native_grid.py @@ -3,20 +3,47 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""The analytic lens textures use the software sampler's directions and invert the native grid.""" +"""The native grid's rays, lens textures and published layout agree with independent geometry.""" import math import pytest import torch from fovi.sensing.coords import SamplingCoords -from fovi.sensing.projection import angular_directions +from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions from isaaclab_fovi.sensors.lens_lut import build_native_grid_textures -from isaaclab_fovi.sensors.native_grid import bounded_angular_radius, native_grid_directions, native_grid_exit_uv +from isaaclab_fovi.sensors.native_grid import ( + allocate_grid_outputs, + bounded_angular_radius, + copy_grid_outputs, + grid_sample_indices, + mask_grid_samples, + native_grid_directions, + native_grid_exit_uv, + unbounded_angular_radius, +) + +from isaaclab.test.utils import DeviceScope, test_devices pytestmark = pytest.mark.kitless +def make_coords(resolution: int = 64, coverage: str = "circular", field: str = "spherical") -> SamplingCoords: + """A wide grid; ``"square_shells"`` is the square footprint with square (infinity-norm) shells.""" + fov = 80.0 if coverage == "wang" else 170.0 + square_shells = coverage == "square_shells" + return SamplingCoords( + fov=fov, + cmf_a=0.036021 * fov, + res=resolution, + style="warped_cartesian_as_grid", + fov_type="square" if square_shells else coverage, + radius_norm=math.inf if square_shells else 2.0, + field_geometry=field, + device="cpu", + ) + + def texel_centers(resolution: int) -> torch.Tensor: """Native texture UV of each canonical sample: columns follow native x, rows native y.""" axis = (torch.arange(resolution) + 0.5) / resolution @@ -24,31 +51,133 @@ def texel_centers(resolution: int) -> torch.Tensor: return torch.stack((col, row), -1).reshape(-1, 2) -def test_rolled_grid_matches_fovi_and_inverts_every_texel(): - coords = SamplingCoords(170.0, 6.0, 65, style="warped_cartesian_as_grid", field_geometry="spherical") - roll = math.radians(37.0) - rendered = native_grid_directions(coords, image_rotation_deg=37.0) - valid = coords.valid_mask - cv_rays = angular_directions(coords.cartesian[valid], coords.fov) - x, y, z = cv_rays.unbind(-1) - reference = torch.stack((math.cos(roll) * x + math.sin(roll) * y, math.sin(roll) * x - math.cos(roll) * y, -z), -1) - torch.testing.assert_close(rendered[valid], reference, atol=3e-7, rtol=0) +def eccentricity_rays(visual: torch.Tensor, fov_deg: float, rotation_deg: float = 0.0) -> torch.Tensor: + """OpenGL rays for visual-chart points: angle off the axis is the visual radius times the half field of view.""" + visual = visual.to(torch.float64) + theta = torch.linalg.vector_norm(visual, dim=-1) * math.radians(fov_deg) / 2 + phi = torch.atan2(visual[..., 1], visual[..., 0]) + math.radians(rotation_deg) + return torch.stack((theta.sin() * phi.cos(), theta.sin() * phi.sin(), -theta.cos()), -1) + + +@pytest.mark.parametrize( + ("coverage", "resolution", "rotation"), + # Circular padding outside the field, and odd square-shell grids with a texel on the axis, under a roll. + [("circular", 64, 0.0), ("square_shells", 15, 37.0)], +) +def test_every_texel_roundtrips(coverage: str, resolution: int, rotation: float) -> None: + coords = make_coords(resolution, coverage) + rays = native_grid_directions(coords, image_rotation_deg=rotation) + uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) + assert valid.all() + torch.testing.assert_close(uv, texel_centers(resolution), atol=2e-6, rtol=0) + torch.testing.assert_close(rays.norm(dim=-1), torch.ones(len(coords)), atol=1e-6, rtol=0) + + +@pytest.mark.parametrize(("coverage", "rotation"), [("wang", 180.0), ("square_shells", 37.0)]) +def test_inverse_maps_independent_rays_to_their_texels(coverage: str, rotation: float) -> None: + coords = make_coords(64, coverage) + half_fov = math.radians(coords.fov) / 2 + # Rays through fovi's own sample positions inside the field land on those samples' texels. + inside = torch.linalg.vector_norm(coords.cartesian, dim=-1) <= (math.sqrt(2) if coverage == "square_shells" else 1) + rays = eccentricity_rays(coords.cartesian[inside], coords.fov, rotation) + uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation) + assert inside.sum() > len(coords) // 2 + assert valid.all() + torch.testing.assert_close(uv, texel_centers(64)[inside], atol=2e-6, rtol=0) + # The optical axis is the texture centre and the nominal rim along each rolled native axis is its edge. + roll = math.radians(rotation) + rim = [ + (math.sin(half_fov) * math.cos(angle), math.sin(half_fov) * math.sin(angle), -math.cos(half_fov)) + for angle in (roll, roll + math.pi / 2) + ] + hand_rays = torch.tensor([(0.0, 0.0, -1.0), *rim], dtype=torch.float64) + uv, _ = native_grid_exit_uv(hand_rays, coords, image_rotation_deg=rotation) + torch.testing.assert_close(uv, torch.tensor([[0.5, 0.5], [0.5, 1.0], [1.0, 0.5]]), atol=1e-6, rtol=0) - uv, visible = native_grid_exit_uv(rendered, coords, image_rotation_deg=37.0) - assert visible.all() - torch.testing.assert_close(uv, texel_centers(coords.resolution), atol=2e-6, rtol=0) - directions, exit_uv = build_native_grid_textures(coords, rendered, image_rotation_deg=37.0, exit_size=129) - torch.testing.assert_close(directions.reshape(-1, 3), rendered) - torch.testing.assert_close(exit_uv[64, 64], torch.tensor([0.5, 0.5])) - torch.testing.assert_close(exit_uv[0, 0], torch.tensor([-1.0, -1.0])) +def test_valid_samples_match_the_software_sampler_rays() -> None: + """The renderer's rays are the ones fovi's software sampler uses on a real camera's images.""" + coords = make_coords() + actual = native_grid_directions(coords) + expected = retinal_directions(coords.cartesian[coords.valid_mask], coords.fov) + torch.testing.assert_close(actual[coords.valid_mask], expected, atol=3e-7, rtol=0) + with pytest.raises(ValueError, match="spherical"): + native_grid_directions(make_coords(16, field="planar")) -def test_spherical_padding_matches_rim_slope_and_does_not_wrap(): - radius = torch.tensor([0.99999, 1.0, 1.00001, 2.0, 10.0], dtype=torch.float64) +def test_spherical_padding_matches_rim_slope_and_does_not_wrap() -> None: + radius = torch.tensor([0.0, 0.99999, 1.0, 1.00001, 2.0, 10.0], dtype=torch.float64) half_fov = math.radians(170) / 2 angles = bounded_angular_radius(radius, half_fov) - assert (angles[1:] > angles[:-1]).all() and (angles < math.pi).all() - left = (angles[1] - angles[0]) / (radius[1] - radius[0]) - right = (angles[2] - angles[1]) / (radius[2] - radius[1]) + assert (angles[1:] > angles[:-1]).all() + assert (angles < math.pi).all() + left = (angles[2] - angles[1]) / (radius[2] - radius[1]) + right = (angles[3] - angles[2]) / (radius[3] - radius[2]) torch.testing.assert_close(left, right, atol=2e-5, rtol=0) + torch.testing.assert_close(unbounded_angular_radius(angles, half_fov), radius, atol=1e-10, rtol=0) + + +@pytest.mark.parametrize(("coverage", "rotation"), [("circular", 0.0), ("square_shells", 37.0)]) +def test_textures_match_independent_geometry(coverage: str, rotation: float) -> None: + coords = make_coords(64, coverage) + size = 256 + direction, inverse = build_native_grid_textures(coords, image_rotation_deg=rotation, exit_size=size) + assert direction.shape == (64, 64, 3) and inverse.shape == (size, size, 2) + inside = coords.valid_mask & (torch.linalg.vector_norm(coords.cartesian, dim=-1) <= math.sqrt(2)) + expected = eccentricity_rays(coords.cartesian[inside], coords.fov, rotation).float() + torch.testing.assert_close(direction.reshape(-1, 3)[inside], expected, atol=1e-6, rtol=0) + # Forward-hemisphere octahedral texel centres decode to (x, y, -(1 - |x| - |y|)) before normalization. + axis = (torch.arange(size, dtype=torch.float64) + 0.5) / size * 2 - 1 + y, x = torch.meshgrid(axis, axis, indexing="ij") + forward = x.abs() + y.abs() < 1 + texel_rays = torch.nn.functional.normalize(torch.stack((x, y, x.abs() + y.abs() - 1), -1), dim=-1) + # Each stored UV, mapped back through fovi's native-to-visual warp, must look along its texel's ray. + stored = forward & (inverse[..., 0] >= 0) + native = (inverse[stored].to(torch.float64) * 2 - 1).flip(-1) + visual = coords.native_to_visual(native) + # Circular grids pad outside the nominal field on another curve; square shells reach their corners linearly. + linear = torch.ones(len(visual), dtype=torch.bool) + if coverage == "circular": + linear = torch.linalg.vector_norm(visual, dim=-1) <= 1 + assert linear.sum() > 1000 + torch.testing.assert_close( + eccentricity_rays(visual[linear], coords.fov, rotation), texel_rays[stored][linear], atol=1e-5, rtol=0 + ) + # The antipode lies outside every grid. + assert (inverse[0, 0] == -1).all() and (inverse[-1, -1] == -1).all() + assert torch.isfinite(inverse).all() + + +def test_upright_grid_masks_and_channel_aliases() -> None: + coords = make_coords(16) + # Coordinate channels make rotation/transposition failures observable. + values = torch.cat((coords.cartesian, torch.ones(len(coords), 2)), -1)[None, :, None] + source = {"rgba": values.clone()} + source["rgb"] = source["rgba"][..., :3] + mask_grid_samples(source, coords) + target = allocate_grid_outputs(source, coords) + copy_grid_outputs(source, target, grid_sample_indices(coords)) + expected = coords.as_grid(source["rgba"][:, :, 0], sample_dim=1) + torch.testing.assert_close(target["rgba"], expected) + assert target["rgb"].untyped_storage().data_ptr() == target["rgba"].untyped_storage().data_ptr() + assert target["rgba"][0, :, :, 0][8, 4] < target["rgba"][0, :, :, 0][8, 11] + assert target["rgba"][0, :, :, 1][4, 8] > target["rgba"][0, :, :, 1][11, 8] + assert (target["rgba"][0][~coords.as_grid(coords.valid_mask)] == 0).all() + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_published_grid_copy_is_graph_capturable(device: str) -> None: + coords = make_coords(16).to(device=device) + source = {"value": torch.arange(3 * len(coords) * 4, device=device).to(torch.uint8).reshape(3, len(coords), 1, 4)} + target = allocate_grid_outputs(source, coords) + indices = grid_sample_indices(coords) + copy_grid_outputs(source, target, indices) + torch.testing.assert_close(target["value"], coords.as_grid(source["value"][:, :, 0], sample_dim=1), atol=0, rtol=0) + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + copy_grid_outputs(source, target, indices) + source["value"].zero_() + graph.replay() + torch.cuda.synchronize() + assert torch.count_nonzero(target["value"]) == 0 diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 42d849230856..b04505672812 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -3,29 +3,360 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Newton's renderer requires whole native-grid tiles.""" +"""The Newton foveated camera's render layout and publication, on stand-in renderer buffers.""" +from dataclasses import asdict from types import SimpleNamespace import pytest import torch -from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera +import warp as wp +from fovi.sensing.coords import SamplingCoords +from fovi.sensing.projection import CameraModel +from isaaclab_fovi.sensors import foveated_camera as base_camera +from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera +from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions +from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera, explicit_rays +from isaaclab_fovi.sensors.native_grid import native_grid_directions -from isaaclab.sensors.camera.camera import Camera +from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless -def test_native_grid_render_size_must_fill_newton_tiles(): - camera = SimpleNamespace( - cfg=SimpleNamespace( - width=83, - height=83, - renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=16, tile_rendering_height=8), +def rendered_rays_only(camera) -> None: + """Stand-in for the gaze geometry: only the rendered rays, in the ROS frame the camera keeps them in.""" + coords = camera._ray_coords + if coords.style == "warped_cartesian_as_grid": + rays = native_grid_directions(coords, image_rotation_deg=0) + else: + rays = retinal_directions(coords.cartesian, coords.fov, 0) + camera._gaze_rays = (rays * rays.new_tensor((1.0, -1.0, -1.0))).float() + + +def new_camera() -> FoveatedNewtonCamera: + """A Newton camera without its constructor: the state its constructor sets and the handles its destructor reads.""" + camera = object.__new__(FoveatedNewtonCamera) + camera._gaze_angles = camera._gaze_rotation = camera._visibility = camera._grid_publish = None + camera._published_shape = camera._segmentation_neighbors = None + camera._initialize_handle = None + camera._invalidate_initialize_handle = None + camera._prim_deletion_handle = None + camera._view = None + camera._renderer = None + camera._device = "cpu" + return camera + + +@pytest.mark.parametrize("pooled", [False, True]) +def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatch, pooled) -> None: + coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") + highres = coords.clone(resolution=32) if pooled else None + ray_coords = highres if pooled else coords + pooler = torch.nn.AdaptiveAvgPool1d(len(coords)) if pooled else None + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (pooler, 4)) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) + + def initialize_renderer(camera): + # Newton launches image tiles; a vector-shaped width of one is not valid. + assert camera.cfg.height == camera.cfg.width == ray_coords.resolution + rgba = torch.zeros((2, camera.cfg.height, camera.cfg.width, 4), dtype=torch.uint8) + camera._data = SimpleNamespace( + output={ + "rgba": ProxyArray(wp.from_torch(rgba)), + "rgb": ProxyArray(wp.from_torch(rgba[..., :3])), + } + ) + camera._render_data = SimpleNamespace(camera_rays=None) + camera._renderer = SimpleNamespace( + cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + cleanup=lambda render_data: None, + ) + camera.renderer_rgba = rgba + + def render(camera, env_mask): + assert camera._data.output["rgba"].torch.shape == camera.renderer_rgba.shape + values = torch.arange(camera.renderer_rgba.numel()).reshape(camera.renderer_rgba.shape) + camera.frame_offset + camera.renderer_rgba.copy_(values.to(torch.uint8)) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) + camera = new_camera() + camera.cfg = SimpleNamespace( + foveated_style="warped_cartesian_as_grid", + mask_to_sensor_fov=False, + cmf_a_deg=0.591, + pool_enabled=pooled, + pool_mode="avg", + pool_sample_cortex=False, + image_rotation_deg=0, + update_period=0.0, + data_types=["rgba", "rgb"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + + rays = wp.to_torch(camera._foveated_rays) + assert rays.shape == (ray_coords.resolution, ray_coords.resolution, 1, 2, 3) + expected_rays = native_grid_directions(ray_coords, image_rotation_deg=0).float() + torch.testing.assert_close(rays.reshape(-1, 2, 3)[:, 1], expected_rays) + public_rgba = camera._data.output["rgba"] + camera.frame_offset = 0 + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) + expected = camera.renderer_rgba.reshape(2, len(ray_coords), 1, 4).clone() + expected[:, ~ray_coords.valid_mask] = 0 + if pooled: + # AdaptiveAvgPool1d maps the 4 * N_lo canonical samples to N_lo by averaging each run of four, which the + # camera rounds to the nearest uint8 value. + expected = expected.reshape(2, len(coords), 4, 1, 4).float().mean(dim=2).round().to(torch.uint8) + expected = coords.as_grid(expected.squeeze(2), sample_dim=1) + torch.testing.assert_close(camera._data.output["rgba"].torch, expected, rtol=0, atol=0) + # The published buffers are stable across frames, and rgb shares rgba's memory. + assert camera._data.output["rgba"] is public_rgba + torch.testing.assert_close(camera._data.output["rgb"].torch, expected[..., :3], rtol=0, atol=0) + assert camera._data.output["rgb"].warp.ptr == public_rgba.warp.ptr + + # Newton redraws every row, but only the updated environment's publication changes. + camera.frame_offset = 1 + camera._update_buffers_impl(wp.array([False, True], dtype=wp.bool, device="cpu")) + published = camera._data.output["rgba"].torch + torch.testing.assert_close(published[0], expected[0], rtol=0, atol=0) + assert not torch.equal(published[1], expected[1]) + + +def test_sample_set_publication_keeps_environments_that_were_not_updated(monkeypatch) -> None: + """A sample-set camera publishes its own buffers: Newton redraws every row, but only updated rows change.""" + coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu") + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 8)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: None) + monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (None, None)) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) + + def initialize_renderer(camera): + depth = torch.zeros((2, camera.cfg.height, camera.cfg.width, 1)) + camera._data = SimpleNamespace(output={"distance_to_camera": ProxyArray(wp.from_torch(depth))}) + camera._render_data = SimpleNamespace(camera_rays=None) + camera.renderer_depth = depth + + def render(camera, env_mask): + camera.renderer_depth.fill_(camera.frame_value) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) + camera = new_camera() + camera.cfg = SimpleNamespace( + foveated_style="isotropic", + mask_to_sensor_fov=False, + pool_enabled=False, + image_rotation_deg=0, + update_period=0.0, + data_types=["distance_to_camera"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + published = camera._data.output["distance_to_camera"] + assert published.torch.shape == (2, len(coords), 1, 1) + assert published.warp.ptr != camera._flat_render_output["distance_to_camera"].warp.ptr + + camera.frame_value = 1.0 + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) + camera.frame_value = 2.0 + camera._update_buffers_impl(wp.array([False, True], dtype=wp.bool, device="cpu")) + assert camera._data.output["distance_to_camera"] is published + assert bool((published.torch[0] == 1.0).all()) and bool((published.torch[1] == 2.0).all()) + + +def test_sample_set_sensor_mask_follows_the_published_frame(monkeypatch) -> None: + """An environment that was not updated keeps its published samples and the sensor visibility that masked them.""" + coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu") + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 8)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: None) + monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (None, None)) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) + + def initialize_renderer(camera): + camera.renderer_depth = torch.ones((2, camera.cfg.height, camera.cfg.width, 1)) + camera._data = SimpleNamespace(output={"distance_to_camera": ProxyArray(wp.from_torch(camera.renderer_depth))}) + camera._render_data = SimpleNamespace(camera_rays=None) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", lambda camera, env_mask: None) + camera = new_camera() + camera.cfg = SimpleNamespace( + foveated_style="isotropic", + mask_to_sensor_fov=True, + camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), + spawn=None, + pool_enabled=False, + image_rotation_deg=0, + update_period=0.0, + data_types=["distance_to_camera"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + # The real gaze geometry, on stand-in pose buffers. + base_camera.FoveatedCamera._initialize_gaze(camera) + camera._view = SimpleNamespace(count=2, close=lambda: None) + camera._data.quat_w_ros = ProxyArray(wp.from_torch(torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2), dtype=wp.quatf)) + + # The second camera looks away from the physical camera's image, so it sees nothing. + camera.set_gaze_angles(torch.tensor([[0.0, 0.0], [0.0, 180.0]])) + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) + seen = camera.sensor_fov_valid_fraction.clone() + assert seen[0] > 0.5 and seen[1] == 0 + # Both look ahead now, but only the first camera's frame is published. + camera.set_gaze_angles(torch.zeros(2, 2)) + camera._update_buffers_impl(wp.array([True, False], dtype=wp.bool, device="cpu")) + assert not camera._data.output["distance_to_camera"].torch[1].any() + torch.testing.assert_close(camera.sensor_fov_valid_fraction, seen) + + +def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatch) -> None: + """A pooled camera's segmentation output holds each sample's majority label exactly, IDs above 2**24 included.""" + coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu") + highres = coords.clone(resolution=32) + runs = torch.arange(len(coords)) + # Each pooled sample's neighbours are a run of four rendered samples, nearest first. + neighbors = torch.stack([4 * runs + j for j in range(4)]) + average = torch.nn.AdaptiveAvgPool1d(len(coords)) + + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (average, 4)) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) + # The camera reads the modal neighbourhoods from its standard pooler. + monkeypatch.setattr(base_camera, "segmentation_neighbor_indices", lambda pooler: neighbors) + + def initialize_renderer(camera): + size = (2, camera.cfg.height, camera.cfg.width) + camera.renderer_rgba = torch.zeros((*size, 4), dtype=torch.uint8) + camera.renderer_labels = torch.zeros((*size, 1), dtype=torch.int32) + camera._data = SimpleNamespace( + output={ + "rgba": ProxyArray(wp.from_torch(camera.renderer_rgba)), + "semantic_segmentation": ProxyArray(wp.from_torch(camera.renderer_labels)), + } ) + camera._render_data = SimpleNamespace(camera_rays=None) + camera._renderer = SimpleNamespace(cleanup=lambda render_data: None) + + # In each run, three samples share a label above 2**24 and one differs; float32 would merge neighbouring labels. + majority = 2**24 + 1 + 2 * runs + labels = majority[:, None].repeat(1, 4) + labels[:, 2] = 2**30 + runs + labels = torch.stack((labels.reshape(-1), (labels + 7).reshape(-1))) + + def render(camera, env_mask): + camera.renderer_labels.copy_(labels.to(torch.int32).reshape(camera.renderer_labels.shape)) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) + camera = new_camera() + camera.cfg = SimpleNamespace( + foveated_style="warped_cartesian_as_grid", + mask_to_sensor_fov=False, + update_period=0.0, + pool_enabled=True, + pool_mode="avg", + pool_sample_cortex=False, + image_rotation_deg=0, + data_types=["rgba", "semantic_segmentation"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) + + # The modal label of each run after the footprint mask zeroes samples outside the retina, ties to the nearest. + rendered = labels.clone() + rendered[:, ~highres.valid_mask] = 0 + expected = torch.zeros(2, len(coords), dtype=torch.int64) + for env in range(2): + for sample in range(len(coords)): + run = rendered[env, 4 * sample : 4 * sample + 4].tolist() + expected[env, sample] = max(run, key=lambda label: (run.count(label), -run.index(label))) + published = camera._data.output["semantic_segmentation"].torch + assert published.dtype == torch.int32 + torch.testing.assert_close(published[..., 0].long(), coords.as_grid(expected, sample_dim=1), rtol=0, atol=0) + assert camera.image_shape == (16, 16) and camera._data.image_shape == (16, 16) + + +def test_native_grid_render_size_must_fill_newton_tiles() -> None: + """A fractional pool_res_mult can give a grid that Newton's tiles do not divide; the camera rejects it.""" + FoveatedNewtonCamera._validate_native_render_layout( + SimpleNamespace(cfg=SimpleNamespace(width=128, height=128)), 16, 8 ) with pytest.raises(ValueError, match="83x83.*16x8"): - FoveatedNewtonCamera._initialize_impl(camera) + FoveatedNewtonCamera._validate_native_render_layout( + SimpleNamespace(cfg=SimpleNamespace(width=83, height=83)), 16, 8 + ) + + +def test_explicit_rays_keep_sample_order_and_pad_whole_tiles() -> None: + """Newton receives one ray per sample from the optical centre, in sample order, padded to whole tiles.""" + wp.init() + directions = torch.nn.functional.normalize(torch.randn(5, 3, generator=torch.Generator().manual_seed(0)), dim=-1) + rays = explicit_rays(directions, 2, 4) + assert rays.shape == (2, 4, 1, 2) and rays.dtype == wp.vec3f + rays = wp.to_torch(rays).reshape(8, 2, 3) + torch.testing.assert_close(rays[:5, 1], directions) + torch.testing.assert_close(rays[5:, 1], directions[-1].expand(3, -1)) + assert not rays[:, 0].any() + with pytest.raises(ValueError, match="shape"): + explicit_rays(torch.zeros(3, 2), 3, 1) + with pytest.raises(ValueError, match="cannot hold"): + explicit_rays(torch.zeros(5, 3), 2, 2) + + +def test_pooled_rgb_is_the_view_of_pooled_rgba(monkeypatch) -> None: + """The renderer publishes rgb as a view of rgba even when only rgba is requested, and so do pooled sample sets.""" + style = "isotropic" + coords = SamplingCoords(60.0, 0.591, 16, style=style, field_geometry="spherical", device="cpu") + highres = coords.clone(resolution=32) + monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) + monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr( + newton_camera, "build_pooler", lambda *args, **kwargs: (torch.nn.AdaptiveAvgPool1d(len(coords)), 4) + ) + monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) + + def initialize_renderer(camera): + camera.renderer_rgba = torch.zeros((2, camera.cfg.height, camera.cfg.width, 4), dtype=torch.uint8) + rgba = ProxyArray(wp.from_torch(camera.renderer_rgba)) + camera._data = SimpleNamespace( + output={"rgba": rgba, "rgb": ProxyArray(wp.from_torch(camera.renderer_rgba[..., :3]))} + ) + camera._render_data = SimpleNamespace(camera_rays=None) + camera._renderer = SimpleNamespace(cleanup=lambda render_data: None) + + def render(camera, env_mask): + camera.renderer_rgba.copy_(torch.tensor([10, 20, 30, 255], dtype=torch.uint8)) + + monkeypatch.setattr(newton_camera.Camera, "_initialize_impl", initialize_renderer) + monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) + camera = new_camera() + camera.cfg = SimpleNamespace( + foveated_style=style, + mask_to_sensor_fov=False, + update_period=0.0, + pool_enabled=True, + pool_mode="avg", + pool_sample_cortex=False, + image_rotation_deg=0, + data_types=["rgba"], + renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), + ) + camera._initialize_impl() + camera._update_buffers_impl(wp.ones(2, dtype=wp.bool, device="cpu")) + + rgb, rgba = camera._data.output["rgb"].torch, camera._data.output["rgba"].torch + assert rgb.any() + torch.testing.assert_close(rgb, rgba[..., :3], rtol=0, atol=0) + # rgb is a view of rgba, not a copy: a write to rgba shows through it. + assert rgb.data_ptr() == rgba.data_ptr() + rgba[..., 0] = 7 + assert bool((rgb[..., 0] == 7).all()) def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch) -> None: @@ -36,9 +367,8 @@ def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch) -> None: def replace_rays(*args, **kwargs): raise AssertionError("the stock setter replaces the renderer's rays") - monkeypatch.setattr(Camera, "set_intrinsic_matrices", replace_rays) - monkeypatch.setattr(Camera, "__del__", lambda self: None) - camera = object.__new__(FoveatedNewtonCamera) + monkeypatch.setattr(newton_camera.Camera, "set_intrinsic_matrices", replace_rays) + camera = new_camera() with pytest.warns(UserWarning, match="leaves a foveated camera as configured") as caught: camera.set_intrinsic_matrices(torch.eye(3).repeat(2, 1, 1)) # The warning points at the caller's line. diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py new file mode 100644 index 000000000000..d8cda0eb5880 --- /dev/null +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -0,0 +1,172 @@ +# 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 + +"""The camera's pooling of its sensor buffers, segmentation and sensor mask, without a simulator. + +fovi's poolers are tested in fovi; these tests cover what the camera builds on them. +""" + +import pytest +import torch +from isaaclab_fovi.sensors import FoveatedCameraCfg, pooling +from isaaclab_fovi.sensors.pooling import ( + build_highres_coords, + build_lowres_coords, + build_pooler, + pool_hwc_buffer, + pool_segmentation_buffer, + segmentation_neighbor_indices, +) + +from isaaclab.sim import PinholeCameraCfg +from isaaclab.test.utils import DeviceScope, test_devices + +pytestmark = pytest.mark.kitless + +DEVICE = next(iter(test_devices(DeviceScope.DEFAULT_CUDA)), "cpu") +"""The modal pooling runs the same tensor operations on every device; the default GPU is what simulations use.""" + + +def pooling_cfg(**overrides) -> FoveatedCameraCfg: + """A pooled foveated camera configuration for the pooling helpers, with ``overrides`` applied. + + A 90 degree pinhole window (focal length 1, aperture 2) with a CMF constant of a tenth of it, and a small isotropic + retina pooled from three visual-field neighbours. + """ + values = dict( + prim_path="/World/Camera", + spawn=PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0), + cmf_a_deg=9.0, + foveated_res=8, + foveated_style="isotropic", + pool_enabled=True, + pool_k=3, + pool_sample_cortex=False, + ) + return FoveatedCameraCfg(**{**values, **overrides}) + + +def test_camera_pools_its_buffers_by_its_config() -> None: + cfg = pooling_cfg(pool_mode="max") + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, lowres, matched) + # The photoreceptor grid shares the retina's geometry at a higher resolution, and the pooler takes the config. + assert len(highres) > len(lowres) and highres.cmf_a == lowres.cmf_a and highres.fov == lowres.fov + pooler, neighbors = build_pooler(cfg, lowres, highres, "cpu") + assert neighbors == 3 and pooler.mode == "max" + # Pooling keeps each environment's channels apart and in order. + constants = torch.tensor([[0.25, 0.5, 0.75], [3.0, 6.0, 9.0]]) + rendered = constants[:, None, None, :].expand(2, len(highres), 1, 3).clone() + actual = pool_hwc_buffer(pooler, rendered) + assert actual.dtype == rendered.dtype + torch.testing.assert_close(actual, constants[:, None, None, :].expand(2, len(lowres), 1, 3)) + # Without pooling there is no photoreceptor grid. + cfg = pooling_cfg(pool_enabled=False) + lowres, matched = build_lowres_coords(cfg, "cpu") + assert build_highres_coords(cfg, lowres, matched) is None + + +# Three output samples over five input samples; 5 marks an excluded neighbour. Columns are outputs, rows are +# neighbour slots nearest first. +HAND_TABLE = torch.tensor([[0, 3, 5], [1, 4, 5], [2, 5, 5]]) + + +def test_modal_pooling_keeps_majority_color_vector() -> None: + # Output 0 sees [0,0,0,255] twice and [0,0,1,255] once; a per-channel max would give [0,0,1,255]. + # Output 1 sees one vote each for two colors (its third slot is excluded): the nearest neighbour wins. + # Output 2 has no valid neighbour and is zero. + colors = torch.tensor( + [[0, 0, 0, 255], [0, 0, 0, 255], [0, 0, 1, 255], [10, 20, 30, 255], [200, 100, 0, 255]], dtype=torch.uint8 + ) + rendered = colors[None, :, None, :].to(DEVICE) + pooled = pool_segmentation_buffer(HAND_TABLE.to(DEVICE), rendered) + expected = torch.tensor([[0, 0, 0, 255], [10, 20, 30, 255], [0, 0, 0, 0]], dtype=torch.uint8) + assert pooled.dtype == torch.uint8 + assert torch.equal(pooled.cpu(), expected[None, :, None, :]) + # Swapping the tied neighbours' order flips the winner. + swapped = HAND_TABLE[[1, 0, 2]].to(DEVICE) + assert torch.equal(pool_segmentation_buffer(swapped, rendered)[0, 1, 0].cpu(), colors[4]) + + +def test_modal_pooling_preserves_ids_above_float_precision() -> None: + # 2**24 + 1 and 2**24 + 3 round to other values in float32; the IDs must come back exactly. + big = 2**40 + ids = torch.tensor([2**24 + 1, 2**24 + 1, 2**24 + 3, big + 7, big + 7], dtype=torch.int64) + batch = torch.stack([ids, ids.flip(0)])[:, :, None, None].to(DEVICE) + pooled = pool_segmentation_buffer(HAND_TABLE.to(DEVICE), batch) + expected = torch.tensor([[2**24 + 1, big + 7, 0], [big + 7, 2**24 + 1, 0]], dtype=torch.int64) + assert pooled.dtype == torch.int64 + assert torch.equal(pooled[..., 0, 0].cpu(), expected) + # Two int64 channels exceed the 8-byte packed key; vectors differing only in the second channel stay distinct. + vectors = torch.tensor([[1, 2**40], [1, 2**40 + 1], [1, 2**40 + 1], [5, 6], [7, 8]], dtype=torch.int64) + pooled = pool_segmentation_buffer(HAND_TABLE.to(DEVICE), vectors[None, :, None, :].to(DEVICE)) + assert torch.equal(pooled[0, :, 0].cpu(), torch.tensor([[1, 2**40 + 1], [5, 6], [0, 0]])) + + +def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Tensor: + """Brute-force modal pooling of ``(B, N_hi, C)`` values over a ``(k, N_lo)`` neighbour table.""" + batch, num_inputs, channels = values.shape + out = torch.zeros(batch, table.shape[1], channels, dtype=values.dtype) + for b in range(batch): + for n in range(table.shape[1]): + neighbours = [tuple(values[b, i].tolist()) for i in table[:, n].tolist() if i != num_inputs] + if neighbours: + # max() keeps the first of equally common values, i.e. the earliest neighbour slot. + out[b, n] = torch.tensor(max(neighbours, key=neighbours.count), dtype=values.dtype) + return out + + +@pytest.mark.parametrize( + ("style", "pool_k", "sample_cortex"), [("warped_cartesian_as_grid", 9, False), ("isotropic", 3, False)] +) +def test_modal_pooling_uses_the_poolers_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex) -> None: + """Segmentation pools over the same neighbourhoods as the camera's other outputs: grid windows or KNN.""" + cfg = pooling_cfg(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex, pool_mode="max") + lowres, matched = build_lowres_coords(cfg, "cpu") + highres = build_highres_coords(cfg, lowres, matched) + pooler, k = build_pooler(cfg, lowres, highres, "cpu") + table = segmentation_neighbor_indices(pooler) + assert table.shape == (k, len(lowres)) + # The table holds exactly the samples the max pooler reduces over: a max over the table matches it. + values = torch.rand(1, len(highres), 1, 1, generator=torch.Generator().manual_seed(0)) + 1 + padded = torch.cat([values[0, :, 0, 0], torch.zeros(1)]) + torch.testing.assert_close(padded[table].max(dim=0).values, pool_hwc_buffer(pooler, values)[0, :, 0, 0]) + + # Few labels so neighbourhoods hold repeats and ties; tiny chunks exercise the batched loop. + monkeypatch.setattr(pooling, "_MODAL_CHUNK_ELEMENTS", 1) + labels = torch.randint(0, 3, (3, len(highres), 1, 2), generator=torch.Generator().manual_seed(1)).to(torch.uint8) + pooled = pool_segmentation_buffer(table, labels) + assert torch.equal(pooled[:, :, 0], reference_modal_pool(table, labels[:, :, 0])) + + +@pytest.mark.parametrize(("style", "pool_k", "mode"), [("warped_cartesian_as_grid", 9, "avg"), ("isotropic", 6, "max")]) +def test_pooling_leaves_out_photoreceptors_the_camera_does_not_see(style: str, pool_k: int, mode: str) -> None: + cfg = pooling_cfg(foveated_style=style, pool_mode=mode, pool_k=pool_k) + lowres, matched = build_lowres_coords(cfg, DEVICE) + highres = build_highres_coords(cfg, lowres, matched) + pooler, _ = build_pooler(cfg, lowres, highres, DEVICE) + # The camera's image edge cuts the retina at x = 0.3 in the first environment; the second sees everything. + visible = torch.stack([highres.cartesian[:, 0] < 0.3, torch.ones(len(highres), dtype=torch.bool, device=DEVICE)]) + # The camera zeroes unseen photoreceptors before pooling. A negative value lets those zeros win a plain max. + value = -0.7 if mode == "max" else 0.7 + values = torch.where(visible, value, 0.0)[:, :, None, None] + pooled = pool_hwc_buffer(pooler, values, visible)[:, :, 0, 0] + unseen = pool_hwc_buffer(pooler, visible.float()[:, :, None, None], visible)[:, :, 0, 0] == 0 + # Some outputs straddle the edge: plain pooling lets the mask's zeros into them. + straddling = (pool_hwc_buffer(pooler, values)[0, :, 0, 0] - value).abs() > 0.01 + assert (straddling & ~unseen[0] & lowres.valid_mask).any() + # Each output pools only what the camera sees: the constant where it sees any photoreceptor, zero where it sees + # none or lies outside the retina. + expected = torch.where(unseen | ~lowres.valid_mask, 0.0, value) + torch.testing.assert_close(pooled, expected) + assert unseen[0].any() and not unseen[1, lowres.valid_mask].any() + + +def test_modal_pooling_leaves_out_labels_the_camera_does_not_see() -> None: + # Output 0 sees labels [1, 1, 2]; hiding the two 1s leaves 2. Output 1 sees [4, 5]; hiding both leaves nothing. + labels = torch.tensor([1, 1, 2, 4, 5], dtype=torch.int32)[None, :, None, None].expand(2, -1, -1, -1) + visible = torch.tensor([[False, False, True, False, False], [True, True, True, True, True]]) + pooled = pool_segmentation_buffer(HAND_TABLE, labels, visible)[..., 0, 0] + assert torch.equal(pooled, torch.tensor([[2, 0, 0], [1, 4, 0]], dtype=torch.int32)) diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index 02594a411ab5..23fbbfd36593 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -5,18 +5,23 @@ """RTX camera contracts that need no renderer: construction, lens textures and their USD schema, and capture.""" +import math import tempfile from pathlib import Path from types import SimpleNamespace import pytest +import torch +import warp as wp +from isaaclab_fovi.sensors import foveated_rtx_camera, lens_lut from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera -from isaaclab_fovi.sensors.lens_lut import apply_lens_lut_to_prim +from isaaclab_fovi.sensors.lens_lut import apply_lens_lut_to_prim, build_lut_textures from isaaclab_ov.renderers import OVRTXRendererCfg from isaaclab.sensors.camera.camera import Camera from isaaclab.sim import PinholeCameraCfg +from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless @@ -42,6 +47,37 @@ def test_near_clip_comes_from_spawn_or_else_the_camera_prim() -> None: assert FoveatedRTXCamera._near_clipping_distance(spawned, prim) == pytest.approx(0.01) +@pytest.mark.parametrize("native_grid", [False, True]) +def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> None: + """Environments outside the update mask keep their samples, and each camera's near-plane offset is added once.""" + height, width = 4, 5 + texture = torch.arange(3 * height * width, dtype=torch.float32).reshape(3, height, width, 1) + if native_grid: + texels = [(py, px) for py in range(height) for px in range(width)] + else: + texels = [(3, 1), (0, 4), (2, 0), (1, 3), (3, 4), (0, 2), (2, 2)] + camera = SimpleNamespace( + cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")), + # An OVRTX camera with distance_to_camera output adds each camera's near clip. + _offset_distance=True, + _native_grid=native_grid, + _near_clip=torch.tensor([0.25, 0.5, 0.75]).view(-1, 1, 1, 1), + # The renderer-bound texture buffers are ProxyArrays, as the parent camera allocates them. + _texture_output={"distance_to_camera": ProxyArray(wp.from_torch(texture))}, + _foveated_output={"distance_to_camera": torch.full((3, len(texels), 1, 1), -1.0)}, + _extract_py=torch.tensor([py for py, _ in texels]), + _extract_px=torch.tensor([px for _, px in texels]), + ) + updated = wp.array([True, False, True], dtype=wp.bool, device="cpu") + for _ in range(2): + FoveatedRTXCamera._extract_foveated_samples(camera, updated) + samples = camera._foveated_output["distance_to_camera"] + for env, near_clip in ((0, 0.25), (2, 0.75)): + expected = torch.tensor([float(texture[env, py, px, 0]) + near_clip for py, px in texels]) + torch.testing.assert_close(samples[env, :, 0, 0], expected, atol=0, rtol=0) + assert bool((samples[1] == -1.0).all()) + + def test_releasing_the_camera_removes_its_lens_textures(monkeypatch, tmp_path) -> None: monkeypatch.setattr(Camera, "__del__", lambda self, *args, **kwargs: None) camera = object.__new__(FoveatedRTXCamera) @@ -65,18 +101,27 @@ def construct(self, cfg): self.cfg = cfg self.stage = stage - def prepare(self): - self._dir_tex_path, self._exit_tex_path = "/textures/enter.exr", "/textures/exit.exr" + build_directions = lens_lut.native_grid_directions + ray_builds = [] + + def measure_directions(*args, **kwargs): + rays = build_directions(*args, **kwargs) + ray_builds.append(rays) + return rays + texture_paths = ("/textures/enter.exr", "/textures/exit.exr") monkeypatch.setattr(Camera, "__init__", construct) - monkeypatch.setattr(FoveatedRTXCamera, "_prepare_projection", prepare) + # Count at both import locations so evaluating a second ray grid in the camera fails this check. + monkeypatch.setattr(lens_lut, "native_grid_directions", measure_directions) + monkeypatch.setattr(foveated_rtx_camera, "native_grid_directions", measure_directions, raising=False) + monkeypatch.setattr(lens_lut, "save_lut_textures", lambda *args: texture_paths) monkeypatch.setattr(FoveatedRTXCamera, "__del__", lambda self, *args, **kwargs: None) cfg = FoveatedCameraCfg( prim_path="/World/envs/env_.*/Camera", spawn=PinholeCameraCfg(), renderer_cfg=OVRTXRendererCfg(), data_types=["rgb"], - foveated_res=64, + foveated_res=16, ) assert cfg.spawn.lock_camera camera = FoveatedRTXCamera(cfg) @@ -84,7 +129,8 @@ def prepare(self): assert prim.GetAttribute("omni:kit:cameraLock").Get() is False assert prim.GetAttribute("omni:lensdistortion:model").Get() == "lut" assert prim.GetAttribute("omni:lensdistortion:lut:rayEnterDirectionTexture").Get().path == "/textures/enter.exr" - assert camera.cfg is not cfg and camera.cfg.height == 64 + assert camera.cfg is not cfg and (camera.cfg.height, camera.cfg.width) == (16, 16) + assert len(ray_builds) == 1 assert cfg.spawn.lock_camera and (cfg.height, cfg.width) == (1, 1) @@ -106,3 +152,32 @@ def test_lens_lut_survives_usd_export_without_schema_registration() -> None: "generalizedProjectionNDCTexturePath", ): assert not prim.HasProperty(name), name + + +def test_sample_set_lens_textures_place_samples_and_mark_rays_outside_the_field() -> None: + # A sample set with one sample per texel, in shuffled order, puts each sample's ray at its own texel. + size = 4 + axis = (torch.arange(size) + 0.5) / size + row, col = torch.meshgrid(axis, axis, indexing="ij") + centres = torch.stack((col, row), -1).reshape(-1, 2) + order = torch.randperm(size * size, generator=torch.Generator().manual_seed(0)) + directions = torch.nn.functional.normalize(torch.randn(size * size, 3, generator=torch.Generator().manual_seed(1))) + direction_texture, _ = build_lut_textures(centres[order], directions, size, size, 16, 16, device="cpu") + texels = (centres[order] * size).long() + torch.testing.assert_close(direction_texture[texels[:, 1], texels[:, 0]], directions) + + # The inverse lookup sends each in-field ray to its nearest sample, and every other ray to the invalid UV, never + # to the fovea. Three samples: the optical axis (OpenGL -z) and two rays 10 degrees off it. + angle = math.radians(10.0) + directions = torch.tensor( + [[0.0, 0.0, -1.0], [math.sin(angle), 0.0, -math.cos(angle)], [0.0, math.sin(angle), -math.cos(angle)]] + ) + uv = torch.tensor([[0.5, 0.5], [0.9, 0.5], [0.5, 0.9]]) + _, exit_texture = build_lut_textures(uv, directions, 8, 8, 32, 32, device="cpu") + texels = exit_texture.reshape(-1, exit_texture.shape[-1])[:, :2] + invalid = (texels == -1.0).all(dim=-1) + # Rays outside the 10 degree field outnumber those inside it on the hemisphere's octahedral grid. + assert invalid.float().mean() > 0.5 and (~invalid).any() + assert all(any(torch.equal(texel, sample) for sample in uv) for texel in texels[~invalid]) + # The octahedral centre is the optical axis, which reaches the axis sample. + torch.testing.assert_close(exit_texture[exit_texture.shape[0] // 2, exit_texture.shape[1] // 2, :2], uv[0]) diff --git a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst index 6a26475420f2..94b3efa5d3dc 100644 --- a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst +++ b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst @@ -1,2 +1,3 @@ -* Added the ``IsaacContrib-Cartpole-Camera-Fovi`` task with foveated RGB and depth presets, policy-controlled - gaze, and the stock RSL-RL PPO runner. The task is available with the ``fovi`` extra. +* Added the ``IsaacContrib-Cartpole-Camera-Fovi`` task in :mod:`isaaclab_tasks.contrib.active_gaze`: the Cartpole + camera task with a foveated camera whose gaze the policy moves, trained with gaze-supervised PPO and a fixed gaze + action noise. It is registered when the ``fovi`` extra is installed. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py new file mode 100644 index 000000000000..3544c85a35fb --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py @@ -0,0 +1,85 @@ +# 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 + +"""Building blocks of active-gaze camera tasks: a foveated version of a stock camera, and the gaze observations.""" + +from __future__ import annotations + +from dataclasses import MISSING, fields + +from isaaclab_fovi import mdp +from isaaclab_fovi.sensors import FoveatedCameraCfg + +from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg +from isaaclab.sensors import CameraCfg +from isaaclab.utils import configclass + +from isaaclab_tasks.utils import PresetCfg, preset + + +def foveated_camera(camera: CameraCfg, foveated_res: int | None = None) -> FoveatedCameraCfg: + """A foveated camera at the camera's mount, with its optics, data types and renderer. + + The retina covers the camera's short side and is ``foveated_res`` samples across, by default the camera's width, + so the number of rendered rays stays close to the camera's pixels. Samples the camera does not see are zero. + The foveated camera keeps its own image size and per-frame pose updates, which render each new gaze. + """ + # A copy, so the foveated camera shares no nested configuration (spawn, renderer, offset) with the preset's. + camera = camera.copy() + own = {"class_type", "width", "height", "update_latest_camera_pose"} + values = {field.name: getattr(camera, field.name) for field in fields(CameraCfg) if field.name not in own} + resolution = camera.width if foveated_res is None else foveated_res + return FoveatedCameraCfg(**values, foveated_res=resolution, mask_to_sensor_fov=True) + + +def foveated_presets(cameras: PresetCfg, foveated_res: int | None = None) -> PresetCfg: + """The foveated version of every camera preset, under the same names. Other sensors are left out. + + ``foveated_res`` applies to every preset; by default each keeps its camera's width. + """ + options = {} + for name in cameras.__dataclass_fields__: + camera = getattr(cameras, name) + if not name.startswith("_") and isinstance(camera, CameraCfg): + options[name] = foveated_camera(camera, foveated_res) + return preset(**options) + + +def select_presets(options: PresetCfg, names) -> PresetCfg: + """The options of a preset whose names are in ``names``, plus its default.""" + return preset( + **{name: getattr(options, name) for name in options.__dataclass_fields__ if name in {*names, "default"}} + ) + + +def oracle_observations( + target_cfg: SceneEntityCfg, offset: tuple[float, float, float] = (0.0, 0.0, 0.0) +) -> OracleObservationsCfg: + """The teacher's gaze labels toward a point fixed to an asset.""" + return OracleObservationsCfg( + labels=ObservationTermCfg(func=mdp.gaze_teacher_labels, params={"target_cfg": target_cfg, "offset": offset}) + ) + + +@configclass +class GazeObservationsCfg(ObservationGroupCfg): + """The gaze, in field radii, and its velocity, in field radii per second.""" + + state = ObservationTermCfg(func=mdp.gaze_state) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + +@configclass +class OracleObservationsCfg(ObservationGroupCfg): + """The teacher's gaze labels. Training labels, never a policy input.""" + + labels: ObservationTermCfg = MISSING + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py index b3ba0ba05bb2..409c686b00e5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py @@ -3,16 +3,38 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Stock Cartpole camera PPO with gaze state in the actor and critic observations.""" +"""RSL-RL agents of the active-gaze tasks: the stock PPO with gaze supervision and a fixed gaze noise.""" -from isaaclab.utils import configclass +from dataclasses import fields + +from isaaclab.utils import configclass, replace + +from isaaclab_rl.rsl_rl import RslRlMLPModelCfg, RslRlPpoAlgorithmCfg from isaaclab_tasks.core.cartpole.agents.rsl_rl_ppo_cfg import CartpoleCameraPPORunnerCfg +from .gaze_distribution_cfg import GazeGaussianDistributionCfg +from .gaze_supervised_ppo_cfg import GazeSupervisedPPOCfg + + +def gaze_supervised(algorithm: RslRlPpoAlgorithmCfg, **kwargs) -> GazeSupervisedPPOCfg: + """The PPO settings of ``algorithm`` with gaze supervision by the teacher.""" + values = {field.name: getattr(algorithm, field.name) for field in fields(algorithm) if field.name != "class_name"} + return GazeSupervisedPPOCfg(**values, **kwargs) + + +def gaze_actor(actor: RslRlMLPModelCfg) -> RslRlMLPModelCfg: + """The stock actor with a fixed, small noise on its gaze actions, the last two.""" + stock = actor.distribution_cfg + head = GazeGaussianDistributionCfg(init_std=stock.init_std, std_type=stock.std_type, std_range=stock.std_range) + return replace(actor, distribution_cfg=head) + @configclass class CartpoleCameraFoviPPORunnerCfg(CartpoleCameraPPORunnerCfg): - """Train the camera policy and gaze actions with the stock PPO runner.""" + """The stock Cartpole camera PPO with gaze supervision; the actor and critic also see the gaze.""" experiment_name = "cartpole_camera_fovi" obs_groups = {"actor": ["policy", "gaze"], "critic": ["critic", "gaze"]} + actor = gaze_actor(CartpoleCameraPPORunnerCfg().actor) + algorithm = gaze_supervised(CartpoleCameraPPORunnerCfg().algorithm) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py index afe967165329..da42ff2226c3 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py @@ -3,84 +3,83 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Camera Cartpole with a foveated view and policy-controlled gaze.""" +"""Cartpole with a foveated camera, in RGB or depth. -from dataclasses import MISSING +The stock camera task with the camera foveated and two gaze actions. The teacher looks at the pole's tip. The retina +is :data:`RETINA_RES` samples across, enough for a task that only needs to see a bar. The policy gets two gaze actions, +whose noise is fixed, and the teacher's gaze labels supervise them during training. +""" from isaaclab_fovi import mdp -from isaaclab_fovi.sensors import FoveatedCameraCfg -from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg -from isaaclab.sensors import CameraCfg +from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg from isaaclab.utils import configclass +from isaaclab_tasks.core.cartpole import mdp as cartpole_mdp from isaaclab_tasks.core.cartpole.cartpole_common import CartpoleTiledCameraCfg -from isaaclab_tasks.core.cartpole.cartpole_manager_camera_env_cfg import ( - CartpoleCameraEnvCfg, - CartpoleCameraSceneCfg, - image_observations_cfg, -) +from isaaclab_tasks.core.cartpole.cartpole_manager_camera_env_cfg import CartpoleCameraEnvCfg, CartpoleCameraSceneCfg from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ActionsCfg as CartpoleActionsCfg +from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ObservationsCfg as CartpoleObservationsCfg from isaaclab_tasks.utils import PresetCfg +from .active_gaze_cfg import GazeObservationsCfg, foveated_presets, oracle_observations, select_presets -def _foveated_camera(camera: CameraCfg) -> FoveatedCameraCfg: - """Apply the retina to the stock Cartpole camera's mount, optics, and renderer.""" - return FoveatedCameraCfg( - prim_path=camera.prim_path, - offset=camera.offset, - spawn=camera.spawn, - data_types=camera.data_types, - renderer_cfg=camera.renderer_cfg, - foveated_res=32, - mask_to_sensor_fov=True, - ) +POLE_TIP = (0.0, 0.0, 1.0) +"""The pole's tip in the pole's frame [m].""" +RETINA_RES = 32 +"""Retina samples across; the stock camera is 96 pixels across.""" -@configclass -class CameraPresetsCfg(PresetCfg): - """Select the foveated RGB or depth output.""" - rgb = _foveated_camera(CartpoleTiledCameraCfg().rgb) - depth = _foveated_camera(CartpoleTiledCameraCfg().depth) - default = rgb +def observations(data_type: str, image_term) -> object: + """The stock camera observations of ``data_type``, the gaze, and the teacher's labels.""" + + @configclass + class ObservationsCfg: + @configclass + class PolicyCfg(ObservationGroupCfg): + image = ObservationTermCfg( + func=image_term, + params={ + "sensor_cfg": SceneEntityCfg("tiled_camera"), + "data_type": data_type, + "channel_first": True, + "frame_stack": 2, + }, + ) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + policy: ObservationGroupCfg = PolicyCfg() + critic: ObservationGroupCfg = CartpoleObservationsCfg.PolicyCfg() + gaze: ObservationGroupCfg = GazeObservationsCfg() + oracle: ObservationGroupCfg = oracle_observations(SceneEntityCfg("robot", body_names="pole"), POLE_TIP) + + return ObservationsCfg() @configclass class SceneCfg(CartpoleCameraSceneCfg): - tiled_camera: CameraPresetsCfg = CameraPresetsCfg() + tiled_camera = select_presets(foveated_presets(CartpoleTiledCameraCfg(), RETINA_RES), ("rgb", "depth")) @configclass class ActionsCfg(CartpoleActionsCfg): + # The gaze must be the last action term. gaze = mdp.GazeActionCfg(asset_name="tiled_camera") -@configclass -class ObservationsCfg: - @configclass - class GazeCfg(ObservationGroupCfg): - state = ObservationTermCfg(func=mdp.gaze_state) - - policy: ObservationGroupCfg = MISSING - critic: ObservationGroupCfg = MISSING - gaze: GazeCfg = GazeCfg() - - -def _observations(data_type: str) -> ObservationsCfg: - images = image_observations_cfg(data_type) - return ObservationsCfg(policy=images.policy, critic=images.critic) - - @configclass class CartpoleCameraFoviEnvCfg(PresetCfg): - """Cartpole with gaze control and RGB or depth retinal observations.""" + """Cartpole with a foveated camera; ``presets=depth`` selects depth images.""" @configclass class BaseCfg(CartpoleCameraEnvCfg.BaseCartpoleCameraEnvCfg): scene: SceneCfg = SceneCfg(num_envs=512, env_spacing=20.0) actions: ActionsCfg = ActionsCfg() - rgb = BaseCfg(observations=_observations("rgb")) - depth = BaseCfg(observations=_observations("depth")) + rgb = BaseCfg(observations=observations("rgb", cartpole_mdp.image_rgb)) + depth = BaseCfg(observations=observations("depth", cartpole_mdp.image_depth)) default = rgb diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py new file mode 100644 index 000000000000..9829707c282f --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py @@ -0,0 +1,61 @@ +# 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 + +"""Gaussian action head whose gaze actions have a fixed standard deviation.""" + +from __future__ import annotations + +import math + +import torch +from rsl_rl.modules.distribution import GaussianDistribution +from torch.distributions import Normal + +GAZE_ACTIONS = 2 +"""The gaze actions (tilt, pan) are the policy's last two actions.""" + + +class GazeGaussianDistribution(GaussianDistribution): + """Gaussian action head with a learned standard deviation for every action but the gaze, the last two, whose + standard deviation is fixed at ``gaze_std``. + + The gaze step clamps each gaze action to [-1, 1], so beyond that range a wider gaze distribution changes neither + the reward nor PPO's surrogate, and the entropy bonus grows a learned standard deviation without bound; the sampled + gaze then random-walks however well its mean follows the teacher. + + Args: + output_dim: Number of actions, the two gaze actions included. + init_std: Initial standard deviation of the other actions. + std_range: (min, max) clamp of the other actions' standard deviation. + std_type: Parameterization of the other actions' standard deviation: ``"scalar"`` or ``"log"``. + learn_std: Whether the other actions' standard deviation is learned. + gaze_std: Fixed standard deviation of the gaze actions. + """ + + def __init__( + self, + output_dim: int, + init_std: float = 1.0, + std_range: tuple[float, float] = (1e-6, 1e6), + std_type: str = "scalar", + learn_std: bool = True, + gaze_std: float = 0.1, + ) -> None: + if output_dim <= GAZE_ACTIONS: + raise ValueError(f"The gaze head needs actions besides the {GAZE_ACTIONS} gaze actions, got {output_dim}.") + if not (math.isfinite(gaze_std) and gaze_std > 0): + raise ValueError(f"gaze_std must be positive and finite, got {gaze_std!r}.") + # The learned parameter covers the other actions only. + super().__init__(output_dim - GAZE_ACTIONS, init_std, std_range, std_type, learn_std) + self.output_dim = output_dim + self.register_buffer("gaze_std", torch.full((GAZE_ACTIONS,), float(gaze_std))) + + def update(self, mlp_output: torch.Tensor) -> None: + """Update the distribution from the MLP output: learned noise for the other actions, fixed for the gaze.""" + if self.std_type == "scalar": + std = self.std_param.clamp(self.std_range[0], self.std_range[1]) + else: + std = self.log_std_param.clamp(self.log_std_range[0], self.log_std_range[1]).exp() + self._distribution = Normal(mlp_output, torch.cat((std, self.gaze_std))) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py new file mode 100644 index 000000000000..fac45da54582 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py @@ -0,0 +1,24 @@ +# 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 + +"""Configuration of :class:`~isaaclab_tasks.contrib.active_gaze.gaze_distribution.GazeGaussianDistribution`.""" + +from __future__ import annotations + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlMLPModelCfg + + +@configclass +class GazeGaussianDistributionCfg(RslRlMLPModelCfg.GaussianDistributionCfg): + """Gaussian action head whose gaze actions, the last two, have a fixed standard deviation. + + ``init_std``, ``std_type`` and ``std_range`` apply to the other actions. + """ + + class_name: str = "isaaclab_tasks.contrib.active_gaze.gaze_distribution:GazeGaussianDistribution" + gaze_std: float = 0.1 + """Fixed standard deviation of the gaze actions. One action moves the gaze by the gaze action's ``step_size``.""" diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py new file mode 100644 index 000000000000..3e1990dfdeb7 --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py @@ -0,0 +1,134 @@ +# 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 + +"""PPO with gaze supervision by a teacher, for RSL-RL. + +The update follows :meth:`rsl_rl.algorithms.PPO.update` (BSD-3-Clause) for feedforward models without RND or +symmetry, and adds the teacher's gaze loss to the PPO loss. +""" + +from __future__ import annotations + +import math + +import torch +from rsl_rl.algorithms import PPO +from torch import nn + +from .gaze_distribution import GAZE_ACTIONS + + +def gaze_loss(mean: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + """Mean distance between the policy's gaze-action means and the teacher's, over valid labels. + + Args: + mean: The policy's gaze-action means, shape (batch, 2). + labels: The teacher's gaze actions and their validity, shape (batch, 3). + """ + valid = labels[:, 2] > 0.5 + # Invalid rows may hold NaN; replacing it keeps their (discarded) residuals finite, so no NaN reaches the gradients. + residual = torch.where(valid[:, None], mean - torch.nan_to_num(labels[:, :2]), 0.0) + return residual.norm(dim=-1).sum() / valid.sum().clamp_min(1) + + +class GazeSupervisedPPO(PPO): + """PPO whose loss also pulls the policy's gaze toward a teacher's. + + The gaze is the last two actions. The teacher's labels are the observation group ``oracle_group``, as + :class:`isaaclab_fovi.mdp.gaze_teacher_labels` computes them; they never enter the actor or the critic. Only the + means of the gaze actions are supervised; pair it with + :class:`~isaaclab_tasks.contrib.active_gaze.gaze_distribution.GazeGaussianDistribution`, which fixes their noise. + + Args: + oracle_loss_coef: Weight of the gaze loss. Zero trains plain PPO. + oracle_group: Observation group of the teacher's labels. + """ + + def __init__( + self, + actor, + critic, + storage, + *, + oracle_loss_coef: float = 1.0, + oracle_group: str = "oracle", + **kwargs, + ): + if actor.is_recurrent or critic.is_recurrent or kwargs.get("rnd_cfg") or kwargs.get("symmetry_cfg"): + raise ValueError("GazeSupervisedPPO supports feedforward models without RND or symmetry.") + if not math.isfinite(oracle_loss_coef) or oracle_loss_coef < 0: + raise ValueError("oracle_loss_coef must be finite and nonnegative.") + super().__init__(actor, critic, storage, **kwargs) + self.oracle_loss_coef = oracle_loss_coef + self.oracle_group = oracle_group + + def update(self) -> dict[str, float]: + totals = torch.zeros(5, device=self.device) + generator = self.storage.mini_batch_generator(self.num_mini_batches, self.num_learning_epochs) + for batch in generator: + if self.normalize_advantage_per_mini_batch: + with torch.no_grad(): + batch.advantages = (batch.advantages - batch.advantages.mean()) / (batch.advantages.std() + 1e-8) + with torch.amp.autocast( + device_type=torch.device(self.device).type, enabled=self.use_mixed_precision, dtype=torch.bfloat16 + ): + self.actor(batch.observations, stochastic_output=True) + log_prob = self.actor.get_output_log_prob(batch.actions) + values = self.critic(batch.observations) + entropy = self.actor.output_entropy.mean() + if self.desired_kl is not None and self.schedule == "adaptive": + self._adapt_learning_rate(batch.old_distribution_params, self.actor.output_distribution_params) + ratio = torch.exp(log_prob - batch.old_actions_log_prob.squeeze(-1)) + advantages = batch.advantages.squeeze(-1) + surrogate = torch.max( + -advantages * ratio, -advantages * ratio.clamp(1.0 - self.clip_param, 1.0 + self.clip_param) + ).mean() + value_error = (values - batch.returns).pow(2) + if self.use_clipped_value_loss: + clipped = batch.values + (values - batch.values).clamp(-self.clip_param, self.clip_param) + value_error = torch.max(value_error, (clipped - batch.returns).pow(2)) + value_loss = value_error.mean() + loss = surrogate + self.value_loss_coef * value_loss - self.entropy_coef * entropy + if self.oracle_loss_coef > 0: + labels = batch.observations[self.oracle_group].float() + oracle = gaze_loss(self.actor.output_mean[:, -GAZE_ACTIONS:].float(), labels) + valid = (labels[:, 2] > 0.5).float().mean() + loss = loss + self.oracle_loss_coef * oracle + else: + # Plain PPO: the teacher's labels are neither needed nor read. + oracle = valid = torch.zeros((), device=self.device) + self.optimizer.zero_grad() + loss.backward() + if self.is_multi_gpu: + self.reduce_parameters() + nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm) + nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm) + self.optimizer.step() + totals += torch.stack((value_loss, surrogate, entropy, oracle, valid)).detach().float() + obs = self.storage.observations.flatten(0, 1) + self.actor.update_normalization(obs) + self.critic.update_normalization(obs) + self.storage.clear() + means = (totals / (self.num_learning_epochs * self.num_mini_batches)).tolist() + return dict(zip(("value", "surrogate", "entropy", "oracle", "oracle_valid"), means, strict=True)) + + def _adapt_learning_rate(self, old_params, new_params): + """Adapt the learning rate to the policy's KL divergence, as PPO's adaptive schedule does.""" + with torch.inference_mode(): + kl = self.actor.get_kl_divergence(old_params, new_params).mean() + if self.is_multi_gpu: + torch.distributed.all_reduce(kl, op=torch.distributed.ReduceOp.SUM) + kl /= self.gpu_world_size + if self.gpu_global_rank == 0: + if kl > self.desired_kl * 2.0: + self.learning_rate = max(1e-5, self.learning_rate / 1.5) + elif 0.0 < kl < self.desired_kl / 2.0: + self.learning_rate = min(1e-2, self.learning_rate * 1.5) + if self.is_multi_gpu: + rate = torch.tensor(self.learning_rate, device=self.device) + torch.distributed.broadcast(rate, src=0) + self.learning_rate = rate.item() + for group in self.optimizer.param_groups: + group["lr"] = self.learning_rate diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py new file mode 100644 index 000000000000..907dc6773afb --- /dev/null +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py @@ -0,0 +1,26 @@ +# 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 + +"""Configuration of :class:`~isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo.GazeSupervisedPPO`.""" + +from __future__ import annotations + +from isaaclab.utils import configclass + +from isaaclab_rl.rsl_rl import RslRlPpoAlgorithmCfg + + +@configclass +class GazeSupervisedPPOCfg(RslRlPpoAlgorithmCfg): + """PPO whose loss also pulls the policy's gaze toward a teacher's. + + See :class:`~isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo.GazeSupervisedPPO`. + """ + + class_name: str = "isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo:GazeSupervisedPPO" + oracle_loss_coef: float = 1.0 + """Weight of the gaze loss. Zero trains plain PPO.""" + oracle_group: str = "oracle" + """Observation group of the teacher's labels.""" diff --git a/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py b/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py new file mode 100644 index 000000000000..3ed040c4f789 --- /dev/null +++ b/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py @@ -0,0 +1,129 @@ +# 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 + +"""Gaze-supervised PPO and the fixed-noise gaze head of the active-gaze tasks, without a simulator.""" + +import pytest +import torch +from rsl_rl.algorithms import PPO +from rsl_rl.models import MLPModel +from rsl_rl.storage import RolloutStorage +from tensordict import TensorDict + +from isaaclab_tasks.contrib.active_gaze.gaze_distribution import GazeGaussianDistribution +from isaaclab_tasks.contrib.active_gaze.gaze_distribution_cfg import GazeGaussianDistributionCfg +from isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss + +pytestmark = pytest.mark.kitless + +NUM_ENVS = 64 +STEPS = 8 + + +def test_gaze_loss_ignores_invalid_labels(): + mean = torch.tensor([[0.0, 0.0], [1.0, 1.0]], requires_grad=True) + labels = torch.tensor([[0.3, 0.4, 1.0], [float("nan"), float("nan"), 0.0]]) + loss = gaze_loss(mean, labels) + loss.backward() + assert float(loss.detach()) == pytest.approx(0.5) + assert torch.isfinite(mean.grad).all() and not mean.grad[1].any() + + +def _algorithm( + oracle_loss_coef: float = 1.0, with_labels: bool = True, stock: bool = False, gaze_head: bool = False +) -> tuple[PPO | GazeSupervisedPPO, TensorDict]: + torch.manual_seed(0) + labels = torch.rand(NUM_ENVS, 3) * 2 - 1 + labels[:, 2] = (torch.arange(NUM_ENVS) % 4 != 0).float() + labels[labels[:, 2] == 0, :2] = float("nan") + groups = {"policy": torch.randn(NUM_ENVS, 6)} | ({"oracle": labels} if with_labels else {}) + obs = TensorDict(groups, batch_size=[NUM_ENVS]) + model_groups = {"actor": ["policy"], "critic": ["policy"]} + distribution = {"class_name": "GaussianDistribution", "init_std": 1.0} + if gaze_head: + head = GazeGaussianDistributionCfg(init_std=1.0, gaze_std=0.1) + distribution = {"class_name": head.class_name, "init_std": 1.0, "gaze_std": head.gaze_std} + actor = MLPModel(obs, model_groups, "actor", 3, hidden_dims=[32], distribution_cfg=distribution) + critic = MLPModel(obs, model_groups, "critic", 1, hidden_dims=[32]) + storage = RolloutStorage("rl", NUM_ENVS, STEPS, obs, [3], "cpu") + settings = dict(num_learning_epochs=4, num_mini_batches=4, learning_rate=3e-3, schedule="fixed", device="cpu") + if stock: + return PPO(actor, critic, storage, **settings), obs + return GazeSupervisedPPO(actor, critic, storage, oracle_loss_coef=oracle_loss_coef, **settings), obs + + +def _train(algorithm: PPO, obs: TensorDict, iterations: int) -> dict[str, float]: + for _ in range(iterations): + for _ in range(STEPS): + with torch.inference_mode(): + algorithm.act(obs) + algorithm.process_env_step(obs, torch.zeros(NUM_ENVS), torch.zeros(NUM_ENVS), {}) + algorithm.compute_returns(obs) + losses = algorithm.update() + return losses + + +def test_update_pulls_the_gaze_toward_the_teacher(): + algorithm, obs = _algorithm() + valid = obs["oracle"][:, 2] > 0.5 + + def distance() -> float: + with torch.no_grad(): + mean = algorithm.actor(obs)[:, -2:] + return float((mean - obs["oracle"][:, :2])[valid].norm(dim=-1).mean()) + + before = distance() + losses = _train(algorithm, obs, 40) + assert losses["oracle_valid"] == pytest.approx(0.75) + assert all(torch.isfinite(p).all() for p in algorithm.actor.parameters()) + assert distance() < 0.7 * before + + +def test_zero_coefficient_update_matches_stock_ppo_without_labels(): + def updated(stock: bool) -> tuple[list[torch.Tensor], list[torch.Tensor], dict[str, float]]: + algorithm, obs = _algorithm(oracle_loss_coef=0.0, with_labels=False, stock=stock) + modules = (algorithm.actor, algorithm.critic) + initial = [p.detach().clone() for module in modules for p in module.parameters()] + torch.manual_seed(1) + losses = _train(algorithm, obs, 1) + return initial, [p.detach().clone() for module in modules for p in module.parameters()], losses + + initial, gaze_params, losses = updated(stock=False) + stock_initial, stock_params, stock_losses = updated(stock=True) + assert losses["oracle"] == 0.0 and losses["oracle_valid"] == 0.0 + for name in ("value", "surrogate", "entropy"): + assert losses[name] == pytest.approx(stock_losses[name], rel=1e-6, abs=1e-7) + for start, stock_start in zip(initial, stock_initial, strict=True): + torch.testing.assert_close(start, stock_start, atol=0, rtol=0) + for param, stock_param in zip(gaze_params, stock_params, strict=True): + torch.testing.assert_close(param, stock_param, atol=0, rtol=0) + assert all(not torch.equal(param, start) for param, start in zip(gaze_params, initial, strict=True)) + + +def test_gaze_head_keeps_the_gaze_noise_fixed_while_ppo_learns_the_rest(): + """The entropy bonus and the surrogate move the other actions' noise, never the gaze's.""" + algorithm, obs = _algorithm(gaze_head=True) + algorithm.entropy_coef = 0.5 + head = algorithm.actor.distribution + assert isinstance(head, GazeGaussianDistribution) + assert head.std_param.shape == (1,) + _train(algorithm, obs, iterations=3) + with torch.no_grad(): + head.update(torch.zeros(1, 3)) + std = head.std[0] + torch.testing.assert_close(std[1:], torch.full((2,), 0.1)) + assert abs(float(std[0]) - 1.0) > 1e-3 + # The gaze noise is part of the saved policy, so a checkpoint restores it. + assert torch.equal(head.state_dict()["gaze_std"], torch.full((2,), 0.1)) + + +def test_gaze_head_fixes_the_last_two_actions_noise_and_rejects_invalid_settings(): + head = GazeGaussianDistribution(5, init_std=2.0, std_type="log", gaze_std=0.05) + assert head.input_dim == 5 + head.update(torch.zeros(3, 5)) + torch.testing.assert_close(head.std, torch.tensor([[2.0, 2.0, 2.0, 0.05, 0.05]]).expand(3, -1)) + for output_dim, gaze_std in ((5, 0.0), (5, float("inf")), (2, 0.1)): + with pytest.raises(ValueError, match="gaze"): + GazeGaussianDistribution(output_dim, gaze_std=gaze_std) diff --git a/source/isaaclab_tasks/test/core/test_cartpole_camera_presets.py b/source/isaaclab_tasks/test/core/test_cartpole_camera_presets.py index d72497bacbcb..b8235943b28f 100644 --- a/source/isaaclab_tasks/test/core/test_cartpole_camera_presets.py +++ b/source/isaaclab_tasks/test/core/test_cartpole_camera_presets.py @@ -21,7 +21,6 @@ CartpoleCameraEnvCfg as CartpoleManagerCameraEnvCfg, ) from isaaclab_tasks.utils.hydra import resolve_presets -from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry _ENV_CFG_CLASSES = [ pytest.param(CartpoleDirectCameraEnvCfg, id="direct"), @@ -50,24 +49,3 @@ def test_newton_renderer_accepts_supported_data_types(cfg_cls): """The guard must not reject data types the Newton Warp renderer does publish.""" cfg = resolve_presets(cfg_cls(), {"newton_warp", "rgb"}) validate(cfg) # must not raise - - -def test_foveated_cartpole_presets_connect_the_camera_and_stock_ppo(): - """The registered task selects matching image data and runs without teacher-specific inputs or training code.""" - pytest.importorskip("isaaclab_fovi") - pytest.importorskip("fovi") - task = "IsaacContrib-Cartpole-Camera-Fovi" - for data_type in ("rgb", "depth"): - raw_cfg = load_cfg_from_registry(task, "env_cfg_entry_point") - cfg = resolve_presets(raw_cfg, {data_type, "newton_warp"}) - validate(cfg) - image = cfg.observations.policy.image.params - assert image["data_type"] == data_type - assert cfg.scene.tiled_camera.data_types == [data_type] - assert image["sensor_cfg"].name == cfg.actions.gaze.asset_name - assert not hasattr(cfg.observations, "oracle") - - agent = load_cfg_from_registry(task, "rsl_rl_cfg_entry_point") - assert agent.obs_groups == {"actor": ["policy", "gaze"], "critic": ["critic", "gaze"]} - assert agent.algorithm.class_name == "PPO" - assert agent.actor.distribution_cfg.class_name == "GaussianDistribution" From 6b3faa83307325552b51c32afaced91a6e90980c Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Thu, 19 Nov 2026 16:17:54 -0800 Subject: [PATCH 48/81] Consolidate foveated sampling and visibility --- .../sensors/calibrated_geometry.py | 27 +++---------- .../isaaclab_fovi/sensors/foveated_camera.py | 19 +++++++-- .../sensors/foveated_newton_camera.py | 18 ++------- .../sensors/foveated_rtx_camera.py | 19 +++------ .../isaaclab_fovi/sensors/gaze_kernels.py | 5 ++- .../isaaclab_fovi/sensors/pooling.py | 37 +++++++---------- source/isaaclab_fovi/test/test_camera_cfg.py | 13 +++--- source/isaaclab_fovi/test/test_camera_gaze.py | 29 ++++++++------ .../isaaclab_fovi/test/test_newton_buffers.py | 40 +++++-------------- source/isaaclab_fovi/test/test_pooling.py | 17 ++++---- source/isaaclab_fovi/test/test_rtx_camera.py | 17 +++++++- 11 files changed, 102 insertions(+), 139 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index d499139eec0c..395ce83ff92f 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -8,13 +8,16 @@ from __future__ import annotations import math -from typing import Protocol +from typing import TYPE_CHECKING import torch from fovi.sensing.projection import CameraCalibration, CameraModel, angular_directions from isaaclab.sim import PinholeCameraCfg +if TYPE_CHECKING: + from .foveated_camera_cfg import FoveatedCameraCfg + IDEAL_IMAGE_WIDTH = 1024 """Pixel width [px] of the image assigned to a camera derived from ideal spawn optics. @@ -79,7 +82,7 @@ def camera_model_from_spawn(spawn: PinholeCameraCfg) -> CameraCalibration: ) -def resolve_camera_model(cfg: SamplingGeometryConfig) -> CameraModel: +def resolve_camera_model(cfg: FoveatedCameraCfg) -> CameraModel: """Return the physical camera the retina looks through. This is ``cfg.camera_model`` when set, otherwise the camera that ``cfg.spawn`` @@ -95,16 +98,6 @@ def resolve_camera_model(cfg: SamplingGeometryConfig) -> CameraModel: return CameraModel(**camera_model_from_spawn(cfg.spawn)) -def sampling_geometry(cfg: SamplingGeometryConfig) -> tuple[float, float]: - """Return the retinal field of view and the CMF constant, both in degrees. - - The field of view is the angular span of the retinal window in the physical - camera. Both values are in the units :class:`fovi.sensing.coords.SamplingCoords` takes. - """ - fov = resolve_camera_model(cfg).field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_fraction) - return fov, cfg.cmf_a_deg - - def retinal_directions(cartesian: torch.Tensor, fov_deg: float, image_rotation_deg: float = 0.0) -> torch.Tensor: """Return OpenGL-frame angular rays, including the sensor mount roll.""" rays = angular_directions(cartesian, fov_deg) @@ -121,13 +114,3 @@ def compose_rotations(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor: training process enables reduced-precision matrix multiplication. """ return (left[..., :, :, None] * right[..., None, :, :]).sum(dim=-2) - - -class SamplingGeometryConfig(Protocol): - """The configuration fields that place the retina in the physical camera.""" - - camera_model: CameraCalibration | None - cmf_a_deg: float - retinal_window_reference_side: str - retinal_window_fraction: float - spawn: PinholeCameraCfg | None diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 28af5b3b8ad7..5f0524baec98 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -34,6 +34,7 @@ ) from .native_grid import GRID_STYLE, buffer_tensor, native_grid_directions from .pooling import ( + build_retinal_coords, is_segmentation_output, pool_hwc_buffer, pool_segmentation_buffer, @@ -280,11 +281,23 @@ def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): stacklevel=2, ) - def _initialize_gaze(self) -> None: - """Prepare the gaze geometry: the rendered rays in the physical camera's frame and the pose conversions.""" + def _prepare_sampling(self) -> None: + """Resolve physical calibration and retinal coordinates before the renderer sizes its buffers.""" self._camera_model = resolve_camera_model(self.cfg) + self._sampling_coords, self._sampling_coords_highres = build_retinal_coords(self.cfg, self._camera_model, "cpu") + self._ray_coords = self._sampling_coords_highres or self._sampling_coords + self._native_grid = self.cfg.foveated_style == GRID_STYLE + self._num_valid_samples = len(self._sampling_coords) + self._num_ray_samples = len(self._ray_coords) + + def _initialize_sampling(self) -> None: + """Move retinal coordinates to the sensor device and prepare the gaze rays and frame conversions.""" + self._sampling_coords = self._sampling_coords.to(device=self._device) + if self._sampling_coords_highres is not None: + self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) + self._ray_coords = self._sampling_coords_highres or self._sampling_coords self._gaze_camera = camera_params(self._camera_model) - coords = self._sampling_coords_highres or self._sampling_coords + coords = self._ray_coords rotation_deg = self.cfg.image_rotation_deg # The rays as rendered, mount roll included, in the ROS frame the camera model projects. if coords.style == GRID_STYLE: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index f86bfeb479a9..55d64a3c68a7 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -19,7 +19,6 @@ from .foveated_camera import OPENGL_TO_ROS_AXES, FoveatedCamera from .native_grid import ( - GRID_STYLE, allocate_grid_outputs, copy_grid_outputs, copy_updated_rows, @@ -28,7 +27,7 @@ mask_grid_samples, proxy_outputs, ) -from .pooling import build_highres_coords, build_lowres_coords, build_pooler +from .pooling import build_pooler if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg @@ -77,11 +76,7 @@ def __init__(self, cfg: FoveatedCameraCfg): def _initialize_impl(self): # The pooler's KNN tensors are plain attributes that nn.Module.to() does not move, so the coordinates start on # the CPU and the pooler is built on the sensor device after the parent initializes. - self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") - self._native_grid = self.cfg.foveated_style == GRID_STYLE - self._sampling_coords_highres = build_highres_coords(self.cfg, self._sampling_coords, matched_res) - self._num_valid_samples = len(self._sampling_coords) - self._num_ray_samples = len(self._sampling_coords_highres or self._sampling_coords) + self._prepare_sampling() logger.info( "FoveatedNewtonCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg", self._num_valid_samples, @@ -92,8 +87,7 @@ def _initialize_impl(self): ) # The parent allocates render buffers for the rendered rays: the high-resolution ones when pooling. - ray_coords = self._sampling_coords_highres or self._sampling_coords - self.cfg.height, self.cfg.width = grid_output_shape(ray_coords) + self.cfg.height, self.cfg.width = grid_output_shape(self._ray_coords) renderer = self.cfg.renderer_cfg if renderer.render_order == "tiled": tile_width = renderer.tile_rendering_width @@ -112,11 +106,7 @@ def _initialize_impl(self): super()._initialize_impl() - self._sampling_coords = self._sampling_coords.to(device=self._device) - if self._sampling_coords_highres is not None: - self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) - self._ray_coords = self._sampling_coords_highres or self._sampling_coords - self._initialize_gaze() + self._initialize_sampling() self._pooler, self._pool_k = build_pooler( self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device) ) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 7260df107eed..c3a6efc0dcc4 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -32,7 +32,6 @@ from .calibrated_geometry import compose_rotations, retinal_directions from .foveated_camera import FoveatedCamera from .native_grid import ( - GRID_STYLE, allocate_grid_outputs, copy_grid_outputs, copy_updated_rows, @@ -40,7 +39,7 @@ mask_grid_samples, proxy_outputs, ) -from .pooling import build_highres_coords, build_lowres_coords, build_pooler +from .pooling import build_pooler if TYPE_CHECKING: from isaaclab.utils.warp import ProxyArray @@ -79,6 +78,7 @@ def __init__(self, cfg: FoveatedCameraCfg): self._pooled_output: dict[str, torch.Tensor] | None = None # The projection sets the texture size on the configuration before the parent allocates for it; the caller's # configuration stays untouched. + # The textures are square, so the parent's inferred vertical aperture agrees with the lens calibration. cfg = clone(cfg) self.cfg = cfg self._prepare_projection() @@ -153,13 +153,8 @@ def process_rendered_frame(self) -> None: def _prepare_projection(self) -> None: # The lens textures and sample extraction use the rendered samples: the high-resolution ones when pooling. - self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") - self._sampling_coords_highres = build_highres_coords(self.cfg, self._sampling_coords, matched_res) - ray_coords = self._sampling_coords_highres or self._sampling_coords - self._ray_coords = ray_coords - self._native_grid = self.cfg.foveated_style == GRID_STYLE - self._num_valid_samples = len(self._sampling_coords) - self._num_ray_samples = len(ray_coords) + self._prepare_sampling() + ray_coords = self._ray_coords size = ray_coords.resolution if not self._native_grid: @@ -233,11 +228,7 @@ def _initialize_impl(self) -> None: if not ext_manager.set_extension_enabled_immediate(ext_name, True): logger.warning("Could not enable Kit extension '%s'; the lens lookup may not render.", ext_name) - self._sampling_coords = self._sampling_coords.to(device=self._device) - if self._sampling_coords_highres is not None: - self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) - self._ray_coords = self._sampling_coords_highres or self._sampling_coords - self._initialize_gaze() + self._initialize_sampling() _, local_orientation = self._view.get_local_poses() self._base_local_orientation = matrix_from_quat(local_orientation.torch).clone() self._pooler, self._pool_k = build_pooler( diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py index 1f90730b1ec4..63beb9bbe386 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py @@ -282,6 +282,7 @@ def publish_grid_kernel( or, when masking, the physical camera's view. ``source`` and ``target`` hold each sample's channels as raw bytes, so one kernel serves every output type. + When masking, the first output records visibility and the other outputs reuse it on the same stream. """ env, cell = wp.tid() if not updated[env]: @@ -289,9 +290,11 @@ def publish_grid_kernel( sample = indices[cell] keep = footprint[sample] if mask_to_sensor != 0: - seen = sees(rays[sample], rotation[env], frame, camera) if record_visible != 0: + seen = sees(rays[sample], rotation[env], frame, camera) visible[env, sample] = seen + else: + seen = visible[env, sample] keep = keep and seen for k in range(target.shape[2]): if keep: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index c7093b517c9b..3735e297f46c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -15,7 +15,7 @@ visual-field geometry at different densities. Construction happens in two stages to accommodate Isaac's sensor init order: -1. ``build_lowres_coords`` + ``build_highres_coords`` run *before* +1. ``build_retinal_coords`` runs *before* ``super()._initialize_impl()`` (CPU) so the backend can size its render buffers from the highres sample count. 2. ``build_pooler`` runs *after* coords have been moved to the sensor's @@ -32,8 +32,7 @@ from fovi.arch.knn import KNNPoolingLayer from fovi.arch.pooling import GridPoolingLayer, build_retinal_pooler from fovi.sensing.coords import SamplingCoords, auto_match_num_coords - -from .calibrated_geometry import sampling_geometry +from fovi.sensing.projection import CameraModel if TYPE_CHECKING: from .foveated_camera_cfg import FoveatedCameraCfg @@ -44,17 +43,15 @@ _MODAL_CHUNK_ELEMENTS = 2**22 -def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCoords, int]: - """Build the lowres (RGC / public output) SamplingCoords. - - Returns ``(lowres_coords, matched_res)`` where ``matched_res`` is the - auto-matched radial resolution also needed for the highres grid. - """ - fov, cmf_a = sampling_geometry(cfg) +def build_retinal_coords( + cfg: FoveatedCameraCfg, camera: CameraModel, device: str +) -> tuple[SamplingCoords, SamplingCoords | None]: + """Build the public retina and, when pooling, the denser retina with the same angular geometry.""" + fov = camera.field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_fraction) matched_res, _ = auto_match_num_coords( fov, - cmf_a, + cfg.cmf_a_deg, cfg.foveated_res, cfg.foveated_style, 1, @@ -66,7 +63,7 @@ def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCo ) lowres = SamplingCoords( fov=fov, - cmf_a=cmf_a, + cmf_a=cfg.cmf_a_deg, res=matched_res, device=device, style=cfg.foveated_style, @@ -75,17 +72,11 @@ def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCo radius_norm=cfg.radius_norm, field_geometry="spherical", ) - return lowres, matched_res - - -def build_highres_coords(cfg: FoveatedCameraCfg, lowres: SamplingCoords, matched_res: int) -> SamplingCoords | None: - """Build the highres (photoreceptor) SamplingCoords when pooling is on: the lowres retina's geometry at - ``pool_res_mult`` times its resolution, on the same device.""" - if not cfg.pool_enabled: - return None - # pool_res_mult is a float to support fractional ratios (e.g. sqrt(2) for - # a 2× N_hi/N_lo ratio). SamplingCoords requires an integer radial res. - return lowres.clone(resolution=int(round(cfg.pool_res_mult * matched_res))) + highres = None + if cfg.pool_enabled: + # Fractional ratios (e.g. sqrt(2) for twice as many samples) still need an integer radial resolution. + highres = lowres.clone(resolution=int(round(cfg.pool_res_mult * lowres.resolution))) + return lowres, highres def build_pooler( diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py index aa783bcb2330..7827c7bf68e8 100644 --- a/source/isaaclab_fovi/test/test_camera_cfg.py +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -14,7 +14,7 @@ import pytest import torch from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg -from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model, sampling_geometry +from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_newton.renderers import NewtonWarpRendererCfg @@ -55,18 +55,16 @@ def test_defaults_are_grid_sampling_at_the_human_cmf_estimate() -> None: def test_pinhole_spawn_describes_an_ideal_pinhole_across_its_short_side() -> None: spawn = PinholeCameraCfg() - fov, cmf_a = sampling_geometry(make_cfg(spawn=spawn)) expected = math.degrees(2 * math.atan(spawn.horizontal_aperture / (2 * spawn.focal_length))) - assert fov == pytest.approx(expected, rel=1e-6) - assert cmf_a == 0.591 camera = resolve_camera_model(make_cfg(spawn=spawn)) + assert camera.field_of_view("short") == pytest.approx(expected, rel=1e-6) assert camera.model == "pinhole" assert camera.distortion == () # Without a vertical aperture the image is square; with one, the retina spans the short (vertical) side. assert camera.image_size[0] == camera.image_size[1] spawn = PinholeCameraCfg(focal_length=10.0, horizontal_aperture=20.0, vertical_aperture=10.0) - fov, _ = sampling_geometry(make_cfg(spawn=spawn)) - assert fov == pytest.approx(math.degrees(2 * math.atan(0.5)), rel=1e-6) + camera = resolve_camera_model(make_cfg(spawn=spawn)) + assert camera.field_of_view("short") == pytest.approx(math.degrees(2 * math.atan(0.5)), rel=1e-6) def test_opencv_pinhole_spawn_gives_that_calibrated_camera() -> None: @@ -96,8 +94,7 @@ def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> No # Equidistant: the angle off the optical axis grows linearly with image radius. for radius in (50.0, 150.0, 310.0): assert ray_angle_deg(camera, (319.5 + radius, 319.5)) == pytest.approx(math.degrees(radius / focal), rel=1e-6) - fov, _ = sampling_geometry(cfg) - assert fov == pytest.approx(math.degrees(640 / focal), rel=1e-6) + assert camera.field_of_view("short") == pytest.approx(math.degrees(640 / focal), rel=1e-6) def test_explicit_camera_model_wins_over_the_spawn() -> None: diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index ae6ac139a472..213bd08463a8 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -15,7 +15,7 @@ from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import CameraModel, angular_directions, gaze_rotation from fovi.sensing.retina import RetinalTransform -from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions, sampling_geometry +from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions from isaaclab_fovi.sensors.foveated_camera import FoveatedCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.gaze_kernels import ( @@ -26,7 +26,7 @@ torch_stream, ) from isaaclab_fovi.sensors.native_grid import GRID_STYLE, grid_sample_indices, native_grid_directions -from isaaclab_fovi.sensors.pooling import build_lowres_coords +from isaaclab_fovi.sensors.pooling import build_retinal_coords from isaaclab.sensors.camera.camera import Camera from isaaclab.sensors.camera.camera_data import CameraData @@ -71,19 +71,20 @@ def camera_config() -> SimpleNamespace: radius_norm=2.0, isotropic_plotting_type="v1like", image_rotation_deg=0.0, + pool_enabled=False, ) def test_rendering_and_software_sampling_share_window_and_nodes() -> None: cfg = camera_config() - fov, a = sampling_geometry(cfg) camera = CameraModel(**cfg.camera_model) - assert fov == pytest.approx(camera.field_of_view("long", 0.75)) - assert a == 2.5 - coords, _ = build_lowres_coords(cfg, "cpu") + fov = camera.field_of_view("long", 0.75) + coords, _ = build_retinal_coords(cfg, camera, "cpu") + assert coords.fov == pytest.approx(fov) + assert coords.cmf_a == 2.5 retina = RetinalTransform( fov=fov, - cmf_a=a, + cmf_a=2.5, resolution=12, device="cpu", field_geometry="spherical", @@ -106,8 +107,7 @@ def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None: self._view = SimpleNamespace(count=count) self._device = device self._ALL_INDICES = wp.array(list(range(count)), dtype=wp.int32, device=device) - self._sampling_coords, _ = build_lowres_coords(self.cfg, device) - self._sampling_coords_highres = None + self._prepare_sampling() # The camera's own pose buffers, at the identity orientation, with their world-to-ROS conversion. self._data = CameraData() self._data.create_buffers(count, device) @@ -115,7 +115,7 @@ def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None: # Isaac RTX's behaviour; Newton and OVRTX turn the pose by the gaze in their pose update. self._gaze_pose_reads_angles = False self._gaze_written = False - self._initialize_gaze() + self._initialize_sampling() @property def orientation(self) -> torch.Tensor: @@ -562,7 +562,10 @@ def test_publish_kernel_matches_masking_then_copying_to_the_grid() -> None: indices = grid_sample_indices(coords).to(torch.int32).contiguous() visible = torch.zeros(6, count, dtype=torch.bool, device=KERNEL_DEVICE) identity = wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) - for name, value in outputs.items(): + # Only the first output receives the real gaze. Reprojecting depth instead of reusing the first launch's + # visibility would point the depth rays the wrong way and hide visible samples. + _, looking_away = set_gaze(torch.tensor([[0.0, 180.0]], device=KERNEL_DEVICE).repeat(6, 1)) + for index, (name, value) in enumerate(outputs.items()): previous = torch.full_like(expected_grid[name], 7) target = previous.clone() with torch_stream(KERNEL_DEVICE): @@ -575,11 +578,11 @@ def test_publish_kernel_matches_masking_then_copying_to_the_grid() -> None: wp.from_torch(coords.valid_mask.contiguous()), wp.from_torch(updated), wp.from_torch(rays, dtype=wp.vec3f), - wp.from_torch(rotation, dtype=wp.mat33f), + wp.from_torch(rotation if index == 0 else looking_away, dtype=wp.mat33f), identity, camera_params(camera), 1, - int(name == "rgba"), + int(index == 0), wp.from_torch(visible), ], outputs=[wp.from_torch(target.view(6, count, -1).view(torch.uint8))], diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index b04505672812..ec3aa5f7bc5a 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -15,7 +15,6 @@ from fovi.sensing.projection import CameraModel from isaaclab_fovi.sensors import foveated_camera as base_camera from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera -from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera, explicit_rays from isaaclab_fovi.sensors.native_grid import native_grid_directions @@ -24,16 +23,6 @@ pytestmark = pytest.mark.kitless -def rendered_rays_only(camera) -> None: - """Stand-in for the gaze geometry: only the rendered rays, in the ROS frame the camera keeps them in.""" - coords = camera._ray_coords - if coords.style == "warped_cartesian_as_grid": - rays = native_grid_directions(coords, image_rotation_deg=0) - else: - rays = retinal_directions(coords.cartesian, coords.fov, 0) - camera._gaze_rays = (rays * rays.new_tensor((1.0, -1.0, -1.0))).float() - - def new_camera() -> FoveatedNewtonCamera: """A Newton camera without its constructor: the state its constructor sets and the handles its destructor reads.""" camera = object.__new__(FoveatedNewtonCamera) @@ -54,10 +43,8 @@ def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatc highres = coords.clone(resolution=32) if pooled else None ray_coords = highres if pooled else coords pooler = torch.nn.AdaptiveAvgPool1d(len(coords)) if pooled else None - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr(base_camera, "build_retinal_coords", lambda *args, **kwargs: (coords, highres)) monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (pooler, 4)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) def initialize_renderer(camera): # Newton launches image tiles; a vector-shaped width of one is not valid. @@ -85,6 +72,7 @@ def render(camera, env_mask): monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) camera = new_camera() camera.cfg = SimpleNamespace( + camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), foveated_style="warped_cartesian_as_grid", mask_to_sensor_fov=False, cmf_a_deg=0.591, @@ -129,10 +117,8 @@ def render(camera, env_mask): def test_sample_set_publication_keeps_environments_that_were_not_updated(monkeypatch) -> None: """A sample-set camera publishes its own buffers: Newton redraws every row, but only updated rows change.""" coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu") - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 8)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: None) + monkeypatch.setattr(base_camera, "build_retinal_coords", lambda *args, **kwargs: (coords, None)) monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (None, None)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) def initialize_renderer(camera): depth = torch.zeros((2, camera.cfg.height, camera.cfg.width, 1)) @@ -147,6 +133,7 @@ def render(camera, env_mask): monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) camera = new_camera() camera.cfg = SimpleNamespace( + camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), foveated_style="isotropic", mask_to_sensor_fov=False, pool_enabled=False, @@ -171,10 +158,8 @@ def render(camera, env_mask): def test_sample_set_sensor_mask_follows_the_published_frame(monkeypatch) -> None: """An environment that was not updated keeps its published samples and the sensor visibility that masked them.""" coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu") - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 8)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: None) + monkeypatch.setattr(base_camera, "build_retinal_coords", lambda *args, **kwargs: (coords, None)) monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (None, None)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) def initialize_renderer(camera): camera.renderer_depth = torch.ones((2, camera.cfg.height, camera.cfg.width, 1)) @@ -185,10 +170,9 @@ def initialize_renderer(camera): monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", lambda camera, env_mask: None) camera = new_camera() camera.cfg = SimpleNamespace( + camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), foveated_style="isotropic", mask_to_sensor_fov=True, - camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), - spawn=None, pool_enabled=False, image_rotation_deg=0, update_period=0.0, @@ -196,8 +180,6 @@ def initialize_renderer(camera): renderer_cfg=SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8), ) camera._initialize_impl() - # The real gaze geometry, on stand-in pose buffers. - base_camera.FoveatedCamera._initialize_gaze(camera) camera._view = SimpleNamespace(count=2, close=lambda: None) camera._data.quat_w_ros = ProxyArray(wp.from_torch(torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2), dtype=wp.quatf)) @@ -222,10 +204,8 @@ def test_pooled_segmentation_publishes_modal_labels_at_full_precision(monkeypatc neighbors = torch.stack([4 * runs + j for j in range(4)]) average = torch.nn.AdaptiveAvgPool1d(len(coords)) - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr(base_camera, "build_retinal_coords", lambda *args, **kwargs: (coords, highres)) monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (average, 4)) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) # The camera reads the modal neighbourhoods from its standard pooler. monkeypatch.setattr(base_camera, "segmentation_neighbor_indices", lambda pooler: neighbors) @@ -255,6 +235,7 @@ def render(camera, env_mask): monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) camera = new_camera() camera.cfg = SimpleNamespace( + camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), foveated_style="warped_cartesian_as_grid", mask_to_sensor_fov=False, update_period=0.0, @@ -314,12 +295,10 @@ def test_pooled_rgb_is_the_view_of_pooled_rgba(monkeypatch) -> None: style = "isotropic" coords = SamplingCoords(60.0, 0.591, 16, style=style, field_geometry="spherical", device="cpu") highres = coords.clone(resolution=32) - monkeypatch.setattr(newton_camera, "build_lowres_coords", lambda *args, **kwargs: (coords, 16)) - monkeypatch.setattr(newton_camera, "build_highres_coords", lambda *args, **kwargs: highres) + monkeypatch.setattr(base_camera, "build_retinal_coords", lambda *args, **kwargs: (coords, highres)) monkeypatch.setattr( newton_camera, "build_pooler", lambda *args, **kwargs: (torch.nn.AdaptiveAvgPool1d(len(coords)), 4) ) - monkeypatch.setattr(FoveatedNewtonCamera, "_initialize_gaze", rendered_rays_only) def initialize_renderer(camera): camera.renderer_rgba = torch.zeros((2, camera.cfg.height, camera.cfg.width, 4), dtype=torch.uint8) @@ -337,6 +316,7 @@ def render(camera, env_mask): monkeypatch.setattr(newton_camera.Camera, "_update_buffers_impl", render) camera = new_camera() camera.cfg = SimpleNamespace( + camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))), foveated_style=style, mask_to_sensor_fov=False, update_period=0.0, diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index d8cda0eb5880..8db3b69c12b4 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -11,10 +11,10 @@ import pytest import torch from isaaclab_fovi.sensors import FoveatedCameraCfg, pooling +from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model from isaaclab_fovi.sensors.pooling import ( - build_highres_coords, - build_lowres_coords, build_pooler, + build_retinal_coords, pool_hwc_buffer, pool_segmentation_buffer, segmentation_neighbor_indices, @@ -50,8 +50,7 @@ def pooling_cfg(**overrides) -> FoveatedCameraCfg: def test_camera_pools_its_buffers_by_its_config() -> None: cfg = pooling_cfg(pool_mode="max") - lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, lowres, matched) + lowres, highres = build_retinal_coords(cfg, resolve_camera_model(cfg), "cpu") # The photoreceptor grid shares the retina's geometry at a higher resolution, and the pooler takes the config. assert len(highres) > len(lowres) and highres.cmf_a == lowres.cmf_a and highres.fov == lowres.fov pooler, neighbors = build_pooler(cfg, lowres, highres, "cpu") @@ -64,8 +63,8 @@ def test_camera_pools_its_buffers_by_its_config() -> None: torch.testing.assert_close(actual, constants[:, None, None, :].expand(2, len(lowres), 1, 3)) # Without pooling there is no photoreceptor grid. cfg = pooling_cfg(pool_enabled=False) - lowres, matched = build_lowres_coords(cfg, "cpu") - assert build_highres_coords(cfg, lowres, matched) is None + _, highres = build_retinal_coords(cfg, resolve_camera_model(cfg), "cpu") + assert highres is None # Three output samples over five input samples; 5 marks an excluded neighbour. Columns are outputs, rows are @@ -124,8 +123,7 @@ def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Ten def test_modal_pooling_uses_the_poolers_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex) -> None: """Segmentation pools over the same neighbourhoods as the camera's other outputs: grid windows or KNN.""" cfg = pooling_cfg(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex, pool_mode="max") - lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, lowres, matched) + lowres, highres = build_retinal_coords(cfg, resolve_camera_model(cfg), "cpu") pooler, k = build_pooler(cfg, lowres, highres, "cpu") table = segmentation_neighbor_indices(pooler) assert table.shape == (k, len(lowres)) @@ -144,8 +142,7 @@ def test_modal_pooling_uses_the_poolers_neighbourhoods(monkeypatch, style: str, @pytest.mark.parametrize(("style", "pool_k", "mode"), [("warped_cartesian_as_grid", 9, "avg"), ("isotropic", 6, "max")]) def test_pooling_leaves_out_photoreceptors_the_camera_does_not_see(style: str, pool_k: int, mode: str) -> None: cfg = pooling_cfg(foveated_style=style, pool_mode=mode, pool_k=pool_k) - lowres, matched = build_lowres_coords(cfg, DEVICE) - highres = build_highres_coords(cfg, lowres, matched) + lowres, highres = build_retinal_coords(cfg, resolve_camera_model(cfg), DEVICE) pooler, _ = build_pooler(cfg, lowres, highres, DEVICE) # The camera's image edge cuts the retina at x = 0.3 in the first environment; the second sees everything. visible = torch.stack([highres.cartesian[:, 0] < 0.3, torch.ones(len(highres), dtype=torch.bool, device=DEVICE)]) diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py index 23fbbfd36593..adb3258ea669 100644 --- a/source/isaaclab_fovi/test/test_rtx_camera.py +++ b/source/isaaclab_fovi/test/test_rtx_camera.py @@ -13,6 +13,7 @@ import pytest import torch import warp as wp +from fovi.sensing.projection import CameraModel from isaaclab_fovi.sensors import foveated_rtx_camera, lens_lut from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera @@ -100,6 +101,16 @@ def test_construction_authors_the_lens_and_unlocks_cameras_without_changing_the_ def construct(self, cfg): self.cfg = cfg self.stage = stage + self._device = "cpu" + # The stock camera infers the vertical aperture using the allocated texture dimensions. + self.cfg.spawn.vertical_aperture = cfg.spawn.horizontal_aperture * cfg.height / cfg.width + + field_of_view = CameraModel.field_of_view + sampling_models = [] + + def measure_window(model, *args): + sampling_models.append(model) + return field_of_view(model, *args) build_directions = lens_lut.native_grid_directions ray_builds = [] @@ -111,6 +122,7 @@ def measure_directions(*args, **kwargs): texture_paths = ("/textures/enter.exr", "/textures/exit.exr") monkeypatch.setattr(Camera, "__init__", construct) + monkeypatch.setattr(CameraModel, "field_of_view", measure_window) # Count at both import locations so evaluating a second ray grid in the camera fails this check. monkeypatch.setattr(lens_lut, "native_grid_directions", measure_directions) monkeypatch.setattr(foveated_rtx_camera, "native_grid_directions", measure_directions, raising=False) @@ -131,7 +143,10 @@ def measure_directions(*args, **kwargs): assert prim.GetAttribute("omni:lensdistortion:lut:rayEnterDirectionTexture").Get().path == "/textures/enter.exr" assert camera.cfg is not cfg and (camera.cfg.height, camera.cfg.width) == (16, 16) assert len(ray_builds) == 1 - assert cfg.spawn.lock_camera and (cfg.height, cfg.width) == (1, 1) + camera._initialize_sampling() + assert len(sampling_models) == 1 and camera.camera_model is sampling_models[0] + assert camera.camera_model.image_size == (1024, 1024) + assert cfg.spawn.lock_camera and cfg.spawn.vertical_aperture is None and (cfg.height, cfg.width) == (1, 1) def test_lens_lut_survives_usd_export_without_schema_registration() -> None: From f0ba80d83080c03609c55f8bb717e11f9eccfa3a Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Thu, 19 Nov 2026 16:17:54 -0800 Subject: [PATCH 49/81] Reuse stock Cartpole camera observations for active gaze --- .../fovi-cartpole-observations.skip | 0 .../cartpole_camera_fovi_env_cfg.py | 37 ++++++------------- 2 files changed, 12 insertions(+), 25 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/fovi-cartpole-observations.skip diff --git a/source/isaaclab_tasks/changelog.d/fovi-cartpole-observations.skip b/source/isaaclab_tasks/changelog.d/fovi-cartpole-observations.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py index da42ff2226c3..75406bd76a00 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py @@ -12,14 +12,16 @@ from isaaclab_fovi import mdp -from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg +from isaaclab.managers import ObservationGroupCfg, SceneEntityCfg from isaaclab.utils import configclass -from isaaclab_tasks.core.cartpole import mdp as cartpole_mdp from isaaclab_tasks.core.cartpole.cartpole_common import CartpoleTiledCameraCfg -from isaaclab_tasks.core.cartpole.cartpole_manager_camera_env_cfg import CartpoleCameraEnvCfg, CartpoleCameraSceneCfg +from isaaclab_tasks.core.cartpole.cartpole_manager_camera_env_cfg import ( + CartpoleCameraEnvCfg, + CartpoleCameraSceneCfg, + image_observations_cfg, +) from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ActionsCfg as CartpoleActionsCfg -from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ObservationsCfg as CartpoleObservationsCfg from isaaclab_tasks.utils import PresetCfg from .active_gaze_cfg import GazeObservationsCfg, foveated_presets, oracle_observations, select_presets @@ -31,29 +33,14 @@ """Retina samples across; the stock camera is 96 pixels across.""" -def observations(data_type: str, image_term) -> object: +def observations(data_type: str) -> object: """The stock camera observations of ``data_type``, the gaze, and the teacher's labels.""" + camera = image_observations_cfg(data_type) @configclass class ObservationsCfg: - @configclass - class PolicyCfg(ObservationGroupCfg): - image = ObservationTermCfg( - func=image_term, - params={ - "sensor_cfg": SceneEntityCfg("tiled_camera"), - "data_type": data_type, - "channel_first": True, - "frame_stack": 2, - }, - ) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - policy: ObservationGroupCfg = PolicyCfg() - critic: ObservationGroupCfg = CartpoleObservationsCfg.PolicyCfg() + policy: ObservationGroupCfg = camera.policy + critic: ObservationGroupCfg = camera.critic gaze: ObservationGroupCfg = GazeObservationsCfg() oracle: ObservationGroupCfg = oracle_observations(SceneEntityCfg("robot", body_names="pole"), POLE_TIP) @@ -80,6 +67,6 @@ class BaseCfg(CartpoleCameraEnvCfg.BaseCartpoleCameraEnvCfg): scene: SceneCfg = SceneCfg(num_envs=512, env_spacing=20.0) actions: ActionsCfg = ActionsCfg() - rgb = BaseCfg(observations=observations("rgb", cartpole_mdp.image_rgb)) - depth = BaseCfg(observations=observations("depth", cartpole_mdp.image_depth)) + rgb = BaseCfg(observations=observations("rgb")) + depth = BaseCfg(observations=observations("depth")) default = rgb From e754d1e3e0af48a3408bee35add69a17dd0e9780 Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 16:02:02 -0800 Subject: [PATCH 50/81] Address the sixth review round on the foveated camera - Count a mount turn by comparing each selected mount before and after any pose write, so repeating a view or writing back a pose leaves the fixed-mount teacher valid; Isaac RTX writes its gaze back onto moved prims through one hook. - Resolve gaze pose index selectors (sequences, slices, tensors, int64 or strided Warp arrays) to contiguous int32 indices. - Publish partial updates with the stock masked copy instead of full-batch torch.where temporaries. - Place every sample-set direction texel by UV, build the high-resolution grid from the low-resolution one, import fovi at module scope in pooling, and check spawn configurations by type. - Add the fovi extra to the opt-in extras of the pyproject test. - Test that pooled rgb is a view of pooled rgba, and document how the sensor mask meets pooling. --- .../test/cli/test_uv_run_pyproject.py | 1 + .../sensors/calibrated_geometry.py | 29 +++++++--- .../isaaclab_fovi/sensors/foveated_camera.py | 57 ++++++++++++++----- .../sensors/foveated_camera_cfg.py | 6 +- .../sensors/foveated_newton_camera.py | 11 ++-- .../sensors/foveated_rtx_camera.py | 37 ++---------- .../isaaclab_fovi/sensors/lens_lut.py | 19 +++---- .../isaaclab_fovi/sensors/native_grid.py | 25 ++++++++ .../isaaclab_fovi/sensors/pooling.py | 37 +++--------- source/isaaclab_fovi/test/test_camera_cfg.py | 2 + source/isaaclab_fovi/test/test_lens_lut.py | 13 +++++ .../isaaclab_fovi/test/test_newton_buffers.py | 4 ++ source/isaaclab_fovi/test/test_pooling.py | 14 ++--- .../test/test_spherical_geometry.py | 40 +++++++++++-- .../test/test_square_native_grid.py | 2 +- 15 files changed, 180 insertions(+), 117 deletions(-) diff --git a/source/isaaclab/test/cli/test_uv_run_pyproject.py b/source/isaaclab/test/cli/test_uv_run_pyproject.py index cc7e06e449af..e28b7b4f8132 100644 --- a/source/isaaclab/test/cli/test_uv_run_pyproject.py +++ b/source/isaaclab/test/cli/test_uv_run_pyproject.py @@ -123,6 +123,7 @@ def test_all_extra_aggregates_curated_ov_rl_and_visualizer_extras(source_checkou "tetrahedralization", "video", "optix", + "fovi", "leapp", "wandb", "test", diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index 1d5edc707b35..d499139eec0c 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -8,18 +8,20 @@ from __future__ import annotations import math -from typing import Any, Protocol +from typing import Protocol import torch from fovi.sensing.projection import CameraCalibration, CameraModel, angular_directions +from isaaclab.sim import PinholeCameraCfg + IDEAL_IMAGE_WIDTH = 1024 """Pixel width [px] of the image assigned to a camera derived from ideal spawn optics. The scale is arbitrary: the retinal window and the gaze are angles, so neither depends on it.""" -def camera_model_from_spawn(spawn: Any) -> CameraCalibration: +def camera_model_from_spawn(spawn: PinholeCameraCfg) -> CameraCalibration: """Describe the camera that the spawn configuration creates as :class:`CameraModel` fields. * An OpenCV model in ``spawn.distortion`` gives that calibrated camera. A fisheye @@ -28,10 +30,12 @@ def camera_model_from_spawn(spawn: Any) -> CameraCalibration: a vertical aperture, the image is square. Raises: - ValueError: The spawn configuration describes a camera fovi cannot model: a USD - fisheye projection, thin-prism distortion, or an aperture offset. + ValueError: The spawn configuration is not a camera's, or describes a camera fovi cannot + model: a USD fisheye projection, thin-prism distortion, or an aperture offset. """ - distortion = getattr(spawn, "distortion", None) + if not isinstance(spawn, PinholeCameraCfg): + raise ValueError(f"{type(spawn).__name__} does not spawn a camera; set camera_model instead.") + distortion = spawn.distortion if distortion is not None: width, height = distortion.image_size intrinsics = (distortion.fx, distortion.fy, distortion.cx, distortion.cy) @@ -40,7 +44,16 @@ def camera_model_from_spawn(spawn: Any) -> CameraCalibration: coefficients = (distortion.k1, distortion.k2, distortion.k3, distortion.k4) elif distortion.model == "opencvPinhole": calibration = CameraCalibration(model="pinhole") - coefficients = tuple(getattr(distortion, name) for name in ("k1", "k2", "p1", "p2", "k3", "k4", "k5", "k6")) + coefficients = ( + distortion.k1, + distortion.k2, + distortion.p1, + distortion.p2, + distortion.k3, + distortion.k4, + distortion.k5, + distortion.k6, + ) thin_prism = (distortion.s1, distortion.s2, distortion.s3, distortion.s4) if distortion.apply_lens_distortion and any(thin_prism): raise ValueError("Thin-prism distortion (s1-s4) is not supported; set camera_model instead.") @@ -50,7 +63,7 @@ def camera_model_from_spawn(spawn: Any) -> CameraCalibration: if distortion.apply_lens_distortion and any(coefficients): calibration["distortion"] = tuple(float(value) for value in coefficients) return calibration - if getattr(spawn, "projection_type", None) != "pinhole": + if spawn.projection_type != "pinhole": raise ValueError( "Only pinhole spawn optics describe a camera; for a fisheye, set spawn.distortion to an " "OpenCvFisheyeDistortionCfg or set camera_model." @@ -117,4 +130,4 @@ class SamplingGeometryConfig(Protocol): cmf_a_deg: float retinal_window_reference_side: str retinal_window_fraction: float - spawn: Any + spawn: PinholeCameraCfg | None diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index ebd03ca8fb33..51c4733ae623 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -246,21 +246,25 @@ def set_world_poses(self, positions=None, orientations=None, env_ids=None, conve Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. """ - # The teachers read the camera's live position, so only a write that turns a selected mount counts; writing - # back the poses that get_world_poses reports does not. - turned = orientations is not None and self._turns_mount(orientations, env_ids, convention) + if orientations is None: + # A position-only move keeps every mount's orientation. + super().set_world_poses(positions, orientations, env_ids, convention) + return + before = self._mount_orientations(env_ids) super().set_world_poses(positions, orientations, env_ids, convention) - if turned: - self.mount_turns += 1 + self._mount_written(env_ids) + self._count_mount_turn(before, env_ids) def set_world_poses_from_view(self, eyes, targets, env_ids=None): """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. """ + before = self._mount_orientations(env_ids) super().set_world_poses_from_view(eyes, targets, env_ids) - if self._turned_by_view(eyes, targets).any(): - self.mount_turns += 1 + # Rows whose eye equals their target are skipped by the base method and keep their poses. + self._mount_written(self._env_indices(env_ids)[self._turned_by_view(eyes, targets)]) + self._count_mount_turn(before, env_ids) def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): """Keep the camera as configured and warn the caller. @@ -357,8 +361,9 @@ def _apply_gaze_pose( frames = (self._gaze_angles, *self._gaze_frames) outputs = [orientation, self._gaze_rotation, self._mount_quat_ros] indexed = env_ids is not None and env_mask is None - if indexed and not isinstance(env_ids, wp.array): - env_ids = wp.from_torch(torch.as_tensor(env_ids, dtype=torch.int32, device=device).contiguous()) + if indexed: + # The kernel takes contiguous int32 indices; this converts sequences, slices, tensors and Warp arrays. + env_ids = self._resolve_env_ids_wp(env_ids) # Every pose update writes the same pose buffer: for all environments, under the camera's update mask, or # for the indexed ones, whose indices each call swaps in. mode = "ids" if indexed else ("all" if env_mask is None else "mask") @@ -377,12 +382,34 @@ def _apply_gaze_pose( launch.set_dim(len(env_ids)) launch.launch(warp_stream(device)) - def _turns_mount(self, orientations, env_ids, convention: str) -> bool: - """Whether writing ``orientations`` would turn any selected camera's mount, compared with its current one.""" - _, current = self.get_world_poses(env_ids, convention=convention) - requested = self._as_device_tensor(orientations, 4).to(current.dtype).expand_as(current) - requested = torch.nn.functional.normalize(requested, dim=-1) - return bool((quat_error_magnitude(current, requested) > MOUNT_TURN_TOLERANCE_RAD).any()) + def _mount_orientations(self, env_ids) -> torch.Tensor: + """The selected cameras' mount orientations (x, y, z, w), world convention, as :meth:`get_world_poses` reports + them.""" + return self.get_world_poses(env_ids, convention="world")[1].clone() + + def _mount_written(self, env_ids) -> None: + """Called after a pose write turned the selected cameras' mounts, before the turn is measured. Cameras that + hold the gaze in their prims write it onto the new mounts here.""" + + def _count_mount_turn(self, before: torch.Tensor, env_ids) -> None: + """Count a mount turn if any selected camera's mount now differs from ``before``. + + The teachers read the camera's live position, so only orientation changes count, and writing back the reported + poses does not. + """ + turned = quat_error_magnitude(before, self._mount_orientations(env_ids)) > MOUNT_TURN_TOLERANCE_RAD + if bool(turned.any()): + self.mount_turns += 1 + + def _env_indices(self, env_ids) -> torch.Tensor: + """The camera indices that ``env_ids`` selects, as a tensor.""" + if env_ids is None: + return torch.arange(self._view.count, device=self._device) + if isinstance(env_ids, slice): + return torch.arange(self._view.count, device=self._device)[env_ids] + if isinstance(env_ids, wp.array): + env_ids = wp.to_torch(env_ids) + return torch.as_tensor(env_ids, device=self._device, dtype=torch.long).reshape(-1) def _turned_by_view(self, eyes, targets) -> torch.Tensor: """Which rows :meth:`set_world_poses_from_view` turns: the base method skips an eye equal to its target.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 6c0c64f38b79..4fabc85fa1bd 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -115,7 +115,11 @@ class FoveatedCameraCfg(CameraCfg): upright; the sensor mask and the gaze use the same roll.""" mask_to_sensor_fov: bool = False - """Zero the samples that fall outside the physical camera's image at the current gaze.""" + """Zero the samples that fall outside the physical camera's image at the current gaze. + + With :attr:`pool_enabled`, the mask applies to the photoreceptor samples before pooling, so a pooled sample whose + neighbourhood straddles the image edge keeps the pooled value of the photoreceptors the camera sees, and is zero + when it sees none of them.""" retinal_window_fraction: float = 1.0 """Diameter of the retinal window as a fraction of the reference image side.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 6b84cb55ff6e..f86bfeb479a9 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -22,6 +22,7 @@ GRID_STYLE, allocate_grid_outputs, copy_grid_outputs, + copy_updated_rows, grid_output_shape, grid_sample_indices, mask_grid_samples, @@ -78,7 +79,7 @@ def _initialize_impl(self): # the CPU and the pooler is built on the sensor device after the parent initializes. self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") self._native_grid = self.cfg.foveated_style == GRID_STYLE - self._sampling_coords_highres = build_highres_coords(self.cfg, matched_res, device="cpu") + self._sampling_coords_highres = build_highres_coords(self.cfg, self._sampling_coords, matched_res) self._num_valid_samples = len(self._sampling_coords) self._num_ray_samples = len(self._sampling_coords_highres or self._sampling_coords) logger.info( @@ -241,20 +242,18 @@ def _update_buffers_impl(self, env_mask: wp.array): self._publish_grid(env_mask) else: self._apply_sensor_fov_mask(self._flat_render_output, env_mask) - updated = wp.to_torch(env_mask)[:, None, None, None] for name, samples in self._sample_output.items(): if name == "rgb" and "rgba" in self._sample_output: continue # rgba alias - samples.copy_(torch.where(updated, self._flat_render_output[name].torch, samples)) + copy_updated_rows(self._flat_render_output[name].torch, samples, env_mask) return mask_grid_samples(self._highres_output, self._ray_coords) self._apply_sensor_fov_mask(self._highres_output, env_mask) - updated = wp.to_torch(env_mask)[:, None, None, None] for name, hi in self._highres_output.items(): if name == "rgb" and "rgba" in self._highres_output: continue # rgba alias - pooled = self._pooled_output[name] - pooled.copy_(torch.where(updated, self._pool_output(name, hi.torch), pooled)) + # Pooling covers every environment; only the updated ones are published. + copy_updated_rows(self._pool_output(name, hi.torch), self._pooled_output[name], env_mask) if self._native_grid: copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py index 2db28d7d2d5c..2a6887d041f8 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py @@ -35,6 +35,7 @@ GRID_STYLE, allocate_grid_outputs, copy_grid_outputs, + copy_updated_rows, grid_sample_indices, mask_grid_samples, native_grid_directions, @@ -109,25 +110,6 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: if not self._gaze_pose_reads_angles: self._write_gaze_local_pose() - def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): - """Move the camera's mount; the gaze stays relative to the new mount. - - Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`. - """ - super().set_world_poses(positions, orientations, env_ids, convention) - # A position-only move keeps the prims' gaze-turned orientation, and with it the saved mount. - if orientations is not None: - self._refresh_mount(env_ids) - - def set_world_poses_from_view(self, eyes, targets, env_ids=None): - """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount. - - Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`. - """ - super().set_world_poses_from_view(eyes, targets, env_ids) - # Rows whose eye equals their target are skipped by the base method and keep their mount. - self._refresh_mount(self._env_indices(env_ids)[self._turned_by_view(eyes, targets)]) - def get_world_poses(self, env_ids=None, convention="ros"): """Read the cameras' mount poses, without the gaze, as every foveated camera reports them. @@ -173,7 +155,7 @@ def process_rendered_frame(self) -> None: def _prepare_projection(self) -> None: # The lens textures and sample extraction use the rendered samples: the high-resolution ones when pooling. self._sampling_coords, matched_res = build_lowres_coords(self.cfg, device="cpu") - self._sampling_coords_highres = build_highres_coords(self.cfg, matched_res, device="cpu") + self._sampling_coords_highres = build_highres_coords(self.cfg, self._sampling_coords, matched_res) ray_coords = self._sampling_coords_highres or self._sampling_coords self._ray_coords = ray_coords self._native_grid = self.cfg.foveated_style == GRID_STYLE @@ -357,17 +339,7 @@ def _allocate_foveated_buffers(self): self._num_valid_samples, ) - def _env_indices(self, env_ids) -> torch.Tensor: - """The camera indices that ``env_ids`` selects, as a tensor.""" - if env_ids is None: - return torch.arange(self._view.count, device=self._device) - if isinstance(env_ids, slice): - return torch.arange(self._view.count, device=self._device)[env_ids] - if isinstance(env_ids, wp.array): - env_ids = wp.to_torch(env_ids) - return torch.as_tensor(env_ids, device=self._device, dtype=torch.long).reshape(-1) - - def _refresh_mount(self, env_ids) -> None: + def _mount_written(self, env_ids) -> None: """Save the moved prims' orientations as their bare mounts and write the gaze on top of them again.""" if self._gaze_pose_reads_angles: return # The pose update turns the new mount by the gaze. @@ -397,7 +369,6 @@ def _update_buffers_impl(self, env_mask: wp.array): def _extract_foveated_samples(self, env_mask: wp.array): """Extract the updated environments' per-sample values from the rendered 2D textures into the (B, N, 1, C) buffers; the other environments keep their last samples.""" - updated = wp.to_torch(env_mask)[:, None, None, None] for name in self._texture_output: if name == "rgb" and "rgba" in self._texture_output: continue # rgba alias @@ -411,7 +382,7 @@ def _extract_foveated_samples(self, env_mask: wp.array): if self._offset_distance and name == "distance_to_camera": # OVRTX measures the distance from the near-clipped ray origin. samples = samples + self._near_clip.to(samples.dtype) - fov.copy_(torch.where(updated, samples, fov)) + copy_updated_rows(samples, fov, env_mask) @staticmethod def _pose_update_turns_gaze(cfg: FoveatedCameraCfg) -> bool: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py index 510a6d393139..383c4f12f14b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py @@ -105,23 +105,20 @@ def build_lut_textures( uv_t = _t(samples_uv, torch.float32, device) dirs_t = _t(ray_directions, torch.float32, device) N = uv_t.shape[0] - Q = texture_width * texture_height # Direction texture. dir_out = torch.zeros(texture_height, texture_width, 3, dtype=torch.float32, device=device) dir_out[:, :, 2] = -1.0 if N > 0: - if N == Q: - dir_out.reshape(-1, 3)[:] = dirs_t - else: - u_t = (torch.arange(texture_width, dtype=torch.float32, device=device) + 0.5) / texture_width - v_t = (torch.arange(texture_height, dtype=torch.float32, device=device) + 0.5) / texture_height - U = u_t.unsqueeze(0).expand(texture_height, texture_width) - V = v_t.unsqueeze(1).expand(texture_height, texture_width) - texel_uv = torch.stack([U.reshape(-1), V.reshape(-1)], dim=1) - k_nn = _nn_chunk(texel_uv, uv_t, chunk) - dir_out.reshape(-1, 3)[:] = dirs_t[k_nn] + # Each texel takes the ray of the sample nearest it in UV, whatever order the samples come in. + u_t = (torch.arange(texture_width, dtype=torch.float32, device=device) + 0.5) / texture_width + v_t = (torch.arange(texture_height, dtype=torch.float32, device=device) + 0.5) / texture_height + U = u_t.unsqueeze(0).expand(texture_height, texture_width) + V = v_t.unsqueeze(1).expand(texture_height, texture_width) + texel_uv = torch.stack([U.reshape(-1), V.reshape(-1)], dim=1) + k_nn = _nn_chunk(texel_uv, uv_t, chunk) + dir_out.reshape(-1, 3)[:] = dirs_t[k_nn] # Exit texture: only texels whose direction lies within the samples' field (r <= max_r) map to a sample; the rest # hold the invalid UV (-1, -1), as in native-grid LUTs, so rays outside the field never reach the fovea. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py index 0da4070dd53a..459bdb690094 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py @@ -16,6 +16,9 @@ from fovi.sensing.coords import SamplingCoords from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.memory import make_masked_copy + +from .gaze_kernels import warp_stream GRID_STYLE = "warped_cartesian_as_grid" @@ -33,6 +36,28 @@ def proxy_outputs(outputs: Mapping[str, torch.Tensor | ProxyArray]) -> dict[str, } +def copy_updated_rows(source: torch.Tensor, target: torch.Tensor, rows: wp.array) -> None: + """Copy the environments that ``rows`` selects from ``source`` into ``target``, shape (num_envs, N, 1, C). + + The other environments keep their values. The masked copy needs no full-batch temporary and no host sync. + + Args: + source: The new samples; may be a strided view. + target: The published samples, written in place. + rows: Which environments to copy, shape (num_envs,) of ``bool``. + """ + source3, target3 = source.squeeze(2), target.squeeze(2) + dtype = wp.dtype_from_torch(target.dtype) + wp.launch( + make_masked_copy(dtype, 3), + dim=tuple(target3.shape), + inputs=[wp.from_torch(source3, dtype=dtype), rows, None], + outputs=[wp.from_torch(target3, dtype=dtype)], + device=str(target.device), + stream=warp_stream(target.device), + ) + + def bounded_angular_radius(radius: torch.Tensor, half_fov_rad: float) -> torch.Tensor: """Continue angular padding monotonically toward the antipode. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py index d402e200bba3..eda13af47813 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py @@ -29,14 +29,13 @@ from typing import TYPE_CHECKING import torch +from fovi.arch.knn import KNNPoolingLayer +from fovi.arch.pooling import GridPoolingLayer, build_retinal_pooler +from fovi.sensing.coords import SamplingCoords, auto_match_num_coords from .calibrated_geometry import sampling_geometry if TYPE_CHECKING: - from fovi.arch.knn import KNNPoolingLayer - from fovi.arch.pooling import GridPoolingLayer - from fovi.sensing.coords import SamplingCoords - from .foveated_camera_cfg import FoveatedCameraCfg @@ -51,8 +50,6 @@ def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCo Returns ``(lowres_coords, matched_res)`` where ``matched_res`` is the auto-matched radial resolution also needed for the highres grid. """ - from fovi.sensing.coords import SamplingCoords, auto_match_num_coords - fov, cmf_a = sampling_geometry(cfg) matched_res, _ = auto_match_num_coords( @@ -81,28 +78,14 @@ def build_lowres_coords(cfg: FoveatedCameraCfg, device: str) -> tuple[SamplingCo return lowres, matched_res -def build_highres_coords(cfg: FoveatedCameraCfg, matched_res: int, device: str) -> SamplingCoords | None: - """Build the highres (photoreceptor) SamplingCoords when pooling is on.""" +def build_highres_coords(cfg: FoveatedCameraCfg, lowres: SamplingCoords, matched_res: int) -> SamplingCoords | None: + """Build the highres (photoreceptor) SamplingCoords when pooling is on: the lowres retina's geometry at + ``pool_res_mult`` times its resolution, on the same device.""" if not cfg.pool_enabled: return None - from fovi.sensing.coords import SamplingCoords - - fov, cmf_a = sampling_geometry(cfg) - # pool_res_mult is a float to support fractional ratios (e.g. sqrt(2) for # a 2× N_hi/N_lo ratio). SamplingCoords requires an integer radial res. - highres_res = int(round(cfg.pool_res_mult * matched_res)) - return SamplingCoords( - fov=fov, - cmf_a=cmf_a, - res=highres_res, - device=device, - style=cfg.foveated_style, - isotropic_plotting_type=cfg.isotropic_plotting_type, - fov_type=cfg.fov_type, - radius_norm=cfg.radius_norm, - field_geometry="spherical", - ) + return lowres.clone(resolution=int(round(cfg.pool_res_mult * matched_res))) def build_pooler( @@ -119,9 +102,6 @@ def build_pooler( """ if highres is None: return None, None - - from fovi.arch.pooling import build_retinal_pooler - return build_retinal_pooler( highres, lowres, @@ -145,9 +125,6 @@ def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer) -> padding, stride and masks as the pooler), ordered by distance from the window centre and then in row-major window order. """ - from fovi.arch.knn import KNNPoolingLayer - from fovi.arch.pooling import GridPoolingLayer - if isinstance(pooler, KNNPoolingLayer): return pooler.knn_indices_pad_token if not isinstance(pooler, GridPoolingLayer): diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py index c118bd709795..2bca02876392 100644 --- a/source/isaaclab_fovi/test/test_camera_cfg.py +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -13,6 +13,7 @@ from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg from isaaclab.sim import ( + CuboidCfg, FisheyeCameraCfg, OpenCvFisheyeDistortionCfg, OpenCvPinholeDistortionCfg, @@ -104,6 +105,7 @@ def test_explicit_camera_model_wins_over_the_spawn() -> None: ("spawn", "message"), [ (None, "camera_model"), + (CuboidCfg(size=(1.0, 1.0, 1.0)), "does not spawn a camera"), (FisheyeCameraCfg(), "OpenCvFisheyeDistortionCfg"), (PinholeCameraCfg(horizontal_aperture_offset=1.0), "Aperture offsets"), ( diff --git a/source/isaaclab_fovi/test/test_lens_lut.py b/source/isaaclab_fovi/test/test_lens_lut.py index cb9549b263d2..c242af2387f3 100644 --- a/source/isaaclab_fovi/test/test_lens_lut.py +++ b/source/isaaclab_fovi/test/test_lens_lut.py @@ -35,3 +35,16 @@ def test_exit_texture_marks_rays_outside_the_field_invalid(): # The octahedral centre is the optical axis, which reaches the axis sample. centre = exit_texture[exit_texture.shape[0] // 2, exit_texture.shape[1] // 2, :2] torch.testing.assert_close(centre, uv[0]) + + +def test_direction_texture_places_each_sample_by_its_uv(): + """A sample set with one sample per texel, in shuffled order, puts each sample's ray at its own texel.""" + size = 4 + axis = (torch.arange(size) + 0.5) / size + row, col = torch.meshgrid(axis, axis, indexing="ij") + centres = torch.stack((col, row), -1).reshape(-1, 2) + order = torch.randperm(size * size, generator=torch.Generator().manual_seed(0)) + directions = torch.nn.functional.normalize(torch.randn(size * size, 3, generator=torch.Generator().manual_seed(1))) + direction_texture, _ = build_lut_textures(centres[order], directions, size, size, 16, 16, device="cpu") + texels = (centres[order] * size).long() + torch.testing.assert_close(direction_texture[texels[:, 1], texels[:, 0]], directions) diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py index 3496c467f45d..35f2f16ca61d 100644 --- a/source/isaaclab_fovi/test/test_newton_buffers.py +++ b/source/isaaclab_fovi/test/test_newton_buffers.py @@ -337,6 +337,10 @@ def render(camera, env_mask): rgb, rgba = camera._data.output["rgb"].torch, camera._data.output["rgba"].torch assert rgb.any() torch.testing.assert_close(rgb, rgba[..., :3], rtol=0, atol=0) + # rgb is a view of rgba, not a copy: a write to rgba shows through it. + assert rgb.data_ptr() == rgba.data_ptr() + rgba[..., 0] = 7 + assert bool((rgb[..., 0] == 7).all()) def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch) -> None: diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 5667c2021fa3..5934e7ef85ab 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -49,7 +49,7 @@ def pooling_cfg(**overrides) -> FoveatedCameraCfg: def test_dual_grid_preserves_constant_channels_and_batch_order() -> None: cfg = pooling_cfg() lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") + highres = build_highres_coords(cfg, lowres, matched) assert highres is not None assert len(highres) > len(lowres) assert highres.cmf_a == lowres.cmf_a @@ -91,7 +91,7 @@ def test_pooling_mode_reduces_each_neighbourhood(mode: str) -> None: sigma = 0.5 cfg = pooling_cfg(pool_mode=mode, pool_gauss_sigma=sigma) lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") + highres = build_highres_coords(cfg, lowres, matched) pooler, _ = build_pooler(cfg, lowres, highres, "cpu") assert isinstance(pooler, KNNPoolingLayer) values = torch.rand(2, len(highres), 1, 3, generator=torch.Generator().manual_seed(0)) @@ -107,7 +107,7 @@ def test_pooling_mode_reduces_each_neighbourhood(mode: str) -> None: def test_disabled_pooling_uses_only_output_grid() -> None: cfg = pooling_cfg(pool_enabled=False) lowres, matched = build_lowres_coords(cfg, "cpu") - assert build_highres_coords(cfg, matched, "cpu") is None + assert build_highres_coords(cfg, lowres, matched) is None assert build_pooler(cfg, lowres, None, "cpu") == (None, None) @@ -187,7 +187,7 @@ def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Ten def test_modal_pooling_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex: bool) -> None: cfg = pooling_cfg(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex) lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") + highres = build_highres_coords(cfg, lowres, matched) fovi_max, k = build_pooler(replace(cfg, pool_mode="max"), lowres, highres, "cpu") # The camera takes the table from its standard pooler, whatever that pooler's mode. standard, _ = build_pooler(cfg, lowres, highres, "cpu") @@ -212,7 +212,7 @@ def test_modal_pooling_uses_fovi_neighbourhoods(monkeypatch, style: str, pool_k: def test_modal_neighbourhoods_stay_on_the_sensor_device(device: str) -> None: cfg = pooling_cfg() lowres, matched = build_lowres_coords(cfg, device) - highres = build_highres_coords(cfg, matched, device) + highres = build_highres_coords(cfg, lowres, matched) table = segmentation_neighbor_indices(build_pooler(cfg, lowres, highres, device)[0]) assert table.device == torch.device(device) labels = torch.randint(0, 3, (1, len(highres), 1, 1), device=device) @@ -239,7 +239,7 @@ def test_native_grid_pooling_excludes_invalid_photoreceptors(mode, style, sample pool_k=9 if style.endswith("_as_grid") else 3, ) lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") + highres = build_highres_coords(cfg, lowres, matched) assert highres is not None pooler, _ = build_pooler(cfg, lowres, highres, "cpu") values = torch.ones(1, len(highres), 1, 1) @@ -264,7 +264,7 @@ def test_native_grid_default_kernel_matches_deployment(style: str, expected: typ pool_sample_cortex=True, ) lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") + highres = build_highres_coords(cfg, lowres, matched) pooler, resolved_k = build_pooler(cfg, lowres, highres, "cpu") assert resolved_k == 4 assert isinstance(pooler, expected) diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index a06ab3289505..c424f51b49f4 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -24,6 +24,7 @@ from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.math import ( convert_camera_frame_orientation_convention, + create_rotation_matrix_from_view, matrix_from_quat, quat_apply, quat_from_matrix, @@ -94,6 +95,7 @@ def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None: setattr(self.cfg, name, value) self._view = SimpleNamespace(count=count) self._device = device + self._ALL_INDICES = wp.array(list(range(count)), dtype=wp.int32, device=device) self._sampling_coords, _ = build_lowres_coords(self.cfg, device) self._sampling_coords_highres = None # The camera's own pose buffers, at the identity orientation, with their world-to-ROS conversion. @@ -142,7 +144,6 @@ class RtxGazeHarness(GazeHarness, FoveatedRTXCamera): def __init__(self, mount_opengl: torch.Tensor) -> None: super().__init__(count=len(mount_opengl)) self._view = PrimView(mount_opengl) - self._ALL_INDICES = wp.array(list(range(len(mount_opengl))), dtype=wp.int32, device="cpu") self._base_local_orientation = matrix_from_quat(mount_opengl) self.mount_turns = 0 @@ -151,6 +152,15 @@ def __init__(self, mount_opengl: torch.Tensor) -> None: """Two cameras' mount orientations (x, y, z, w), OpenGL convention, for the prim-writing harness.""" +def write_view(camera, eyes, targets, env_ids=None): + """Stand-in for the stock look-at write on :class:`RtxGazeHarness`: each row whose eye differs from its target + looks at it; the others keep their poses.""" + rotation = create_rotation_matrix_from_view(eyes, targets, "Z") + looks = ~torch.isnan(rotation).any(dim=(-2, -1)) + ids = camera._env_indices(env_ids)[looks] + camera._view.local[ids] = quat_from_matrix(rotation[looks]) + + def write_prims(camera, positions=None, orientations=None, env_ids=None, convention="ros"): """Stand-in for the stock pose write on :class:`RtxGazeHarness`: the orientations become the prims' poses.""" if orientations is not None: @@ -193,7 +203,14 @@ def test_gaze_away_from_sensor_masks_all_rays() -> None: @pytest.mark.parametrize("device", CPU_AND_CUDA) @pytest.mark.parametrize( "mode, autocast", - [("spherical", False), ("spherical", True), ("spherical_ids", False), ("spherical_mask", False)], + [ + ("spherical", False), + ("spherical", True), + ("spherical_ids", False), + ("spherical_warp_ids", False), + ("spherical_slice", False), + ("spherical_mask", False), + ], ) def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, mode: str, tf32_enabled) -> None: batch_size = 48 @@ -216,11 +233,16 @@ def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, m with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast): if mode == "spherical_ids": camera._apply_gaze_pose(torch.nonzero(selected).flatten()) + elif mode == "spherical_warp_ids": + # An int64 Warp selector, which the kernel's int32 indices must not reinterpret. + camera._apply_gaze_pose(wp.from_torch(torch.nonzero(selected).flatten(), dtype=wp.int64)) + elif mode == "spherical_slice": + camera._apply_gaze_pose(slice(0, None, 2)) elif mode == "spherical_mask": camera._apply_gaze_pose(env_mask=wp.from_torch(selected)) else: camera._apply_gaze_pose() - if mode in ("spherical_ids", "spherical_mask"): + if mode != "spherical": torch.testing.assert_close(source[~selected], original[~selected], atol=0, rtol=0) source = source[selected] expected = expected[selected] @@ -258,8 +280,15 @@ def test_only_a_turned_mount_is_recorded(monkeypatch) -> None: """The fixed-mount teacher reads the live camera position, so only writes that turn a mount count: not a position move, and not writing back the reported mount (of either quaternion sign), even with a gaze held in the prims.""" monkeypatch.setattr(Camera, "set_world_poses", write_prims) - monkeypatch.setattr(Camera, "set_world_poses_from_view", lambda *args, **kwargs: None) + monkeypatch.setattr(Camera, "set_world_poses_from_view", write_view) eyes = torch.zeros(2, 3) + targets = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) + + def view_twice(camera): + # Looking again from the same eye at the same target leaves the mount where the first view put it. + camera.set_world_poses_from_view(eyes, targets) + camera.mount_turns = 0 + camera.set_world_poses_from_view(eyes, targets) def reported(camera, env_ids=None): return camera.get_world_poses(env_ids, convention="ros")[1] @@ -276,7 +305,8 @@ def turn_second(camera): (lambda camera: camera.set_world_poses(orientations=-reported(camera, [1]), env_ids=[1]), False), (turn_second, True), (lambda camera: camera.set_world_poses_from_view(eyes, eyes), False), - (lambda camera: camera.set_world_poses_from_view(eyes, torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])), True), + (lambda camera: camera.set_world_poses_from_view(eyes, targets), True), + (view_twice, False), ): camera = RtxGazeHarness(MOUNT) camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) diff --git a/source/isaaclab_fovi/test/test_square_native_grid.py b/source/isaaclab_fovi/test/test_square_native_grid.py index 71e6f90aeb7a..ad4b7de2e219 100644 --- a/source/isaaclab_fovi/test/test_square_native_grid.py +++ b/source/isaaclab_fovi/test/test_square_native_grid.py @@ -183,7 +183,7 @@ def test_camera_pooling_preserves_square_shells(coverage: str) -> None: pool_res_mult=2.0, ) lowres, matched = build_lowres_coords(cfg, "cpu") - highres = build_highres_coords(cfg, matched, "cpu") + highres = build_highres_coords(cfg, lowres, matched) assert lowres.radius_norm == highres.radius_norm == math.inf for coords in (lowres, highres): assert coords.fov_type == coverage From ca7916ccf9e49acd5893d717d39869dddcdc41a5 Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Thu, 19 Nov 2026 16:25:45 -0800 Subject: [PATCH 51/81] Simplify foveated camera and gaze config validation --- .../isaaclab_fovi/mdp/gaze_cfg.py | 11 +++----- .../sensors/foveated_camera_cfg.py | 26 +++++++------------ source/isaaclab_fovi/test/test_active_gaze.py | 8 +++++- 3 files changed, 19 insertions(+), 26 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py index 0318605a11fc..1d8b75373902 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py @@ -36,13 +36,8 @@ class GazeActionCfg(ActionTermCfg): def validate_config(self): """Reject gaze bounds that would divide by zero and unknown mounts.""" - if not _positive_finite(self.step_size): - raise ValueError(f"GazeActionCfg.step_size must be positive and finite, got {self.step_size!r}.") - if not _positive_finite(self.gaze_limit): - raise ValueError(f"GazeActionCfg.gaze_limit must be positive and finite, got {self.gaze_limit!r}.") + for name, value in (("step_size", self.step_size), ("gaze_limit", self.gaze_limit)): + if not (isinstance(value, (int, float)) and math.isfinite(value) and value > 0): + raise ValueError(f"GazeActionCfg.{name} must be positive and finite, got {value!r}.") if self.mount not in ("fixed", "tracked"): raise ValueError(f"GazeActionCfg.mount must be 'fixed' or 'tracked', got {self.mount!r}.") - - -def _positive_finite(value) -> bool: - return isinstance(value, (int, float)) and math.isfinite(value) and value > 0 diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index c4039eabcee6..9f1db703ac50 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -23,19 +23,6 @@ POOL_MODES = ("avg", "gaussian", "max", "sum") """fovi pooling modes for the outputs other than segmentation.""" -SEGMENTATION_POOL_MODES = ("modal",) -"""Pooling modes for segmentation outputs: the modal label only.""" - - -def validate_radius_norm(radius_norm: float, style: str, fov_type: str) -> None: - """Reject warped-grid radius norms that fovi cannot sample, before renderer startup.""" - if radius_norm not in RADIUS_NORMS: - raise ValueError(f"radius_norm must be one of {RADIUS_NORMS}, got {radius_norm!r}.") - if radius_norm != 2.0 and style not in WARPED_CARTESIAN_STYLES: - raise ValueError("Non-default radius_norm requires a warped_cartesian style.") - if radius_norm == math.inf and fov_type == "wang": - raise ValueError("radius_norm=inf does not support fov_type='wang'.") - @configclass class FoveatedCameraCfg(CameraCfg): @@ -118,15 +105,20 @@ class FoveatedCameraCfg(CameraCfg): """Update the camera pose every frame. Newton and OVRTX require it: their pose update applies the gaze.""" def __post_init__(self): - # Resolves the default renderer and forwards deprecated renderer fields. super().__post_init__() - validate_radius_norm(self.radius_norm, self.foveated_style, self.fov_type) + # Reject incompatible geometry before the renderer creates the retina. + if self.radius_norm not in RADIUS_NORMS: + raise ValueError(f"radius_norm must be one of {RADIUS_NORMS}, got {self.radius_norm!r}.") + if self.radius_norm != 2.0 and self.foveated_style not in WARPED_CARTESIAN_STYLES: + raise ValueError("Non-default radius_norm requires a warped_cartesian style.") + if self.radius_norm == math.inf and self.fov_type == "wang": + raise ValueError("radius_norm=inf does not support fov_type='wang'.") if self.pool_mode not in POOL_MODES: raise ValueError( f"pool_mode must be one of {POOL_MODES}, got {self.pool_mode!r}; segmentation pools with pool_int_mode." ) - if self.pool_int_mode not in SEGMENTATION_POOL_MODES: + if self.pool_int_mode not in ("modal",): raise ValueError( - f"pool_int_mode must be one of {SEGMENTATION_POOL_MODES}, got {self.pool_int_mode!r}: segmentation" + f"pool_int_mode must be one of ('modal',), got {self.pool_int_mode!r}: segmentation" " pools by modal label, since other modes would mix labels into ones no object has." ) diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 001403d620f1..3077bf89c68a 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -203,7 +203,13 @@ def test_teacher_gaze_fixates_the_target_through_a_rolled_mount(): def test_gaze_config_rejects_bounds_that_divide_by_zero_and_unknown_mounts(): GazeActionCfg(asset_name="camera").validate_config() GazeActionCfg(asset_name="camera", mount="tracked").validate_config() - for field, value in (("step_size", 0.0), ("step_size", float("nan")), ("gaze_limit", math.inf), ("mount", "head")): + for field, value in ( + ("step_size", 0.0), + ("step_size", float("nan")), + ("gaze_limit", math.inf), + ("gaze_limit", "1.0"), + ("mount", "head"), + ): cfg = GazeActionCfg(asset_name="camera") setattr(cfg, field, value) with pytest.raises(ValueError, match=field): From dcde5d048ea8ab199f539f8914b5d1dc3a67ba11 Mon Sep 17 00:00:00 2001 From: nblauch Date: Wed, 18 Nov 2026 16:29:20 -0800 Subject: [PATCH 52/81] Read the Isaac RTX mount after a gaze and reduce the motor penalty once - ungazed_quat_w_ros reads an Isaac RTX camera's mount through get_world_poses once a gaze is in its prims, so a fixed-mount gaze action created after a gaze captures the real mount instead of raising. - motor_action_l2 reduces only the actions before the gaze, and requires the gaze to be the last action term. --- .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 10 +++++++-- .../isaaclab_fovi/sensors/foveated_camera.py | 12 ++++------ source/isaaclab_fovi/test/test_active_gaze.py | 15 +++++++++++++ .../test/test_spherical_geometry.py | 22 +++++++++---------- 4 files changed, 38 insertions(+), 21 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 6502ea7537c6..bbefc7090656 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -186,9 +186,15 @@ def motor_action_l2(env: ManagerBasedRLEnv, gaze_action_name: str = "gaze") -> t """Squared L2 norm of the actions other than the gaze, shape (num_envs,). Matches :func:`isaaclab.envs.mdp.action_l2` on the task's own actions, so moving the gaze costs nothing. + + Raises: + ValueError: The gaze is not the last action term. """ - gaze = env.action_manager.get_term(gaze_action_name).raw_actions - return env.action_manager.action.square().sum(-1) - gaze.square().sum(-1) + manager = env.action_manager + if manager.active_terms[-1] != gaze_action_name: + raise ValueError(f"The gaze action term {gaze_action_name!r} must be the last action term.") + # One reduction over the actions before the gaze. + return manager.action[:, : manager.total_action_dim - manager.action_term_dim[-1]].square().sum(-1) class GazeAction(ActionTerm): diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 51c4733ae623..cda08977f9e6 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -228,17 +228,13 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: def ungazed_quat_w_ros(self) -> torch.Tensor: """World orientation (x, y, z, w) of the physical camera now, before the gaze turns it, ROS convention, shape - (num_envs, 4). - - Raises: - RuntimeError: A gaze is set on a camera that writes it into its prims (Isaac RTX), so the current pose - includes it. - """ + (num_envs, 4).""" if self._gaze_pose_reads_angles and self._gaze_angles is not None: # The record starts at the pose before any gaze and follows each pose update. return self._mount_quat_ros.torch.clone() - if self._gaze_written and not self._gaze_pose_reads_angles: - raise RuntimeError("The camera's prims already hold a gaze; read its mount before setting one.") + if self._gaze_written: + # The prims hold the gaze (Isaac RTX); get_world_poses reports the mount without it. + return self.get_world_poses(convention="ros")[1] return self._data.quat_w_ros.torch.clone() def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"): diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 03d2382c9d2c..a896a797bb87 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -19,6 +19,7 @@ gaze_reset_kernel, gaze_state, gaze_step_kernel, + motor_action_l2, teacher_block_dim, teacher_labels_kernel, ) @@ -32,6 +33,7 @@ from rsl_rl.storage import RolloutStorage from tensordict import TensorDict +from isaaclab.envs.mdp.rewards import action_l2 from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.math import quat_apply, quat_apply_inverse from isaaclab.utils.warp import ProxyArray @@ -325,6 +327,19 @@ def test_fixed_mount_teacher_rejects_only_turns_after_capture(): GazeAction.teacher_mounts(term) +def test_motor_penalty_is_the_action_l2_of_the_actions_before_the_gaze(): + actions = torch.tensor([[1.0, -2.0, 0.5, 0.9, -0.7], [0.0, 3.0, -1.0, 0.1, 0.2]]) + + def env(terms: list[str], dims: list[int]) -> SimpleNamespace: + manager = SimpleNamespace(active_terms=terms, action_term_dim=dims, total_action_dim=sum(dims), action=actions) + return SimpleNamespace(action_manager=manager) + + expected = action_l2(SimpleNamespace(action_manager=SimpleNamespace(action=actions[:, :3]))) + torch.testing.assert_close(motor_action_l2(env(["joints", "gaze"], [3, 2])), expected) + with pytest.raises(ValueError, match="last action term"): + motor_action_l2(env(["gaze", "joints"], [2, 3])) + + def test_gaze_loss_ignores_invalid_labels(): mean = torch.tensor([[0.0, 0.0], [1.0, 1.0]], requires_grad=True) labels = torch.tensor([[0.3, 0.4, 1.0], [float("nan"), float("nan"), 0.0]]) diff --git a/source/isaaclab_fovi/test/test_spherical_geometry.py b/source/isaaclab_fovi/test/test_spherical_geometry.py index c424f51b49f4..903583932cd3 100644 --- a/source/isaaclab_fovi/test/test_spherical_geometry.py +++ b/source/isaaclab_fovi/test/test_spherical_geometry.py @@ -347,17 +347,17 @@ def test_mount_record_starts_at_the_current_pose() -> None: ) -def test_prim_writing_camera_reads_its_mount_until_a_gaze_is_written() -> None: - """Isaac RTX writes the gaze into its prims, so its pose is the mount only until the first gaze.""" - camera = GazeHarness() - camera.gaze_angles - expected = convert_camera_frame_orientation_convention(camera.orientation, "world", "ros") - torch.testing.assert_close( - matrix_from_quat(camera.ungazed_quat_w_ros()), matrix_from_quat(expected), atol=1e-6, rtol=0 - ) - camera.set_gaze_angles(torch.zeros(2, 2)) - with pytest.raises(RuntimeError, match="already hold a gaze"): - camera.ungazed_quat_w_ros() +def test_prim_writing_camera_reads_its_mount_before_and_after_a_gaze() -> None: + """Isaac RTX writes the gaze into its prims; its mount reads the same before and after a gaze is set, so a + fixed-mount teacher created after a gaze aims from the real mount.""" + camera = RtxGazeHarness(MOUNT) + # The last pose update read the bare mount. + camera.orientation.copy_(convert_camera_frame_orientation_convention(MOUNT, "opengl", "world")) + expected = matrix_from_quat(convert_camera_frame_orientation_convention(MOUNT, "opengl", "ros")) + torch.testing.assert_close(matrix_from_quat(camera.ungazed_quat_w_ros()), expected, atol=1e-6, rtol=0) + camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]])) + assert not torch.allclose(matrix_from_quat(camera._view.local), matrix_from_quat(MOUNT), atol=1e-3) + torch.testing.assert_close(matrix_from_quat(camera.ungazed_quat_w_ros()), expected, atol=1e-6, rtol=0) def test_sensor_mask_reuses_its_buffer_and_keeps_rows_that_were_not_updated() -> None: From bd040213df66ba16dcc3ce3debcf4dc7a00c82fa Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Thu, 19 Nov 2026 17:17:59 -0800 Subject: [PATCH 53/81] Inline physical camera calibration selection --- .../sensors/calibrated_geometry.py | 22 +-------------- .../isaaclab_fovi/sensors/foveated_camera.py | 9 +++++-- source/isaaclab_fovi/test/test_camera_cfg.py | 27 ++++++++++--------- source/isaaclab_fovi/test/test_pooling.py | 18 ++++++------- 4 files changed, 31 insertions(+), 45 deletions(-) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py index 395ce83ff92f..8dfa0d0ddc3b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py @@ -8,16 +8,12 @@ from __future__ import annotations import math -from typing import TYPE_CHECKING import torch -from fovi.sensing.projection import CameraCalibration, CameraModel, angular_directions +from fovi.sensing.projection import CameraCalibration, angular_directions from isaaclab.sim import PinholeCameraCfg -if TYPE_CHECKING: - from .foveated_camera_cfg import FoveatedCameraCfg - IDEAL_IMAGE_WIDTH = 1024 """Pixel width [px] of the image assigned to a camera derived from ideal spawn optics. @@ -82,22 +78,6 @@ def camera_model_from_spawn(spawn: PinholeCameraCfg) -> CameraCalibration: ) -def resolve_camera_model(cfg: FoveatedCameraCfg) -> CameraModel: - """Return the physical camera the retina looks through. - - This is ``cfg.camera_model`` when set, otherwise the camera that ``cfg.spawn`` - creates (see :func:`camera_model_from_spawn`). - - Raises: - ValueError: Neither ``cfg.camera_model`` nor ``cfg.spawn`` describes the camera. - """ - if cfg.camera_model is not None: - return CameraModel(**cfg.camera_model) - if cfg.spawn is None: - raise ValueError("A foveated camera on an existing prim needs camera_model.") - return CameraModel(**camera_model_from_spawn(cfg.spawn)) - - def retinal_directions(cartesian: torch.Tensor, fov_deg: float, image_rotation_deg: float = 0.0) -> torch.Tensor: """Return OpenGL-frame angular rays, including the sensor mount roll.""" rays = angular_directions(cartesian, fov_deg) diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 5f0524baec98..813560db7352 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -20,7 +20,7 @@ from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_error_magnitude from isaaclab.utils.warp import ProxyArray -from .calibrated_geometry import resolve_camera_model, retinal_directions +from .calibrated_geometry import camera_model_from_spawn, retinal_directions from .gaze_kernels import ( CameraParams, apply_gaze_indexed_kernel, @@ -283,7 +283,12 @@ def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): def _prepare_sampling(self) -> None: """Resolve physical calibration and retinal coordinates before the renderer sizes its buffers.""" - self._camera_model = resolve_camera_model(self.cfg) + calibration = self.cfg.camera_model + if calibration is None: + if self.cfg.spawn is None: + raise ValueError("A foveated camera on an existing prim needs camera_model.") + calibration = camera_model_from_spawn(self.cfg.spawn) + self._camera_model = CameraModel(**calibration) self._sampling_coords, self._sampling_coords_highres = build_retinal_coords(self.cfg, self._camera_model, "cpu") self._ray_coords = self._sampling_coords_highres or self._sampling_coords self._native_grid = self.cfg.foveated_style == GRID_STYLE diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py index 7827c7bf68e8..16b4ea76297a 100644 --- a/source/isaaclab_fovi/test/test_camera_cfg.py +++ b/source/isaaclab_fovi/test/test_camera_cfg.py @@ -10,11 +10,13 @@ import subprocess import sys from dataclasses import dataclass +from types import SimpleNamespace import pytest import torch +from fovi.sensing.projection import CameraModel from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg -from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model +from isaaclab_fovi.sensors.calibrated_geometry import camera_model_from_spawn from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_newton.renderers import NewtonWarpRendererCfg @@ -56,14 +58,14 @@ def test_defaults_are_grid_sampling_at_the_human_cmf_estimate() -> None: def test_pinhole_spawn_describes_an_ideal_pinhole_across_its_short_side() -> None: spawn = PinholeCameraCfg() expected = math.degrees(2 * math.atan(spawn.horizontal_aperture / (2 * spawn.focal_length))) - camera = resolve_camera_model(make_cfg(spawn=spawn)) + camera = CameraModel(**camera_model_from_spawn(spawn)) assert camera.field_of_view("short") == pytest.approx(expected, rel=1e-6) assert camera.model == "pinhole" assert camera.distortion == () # Without a vertical aperture the image is square; with one, the retina spans the short (vertical) side. assert camera.image_size[0] == camera.image_size[1] spawn = PinholeCameraCfg(focal_length=10.0, horizontal_aperture=20.0, vertical_aperture=10.0) - camera = resolve_camera_model(make_cfg(spawn=spawn)) + camera = CameraModel(**camera_model_from_spawn(spawn)) assert camera.field_of_view("short") == pytest.approx(math.degrees(2 * math.atan(0.5)), rel=1e-6) @@ -71,7 +73,7 @@ def test_opencv_pinhole_spawn_gives_that_calibrated_camera() -> None: distortion = OpenCvPinholeDistortionCfg( fx=500.0, fy=510.0, cx=320.0, cy=240.0, image_size=(640, 480), k1=-0.1, k2=0.01, p1=0.001, k4=0.002 ) - camera = resolve_camera_model(make_cfg(spawn=PinholeCameraCfg(distortion=distortion))) + camera = CameraModel(**camera_model_from_spawn(PinholeCameraCfg(distortion=distortion))) assert camera.model == "pinhole" # Isaac Lab sizes are (width, height); fovi's are (height, width). assert camera.image_size == (480, 640) @@ -79,15 +81,14 @@ def test_opencv_pinhole_spawn_gives_that_calibrated_camera() -> None: assert camera.distortion == (-0.1, 0.01, 0.001, 0.0, 0.0, 0.002, 0.0, 0.0) distortion.apply_lens_distortion = False - assert resolve_camera_model(make_cfg(spawn=PinholeCameraCfg(distortion=distortion))).distortion == () + assert CameraModel(**camera_model_from_spawn(PinholeCameraCfg(distortion=distortion))).distortion == () def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> None: # The image edge is 320 / 250 rad (73 deg) off axis, inside the default 180 deg lens. focal = 250.0 distortion = OpenCvFisheyeDistortionCfg(fx=focal, fy=focal, cx=319.5, cy=319.5, image_size=(640, 640)) - cfg = make_cfg(spawn=PinholeCameraCfg(distortion=distortion)) - camera = resolve_camera_model(cfg) + camera = CameraModel(**camera_model_from_spawn(PinholeCameraCfg(distortion=distortion))) assert camera.model == "fisheye" assert camera.distortion == () assert camera.max_angle_deg == pytest.approx(90.0) @@ -98,23 +99,23 @@ def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> No def test_explicit_camera_model_wins_over_the_spawn() -> None: - cfg = make_cfg(spawn=PinholeCameraCfg(), camera_model=CAMERA_MODEL) - assert resolve_camera_model(cfg).intrinsics == CAMERA_MODEL["intrinsics"] - # A prim without spawn configuration needs a camera model. - assert resolve_camera_model(make_cfg(spawn=None, camera_model=CAMERA_MODEL)).image_size == (480, 640) + for spawn in (PinholeCameraCfg(), None): + camera = SimpleNamespace(cfg=make_cfg(spawn=spawn, camera_model=CAMERA_MODEL, foveated_res=8)) + FoveatedCamera._prepare_sampling(camera) + assert camera._camera_model == CameraModel(**CAMERA_MODEL) def test_cameras_fovi_cannot_model_are_rejected() -> None: thin_prism = OpenCvPinholeDistortionCfg(fx=1.0, fy=1.0, cx=1.0, cy=1.0, image_size=(4, 4), s1=0.1) for spawn, message in ( - (None, "camera_model"), + (None, "existing prim needs camera_model"), (CuboidCfg(size=(1.0, 1.0, 1.0)), "does not spawn a camera"), (FisheyeCameraCfg(), "OpenCvFisheyeDistortionCfg"), (PinholeCameraCfg(horizontal_aperture_offset=1.0), "Aperture offsets"), (PinholeCameraCfg(distortion=thin_prism), "Thin-prism"), ): with pytest.raises(ValueError, match=message): - resolve_camera_model(make_cfg(spawn=spawn)) + FoveatedCamera._prepare_sampling(SimpleNamespace(cfg=make_cfg(spawn=spawn))) def test_config_validates_pooling_and_shell_settings() -> None: diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py index 8db3b69c12b4..f591dc130682 100644 --- a/source/isaaclab_fovi/test/test_pooling.py +++ b/source/isaaclab_fovi/test/test_pooling.py @@ -10,8 +10,8 @@ import pytest import torch +from fovi.sensing.projection import CameraModel from isaaclab_fovi.sensors import FoveatedCameraCfg, pooling -from isaaclab_fovi.sensors.calibrated_geometry import resolve_camera_model from isaaclab_fovi.sensors.pooling import ( build_pooler, build_retinal_coords, @@ -20,7 +20,6 @@ segmentation_neighbor_indices, ) -from isaaclab.sim import PinholeCameraCfg from isaaclab.test.utils import DeviceScope, test_devices pytestmark = pytest.mark.kitless @@ -28,16 +27,17 @@ DEVICE = next(iter(test_devices(DeviceScope.DEFAULT_CUDA)), "cpu") """The modal pooling runs the same tensor operations on every device; the default GPU is what simulations use.""" +CAMERA_MODEL = CameraModel("pinhole", (1024, 1024), (512.0, 512.0, 511.5, 511.5)) + def pooling_cfg(**overrides) -> FoveatedCameraCfg: """A pooled foveated camera configuration for the pooling helpers, with ``overrides`` applied. - A 90 degree pinhole window (focal length 1, aperture 2) with a CMF constant of a tenth of it, and a small isotropic - retina pooled from three visual-field neighbours. + A CMF constant of a tenth of the 90 degree pinhole window, and a small isotropic retina pooled from three + visual-field neighbours. """ values = dict( prim_path="/World/Camera", - spawn=PinholeCameraCfg(focal_length=1.0, horizontal_aperture=2.0), cmf_a_deg=9.0, foveated_res=8, foveated_style="isotropic", @@ -50,7 +50,7 @@ def pooling_cfg(**overrides) -> FoveatedCameraCfg: def test_camera_pools_its_buffers_by_its_config() -> None: cfg = pooling_cfg(pool_mode="max") - lowres, highres = build_retinal_coords(cfg, resolve_camera_model(cfg), "cpu") + lowres, highres = build_retinal_coords(cfg, CAMERA_MODEL, "cpu") # The photoreceptor grid shares the retina's geometry at a higher resolution, and the pooler takes the config. assert len(highres) > len(lowres) and highres.cmf_a == lowres.cmf_a and highres.fov == lowres.fov pooler, neighbors = build_pooler(cfg, lowres, highres, "cpu") @@ -63,7 +63,7 @@ def test_camera_pools_its_buffers_by_its_config() -> None: torch.testing.assert_close(actual, constants[:, None, None, :].expand(2, len(lowres), 1, 3)) # Without pooling there is no photoreceptor grid. cfg = pooling_cfg(pool_enabled=False) - _, highres = build_retinal_coords(cfg, resolve_camera_model(cfg), "cpu") + _, highres = build_retinal_coords(cfg, CAMERA_MODEL, "cpu") assert highres is None @@ -123,7 +123,7 @@ def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Ten def test_modal_pooling_uses_the_poolers_neighbourhoods(monkeypatch, style: str, pool_k: int, sample_cortex) -> None: """Segmentation pools over the same neighbourhoods as the camera's other outputs: grid windows or KNN.""" cfg = pooling_cfg(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex, pool_mode="max") - lowres, highres = build_retinal_coords(cfg, resolve_camera_model(cfg), "cpu") + lowres, highres = build_retinal_coords(cfg, CAMERA_MODEL, "cpu") pooler, k = build_pooler(cfg, lowres, highres, "cpu") table = segmentation_neighbor_indices(pooler) assert table.shape == (k, len(lowres)) @@ -142,7 +142,7 @@ def test_modal_pooling_uses_the_poolers_neighbourhoods(monkeypatch, style: str, @pytest.mark.parametrize(("style", "pool_k", "mode"), [("warped_cartesian_as_grid", 9, "avg"), ("isotropic", 6, "max")]) def test_pooling_leaves_out_photoreceptors_the_camera_does_not_see(style: str, pool_k: int, mode: str) -> None: cfg = pooling_cfg(foveated_style=style, pool_mode=mode, pool_k=pool_k) - lowres, highres = build_retinal_coords(cfg, resolve_camera_model(cfg), DEVICE) + lowres, highres = build_retinal_coords(cfg, CAMERA_MODEL, DEVICE) pooler, _ = build_pooler(cfg, lowres, highres, DEVICE) # The camera's image edge cuts the retina at x = 0.3 in the first environment; the second sees everything. visible = torch.stack([highres.cartesian[:, 0] < 0.3, torch.ones(len(highres), dtype=torch.bool, device=DEVICE)]) From d15eb26c69f70e18377991293103a3c2048859f9 Mon Sep 17 00:00:00 2001 From: nblauch Date: Thu, 19 Nov 2026 08:41:24 -0800 Subject: [PATCH 54/81] Move the foveated Cartpole task into isaaclab_tasks contrib and document the camera - isaaclab_fovi now holds only the sensors and the gaze manager terms and depends only on isaaclab. - The active-gaze Cartpole task, its gaze-supervised PPO and its gaze action head move to isaaclab_tasks.contrib.active_gaze as IsaacContrib-Cartpole-Camera-Fovi, registered when the fovi extra is installed. The other active-gaze tasks and motor_action_l2 are removed. - Without an entry point, the wheel builder change and its test are reverted. - The render example becomes the foveated-camera demo. - Document the foveated camera: a sensor concept page, a rendering section, the demo, the fovi extra in the install and troubleshooting tables, and the task in the environment browser; the package README points to them. --- docs/source/_static/css/demo-browser.js | 2 +- .../source/_static/css/environment-browser.js | 1 + docs/source/_static/demos/foveated_camera.jpg | Bin 0 -> 48983 bytes docs/source/api/index.rst | 1 - .../source/api/lab_fovi/isaaclab_fovi.mdp.rst | 6 - .../api/lab_fovi/isaaclab_fovi.rsl_rl.rst | 39 ---- docs/source/concepts/sensors/camera.rst | 2 + .../concepts/sensors/foveated_camera.rst | 153 +++++++++++++++ docs/source/concepts/sensors/index.rst | 4 + docs/source/how-to/configure_rendering.rst | 13 ++ docs/source/isaaclab/demos.rst | 23 +++ docs/source/isaaclab/installation.rst | 7 +- docs/source/refs/troubleshooting.rst | 4 + examples/demos/foveated_camera.py | 169 +++++++++++++++++ .../foveated-camera-demo.added.rst | 2 + .../changelog.d/foveated-camera-demo.minor | 0 .../wheel-bundled-entry-points.fixed.rst | 2 - source/isaaclab/isaaclab/programs.py | 7 + .../test/cli/test_wheel_builder_metadata.py | 37 ---- .../changelog.d/isaaclab-fovi.added.rst | 11 +- source/isaaclab_fovi/docs/README.md | 178 +----------------- .../isaaclab_fovi/examples/render_foveated.py | 164 ---------------- .../isaaclab_fovi/mdp/__init__.pyi | 2 - .../isaaclab_fovi/isaaclab_fovi/mdp/gaze.py | 17 +- .../isaaclab_fovi/rsl_rl/__init__.py | 14 -- .../isaaclab_fovi/rsl_rl/__init__.pyi | 11 -- .../isaaclab_fovi/tasks/__init__.py | 14 -- .../isaaclab_fovi/tasks/cartpole/__init__.py | 19 -- .../isaaclab_fovi/tasks/cartpole/agents.py | 20 -- .../tasks/kuka_allegro/__init__.py | 20 -- .../tasks/kuka_allegro/agents.py | 27 --- .../tasks/kuka_allegro/env_cfg.py | 76 -------- source/isaaclab_fovi/pyproject.toml | 9 +- source/isaaclab_fovi/test/test_active_gaze.py | 139 +------------- .../active-gaze-cartpole.added.rst | 3 + .../changelog.d/active-gaze-cartpole.minor | 0 .../contrib/active_gaze/__init__.py | 29 +++ .../contrib/active_gaze/active_gaze_cfg.py} | 8 +- .../contrib/active_gaze}/agents.py | 19 +- .../cartpole_camera_fovi_env_cfg.py} | 10 +- .../contrib/active_gaze}/gaze_distribution.py | 0 .../active_gaze}/gaze_distribution_cfg.py | 4 +- .../active_gaze}/gaze_supervised_ppo.py | 2 +- .../active_gaze}/gaze_supervised_ppo_cfg.py | 6 +- .../test/contrib/test_active_gaze_ppo.py | 135 +++++++++++++ tools/wheel_builder/gen_pyproject.py | 32 +--- uv.lock | 8 +- 47 files changed, 598 insertions(+), 851 deletions(-) create mode 100644 docs/source/_static/demos/foveated_camera.jpg delete mode 100644 docs/source/api/lab_fovi/isaaclab_fovi.rsl_rl.rst create mode 100644 docs/source/concepts/sensors/foveated_camera.rst create mode 100644 examples/demos/foveated_camera.py create mode 100644 source/isaaclab/changelog.d/foveated-camera-demo.added.rst create mode 100644 source/isaaclab/changelog.d/foveated-camera-demo.minor delete mode 100644 source/isaaclab/changelog.d/wheel-bundled-entry-points.fixed.rst delete mode 100644 source/isaaclab_fovi/examples/render_foveated.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/rsl_rl/__init__.pyi delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/__init__.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/__init__.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/cartpole/agents.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/__init__.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/agents.py delete mode 100644 source/isaaclab_fovi/isaaclab_fovi/tasks/kuka_allegro/env_cfg.py create mode 100644 source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst create mode 100644 source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor create mode 100644 source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py rename source/{isaaclab_fovi/isaaclab_fovi/tasks/active_gaze.py => isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py} (94%) rename source/{isaaclab_fovi/isaaclab_fovi/tasks => isaaclab_tasks/isaaclab_tasks/contrib/active_gaze}/agents.py (55%) rename source/{isaaclab_fovi/isaaclab_fovi/tasks/cartpole/env_cfg.py => isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py} (90%) rename source/{isaaclab_fovi/isaaclab_fovi/rsl_rl => isaaclab_tasks/isaaclab_tasks/contrib/active_gaze}/gaze_distribution.py (100%) rename source/{isaaclab_fovi/isaaclab_fovi/rsl_rl => isaaclab_tasks/isaaclab_tasks/contrib/active_gaze}/gaze_distribution_cfg.py (77%) rename source/{isaaclab_fovi/isaaclab_fovi/rsl_rl => isaaclab_tasks/isaaclab_tasks/contrib/active_gaze}/gaze_supervised_ppo.py (98%) rename source/{isaaclab_fovi/isaaclab_fovi/rsl_rl => isaaclab_tasks/isaaclab_tasks/contrib/active_gaze}/gaze_supervised_ppo_cfg.py (68%) create mode 100644 source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py diff --git a/docs/source/_static/css/demo-browser.js b/docs/source/_static/css/demo-browser.js index e8bea6389197..3d6e15878fb6 100644 --- a/docs/source/_static/css/demo-browser.js +++ b/docs/source/_static/css/demo-browser.js @@ -54,7 +54,7 @@ if (["rerun", "viser"].includes(fields.visualizer.value)) { requiredExtras.add(fields.visualizer.value); } - const extraOrder = ["isaacsim", "ovphysx", "ovrtx", "tetrahedralization", "teleop", "rerun", "viser"]; + const extraOrder = ["isaacsim", "ovphysx", "ovrtx", "tetrahedralization", "teleop", "fovi", "rerun", "viser"]; const extras = extraOrder.filter((extra) => requiredExtras.has(extra)); const parts = ["uvx"]; diff --git a/docs/source/_static/css/environment-browser.js b/docs/source/_static/css/environment-browser.js index 66bbc79dd875..f1793a6e0d33 100644 --- a/docs/source/_static/css/environment-browser.js +++ b/docs/source/_static/css/environment-browser.js @@ -69,6 +69,7 @@ ["IsaacContrib-Assemble-Trocar-G129-Dex3", "rlinf", "isaacsim_physx,newton_mjwarp", "", "", "environments/previews/manipulation/g1_assemble_trocar.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "newton_mjwarp||"]], ["IsaacContrib-AutoMate-Assembly-Direct", "rl_games", "", "", "", "environment-previews/automate_assembly.jpg"], ["IsaacContrib-AutoMate-Disassembly-Direct", "rl_games", "", "", "", "environment-previews/automate_disassembly.jpg"], + ["IsaacContrib-Cartpole-Camera-Fovi", "rsl_rl", "isaacsim_physx,newton_kamino,newton_mjwarp,newton_steel,ovphysx", "isaacsim_rtx,newton_optix,newton_warp,ovrtx", "depth,rgb", "", false, {}, {}, "", null, ["||", "||depth", "||rgb", "|isaacsim_rtx|", "|isaacsim_rtx|depth", "|isaacsim_rtx|rgb", "|newton_optix|", "|newton_optix|depth", "|newton_optix|rgb", "|newton_warp|", "|newton_warp|depth", "|newton_warp|rgb", "|ovrtx|", "|ovrtx|depth", "|ovrtx|rgb", "isaacsim_physx||", "isaacsim_physx||depth", "isaacsim_physx||rgb", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|isaacsim_rtx|depth", "isaacsim_physx|isaacsim_rtx|rgb", "isaacsim_physx|newton_optix|", "isaacsim_physx|newton_optix|depth", "isaacsim_physx|newton_optix|rgb", "isaacsim_physx|newton_warp|", "isaacsim_physx|newton_warp|depth", "isaacsim_physx|newton_warp|rgb", "newton_kamino||", "newton_kamino||depth", "newton_kamino||rgb", "newton_kamino|isaacsim_rtx|", "newton_kamino|isaacsim_rtx|depth", "newton_kamino|isaacsim_rtx|rgb", "newton_kamino|newton_optix|", "newton_kamino|newton_optix|depth", "newton_kamino|newton_optix|rgb", "newton_kamino|newton_warp|", "newton_kamino|newton_warp|depth", "newton_kamino|newton_warp|rgb", "newton_kamino|ovrtx|", "newton_kamino|ovrtx|depth", "newton_kamino|ovrtx|rgb", "newton_mjwarp||", "newton_mjwarp||depth", "newton_mjwarp||rgb", "newton_mjwarp|isaacsim_rtx|", "newton_mjwarp|isaacsim_rtx|depth", "newton_mjwarp|isaacsim_rtx|rgb", "newton_mjwarp|newton_optix|", "newton_mjwarp|newton_optix|depth", "newton_mjwarp|newton_optix|rgb", "newton_mjwarp|newton_warp|", "newton_mjwarp|newton_warp|depth", "newton_mjwarp|newton_warp|rgb", "newton_mjwarp|ovrtx|", "newton_mjwarp|ovrtx|depth", "newton_mjwarp|ovrtx|rgb", "newton_steel||", "newton_steel||depth", "newton_steel||rgb", "newton_steel|isaacsim_rtx|", "newton_steel|isaacsim_rtx|depth", "newton_steel|isaacsim_rtx|rgb", "newton_steel|newton_optix|", "newton_steel|newton_optix|depth", "newton_steel|newton_optix|rgb", "newton_steel|newton_warp|", "newton_steel|newton_warp|depth", "newton_steel|newton_warp|rgb", "newton_steel|ovrtx|", "newton_steel|ovrtx|depth", "newton_steel|ovrtx|rgb", "ovphysx||", "ovphysx||depth", "ovphysx||rgb", "ovphysx|newton_optix|", "ovphysx|newton_optix|depth", "ovphysx|newton_optix|rgb", "ovphysx|newton_warp|", "ovphysx|newton_warp|depth", "ovphysx|newton_warp|rgb", "ovphysx|ovrtx|", "ovphysx|ovrtx|depth", "ovphysx|ovrtx|rgb"]], ["IsaacContrib-Cartpole-Camera-Showcase-Direct", "skrl", "", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete"]], ["IsaacContrib-Cartpole-Showcase-Direct", "skrl", "isaacsim_physx,newton_kamino,newton_mjwarp,newton_steel,ovphysx", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,discrete_box,discrete_discrete,discrete_multidiscrete,multidiscrete_box,multidiscrete_discrete,multidiscrete_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "environment-previews/cartpole.jpg", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||discrete_box", "||discrete_discrete", "||discrete_multidiscrete", "||multidiscrete_box", "||multidiscrete_discrete", "||multidiscrete_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete", "isaacsim_physx||", "isaacsim_physx||box_box", "isaacsim_physx||box_discrete", "isaacsim_physx||box_multidiscrete", "isaacsim_physx||dict_box", "isaacsim_physx||dict_discrete", "isaacsim_physx||dict_multidiscrete", "isaacsim_physx||discrete_box", "isaacsim_physx||discrete_discrete", "isaacsim_physx||discrete_multidiscrete", "isaacsim_physx||multidiscrete_box", "isaacsim_physx||multidiscrete_discrete", "isaacsim_physx||multidiscrete_multidiscrete", "isaacsim_physx||tuple_box", "isaacsim_physx||tuple_discrete", "isaacsim_physx||tuple_multidiscrete", "newton_kamino||", "newton_kamino||box_box", "newton_kamino||box_discrete", "newton_kamino||box_multidiscrete", "newton_kamino||dict_box", "newton_kamino||dict_discrete", "newton_kamino||dict_multidiscrete", "newton_kamino||discrete_box", "newton_kamino||discrete_discrete", "newton_kamino||discrete_multidiscrete", "newton_kamino||multidiscrete_box", "newton_kamino||multidiscrete_discrete", "newton_kamino||multidiscrete_multidiscrete", "newton_kamino||tuple_box", "newton_kamino||tuple_discrete", "newton_kamino||tuple_multidiscrete", "newton_mjwarp||", "newton_mjwarp||box_box", "newton_mjwarp||box_discrete", "newton_mjwarp||box_multidiscrete", "newton_mjwarp||dict_box", "newton_mjwarp||dict_discrete", "newton_mjwarp||dict_multidiscrete", "newton_mjwarp||discrete_box", "newton_mjwarp||discrete_discrete", "newton_mjwarp||discrete_multidiscrete", "newton_mjwarp||multidiscrete_box", "newton_mjwarp||multidiscrete_discrete", "newton_mjwarp||multidiscrete_multidiscrete", "newton_mjwarp||tuple_box", "newton_mjwarp||tuple_discrete", "newton_mjwarp||tuple_multidiscrete", "newton_steel||", "newton_steel||box_box", "newton_steel||box_discrete", "newton_steel||box_multidiscrete", "newton_steel||dict_box", "newton_steel||dict_discrete", "newton_steel||dict_multidiscrete", "newton_steel||discrete_box", "newton_steel||discrete_discrete", "newton_steel||discrete_multidiscrete", "newton_steel||multidiscrete_box", "newton_steel||multidiscrete_discrete", "newton_steel||multidiscrete_multidiscrete", "newton_steel||tuple_box", "newton_steel||tuple_discrete", "newton_steel||tuple_multidiscrete", "ovphysx||", "ovphysx||box_box", "ovphysx||box_discrete", "ovphysx||box_multidiscrete", "ovphysx||dict_box", "ovphysx||dict_discrete", "ovphysx||dict_multidiscrete", "ovphysx||discrete_box", "ovphysx||discrete_discrete", "ovphysx||discrete_multidiscrete", "ovphysx||multidiscrete_box", "ovphysx||multidiscrete_discrete", "ovphysx||multidiscrete_multidiscrete", "ovphysx||tuple_box", "ovphysx||tuple_discrete", "ovphysx||tuple_multidiscrete"]], ["IsaacContrib-Deploy-GearAssembly-Rizon4s-Grav", "rsl_rl", "", "", "", "environment-previews/rizon4s_gear_assembly.jpg"], diff --git a/docs/source/_static/demos/foveated_camera.jpg b/docs/source/_static/demos/foveated_camera.jpg new file mode 100644 index 0000000000000000000000000000000000000000..de17d18a3a2717045424627ea971846310f7f80d GIT binary patch literal 48983 zcmbTd2SC%=wmup~2P=q(s0bMaMMXqKdPqhcMNnXDptOtvMrs74L!zUA(juZFH3}jk zCDMB$HS|ag5FqqW0wD>ckoJB!_nddmefPfiKQGA!5(wFA@3p`6t#7TLWI!?o+GTdx z^fG9}1`ucia0f{!po<`>jT_e=z-<%o*t}))=1rS6ZrmkLpiOd{cON=){ulY{_oNSd?K%52?&B8K3k9_bH@cS9wC{WWwRPKG#eMq^ z9673f?D&auI=XuL28I`ZzjWE;imBPnTeq#O@7%Rr_9e;U$Vaz78RG2mX%jj*3~yOHW8a!TDyCC`})ZPgG1vJ zlT*_(wAs0NCX2nY%Hi_(YwLDx07?CA7V!0N!~UCHa)4bMH*J#IB)x9ehK>HfkdoW9 z`OukPcAvj4ea}n&@Y$zZ_FRbjSWvrFRr|)W!hP?qZF|+ujUQpIoA%SP|1-n>`u}Cw zKMni8?HU5@klFxjo|GI21`>Wvk30tYw^0Kd!_qsL>YPaNpac{aJWk+UffWd`W#}wh z+dwEXaasb(kJCf6#xK#70-G+QEm2z~pjuV2Qh<^GA>OMX0SQksN&;c`L>-;+9A!Kr zQT%z9pUgGk;u#6V(Q_O4I?JSS>`T;{0IKUP29iPACj50c|7F@s-d(CI3so;jPF1HHg^;vG=3Q*PB@82!s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pKjexI3GllS3& zhR%EJI8o>fGv_G|eF>fNJdToMs?LmyNGHIC-TPOQStkZS|G}xj@6`X#>xAk?Qu?n@ z?Q0t&l?$TuyFt5YPZ|rt^+1Hdmvu38RnUnL-7m>f19pWG;ucV{07mu!FswIKVkgk~ zoOoAY3!qdY*WPavkV4b7e0r^nOf-+QKIEH$dZD{qVl#wq|W$IS%|~sihp?YAQti$U5=6m^rh+@fHv>XGeuLiNws8u3a_}t1R4gp|0in Wf9JJ>zSVy)-2b{0`P#2Pll~tG5YmVM literal 0 HcmV?d00001 diff --git a/docs/source/api/index.rst b/docs/source/api/index.rst index 13d3439f1eec..107ad3da5939 100644 --- a/docs/source/api/index.rst +++ b/docs/source/api/index.rst @@ -102,7 +102,6 @@ The following modules are available in the ``isaaclab_fovi`` extension: :toctree: lab_fovi mdp - rsl_rl sensors isaaclab_tasks extension diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst index 0be111108358..779ad564d64a 100644 --- a/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst +++ b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst @@ -16,7 +16,6 @@ isaaclab_fovi.mdp .. autosummary:: gaze_state - motor_action_l2 Actions ------- @@ -38,8 +37,3 @@ Observations .. autoclass:: gaze_teacher_labels :show-inheritance: - -Rewards -------- - -.. autofunction:: motor_action_l2 diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.rsl_rl.rst b/docs/source/api/lab_fovi/isaaclab_fovi.rsl_rl.rst deleted file mode 100644 index 4a8d7fc727d8..000000000000 --- a/docs/source/api/lab_fovi/isaaclab_fovi.rsl_rl.rst +++ /dev/null @@ -1,39 +0,0 @@ -isaaclab_fovi.rsl_rl -==================== - -.. automodule:: isaaclab_fovi.rsl_rl - - .. rubric:: Classes - - .. autosummary:: - - GazeSupervisedPPO - GazeSupervisedPPOCfg - GazeGaussianDistribution - GazeGaussianDistributionCfg - -Gaze-Supervised PPO -------------------- - -.. autoclass:: GazeSupervisedPPO - :members: - :show-inheritance: - -.. autoclass:: GazeSupervisedPPOCfg - :members: - :inherited-members: - :show-inheritance: - :exclude-members: __init__ - -Gaze Action Distribution ------------------------- - -.. autoclass:: GazeGaussianDistribution - :members: - :show-inheritance: - -.. autoclass:: GazeGaussianDistributionCfg - :members: - :inherited-members: - :show-inheritance: - :exclude-members: __init__ diff --git a/docs/source/concepts/sensors/camera.rst b/docs/source/concepts/sensors/camera.rst index 501192cf5bcc..de8c7f04839d 100644 --- a/docs/source/concepts/sensors/camera.rst +++ b/docs/source/concepts/sensors/camera.rst @@ -13,6 +13,8 @@ configuration can work across supported physics and rendering backends. Isaac Lab batches camera views from cloned environments into tiled render passes. Each requested output is returned as one GPU buffer with a separate image per view. +For a retina-like image that is dense where a movable gaze points, see :doc:`foveated_camera`. + For silent black or corrupted RTX camera images when scaling the workload, see :ref:`known-issues-rtx-buffer-limit`. diff --git a/docs/source/concepts/sensors/foveated_camera.rst b/docs/source/concepts/sensors/foveated_camera.rst new file mode 100644 index 000000000000..ec77cc6ee6b6 --- /dev/null +++ b/docs/source/concepts/sensors/foveated_camera.rst @@ -0,0 +1,153 @@ +.. _concepts_sensors_foveated_camera: + +.. currentmodule:: isaaclab_fovi + +Foveated Camera +=============== + +A :class:`~sensors.FoveatedCamera` samples the scene densely where it looks and sparsely in the periphery, as a +retina does, instead of on a uniform pixel grid. It is a :class:`~isaaclab.sensors.Camera` whose rays are laid out +by the `fovi `__ library, and its gaze moves inside the field of view of the +physical camera it looks through. + +The camera comes with the ``fovi`` extra: + +.. code-block:: bash + + uv sync --extra fovi + +The demo moves the gaze from object to object while the viewer shows the retina: + +.. code-block:: bash + + uv run --extra fovi isaaclab demo foveated-camera + +Configure a foveated camera +--------------------------- + +Add a :class:`~sensors.FoveatedCameraCfg` to a scene like any camera configuration. The renderer selects how the +retina is rendered: + +.. list-table:: + :header-rows: 1 + :widths: 45 55 + + * - Renderer configuration + - Rendering + * - :class:`~isaaclab_newton.renderers.NewtonWarpRendererCfg` + - One ray per retinal sample. + * - :class:`~isaaclab_physx.renderers.IsaacRtxRendererCfg`, + :class:`~isaaclab_ov.renderers.OVRTXRendererCfg` + - A lens lookup texture on the camera prim maps the image to the retina's rays. + +The camera also accepts the Newton OptiX renderer (``optix`` extra), which receives the same rays as Newton Warp. + +.. code-block:: python + + import isaaclab.sim as sim_utils + from isaaclab_fovi.sensors import FoveatedCameraCfg + from isaaclab_newton.renderers import NewtonWarpRendererCfg + + eye = FoveatedCameraCfg( + prim_path="{ENV_REGEX_NS}/Eye", + data_types=["rgb"], + renderer_cfg=NewtonWarpRendererCfg(), + spawn=sim_utils.PinholeCameraCfg(), + foveated_res=64, + ) + +The camera computes its image size from the retina. With the default grid style it publishes an upright image of +shape ``(num_envs, foveated_res, foveated_res, channels)`` in :attr:`~isaaclab.sensors.Camera.data`, like any +camera, and any output the renderer supports. + +The physical camera +~~~~~~~~~~~~~~~~~~~ + +The retina places its samples by visual angle inside the image of a physical camera, and its rays are cast at those +angles, so no pinhole image is resampled. By default that camera is the one ``spawn`` creates: + +* :class:`~isaaclab.sim.PinholeCameraCfg` optics give an ideal pinhole. +* An OpenCV model in ``spawn.distortion`` gives that calibrated camera. An + :class:`~isaaclab.sim.OpenCvFisheyeDistortionCfg` with zero coefficients is an ideal equidistant fisheye. + +For any other calibrated camera, or a camera prim without spawn configuration, set +:attr:`~sensors.FoveatedCameraCfg.camera_model` to the fields of a ``fovi.sensing.projection.CameraModel``: + +.. code-block:: python + + camera_model = { + "model": "pinhole", # or "fisheye" + "image_size": (480, 640), # (height, width) + "intrinsics": (550.0, 550.0, 319.5, 239.5), # fx, fy, cx, cy [px] + } + +The same fields configure fovi's software sampler on images from a real camera. + +The projection is set in the configuration. :meth:`~sensors.FoveatedCamera.set_intrinsic_matrices` leaves a +foveated camera as configured and warns, as cameras with an OpenCV lens model do. + +Foveation strength +~~~~~~~~~~~~~~~~~~ + +:attr:`~sensors.FoveatedCameraCfg.cmf_a_deg` is the cortical magnification constant in degrees. Smaller values +concentrate more samples at the fixation; the default, 0.591, is an estimate from human data. A value much larger +than the field of view samples nearly uniformly, which gives a matched non-foveated baseline with the same +resolution, field of view and gaze: + +.. code-block:: bash + + uv run --extra fovi isaaclab demo foveated-camera env.scene.eye.cmf_a_deg=1000 + +Move the gaze +------------- + +The gaze turns the retina relative to the physical camera's optical axis: + +.. code-block:: python + + # (tilt, pan) [deg] from the optical axis, shape (num_envs, 2): positive tilt looks up, positive pan looks left. + camera.set_gaze_angles(angles) + +The gaze stays relative to the camera's mount when the mount moves, and +:meth:`~sensors.FoveatedCamera.get_world_poses` reports the mount without the gaze. Set +:attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero the samples that fall outside the physical camera's +image at the current gaze. + +Pooling +------- + +With :attr:`~sensors.FoveatedCameraCfg.pool_enabled`, the camera renders a denser photoreceptor grid and pools it to +the retina, ``pool_res_mult`` times denser, with ``pool_mode`` (``avg``, ``gaussian``, ``max`` or ``sum``). +Segmentation outputs pool by modal label in their own dtype (``pool_int_mode="modal"``), since averaging would mix +labels into ones no object has. The sensor mask applies to the photoreceptors before pooling, so a pooled sample at +the image edge keeps what the camera sees of its neighbourhood. + +Further sampling options are passed to fovi's ``SamplingCoords``, whose +`documentation `__ describes them: ``fov_type`` and ``radius_norm`` set the +region the retina covers, and sample-set styles such as ``foveated_style="isotropic"`` publish +``(num_envs, num_samples, 1, channels)``. Sample-set styles are experimental on the RTX renderers, where crowded +samples can share a lens-texture texel. + +Active gaze +----------- + +:mod:`isaaclab_fovi.mdp` holds the manager terms for a policy that moves the gaze: + +* :class:`~mdp.GazeActionCfg`: two actions that move the gaze by up to ``step_size`` field radii per step, within + ``gaze_limit`` of the optical axis. Make it the last action term. With the default ``mount="fixed"`` the teacher + aims from the camera's orientation when the action is created; ``mount="tracked"`` lets the camera ride a moving + body, such as a turning head (Newton and OVRTX). +* :func:`~mdp.gaze_state`: the gaze and its velocity. +* :class:`~mdp.gaze_teacher_labels`: a teacher's gaze action toward a point fixed to an asset, and whether that point + is a valid target. It is a training label, never a policy input. + +The ``IsaacContrib-Cartpole-Camera-Fovi`` task in :mod:`isaaclab_tasks.contrib.active_gaze` puts them together. It is +the stock Cartpole camera task with the camera foveated (a 32-sample retina), two gaze actions, and a teacher that looks +at the pole's tip. Its PPO adds a loss that pulls the gaze actions toward the teacher's, and its action head keeps +the gaze actions' noise fixed: + +.. code-block:: bash + + uv run --extra fovi isaaclab train --rl_library rsl_rl --task IsaacContrib-Cartpole-Camera-Fovi + +The task is registered when the ``fovi`` extra is installed. diff --git a/docs/source/concepts/sensors/index.rst b/docs/source/concepts/sensors/index.rst index 609c514ce5ed..75fa8c447df7 100644 --- a/docs/source/concepts/sensors/index.rst +++ b/docs/source/concepts/sensors/index.rst @@ -19,6 +19,9 @@ Choose a sensor * - :doc:`camera` - Renderer-produced color, depth, normals, motion, and segmentation images - Vision observations and synthetic data + * - :doc:`foveated_camera` + - Retina-like images, dense where the gaze points and sparse in the periphery + - Active vision; requires the ``fovi`` extra * - :doc:`ray_caster` - First collision locations for configurable ray patterns - Terrain sensing, lidar-style queries, and ray-cast cameras @@ -69,6 +72,7 @@ Warp array. :hidden: camera + foveated_camera ray_caster contact_sensor frame_transformer diff --git a/docs/source/how-to/configure_rendering.rst b/docs/source/how-to/configure_rendering.rst index 18e835ffe0e6..70866f72754f 100644 --- a/docs/source/how-to/configure_rendering.rst +++ b/docs/source/how-to/configure_rendering.rst @@ -134,6 +134,19 @@ that legacy renderer; use Newton Warp or OVRTX for new Newton and kit-less workl preserve the color output; the ``simple_shading_*`` output remains available but does not receive the RTX Minimal performance improvement. +Render a foveated camera +------------------------ + +A :doc:`foveated camera ` (``fovi`` extra) renders a retina-like image, +dense where its gaze points, with the same renderer configurations as a regular camera: Newton Warp casts one ray per +retinal sample, and OVRTX and Isaac RTX render through a lens lookup texture on the camera prim. Select the renderer +with ``renderer=`` as for any camera: + +.. code-block:: bash + + uv run --extra fovi isaaclab demo foveated-camera renderer=newton_warp + uv run --extra fovi --extra ovrtx isaaclab demo foveated-camera renderer=ovrtx + Overriding Specific Rendering Settings -------------------------------------- diff --git a/docs/source/isaaclab/demos.rst b/docs/source/isaaclab/demos.rst index cea82bbf7fcc..d4a9316852ea 100644 --- a/docs/source/isaaclab/demos.rst +++ b/docs/source/isaaclab/demos.rst @@ -134,6 +134,15 @@ No source checkout is required. alt="Rizon and Sharpa hand scooping coffee beside a filled cup" loading="lazy"> Rizon–Sharpa Coffee +