diff --git a/docs/source/_static/overview/sensors/foveated_camera_binocular.jpg b/docs/source/_static/overview/sensors/foveated_camera_binocular.jpg new file mode 100644 index 000000000000..a07de210e082 Binary files /dev/null and b/docs/source/_static/overview/sensors/foveated_camera_binocular.jpg differ 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..2dc2852595bc --- /dev/null +++ b/docs/source/api/lab_fovi/isaaclab_fovi.assets.rst @@ -0,0 +1,46 @@ +isaaclab_fovi.assets +==================== + +.. automodule:: isaaclab_fovi.assets + + .. rubric:: Classes + + .. autosummary:: + + PanTiltCfg + + .. rubric:: Functions + + .. autosummary:: + + spawn_pan_tilt + + .. rubric:: Data + + .. autosummary:: + + PAN_TILT_CFG + PAN_TILT_CAMERA_OFFSET + PAN_TILT_STEREO_OFFSETS + PAN_TILT_STEREO_BASELINE + +Pan-tilt mount +-------------- + +.. autodata:: PAN_TILT_CFG + :no-value: + +.. autodata:: PAN_TILT_CAMERA_OFFSET + :no-value: + +.. autodata:: PAN_TILT_STEREO_OFFSETS + :no-value: + +.. autodata:: PAN_TILT_STEREO_BASELINE + +.. autoclass:: PanTiltCfg + :members: + :show-inheritance: + :exclude-members: __init__, func + +.. autofunction:: spawn_pan_tilt diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst index 779ad564d64a..1e58f3eb1705 100644 --- a/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst +++ b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst @@ -9,13 +9,19 @@ isaaclab_fovi.mdp GazeAction GazeActionCfg + GazeRigCfg + BinocularGazeAction + BinocularGazeActionCfg gaze_teacher_labels + binocular_gaze_teacher_labels .. rubric:: Functions .. autosummary:: gaze_state + binocular_gaze_state + binocular_gaze_angles Actions ------- @@ -30,6 +36,23 @@ Actions :show-inheritance: :exclude-members: __init__, class_type +.. autoclass:: GazeRigCfg + :members: + :show-inheritance: + :exclude-members: __init__ + +.. autoclass:: BinocularGazeAction + :members: + :show-inheritance: + +.. autoclass:: BinocularGazeActionCfg + :members: + :inherited-members: + :show-inheritance: + :exclude-members: __init__, class_type + +.. autofunction:: binocular_gaze_angles + Observations ------------ @@ -37,3 +60,8 @@ Observations .. autoclass:: gaze_teacher_labels :show-inheritance: + +.. autofunction:: binocular_gaze_state + +.. autoclass:: binocular_gaze_teacher_labels + :show-inheritance: diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst index 064c45720a77..5f6a4e5e5383 100644 --- a/docs/source/experimental-features/foveated_camera.rst +++ b/docs/source/experimental-features/foveated_camera.rst @@ -19,9 +19,11 @@ The Newton viewer shows the camera's image, the foveated camera's cortical view a window that shows the fisheye on a curved viewing sphere beside that view: the green lens boundary follows the camera mount, and the blue gaze circle and sampling grid show the retina's coverage. Use WASD or the arrow keys to move the camera and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze. Below -the side panel's Camera Source selector, gaze sliders follow the gaze and set it, and on Newton a foveation slider -steps the CMF constant, through other stops with ``--cmf_a_values 0.2,2,20`` plus the camera's own. H shows or hides -the viewer controls. Pass ``--target power_drill`` to start fixating the drill. +the side panel's Camera Source selector, gaze sliders follow the gaze and set it, a checkbox draws an eyeball at the +camera, turned with its gaze, in the perspective view, and on Newton a foveation slider steps the CMF constant, through +other stops with ``--cmf_a_values 0.2,2,20`` plus the camera's own. H shows or hides the viewer controls. Every +foveated camera has these controls in the Newton viewer; the eyeball is its debug visualization, which +``debug_vis=True`` turns on from the start. Pass ``--target power_drill`` to start fixating the drill. .. figure:: ../_static/overview/sensors/foveated_camera_overview.jpg :alt: A retina behind a 180-degree fisheye lens on the viewing sphere, and its rendered images at two fixations. @@ -140,3 +142,98 @@ 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/base/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. + +.. _concepts_sensors_foveated_camera_binocular: + +Binocular gaze +-------------- + +:class:`~mdp.BinocularGazeActionCfg` moves two foveated cameras on one body with three actions: the version, their +shared line of sight (tilt, pan), and the vergence, the angle between their lines of sight. Each eye turns from the +version by half the vergence toward the other, in the plane of the version and the baseline, so with any vergence +above zero the lines of sight meet; at zero they are parallel. The version moves as a single camera's gaze does in +``"software"``, ``"physical"`` or ``"hybrid"`` mode; the vergence always turns the retinas. The eyes need one body +to carry them, parallel optical axes and the same retina. :data:`~assets.PAN_TILT_STEREO_OFFSETS` +places two eyes 6.5 cm apart on the pan-tilt mount: + +.. code-block:: python + + from isaaclab_fovi.assets import PAN_TILT_STEREO_OFFSETS + from isaaclab_fovi.mdp import BinocularGazeActionCfg + + link = "{ENV_REGEX_NS}/PanTilt/base/pan_link/tilt_link" + left_eye = eye.replace(prim_path=f"{link}/LeftEye", offset=PAN_TILT_STEREO_OFFSETS[0]) + right_eye = eye.replace(prim_path=f"{link}/RightEye", offset=PAN_TILT_STEREO_OFFSETS[1]) + gaze = BinocularGazeActionCfg( + asset_name="left_eye", right_asset_name="right_eye", mode="hybrid", rig=GazeRigCfg(asset_name="rig") + ) + +:func:`~mdp.binocular_gaze_state` observes the version, the vergence and their velocities, and +:class:`~mdp.binocular_gaze_teacher_labels` labels the actions that fixate a point with both eyes. Without an action +term, :func:`~mdp.binocular_gaze_angles` turns a version and a vergence into each eye's gaze, as the action does. + +With ``--stereo``, the ``foveated-camera`` example looks at the scene above through two free eyes, 6.5 cm apart and +each drawn as an eyeball, in software binocular gaze: the teacher's labels move both retinas onto the fixation the +controls set. Its viewer opens on a perspective view that draws each eye's line of sight and the point where they meet, +and a window shows both eyes' cortical views. The side panel's sliders set the version and the vergence, a button +glides the fixation onto the next object, and checkboxes hide or show that overlay and the eyeballs; I/J/K/L, or a drag +in the eyes' window, turn the version, and U/O converge and diverge the eyes. A slider moves the eyes apart, from 2 to +30 cm, which changes their disparity while they keep the fixation. On Newton, a foveation slider steps both eyes' CMF +constant. + +With ``--galbot`` as well, the eyes are the two lenses, 6 cm apart, of a Galbot G1 from Nucleus, in hybrid binocular +gaze: the robot's neck turns after the version. Only the neck moves; every other joint holds a standing pose. The lenses +are fixed on the head, so the eyes have no eyeballs and no separation slider: + +.. code-block:: bash + + uv run --extra fovi isaaclab example foveated-camera --stereo --target banana + uv run --extra fovi isaaclab example foveated-camera --stereo --galbot --target banana + +.. figure:: ../_static/overview/sensors/foveated_camera_binocular.jpg + :alt: Left and right eye images at four fixations, with the version, head pan and vergence over time. + + Two eyes on the pan-tilt mount in hybrid gaze, stepped by the teacher's labels between four objects. The fixated + object sits in both foveas, the version jumps to each object while the head turns after it, and the vergence + follows the object's distance, from 1° at 3.6 m to 10° at 0.4 m. diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index 7cc1977c4b12..f0fa9958e711 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -9,13 +9,29 @@ gaze on the viewing sphere beside that view; move or resize that window to see the viewer's own. Use WASD or the arrow keys to move the camera, and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze. -Below the side panel's Camera Source selector, gaze sliders follow the gaze and set it, and on Newton a foveation -slider steps the CMF constant (cmf_a) through --cmf_a_values. Press H to show or hide the viewer controls. +Below the side panel's Camera Source selector, gaze sliders follow the gaze and set it, a checkbox draws an eyeball at +the camera in the perspective view, and on Newton a foveation slider steps the CMF constant (cmf_a) through +--cmf_a_values. Press H to show or hide the viewer controls. Use --target to choose where the retina looks at launch. +With --stereo, two free eyes 6.5 cm apart, each drawn as an eyeball, look together in software binocular gaze: a +version, their shared line of sight, and a vergence, the angle between their lines of sight, move the retinas. The +teacher's labels step both toward the fixation the controls set. The viewer opens on a perspective view that draws +each eye's line of sight and the fixation point where they meet, and a window shows both eyes' cortical views. The +side panel's sliders set the version and the vergence, a button glides the fixation onto the next object, checkboxes +hide or show that overlay and the eyeballs, and a slider moves the eyes apart, which changes their disparity; +I/J/K/L, or a drag in the eyes' window, turn the version, and U/O converge and diverge the eyes. On Newton, a +foveation slider steps both eyes' cmf_a through --cmf_a_values. The camera menu also shows each eye. + +With --galbot as well, the eyes are a Galbot G1's two lenses, 6 cm apart, in hybrid binocular gaze: the neck turns +after the version. Only the neck moves; every other joint holds a standing pose. The lenses are fixed on the head, so +the eyes have no eyeballs and no separation slider. + .. code-block:: bash uv run --extra fovi isaaclab example foveated-camera + uv run --extra fovi isaaclab example foveated-camera --stereo --target banana + uv run --extra fovi isaaclab example foveated-camera --stereo --galbot --target banana uv run --extra fovi --extra ovrtx isaaclab example foveated-camera renderer=ovrtx --viz newton # A large CMF constant gives the matched non-foveated retina, for comparison: uv run --extra fovi isaaclab example foveated-camera env.scene.eye.cmf_a_deg=1000 @@ -40,13 +56,14 @@ from isaaclab_fovi.sensors.native_grid import GRID_STYLE, native_grid_exit_uv from isaaclab_isaacsim.physics import PhysxCfg from isaaclab_isaacsim.renderers import IsaacRtxRendererCfg -from isaaclab_newton.physics import NewtonCfg, XPBDSolverCfg +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg, XPBDSolverCfg from isaaclab_newton.renderers import NewtonWarpRendererCfg from isaaclab_ov.renderers import OVRTXRendererCfg import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg from isaaclab.app import add_launcher_args, launch_simulation -from isaaclab.assets import AssetBaseCfg, RigidObjectCfg +from isaaclab.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg from isaaclab.envs import ManagerBasedEnvCfg from isaaclab.scene import InteractiveSceneCfg from isaaclab.terrains import TerrainImporterCfg @@ -59,7 +76,7 @@ quat_apply_inverse, quat_from_matrix, ) -from isaaclab.visualizers import SceneCameraCfg, VisualizerCfg +from isaaclab.visualizers import PerspectiveCameraCfg, SceneCameraCfg, VisualizerCfg from isaaclab_tasks.utils import preset, setup_preset_cli from isaaclab_tasks.utils.hydra import resolve_task_config @@ -108,6 +125,74 @@ PREVIEW_SIZE = 256 COMPARISON_WINDOW = "Foveated camera" """Title of the window that shows the viewing sphere beside the foveated camera's cortical view.""" +STEREO_WINDOW = "Foveated eyes (left, right)" +"""Title of the window that shows both eyes' cortical views with --stereo.""" +GALBOT_G1_USD = f"{ISAAC_NUCLEUS_DIR}/Robots/Galbot/galbot_g1/galbot_g1.usda" +"""The Galbot G1 humanoid, whose head carries the two eyes with --stereo.""" +STEREO_BASELINE = 0.065 +"""Distance between the free eyes at launch [m], about a person's.""" +STEREO_SEPARATION_RANGE = (0.02, 0.3) +"""Smallest and largest distance between the free eyes [m] the side panel's slider sets.""" +GALBOT_HEAD_LINK = ( + "OmniChassis/base_link/omni_chassis_base_link/omni_chassis_leg_mount_link/leg_base_link/leg_link1/leg_link2/" + "leg_link3/leg_link4/leg_link5/leg_end_effector_mount_link/torso_base_link/Head_Golf/torso_base_link/" + "torso_head_mount_link/head_base_link/head_link1/head_link2" +) +"""Path of the Galbot G1's head link below the robot prim.""" +GALBOT_BASE_LINK = "OmniChassis/base_link/omni_chassis_base_link/omni_chassis_leg_mount_link" +"""Path of the Galbot G1's root link, the parent of its base and legs in its joints, below the robot prim.""" +GALBOT_BASELINE = 0.06 +"""Distance between the Galbot G1's two lenses [m].""" +_GALBOT_EYE_TILT = math.radians(15.0) +GALBOT_EYE_OFFSETS = tuple( + FoveatedCameraCfg.OffsetCfg( + pos=(0.098, -0.0493, side * GALBOT_BASELINE / 2), + # Optical +Z along the head's +X and optical +X along its -Z, tilted 15 degrees down toward its +Y. + rot=tuple( + value * math.sqrt(0.5) + for value in ( + -math.sin(_GALBOT_EYE_TILT / 2), + math.cos(_GALBOT_EYE_TILT / 2), + math.sin(_GALBOT_EYE_TILT / 2), + math.cos(_GALBOT_EYE_TILT / 2), + ) + ), + convention="ros", + ) + for side in (1.0, -1.0) +) +"""Poses (left, right) of the eyes in the Galbot G1's head link: FOVI-Dex's estimates of its lenses from the head's +mesh, not measured extrinsics, moved 1 cm forward to just outside this asset's face plate, which reaches 9.4 cm.""" +GALBOT_POSE = ((OFFSET[0], OFFSET[1] - 1.5, 0.0), (0.0, 0.0, math.sqrt(0.5), math.sqrt(0.5))) +"""Position [m] and orientation (x, y, z, w) of the Galbot G1, which faces +X, turned to face the objects along +Y. From +1.5 m behind the objects' centre its neck points the eyes within 2 degrees of every object.""" +GALBOT_NECK_JOINTS = ("head_joint1", "head_joint2") +"""The neck's joints, pan and tilt: the robot's only joints that move.""" +_GALBOT_ARM = (1.036, -1.458, -0.514, 1.116, -0.103, 0.0, 0.014) +GALBOT_BODY_POSE = { + # Standing tall on nearly straight legs; the middle joint makes up the other two, so the torso stays level. + "leg_joint1": math.radians(50.0), + "leg_joint2": math.radians(122.5), + "leg_joint3": math.radians(72.5), + # Upper arms at the sides, elbows bent to hold the hands at the waist, wrists straight; the arms mirror each + # other with the same angles. + **{f"{side}_arm_joint{i}": angle for side in ("left", "right") for i, angle in enumerate(_GALBOT_ARM, start=1)}, +} +"""Angles [rad] at which the Galbot G1's other joints are frozen; joints not named hold the asset's pose.""" +GALBOT_JOINT_POS = {"head_joint1": 0.0, "head_joint2": 0.35} +"""The neck's home pose: facing ahead and tilted down as in FOVI-Dex.""" +GALBOT_HEAD_SIGNS = (1.0, -1.0) +"""Signs of ``head_joint1`` and ``head_joint2`` for a turn of the eyes to the left and up.""" +STEREO_STEER_DEG_PER_S = 15.0 +"""How fast I/J/K/L turn the version with --stereo [deg/s].""" +STEREO_VERGE_DEG_PER_S = 3.0 +"""How fast U/O change the vergence with --stereo [deg/s].""" +STEREO_VERSION_LIMIT = 88.0 +"""Largest version tilt or pan with --stereo [deg], within the fisheye's 180 degree view.""" +STEREO_VERGENCE_LIMIT = 25.0 +"""Largest vergence with --stereo [deg]: the eyes fixate about 15 cm away.""" +STEREO_GLIDE_DEG_PER_S = (20.0, 5.0) +"""How fast the version and the vergence glide to the next object with --stereo [deg/s]; both arrive together.""" def viewing_sphere_rays(screen: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: @@ -141,6 +226,14 @@ def _cmf_a_values(text: str) -> tuple[float, ...]: "--max_steps", type=int, default=-1, help="Number of render frames; -1 runs until the viewer closes." ) parser.add_argument("--target", choices=OBJECTS, help="Set the initial gaze toward this object.") +parser.add_argument( + "--stereo", action="store_true", help="Look through two foveated eyes that fixate one point together." +) +parser.add_argument( + "--galbot", + action="store_true", + help="With --stereo, mount the eyes on a Galbot G1's head, which turns with the gaze, instead of two free eyes.", +) parser.add_argument( "--cmf_a_values", type=_cmf_a_values, @@ -153,6 +246,8 @@ def _cmf_a_values(text: str) -> tuple[float, ...]: args_cli, overrides = setup_preset_cli(parser) if args_cli.max_steps == 0 or args_cli.max_steps < -1: parser.error("--max_steps must be positive or -1.") +if args_cli.galbot and not args_cli.stereo: + parser.error("--galbot needs --stereo.") def _eye_rotation() -> torch.Tensor: @@ -194,7 +289,16 @@ class FoveatedSceneCfg(InteractiveSceneCfg): """The cluttered fisheye scene from the foveated camera docs.""" ground = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane") - light = AssetBaseCfg(prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=900.0)) + # Newton cameras read a dome's intensity as linear radiance, while the RTX renderers expect hundreds. + light = AssetBaseCfg( + prim_path="/World/Light", + spawn=preset( + default=sim_utils.DomeLightCfg(intensity=1.0), + newton_warp=sim_utils.DomeLightCfg(intensity=1.0), + ovrtx=sim_utils.DomeLightCfg(intensity=900.0), + isaacsim_rtx=sim_utils.DomeLightCfg(intensity=900.0), + ), + ) # Keep one body below the ground for Newton's model. anchor = RigidObjectCfg( prim_path="{ENV_REGEX_NS}/Anchor", @@ -352,16 +456,298 @@ def compose(image: torch.Tensor) -> wp.array: return prepare, compose +@sim_utils.clone +def spawn_fixed_galbot(prim_path: str, cfg: sim_utils.UsdFileCfg, *args, **kwargs): + """Spawn the Galbot G1 with its base fixed to the world and every joint but the neck's frozen. + + Its articulation root is the asset's top Xform, which is not a rigid body, so ``fix_root_link`` cannot fix it; a + fixed joint from the world to the root link, below that Xform, holds it instead. Each other moving joint becomes a + fixed joint with the same bodies, frozen at its angle in :data:`GALBOT_BODY_POSE`: the demo turns only the neck, + and the legs, arms, grippers and omni-wheels' nearly massless rollers would otherwise shake it. + """ + from pxr import Gf, Usd, UsdPhysics + + from isaaclab.sim.schemas.schemas import create_world_fixed_joint + + prim = sim_utils.spawn_from_usd.__wrapped__(prim_path, cfg, *args, **kwargs) + stage = prim.GetStage() + create_world_fixed_joint(stage.GetPrimAtPath(f"{prim_path}/{GALBOT_BASE_LINK}"), stage) + for part in list(Usd.PrimRange(prim)): + if not part.IsA(UsdPhysics.Joint) or part.IsA(UsdPhysics.FixedJoint) or part.GetName() in GALBOT_NECK_JOINTS: + continue + joint = UsdPhysics.Joint(part) + frozen = UsdPhysics.FixedJoint.Define( + stage, part.GetPath().GetParentPath().AppendChild(f"{part.GetName()}_frozen") + ) + frozen.CreateBody0Rel().SetTargets(joint.GetBody0Rel().GetTargets()) + frozen.CreateBody1Rel().SetTargets(joint.GetBody1Rel().GetTargets()) + for name in ("LocalPos0", "LocalPos1", "LocalRot1"): + getattr(frozen, f"Create{name}Attr")(getattr(joint, f"Get{name}Attr")().Get()) + # A joint frozen at an angle keeps its first frame turned by that angle about the joint's axis. + rot0, angle = joint.GetLocalRot0Attr().Get(), GALBOT_BODY_POSE.get(part.GetName(), 0.0) + if angle: + imag = [0.0, 0.0, 0.0] + imag["XYZ".index(UsdPhysics.RevoluteJoint(part).GetAxisAttr().Get())] = math.sin(angle / 2) + rot0 = rot0 * Gf.Quatf(math.cos(angle / 2), Gf.Vec3f(*imag)) + frozen.CreateLocalRot0Attr(rot0) + part.SetActive(False) + return prim + + +def add_galbot_eyes(scene_cfg: FoveatedSceneCfg) -> None: + """Add the Galbot G1 and split the eye into two at its lenses, with the same lens and retina.""" + position, orientation = GALBOT_POSE + scene_cfg.robot = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Galbot", + # Nothing touches the robot, and its base's rollers resting on the ground make the solver diverge. + spawn=sim_utils.UsdFileCfg( + func=spawn_fixed_galbot, + usd_path=GALBOT_G1_USD, + collision_props={"/.*": [sim_utils.UsdPhysicsCollisionCfg(collision_enabled=False)]}, + ), + init_state=ArticulationCfg.InitialStateCfg(pos=position, rot=orientation, joint_pos=GALBOT_JOINT_POS), + # The USD's drive gains are far too stiff for the neck, which the gaze drives. + actuators={ + "neck": ImplicitActuatorCfg( + joint_names_expr=list(GALBOT_NECK_JOINTS), stiffness=40.0, damping=4.0, armature=0.02 + ) + }, + ) + head = f"{{ENV_REGEX_NS}}/Galbot/{GALBOT_HEAD_LINK}" + for name, prim, offset in ( + ("eye", "LeftEye", GALBOT_EYE_OFFSETS[0]), + ("right_eye", "RightEye", GALBOT_EYE_OFFSETS[1]), + ): + setattr(scene_cfg, name, scene_cfg.eye.replace(prim_path=f"{head}/{prim}", offset=offset)) + + +def add_second_eye(scene_cfg: FoveatedSceneCfg) -> None: + """Split the eye into two free eyes, :data:`STEREO_BASELINE` apart across its optical axis, with the same lens and + retina, each marked in the viewer by an eyeball.""" + offset = scene_cfg.eye.offset + right = quat_apply(torch.tensor([offset.rot]), torch.tensor([[1.0, 0.0, 0.0]]))[0] # OpenGL cameras: +X right. + centre = torch.tensor(offset.pos) + for name, prim, side in (("eye", "LeftEye", -0.5), ("right_eye", "RightEye", 0.5)): + pos = tuple((centre + side * STEREO_BASELINE * right).tolist()) + eye = scene_cfg.eye.replace( + prim_path=f"{{ENV_REGEX_NS}}/{prim}", offset=offset.replace(pos=pos), debug_vis=True + ) + setattr(scene_cfg, name, eye) + + +def ros_direction(angles_deg: torch.Tensor) -> torch.Tensor: + """Line-of-sight directions for (tilt, pan) [deg] in a camera's ROS frame: +Z forward, +Y down.""" + tilt, pan = angles_deg.deg2rad().unbind(-1) + return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), dim=-1) + + +def ros_angles(direction: torch.Tensor) -> torch.Tensor: + """(tilt, pan) [deg] of directions in a camera's ROS frame; the inverse of :func:`ros_direction`.""" + x, y, z = direction.unbind(-1) + return torch.stack((-torch.atan2(y, torch.hypot(x, z)), -torch.atan2(x, z)), dim=-1).rad2deg() + + +class StereoGaze: + """The fixation the eyes should take, as a version, their shared line of sight (tilt, pan), and a vergence, the + angle between their lines of sight, both from the eyes' mount with the head in its home pose. + + The eyes do not turn here: :meth:`fixation` is the world point the version and the vergence pick, and the + binocular gaze action, led by its teacher, moves the eyes and, in hybrid gaze, the head onto it. + """ + + def __init__(self, left: FoveatedCamera, right: FoveatedCamera) -> None: + self.eyes = (left, right) + self.home() + self.version = torch.zeros(2) + """The shared line of sight (tilt, pan) [deg] from the home mount's optical axis.""" + self.vergence = 0.0 + """The angle between the lines of sight [deg]; zero keeps them parallel.""" + + def home(self) -> None: + """Record the eyes' mount as the home pose, with the head, if any, in its home pose.""" + # Copies: the mounts are views of the cameras' buffers, which follow the head as it turns. + home_quat, home_positions = (value.clone() for value in self.mounts()) + self.home_quat = home_quat + """The eyes' shared mount (x, y, z, w), ROS convention, shape (1, 4), with the head in its home pose.""" + self.home_centre = home_positions.mean(0) + """The point between the eyes [m] with the head in its home pose.""" + self.home_positions = home_positions + self.separation = float((home_positions[1] - home_positions[0]).norm()) + """The distance between the eyes [m].""" + + def set_separation(self, separation: float) -> None: + """Move free eyes ``separation`` [m] apart about the point between them, and keep the fixation.""" + point = self.fixation() + left, right = self.eyes + start, end = left.mount_pos_w.torch, right.mount_pos_w.torch + centre, across = (start + end) / 2, torch.nn.functional.normalize(end - start, dim=-1) + for eye, side in ((left, -0.5), (right, 0.5)): + eye.set_world_poses(positions=centre + side * separation * across) + self.home() + self.look_at(point) + + def mounts(self) -> tuple[torch.Tensor, torch.Tensor]: + """The eyes' shared mount (x, y, z, w), ROS convention, shape (1, 4), and their positions [m], shape (2, 3).""" + left, right = self.eyes + quat = left.update_mount().torch[:1] + right.update_mount() + return quat, torch.stack((left.mount_pos_w.torch[0], right.mount_pos_w.torch[0])) + + def toward(self, point: torch.Tensor) -> tuple[torch.Tensor, float]: + """The version (tilt, pan) [deg] and the vergence [deg] that fixate a world point [m] from the home pose: the + version bisects the eyes' lines of sight to it, and the vergence is their angle, as the binocular teacher + labels them.""" + quat, positions = self.home_quat, self.home_positions + sight = torch.nn.functional.normalize(quat_apply_inverse(quat.expand(2, -1), point.to(quat.device) - positions)) + vergence = math.degrees(math.acos(min(1.0, float((sight[0] * sight[1]).sum())))) + return ros_angles(sight.sum(0)).cpu(), vergence + + def fixation(self) -> torch.Tensor: + """The world point [m] the version and the vergence pick: along the version from between the eyes, as far as + the eyes' two lines of sight meet at the vergence.""" + half = math.radians(max(self.vergence, 0.05)) / 2 + distance = min(self.separation / 2 / math.tan(half), 20.0) + direction = quat_apply(self.home_quat, ros_direction(self.version.to(self.home_quat.device))[None])[0] + return self.home_centre + distance * direction + + def look_at(self, point: torch.Tensor) -> None: + """Fixate a world point [m].""" + version, vergence = self.toward(point) + self.set(tuple(version.tolist()), vergence) + + def set(self, version: tuple[float, float] | None = None, vergence: float | None = None) -> None: + """Set the version (tilt, pan) [deg] or the vergence [deg], within their limits.""" + if version is not None: + self.version = torch.tensor(version, dtype=torch.float32).clamp(-STEREO_VERSION_LIMIT, STEREO_VERSION_LIMIT) + if vergence is not None: + self.vergence = min(max(vergence, 0.0), STEREO_VERGENCE_LIMIT) + + def steer(self, tilt_deg: float, pan_deg: float, vergence_deg: float = 0.0) -> bool: + """Turn the version by (tilt, pan) [deg] and change the vergence [deg]; return whether either moved.""" + if not tilt_deg and not pan_deg and not vergence_deg: + return False + self.set(tuple((self.version + torch.tensor((tilt_deg, pan_deg))).tolist()), self.vergence + vergence_deg) + return True + + +def lines_of_sight( + eyes: tuple[FoveatedCamera, FoveatedCamera], +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: + """Each eye's line of sight from its current gaze, as segments (starts, ends), shape (2, 3) each, and the point + nearest both, where they meet, or None when they do not converge in front of the eyes.""" + starts, directions = [], [] + for eye in eyes: + quat = eye.update_mount().torch[:1] + starts.append(eye.mount_pos_w.torch[0]) + directions.append(quat_apply(quat, ros_direction(eye.gaze_angles.torch[:1]))[0]) + (p, q), (u, v) = starts, directions + # Closest points p + s u and q + t v of the two lines. + w, b = p - q, float((u * v).sum()) + d, e = float((u * w).sum()), float((v * w).sum()) + denominator = 1.0 - b * b + s = (b * e - d) / denominator if denominator > 1e-9 else -1.0 + t = (e - b * d) / denominator if denominator > 1e-9 else -1.0 + meeting = None + lengths = (2.0, 2.0) + if s > 0 and t > 0: + meeting = 0.5 * (p + s * u + q + t * v) + lengths = (s, t) + starts = torch.stack(starts) + ends = starts + torch.stack(directions) * starts.new_tensor(lengths)[:, None] + return starts, ends, meeting + + +class StereoAnnotations: + """Draw each eye's line of sight and, where they meet, the binocular fixation in the Newton viewers' perspective + view.""" + + COLOR = (0.0, 0.0, 0.0) + """Color of the lines of sight and the fixation.""" + FIXATION_RADIUS = 0.008 + """Radius of the sphere at the fixation [m].""" + + def __init__(self, visualizers: list[BaseVisualizer]) -> None: + self.windows = [newton_window(visualizer) for visualizer in visualizers] + self.visible = True + """Whether the viewers show the overlay; the side panel's checkbox toggles it.""" + self._arrays = None # The logged arrays stay alive until the next frame replaces them. + + def draw(self, eyes: tuple[FoveatedCamera, FoveatedCamera]) -> None: + if not self.visible: + for window in self.windows: + window.log_lines("/foveated/lines_of_sight", None, None, None, hidden=True) + window.log_points("/foveated/fixation", None, hidden=True) + return + starts, ends, meeting = lines_of_sight(eyes) + colors = starts.new_tensor((self.COLOR, self.COLOR)) + point = (meeting if meeting is not None else ends.mean(0))[None] + point_color = colors[:1] + self._arrays = [ + wp.from_torch(array.float().contiguous(), dtype=wp.vec3) + for array in (starts, ends, colors, point, point_color) + ] + starts_wp, ends_wp, colors_wp, point_wp, point_color_wp = self._arrays + for window in self.windows: + window.log_lines("/foveated/lines_of_sight", starts_wp, ends_wp, colors_wp) + window.log_points( + "/foveated/fixation", + point_wp, + radii=self.FIXATION_RADIUS, + colors=point_color_wp, + hidden=meeting is None, + ) + + +def stereo_view(eyes: tuple[FoveatedCamera, FoveatedCamera]) -> Callable[[], wp.array]: + """Return a function that composes both eyes' cortical views side by side (left, right).""" + size, gap = PREVIEW_SIZE, 6 + device = eyes[0].device + divider = torch.tensor((25, 28, 32, 255), dtype=torch.uint8, device=device).expand(size, gap, -1) + center = (torch.arange(size, device=device) + 0.5) * (2 / size) - 1 + screen = torch.stack(torch.meshgrid(center, center, indexing="xy"), dim=-1) + outside = screen.square().sum(-1) > 1 + + def compose() -> wp.array: + views = [] + for eye in eyes: + image = eye.data.output["rgb"].torch[0, ..., :3] + view = torch.cat((image, torch.full_like(image[..., :1], 255)), dim=-1).permute(2, 0, 1)[None] + view = torch.nn.functional.interpolate(view, size=(size, size), mode="nearest")[0].permute(1, 2, 0) + view[..., :3].masked_fill_(outside[..., None], 0) + views.append(view) + return wp.from_torch(torch.cat((views[0], divider, views[1]), dim=1).contiguous()) + + return compose + + +def place_stereo_window(): + """A side-panel callback that puts the stereo window in the view's top-right corner once, where it leaves the + perspective view and its annotations visible; afterwards its size and position are the user's.""" + placed = [False] + + def place(imgui) -> None: + if placed[0] or imgui.internal.find_window_by_name(STEREO_WINDOW) is None: + return + placed[0] = True + viewport = imgui.get_main_viewport() + width, height = 2 * PREVIEW_SIZE + 6 + 24, PREVIEW_SIZE + 48 + right = viewport.work_pos.x + viewport.work_size.x + imgui.set_window_pos(STEREO_WINDOW, imgui.ImVec2(right - width - 12, viewport.work_pos.y + 12)) + imgui.set_window_size(STEREO_WINDOW, imgui.ImVec2(width, height)) + + return place + + def newton_window(visualizer): """The window of a Newton visualizer, which shows the example's view. Isaac Lab's Newton raycast example reaches it the same way.""" return visualizer._viewer -def comparison_image_hovered(imgui, edge: float = 8.0) -> bool: - """Whether the mouse is inside the comparison window's image: below its title bar and away from its resize edges.""" +def comparison_image_hovered(imgui, name: str = COMPARISON_WINDOW, edge: float = 8.0) -> bool: + """Whether the mouse is inside window ``name``'s image: below its title bar and away from its resize edges.""" window = imgui.get_current_context().hovered_window - if window is None or str(window.root_window.name) != COMPARISON_WINDOW: + if window is None or str(window.root_window.name) != name: return False root = window.root_window mouse = imgui.get_io().mouse_pos @@ -418,12 +804,14 @@ def main() -> None: " (--viz newton). With %s, the gaze stays where it starts (see --target).", ", ".join(sorted(visualizer_types - {"newton"})), ) + if args_cli.stereo: + run_stereo(cfg) + return sim_utils.create_new_stage() sim = sim_utils.SimulationContext(cfg.sim) centres = _add_clutter(cfg.scene) compare = "newton" in visualizer_types if compare: - cfg.scene.eye.mask_to_sensor_fov = True cfg.scene.overview = cfg.scene.eye.replace( prim_path="{ENV_REGEX_NS}/Overview", foveated_res=PREVIEW_SIZE, @@ -439,12 +827,12 @@ def main() -> None: scene = instantiate(cfg.scene) sim.register_interactive_scene(scene) sim.reset() + viewers = [v for v in sim.visualizers if v.cfg.backend.visualizer_type == "newton"] camera = scene["eye"] angles = torch.zeros(scene.num_envs, 2, device=sim.device) if args_cli.target is not None: angles[:] = angles.new_tensor(gaze_toward(centres[args_cli.target], cfg.scene.eye)) camera.set_gaze_angles(angles) - viewers = [v for v in sim.visualizers if v.cfg.backend.visualizer_type == "newton"] if viewers: prepare, compose = camera_comparison(camera, scene["overview"]) gaze = GazeSteering(camera, viewers) @@ -497,6 +885,10 @@ class GazeSteering: DRAG_DEG_PER_PIXEL = 0.15 GAZE_LIMIT_DEG = 85.0 + WINDOW = COMPARISON_WINDOW + """The window whose image a drag steers the gaze in.""" + STEER_ON_VIEW = True + """Whether a drag on the bare view steers the gaze too; otherwise the viewer keeps it.""" def __init__(self, camera: FoveatedCamera, visualizers: list[BaseVisualizer]) -> None: self.camera = camera @@ -535,8 +927,8 @@ def _on_mouse_press(self, x: int, y: int, button: int, modifiers: int) -> bool | if button != mouse.LEFT: return None - self.press_over_panel = imgui.get_io().want_capture_mouse - if self.press_over_panel and comparison_image_hovered(imgui): + self.press_over_panel = imgui.get_io().want_capture_mouse or not self.STEER_ON_VIEW + if imgui.get_io().want_capture_mouse and comparison_image_hovered(imgui, self.WINDOW): self.press_over_panel = False # Keep ImGui from taking the press, which would drag the window instead of the gaze. return event.EVENT_HANDLED @@ -554,5 +946,329 @@ def _on_mouse_drag(self, x: int, y: int, dx: int, dy: int, buttons: int, modifie return event.EVENT_HANDLED +class StereoSteering(GazeSteering): + """Steer both eyes: I/J/K/L and drags in the eyes' window turn the version, U/O converge and diverge them, and the + side panel's sliders set either. A drag on the perspective view stays with the viewer, which orbits its camera. + + The panel's "Gaze to next object" button glides both eyes onto the next object, left to right; steering by hand + stops the glide. Free eyes also get a checkbox for their eyeballs and a slider for the distance between them. + """ + + DRAG_DEG_PER_PIXEL = 0.08 + WINDOW = STEREO_WINDOW + STEER_ON_VIEW = False + + def __init__( + self, + stereo: StereoGaze, + visualizers: list[BaseVisualizer], + annotations: StereoAnnotations, + targets: dict[str, torch.Tensor], + target: str | None = None, + free_eyes: bool = True, + ) -> None: + super().__init__(stereo.eyes[0], visualizers) + self.stereo = stereo + self.free_eyes = free_eyes + """Whether the eyes are free, so the panel may move them apart; eyes on a robot's head stay where they are.""" + self.annotations = annotations + self.targets = targets + """World centres [m] of the objects the button visits, in order.""" + self.target = target + """The object the eyes glide to or last reached by the button, if any.""" + self._glide: tuple[torch.Tensor, float] | None = None + """The version and the vergence the eyes glide to.""" + self._start_cmf_a = float(stereo.eyes[0].cfg.cmf_a_deg) + """The eyes' starting CMF constant [deg], which stays a stop of the foveation slider.""" + for visualizer in visualizers: + # The viewer offers no hook below its Camera Source selector that draws for every source, so the controls + # follow its view controls, which end with that selector; without them they go in the side panel. + window = newton_window(visualizer) + draw_view_controls = getattr(window, "_view_controls", None) + if draw_view_controls is None: + visualizer.register_ui_callback(self._draw_sliders, position="side") + continue + + def draw_below_camera_source(imgui, draw_view_controls=draw_view_controls) -> None: + draw_view_controls(imgui) + self._draw_sliders(imgui) + + window._view_controls = draw_below_camera_source + + def steer(self, tilt_deg: float, pan_deg: float, vergence_deg: float = 0.0, elapsed: float = 0.0) -> None: + """Turn the version by (tilt, pan) [deg], plus any drag, and change the vergence [deg]; without either, glide + ``elapsed`` [s] further toward the next object, if the button chose one.""" + pan_deg -= self.drag[0] * self.DRAG_DEG_PER_PIXEL + tilt_deg += self.drag[1] * self.DRAG_DEG_PER_PIXEL + self.drag = [0.0, 0.0] + if self.stereo.steer(tilt_deg, pan_deg, vergence_deg): + self._glide = None + self._redraw() + elif self._glide is not None: + self._glide_by(elapsed) + + def gaze_to_next_object(self) -> None: + """Start gliding both eyes onto the object after the current target.""" + names = list(self.targets) + self.target = names[(names.index(self.target) + 1) % len(names) if self.target in names else 0] + self._glide = self.stereo.toward(self.targets[self.target]) + + def _glide_by(self, elapsed: float) -> None: + """Move the version and the vergence toward the glide's end, both arriving together.""" + version, vergence = self._glide + stereo = self.stereo + to_version, to_vergence = version - stereo.version, vergence - stereo.vergence + rate_version, rate_vergence = STEREO_GLIDE_DEG_PER_S + remaining = max(float(to_version.norm()) / rate_version, abs(to_vergence) / rate_vergence) + fraction = 1.0 if remaining <= elapsed else elapsed / remaining + stereo.set(tuple((stereo.version + fraction * to_version).tolist()), stereo.vergence + fraction * to_vergence) + if fraction == 1.0: + self._glide = None + self._redraw() + + def _redraw(self) -> None: + for visualizer in self.visualizers: + # A view of either eye redraws with the new gaze, even while paused. + visualizer.current_image_view.invalidate() + + def _draw_sliders(self, imgui) -> None: + """Draw the version and vergence sliders in the side panel.""" + stereo = self.stereo + imgui.separator_text("Binocular gaze") + tilt, pan = stereo.version.tolist() + limit = STEREO_VERSION_LIMIT + tilt_changed, tilt = imgui.slider_float("Version tilt", tilt, -limit, limit, "%.1f deg") + pan_changed, pan = imgui.slider_float("Version pan", pan, -limit, limit, "%.1f deg") + verge_changed, vergence = imgui.slider_float( + "Vergence", stereo.vergence, 0.0, STEREO_VERGENCE_LIMIT, "%.2f deg" + ) + if imgui.is_item_hovered(): + imgui.set_tooltip("The angle between the eyes' lines of sight; zero keeps them parallel.") + if imgui.button("Center version"): + tilt, pan, tilt_changed = 0.0, 0.0, True + imgui.same_line() + if imgui.button("Parallel"): + vergence, verge_changed = 0.0, True + if tilt_changed or pan_changed or verge_changed: + self._glide = None + stereo.set((tilt, pan), vergence) + self._redraw() + if imgui.button("Gaze to next object"): + self.gaze_to_next_object() + if self.target is not None: + imgui.same_line() + imgui.text(f"{'->' if self._glide is not None else 'at'} {self.target.replace('_', ' ')}") + _, self.annotations.visible = imgui.checkbox("Show gaze overlay", self.annotations.visible) + if imgui.is_item_hovered(): + imgui.set_tooltip("Draw the eyes' lines of sight and the fixation in the perspective view.") + if self.free_eyes: + self._draw_free_eyes(imgui) + self._draw_foveation(imgui) + imgui.text("I/J/K/L: version U/O: vergence") + + def _draw_free_eyes(self, imgui) -> None: + """Draw the eyeballs' checkbox and the slider for the distance between the eyes.""" + eyes = self.stereo.eyes + changed, shown = imgui.checkbox("Show eyeballs", eyes[0].shows_eyeball) + if imgui.is_item_hovered(): + imgui.set_tooltip("Draw an eyeball at each eye in the perspective view, turned with its gaze.") + if changed: + for eye in eyes: + eye.set_debug_vis(shown) + low, high = (1000 * value for value in STEREO_SEPARATION_RANGE) + changed, separation = imgui.slider_float("Eye separation", 1000 * self.stereo.separation, low, high, "%.0f mm") + if imgui.is_item_hovered(): + imgui.set_tooltip( + "The distance between the eyes, which sets their disparity. The fixation stays where it is." + ) + if changed: + self._glide = None + self.stereo.set_separation(separation / 1000) + self._redraw() + + def _draw_foveation(self, imgui) -> None: + """Draw the CMF constant both eyes share: a slider over the foveation slider's stops where the renderer can + change the retina while it runs, and otherwise the fixed value.""" + # The panel's controls load USD, so they are imported once the simulation has launched. + from isaaclab_fovi.sensors import ViewerGazeControls + + eyes = self.stereo.eyes + current = float(eyes[0].cfg.cmf_a_deg) + if not eyes[0].supports_runtime_cmf_a: + imgui.text(f"Foveation: cmf_a {current:g} deg (fixed)") + if imgui.is_item_hovered(): + imgui.set_tooltip("Only the Newton Warp renderer changes the retina while it runs.") + return + values = sorted({float(value) for value in ViewerGazeControls.cmf_a_values} | {self._start_cmf_a, current}) + changed, index = imgui.slider_int( + "Foveation", values.index(current), 0, len(values) - 1, f"cmf_a {current:g} deg" + ) + if imgui.is_item_hovered(): + imgui.set_tooltip("Both eyes. Smaller cmf_a concentrates the samples at the fixation; larger spreads them.") + if changed and values[index] != current: + for eye in eyes: + eye.set_cmf_a(values[index]) + self._redraw() + + +def match_gltf_colors(sim: sim_utils.SimulationContext, visualizers: list[BaseVisualizer]) -> None: + """Give each Newton shape the base color of its glTF material, in every Newton model: the physics' on Newton, and + each Newton viewer's, which on PhysX is a model of its own. + + Isaac Lab's Newton import takes shape colors from OmniPBR materials only, so shapes with glTF materials, as most of + the Galbot G1's are, keep Newton's palette. The viewers and the Newton cameras read the model's colors as they draw. + """ + from pxr import UsdShade + + owners = [sim.backend_manager, *visualizers] + models = [getattr(getattr(owner, "backend", None), "model", None) for owner in owners] + for model in {id(model): model for model in models if model is not None}.values(): + if getattr(model, "shape_color", None) is None: + continue + colors = model.shape_color.numpy() + for index, label in enumerate(model.shape_label): + prim = sim.stage.GetPrimAtPath(label) + material = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()[0] if prim else None + shader = material.ComputeSurfaceSource("mdl")[0] if material else None + factor = shader.GetInput("base_color_factor") if shader else None + if factor and factor.Get() is not None: + # The factor is linear; the model holds sRGB. + colors[index] = [12.92 * c if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055 for c in factor.Get()] + model.shape_color.assign(colors) + + +def run_stereo(cfg: FoveatedExampleCfg) -> None: + """Look through two eyes in binocular gaze, free or, with --galbot, on a Galbot G1's head in hybrid gaze: steer + their fixation, show their cortical views and draw their lines of sight.""" + # The gaze terms and the environment load USD, so they are imported once the simulation has launched. + from isaaclab_fovi.mdp import BinocularGazeActionCfg, GazeRigCfg, binocular_gaze_state + + from isaaclab.envs import ManagerBasedEnv + from isaaclab.envs.manager_based_env_cfg import DefaultEventManagerCfg + from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg + + if args_cli.galbot: + add_galbot_eyes(cfg.scene) + # From beyond the objects and to one side, facing the robot's head over the scene. + view = PerspectiveCameraCfg( + eye=(OFFSET[0] + 2.3, OFFSET[1] + 1.1, 2.0), lookat=(OFFSET[0] - 0.1, OFFSET[1] - 0.3, 0.55) + ) + else: + add_second_eye(cfg.scene) + # From beyond the objects, at about the eyes' height, so the eyes face it over the whole scene. + view = PerspectiveCameraCfg( + eye=(OFFSET[0] - 0.24, OFFSET[1] + 1.40, 0.37), lookat=(OFFSET[0] + 0.28, OFFSET[1] + 0.10, 0.31) + ) + centres = _add_clutter(cfg.scene) + for visualizer_cfg in cfg.sim.visualizer_cfgs: + # The viewer opens on the scene, where it draws the lines of sight; its camera menu offers each eye. + visualizer_cfg.cameras = [ + view, + SceneCameraCfg(prim_path=cfg.scene.eye.prim_path), + SceneCameraCfg(prim_path=cfg.scene.right_eye.prim_path), + ] + # Physics steps for the gaze action: at 120 Hz with a 30 Hz action, without gravity, which would topple the + # free-standing Galbot. Newton's MuJoCo solver drives its head joints. + cfg.decimation = 4 + cfg.sim.dt = 1 / 120 + cfg.sim.render_interval = 4 + cfg.sim.gravity = (0.0, 0.0, 0.0) + if isinstance(cfg.sim.physics, NewtonCfg): + cfg.sim.physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), load_visual_shapes=True) + + @configclass + class ActionsCfg: + # The Galbot's neck turns after the version; free eyes turn their retinas alone. + gaze = BinocularGazeActionCfg( + asset_name="eye", + right_asset_name="right_eye", + mode="hybrid" if args_cli.galbot else "software", + rig=( + GazeRigCfg(asset_name="robot", joint_names=GALBOT_NECK_JOINTS, joint_signs=GALBOT_HEAD_SIGNS) + if args_cli.galbot + else None + ), + ) + + @configclass + class ObservationsCfg: + @configclass + class PolicyCfg(ObservationGroupCfg): + gaze = ObservationTermCfg(func=binocular_gaze_state) + + policy = PolicyCfg() + + cfg.actions = ActionsCfg() + # A manager-based environment needs an observation group, which the example does not read, and its reset events. + cfg.observations = ObservationsCfg() + cfg.events = DefaultEventManagerCfg() + env = ManagerBasedEnv(cfg) + env.reset() + sim, scene = env.sim, env.scene + viewers = [v for v in sim.visualizers if v.cfg.backend.visualizer_type == "newton"] + if args_cli.galbot: + match_gltf_colors(sim, viewers) + gaze = env.action_manager.get_term("gaze") + point = torch.zeros(env.num_envs, 3, device=env.device) + labels = torch.zeros(env.num_envs, 4, device=env.device) + point_wp, labels_wp = wp.from_torch(point, dtype=wp.vec3f), wp.from_torch(labels) + # Let the Galbot's head settle in its home pose before the fixation's frame is read from it. + for _ in range(10): + env.step(torch.zeros(env.num_envs, 3, device=env.device)) + + stereo = StereoGaze(scene["eye"], scene["right_eye"]) + # The objects in the scene's order, from left to right of the eyes. + targets = {name: torch.tensor(centre, device=sim.device) + scene.env_origins[0] for name, centre in centres.items()} + if args_cli.target is not None: + stereo.look_at(targets[args_cli.target]) + else: + # Fixate 1 m straight ahead. + stereo.set((0.0, 0.0), math.degrees(2 * math.atan(stereo.separation / 2))) + if viewers: + annotations = StereoAnnotations(viewers) + steering = StereoSteering(stereo, viewers, annotations, targets, args_cli.target, not args_cli.galbot) + compose = stereo_view(stereo.eyes) + for viewer in viewers: + viewer.register_ui_callback(place_stereo_window(), position="side") + + last_update = time.monotonic() + shown_state = None # The gazes and foveation the eyes' window was drawn with. + frame = 0 + while sim.is_running() and (args_cli.max_steps < 0 or frame < args_cli.max_steps): + now = time.monotonic() + if viewers and now - last_update >= 1 / 30: + elapsed = min(now - last_update, 0.05) + last_update = now + viewer = viewers[0] + tilt = int(viewer.is_key_down("i")) - int(viewer.is_key_down("k")) + pan = int(viewer.is_key_down("j")) - int(viewer.is_key_down("l")) + converge = int(viewer.is_key_down("u")) - int(viewer.is_key_down("o")) + step = STEREO_STEER_DEG_PER_S * elapsed + steering.steer(tilt * step, pan * step, converge * STEREO_VERGE_DEG_PER_S * elapsed, elapsed) + # The teacher's labels step the eyes, and in hybrid gaze the head, toward the fixation; an unseen point holds + # them still. + point.copy_(stereo.fixation()[None]) + gaze.teacher_labels(point_wp, labels_wp) + env.step(labels[:, :3] * labels[:, 3:]) + if viewers: + annotations.draw(stereo.eyes) + # Redraw the eyes' window only when what it shows changes; re-rendering a still view would show OVRTX's + # frame-to-frame sampling noise as jitter. + state = tuple( + (tuple(eye.gaze_angles.torch[0].tolist()), tuple(eye.mount_pos_w.torch[0].tolist()), eye.cfg.cmf_a_deg) + for eye in stereo.eyes + ) + if state != shown_state: + shown_state = state + view = compose() + for viewer in viewers: + newton_window(viewer).log_image(STEREO_WINDOW, view) + else: + # Without a viewer, explicitly request sensor data to render the frame. + for eye in stereo.eyes: + _ = eye.data + frame += 1 + + if __name__ == "__main__": main() diff --git a/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-stereo-vergence.added.rst b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-stereo-vergence.added.rst new file mode 100644 index 000000000000..fe8bddb2adaa --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-stereo-vergence.added.rst @@ -0,0 +1,3 @@ +* Added an eyeball that marks a foveated camera in the Newton viewer, turned with its gaze, as the camera's debug + visualization: ``debug_vis=True``, :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_debug_vis` or a checkbox in the + camera's viewer controls switch it, and :attr:`~isaaclab_fovi.sensors.FoveatedCamera.shows_eyeball` reports it. diff --git a/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-stereo-vergence.minor b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-stereo-vergence.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_fovi/changelog.d/fovi-binocular-gaze.added.rst b/source/isaaclab_fovi/changelog.d/fovi-binocular-gaze.added.rst new file mode 100644 index 000000000000..5f52f5c696dd --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/fovi-binocular-gaze.added.rst @@ -0,0 +1,5 @@ +* Added binocular gaze for two foveated cameras on one body: :class:`~isaaclab_fovi.mdp.BinocularGazeActionCfg` + moves a shared version and a vergence in software, physical or hybrid gaze, with + :func:`~isaaclab_fovi.mdp.binocular_gaze_state` and :class:`~isaaclab_fovi.mdp.binocular_gaze_teacher_labels`. + :func:`~isaaclab_fovi.mdp.binocular_gaze_angles` aims both eyes by a version and a vergence without an action term. +* Added :data:`~isaaclab_fovi.assets.PAN_TILT_STEREO_OFFSETS`, two eyes on the pan-tilt mount. diff --git a/source/isaaclab_fovi/changelog.d/fovi-binocular-gaze.minor b/source/isaaclab_fovi/changelog.d/fovi-binocular-gaze.minor new file mode 100644 index 000000000000..e69de29bb2d1 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..6d5c00c2e47c --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/fovi-gaze-modes.added.rst @@ -0,0 +1,10 @@ +* 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, which + :func:`~isaaclab_fovi.assets.spawn_pan_tilt` builds in the stage. +* 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..d3c342863e94 --- /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, with one or two cameras.""" + +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..4e72c658d9aa --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/assets/__init__.pyi @@ -0,0 +1,22 @@ +# 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_STEREO_BASELINE", + "PAN_TILT_STEREO_OFFSETS", + "PanTiltCfg", + "spawn_pan_tilt", +] + +from .pan_tilt import ( + PAN_TILT_CAMERA_OFFSET, + PAN_TILT_CFG, + PAN_TILT_STEREO_BASELINE, + PAN_TILT_STEREO_OFFSETS, + PanTiltCfg, + spawn_pan_tilt, +) diff --git a/source/isaaclab_fovi/isaaclab_fovi/assets/data/eyeball.usda b/source/isaaclab_fovi/isaaclab_fovi/assets/data/eyeball.usda new file mode 100644 index 000000000000..4abd9cb92e03 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/assets/data/eyeball.usda @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53f1e4e6ef84cb0214ea8f20b5ccf597001481ef98aa8d13cb55499b6309c0de +size 793427 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..83dc6ad2a188 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/assets/pan_tilt.py @@ -0,0 +1,147 @@ +# 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 +``base/pan_link/tilt_link`` at :data:`PAN_TILT_CAMERA_OFFSET` looks along it with +Z up. The mount has no visual +geometry, and :func:`spawn_pan_tilt` builds it in the stage, with or without Kit. +""" + +from __future__ import annotations + +import math +from typing import TYPE_CHECKING + +import isaaclab.sim as sim_utils +from isaaclab.actuators import ImplicitActuatorCfg +from isaaclab.assets.articulation import ArticulationCfg +from isaaclab.sensors import CameraCfg +from isaaclab.utils import configclass + +if TYPE_CHECKING: + from pxr import Usd + +_LINK_HEIGHT = 0.04 +"""Height [m] of each joint above the link that carries it.""" + +_JOINT_LIMIT = 1.7 +"""Limit [rad] of both joints, in either direction.""" + +_EFFORT_LIMIT = 20.0 +"""Effort limit [N·m] of both joints.""" + +_LINKS = ( + # name, height above its parent [m], mass [kg], center of mass [m], diagonal inertia [kg·m²] + ("base", 0.0, 0.501, (0.0, 0.0, 0.02), (2.014e-4, 2.014e-4, 2.01e-4)), + ("pan_link", _LINK_HEIGHT, 0.1, (0.0, 0.0, 0.015), (3e-5, 3e-5, 3e-5)), + ("tilt_link", _LINK_HEIGHT, 0.1, (0.0, 0.0, 0.0), (2e-5, 2e-5, 2e-5)), +) + +_JOINTS = ( + # name, axis, parent link, child link + ("pan_joint", "Z", "base", "base/pan_link"), + ("tilt_joint", "X", "base/pan_link", "base/pan_link/tilt_link"), +) + + +@sim_utils.clone +def spawn_pan_tilt( + prim_path: str, + cfg: PanTiltCfg, + translation: tuple[float, float, float] | None = None, + orientation: tuple[float, float, float, float] | None = None, + **kwargs, +) -> Usd.Prim: + """Build the pan-tilt mount at ``prim_path``: three links, fixed to the world at its base. + + Args: + prim_path: The prim path or expression to spawn the mount at. + cfg: The spawner configuration. + translation: The mount's translation from its parent prim. Defaults to None, which leaves it at the origin. + orientation: The mount's orientation (x, y, z, w) relative to its parent prim. Defaults to None, which leaves + it unrotated. + + Returns: + The mount's root prim. + """ + from pxr import Gf, UsdPhysics + + stage = sim_utils.get_current_stage() + root = sim_utils.create_prim(prim_path, "Xform", translation=translation, orientation=orientation, stage=stage) + link_path = prim_path + for name, height, mass, center_of_mass, inertia in _LINKS: + link_path = f"{link_path}/{name}" + link = sim_utils.create_prim(link_path, "Xform", translation=(0.0, 0.0, height), stage=stage) + UsdPhysics.RigidBodyAPI.Apply(link) + mass_api = UsdPhysics.MassAPI.Apply(link) + mass_api.CreateMassAttr(mass) + mass_api.CreateCenterOfMassAttr(Gf.Vec3f(*center_of_mass)) + mass_api.CreateDiagonalInertiaAttr(Gf.Vec3f(*inertia)) + + # The root prim is not a body, so the fixed joint holds the base where the root stands. + root_joint = UsdPhysics.FixedJoint.Define(stage, f"{prim_path}/root_joint") + root_joint.CreateBody0Rel().SetTargets([prim_path]) + root_joint.CreateBody1Rel().SetTargets([f"{prim_path}/base"]) + UsdPhysics.ArticulationRootAPI.Apply(root_joint.GetPrim()) + + limit_deg = math.degrees(_JOINT_LIMIT) + for name, axis, parent, child in _JOINTS: + joint = UsdPhysics.RevoluteJoint.Define(stage, f"{prim_path}/{name}") + joint.CreateBody0Rel().SetTargets([f"{prim_path}/{parent}"]) + joint.CreateBody1Rel().SetTargets([f"{prim_path}/{child}"]) + joint.CreateAxisAttr(axis) + joint.CreateLocalPos0Attr(Gf.Vec3f(0.0, 0.0, _LINK_HEIGHT)) + joint.CreateLocalPos1Attr(Gf.Vec3f(0.0)) + joint.CreateLowerLimitAttr(-limit_deg) + joint.CreateUpperLimitAttr(limit_deg) + drive = UsdPhysics.DriveAPI.Apply(joint.GetPrim(), "angular") + drive.CreateTypeAttr("force") + drive.CreateMaxForceAttr(_EFFORT_LIMIT) + return root + + +@configclass +class PanTiltCfg(sim_utils.SpawnerCfg): + """Spawns the pan-tilt mount with :func:`spawn_pan_tilt`.""" + + func = spawn_pan_tilt + + +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_STEREO_BASELINE = 0.065 +"""Distance between the stereo eyes [m], about a human's.""" + +PAN_TILT_STEREO_OFFSETS = tuple( + PAN_TILT_CAMERA_OFFSET.replace(pos=(side * PAN_TILT_STEREO_BASELINE / 2, 0.0, 0.0)) for side in (-1.0, 1.0) +) +"""Poses (left, right) of two cameras under ``tilt_link`` that look along the mount's forward axis, for binocular +gaze.""" + +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=PanTiltCfg(), + 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=_EFFORT_LIMIT, + 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/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi index e78c9a3844e8..5799132efdc7 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi @@ -4,15 +4,27 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "BinocularGazeAction", + "BinocularGazeActionCfg", "GazeAction", "GazeActionCfg", + "GazeRigCfg", + "binocular_gaze_angles", + "binocular_gaze_state", + "binocular_gaze_teacher_labels", "gaze_state", "gaze_teacher_labels", ] +from .binocular_gaze import ( + BinocularGazeAction, + binocular_gaze_angles, + binocular_gaze_state, + binocular_gaze_teacher_labels, +) from .gaze import ( GazeAction, gaze_state, gaze_teacher_labels, ) -from .gaze_cfg import GazeActionCfg +from .gaze_cfg import BinocularGazeActionCfg, GazeActionCfg, GazeRigCfg diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/binocular_gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/binocular_gaze.py new file mode 100644 index 000000000000..9c975621009a --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/binocular_gaze.py @@ -0,0 +1,677 @@ +# 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 + +"""Binocular gaze for two foveated cameras on one body: a shared version and a vergence. + +The version is the shared line of sight, (tilt, pan) as for a single camera's gaze; the vergence is the angle between +the two eyes' lines of sight. Each eye turns from the version by half the vergence, toward the other eye, in the plane +that holds the version and the baseline between the eyes, so with any vergence above zero the two lines of sight +meet; at zero they are parallel. Both are in field radii, half the retina's field of view. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable +from functools import cache +from typing import TYPE_CHECKING, ClassVar + +import torch +import warp as wp + +from isaaclab.managers import ActionTerm, ManagerTermBase, ObservationTermCfg, SceneEntityCfg +from isaaclab.utils.math import quat_apply_inverse +from isaaclab.utils.warp import ProxyArray + +from ..sensors.gaze_kernels import DEG_TO_RAD, CameraParams, project_direction, record_launch, warp_stream +from .gaze import ( + HYBRID, + PHYSICAL, + RAD_TO_DEG, + clamp_unit, + gaze_direction, + gaze_of, + head_and_target_kernel, + head_angles, + rig_gaze, + target_body_index, + within, + write_head_targets, +) + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + from ..sensors import FoveatedCamera + from .gaze_cfg import BinocularGazeActionCfg + +SOFTWARE = 0 +"""Code of software gaze for :func:`make_binocular_gaze_step`; the rig modes share the single camera's codes.""" + + +@wp.func +def eye_gazes(version: wp.vec2f, vergence: wp.float32, baseline: wp.vec3f, field_radius_deg: wp.float32): + """Each eye's gaze (left, right) for a version and a vergence, all in field radii: each eye turns from the version + by half the vergence toward the other, in the plane of the version and the ``baseline``, the unit direction from + the left eye to the right in the upright frame.""" + d = gaze_direction(version, field_radius_deg) + toward_right = wp.normalize(baseline - wp.dot(baseline, d) * d) + half = 0.5 * vergence * field_radius_deg * wp.float32(DEG_TO_RAD) + left = gaze_of(wp.cos(half) * d + wp.sin(half) * toward_right, field_radius_deg) + right = gaze_of(wp.cos(half) * d - wp.sin(half) * toward_right, field_radius_deg) + return left, right + + +@wp.kernel(enable_backward=False) +def binocular_gaze_angles_kernel( + version_deg: wp.array(dtype=wp.vec2f), + vergence_deg: wp.array(dtype=wp.float32), + baseline: wp.vec3f, + left_deg: wp.array(dtype=wp.vec2f), + right_deg: wp.array(dtype=wp.vec2f), +): + """Each eye's gaze [deg] for a version [deg] and a vergence [deg]; see :func:`binocular_gaze_angles`.""" + i = wp.tid() + # With a field radius of one degree, field radii are degrees. + left, right = eye_gazes(version_deg[i], vergence_deg[i], baseline, 1.0) + left_deg[i] = left + right_deg[i] = right + + +def binocular_gaze_angles( + version_deg: torch.Tensor, vergence_deg: torch.Tensor, baseline: tuple[float, float, float] +) -> tuple[torch.Tensor, torch.Tensor]: + """Each eye's gaze (tilt, pan) [deg] for a version and a vergence, as :class:`BinocularGazeAction` aims them. + + Each eye turns from the version by half the vergence toward the other, in the plane of the version and the + baseline, so with any vergence above zero the two lines of sight meet. Set each camera's gaze with + :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles` to look along them without an action term. + + Args: + version_deg: The shared line of sight (tilt, pan) [deg], shape (N, 2). + vergence_deg: The angle between the two lines of sight [deg], shape (N,). + baseline: The direction from the left eye to the right in the eyes' upright frame: for eyes without image + roll, their camera frame (ROS convention, +X right, +Y down, +Z forward). It need not be a unit vector. + + Returns: + The left and the right eye's gaze (tilt, pan) [deg], each shape (N, 2). + """ + version = version_deg.detach().float().contiguous() + vergence = vergence_deg.detach().float().to(version.device).contiguous() + length = math.sqrt(sum(value * value for value in baseline)) + left, right = torch.empty_like(version), torch.empty_like(version) + wp.launch( + binocular_gaze_angles_kernel, + dim=version.shape[0], + inputs=[ + wp.from_torch(version, dtype=wp.vec2f), + wp.from_torch(vergence), + wp.vec3f(*(value / length for value in baseline)), + ], + outputs=[wp.from_torch(left, dtype=wp.vec2f), wp.from_torch(right, dtype=wp.vec2f)], + device=str(version.device), + ) + return left, right + + +@cache +def make_binocular_gaze_step(mode: int) -> wp.Kernel: + """Return the binocular gaze step of one mode: :data:`SOFTWARE`, :data:`~isaaclab_fovi.mdp.gaze.PHYSICAL` or + :data:`~isaaclab_fovi.mdp.gaze.HYBRID`.""" + if mode not in (SOFTWARE, PHYSICAL, HYBRID): + raise ValueError(f"Unknown binocular gaze mode {mode!r}.") + + @wp.kernel(enable_backward=False, module="unique") + def binocular_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), + baseline: wp.vec3f, + step_size: wp.float32, + gaze_limit: wp.float32, + vergence_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), + version: wp.array(dtype=wp.vec2f), + left_deg: wp.array(dtype=wp.vec2f), + right_deg: wp.array(dtype=wp.vec2f), + state: wp.array2d(dtype=wp.float32), + targets: wp.array2d(dtype=wp.float32), + ): + """Move each pair of eyes by its actions (version tilt, version pan, vergence) and aim both retinas. + + The version moves as a single camera's gaze does in the same mode (see + :func:`~isaaclab_fovi.mdp.gaze.make_rig_gaze_step`); the vergence always moves the retinas. ``baseline`` is + the unit direction from the left eye to the right in the upright frame, and ``mounts`` the eyes' shared mount. + Software gaze reads no joints, and only hybrid gaze holds a fixation, so the arrays a mode leaves alone may be + empty. Writes both eyes' gaze angles ``left_deg`` and ``right_deg``, the joint ``targets`` (pan, tilt) and + ``state``: the version's direction from the rig's zero pose, the vergence, which the state alone holds, and + their velocities. + """ + i = wp.tid() + radius_rad = field_radius_deg * wp.float32(DEG_TO_RAD) + soft = version[i] + action = clamp_unit(wp.vec2f(actions[i, 0], actions[i, 1])) + head = wp.vec2f(0.0, 0.0) + if wp.static(mode == SOFTWARE): + soft = within(soft + action * step_size, gaze_limit) + if wp.static(mode != SOFTWARE): + head = head_angles(joint_pos, i, joints, signs) + # Commanded head steps add to the last targets; hybrid gaze steps from where the head is. + base = wp.vec2f(targets[i, 0], targets[i, 1]) + turn = action * step_size + if wp.static(mode == HYBRID): + if held_valid[i] != 0: + # The head turned since the last step: aim the version back at the fixation it holds. + soft = gaze_of(wp.quat_rotate_inv(mounts[i], held[i]), field_radius_deg) + soft = within(soft + action * 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) + verge = wp.clamp(state[i, 2] + wp.clamp(actions[i, 2], -1.0, 1.0) * step_size, 0.0, vergence_limit) + left, right = eye_gazes(soft, verge, baseline, field_radius_deg) + left_deg[i] = left * field_radius_deg + right_deg[i] = right * field_radius_deg + version[i] = soft + gaze = rig_gaze(head, soft, field_radius_deg) + state[i, 3] = (gaze[0] - state[i, 0]) / step_dt + state[i, 4] = (gaze[1] - state[i, 1]) / step_dt + state[i, 5] = (verge - state[i, 2]) / step_dt + state[i, 0] = gaze[0] + state[i, 1] = gaze[1] + state[i, 2] = verge + + return binocular_gaze_step + + +@wp.kernel(enable_backward=False) +def binocular_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, + has_rig: wp.int32, + clear_held: wp.int32, + targets: wp.array2d(dtype=wp.float32), + held_valid: wp.array(dtype=wp.int32), + version: wp.array(dtype=wp.vec2f), + left_deg: wp.array(dtype=wp.vec2f), + right_deg: wp.array(dtype=wp.vec2f), + state: wp.array2d(dtype=wp.float32), +): + """Put each reset environment's version on the optical axes, its vergence at zero and, with a rig (``has_rig``), + its joint targets at their defaults; the state starts at the default head's angles, at rest.""" + k = wp.tid() + i = k + if use_ids != 0: + i = ids[k] + version[i] = wp.vec2f(0.0, 0.0) + left_deg[i] = wp.vec2f(0.0, 0.0) + right_deg[i] = wp.vec2f(0.0, 0.0) + head = wp.vec2f(0.0, 0.0) + if has_rig != 0: + targets[i, 0] = default_joint_pos[i, joints[0]] + targets[i, 1] = default_joint_pos[i, joints[1]] + head = head_angles(default_joint_pos, i, joints, signs) / (field_radius_deg * wp.float32(DEG_TO_RAD)) + if clear_held != 0: + held_valid[i] = 0 + state[i, 0] = head[0] + state[i, 1] = head[1] + for column in range(2, 6): + state[i, column] = 0.0 + + +@wp.kernel(enable_backward=False) +def binocular_teacher_kernel( + points: wp.array(dtype=wp.vec3f), + left_positions: wp.array(dtype=wp.vec3f), + right_positions: wp.array(dtype=wp.vec3f), + mounts: wp.array(dtype=wp.quatf), + version: wp.array(dtype=wp.vec2f), + state: wp.array2d(dtype=wp.float32), + 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, + gaze_limit: wp.float32, + vergence_limit: wp.float32, + left_camera: CameraParams, + right_camera: CameraParams, + labels: wp.array2d(dtype=wp.float32), +): + """Labels (version tilt, version pan, vergence, valid) that fixate each point with both eyes. + + The version that fixates a point bisects the two eyes' lines of sight to it, and the vergence is the angle between + them; ``state`` holds the current vergence in its third column. A point is a valid target when each eye's camera + sees it and the fixation is within the limits. The version is labelled from where the next step starts: in hybrid + gaze the version re-aimed at the fixation it holds in ``held``, once ``held_valid`` is set. In physical gaze the + version actions turn the head, so they are labelled from ``heads``, the head's measured and commanded (tilt, pan) + in field radii, and never repeat a turn the head has yet to make. ``mode`` is the mode's code, and the arrays it + does not use may be empty. + """ + i = wp.tid() + mount = mounts[i] + left = wp.quat_rotate_inv(mount, wp.normalize(points[i] - left_positions[i])) + right = wp.quat_rotate_inv(mount, wp.normalize(points[i] - right_positions[i])) + desired = gaze_of(wp.transpose(frame) * wp.normalize(left + right), field_radius_deg) + angle = wp.atan2(wp.length(wp.cross(left, right)), wp.dot(left, right)) * wp.float32(RAD_TO_DEG) + verge = angle / field_radius_deg + ok = ( + project_direction(left, left_camera)[2] > 0.5 + and project_direction(right, right_camera)[2] > 0.5 + and wp.length(desired) <= gaze_limit + and verge <= vergence_limit + ) + step = wp.vec3f(0.0, 0.0, 0.0) + if ok: + start = version[i] + if mode == HYBRID: + if held_valid[i] != 0: + start = gaze_of(wp.transpose(frame) * wp.quat_rotate_inv(mount, held[i]), field_radius_deg) + turn = desired - start + if mode == PHYSICAL: + head = heads[i] + measured = wp.vec2f(head[0], head[1]) * field_radius_deg * wp.float32(DEG_TO_RAD) + turn = rig_gaze(measured, desired, field_radius_deg) - wp.vec2f(head[2], head[3]) + turn = clamp_unit(turn / step_size) + step = wp.vec3f(turn[0], turn[1], wp.clamp((verge - state[i, 2]) / step_size, -1.0, 1.0)) + labels[i, 0] = step[0] + labels[i, 1] = step[1] + labels[i, 2] = step[2] + labels[i, 3] = wp.where(ok, 1.0, 0.0) + + +@wp.kernel(enable_backward=False) +def offset_points_kernel( + positions: wp.array(dtype=wp.vec3f), + orientations: wp.array(dtype=wp.quatf), + offset: wp.vec3f, + points: wp.array(dtype=wp.vec3f), +): + """World points at ``offset`` in each frame.""" + i = wp.tid() + points[i] = positions[i] + wp.quat_rotate(orientations[i], offset) + + +def binocular_gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor: + """Version, vergence and their velocities, in field radii and field radii per second, shape (num_envs, 6).""" + term: BinocularGazeAction = env.action_manager.get_term(action_name) + return term.state + + +class BinocularGazeAction(ActionTerm): + """Moves two foveated cameras' gazes together: three actions step the version (tilt, pan) and the vergence. + + Actions, limits and the observed gaze are in field radii. An action of 1 changes the version's coordinates and + the vergence by ``step_size``; the version stays within ``gaze_limit`` of the eyes' optical axes, and the vergence + between zero, parallel lines of sight, and ``vergence_limit``. + + Both eyes ride one body with parallel optical axes and the same retina, on any renderer. + :attr:`~isaaclab_fovi.mdp.BinocularGazeActionCfg.mode` sets what the version actions + turn, as for a single camera's :class:`~isaaclab_fovi.mdp.GazeAction`: the retinas (``"software"``), the rig's + joints (``"physical"``), or the retinas at once while the rig follows (``"hybrid"``). The vergence always turns + the retinas. The modes that turn a rig need eyes without image roll, whose tilt and pan follow the rig's joints. + + The term owns the version and the vergence and sets both eyes' gaze angles from them each step, so a gaze set on + an eye directly lasts until the next step. Each episode starts with the version on the optical axes and the + vergence at zero. :attr:`state`, the observation, holds the version, with a rig its direction from the rig's zero + pose, the head's turn composed with the version, then the vergence, and their velocities. + """ + + cfg: BinocularGazeActionCfg + + is_graphable: ClassVar[bool] = True + """The gaze moves in :meth:`process_actions`; :meth:`apply_actions` at most writes a rig's joint targets.""" + + def __init__(self, cfg: BinocularGazeActionCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._right: FoveatedCamera = env.scene[cfg.right_asset_name] + left, right = self.left, self.right + if left.cfg.prim_path.rpartition("/")[0] != right.cfg.prim_path.rpartition("/")[0]: + # The version, the vergence and the baseline assume one rigid head that carries both eyes. + raise ValueError( + "Both eyes of a binocular gaze must be on one body: their prims need the same parent, got" + f" {left.cfg.prim_path!r} and {right.cfg.prim_path!r}." + ) + if cfg.mode != "software" and left.cfg.image_rotation_deg != 0: + raise ValueError( + f"BinocularGazeActionCfg.mode={cfg.mode!r} turns the eyes with a rig's pan and tilt joints, which a" + f" rolled image's tilt and pan do not follow; got image_rotation_deg={left.cfg.image_rotation_deg!r}." + ) + self.field_radius_deg = left.sampling_coords.fov / 2 + """Half the retina's field of view [deg].""" + if not math.isclose(right.sampling_coords.fov / 2, self.field_radius_deg, rel_tol=1e-6): + raise ValueError("Both eyes of a binocular gaze need the same retina field of view.") + if _rows(right.image_frame) != _rows(left.image_frame): + raise ValueError("Both eyes of a binocular gaze need the same image rotation.") + mount_left, mount_right = left.update_mount().torch, right.update_mount().torch + # The quaternions' dot product is +-1 for one orientation. + if (1 - (mount_left * mount_right).sum(-1).abs()).amax() > 1e-5: + raise ValueError("Both eyes of a binocular gaze need parallel optical axes.") + self.baseline = self._baseline(mount_left[0], left.data.pos_w.torch[0], right.data.pos_w.torch[0]) + """Unit direction from the left eye to the right, in the upright image frame.""" + self._raw: torch.Tensor | None = None + self._version = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec2f, device=self.device)) + self._state = ProxyArray(wp.zeros((self.num_envs, 6), dtype=wp.float32, device=self.device)) + """Version, vergence and their velocities; the vergence lives here alone.""" + self._mode_code = {"software": SOFTWARE, "physical": PHYSICAL, "hybrid": HYBRID}[cfg.mode] + # 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)) + self._held_valid = ProxyArray(wp.zeros(held, dtype=wp.int32, device=self.device)) + 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._step_launch: tuple[tuple, wp.Launch] | None = None + self._teacher_launch: tuple[tuple, wp.Launch] | None = None + self._heads_launch: tuple[wp.array, wp.Launch] | None = None + self._reset_ids = ProxyArray(wp.zeros(self.num_envs, dtype=wp.int32, device=self.device)) + self._reset_launches: dict[bool, wp.Launch] = {} + self.rig = None + """The articulation that turns both eyes, for physical and hybrid gaze.""" + if cfg.mode == "software": + # Software gaze reads no joints; its launches take empty arrays. + self._joint_ids = [0, 1] + self._targets = ProxyArray(wp.zeros((0, 2), dtype=wp.float32, device=self.device)) + self._no_joints = wp.zeros((0, 2), dtype=wp.float32, device=self.device) + self._no_limits = wp.zeros((0, 2), dtype=wp.vec2f, device=self.device) + self._signs = wp.vec2f(1.0, 1.0) + else: + self.rig = env.scene[cfg.rig.asset_name] + self._joint_ids = list(self.rig.find_joints(list(cfg.rig.joint_names), preserve_order=True)[0]) + # A list would become a new index array on every target write; with cameras rendering, a captured + # Newton physics step then faulted on freed memory. + self._joint_ids_wp = wp.array(self._joint_ids, dtype=wp.int32, device=self.device) + self._signs = wp.vec2f(*cfg.rig.joint_signs) + # Indexing the selected joints copies them, so the targets own their storage. + self._targets = ProxyArray(wp.from_torch(self.rig.data.default_joint_pos.torch[:, self._joint_ids])) + self._joints = wp.vec2i(*self._joint_ids) + self.reset() + + @property + def left(self) -> FoveatedCamera: + """The left eye.""" + return self._asset + + @property + def right(self) -> FoveatedCamera: + """The right eye.""" + return self._right + + @property + def action_dim(self) -> int: + return 3 + + @property + def raw_actions(self) -> torch.Tensor: + if self._raw is not None: + return self._raw + return torch.zeros(self.num_envs, 3, dtype=torch.float32, device=self.device) + + @property + def processed_actions(self) -> torch.Tensor: + return self._state.torch[:, :3] + + @property + def version(self) -> torch.Tensor: + """The software version (tilt, pan) from the eyes' optical axes, in field radii, shape (num_envs, 2).""" + return self._version.torch + + @property + def vergence(self) -> torch.Tensor: + """The vergence, the angle between the lines of sight, in field radii, shape (num_envs,).""" + return self._state.torch[:, 2] + + @property + def state(self) -> torch.Tensor: + """Version, vergence and their velocities, in field radii and field radii per second, shape (num_envs, 6).""" + return self._state.torch + + def process_actions(self, actions: torch.Tensor): + """Move the version and vergence by the supplied actions, shape (num_envs, 3), and aim both retinas.""" + if actions.dtype != torch.float32: + actions = actions.float() + left, right = self.left, self.right + if self.rig is None: + joint_pos, limits = self._no_joints, self._no_limits + else: + # Reading the properties refreshes the rig's joint buffers. + joint_pos, limits = self.rig.data.joint_pos.warp, self.rig.data.soft_joint_pos_limits.warp + # Hybrid gaze aims from the mount as the head stands now, which a lazily updated camera has not read yet. + mounts = left.update_mount() if self._mode_code == HYBRID else left.mount_quat_w_ros + key = (actions.data_ptr(), actions.stride(), actions.device) + arrays = (joint_pos, limits, mounts) + cached = self._step_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_binocular_gaze_step(self._mode_code), + self.num_envs, + [ + wp.from_torch(actions), + joint_pos, + limits, + self._joints, + self._signs, + mounts, + self.baseline, + self.cfg.step_size, + self.cfg.gaze_limit, + self.cfg.vergence_limit, + (self.cfg.rig.max_step_deg if self.rig is not None else 0.0) / self.field_radius_deg, + self._env.step_dt, + self.field_radius_deg, + ], + [ + self._held, + self._held_valid, + self._version, + left.gaze_angles, + right.gaze_angles, + self._state, + self._targets, + ], + self.device, + ) + self._step_launch = ((key, arrays), launch) + self._raw = actions + self._step_launch[1].launch(warp_stream(self.device)) + left.set_gaze_angles(left.gaze_angles.torch) + right.set_gaze_angles(right.gaze_angles.torch) + + def apply_actions(self): + if self.rig is not None: + self.rig.actuators.target_command.set_position_index( + value=self._targets.torch, joint_ids=self._joint_ids_wp + ) + + def reset(self, env_ids=None): + # The action manager zeroes the reset environments' actions itself. + indexed = env_ids is not None + count = self.num_envs + if indexed: + if isinstance(env_ids, slice): + env_ids = torch.arange(*env_ids.indices(self.num_envs), device=self.device) + count = len(env_ids) + if count == 0: + return + self._reset_ids.torch[:count] = torch.as_tensor(env_ids, device=self.device) + left, right = self.left, self.right + launch = self._reset_launches.get(indexed) + if launch is None: + default = self._no_joints if self.rig is None else self.rig.data.default_joint_pos.warp + launch = self._reset_launches[indexed] = record_launch( + binocular_gaze_reset_kernel, + self.num_envs, + [ + self._reset_ids, + int(indexed), + default, + self._joints, + self._signs, + self.field_radius_deg, + int(self.rig is not None), + int(self._mode_code == HYBRID), + ], + [ + self._targets, + self._held_valid, + self._version, + left.gaze_angles, + right.gaze_angles, + self._state, + ], + self.device, + ) + launch.set_dim(count) + launch.launch(warp_stream(self.device)) + left.set_gaze_angles(left.gaze_angles.torch) + right.set_gaze_angles(right.gaze_angles.torch) + + 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 version actions turn the head.""" + if 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 teacher_labels(self, points: wp.array, labels: wp.array) -> None: + """Write the teacher's labels (version tilt, version pan, vergence, valid) toward world ``points`` [m]. + + Args: + points: One world point per environment, ``vec3f``. + labels: The output, shape (num_envs, 4). + """ + left, right = self.left, self.right + # Both eyes read their poses, without capturing an image. + mounts = left.update_mount() + right.update_mount() + heads = self.head_and_target() + left_positions, right_positions = left.mount_pos_w.warp, right.mount_pos_w.warp + sources = (points, labels, mounts, left_positions, right_positions) + if self._teacher_launch is None or any(a is not b for a, b in zip(self._teacher_launch[0], sources)): + launch = record_launch( + binocular_teacher_kernel, + self.num_envs, + [ + points, + left_positions, + right_positions, + mounts, + self._version, + self._state, + heads, + self._held, + self._held_valid, + self._mode_code, + left.image_frame, + self.field_radius_deg, + self.cfg.step_size, + self.cfg.gaze_limit, + self.cfg.vergence_limit, + left.projection_params, + right.projection_params, + ], + [labels], + self.device, + ) + self._teacher_launch = (sources, launch) + self._teacher_launch[1].launch(warp_stream(self.device)) + + def _baseline(self, mount: torch.Tensor, left: torch.Tensor, right: torch.Tensor) -> wp.vec3f: + """The unit direction from the left eye to the right in the upright frame; it must cross the optical axes.""" + local = quat_apply_inverse(mount[None], (right - left)[None])[0] + upright = torch.tensor(_rows(self.left.image_frame), device=mount.device).T @ local + length = float(upright.norm()) + if length < 1e-6 or abs(float(upright[2])) > 0.1 * length: + raise ValueError("The eyes of a binocular gaze need a baseline across their optical axes.") + return wp.vec3f(*(upright / length).tolist()) + + +class binocular_gaze_teacher_labels(ManagerTermBase): + """The teacher's binocular gaze action toward a target point, and its validity, shape (num_envs, 4). + + The target is a point fixed to an asset (``target_cfg``), or any world point each environment supplies + (``target_w``), as for :class:`~isaaclab_fovi.mdp.gaze_teacher_labels`. + + A training label, never a policy input. + + Args: + 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 binocular 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): + super().__init__(cfg, env) + self._gaze: BinocularGazeAction = env.action_manager.get_term(cfg.params.get("action_name", "gaze")) + self._points = wp.zeros(env.num_envs, dtype=wp.vec3f, device=env.device) + self._labels = ProxyArray(wp.zeros((env.num_envs, 4), dtype=wp.float32, device=env.device)) + + def __call__( + self, + env: ManagerBasedEnv, + 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: + if (target_cfg is None) == (target_w is None): + raise ValueError("binocular_gaze_teacher_labels needs one target: target_cfg or target_w.") + if target_w is not None: + points = target_w(env) + if tuple(points.shape) != (env.num_envs, 3): + raise ValueError( + f"target_w must return points of shape ({env.num_envs}, 3), got {tuple(points.shape)}." + ) + wp.to_torch(self._points).copy_(points + points.new_tensor(offset)) + self._gaze.teacher_labels(self._points, self._labels.warp) + return self._labels.torch + data = env.scene[target_cfg.name].data + body = target_body_index(target_cfg) + if body is None: + positions, orientations = data.root_pos_w.warp, data.root_quat_w.warp + else: + positions = wp.from_torch(data.body_pos_w.torch[:, body], dtype=wp.vec3f) + orientations = wp.from_torch(data.body_quat_w.torch[:, body], dtype=wp.quatf) + wp.launch( + offset_points_kernel, + env.num_envs, + [positions, orientations, wp.vec3f(*offset)], + [self._points], + device=str(env.device), + stream=warp_stream(env.device), + ) + self._gaze.teacher_labels(self._points, self._labels.warp) + return self._labels.torch + + +def _rows(matrix: wp.mat33f) -> list[list[float]]: + """A 3 x 3 Warp matrix as nested lists of rows.""" + return [[float(matrix[row][col]) for col in range(3)] for row in range(3)] diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py index 862897ab93ca..1570a8cef772 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,10 @@ 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_wp + ) def reset(self, env_ids=None): # The action manager zeroes the reset environments' actions itself. @@ -320,6 +596,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 +632,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 +648,143 @@ 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) + # A list would become a new index array on every target write; with cameras rendering, a captured + # Newton physics step then faulted on freed memory. + self._joint_ids_wp = wp.array(self._joint_ids, dtype=wp.int32, device=self.device) + 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 +794,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 +836,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 +858,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..ccfda3556e49 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py @@ -15,8 +15,36 @@ from isaaclab.utils import configclass if TYPE_CHECKING: + from .binocular_gaze import BinocularGazeAction 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 +53,83 @@ 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() + + +BINOCULAR_GAZE_MODES = ("software", "physical", "hybrid") +"""How the binocular gaze action moves its version; see :class:`~isaaclab_fovi.mdp.BinocularGazeAction`.""" + + +@configclass +class BinocularGazeActionCfg(ActionTermCfg): + """Configuration of :class:`~isaaclab_fovi.mdp.binocular_gaze.BinocularGazeAction`.""" + + class_type: type[BinocularGazeAction] | str = "{DIR}.binocular_gaze:BinocularGazeAction" + asset_name: str = MISSING + """Scene name of the left eye's foveated camera.""" + right_asset_name: str = MISSING + """Scene name of the right eye's foveated camera, on the same body as the left with a parallel optical axis.""" + mode: str = "software" + """``"software"``, ``"physical"`` or ``"hybrid"``: what the version actions turn; vergence is always software.""" + rig: GazeRigCfg | None = None + """The articulation that turns both eyes; needed by physical and hybrid gaze.""" + step_size: float = 0.1 + """Change of the version's coordinates and of the vergence per step at an action of 1, in field radii.""" + gaze_limit: float = 1.0 + """Largest distance of the software version from the eyes' optical axes, in field radii.""" + vergence_limit: float = 0.5 + """Largest vergence, the angle between the two lines of sight, in field radii.""" + + def validate_config(self) -> None: + """Reject invalid steps, limits and modes, and rig settings that a mode cannot use.""" + for name, value in ( + ("step_size", self.step_size), + ("gaze_limit", self.gaze_limit), + ("vergence_limit", self.vergence_limit), + ): + if not _positive_finite(value): + raise ValueError(f"BinocularGazeActionCfg.{name} must be positive and finite, got {value!r}.") + if self.asset_name == self.right_asset_name: + raise ValueError("BinocularGazeActionCfg needs two different eyes.") + if self.mode not in BINOCULAR_GAZE_MODES: + raise ValueError(f"BinocularGazeActionCfg.mode must be one of {BINOCULAR_GAZE_MODES}, got {self.mode!r}.") + if self.mode == "software": + return + if self.rig is None: + raise ValueError(f"BinocularGazeActionCfg.mode={self.mode!r} turns a rig's joints; set its rig.") + 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/eyeball.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/eyeball.py new file mode 100644 index 000000000000..c910a17d0566 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/eyeball.py @@ -0,0 +1,157 @@ +# 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 + +"""An eyeball that marks a foveated camera in the Newton viewer windows, turned with the camera's gaze.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, ClassVar + +import torch +import warp as wp + +from isaaclab.sim import SimulationContext +from isaaclab.utils.math import quat_apply, quat_from_matrix, quat_mul + +EYEBALL_USD = str(Path(__file__).resolve().parents[1] / "assets" / "data" / "eyeball.usda") +"""FOVI-Dex's eyeball, about 24 mm across, with its cornea facing +Z.""" +EYEBALL_SCALE = 2.0 +"""Scale of the drawn eyeball: 48 mm across, which leaves a gap between eyes 65 mm apart.""" +EYEBALL_FRONT = 0.0127 +"""Distance from the eyeball's centre to the front of its cornea, as authored [m].""" +EYEBALL_CLEARANCE = 0.002 +"""Gap from the front of the drawn cornea to the camera [m].""" + + +def gaze_matrix(angles_deg: torch.Tensor) -> torch.Tensor: + """Pan-then-tilt rotations of gazes (tilt, pan) [deg], shape (N, 2), as (N, 3, 3) matrices that turn a camera's + optical axis (ROS +Z) onto each line of sight; the Torch twin of the gaze kernels' ``gaze_rotation``.""" + tilt, pan = angles_deg.float().deg2rad().unbind(-1) + x, y, z = -tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos() + pitch, roll = torch.atan2(x, z), torch.atan2(-y, torch.hypot(x, z)) + cp, sp, cr, sr = pitch.cos(), pitch.sin(), roll.cos(), roll.sin() + zero = torch.zeros_like(cp) + rows = (cp, sp * sr, sp * cr), (zero, cr, -sr), (-sp, cp * sr, cp * cr) + return torch.stack([torch.stack(row, dim=-1) for row in rows], dim=-2) + + +class ViewerEyeball: + """Draw FOVI-Dex's eyeball at each of a camera's environments in every Newton viewer window, as mesh instances + that the cameras' own images never see. The cornea sits just behind the camera, and the eyeball turns with the + gaze. + + The asset's iris fibers and veins are curves, which the viewer could only draw as lines that surfaces do not hide, + so they would show through the eyeball; the iris keeps its base, collarette and limbal ring. + """ + + _parts: ClassVar[list[tuple[str, list, list[int], tuple[float, float, float], float, float]] | None] = None + """Each mesh's name, points, triangle indices, color, opacity and roughness, read from :data:`EYEBALL_USD` once.""" + + def __init__(self, name: str): + """Create the eyeball, drawn under the viewer path ``name``.""" + self.name = name + self._windows: dict[int, Any] = {} + """The Newton viewer windows the meshes are registered in, by identity.""" + self._arrays: list[wp.array] = [] + """The logged arrays, which stay alive until the next draw replaces them.""" + + @classmethod + def parts(cls) -> list[tuple[str, list, list[int], tuple[float, float, float], float, float]]: + """The eyeball's meshes: name, points, triangle indices, color, opacity and roughness.""" + if cls._parts is None: + # USD comes from Kit when the selected backends start it, so it is imported once the simulation runs. + from pxr import Usd, UsdGeom, UsdShade + + parts = [] + stage = Usd.Stage.Open(EYEBALL_USD) # The traversal needs the stage alive. + for prim in stage.Traverse(): + material = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()[0] + if not material or not prim.IsA(UsdGeom.Mesh): + continue + shader = material.ComputeSurfaceSource()[0] + mesh = UsdGeom.Mesh(prim) + counts, indices = mesh.GetFaceVertexCountsAttr().Get(), mesh.GetFaceVertexIndicesAttr().Get() + triangles, start = [], 0 + for count in counts: + # A fan of triangles from each face's first vertex. + for k in range(start + 1, start + count - 1): + triangles += [indices[start], indices[k], indices[k + 1]] + start += count + points = [tuple(point) for point in mesh.GetPointsAttr().Get()] + color = tuple(float(value) for value in shader.GetInput("diffuseColor").Get()) + opacity, roughness = (float(shader.GetInput(key).Get()) for key in ("opacity", "roughness")) + parts.append((prim.GetName(), points, triangles, color, opacity, roughness)) + cls._parts = parts + return cls._parts + + def windows(self) -> list[Any]: + """The open Newton viewer windows, each with the eyeball's meshes registered.""" + sim = SimulationContext.instance() + windows = [] + for visualizer in [] if sim is None else sim.visualizers: + window = getattr(visualizer, "_viewer", None) + if visualizer.cfg.backend.visualizer_type != "newton" or window is None: + continue + if id(window) not in self._windows: + for part, points, triangles, *_ in self.parts(): + window.log_mesh( + f"/isaaclab_fovi/eyeball/{part}", + wp.array(points, dtype=wp.vec3, device=window.device), + wp.array(triangles, dtype=wp.int32, device=window.device), + hidden=True, + ) + self._windows[id(window)] = window + windows.append(window) + return windows + + def draw(self, positions: torch.Tensor, mounts: torch.Tensor, gazes: torch.Tensor, image_frame: torch.Tensor): + """Draw an eyeball at each camera. + + Args: + positions: The cameras' positions [m], shape (N, 3). + mounts: The cameras' orientations (x, y, z, w) before the gaze, ROS convention, shape (N, 4). + gazes: The cameras' gazes (tilt, pan) [deg], shape (N, 2). + image_frame: Rotation from the upright image frame, in which gazes are measured, to the camera's frame, + shape (3, 3). + """ + windows = self.windows() + if not windows: + return + frame = image_frame.to(gazes.device, torch.float32) + turn = quat_from_matrix(frame @ gaze_matrix(gazes) @ frame.T) + quats = quat_mul(mounts.float(), turn) + forward = quat_apply(quats, positions.new_tensor((0.0, 0.0, 1.0)).expand(len(positions), -1).float()) + centres = positions.float() - forward * (EYEBALL_FRONT * EYEBALL_SCALE + EYEBALL_CLEARANCE) + poses = torch.cat((centres, quats), dim=-1).cpu().numpy() + count = len(positions) + self._arrays = [] + for window in windows: + xforms = wp.array(poses, dtype=wp.transform, device=window.device) + scales = wp.array([wp.vec3(EYEBALL_SCALE)] * count, dtype=wp.vec3, device=window.device) + self._arrays += [xforms, scales] + for part, _, _, color, opacity, roughness in self.parts(): + colors = wp.array([wp.vec3(*color)] * count, dtype=wp.vec3, device=window.device) + materials = wp.array([wp.vec4(roughness, 0.0, 0.0, 0.0)] * count, dtype=wp.vec4, device=window.device) + opacities = wp.array([opacity] * count, dtype=wp.float32, device=window.device) + window.log_instances( + f"{self.name}/{part}", + f"/isaaclab_fovi/eyeball/{part}", + xforms, + scales, + colors, + materials, + opacities=opacities, + ) + self._arrays += [colors, materials, opacities] + + def hide(self) -> None: + """Hide the eyeball in every window it was drawn in.""" + for window in self._windows.values(): + for part, *_ in self.parts(): + window.log_instances( + f"{self.name}/{part}", f"/isaaclab_fovi/eyeball/{part}", None, None, None, None, hidden=True + ) + self._arrays = [] diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 7fa4f9f2d5ab..ae59be4ebf77 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -24,6 +24,7 @@ from isaaclab.utils.warp import ProxyArray from .calibrated_geometry import camera_model_from_spawn, retinal_directions +from .eyeball import ViewerEyeball from .gaze_controls import add_viewer_gaze_controls from .gaze_kernels import ( CameraParams, @@ -107,6 +108,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.""" @@ -164,6 +167,8 @@ def __init__(self, cfg: FoveatedCameraCfg, *, turns_pose_by_gaze: bool = False): """Retinas built for :meth:`set_cmf_a`, by CMF constant.""" self.mount_turns = 0 """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount.""" + self._eyeball: ViewerEyeball | None = None + """The eyeball the Newton viewer windows draw at the camera while it shows its debug visualization.""" super().__init__(cfg) # Each Newton viewer window draws the controls while it shows this camera. add_viewer_gaze_controls(self) @@ -226,15 +231,56 @@ 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 shows_eyeball(self) -> bool: + """Whether the Newton viewer windows draw an eyeball at the camera, turned with its gaze: the camera's debug + visualization, which ``cfg.debug_vis`` and :meth:`set_debug_vis` switch.""" + return self._is_visualizing + + def _set_debug_vis_impl(self, debug_vis: bool) -> None: + """Create the eyeball that marks the camera in the Newton viewer windows, or hide it.""" + if debug_vis and self._eyeball is None: + self._eyeball = ViewerEyeball(f"/isaaclab_fovi/eyeballs/{id(self)}") + elif not debug_vis and self._eyeball is not None: + self._eyeball.hide() + + def _debug_vis_callback(self, event) -> None: + """Draw the eyeball at each environment's camera, turned with its gaze.""" + if not self.is_initialized or self._eyeball is None: + return + mounts = self.update_mount().torch + frame = torch.tensor([[self.image_frame[i][j] for j in range(3)] for i in range(3)]) + self._eyeball.draw(self.mount_pos_w.torch, mounts, self.gaze_angles.torch, frame) + @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 +299,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/isaaclab_fovi/sensors/gaze_controls.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py index 5e3e6bb855d7..68ec386da463 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py @@ -28,7 +28,9 @@ class ViewerGazeControls: A window draws the controls while the camera is its camera source, so a camera the viewer cannot show, or another camera chosen in the window's camera menu, has none. The tilt and pan sliders show the first environment's gaze every frame, so they follow whatever sets it, such as a gaze action or a drag in the viewer. Moving one sets that - gaze in every environment; a gaze action that sets the gaze every step overrides them. The foveation slider steps + gaze in every environment; a gaze action that sets the gaze every step overrides them. A checkbox switches the + camera's debug visualization, an eyeball that the windows draw at the camera, turned with its gaze, and that shows + in the perspective view. The foveation slider steps through :attr:`cmf_a_values` and the camera's starting CMF constant where :meth:`FoveatedCamera.set_cmf_a` can change the retina, and otherwise shows the CMF constant and why it is fixed. A change in any window redraws the camera view of every window. @@ -72,7 +74,7 @@ def _render(self, imgui: Any, sensor: Any) -> None: imgui.pop_id() def _draw_controls(self, imgui: Any, camera: FoveatedCamera) -> None: - """Draw the gaze sliders, the center button and the foveation control.""" + """Draw the gaze sliders, the center button, the eyeball checkbox and the foveation control.""" tilt, pan = camera.gaze_angles.torch[0].tolist() tilt_changed, tilt = imgui.slider_float("Gaze tilt", tilt, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") pan_changed, pan = imgui.slider_float("Gaze pan", pan, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") @@ -85,6 +87,11 @@ def _draw_controls(self, imgui: Any, camera: FoveatedCamera) -> None: gaze[:] = gaze.new_tensor((0.0, 0.0) if center else (tilt, pan)) camera.set_gaze_angles(gaze) self._redraw() + changed, shown = imgui.checkbox("Show eyeball", camera.shows_eyeball) + if imgui.is_item_hovered(): + imgui.set_tooltip("Draw an eyeball at the camera, turned with its gaze; the perspective view shows it.") + if changed: + camera.set_debug_vis(shown) self._draw_foveation(imgui, camera) def _draw_foveation(self, imgui: Any, camera: FoveatedCamera) -> None: diff --git a/source/isaaclab_fovi/pyproject.toml b/source/isaaclab_fovi/pyproject.toml index b182018f8f78..9be0fa08699c 100644 --- a/source/isaaclab_fovi/pyproject.toml +++ b/source/isaaclab_fovi/pyproject.toml @@ -37,3 +37,4 @@ include = ["isaaclab_fovi", "isaaclab_fovi.*"] [tool.setuptools.package-data] "*" = ["*.pyi"] +"isaaclab_fovi.assets" = ["data/*.usda"] diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py index ad53e65feed4..4f192d3a27a0 100644 --- a/source/isaaclab_fovi/test/foveated_render_cases.py +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -284,6 +284,192 @@ 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/base/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 binocular_gaze_fixates_a_near_point_with_both_eyes(backend: tuple): + """Binocular hybrid gaze on the pan-tilt mount: the teacher's labels bring both lines of sight onto a near point. + + The point is 0.4 m away and 15 degrees to the left, where the vergence matters. After the head settles, the two + eyes' optical axes, gaze included, pass within a millimetre of the point and of each other, and the head carries + the version. A reset brings both eyes back to parallel lines of sight on the optical axes. + """ + import warp as wp + from isaaclab_fovi.assets import PAN_TILT_CFG, PAN_TILT_STEREO_BASELINE, PAN_TILT_STEREO_OFFSETS + from isaaclab_fovi.mdp import BinocularGazeActionCfg, GazeRigCfg, binocular_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 + link = "{ENV_REGEX_NS}/PanTilt/base/pan_link/tilt_link" + + def eye(name, offset): + return FoveatedCameraCfg( + prim_path=f"{link}/{name}", + data_types=["distance_to_camera"], + renderer_cfg=renderer_cfg(), + spawn=sim_utils.PinholeCameraCfg(clipping_range=CLIPPING_RANGE), + foveated_res=16, + offset=offset, + ) + + @configclass + class SceneCfg(InteractiveSceneCfg): + head = PAN_TILT_CFG.replace(init_state=PAN_TILT_CFG.init_state.replace(pos=(0.0, 0.0, 0.5))) + left_eye = eye("LeftEye", PAN_TILT_STEREO_OFFSETS[0]) + right_eye = eye("RightEye", PAN_TILT_STEREO_OFFSETS[1]) + + @configclass + class ActionsCfg: + gaze = BinocularGazeActionCfg( + asset_name="left_eye", right_asset_name="right_eye", mode="hybrid", rig=GazeRigCfg(asset_name="head") + ) + + @configclass + class ObservationsCfg: + @configclass + class PolicyCfg(ObservationGroupCfg): + gaze = ObservationTermCfg(func=binocular_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, render_interval=4, physics=physics_cfg, device=DEVICE) + + sim_utils.create_new_stage() + env = ManagerBasedEnv(EnvCfg()) + try: + env.reset() + gaze = env.action_manager.get_term("gaze") + left, right, head = env.scene["left_eye"], env.scene["right_eye"], env.scene["head"] + pan_joint = head.find_joints(["pan_joint"])[0][0] + pan = math.radians(15.0) + point = env.scene.env_origins[:1] + torch.tensor( + [[-0.4 * math.sin(pan), 0.4 * math.cos(pan), 0.5]], device=env.device + ) + labels = torch.zeros(1, 4, device=env.device) + point_wp, labels_wp = wp.from_torch(point, dtype=wp.vec3f), wp.from_torch(labels) + for _ in range(45): + gaze.teacher_labels(point_wp, labels_wp) + assert labels[0, 3] == 1.0 + env.step(labels[:, :3]) + + axis = torch.tensor([[0.0, 0.0, 1.0]], device=env.device) + lines = [(eye.data.pos_w.torch[:1], quat_apply(eye.data.quat_w_ros.torch[:1], axis)) for eye in (left, right)] + for origin, direction in lines: + # The point's distance from each eye's line of sight. + offset = point - origin + assert float(torch.linalg.cross(offset, direction).norm()) < 1e-3 + # The head carries the version, and the retinas only the vergence. + assert math.degrees(float(head.data.joint_pos.torch[0, pan_joint])) == pytest.approx(15.0, abs=1.0) + assert float(gaze.version.abs().max()) < 0.01 + expected = 2 * math.degrees(math.atan2(PAN_TILT_STEREO_BASELINE / 2, 0.4)) / gaze.field_radius_deg + assert float(gaze.vergence[0]) == pytest.approx(expected, rel=0.05) + + env.reset() + assert not gaze.vergence.any() and not gaze.version.any() + assert not left.gaze_angles.torch.any() and not right.gaze_angles.torch.any() + 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..28235f4a2cbe 100644 --- a/source/isaaclab_fovi/test/test_active_gaze.py +++ b/source/isaaclab_fovi/test/test_active_gaze.py @@ -12,25 +12,46 @@ import torch import warp as wp from fovi.sensing.projection import CameraModel +from isaaclab_fovi.mdp.binocular_gaze import ( + SOFTWARE, + BinocularGazeAction, + binocular_gaze_angles, + binocular_gaze_teacher_labels, + binocular_teacher_kernel, + make_binocular_gaze_step, +) 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 BinocularGazeActionCfg, 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 +70,221 @@ 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 + + +HALF_BASELINE = 0.0325 +IDENTITY = wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) +VERGENCE_LIMIT = 0.5 + + +class BinocularStep: + """One pair of eyes, the left at -x and the right at +x of an unturned ROS mount, on the rig of the single-camera + cases, stepped by :func:`make_binocular_gaze_step`'s kernel.""" + + def __init__(self, mode: int): + self.mode = mode + # Software gaze reads no joints, and only hybrid gaze holds a fixation: the term gives them empty arrays. + rig = 0 if mode == SOFTWARE else 1 + held = 1 if mode == HYBRID else 0 + self.joint_pos = torch.zeros(rig, 3) + self.limits = torch.tensor([[[-0.5, 0.5], [-0.2, 0.2], [-1.0, 1.0]]] * rig).reshape(rig, 3, 2) + self.mount = yaw_left(0.0) + self.held = torch.zeros(held, 3) + self.held_valid = torch.zeros(held, dtype=torch.int32) + self.version = torch.zeros(1, 2) + self.left = torch.zeros(1, 2) + self.right = torch.zeros(1, 2) + self.state = torch.zeros(1, 6) + self.targets = torch.zeros(rig, 2) + + def __call__(self, actions) -> None: + with torch_stream("cpu"): + wp.launch( + make_binocular_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), + wp.vec3f(1.0, 0.0, 0.0), + STEP, + LIMIT, + VERGENCE_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.version, dtype=wp.vec2f), + wp.from_torch(self.left, dtype=wp.vec2f), + wp.from_torch(self.right, dtype=wp.vec2f), + wp.from_torch(self.state), + wp.from_torch(self.targets), + ], + ) + + +def binocular_labels( + points: torch.Tensor, + mount: torch.Tensor, + mode: int = SOFTWARE, + heads: torch.Tensor | None = None, + version: torch.Tensor | None = None, + held: torch.Tensor | None = None, +) -> torch.Tensor: + """The binocular teacher's labels at a step of one field radius, for eyes at -x and +x of ``mount``, ``points`` + shape (N, 3): from a zero version and vergence, or ``version``, and in hybrid gaze a ``held`` fixation.""" + count = len(points) + eyes = quat_apply(mount.repeat(count, 1), torch.tensor([[HALF_BASELINE, 0.0, 0.0]]).repeat(count, 1)) + heads = torch.zeros(1, 4) if heads is None else heads + version = torch.zeros(1, 2) if version is None else version + held = torch.zeros(0, 3) if held is None else held.repeat(count, 1) + labels = torch.zeros(count, 4) + camera = camera_params(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))) + with torch_stream("cpu"): + wp.launch( + binocular_teacher_kernel, + dim=count, + inputs=[ + wp.from_torch(points, dtype=wp.vec3f), + wp.from_torch(-eyes, dtype=wp.vec3f), + wp.from_torch(eyes.contiguous(), dtype=wp.vec3f), + wp.from_torch(mount.repeat(count, 1).contiguous(), dtype=wp.quatf), + wp.from_torch(version.repeat(count, 1).contiguous(), dtype=wp.vec2f), + wp.from_torch(torch.zeros(count, 6)), + wp.from_torch(heads.repeat(count, 1).contiguous(), dtype=wp.vec4f), + wp.from_torch(held.contiguous(), dtype=wp.vec3f), + wp.from_torch(torch.ones(len(held), dtype=torch.int32)), + mode, + IDENTITY, + FIELD_RADIUS, + 1.0, + LIMIT, + VERGENCE_LIMIT, + camera, + camera, + ], + outputs=[wp.from_torch(labels)], + ) + return labels + + @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 +340,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 +353,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 +395,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 +431,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 +522,317 @@ 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]) + + +# -- Binocular gaze ---------------------------------------------------------------------------------------------------- + + +def test_vergence_turns_the_eyes_toward_each_other_so_their_lines_of_sight_meet(): + eyes = BinocularStep(SOFTWARE) + eyes([0.0, 0.0, 1.0]) # converge a full step + half = STEP * FIELD_RADIUS / 2 + # Each eye turns half the vergence toward the other: the left eye right (negative pan), the right eye left. + torch.testing.assert_close(eyes.left[0], torch.tensor([0.0, -half])) + torch.testing.assert_close(eyes.right[0], torch.tensor([0.0, half])) + torch.testing.assert_close(eyes.state[0], torch.tensor([0.0, 0.0, STEP, 0.0, 0.0, STEP / 0.5])) + # Off the optical axis the lines of sight still meet: they and the baseline lie in one plane. + eyes([1.0, 1.0, 1.0]) + left, right = angles_to_direction(eyes.left), angles_to_direction(eyes.right) + assert abs(float(torch.linalg.cross(left, right)[0] @ torch.tensor([1.0, 0.0, 0.0]))) < 1e-6 + angle = math.degrees(math.acos(float((left * right).sum()))) + assert angle == pytest.approx(2 * STEP * FIELD_RADIUS, abs=1e-3) + torch.testing.assert_close(eyes.version[0], torch.tensor([STEP, STEP])) + # Vergence stops at parallel lines of sight and at the limit. + eyes([0.0, 0.0, -5.0]) + eyes([0.0, 0.0, -5.0]) + assert float(eyes.state[0, 2]) == 0.0 + for _ in range(int(VERGENCE_LIMIT / STEP) + 2): + eyes([0.0, 0.0, 1.0]) + assert float(eyes.state[0, 2]) == pytest.approx(VERGENCE_LIMIT) + + +def test_binocular_gaze_angles_aim_the_eyes_as_the_action_does(): + eyes = BinocularStep(SOFTWARE) + eyes([1.0, -0.5, 1.0]) + eyes([0.0, 0.0, 1.0]) + # A longer baseline in the same direction aims the eyes the same way. + left, right = binocular_gaze_angles(eyes.version * FIELD_RADIUS, eyes.state[:, 2] * FIELD_RADIUS, (2.0, 0.0, 0.0)) + torch.testing.assert_close(left, eyes.left, atol=1e-5, rtol=0) + torch.testing.assert_close(right, eyes.right, atol=1e-5, rtol=0) + + +def test_hybrid_binocular_gaze_turns_the_version_at_once_while_the_head_follows(): + eyes = BinocularStep(HYBRID) + eyes([0.0, 1.0, 1.0]) # pan left a full step and converge + torch.testing.assert_close(eyes.version[0], torch.tensor([0.0, STEP])) + torch.testing.assert_close(eyes.targets[0], torch.tensor([HEAD_STEP * RADIUS_RAD, 0.0])) + # The head turns left by 3 degrees: the version comes back by as much and the vergence stays. + eyes.mount = yaw_left(3.0) + eyes.joint_pos[0, 1] = math.radians(3.0) + eyes([0.0, 0.0, 0.0]) + torch.testing.assert_close(eyes.version[0, 1], torch.tensor(STEP - 3.0 / FIELD_RADIUS), atol=1e-5, rtol=0) + torch.testing.assert_close(eyes.state[0, :3], torch.tensor([0.0, STEP, STEP]), atol=1e-5, rtol=0) + + +def test_binocular_teacher_fixates_a_point_with_both_eyes(): + distance = 1.0 + # Ahead and up, and then behind the eyes; the ROS mount is unturned, so world and camera frames agree. + points = torch.tensor([[0.0, -0.2, distance], [0.0, 0.0, -1.0]]) + labels = binocular_labels(points, yaw_left(0.0)) + # With a step of one field radius the labels are the fixation itself: up, straight ahead, and converged. + tilt = math.degrees(math.atan2(0.2, distance)) + vergence = 2 * math.degrees(math.atan2(HALF_BASELINE, math.hypot(distance, 0.2))) + torch.testing.assert_close(labels[0], torch.tensor([tilt, 0.0, vergence, FIELD_RADIUS]) / FIELD_RADIUS) + torch.testing.assert_close(labels[1], torch.zeros(4)) + + +def test_physical_binocular_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. + mount = turn(20.0, 0.0) + heads = torch.tensor([[20.0, 0.0, 20.0, 5.0]]) / FIELD_RADIUS + # A point 2 m away, 22 degrees up and 7 left of the rig's zero pose. + point = 2.0 * quat_apply(turn(22.0, 7.0), torch.tensor([[0.0, 0.0, 1.0]])) + labels = binocular_labels(point, mount, PHYSICAL, heads=heads) + assert labels[0, 3] == 1.0 + # The commanded head plus the version label faces the bisector of the two eyes' lines of sight to the point. + eyes = quat_apply(mount, torch.tensor([[HALF_BASELINE, 0.0, 0.0]])) + bisector = torch.nn.functional.normalize( + torch.nn.functional.normalize(point + eyes, dim=-1) + torch.nn.functional.normalize(point - eyes, dim=-1), + dim=-1, + ) + tilt, pan = (torch.tensor([20.0, 5.0]) + labels[0, :2] * FIELD_RADIUS).tolist() + facing = quat_apply(turn(tilt, pan), torch.tensor([[0.0, 0.0, 1.0]])) + torch.testing.assert_close(facing, bisector, atol=1e-5, rtol=0) + + +def test_hybrid_binocular_teacher_labels_from_the_version_the_next_step_starts_at(): + # The head has turned left 3 degrees since the last step, under a fixation held on a point 2 m away. The stored + # version still holds the last step's angle, but the next step re-aims it at the fixation first. + mount = yaw_left(3.0) + point = 2.0 * quat_apply(turn(2.0, 7.5), torch.tensor([[0.0, 0.0, 1.0]])) + eyes = quat_apply(mount, torch.tensor([[HALF_BASELINE, 0.0, 0.0]])) + held = torch.nn.functional.normalize( + torch.nn.functional.normalize(point + eyes, dim=-1) + torch.nn.functional.normalize(point - eyes, dim=-1), + dim=-1, + ) + stale = torch.tensor([[2.0, 7.5]]) / FIELD_RADIUS + labels = binocular_labels(point, mount, HYBRID, version=stale, held=held) + # The fixation is on the point already, so the version needs no further turn; from the stored version the labels + # would ask for the head's 3 degrees back. + assert labels[0, 3] == 1.0 + torch.testing.assert_close(labels[0, :2], torch.zeros(2), atol=1e-5, rtol=0) + + +def test_binocular_gaze_rejects_eyes_on_different_bodies(): + # The version, the vergence and the baseline assume one rigid head, so the eyes' prims must share a parent. + def eye(path): + return SimpleNamespace(cfg=SimpleNamespace(prim_path=path)) + + scene = {"left": eye("{ENV_REGEX_NS}/Head/LeftEye"), "right": eye("{ENV_REGEX_NS}/OtherHead/RightEye")} + env = SimpleNamespace(scene=scene, num_envs=1, device="cpu") + with pytest.raises(ValueError, match="one body"): + BinocularGazeAction(BinocularGazeActionCfg(asset_name="left", right_asset_name="right"), env) + + +def test_binocular_teacher_hands_world_points_to_its_gaze_term(): + points = torch.tensor([[0.1, -0.2, 1.0]]) + received = [] + eyes = SimpleNamespace(teacher_labels=lambda points, labels: received.append(wp.to_torch(points).clone())) + env = SimpleNamespace( + device="cpu", num_envs=1, scene={}, action_manager=SimpleNamespace(get_term=lambda name: eyes), extras={} + ) + teacher = binocular_gaze_teacher_labels(ObservationTermCfg(func=binocular_gaze_teacher_labels), env) + # The offset of a world point runs along the world axes. + teacher(env, target_w=lambda env: points, offset=(0.0, 0.0, 0.5)) + torch.testing.assert_close(received[0], points + torch.tensor([[0.0, 0.0, 0.5]])) + with pytest.raises(ValueError, match="one target"): + teacher(env) + with pytest.raises(ValueError, match=r"shape \(1, 3\)"): + teacher(env, target_w=lambda env: points[0]) + + +def test_binocular_gaze_config_rejects_one_eye_and_a_rigless_rig_mode(): + BinocularGazeActionCfg(asset_name="left", right_asset_name="right").validate_config() + rig = GazeRigCfg(asset_name="rig") + BinocularGazeActionCfg(asset_name="left", right_asset_name="right", mode="hybrid", rig=rig).validate_config() + for changes, message in ( + (dict(right_asset_name="left"), "two different eyes"), + (dict(mode="dual", rig=rig), "mode"), + (dict(mode="physical"), "rig"), + (dict(vergence_limit=0.0), "vergence_limit"), + ): + cfg = BinocularGazeActionCfg(asset_name="left", right_asset_name="right") + for name, value in changes.items(): + setattr(cfg, name, value) + with pytest.raises(ValueError, match=message): + cfg.validate_config() diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index 6eedc522805d..5f3883cdcc44 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -17,6 +17,7 @@ from fovi.sensing.projection import CameraModel, gaze_rotation from fovi.sensing.retina import RetinalTransform from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions +from isaaclab_fovi.sensors.eyeball import gaze_matrix from isaaclab_fovi.sensors.foveated_camera import FoveatedCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera from isaaclab_fovi.sensors.gaze_controls import ViewerGazeControls, add_viewer_gaze_controls @@ -481,6 +482,8 @@ def test_gaze_rotation_follows_fovis_pan_tilt_convention() -> None: direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1) torch.testing.assert_close(stored, angles, atol=0, rtol=0) torch.testing.assert_close(rotation, gaze_rotation(direction, "pan_tilt"), atol=1e-5, rtol=0) + # The viewer's eyeball turns by the same rotation. + torch.testing.assert_close(gaze_matrix(angles), rotation, atol=1e-5, rtol=0) def test_publish_kernel_matches_masking_then_copying_to_the_grid() -> None: @@ -557,6 +560,7 @@ def __init__(self, num_envs: int, switchable: bool = True): self._renders_switchable_rays = switchable self.gaze_angles = SimpleNamespace(torch=torch.tensor([[5.0, -10.0]]).repeat(num_envs, 1)) self.written = [] + self.shows_eyeball = False def set_gaze_angles(self, angles: torch.Tensor) -> None: self.written.append(angles.clone()) @@ -565,15 +569,20 @@ def set_gaze_angles(self, angles: torch.Tensor) -> None: def set_cmf_a(self, cmf_a_deg: float) -> None: self.cfg.cmf_a_deg = cmf_a_deg + def set_debug_vis(self, debug_vis: bool) -> bool: + self.shows_eyeball = debug_vis + return True + class _Imgui: """The ImGui calls the controls make; each float slider returns a scripted (changed, value), and the foveation slider a scripted (changed, index).""" - def __init__(self, sliders=(), button=False, foveation=None): + def __init__(self, sliders=(), button=False, foveation=None, checkbox=None): self.sliders = list(sliders) self.button_pressed = button self.foveation = foveation + self.checked = checkbox self.shown = [] self.ids = [] self.scopes = [] @@ -607,6 +616,10 @@ def is_item_hovered(self): def button(self, label): return self.button_pressed + def checkbox(self, label, value): + self.shown.append((label, value)) + return (True, self.checked) if self.checked is not None else (False, value) + def _visualizer(kind: str) -> SimpleNamespace: """A visualizer of ``kind`` that records its sensor UI callbacks and counts redraws of its camera view.""" @@ -661,6 +674,13 @@ def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows(monkeypat assert newton.current_image_view.invalidated == 1 and second.current_image_view.invalidated == 1 render(_Imgui(button=True)) assert not camera.written[-1].any() + # The checkbox shows and switches the camera's eyeball, its debug visualization. + imgui = _Imgui(checkbox=True) + render(imgui) + assert ("Show eyeball", False) in imgui.shown and camera.shows_eyeball + imgui = _Imgui(checkbox=False) + render(imgui) + assert ("Show eyeball", True) in imgui.shown and not camera.shows_eyeball # The foveation slider steps through ViewerGazeControls.cmf_a_values with the camera's own added, in order. imgui = _Imgui() diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index ed649a08a794..5909775353a8 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -46,6 +46,19 @@ 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.mark.parametrize("backend", ["newton_warp", "isaac_rtx"]) +def test_binocular_gaze_fixates_a_near_point_with_both_eyes(backend): + cases.binocular_gaze_fixates_a_near_point_with_both_eyes(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."""