diff --git a/docs/source/_static/overview/sensors/foveated_camera_gaze_modes.jpg b/docs/source/_static/overview/sensors/foveated_camera_gaze_modes.jpg new file mode 100644 index 000000000000..6daa6f826c42 Binary files /dev/null and b/docs/source/_static/overview/sensors/foveated_camera_gaze_modes.jpg differ diff --git a/docs/source/api/index.rst b/docs/source/api/index.rst index 1e89ff9500b0..f7e5375a31fa 100644 --- a/docs/source/api/index.rst +++ b/docs/source/api/index.rst @@ -103,6 +103,7 @@ The following modules are available in the ``isaaclab_fovi`` extension: .. autosummary:: :toctree: lab_fovi + assets mdp sensors diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.assets.rst b/docs/source/api/lab_fovi/isaaclab_fovi.assets.rst new file mode 100644 index 000000000000..f5dc8cda3b04 --- /dev/null +++ b/docs/source/api/lab_fovi/isaaclab_fovi.assets.rst @@ -0,0 +1,24 @@ +isaaclab_fovi.assets +==================== + +.. automodule:: isaaclab_fovi.assets + + .. rubric:: Data + + .. autosummary:: + + PAN_TILT_CFG + PAN_TILT_CAMERA_OFFSET + PAN_TILT_USD_PATH + +Pan-tilt mount +-------------- + +.. autodata:: PAN_TILT_CFG + :no-value: + +.. autodata:: PAN_TILT_CAMERA_OFFSET + :no-value: + +.. autodata:: PAN_TILT_USD_PATH + :no-value: diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst index 779ad564d64a..faf467a167fc 100644 --- a/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst +++ b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst @@ -9,6 +9,7 @@ isaaclab_fovi.mdp GazeAction GazeActionCfg + GazeRigCfg gaze_teacher_labels .. rubric:: Functions @@ -30,6 +31,11 @@ Actions :show-inheritance: :exclude-members: __init__, class_type +.. autoclass:: GazeRigCfg + :members: + :show-inheritance: + :exclude-members: __init__ + Observations ------------ diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst index 064c45720a77..208e262c8e4d 100644 --- a/docs/source/experimental-features/foveated_camera.rst +++ b/docs/source/experimental-features/foveated_camera.rst @@ -140,3 +140,44 @@ Select ``presets=depth`` for depth images. 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. + +Gaze modes +---------- + +:attr:`~mdp.GazeActionCfg.mode` sets what the gaze actions turn, two (tilt, pan) actions in every mode but dual gaze: + +* ``"software"`` (the default): the retina, relative to the camera's optical axis. The camera itself may move, for + example on a robot's head, with ``mount="tracked"``. +* ``"physical"``: the joints of a rig that carries the camera. Each action steps the joint targets. +* ``"hybrid"``: the retina at once, while the rig turns the camera after it by at most + :attr:`~mdp.GazeRigCfg.max_step_deg` per step. The fixation holds in the world as the head takes over, so the + camera ends up pointing where it looks. +* ``"dual"`` (experimental): four actions that move the rig's joints and then the retina independently. + +The rig modes need a :class:`~mdp.GazeRigCfg`, which names the articulation and its pan and tilt joints, +``mount="tracked"``, and a camera without image roll. :data:`~assets.PAN_TILT_CFG` is a two-joint +pan-tilt mount: + +.. code-block:: python + + from isaaclab.sim import PinholeCameraCfg + from isaaclab_fovi.assets import PAN_TILT_CAMERA_OFFSET, PAN_TILT_CFG + from isaaclab_fovi.mdp import GazeActionCfg, GazeRigCfg + from isaaclab_fovi.sensors import FoveatedCameraCfg + + rig = PAN_TILT_CFG + eye = FoveatedCameraCfg( + prim_path="{ENV_REGEX_NS}/PanTilt/Geometry/world/pan_link/tilt_link/Eye", + offset=PAN_TILT_CAMERA_OFFSET, + spawn=PinholeCameraCfg(), + ) + gaze = GazeActionCfg(asset_name="eye", mode="hybrid", mount="tracked", rig=GazeRigCfg(asset_name="rig")) + +With a rig, :func:`~mdp.gaze_state` reports the fixation's direction from the rig's zero pose: the head's turn +composed with the software gaze. + +.. figure:: ../_static/overview/sensors/foveated_camera_gaze_modes.jpg + :alt: Pan angles over time for the four gaze modes, with the camera's images before, during and after. + + Each mode on the pan-tilt mount with Newton's MJWarp solver: the policy pans 4.5° left three times. In hybrid gaze + the fixation jumps at once and holds while the head takes over from the retina. diff --git a/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.added.rst b/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.added.rst new file mode 100644 index 000000000000..9e733f08e3a2 --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.added.rst @@ -0,0 +1,9 @@ +* Added physical, hybrid and dual (experimental) gaze to :class:`~isaaclab_fovi.mdp.GazeActionCfg` through its + ``mode`` and :class:`~isaaclab_fovi.mdp.GazeRigCfg`: the gaze actions turn a rig's joints, the retina while the + rig follows, or both independently. +* Added :data:`~isaaclab_fovi.assets.PAN_TILT_CFG`, a two-joint pan-tilt mount for a camera. +* Added :meth:`~isaaclab_fovi.sensors.FoveatedCamera.update_mount`, which reads the camera's mount before a lazily + updated camera renders; hybrid gaze and the tracked-mount teacher aim from it. +* Added :attr:`~isaaclab_fovi.sensors.FoveatedCamera.gaze_writes`, which counts + :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles` calls, so hybrid gaze starts a new fixation after a + gaze set from elsewhere. diff --git a/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.fixed.rst b/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.fixed.rst new file mode 100644 index 000000000000..724db25386a8 --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.fixed.rst @@ -0,0 +1,9 @@ +* Fixed :class:`~isaaclab_fovi.mdp.gaze_teacher_labels` rendering a frame for every label, also between the frames + a policy observes: it read the camera's position from its data, which updates the image. It now reads + :attr:`~isaaclab_fovi.sensors.FoveatedCamera.mount_pos_w`, which + :meth:`~isaaclab_fovi.sensors.FoveatedCamera.update_mount` refreshes. +* Fixed the gaze teacher of a tracked mount aiming from the mount of the step before: a lazily updated camera + records its mount only when its data is read. The teacher now reads it with + :meth:`~isaaclab_fovi.sensors.FoveatedCamera.update_mount`. +* Fixed :class:`~isaaclab_fovi.mdp.gaze_teacher_labels` raising a ``TypeError`` when its target names every body + of the asset, as naming a rigid object's only body does, which resolves the body ids to a slice. diff --git a/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.minor b/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_fovi/changelog.d/fovi-teacher-world-points.added.rst b/source/isaaclab_fovi/changelog.d/fovi-teacher-world-points.added.rst new file mode 100644 index 000000000000..95e449d29210 --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/fovi-teacher-world-points.added.rst @@ -0,0 +1,3 @@ +* Added ``target_w`` to :class:`~isaaclab_fovi.mdp.gaze_teacher_labels`: a function of the environment that returns + each environment's target point in the world, for a target that is not fixed to one asset, such as the object a + command picks among several. diff --git a/source/isaaclab_fovi/changelog.d/fovi-teacher-world-points.minor b/source/isaaclab_fovi/changelog.d/fovi-teacher-world-points.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_fovi/changelog.d/fovi-tracked-mount-isaac-rtx.added.rst b/source/isaaclab_fovi/changelog.d/fovi-tracked-mount-isaac-rtx.added.rst new file mode 100644 index 000000000000..732d4e2e58db --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/fovi-tracked-mount-isaac-rtx.added.rst @@ -0,0 +1,3 @@ +* Added tracked gaze mounts on Isaac RTX: :meth:`~isaaclab_fovi.sensors.FoveatedCamera.update_mount` now reads the + mount of a camera that holds its gaze in its prim, so :class:`~isaaclab_fovi.mdp.GazeActionCfg` takes + ``mount="tracked"``, and with it the physical, hybrid and dual gaze modes, with every renderer. diff --git a/source/isaaclab_fovi/changelog.d/fovi-tracked-mount-isaac-rtx.minor b/source/isaaclab_fovi/changelog.d/fovi-tracked-mount-isaac-rtx.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_fovi/isaaclab_fovi/assets/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/assets/__init__.py new file mode 100644 index 000000000000..1cc669390ceb --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/assets/__init__.py @@ -0,0 +1,10 @@ +# 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 + +"""Assets for physical gaze: a pan-tilt camera mount.""" + +from isaaclab.utils.module import lazy_export + +lazy_export() diff --git a/source/isaaclab_fovi/isaaclab_fovi/assets/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/assets/__init__.pyi new file mode 100644 index 000000000000..e2845acae9a8 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/assets/__init__.pyi @@ -0,0 +1,12 @@ +# 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__ = [ + "PAN_TILT_CAMERA_OFFSET", + "PAN_TILT_CFG", + "PAN_TILT_USD_PATH", +] + +from .pan_tilt import PAN_TILT_CAMERA_OFFSET, PAN_TILT_CFG, PAN_TILT_USD_PATH diff --git a/source/isaaclab_fovi/isaaclab_fovi/assets/pan_tilt.py b/source/isaaclab_fovi/isaaclab_fovi/assets/pan_tilt.py new file mode 100644 index 000000000000..fbcd9773d653 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/assets/pan_tilt.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 + +"""A two-joint pan-tilt mount that turns a camera, for physical and hybrid gaze. + +The mount stands on a fixed base. ``pan_joint`` turns about the base's +Z axis (positive turns left) and +``tilt_joint`` about the panned +X axis (positive turns up). At zero the mount faces +Y; a camera prim under +``tilt_link`` at :data:`PAN_TILT_CAMERA_OFFSET` looks along it with +Z up. The asset has no visual geometry. +""" + +from __future__ import annotations + +from pathlib import Path + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets.articulation import ArticulationCfg +from isaaclab.sensors import CameraCfg + +PAN_TILT_USD_PATH = str(Path(__file__).with_name("pan_tilt.usda")) +"""The mount's USD, converted from its URDF with fixed joints merged; it loads with or without Kit.""" + +PAN_TILT_CAMERA_OFFSET = CameraCfg.OffsetCfg( + pos=(0.0, 0.0, 0.0), rot=(0.0, 0.0, 0.70710678, 0.70710678), convention="world" +) +"""Pose of a camera under ``tilt_link`` that looks along the mount's forward axis (world convention).""" + +PAN_TILT_CFG = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/PanTilt", + # Gravity stays on: Newton reads a body's disable-gravity flag as the whole scene's. + spawn=sim_utils.UsdFileCfg(usd_path=PAN_TILT_USD_PATH, fix_root_link=True), + init_state=ArticulationCfg.InitialStateCfg(joint_pos={"pan_joint": 0.0, "tilt_joint": 0.0}), + actuators={ + "pan_tilt": ImplicitActuatorCfg( + joint_names_expr=["pan_joint", "tilt_joint"], + stiffness=10.0, + damping=1.4, + joint_effort_limit=20.0, + armature=0.05, + ) + }, + soft_joint_pos_limit_factor=1.0, +) +"""The pan-tilt mount: about critically damped position drives that settle in about 0.3 s. + +The armature carries the drives' inertia: the links themselves are too light for a stable stiff drive at Isaac Lab's +usual physics step.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/assets/pan_tilt.usda b/source/isaaclab_fovi/isaaclab_fovi/assets/pan_tilt.usda new file mode 100644 index 000000000000..fe6734eb43a8 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/assets/pan_tilt.usda @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58b8b3dd6467b926daeae7e0cb8ffb9c229125004f28cecece5a3db3f0bea923 +size 5430 diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi index e78c9a3844e8..c8adeac9610d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -6,6 +6,7 @@ __all__ = [ "GazeAction", "GazeActionCfg", + "GazeRigCfg", "gaze_state", "gaze_teacher_labels", ] @@ -15,4 +16,4 @@ from .gaze import ( gaze_state, gaze_teacher_labels, ) -from .gaze_cfg import GazeActionCfg +from .gaze_cfg import GazeActionCfg, GazeRigCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 862897ab93ca..f3a3742af2ff 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py @@ -14,6 +14,8 @@ from __future__ import annotations import math +from collections.abc import Callable +from functools import cache from typing import TYPE_CHECKING, ClassVar import torch @@ -39,6 +41,79 @@ RAD_TO_DEG = 180.0 / math.pi +PHYSICAL, HYBRID, DUAL = 1, 2, 3 +"""Codes of the gaze modes that turn a rig, for :func:`make_rig_gaze_step`.""" + +RIG_MODES = {"physical": PHYSICAL, "hybrid": HYBRID, "dual": DUAL} +"""The rig modes' codes by :attr:`~isaaclab_fovi.mdp.GazeActionCfg.mode`.""" + + +@wp.func +def clamp_unit(a: wp.vec2f) -> wp.vec2f: + """Each coordinate of an action clamped to [-1, 1].""" + return wp.vec2f(wp.clamp(a[0], -1.0, 1.0), wp.clamp(a[1], -1.0, 1.0)) + + +@wp.func +def within(g: wp.vec2f, limit: wp.float32) -> wp.vec2f: + """A gaze scaled back onto the circle of radius ``limit`` when it leaves it.""" + return g * (limit / wp.max(wp.length(g), limit)) + + +@wp.func +def gaze_direction(g: wp.vec2f, field_radius_deg: wp.float32) -> wp.vec3f: + """Upright-frame unit direction of a gaze (tilt, pan) in field radii.""" + tilt = g[0] * field_radius_deg * wp.float32(DEG_TO_RAD) + pan = g[1] * field_radius_deg * wp.float32(DEG_TO_RAD) + return wp.vec3f(-wp.cos(tilt) * wp.sin(pan), -wp.sin(tilt), wp.cos(tilt) * wp.cos(pan)) + + +@wp.func +def gaze_of(u: wp.vec3f, field_radius_deg: wp.float32) -> wp.vec2f: + """Gaze (tilt, pan) in field radii of an upright-frame direction.""" + 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) + return wp.vec2f(tilt, pan) / field_radius_deg + + +@wp.func +def head_angles(joint_pos: wp.array2d(dtype=wp.float32), i: wp.int32, joints: wp.vec2i, signs: wp.vec2f) -> wp.vec2f: + """The head's (tilt, pan) [rad], left and up positive, from the rig's (pan, tilt) ``joints``.""" + return wp.vec2f(signs[1] * joint_pos[i, joints[1]], signs[0] * joint_pos[i, joints[0]]) + + +@wp.func +def rig_gaze(head_rad: wp.vec2f, soft: wp.vec2f, field_radius_deg: wp.float32) -> wp.vec2f: + """Gaze (tilt, pan) in field radii, from the rig's zero pose, of a software gaze ``soft`` [field radii] seen + through a head turned by ``head_rad`` (tilt, pan) [rad]. + + The head pans and then tilts, as the retina does within it, so their rotations compose rather than add. + """ + d = gaze_direction(soft, field_radius_deg) + c, s = wp.cos(head_rad[0]), wp.sin(head_rad[0]) + d = wp.vec3f(d[0], c * d[1] - s * d[2], s * d[1] + c * d[2]) + c, s = wp.cos(head_rad[1]), wp.sin(head_rad[1]) + d = wp.vec3f(c * d[0] - s * d[2], d[1], s * d[0] + c * d[2]) + return gaze_of(d, field_radius_deg) + + +@wp.func +def write_head_targets( + targets: wp.array2d(dtype=wp.float32), + limits: wp.array2d(dtype=wp.vec2f), + i: wp.int32, + joints: wp.vec2i, + signs: wp.vec2f, + base: wp.vec2f, + turn_rad: wp.vec2f, +): + """Set the rig's joint targets (pan, tilt) to ``base`` (pan, tilt) [rad] turned by ``turn_rad`` (tilt, pan) + [rad], within the joints' limits.""" + pan_limit = limits[i, joints[0]] + tilt_limit = limits[i, joints[1]] + targets[i, 0] = wp.clamp(base[0] + signs[0] * turn_rad[1], pan_limit[0], pan_limit[1]) + targets[i, 1] = wp.clamp(base[1] + signs[1] * turn_rad[0], tilt_limit[0], tilt_limit[1]) + @wp.func def teach( @@ -46,6 +121,9 @@ def teach( position: wp.vec3f, mount: wp.quatf, g: wp.vec2f, + start: wp.vec2f, + head: wp.vec4f, + physical: wp.int32, frame: wp.mat33f, field_radius_deg: wp.float32, step_size: wp.float32, @@ -54,23 +132,27 @@ def teach( ) -> 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. + ``g`` is the software gaze in field radii as the camera looks now, from which the error is measured, and ``start`` + the software gaze the next step moves from: ``g`` itself, or in hybrid gaze ``g`` re-aimed at its held fixation + for the head's turn. In physical gaze (``physical``) the action moves the head instead: ``head`` holds its + measured and commanded (tilt, pan) in field radii, and the action takes the commanded head to the pose that faces + the point, so it does not repeat a turn the head has yet to make. ``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 + desired = gaze_of(u, 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)) + if physical != 0: + measured = wp.vec2f(head[0], head[1]) * field_radius_deg * wp.float32(DEG_TO_RAD) + facing = rig_gaze(measured, desired, field_radius_deg) + step = clamp_unit((facing - wp.vec2f(head[2], head[3])) / step_size) + else: + step = clamp_unit((desired - start) / step_size) + looking = gaze_direction(g, field_radius_deg) # 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) @@ -83,6 +165,10 @@ def teacher_labels_kernel( positions: wp.array(dtype=wp.vec3f), mounts: wp.array(dtype=wp.quatf), angles_deg: wp.array(dtype=wp.vec2f), + heads: wp.array(dtype=wp.vec4f), + held: wp.array(dtype=wp.vec3f), + held_valid: wp.array(dtype=wp.int32), + mode: wp.int32, frame: wp.mat33f, field_radius_deg: wp.float32, step_size: wp.float32, @@ -94,8 +180,11 @@ def teacher_labels_kernel( """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. + ``mounts`` holds each camera's mount (ROS convention); ``angles_deg`` the camera's stored gaze angles [deg]; + ``heads`` the head's measured and commanded (tilt, pan) in field radii, which physical gaze labels from; ``held`` + the world fixation hybrid gaze holds, once ``held_valid`` is set, which the next step re-aims the gaze at first. + ``mode`` is the rig mode's code, or 0 without a rig; the arrays a mode does not use may be empty. One block labels + every environment and reduces the logs itself, so the launch needs no zeroed accumulators. """ _block, lane = wp.tid() count = target_poses.shape[0] @@ -105,7 +194,27 @@ def teacher_labels_kernel( while i < count: 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) + start = gaze + if mode == HYBRID: + if held_valid[i] != 0: + start = gaze_of(wp.transpose(frame) * wp.quat_rotate_inv(mounts[i], held[i]), field_radius_deg) + head = wp.vec4f(0.0, 0.0, 0.0, 0.0) + if mode == PHYSICAL: + head = heads[i] + result = teach( + point, + positions[i], + mounts[i], + gaze, + start, + head, + wp.where(mode == PHYSICAL, 1, 0), + frame, + field_radius_deg, + step_size, + gaze_limit, + camera, + ) labels[i] = wp.vec3f(result[0], result[1], result[2]) if result[2] > 0.5: error_sum += result[3] @@ -161,13 +270,140 @@ def gaze_step_kernel( i = wp.tid() a = actions[i] 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)) + current = within(previous + clamp_unit(a) * step_size, gaze_limit) rate = (current - previous) / step_dt angles_deg[i] = current * field_radius_deg state[i] = wp.vec4f(current[0], current[1], rate[0], rate[1]) +@cache +def make_rig_gaze_step(mode: int) -> wp.Kernel: + """Return the gaze step of one rig mode: :data:`PHYSICAL`, :data:`HYBRID` or :data:`DUAL`.""" + if mode not in (PHYSICAL, HYBRID, DUAL): + raise ValueError(f"Unknown rig gaze mode {mode!r}.") + + @wp.kernel(enable_backward=False, module="unique") + def rig_gaze_step( + actions: wp.array2d(dtype=wp.float32), + joint_pos: wp.array2d(dtype=wp.float32), + limits: wp.array2d(dtype=wp.vec2f), + joints: wp.vec2i, + signs: wp.vec2f, + mounts: wp.array(dtype=wp.quatf), + step_size: wp.float32, + gaze_limit: wp.float32, + head_step: wp.float32, + step_dt: wp.float32, + field_radius_deg: wp.float32, + held: wp.array(dtype=wp.vec3f), + held_valid: wp.array(dtype=wp.int32), + angles_deg: wp.array(dtype=wp.vec2f), + state: wp.array(dtype=wp.vec4f), + targets: wp.array2d(dtype=wp.float32), + ): + """Move each camera's gaze with its rig's joints and, in hybrid and dual gaze, its software gaze. + + Gazes are (tilt, pan) in field radii, in the camera's frame, which needs no image roll; the rig's ``joints`` + are (pan, tilt) with ``signs`` that turn the camera left and up. ``mounts`` holds each camera's mount (ROS + convention) as of its last pose update. ``head_step`` bounds the hybrid head target's offset from the measured + joints, in field radii. Hybrid gaze holds each fixation as a world direction in ``held`` once ``held_valid`` + is set; the other modes leave those arrays alone, so they may be empty. + Writes the software gaze ``angles_deg``, the joint ``targets`` (pan, tilt) and ``state``: the fixation's + direction from the rig's zero pose and its velocity. + """ + i = wp.tid() + radius_rad = field_radius_deg * wp.float32(DEG_TO_RAD) + head = head_angles(joint_pos, i, joints, signs) + soft = angles_deg[i] / field_radius_deg + # Commanded head steps add to the last target, so a lagging head still reaches every commanded step. + base = wp.vec2f(targets[i, 0], targets[i, 1]) + turn = wp.vec2f(0.0, 0.0) + if wp.static(mode == PHYSICAL): + turn = clamp_unit(wp.vec2f(actions[i, 0], actions[i, 1])) * step_size + if wp.static(mode == DUAL): + turn = clamp_unit(wp.vec2f(actions[i, 0], actions[i, 1])) * step_size + soft = within(soft + clamp_unit(wp.vec2f(actions[i, 2], actions[i, 3])) * step_size, gaze_limit) + if wp.static(mode == HYBRID): + if held_valid[i] != 0: + # The head turned since the last step: aim the software gaze back at the fixation it holds in the world. + soft = gaze_of(wp.quat_rotate_inv(mounts[i], held[i]), field_radius_deg) + soft = within(soft + clamp_unit(wp.vec2f(actions[i, 0], actions[i, 1])) * step_size, gaze_limit) + turn = wp.vec2f(wp.clamp(soft[0], -head_step, head_step), wp.clamp(soft[1], -head_step, head_step)) + held[i] = wp.quat_rotate(mounts[i], gaze_direction(soft, field_radius_deg)) + held_valid[i] = 1 + base = wp.vec2f(joint_pos[i, joints[0]], joint_pos[i, joints[1]]) + write_head_targets(targets, limits, i, joints, signs, base, turn * radius_rad) + angles_deg[i] = soft * field_radius_deg + gaze = rig_gaze(head, soft, field_radius_deg) + previous = wp.vec2f(state[i][0], state[i][1]) + rate = (gaze - previous) / step_dt + state[i] = wp.vec4f(gaze[0], gaze[1], rate[0], rate[1]) + + return rig_gaze_step + + +@wp.kernel(enable_backward=False) +def rig_gaze_reset_kernel( + ids: wp.array(dtype=wp.int32), + use_ids: wp.int32, + default_joint_pos: wp.array2d(dtype=wp.float32), + joints: wp.vec2i, + signs: wp.vec2f, + field_radius_deg: wp.float32, + clear_held: wp.int32, + targets: wp.array2d(dtype=wp.float32), + held_valid: wp.array(dtype=wp.int32), + angles_deg: wp.array(dtype=wp.vec2f), + state: wp.array(dtype=wp.vec4f), +): + """Put each reset environment's joint targets at their defaults and its software gaze on the optical axis. + + The gaze state starts at the default head's angles, at rest; hybrid gaze (``clear_held``) drops its fixation. + """ + k = wp.tid() + i = k + if use_ids != 0: + i = ids[k] + targets[i, 0] = default_joint_pos[i, joints[0]] + targets[i, 1] = default_joint_pos[i, joints[1]] + if clear_held != 0: + held_valid[i] = 0 + angles_deg[i] = wp.vec2f(0.0, 0.0) + head = head_angles(default_joint_pos, i, joints, signs) / (field_radius_deg * wp.float32(DEG_TO_RAD)) + state[i] = wp.vec4f(head[0], head[1], 0.0, 0.0) + + +@wp.kernel(enable_backward=False) +def head_and_target_kernel( + joint_pos: wp.array2d(dtype=wp.float32), + targets: wp.array2d(dtype=wp.float32), + joints: wp.vec2i, + signs: wp.vec2f, + field_radius_deg: wp.float32, + heads: wp.array(dtype=wp.vec4f), +): + """Each head's measured (tilt, pan) and the (tilt, pan) its joint targets (pan, tilt) command, in field radii.""" + i = wp.tid() + radius_rad = field_radius_deg * wp.float32(DEG_TO_RAD) + head = head_angles(joint_pos, i, joints, signs) / radius_rad + target = head_angles(targets, i, wp.vec2i(0, 1), signs) / radius_rad + heads[i] = wp.vec4f(head[0], head[1], target[0], target[1]) + + +def target_body_index(target_cfg: SceneEntityCfg) -> int | None: + """The body a teacher's point is fixed to, or None for the asset's root. + + :class:`~isaaclab.managers.SceneEntityCfg` resolves ``body_ids`` to a slice when the named bodies cover every body + of the asset, as naming the only body of a rigid object does; the slice starts at the first of them. + """ + if target_cfg.body_names is None: + return None + ids = target_cfg.body_ids + if isinstance(ids, slice): + return ids.start or 0 + return int(ids[0]) + + 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) @@ -178,35 +414,50 @@ 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. Gazes are measured - in the upright image frame, which :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.image_rotation_deg` rolls - against a rolled mount. + ``step_size``, and the software gaze stays within ``gaze_limit`` of the optical axis. Gazes are measured in the + upright image frame, which :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.image_rotation_deg` rolls against a + rolled mount. + + :attr:`~isaaclab_fovi.mdp.GazeActionCfg.mode` sets what the actions turn, two (tilt, pan) actions in every mode + but dual gaze, which takes four: + + * ``"software"``: the retina, at once, relative to the camera's optical axis; the camera itself may move with a + tracked mount. + * ``"physical"``: the joints of the rig that carries the camera, by moving their targets from the last targets; + the retina stays on the optical axis, and the gaze follows as the joints reach their targets. + * ``"hybrid"``: the retina at once, while the rig's joints follow, by at most + :attr:`~isaaclab_fovi.mdp.GazeRigCfg.max_step_deg` per step. Each step the software gaze is re-aimed at the + fixation it holds in the world, so as the head catches up the retina returns toward the optical axis and the + fixation stays put. + * ``"dual"`` (experimental): the rig's joints as in physical gaze and then the retina as in software gaze, each + moved independently by the policy. + + The modes that turn a rig need a camera without image roll, whose tilt and pan follow the rig's joints. + + The software gaze starts each episode on the optical axis, or, in software gaze, anywhere the physical camera sees + within the limit when ``random_reset`` is set. 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. + The camera's stored gaze angles own the software 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, and in hybrid gaze starts a + new fixation. :attr:`state`, the observation, is the gaze and velocity as of the last step or reset; with a rig, + the gaze is the fixation's direction from the rig's zero pose, the head's turn composed with the software gaze. """ 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.""" + """The gaze moves in :meth:`process_actions`, once per environment step; :meth:`apply_actions` at most writes a + rig's joint targets from a fixed buffer, so physics may record its decimation loop into a CUDA graph.""" 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, @@ -239,10 +490,27 @@ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv): 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] = {} + self._heads = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec4f, device=self.device)) + """The head's measured and commanded (tilt, pan) [field radii], which the teacher labels physical gaze from.""" + self._own_gaze_writes = 0 + """The camera's :attr:`~isaaclab_fovi.sensors.FoveatedCamera.gaze_writes` after this term's last write.""" + # Without a rig there is no fixation to hold; _init_rig replaces these for the rig modes. + self._mode_code = 0 + self._held = ProxyArray(wp.zeros(0, dtype=wp.vec3f, device=self.device)) + self._held_valid = ProxyArray(wp.zeros(0, dtype=wp.int32, device=self.device)) + self.rig = None + """The articulation that turns the camera, for every mode but software gaze.""" + if cfg.mode != "software": + if camera.cfg.image_rotation_deg != 0: + raise ValueError( + f"GazeActionCfg.mode={cfg.mode!r} turns the camera with a rig's pan and tilt joints, which a rolled" + f" image's tilt and pan do not follow; got image_rotation_deg={camera.cfg.image_rotation_deg!r}." + ) + self._init_rig(env) @property def action_dim(self) -> int: - return 2 + return 4 if self.cfg.mode == "dual" else 2 @property def camera(self) -> FoveatedCamera: @@ -251,7 +519,9 @@ def camera(self) -> FoveatedCamera: @property def raw_actions(self) -> torch.Tensor: - return self._raw if self._raw is not None else torch.zeros_like(self._velocity) + if self._raw is not None: + return self._raw + return torch.zeros(self.num_envs, self.action_dim, dtype=torch.float32, device=self.device) @property def processed_actions(self) -> torch.Tensor: @@ -278,13 +548,16 @@ def angles_deg(self) -> torch.Tensor: return self.camera.gaze_angles.torch def process_actions(self, actions: torch.Tensor): - """Move the gaze by the supplied actions, shape (num_envs, 2). + """Move the gaze by the supplied actions, shape (num_envs, :attr:`action_dim`): 2, or 4 in dual gaze. 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() + if self.rig is not None: + self._process_rig_actions(actions) + return key = (actions.data_ptr(), actions.stride(), actions.device) if self._step_launch is None or self._step_launch[0] != key: launch = record_launch( @@ -307,7 +580,8 @@ def process_actions(self, actions: torch.Tensor): self.camera.set_gaze_angles(self.camera.gaze_angles.torch) def apply_actions(self): - pass + if self.rig is not None: + self.rig.actuators.target_command.set_position_index(value=self._targets.torch, joint_ids=self._joint_ids) def reset(self, env_ids=None): # The action manager zeroes the reset environments' actions itself. @@ -320,6 +594,9 @@ def reset(self, env_ids=None): if count == 0: return self._reset_ids.torch[:count] = torch.as_tensor(env_ids, device=self.device) + if self.rig is not None: + self._reset_rig(indexed, count) + return random_start = self.cfg.random_reset if random_start: # A square root gives uniform area density in the gaze disc. @@ -353,11 +630,15 @@ 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. + The call reads the camera's pose, so the teacher aims from where the camera stands now, though no term has + read its image yet; it captures no image. + Raises: RuntimeError: The camera's mount turned while the gaze assumes a fixed mount. """ + mount = self.camera.update_mount() if self.tracked_mount: - return self.camera.mount_quat_w_ros + return mount 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;" @@ -365,17 +646,140 @@ def teacher_mounts(self) -> ProxyArray: ) return self._fixed_mount + def held_fixation(self) -> tuple[ProxyArray, ProxyArray]: + """The world fixation hybrid gaze holds (ROS world directions) and whether it holds one, per environment; both + empty but in hybrid gaze. The next step re-aims the software gaze at it, so the teacher labels from there.""" + return self._held, self._held_valid + + def head_and_target(self) -> ProxyArray: + """The head's measured (tilt, pan) and the (tilt, pan) its joint targets command, in field radii, shape + (num_envs,) of ``vec4f``; zero but in physical gaze, the one mode whose actions turn the head. + + The teacher labels physical gaze from them, so it does not command a turn again while the head catches up. + """ + if self.rig is not None and self._mode_code == PHYSICAL: + # Reading the property refreshes the rig's joint buffer. + joint_pos = self.rig.data.joint_pos.warp + if self._heads_launch is None or self._heads_launch[0] is not joint_pos: + launch = record_launch( + head_and_target_kernel, + self.num_envs, + [joint_pos, self._targets, self._joints, self._signs, self.field_radius_deg], + [self._heads], + self.device, + ) + self._heads_launch = (joint_pos, launch) + self._heads_launch[1].launch(warp_stream(self.device)) + return self._heads + + def _init_rig(self, env: ManagerBasedEnv) -> None: + """Find the rig's joints and allocate the joint targets and, in hybrid gaze, the fixation it holds.""" + rig_cfg = self.cfg.rig + self.rig = env.scene[rig_cfg.asset_name] + joint_ids, _ = self.rig.find_joints(list(rig_cfg.joint_names), preserve_order=True) + self._joint_ids = list(joint_ids) + self._joints = wp.vec2i(*self._joint_ids) + self._signs = wp.vec2f(*rig_cfg.joint_signs) + self._mode_code = RIG_MODES[self.cfg.mode] + default = self.rig.data.default_joint_pos.torch[:, self._joint_ids] + # Indexing the selected joints copies them, so the targets own their storage. + self._targets = ProxyArray(wp.from_torch(default.contiguous())) + """Joint position targets (pan, tilt) [rad] the rig drives to.""" + # Only hybrid gaze holds a fixation; the other modes' kernels never touch these, so they stay empty. + held = self.num_envs if self._mode_code == HYBRID else 0 + self._held = ProxyArray(wp.zeros(held, dtype=wp.vec3f, device=self.device)) + """The world fixation hybrid gaze holds (ROS world directions), once ``_held_valid`` is set.""" + self._held_valid = ProxyArray(wp.zeros(held, dtype=wp.int32, device=self.device)) + self._rig_launch: tuple[tuple, wp.Launch] | None = None + self._rig_reset_launches: dict[bool, wp.Launch] = {} + self._heads_launch: tuple[wp.array, wp.Launch] | None = None + + def _process_rig_actions(self, actions: torch.Tensor) -> None: + """Move the gaze with the rig's joints and the software gaze, in one launch.""" + data = self.rig.data + # Reading the properties refreshes the rig's joint buffers. Hybrid gaze aims from the mount as the head stands + # now, which a lazily updated camera has not read yet. + joint_pos, limits = data.joint_pos.warp, data.soft_joint_pos_limits.warp + mounts = self.camera.update_mount() if self._mode_code == HYBRID else self.camera.mount_quat_w_ros + if self._mode_code == HYBRID and self.camera.gaze_writes != self._own_gaze_writes: + # A gaze set on the camera since this term's last write, even to the same angles, starts a new fixation. + self._held_valid.torch.zero_() + key = (actions.data_ptr(), actions.stride(), actions.device) + arrays = (joint_pos, limits, mounts) + cached = self._rig_launch + if cached is None or cached[0][0] != key or any(a is not b for a, b in zip(cached[0][1], arrays)): + launch = record_launch( + make_rig_gaze_step(self._mode_code), + self.num_envs, + [ + wp.from_torch(actions), + joint_pos, + limits, + self._joints, + self._signs, + mounts, + self.cfg.step_size, + self.cfg.gaze_limit, + self.cfg.rig.max_step_deg / self.field_radius_deg, + self._env.step_dt, + self.field_radius_deg, + ], + [self._held, self._held_valid, self.camera.gaze_angles, self._state, self._targets], + self.device, + ) + self._rig_launch = ((key, arrays), launch) + self._raw = actions + self._rig_launch[1].launch(warp_stream(self.device)) + self._write_gaze() + + def _reset_rig(self, indexed: bool, count: int) -> None: + """Put the reset environments, the first ``count`` of :attr:`_reset_ids` if ``indexed``, at the rig's default + joint targets with the software gaze on the optical axis. + + The articulation resets its own joints; the gaze state starts at the joints' default angles, at rest. + """ + launch = self._rig_reset_launches.get(indexed) + if launch is None: + launch = self._rig_reset_launches[indexed] = record_launch( + rig_gaze_reset_kernel, + self.num_envs, + [ + self._reset_ids, + int(indexed), + self.rig.data.default_joint_pos.warp, + self._joints, + self._signs, + self.field_radius_deg, + int(self._mode_code == HYBRID), + ], + [self._targets, self._held_valid, self.camera.gaze_angles, self._state], + self.device, + ) + launch.set_dim(count) + launch.launch(warp_stream(self.device)) + self._write_gaze() + + def _write_gaze(self) -> None: + """Publish the camera's stored gaze, which the kernels wrote, and note the write as this term's own.""" + self.camera.set_gaze_angles(self.camera.gaze_angles.torch) + self._own_gaze_writes = self.camera.gaze_writes + class gaze_teacher_labels(ManagerTermBase): - """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3). + """The teacher's gaze action toward a target point, and its validity, shape (num_envs, 3). + + The target is a point fixed to an asset (``target_cfg``), or any world point each environment supplies + (``target_w``), for example the object a command picks among several. 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]. + target_cfg: The asset, and optionally one body by ``body_names``; give this or ``target_w``. + offset: The point in the root's or the body's frame [m]; along the world axes from ``target_w``. action_name: The gaze action term. + target_w: A function of the environment that returns each environment's target point in the world [m], shape + (num_envs, 3); give this or ``target_cfg``. """ def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv): @@ -385,24 +789,36 @@ def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv): 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._launch: tuple[tuple, wp.Launch] | None = None + self._point_poses: ProxyArray | None = None + """Poses at the points ``target_w`` returns, unturned, which the launch reads as it reads an asset's.""" def __call__( self, env: ManagerBasedEnv, - target_cfg: SceneEntityCfg, + target_cfg: SceneEntityCfg | None = None, offset: tuple[float, float, float] = (0.0, 0.0, 0.0), action_name: str = "gaze", + target_w: Callable[[ManagerBasedEnv], torch.Tensor] | None = None, ) -> torch.Tensor: - data = env.scene[target_cfg.name].data - # 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 + if (target_cfg is None) == (target_w is None): + raise ValueError("gaze_teacher_labels needs one target: target_cfg or target_w.") + if target_w is not None: + body_id = None + poses = self._poses_at(target_w(env)) + else: + data = env.scene[target_cfg.name].data + # Reading the property refreshes the producer's poses. + body_id = target_body_index(target_cfg) + 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) gaze = self._gaze mounts = gaze.teacher_mounts() - camera_positions = gaze.camera.data.pos_w.warp + heads = gaze.head_and_target() + held, held_valid = gaze.held_fixation() + # The mounts' pose read refreshed the position; reading the camera's data would capture an image. + camera_positions = gaze.camera.mount_pos_w.warp # Warp retains the selected view and its backing array in the recorded launch. - key = (id(poses), body_id, id(camera_positions), id(mounts), point) + key = (id(poses), body_id, id(camera_positions), id(mounts), id(heads), 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 @@ -415,6 +831,10 @@ def __call__( camera_positions, mounts, gaze.camera.gaze_angles, + heads, + held, + held_valid, + RIG_MODES.get(gaze.cfg.mode, 0), gaze.camera.image_frame, gaze.field_radius_deg, gaze.cfg.step_size, @@ -433,3 +853,15 @@ def __call__( log["Gaze/target_error_deg"] = error log["Gaze/valid_target_fraction"] = fraction return self._labels.torch + + def _poses_at(self, points: torch.Tensor) -> wp.array: + """World points as unturned poses in one buffer, shape (num_envs,) of ``transformf``, so the recorded launch + reads them as it reads an asset's poses.""" + if tuple(points.shape) != (self.num_envs, 3): + raise ValueError(f"target_w must return points of shape ({self.num_envs}, 3), got {tuple(points.shape)}.") + if self._point_poses is None: + self._point_poses = ProxyArray(wp.zeros(self.num_envs, dtype=wp.transformf, device=self.device)) + # Identity orientations (x, y, z, w). + self._point_poses.torch[:, 6] = 1.0 + self._point_poses.torch[:, :3] = points + return self._point_poses.warp diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py index 1d8b75373902..97754e71b579 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py @@ -17,6 +17,33 @@ if TYPE_CHECKING: from .gaze import GazeAction +GAZE_MODES = ("software", "physical", "hybrid", "dual") +"""How the gaze action moves the gaze; see :class:`~isaaclab_fovi.mdp.gaze.GazeAction`.""" + + +@configclass +class GazeRigCfg: + """The articulation that turns the camera, for physical, hybrid and dual gaze.""" + + asset_name: str = MISSING + """Scene name of the articulation whose joints turn the camera.""" + joint_names: tuple[str, str] = ("pan_joint", "tilt_joint") + """The joints that turn the camera left and up, in that order.""" + joint_signs: tuple[float, float] = (1.0, 1.0) + """Sign of each joint's angle for a turn of the camera to the left and up.""" + max_step_deg: float = 6.0 + """Largest offset [deg] of each joint target from the joint's measured angle in hybrid gaze, which each step sets + from where the head stands: how fast the head catches up.""" + + def validate_config(self) -> None: + """Reject a rig without two distinct joints, a sign of 1 or -1 for each, and a positive, finite step.""" + if not _positive_finite(self.max_step_deg): + raise ValueError(f"GazeRigCfg.max_step_deg must be positive and finite, got {self.max_step_deg!r}.") + if len(self.joint_names) != 2 or len(set(self.joint_names)) != 2: + raise ValueError(f"GazeRigCfg.joint_names must name two joints, got {self.joint_names!r}.") + if len(self.joint_signs) != 2 or any(sign not in (-1.0, 1.0) for sign in self.joint_signs): + raise ValueError(f"GazeRigCfg.joint_signs must be two signs, each 1 or -1, got {self.joint_signs!r}.") + @configclass class GazeActionCfg(ActionTermCfg): @@ -25,19 +52,39 @@ class GazeActionCfg(ActionTermCfg): class_type: type[GazeAction] | str = "{DIR}.gaze:GazeAction" asset_name: str = MISSING """Scene name of the foveated camera whose gaze the action moves.""" + mode: str = "software" + """``"software"``, ``"physical"``, ``"hybrid"``, or ``"dual"`` (experimental): what the actions turn.""" + rig: GazeRigCfg | None = None + """The articulation that turns the camera; needed by every mode but software gaze.""" 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.""" + """Largest distance of the software 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.""" + """Start episodes at a random software 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).""" + """Teacher's mount: ``"fixed"`` at the action's creation, or ``"tracked"`` on a moving body.""" - def validate_config(self): - """Reject gaze bounds that would divide by zero and unknown mounts.""" + def validate_config(self) -> None: + """Reject invalid gaze bounds, modes and mounts, and rig settings that a mode cannot use.""" 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): + if not _positive_finite(value): 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}.") + if self.mode not in GAZE_MODES: + raise ValueError(f"GazeActionCfg.mode must be one of {GAZE_MODES}, got {self.mode!r}.") + if self.mode == "software": + return + if self.rig is None: + raise ValueError(f"GazeActionCfg.mode={self.mode!r} turns a rig's joints; set GazeActionCfg.rig.") + if self.mount != "tracked": + raise ValueError(f"GazeActionCfg.mode={self.mode!r} moves the camera's mount; set mount='tracked'.") + if self.random_reset: + raise ValueError("GazeActionCfg.random_reset applies only to software gaze.") + self.rig.validate_config() + + +def _positive_finite(value: object) -> bool: + """Whether ``value`` is a finite real number above zero; strings and other types are not.""" + return isinstance(value, (int, float)) and math.isfinite(value) and value > 0 diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 7fa4f9f2d5ab..e51bbbc9311e 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -107,6 +107,8 @@ class FoveatedCamera(Camera): cfg: FoveatedCameraCfg + gaze_writes: int = 0 + """How many times :meth:`set_gaze_angles` has been called, so a gaze action can tell another caller's writes.""" _renders_switchable_rays: ClassVar[bool] = False """Whether the renderer traces rays the camera can replace while it runs, as :meth:`set_cmf_a` needs.""" @@ -226,15 +228,35 @@ 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. + It follows a mount that moves, for example a camera on a robot's head. Cameras whose pose update turns the + gaze (Newton and OVRTX) refresh it in each pose update; cameras that hold the gaze in their prims (Isaac RTX) + refresh it in :meth:`update_mount`. """ - 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 + @property + def mount_pos_w(self) -> ProxyArray: + """World position [m] of the physical camera as of its last pose update, shape (num_envs,) of ``vec3f``. + + Reading it captures no image, unlike ``data.pos_w``; :meth:`update_mount` refreshes it. + """ + return self._data.pos_w + + def update_mount(self) -> ProxyArray: + """Read the camera's pose now, without capturing an image, and return :attr:`mount_quat_w_ros`. + + A lazily updated camera reads its pose only when its data is read, so its recorded mount and + :attr:`mount_pos_w` may be a step old. + """ + mount = self.mount_quat_w_ros + self._update_poses() + if not self._gaze_pose_reads_angles: + # The prims hold the gaze, which the reported pose leaves out. + mount.torch.copy_(self.get_world_poses(convention="ros")[1]) + return mount + @property def supports_runtime_cmf_a(self) -> bool: """Whether :meth:`set_cmf_a` can change this camera's foveation while it runs: on Newton, for retinas whose @@ -253,6 +275,7 @@ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: Raises: ValueError: The angles do not hold one row per camera. """ + self.gaze_writes += 1 stored = self._gaze_angles is not None and angles_deg is self._gaze_angles.torch if stored and self.turns_pose_by_gaze: # The next pose update reads the stored angles; nothing has to happen now. diff --git a/source/isaaclab_fovi/pyproject.toml b/source/isaaclab_fovi/pyproject.toml index b182018f8f78..42e07db11745 100644 --- a/source/isaaclab_fovi/pyproject.toml +++ b/source/isaaclab_fovi/pyproject.toml @@ -36,4 +36,4 @@ where = ["."] include = ["isaaclab_fovi", "isaaclab_fovi.*"] [tool.setuptools.package-data] -"*" = ["*.pyi"] +"*" = ["*.pyi", "*.usda"] diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py index ad53e65feed4..64692c3054f3 100644 --- a/source/isaaclab_fovi/test/foveated_render_cases.py +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -284,6 +284,98 @@ def foveated_camera_samples_densest_at_the_fixation(ground: GroundScene): assert float((errors < 0.03).float().mean()) < 0.5 +def hybrid_gaze_turns_the_head_onto_the_fixation(backend: tuple): + """Hybrid gaze on the pan-tilt mount: the retina turns at once, then the joints carry the camera onto the fixation. + + The policy pans left three full steps, then holds. The retina leads while the head turns; the head then ends on + the commanded fixation, the retina back on the optical axis, and the camera's world axis turned with the head. + A reset brings the joint targets and the gaze back to the rig's default pose. + """ + from isaaclab_fovi.assets import PAN_TILT_CAMERA_OFFSET, PAN_TILT_CFG + from isaaclab_fovi.mdp import GazeActionCfg, GazeRigCfg, gaze_state + + from isaaclab.envs import ManagerBasedEnv, ManagerBasedEnvCfg + from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg + from isaaclab.utils.math import quat_apply + + physics_cfg, renderer_cfg, _ = backend + + @configclass + class SceneCfg(InteractiveSceneCfg): + rig = PAN_TILT_CFG.replace(init_state=PAN_TILT_CFG.init_state.replace(pos=(0.0, 0.0, 0.5))) + eye = FoveatedCameraCfg( + prim_path="{ENV_REGEX_NS}/PanTilt/Geometry/world/pan_link/tilt_link/Eye", + data_types=["distance_to_camera"], + renderer_cfg=renderer_cfg(), + spawn=sim_utils.PinholeCameraCfg(clipping_range=CLIPPING_RANGE), + foveated_res=16, + offset=PAN_TILT_CAMERA_OFFSET, + ) + + @configclass + class ActionsCfg: + gaze = GazeActionCfg(asset_name="eye", mode="hybrid", mount="tracked", rig=GazeRigCfg(asset_name="rig")) + + @configclass + class ObservationsCfg: + @configclass + class PolicyCfg(ObservationGroupCfg): + gaze = ObservationTermCfg(func=gaze_state) + + policy = PolicyCfg() + + @configclass + class EnvCfg(ManagerBasedEnvCfg): + decimation = 4 + scene = SceneCfg(num_envs=1, env_spacing=5.0) + actions = ActionsCfg() + observations = ObservationsCfg() + ui_window_class_type = None + sim = SimulationCfg(dt=1 / 120, physics=physics_cfg, device=DEVICE) + + sim_utils.create_new_stage() + env = ManagerBasedEnv(EnvCfg()) + try: + env.reset() + term = env.action_manager.get_term("gaze") + camera, rig = env.scene["eye"], env.scene["rig"] + joints = rig.find_joints(["pan_joint", "tilt_joint"], preserve_order=True)[0] + + def pan_deg(): + """The head's pan, the retina's pan and the camera's world yaw, left of the start [deg].""" + axis = quat_apply(camera.data.quat_w_ros.torch[:1], torch.tensor([[0.0, 0.0, 1.0]], device=env.device)) + yaw = math.degrees(math.atan2(-float(axis[0, 0]), float(axis[0, 1]))) + head = math.degrees(float(rig.data.joint_pos.torch[0, joints[0]])) + return head, float(camera.gaze_angles.torch[0, 1]), yaw + + commanded = 3 * term.cfg.step_size * term.field_radius_deg + pan_left = torch.tensor([[0.0, 1.0]], device=env.device) + # Nothing reads the camera between steps, so it updates lazily: the gaze must read the head's pose itself. + for _ in range(3): + env.step(pan_left) + head, retina, fixation = pan_deg() + # The retina leads the head, and the fixation is already near the command. + assert retina > head + assert fixation == pytest.approx(commanded, abs=1.5) + for _ in range(30): + env.step(torch.zeros_like(pan_left)) + head, retina, fixation = pan_deg() + assert head == pytest.approx(commanded, abs=0.2) + assert retina == pytest.approx(0.0, abs=0.2) + assert fixation == pytest.approx(commanded, abs=0.2) + assert float(term.state[0, 1]) == pytest.approx(3 * term.cfg.step_size, abs=0.005) + + env.reset() + assert not camera.gaze_angles.torch.any() + assert not term.state.any() + # From the reset, a step without gaze commands the rig to stay at its default pose. + env.step(torch.zeros_like(pan_left)) + targets = rig.data.joint_pos_target.torch[0, joints] + torch.testing.assert_close(targets, torch.zeros_like(targets), atol=1e-3, rtol=0) + finally: + env.close() + + def cmf_a_switches_the_retina_at_runtime(ground: GroundScene): """Newton re-samples the retina for a new CMF constant in place: each sample renders along its new ray, the outputs keep their shape, and switching back restores the first image. Building the camera added its viewer controls.""" diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py index 43de48eb44d9..cfb8cad580c0 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -13,24 +13,37 @@ import warp as wp from fovi.sensing.projection import CameraModel from isaaclab_fovi.mdp.gaze import ( + DUAL, + HYBRID, + PHYSICAL, GazeAction, gaze_reset_kernel, gaze_state, gaze_step_kernel, gaze_teacher_labels, + make_rig_gaze_step, + target_body_index, ) -from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg +from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg, GazeRigCfg from isaaclab_fovi.sensors.gaze_kernels import camera_params, torch_stream from isaaclab.managers import ObservationTermCfg, SceneEntityCfg from isaaclab.test.utils import DeviceScope, test_devices -from isaaclab.utils.math import quat_apply, quat_apply_inverse +from isaaclab.utils.math import quat_apply, quat_apply_inverse, quat_from_angle_axis, quat_mul from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.kitless DEVICES = test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA) +# The rig cases: a 45-degree field radius, and a rig whose pan joint is 1 and tilt joint 0 of three, with sign -1. +FIELD_RADIUS = 45.0 +RADIUS_RAD = math.radians(FIELD_RADIUS) +STEP, LIMIT, HEAD_STEP = 0.1, 1.0, 0.05 +JOINTS, SIGNS = (1, 0), (1.0, -1.0) +PINHOLE = CameraModel("pinhole", (480, 640), (200.0, 200.0, 319.5, 239.5)) +"""A wide pinhole for the rig teacher, so its targets stay in view.""" + 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.""" @@ -49,6 +62,119 @@ def clamp_gaze(gaze: torch.Tensor, limit: float) -> torch.Tensor: return gaze * (limit / gaze.norm(dim=-1, keepdim=True).clamp_min(limit)) +def turn(tilt_deg: float, pan_deg: float) -> torch.Tensor: + """The rotation (x, y, z, w), ROS camera frame, that pans left by ``pan_deg`` about the up axis (-y) and then tilts + up by ``tilt_deg`` about the turned x axis, as a pan-tilt head or a retina does.""" + pan = quat_from_angle_axis(torch.tensor([math.radians(pan_deg)]), torch.tensor([[0.0, -1.0, 0.0]])) + tilt = quat_from_angle_axis(torch.tensor([math.radians(tilt_deg)]), torch.tensor([[1.0, 0.0, 0.0]])) + return quat_mul(pan, tilt) + + +def yaw_left(degrees: float) -> torch.Tensor: + """A camera mount (x, y, z, w), ROS convention, turned left by ``degrees``: about the camera's up axis, -y.""" + half = math.radians(degrees) / 2 + return torch.tensor([[0.0, -math.sin(half), 0.0, math.cos(half)]]) + + +class RigStep: + """One camera's rig stepped by :func:`make_rig_gaze_step`'s kernel.""" + + def __init__(self, mode: int, joint_pos=(0.1, 0.0, 0.0)): + self.mode = mode + self.joint_pos = torch.tensor([joint_pos]) + self.limits = torch.tensor([[[-0.5, 0.5], [-0.2, 0.2], [-1.0, 1.0]]]) + self.mount = yaw_left(0.0) + # Only hybrid gaze holds a fixation; the other modes get empty buffers, as the term gives them. + held = 1 if mode == HYBRID else 0 + self.held = torch.zeros(held, 3) + self.held_valid = torch.zeros(held, dtype=torch.int32) + self.angles = torch.zeros(1, 2) + self.state = torch.zeros(1, 4) + self.targets = torch.zeros(1, 2) + + def __call__(self, actions) -> None: + with torch_stream("cpu"): + wp.launch( + make_rig_gaze_step(self.mode), + dim=1, + inputs=[ + wp.from_torch(torch.tensor([actions], dtype=torch.float32)), + wp.from_torch(self.joint_pos), + wp.from_torch(self.limits, dtype=wp.vec2f), + wp.vec2i(*JOINTS), + wp.vec2f(*SIGNS), + wp.from_torch(self.mount, dtype=wp.quatf), + STEP, + LIMIT, + HEAD_STEP, + 0.5, + FIELD_RADIUS, + ], + outputs=[ + wp.from_torch(self.held, dtype=wp.vec3f), + wp.from_torch(self.held_valid), + wp.from_torch(self.angles, dtype=wp.vec2f), + wp.from_torch(self.state, dtype=wp.vec4f), + wp.from_torch(self.targets), + ], + ) + + +class _Camera: + """The parts of a foveated camera a rig gaze action uses, which counts its gaze writes as the camera does.""" + + def __init__(self, mount: torch.Tensor): + self.gaze_angles = ProxyArray(wp.zeros(1, dtype=wp.vec2f, device="cpu")) + self.mount = ProxyArray(wp.from_torch(mount.contiguous(), dtype=wp.quatf)) + self.gaze_writes = 0 + self.mount_pos_w = ProxyArray(wp.zeros(1, dtype=wp.vec3f, device="cpu")) + self.image_frame = wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) + self.projection_params = camera_params(PINHOLE) + + def set_gaze_angles(self, angles: torch.Tensor) -> None: + self.gaze_writes += 1 + self.gaze_angles.torch.copy_(angles) + + def update_mount(self) -> ProxyArray: + return self.mount + + @property + def mount_quat_w_ros(self) -> ProxyArray: + return self.mount + + +def rig_term(mode: str, joint_pos=(0.0, 0.0, 0.0), mount: torch.Tensor | None = None) -> GazeAction: + """A rig gaze action of one environment, built through its own rig setup on a stand-in rig and camera.""" + joint_pos = torch.tensor([joint_pos]) + rig = SimpleNamespace( + find_joints=lambda names, preserve_order: (list(JOINTS), list(names)), + data=SimpleNamespace( + joint_pos=ProxyArray(wp.from_torch(joint_pos)), + default_joint_pos=ProxyArray(wp.from_torch(torch.zeros(1, 3))), + soft_joint_pos_limits=ProxyArray(wp.from_torch(torch.tensor([[[-1.0, 1.0]] * 3]), dtype=wp.vec2f)), + ), + ) + term = object.__new__(GazeAction) + term._env = SimpleNamespace(num_envs=1, device="cpu", step_dt=0.5, scene={"rig": rig}) + term.cfg = GazeActionCfg( + asset_name="eye", + mode=mode, + mount="tracked", + step_size=STEP, + rig=GazeRigCfg(asset_name="rig", joint_signs=SIGNS, max_step_deg=HEAD_STEP * FIELD_RADIUS), + ) + term._asset = _Camera(yaw_left(0.0) if mount is None else mount) + term.tracked_mount = True + term.field_radius_deg = FIELD_RADIUS + term._state = ProxyArray(wp.zeros(1, dtype=wp.vec4f, device="cpu")) + term._velocity = term._state.torch[:, 2:] + term._raw = None + term._heads = ProxyArray(wp.zeros(1, dtype=wp.vec4f, device="cpu")) + term._own_gaze_writes = 0 + term._init_rig(term._env) + return term + + @pytest.mark.parametrize(("device", "body_id"), [("cpu", None), (DEVICES[-1] if DEVICES else "cpu", 1)]) def test_teacher_labels_and_diagnostics_match_the_torch_reference(device, body_id): # The root case checks fixation from rest through a roll over 90 degrees. The body case exercises clamping @@ -104,8 +230,12 @@ def teachable(direction: torch.Tensor) -> torch.Tensor: bodies = torch.stack((torch.zeros_like(poses), poses), dim=1) asset_data = SimpleNamespace(body_pose_w=ProxyArray(wp.from_torch(bodies, dtype=wp.transformf))) mounts = ProxyArray(wp.from_torch(mount.to(device), dtype=wp.quatf)) + # Software gaze labels the retina from its stored angles, so the head and the fixation go unused. + heads = ProxyArray(wp.zeros(count, dtype=wp.vec4f, device=device)) + empty_held = ProxyArray(wp.zeros(0, dtype=wp.vec3f, device=device)) + empty_valid = ProxyArray(wp.zeros(0, dtype=wp.int32, device=device)) sensor = SimpleNamespace( - data=SimpleNamespace(pos_w=ProxyArray(wp.from_torch(positions.to(device), dtype=wp.vec3f))), + mount_pos_w=ProxyArray(wp.from_torch(positions.to(device), dtype=wp.vec3f)), gaze_angles=ProxyArray(wp.from_torch((gaze * field_radius).to(device), dtype=wp.vec2f)), image_frame=wp.mat33f(*frame.flatten().tolist()), projection_params=camera_params(camera), @@ -113,6 +243,8 @@ def teachable(direction: torch.Tensor) -> torch.Tensor: gaze_term = SimpleNamespace( camera=sensor, teacher_mounts=lambda: mounts, + head_and_target=lambda: heads, + held_fixation=lambda: (empty_held, empty_valid), field_radius_deg=field_radius, cfg=GazeActionCfg(asset_name="camera", step_size=step), ) @@ -153,6 +285,26 @@ def test_gaze_config_rejects_bounds_that_divide_by_zero_and_unknown_mounts(): cfg.validate_config() # The config names its term lazily, so Isaac Lab's action manager resolves it to the gaze action. assert GazeActionCfg(asset_name="camera").class_type._resolve() is GazeAction + # The modes that turn a rig need one, and a tracked mount since the rig moves the camera. + rig = GazeRigCfg(asset_name="rig") + GazeActionCfg(asset_name="camera", mode="hybrid", rig=rig, mount="tracked").validate_config() + for changes, message in ( + (dict(mode="saccade"), "mode"), + (dict(mode="physical", mount="tracked"), "rig"), + (dict(mode="hybrid", rig=rig), "tracked"), + (dict(mode="dual", rig=rig, mount="tracked", random_reset=True), "random_reset"), + (dict(mode="hybrid", rig=GazeRigCfg(asset_name="rig", joint_signs=(1.0, 0.5)), mount="tracked"), "signs"), + ): + with pytest.raises(ValueError, match=message): + GazeActionCfg(asset_name="camera", **changes).validate_config() + # The rig checks its own fields, alone as well as inside the action's config. + for changes, message in ( + (dict(joint_signs=(1.0,)), "signs"), + (dict(joint_names=("pan_joint", "pan_joint")), "joint_names"), + (dict(max_step_deg=0.0), "max_step_deg"), + ): + with pytest.raises(ValueError, match=message): + GazeRigCfg(asset_name="rig", **changes).validate_config() def test_process_actions_moves_the_gaze_by_the_supplied_actions(): @@ -169,7 +321,7 @@ def test_process_actions_moves_the_gaze_by_the_supplied_actions(): 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._step_launch = term._raw = None + term._step_launch = term._raw = term.rig = 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]]) @@ -260,8 +412,173 @@ def test_fixed_mount_teacher_rejects_only_turns_after_capture(): term.tracked_mount = False term._mount_turns = 2 term._fixed_mount = "captured" - term._asset = SimpleNamespace(mount_turns=2) + pose_reads = [] + term._asset = SimpleNamespace(mount_turns=2, update_mount=lambda: pose_reads.append(1)) assert GazeAction.teacher_mounts(term) == "captured" + # The teacher aims from the camera's position now, so a fixed mount reads the pose too. + assert len(pose_reads) == 1 term._asset.mount_turns = 3 with pytest.raises(RuntimeError, match="mount='tracked'"): GazeAction.teacher_mounts(term) + + +# -- Gaze modes that turn a rig ---------------------------------------------------------------------------------------- + + +def test_physical_gaze_steps_the_joint_targets_and_leaves_the_retina_alone(): + rig = RigStep(PHYSICAL, joint_pos=(0.0, 0.0, 0.0)) + # The head lags its last targets (pan, tilt) = (0.05, 0.1): each step adds to the targets, not the measured joints. + rig.targets[0] = torch.tensor([0.05, 0.1]) + # Tilt up a full step, pan left half a step (pan joint 1, tilt joint 0 with sign -1). + rig([1.0, 0.5]) + torch.testing.assert_close(rig.targets[0], torch.tensor([0.05 + 0.5 * STEP * RADIUS_RAD, 0.1 - STEP * RADIUS_RAD])) + assert not rig.angles.any() + # The state is the measured head's gaze: (tilt, pan) = (-tilt joint, pan joint) in field radii. + rig.joint_pos[0, :2] = torch.tensor([0.1, 0.05]) + rig([0.0, 0.0]) + torch.testing.assert_close(rig.state[0, :2], torch.tensor([-0.1, 0.05]) / RADIUS_RAD) + # A large step stops at the joint limits: tilt joint 0 within [-0.5, 0.5], pan joint 1 within [-0.2, 0.2]. + rig.targets[0] = torch.tensor([0.18, -0.45]) + rig([3.0, 3.0]) + torch.testing.assert_close(rig.targets[0], torch.tensor([0.2, -0.5])) + + +def test_hybrid_gaze_moves_the_retina_at_once_and_holds_the_fixation_while_the_head_follows(): + rig = RigStep(HYBRID, joint_pos=(0.0, 0.0, 0.0)) + rig([0.0, 1.0]) # pan left a full step + # The retina turns at once; the head steps toward it by at most HEAD_STEP. + torch.testing.assert_close(rig.angles[0], torch.tensor([0.0, STEP * FIELD_RADIUS])) + torch.testing.assert_close(rig.targets[0], torch.tensor([HEAD_STEP * RADIUS_RAD, 0.0])) + # The head turns left by 3 degrees before the next step: the retina comes back by as much, so the fixation holds. + rig.mount = yaw_left(3.0) + rig.joint_pos[0, 1] = math.radians(3.0) + rig([0.0, 0.0]) + torch.testing.assert_close(rig.angles[0], torch.tensor([0.0, STEP * FIELD_RADIUS - 3.0]), atol=1e-4, rtol=0) + torch.testing.assert_close(rig.state[0, :2], torch.tensor([0.0, STEP]), atol=1e-5, rtol=0) + # From where it is, the head steps the remaining 1.5 degrees (under HEAD_STEP) onto the fixation. + pan_target = math.radians(STEP * FIELD_RADIUS) + torch.testing.assert_close(rig.targets[0, 0], torch.tensor(pan_target), atol=1e-5, rtol=0) + + +def test_hybrid_gaze_starts_a_new_fixation_when_the_camera_gaze_is_set_directly(): + term = rig_term("hybrid") + camera = term.camera + term.process_actions(torch.tensor([[0.0, 1.0]])) # pan the retina left a full step + first = camera.gaze_angles.torch.clone() + # The head turns left 1 degree before the next step, which aims the retina back by as much. + camera.mount = ProxyArray(wp.from_torch(yaw_left(1.0).contiguous(), dtype=wp.quatf)) + term.process_actions(torch.zeros(1, 2)) + torch.testing.assert_close(camera.gaze_angles.torch, first - torch.tensor([[0.0, 1.0]]), atol=1e-4, rtol=0) + # Setting the gaze through the camera, even to the angles it holds, starts a new fixation there: the head turns + # again, and the retina stays where it was set rather than being aimed back at the old fixation. + held = camera.gaze_angles.torch.clone() + camera.set_gaze_angles(held.clone()) + camera.mount = ProxyArray(wp.from_torch(yaw_left(2.0).contiguous(), dtype=wp.quatf)) + term.process_actions(torch.zeros(1, 2)) + torch.testing.assert_close(camera.gaze_angles.torch, held, atol=1e-5, rtol=0) + + +def test_dual_gaze_moves_the_head_and_the_retina_independently_and_composes_them(): + rig = RigStep(DUAL, joint_pos=(0.0, 0.0, 0.0)) + rig([0.0, 1.0, 1.0, 0.0]) # the head pans left, the retina tilts up + torch.testing.assert_close(rig.targets[0], torch.tensor([STEP * RADIUS_RAD, 0.0])) + torch.testing.assert_close(rig.angles[0], torch.tensor([STEP * FIELD_RADIUS, 0.0])) + # With the head tilted up 20 degrees, the retina pans left 30: the observed gaze is the direction the turns + # compose to from the rig's zero pose, by quaternion composition, not the sum of their angles. + rig.joint_pos[0, 0] = -math.radians(20.0) # tilt joint 0 turns the camera up with sign -1 + rig.angles[0] = torch.tensor([0.0, 30.0]) + rig([0.0, 0.0, 0.0, 0.0]) + direction = quat_apply(quat_mul(turn(20.0, 0.0), turn(0.0, 30.0)), torch.tensor([[0.0, 0.0, 1.0]])) + composed = direction_to_angles(direction)[0] / FIELD_RADIUS + torch.testing.assert_close(rig.state[0, :2], composed, atol=1e-5, rtol=0) + assert not torch.allclose(composed, torch.tensor([20.0, 30.0]) / FIELD_RADIUS, atol=1e-3) + + +def test_physical_teacher_labels_only_the_head_turn_not_yet_commanded(): + # The head stands tilted up 20 degrees, and its joint targets already command a 5-degree pan left. + term = rig_term("physical", joint_pos=(-math.radians(20.0), 0.0, 0.0), mount=turn(20.0, 0.0)) + term._targets.torch[0] = torch.tensor([math.radians(5.0), -math.radians(20.0)]) # (pan, tilt) + torch.testing.assert_close( + term.head_and_target().torch[0], torch.tensor([20.0, 0.0, 20.0, 5.0]) / FIELD_RADIUS, atol=1e-6, rtol=0 + ) + # A point 22 degrees up and 7 left of the rig's zero pose. + point = quat_apply(turn(22.0, 7.0), torch.tensor([[0.0, 0.0, 1.0]])) + pose = torch.cat((point, torch.tensor([[0.0, 0.0, 0.0, 1.0]])), dim=-1) + target = SimpleNamespace(data=SimpleNamespace(root_pose_w=ProxyArray(wp.from_torch(pose, dtype=wp.transformf)))) + env = SimpleNamespace( + device="cpu", + num_envs=1, + scene={"target": target}, + action_manager=SimpleNamespace(get_term=lambda name: term), + extras={}, + ) + labels = gaze_teacher_labels(ObservationTermCfg(func=gaze_teacher_labels), env)(env, SceneEntityCfg("target")) + assert labels[0, 2] == 1.0 + # Adding the label to the commanded head faces the point exactly, so the label leaves out the queued 5 degrees. + tilt, pan = (torch.tensor([20.0, 5.0]) + labels[0, :2] * STEP * FIELD_RADIUS).tolist() + facing = quat_apply(turn(tilt, pan), torch.tensor([[0.0, 0.0, 1.0]])) + torch.testing.assert_close(facing, point, atol=1e-5, rtol=0) + + +def test_hybrid_teacher_labels_from_the_gaze_the_next_step_starts_at(): + term = rig_term("hybrid") + camera = term.camera + term.process_actions(torch.tensor([[0.0, 1.0]])) # the retina pans left a full step onto a fixation + fixation = quat_apply(yaw_left(0.0), angles_to_direction(camera.gaze_angles.torch)) + # The head turns left 3 degrees after the step; the fixation, and a target on it, stay where they are. + camera.mount = ProxyArray(wp.from_torch(yaw_left(3.0).contiguous(), dtype=wp.quatf)) + pose = torch.cat((2.0 * fixation, torch.tensor([[0.0, 0.0, 0.0, 1.0]])), dim=-1) + target = SimpleNamespace(data=SimpleNamespace(root_pose_w=ProxyArray(wp.from_torch(pose, dtype=wp.transformf)))) + env = SimpleNamespace( + device="cpu", + num_envs=1, + scene={"target": target}, + action_manager=SimpleNamespace(get_term=lambda name: term), + extras={}, + ) + labels = gaze_teacher_labels(ObservationTermCfg(func=gaze_teacher_labels), env)(env, SceneEntityCfg("target")) + # The next step re-aims the retina at the fixation itself, so the teacher asks for no further turn; labelling + # from the retina's last angles would count the head's turn twice and ask for 3 degrees back. + assert labels[0, 2] == 1.0 + torch.testing.assert_close(labels[0, :2], torch.zeros(2), atol=1e-4, rtol=0) + term.process_actions(labels[:, :2].clone()) + looking = quat_apply(yaw_left(3.0), angles_to_direction(camera.gaze_angles.torch)) + torch.testing.assert_close(looking, fixation, atol=1e-5, rtol=0) + + +def test_teacher_target_body_resolves_a_slice_of_every_body(): + assert target_body_index(SceneEntityCfg("target")) is None + named = SceneEntityCfg("target", body_names=["pole"]) + named.body_ids = [2] + assert target_body_index(named) == 2 + # Naming every body of the asset, as naming a rigid object's only body does, resolves to a slice. + named.body_ids = slice(None) + assert target_body_index(named) == 0 + + +def test_teacher_labels_world_points_as_it_labels_an_asset_there(): + # Each environment picks its own point, as a command that chooses one object among several does. + term = rig_term("physical", joint_pos=(0.0, 0.0, 0.0), mount=turn(0.0, 0.0)) + points = quat_apply(turn(10.0, -6.0), torch.tensor([[0.0, 0.0, 1.0]])) + pose = torch.cat((points, torch.tensor([[0.0, 0.0, 0.7071068, 0.7071068]])), dim=-1) + asset = SimpleNamespace(data=SimpleNamespace(root_pose_w=ProxyArray(wp.from_torch(pose, dtype=wp.transformf)))) + env = SimpleNamespace( + device="cpu", + num_envs=1, + scene={"target": asset}, + action_manager=SimpleNamespace(get_term=lambda name: term), + extras={}, + ) + teacher = gaze_teacher_labels(ObservationTermCfg(func=gaze_teacher_labels), env) + expected = teacher(env, SceneEntityCfg("target")).clone() + assert expected[0, 2] == 1.0 and expected[0, :2].abs().min() > 0 + torch.testing.assert_close(teacher(env, target_w=lambda env: points), expected) + # The offset of a world point runs along the world axes, not the turned asset's. + shifted = teacher(env, target_w=lambda env: points - torch.tensor([[0.0, 0.2, 0.0]]), offset=(0.0, 0.2, 0.0)) + torch.testing.assert_close(shifted, expected) + with pytest.raises(ValueError, match="one target"): + teacher(env) + with pytest.raises(ValueError, match="one target"): + teacher(env, SceneEntityCfg("target"), target_w=lambda env: points) + with pytest.raises(ValueError, match=r"shape \(1, 3\)"): + teacher(env, target_w=lambda env: points[0]) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index ed649a08a794..5eec813832e6 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -46,6 +46,14 @@ def backend_cfg(name: str): return BACKENDS[name] +@pytest.mark.parametrize("backend", ["newton_warp", "isaac_rtx"]) +def test_hybrid_gaze_turns_the_head_onto_the_fixation(backend): + # Gaze that turns a rig tracks the camera's mount: Newton turns the pose it reads by the gaze, and Isaac RTX reads + # the mount back from the camera prim, which holds the gaze. The case builds its own environment around the rig, + # so it runs before the shared ground scenes below. + cases.hybrid_gaze_turns_the_head_onto_the_fixation(backend_cfg(backend)) + + @pytest.fixture(scope="module", params=list(BACKENDS)) def ground(request): """One ground scene per backend, which every case below renders in turn."""