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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
319 changes: 54 additions & 265 deletions docs/source/concepts/sensors/foveated_camera.rst

Large diffs are not rendered by default.

Empty file.
94 changes: 29 additions & 65 deletions source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ def teach(

@wp.kernel(enable_backward=False)
def teacher_labels_kernel(
targets: wp.array(dtype=wp.vec3f),
orientations: wp.array(dtype=wp.quatf),
target_poses: wp.array(dtype=wp.transformf),
offset: wp.vec3f,
positions: wp.array(dtype=wp.vec3f),
mounts: wp.array(dtype=wp.quatf),
Expand All @@ -89,7 +88,7 @@ def teacher_labels_kernel(
step_size: wp.float32,
gaze_limit: wp.float32,
camera: CameraParams,
labels: wp.array2d(dtype=wp.float32),
labels: wp.array(dtype=wp.vec3f),
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
Expand All @@ -99,17 +98,15 @@ def teacher_labels_kernel(
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]
count = target_poses.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)
point = wp.transform_point(target_poses[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]
labels[i] = wp.vec3f(result[0], result[1], result[2])
if result[2] > 0.5:
error_sum += result[3]
valid_count += 1.0
Expand All @@ -121,11 +118,6 @@ def teacher_labels_kernel(
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),
Expand Down Expand Up @@ -330,8 +322,13 @@ 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))
# A square root gives uniform area density in the gaze disc.
radius = self.cfg.gaze_limit * torch.rand(count, device=self.device).sqrt()
angle = 2 * math.pi * torch.rand(count, device=self.device)
gaze = torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1)
tilt, pan = (gaze * self.field_radius_deg).deg2rad().unbind(-1)
direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1)
visible = self.visible(direction)
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))
Expand Down Expand Up @@ -384,12 +381,9 @@ 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._labels = ProxyArray(wp.zeros(env.num_envs, dtype=wp.vec3f, 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__(
Expand All @@ -400,36 +394,24 @@ def __call__(
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:
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)
# Reading the property refreshes the producer's poses.
body_id = None if target_cfg.body_names is None else int(target_cfg.body_ids[0])
poses = data.root_pose_w.warp if body_id is None else data.body_pose_w.warp
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)
# Warp retains the selected view and its backing array in the recorded launch.
key = (id(poses), body_id, id(camera_positions), id(mounts), point)
if self._launch is None or self._launch[0] != key:
# Warp runs CPU blocks as one thread.
block = 1024 if torch.device(env.device).type == "cuda" else 1
launch = record_launch(
teacher_labels_kernel,
(1, block),
[
self._targets,
self._orientations,
self._offset[1],
poses if body_id is None else poses[:, body_id],
wp.vec3f(*point),
camera_positions,
mounts,
gaze.camera.gaze_angles,
Expand All @@ -443,29 +425,11 @@ def __call__(
env.device,
block_dim=block,
)
self._launch = (sources, launch)
self._launch = (key, launch)
self._launch[1].launch(warp_stream(env.device))
_log_teacher(env, self._log.torch)
# Each step's log must survive the next write to this buffer.
error, fraction = self._log.torch.clone()
log = env.extras.setdefault("log", {})
log["Gaze/target_error_deg"] = error
log["Gaze/valid_target_fraction"] = fraction
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)
11 changes: 3 additions & 8 deletions source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@
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, angular_directions

from isaaclab.sim import PinholeCameraCfg

Expand Down Expand Up @@ -79,32 +78,6 @@ def camera_model_from_spawn(spawn: PinholeCameraCfg) -> CameraCalibration:
)


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``
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 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)
Expand All @@ -121,13 +94,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
50 changes: 30 additions & 20 deletions source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -96,14 +97,14 @@ def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs):
" 'ovrtx'."
)

def __init__(self, cfg: FoveatedCameraCfg):
def __init__(self, cfg: FoveatedCameraCfg, *, turns_pose_by_gaze: bool = False):
"""Create the camera.

Raises:
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)
self._gaze_pose_reads_angles = turns_pose_by_gaze
"""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:
Expand Down Expand Up @@ -259,7 +260,8 @@ def set_world_poses_from_view(self, eyes, targets, env_ids=None):
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)])
turned = (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0
self._mount_written(self._env_indices(env_ids)[turned])
self._count_mount_turn(before, env_ids)

def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None):
Expand All @@ -280,11 +282,28 @@ 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."""
self._camera_model = resolve_camera_model(self.cfg)
def _prepare_sampling(self) -> None:
"""Resolve physical calibration and retinal coordinates before the renderer sizes its buffers."""
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
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:
Expand Down Expand Up @@ -407,10 +426,6 @@ def _env_indices(self, env_ids) -> torch.Tensor:
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."""
Expand Down Expand Up @@ -464,9 +479,9 @@ def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor], env_mask:

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)
self._segmentation_neighbors = (
segmentation_neighbor_indices(self._pooler) if any(is_segmentation_output(name) for name in names) else None
)

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.
Expand Down Expand Up @@ -563,8 +578,3 @@ def _set_published_shape(self, outputs: Mapping[str, torch.Tensor]) -> None:
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
Loading