diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml
index 700903b0fcec..c96f199e2b1d 100644
--- a/.github/workflows/build.yaml
+++ b/.github/workflows/build.yaml
@@ -624,7 +624,7 @@ jobs:
image-tag: ${{ needs.config.outputs.ci_image_tag }}
isaacsim-base-image: ${{ needs.config.outputs.isaacsim_image_name }}
isaacsim-version: ${{ needs.config.outputs.isaacsim_image_tag }}
- filter-pattern: "isaaclab_assets,isaaclab_contrib,isaaclab_teleop,isaaclab_mimic,isaaclab_experimental"
+ filter-pattern: "isaaclab_assets,isaaclab_contrib,isaaclab_teleop,isaaclab_mimic,isaaclab_experimental,isaaclab_fovi"
warp-cache: restore
ovrtx-shader-cache: restore
test-jobs: "4"
diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base
index 8d7b15aaee64..6722e33489a7 100644
--- a/docker/Dockerfile.base
+++ b/docker/Dockerfile.base
@@ -138,7 +138,7 @@ COPY --parents source/*/pyproject.toml ${ISAACLAB_PATH}/
# The image's package set. Kit ships in the base image, so the teleop stack comes without the
# ``isaacsim`` wheel; ``teleop`` itself is left exactly as tuned.
-ARG IMAGE_EXTRAS="--extra sb3 --extra skrl --extra rl-games --extra rsl-rl --extra viser --extra rerun --extra mimic --extra teleop --extra test --extra tetrahedralization --extra ov"
+ARG IMAGE_EXTRAS="--extra sb3 --extra skrl --extra rl-games --extra rsl-rl --extra viser --extra rerun --extra mimic --extra teleop --extra test --extra tetrahedralization --extra ov --extra fovi"
RUN --mount=type=cache,target=/root/.cache/uv \
cd ${ISAACLAB_PATH} && \
diff --git a/docs/conf.py b/docs/conf.py
index 8900d855f2b6..f68ddf96c4b6 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -48,6 +48,8 @@
sys.path.insert(0, os.path.abspath("../source/isaaclab_ov/isaaclab_ov"))
sys.path.insert(0, os.path.abspath("../source/isaaclab_visualizers"))
sys.path.insert(0, os.path.abspath("../source/isaaclab_visualizers/isaaclab_visualizers"))
+# Only the package root: the package's ``rsl_rl`` subpackage would shadow RSL-RL as a top-level module.
+sys.path.insert(0, os.path.abspath("../source/isaaclab_fovi"))
# -- Project information -----------------------------------------------------
@@ -300,6 +302,7 @@ def _read_pinned_versions() -> dict:
"hydra.core.config_store",
"omegaconf",
"newton",
+ "fovi",
]
# List of zero or more Sphinx-specific warning categories to be squelched (i.e.,
@@ -349,11 +352,13 @@ def _read_pinned_versions() -> dict:
"css/environment-browser.css",
"css/demo-browser.css",
"css/guide-browser.css",
+ "css/foveation-viewer.css",
]
html_js_files = [
"css/environment-browser.js",
"css/demo-browser.js",
"css/guide-browser.js",
+ "css/foveation-viewer.js",
]
html_theme_options = {
diff --git a/docs/index.rst b/docs/index.rst
index d63544d085d1..b330248ab682 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -169,6 +169,7 @@ Table of Contents
source/experimental-features/mdp2
source/experimental-features/ray
source/experimental-features/visuo_tactile_sensor
+ source/experimental-features/foveated_camera
source/experimental-features/rlinf_vla_posttraining
source/features/imitation-learning/index
diff --git a/docs/source/_static/css/environment-browser.js b/docs/source/_static/css/environment-browser.js
index 0bf0b9d3afd9..288d28419939 100644
--- a/docs/source/_static/css/environment-browser.js
+++ b/docs/source/_static/css/environment-browser.js
@@ -68,6 +68,7 @@
["IsaacContrib-Assemble-Trocar-G129-Dex3", "rlinf", "isaacsim_physx,newton_mjwarp", "", "", "environments/previews/manipulation/g1_assemble_trocar.jpg", false, {}, {}, "", null, ["||", "isaacsim_physx||", "newton_mjwarp||"]],
["IsaacContrib-AutoMate-Assembly-Direct", "rl_games", "", "", "", "environment-previews/automate_assembly.jpg"],
["IsaacContrib-AutoMate-Disassembly-Direct", "rl_games", "", "", "", "environment-previews/automate_disassembly.jpg"],
+ ["IsaacContrib-Cartpole-Camera-Fovi", "rsl_rl", "isaacsim_physx,newton_kamino,newton_mjwarp,newton_steel,ovphysx", "isaacsim_rtx,newton_optix,newton_warp,ovrtx", "depth,rgb", "", false, {}, {}, "", null, ["||", "||depth", "||rgb", "|isaacsim_rtx|", "|isaacsim_rtx|depth", "|isaacsim_rtx|rgb", "|newton_optix|", "|newton_optix|depth", "|newton_optix|rgb", "|newton_warp|", "|newton_warp|depth", "|newton_warp|rgb", "|ovrtx|", "|ovrtx|depth", "|ovrtx|rgb", "isaacsim_physx||", "isaacsim_physx||depth", "isaacsim_physx||rgb", "isaacsim_physx|isaacsim_rtx|", "isaacsim_physx|isaacsim_rtx|depth", "isaacsim_physx|isaacsim_rtx|rgb", "isaacsim_physx|newton_optix|", "isaacsim_physx|newton_optix|depth", "isaacsim_physx|newton_optix|rgb", "isaacsim_physx|newton_warp|", "isaacsim_physx|newton_warp|depth", "isaacsim_physx|newton_warp|rgb", "newton_kamino||", "newton_kamino||depth", "newton_kamino||rgb", "newton_kamino|isaacsim_rtx|", "newton_kamino|isaacsim_rtx|depth", "newton_kamino|isaacsim_rtx|rgb", "newton_kamino|newton_optix|", "newton_kamino|newton_optix|depth", "newton_kamino|newton_optix|rgb", "newton_kamino|newton_warp|", "newton_kamino|newton_warp|depth", "newton_kamino|newton_warp|rgb", "newton_kamino|ovrtx|", "newton_kamino|ovrtx|depth", "newton_kamino|ovrtx|rgb", "newton_mjwarp||", "newton_mjwarp||depth", "newton_mjwarp||rgb", "newton_mjwarp|isaacsim_rtx|", "newton_mjwarp|isaacsim_rtx|depth", "newton_mjwarp|isaacsim_rtx|rgb", "newton_mjwarp|newton_optix|", "newton_mjwarp|newton_optix|depth", "newton_mjwarp|newton_optix|rgb", "newton_mjwarp|newton_warp|", "newton_mjwarp|newton_warp|depth", "newton_mjwarp|newton_warp|rgb", "newton_mjwarp|ovrtx|", "newton_mjwarp|ovrtx|depth", "newton_mjwarp|ovrtx|rgb", "newton_steel||", "newton_steel||depth", "newton_steel||rgb", "newton_steel|isaacsim_rtx|", "newton_steel|isaacsim_rtx|depth", "newton_steel|isaacsim_rtx|rgb", "newton_steel|newton_optix|", "newton_steel|newton_optix|depth", "newton_steel|newton_optix|rgb", "newton_steel|newton_warp|", "newton_steel|newton_warp|depth", "newton_steel|newton_warp|rgb", "newton_steel|ovrtx|", "newton_steel|ovrtx|depth", "newton_steel|ovrtx|rgb", "ovphysx||", "ovphysx||depth", "ovphysx||rgb", "ovphysx|newton_optix|", "ovphysx|newton_optix|depth", "ovphysx|newton_optix|rgb", "ovphysx|newton_warp|", "ovphysx|newton_warp|depth", "ovphysx|newton_warp|rgb", "ovphysx|ovrtx|", "ovphysx|ovrtx|depth", "ovphysx|ovrtx|rgb"]],
["IsaacContrib-Cartpole-Camera-Showcase-Direct", "skrl", "", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete"]],
["IsaacContrib-Cartpole-Showcase-Direct", "skrl", "isaacsim_physx,newton_kamino,newton_mjwarp,newton_steel,ovphysx", "", "box_box,box_discrete,box_multidiscrete,dict_box,dict_discrete,dict_multidiscrete,discrete_box,discrete_discrete,discrete_multidiscrete,multidiscrete_box,multidiscrete_discrete,multidiscrete_multidiscrete,tuple_box,tuple_discrete,tuple_multidiscrete", "environment-previews/cartpole.jpg", false, {}, {}, "", null, ["||", "||box_box", "||box_discrete", "||box_multidiscrete", "||dict_box", "||dict_discrete", "||dict_multidiscrete", "||discrete_box", "||discrete_discrete", "||discrete_multidiscrete", "||multidiscrete_box", "||multidiscrete_discrete", "||multidiscrete_multidiscrete", "||tuple_box", "||tuple_discrete", "||tuple_multidiscrete", "isaacsim_physx||", "isaacsim_physx||box_box", "isaacsim_physx||box_discrete", "isaacsim_physx||box_multidiscrete", "isaacsim_physx||dict_box", "isaacsim_physx||dict_discrete", "isaacsim_physx||dict_multidiscrete", "isaacsim_physx||discrete_box", "isaacsim_physx||discrete_discrete", "isaacsim_physx||discrete_multidiscrete", "isaacsim_physx||multidiscrete_box", "isaacsim_physx||multidiscrete_discrete", "isaacsim_physx||multidiscrete_multidiscrete", "isaacsim_physx||tuple_box", "isaacsim_physx||tuple_discrete", "isaacsim_physx||tuple_multidiscrete", "newton_kamino||", "newton_kamino||box_box", "newton_kamino||box_discrete", "newton_kamino||box_multidiscrete", "newton_kamino||dict_box", "newton_kamino||dict_discrete", "newton_kamino||dict_multidiscrete", "newton_kamino||discrete_box", "newton_kamino||discrete_discrete", "newton_kamino||discrete_multidiscrete", "newton_kamino||multidiscrete_box", "newton_kamino||multidiscrete_discrete", "newton_kamino||multidiscrete_multidiscrete", "newton_kamino||tuple_box", "newton_kamino||tuple_discrete", "newton_kamino||tuple_multidiscrete", "newton_mjwarp||", "newton_mjwarp||box_box", "newton_mjwarp||box_discrete", "newton_mjwarp||box_multidiscrete", "newton_mjwarp||dict_box", "newton_mjwarp||dict_discrete", "newton_mjwarp||dict_multidiscrete", "newton_mjwarp||discrete_box", "newton_mjwarp||discrete_discrete", "newton_mjwarp||discrete_multidiscrete", "newton_mjwarp||multidiscrete_box", "newton_mjwarp||multidiscrete_discrete", "newton_mjwarp||multidiscrete_multidiscrete", "newton_mjwarp||tuple_box", "newton_mjwarp||tuple_discrete", "newton_mjwarp||tuple_multidiscrete", "newton_steel||", "newton_steel||box_box", "newton_steel||box_discrete", "newton_steel||box_multidiscrete", "newton_steel||dict_box", "newton_steel||dict_discrete", "newton_steel||dict_multidiscrete", "newton_steel||discrete_box", "newton_steel||discrete_discrete", "newton_steel||discrete_multidiscrete", "newton_steel||multidiscrete_box", "newton_steel||multidiscrete_discrete", "newton_steel||multidiscrete_multidiscrete", "newton_steel||tuple_box", "newton_steel||tuple_discrete", "newton_steel||tuple_multidiscrete", "ovphysx||", "ovphysx||box_box", "ovphysx||box_discrete", "ovphysx||box_multidiscrete", "ovphysx||dict_box", "ovphysx||dict_discrete", "ovphysx||dict_multidiscrete", "ovphysx||discrete_box", "ovphysx||discrete_discrete", "ovphysx||discrete_multidiscrete", "ovphysx||multidiscrete_box", "ovphysx||multidiscrete_discrete", "ovphysx||multidiscrete_multidiscrete", "ovphysx||tuple_box", "ovphysx||tuple_discrete", "ovphysx||tuple_multidiscrete"]],
["IsaacContrib-Deploy-GearAssembly-Rizon4s-Grav", "rsl_rl", "", "", "", "environment-previews/rizon4s_gear_assembly.jpg"],
diff --git a/docs/source/_static/css/foveation-pooling-isotropic.json b/docs/source/_static/css/foveation-pooling-isotropic.json
new file mode 100644
index 000000000000..90d14b291e94
--- /dev/null
+++ b/docs/source/_static/css/foveation-pooling-isotropic.json
@@ -0,0 +1 @@
+{"fov":90,"cmfA":2.0,"res":16,"rings":14,"count":243,"mult":{"2":{"rings":28,"count":1026,"defaultK":4,"kMax":8,"geodesic":[0,1,4,2,3,5,6,8,7,18,8,1,19,34,20,2,9,10,8,2,22,21,23,3,11,12,10,3,24,25,23,2,13,14,12,4,27,28,26,5,15,14,16,5,30,29,31,4,17,16,18,6,32,33,31,5,35,55,36,19,56,79,57,34,37,38,36,58,21,20,59,57,39,38,40,22,61,60,23,21,41,40,42,63,24,23,62,64,43,42,44,25,65,66,26,64,46,47,45,69,27,68,28,70,48,49,47,29,71,70,28,72,50,51,49,73,30,31,74,72,52,51,53,32,75,76,31,33,54,53,55,78,33,34,77,79,80,107,81,56,108,109,137,79,82,81,83,110,58,57,111,109,84,83,85,112,59,60,113,111,86,87,85,61,114,115,62,60,88,87,89,63,117,116,62,64,90,89,91,119,65,64,118,120,92,93,91,121,66,67,120,122,94,95,93,68,123,124,122,67,96,95,97,125,70,69,126,124,98,99,97,127,71,72,128,126,100,101,99,73,129,130,74,72,102,101,103,75,132,131,74,76,104,105,103,134,77,76,133,135,106,105,107,136,78,79,135,137,138,170,139,108,171,172,205,109,140,141,139,173,110,174,109,172,142,141,143,175,112,111,176,174,144,145,143,177,113,114,178,176,146,147,145,115,179,180,116,114,148,147,149,117,182,181,118,116,150,151,149,119,184,183,118,120,152,153,151,186,121,120,185,187,154,153,155,188,123,122,187,189,157,158,156,191,125,126,192,190,159,158,160,127,193,194,128,126,161,160,162,129,195,196,128,130,163,162,164,131,198,197,130,132,165,164,166,200,133,132,199,201,167,168,166,202,134,135,201,203,169,168,170,204,136,203,137,205,206,207,242,171,243,244,281,205,208,209,207,245,173,246,172,244,210,209,211,247,175,248,174,246,212,211,213,249,177,250,176,248,214,215,213,251,179,252,178,250,216,217,215,254,180,253,181,255,218,217,219,256,182,255,183,257,220,221,219,258,184,257,185,259,222,223,221,260,186,259,187,261,225,226,224,263,189,264,262,188,227,228,226,265,191,266,190,264,229,230,228,267,193,268,192,266,231,232,230,269,195,270,194,268,233,234,232,271,197,272,196,270,235,234,236,274,198,273,199,275,237,236,238,276,200,275,201,277,239,240,238,278,202,277,203,279,241,242,240,280,204,279,205,281,282,322,283,243,323,364,324,244,284,285,283,325,245,244,326,324,286,287,285,327,247,246,328,326,288,289,287,329,249,248,330,328,290,289,291,331,251,250,332,330,292,293,291,333,253,252,334,332,294,295,293,335,254,255,336,334,296,295,297,256,337,338,257,336,340,339,341,383,299,298,382,384,342,341,343,385,301,300,384,386,344,343,345,387,303,302,388,386,346,347,345,389,304,305,390,388,348,349,347,391,306,307,392,390,309,308,310,269,351,350,268,352,311,310,312,353,271,270,352,354,313,312,314,355,272,273,354,356,315,316,314,357,274,275,356,358,317,318,316,359,276,277,358,360,319,318,320,361,278,279,360,362,321,322,320,363,280,281,362,364,409,410,453,365,454,499,455,366,411,410,412,456,367,457,366,455,413,414,412,458,369,459,368,457,371,370,372,415,329,328,416,414,418,419,417,463,374,464,373,462,420,421,419,465,376,466,375,464,422,421,423,467,378,468,377,466,424,425,423,469,380,470,379,468,426,425,427,471,382,472,381,470,428,429,427,473,384,474,383,472,386,385,387,343,430,431,344,342,388,389,387,345,433,432,344,346,435,434,436,481,390,480,391,482,437,438,436,483,392,482,393,484,439,440,438,485,394,484,395,486,441,440,442,487,396,486,397,488,443,442,444,489,398,488,399,490,445,446,444,491,400,490,401,492,403,404,402,448,359,360,447,449,450,449,451,496,405,495,406,497,452,451,453,498,407,497,408,499,500,545,501,454,546,592,547,499,502,501,503,456,548,549,455,457,504,503,505,458,550,551,457,459,506,507,505,460,552,553,461,459,508,507,509,462,554,555,461,463,510,509,511,464,556,557,463,465,513,514,512,467,559,560,468,466,515,516,514,469,561,562,470,468,517,518,516,471,563,564,470,472,519,518,520,473,565,566,474,472,521,522,520,475,567,568,476,474,523,524,522,477,570,569,478,476,525,524,526,479,572,571,478,480,527,528,526,481,574,573,482,480,529,528,530,483,576,575,484,482,531,532,530,485,578,577,486,484,533,534,532,487,580,579,486,488,536,535,537,490,583,582,489,491,538,539,537,492,585,584,493,491,540,539,541,494,587,586,493,495,542,543,541,496,589,588,495,497,544,543,545,498,591,590,499,497,593,594,640,641,546,642,688,592,595,594,596,643,548,547,642,644,597,596,598,645,550,549,644,646,599,598,600,647,552,551,646,648,601,602,600,649,554,553,650,648,603,602,604,651,556,555,650,652,606,605,607,654,559,558,653,655,608,607,609,656,561,560,657,655,610,611,609,658,563,562,657,659,612,611,613,660,565,564,661,659,614,615,613,662,567,566,663,661,616,615,617,664,569,568,663,665,618,617,619,666,570,571,667,665,620,619,621,668,572,573,669,667,622,623,621,670,574,575,671,669,624,623,625,672,576,577,671,673,626,627,625,674,578,579,675,673,628,629,627,676,580,581,677,675,631,630,632,679,583,584,678,680,633,632,634,681,585,586,680,682,635,636,634,683,587,588,684,682,637,638,636,685,589,590,686,684,639,640,638,687,591,592,688,686,689,690,736,737,641,785,738,642,691,690,692,643,739,740,642,644,693,694,692,645,741,742,644,646,695,694,696,647,743,744,646,648,697,698,696,649,745,746,650,648,699,698,700,651,747,748,650,652,702,701,703,654,750,751,653,655,704,703,705,656,752,753,655,657,706,707,705,658,754,755,659,657,708,707,709,660,756,757,659,661,710,711,709,662,758,759,663,661,712,711,713,664,760,761,663,665,714,715,713,666,763,762,667,665,716,715,717,668,765,764,669,667,718,719,717,670,767,766,671,669,720,719,721,672,769,768,671,673,722,723,721,674,771,770,675,673,724,725,723,676,773,772,677,675,727,726,728,679,776,775,678,680,729,728,730,681,778,777,680,682,731,732,730,683,780,779,684,682,733,734,732,685,782,781,686,684,735,736,734,687,784,783,688,686,786,834,787,835,737,785,738,836,788,789,787,739,837,836,740,738,790,791,789,741,839,838,740,742,792,793,791,743,841,840,744,742,795,796,794,746,844,843,745,747,797,796,798,748,846,845,749,747,799,800,798,750,848,847,749,751,801,802,800,752,850,849,753,751,803,802,804,754,852,851,753,755,805,804,806,756,854,853,755,757,807,806,808,758,856,855,757,759,809,810,808,760,858,857,761,759,812,813,811,763,860,861,764,762,814,813,815,765,862,863,764,766,816,817,815,767,864,865,766,768,818,819,817,769,866,867,770,768,820,819,821,771,868,869,770,772,822,823,821,773,870,871,774,772,824,823,825,775,872,873,774,776,826,827,825,777,874,875,778,776,829,830,828,780,877,878,781,779,831,830,832,782,879,880,781,783,833,834,832,784,881,882,785,783,883,884,930,931,835,932,978,836,885,884,886,933,837,932,934,836,887,886,888,935,839,934,936,838,889,888,890,937,841,936,938,840,891,890,892,939,843,940,938,844,893,892,894,941,845,940,942,844,896,895,897,944,848,943,945,847,898,897,899,946,850,945,947,849,900,901,899,948,852,949,947,853,902,901,903,950,854,949,951,853,904,905,903,952,856,953,951,857,906,905,907,954,858,953,955,857,908,909,907,956,860,957,955,861,910,909,911,958,862,957,959,861,912,913,911,960,864,961,959,865,914,913,915,962,866,963,961,865,916,917,915,964,868,965,963,869,918,919,917,966,870,967,965,871,921,920,922,969,873,968,970,872,923,922,924,971,875,970,972,874,925,926,924,973,877,974,972,878,927,928,926,975,879,976,974,880,929,930,928,977,881,978,976,882,979,-1,1025,980,-1,931,-1,932,981,-1,980,982,933,-1,934,932,983,-1,984,982,935,-1,936,-1,985,-1,984,986,937,-1,-1,938,987,-1,988,986,939,-1,940,-1,989,-1,990,988,941,-1,942,-1,991,-1,990,992,943,-1,944,-1,993,-1,992,994,945,-1,946,-1,995,-1,994,996,-1,947,948,-1,997,-1,996,998,949,-1,950,-1,999,-1,1000,998,951,-1,952,-1,1001,-1,1000,1002,-1,953,954,-1,1004,-1,1005,1003,957,956,-1,-1,1006,-1,1007,1005,-1,959,958,-1,1008,-1,1009,1007,-1,961,960,-1,1010,-1,1011,1009,963,962,-1,-1,1012,-1,1011,1013,965,-1,964,-1,1014,-1,1015,1013,-1,967,966,-1,1016,-1,1017,1015,969,-1,968,-1,1018,-1,1017,1019,971,-1,970,-1,1020,-1,1021,1019,973,-1,972,974,1022,-1,1023,1021,975,-1,-1,974,1024,-1,1023,1025,977,-1,-1,976],"visual":[0,3,4,1,5,2,6,8,7,18,8,19,1,20,34,2,9,8,10,2,22,21,23,3,11,12,10,3,24,25,23,4,13,12,14,27,4,28,26,3,15,14,16,5,30,29,31,6,17,16,18,6,32,33,31,5,35,56,55,36,19,79,57,34,37,38,58,59,36,21,20,57,39,40,61,22,38,60,23,62,41,42,63,24,64,40,23,62,43,44,66,65,25,26,42,45,45,46,68,27,67,69,44,47,48,47,70,71,29,28,49,46,50,49,73,30,72,51,31,74,52,51,75,32,53,76,31,74,54,53,78,77,55,33,34,79,80,108,107,81,56,137,109,79,82,110,81,83,111,58,57,109,84,112,83,85,113,59,60,111,86,114,115,87,85,61,62,60,88,117,116,87,89,63,62,64,90,119,91,89,118,65,64,120,92,121,93,91,120,66,67,122,94,123,95,93,68,122,124,67,96,125,97,95,126,70,69,124,98,127,99,97,128,71,72,126,100,129,130,99,101,73,74,72,102,132,131,101,103,75,74,76,104,134,105,103,133,77,76,135,106,136,107,105,135,78,79,137,138,171,170,139,108,205,172,137,140,173,141,139,174,110,172,109,142,175,143,176,141,112,111,174,144,178,145,177,143,114,113,179,146,180,147,179,145,115,116,181,148,182,149,181,117,183,147,118,150,151,184,185,119,183,149,120,152,153,186,187,121,151,122,185,154,155,188,189,123,153,156,124,157,156,191,190,125,158,124,192,159,158,193,192,127,194,160,126,161,195,160,196,129,194,162,128,163,197,162,198,164,130,131,196,165,199,164,200,166,132,133,198,167,202,166,201,168,134,135,203,169,204,168,170,203,136,205,137,206,243,242,207,244,281,171,205,208,245,209,246,207,173,244,172,210,247,248,211,209,175,246,174,212,249,250,213,211,177,176,251,214,252,215,251,213,179,178,253,216,254,217,253,181,215,255,180,218,256,219,257,255,183,217,182,220,258,221,259,185,257,184,219,222,223,260,261,187,186,221,259,224,225,262,263,188,189,226,223,227,226,265,264,190,191,228,266,229,267,228,266,192,268,193,230,231,269,230,270,268,194,232,195,233,271,232,272,196,234,270,197,235,273,234,274,236,198,199,272,237,275,276,236,238,200,201,274,239,278,277,238,240,202,279,203,241,280,240,279,242,204,281,205,282,323,322,283,364,324,243,244,284,325,285,326,283,324,245,244,286,327,287,328,285,326,247,246,288,329,330,289,287,249,328,248,290,331,332,291,289,251,330,250,292,333,334,293,291,253,252,332,294,336,295,335,293,255,254,337,296,338,297,337,295,257,339,256,340,298,299,339,341,259,297,258,342,300,301,341,343,261,260,299,344,303,302,343,345,263,262,301,346,305,304,347,345,264,265,306,348,307,306,349,347,266,308,267,309,350,308,351,310,268,349,269,311,352,310,353,312,270,271,351,313,354,355,312,314,272,273,353,315,357,356,314,316,274,358,275,317,359,358,316,318,276,360,277,319,361,318,360,320,362,278,279,321,363,320,362,322,364,280,281,409,365,366,408,410,453,323,454,411,367,412,368,366,410,325,456,369,413,414,370,368,412,327,458,371,415,416,372,370,329,414,417,373,418,417,374,331,372,419,463,420,375,376,419,421,333,374,377,422,378,377,421,423,335,379,376,424,380,379,425,423,381,337,469,426,382,381,427,425,383,339,472,384,428,429,383,385,427,341,474,386,430,431,385,387,343,429,476,388,433,432,389,387,345,434,478,390,435,434,391,389,436,347,480,437,392,393,436,438,391,349,482,439,394,395,440,438,393,351,485,441,396,397,442,440,353,395,398,443,399,398,444,442,355,400,397,401,445,446,400,357,402,444,491,403,448,447,402,404,359,449,446,405,450,449,404,406,451,361,496,452,407,451,406,408,453,363,498,500,454,545,501,455,499,409,546,502,456,503,457,501,455,411,548,504,458,505,459,503,457,413,550,506,460,507,461,459,505,415,552,508,462,509,463,461,507,417,555,510,511,464,465,419,463,557,509,513,512,467,466,421,468,559,514,515,469,514,468,470,516,423,561,517,471,516,470,472,518,563,425,519,473,518,472,520,474,427,565,521,475,520,474,522,476,429,567,523,477,522,524,476,478,432,431,525,479,526,480,524,478,434,572,527,481,528,482,526,480,436,574,529,483,530,484,482,528,576,438,531,485,532,486,484,530,440,578,533,534,487,488,442,486,580,532,536,535,490,489,444,491,582,537,538,492,537,491,493,539,446,584,540,494,539,493,495,541,448,587,542,496,541,495,543,497,450,589,544,498,543,497,545,499,452,591,593,546,640,594,592,547,641,500,595,548,596,549,594,547,643,502,597,550,598,551,596,549,645,504,599,552,600,553,551,598,647,506,601,554,602,555,553,600,649,508,603,604,556,557,555,602,651,510,606,605,558,559,557,654,653,607,608,607,560,561,559,609,656,514,610,562,609,563,611,658,561,516,612,564,611,565,613,660,563,518,614,566,567,613,615,662,520,565,616,568,569,615,617,664,522,567,618,571,570,619,617,666,524,572,620,573,572,621,619,668,526,574,622,575,623,574,621,670,576,528,624,577,625,576,623,672,578,530,626,627,579,578,580,625,674,532,628,629,581,580,582,676,677,627,631,630,583,582,584,632,679,536,633,585,632,584,586,634,681,538,635,587,634,586,588,636,683,540,637,589,636,588,638,590,685,542,639,591,638,590,640,592,687,544,689,641,690,736,688,642,737,593,691,643,692,690,644,642,739,595,693,645,694,646,692,741,644,742,695,647,696,648,694,743,646,744,697,698,649,650,696,746,745,648,699,700,651,652,748,747,698,650,702,701,654,653,750,703,749,700,704,703,656,655,752,705,657,608,706,705,658,657,754,707,659,610,708,660,707,659,709,756,661,757,710,662,709,661,711,663,758,759,712,664,711,713,663,665,760,761,714,666,715,713,667,665,763,762,716,668,717,669,715,667,765,764,718,670,719,671,717,767,669,766,720,721,672,673,769,719,671,624,722,723,674,675,771,721,673,626,724,725,676,677,773,723,774,726,727,726,679,678,775,776,728,680,729,728,681,680,730,777,778,682,731,683,730,682,732,780,684,779,733,685,732,684,734,782,686,781,735,687,734,736,686,688,784,639,786,737,834,787,835,785,738,689,788,739,789,740,787,837,738,838,790,791,741,742,839,789,740,840,792,793,743,744,841,791,842,742,795,794,746,745,843,844,796,793,797,796,748,747,845,846,798,749,799,798,750,749,800,848,847,751,801,752,800,802,751,850,753,849,803,754,804,802,755,852,753,851,805,756,806,757,804,854,755,853,807,808,758,759,856,806,757,855,809,810,760,761,858,808,759,811,812,811,763,762,860,813,764,810,814,813,765,764,862,815,766,863,816,767,815,766,817,864,768,865,818,769,817,819,768,866,770,867,820,771,821,819,772,868,770,869,822,823,773,774,821,870,871,772,824,825,775,776,873,872,823,774,826,827,777,778,875,874,825,828,829,828,780,779,877,830,876,781,831,830,782,781,879,832,783,878,833,784,832,783,834,881,785,880,883,835,930,884,931,882,836,932,885,837,886,933,884,838,836,934,887,888,839,935,840,886,838,936,889,890,841,842,937,888,938,840,891,892,843,844,939,940,890,842,893,894,845,846,941,942,892,895,896,895,848,847,944,943,897,894,898,897,850,849,946,945,899,851,900,899,852,851,948,901,947,853,902,901,854,853,950,903,949,855,904,856,903,952,905,855,857,951,906,858,905,907,954,857,859,953,908,860,909,907,956,861,859,957,910,862,911,958,909,863,861,959,912,913,864,865,960,911,961,863,914,915,866,867,962,913,963,865,916,917,868,869,964,965,915,867,918,919,870,871,966,967,917,920,921,920,873,872,969,968,922,919,923,922,875,874,971,970,924,876,925,924,877,876,973,926,972,878,927,926,879,975,878,928,880,974,929,881,928,977,930,880,882,976,979,931,-1,-1,1025,980,-1,978,981,933,-1,982,-1,980,934,932,983,935,-1,984,982,-1,936,934,985,-1,986,937,938,984,-1,-1,987,988,939,-1,-1,940,986,938,989,990,-1,941,942,-1,988,-1,991,992,-1,944,943,-1,990,-1,993,994,946,-1,-1,945,992,947,995,996,-1,948,947,-1,-1,994,997,998,950,-1,-1,949,996,951,999,1000,952,-1,-1,951,953,998,1001,1002,954,-1,-1,953,955,-1,1004,1003,956,-1,-1,957,955,1005,1006,1005,958,-1,-1,959,957,-1,1008,1007,-1,960,961,-1,-1,1009,1010,1009,962,-1,-1,963,1011,961,1012,1011,-1,964,965,-1,1013,-1,1014,1013,-1,966,967,-1,1015,-1,1016,1015,-1,969,968,-1,1017,-1,1018,1017,-1,971,970,1019,-1,-1,1020,1019,973,-1,-1,972,1021,974,1022,975,-1,1021,1023,-1,974,976,1024,977,-1,1023,1025,-1,976,978]},"3":{"rings":42,"count":2340,"defaultK":10,"kMax":18,"geodesic":[0,6,3,4,2,7,1,5,14,9,19,12,16,17,11,10,18,15,20,21,36,8,37,38,58,19,9,22,35,39,57,1,59,60,85,7,23,24,22,41,10,40,42,11,9,39,21,25,64,2,43,63,65,3,26,27,25,45,12,44,13,46,11,43,24,28,69,68,3,4,47,14,28,27,29,47,14,48,13,46,49,15,30,26,72,4,71,12,73,5,31,30,32,51,16,52,15,50,17,53,33,29,76,77,6,5,49,14,34,35,33,55,18,56,54,17,19,57,36,32,81,7,53,82,80,6,86,116,87,59,117,150,118,60,85,115,88,37,151,119,149,188,152,84,89,90,88,120,62,61,121,119,63,122,91,87,60,39,155,154,40,156,92,93,91,64,124,123,65,63,125,122,90,94,41,158,159,66,42,157,95,96,94,127,67,126,66,128,68,97,93,162,125,43,44,65,163,161,98,97,99,130,69,70,131,129,68,71,96,100,132,166,46,45,165,128,102,103,101,73,135,134,72,74,136,133,104,100,171,48,170,49,71,172,105,104,106,138,76,75,137,139,77,74,103,107,136,174,50,51,175,140,108,109,107,141,78,142,79,140,77,106,110,178,143,53,52,80,177,179,111,112,110,81,144,145,80,82,143,146,113,109,55,182,181,79,54,183,114,115,113,148,83,84,147,149,82,146,112,116,85,57,185,186,56,184,189,229,190,151,230,231,273,188,152,228,191,117,274,232,272,320,275,150,192,191,193,233,154,234,153,232,155,235,194,190,277,278,119,120,152,231,195,194,196,236,157,237,156,235,158,238,155,197,193,122,281,280,282,121,198,197,199,240,159,239,160,241,158,238,161,196,200,284,124,125,285,283,201,200,202,243,162,242,163,244,161,199,203,127,288,241,287,164,126,245,204,205,203,246,165,247,164,245,166,206,202,291,129,248,130,292,163,244,249,250,248,294,207,295,206,293,208,296,251,247,205,343,167,342,168,344,252,251,253,297,298,209,210,296,299,208,211,250,254,170,346,345,347,169,255,256,254,301,212,300,213,302,211,299,257,253,214,349,173,350,172,348,215,214,216,258,175,257,176,259,174,213,217,304,139,256,138,303,177,260,218,217,219,261,178,262,177,260,179,220,216,141,307,263,308,176,142,259,221,222,220,264,181,265,180,263,182,266,179,223,219,311,144,143,310,312,224,225,223,268,183,267,184,269,182,266,185,226,222,146,314,315,313,147,227,228,226,271,186,270,187,272,185,269,229,225,318,317,149,148,188,273,371,372,422,321,423,476,424,370,322,421,373,274,477,425,475,478,532,369,374,375,373,426,324,427,323,425,325,376,372,480,277,428,481,276,322,424,377,378,376,429,327,430,326,428,328,379,375,431,325,279,483,484,280,427,381,382,380,433,331,434,330,432,332,435,329,379,383,283,488,487,284,282,384,383,385,436,437,333,334,435,438,332,335,382,386,491,286,285,490,492,387,388,386,440,336,439,337,441,335,438,338,385,389,494,288,289,495,493,391,392,390,444,340,443,341,445,339,393,389,442,292,342,499,498,293,291,394,395,393,447,343,446,344,448,342,396,392,295,502,445,501,345,294,449,397,396,398,346,450,449,451,345,347,395,399,505,297,298,448,452,504,506,400,401,399,453,349,454,348,452,350,402,398,300,508,455,509,347,301,451,404,405,403,457,353,458,352,456,354,459,406,402,304,351,513,512,303,305,407,408,406,460,356,461,355,459,357,462,354,409,405,516,307,306,515,517,410,409,411,463,464,358,359,462,465,357,360,408,412,519,309,310,518,520,413,412,414,467,361,466,362,468,360,465,363,411,415,312,522,523,311,313,417,416,418,471,365,470,366,472,364,415,419,469,367,316,527,526,315,473,420,419,421,474,368,473,369,475,367,422,418,530,318,472,529,319,370,476,533,534,590,477,591,650,592,532,478,535,589,423,651,593,649,652,712,476,536,535,537,594,480,595,479,593,481,538,534,654,426,596,655,425,478,592,539,538,540,597,483,598,482,596,484,537,541,599,657,429,481,658,428,595,543,542,544,601,487,602,486,600,488,603,485,541,545,662,432,661,433,663,546,547,545,604,490,605,489,603,491,606,488,544,548,665,435,664,436,666,549,550,548,608,492,607,493,609,491,606,494,551,547,668,438,669,437,667,552,551,553,611,495,610,496,612,494,609,497,550,554,671,441,672,440,670,556,555,557,615,499,614,500,616,498,554,558,613,676,444,501,675,445,617,559,560,558,618,502,617,503,619,501,561,557,679,447,616,678,448,504,620,562,561,563,505,621,620,622,504,506,560,564,450,682,619,623,681,683,449,565,564,566,624,508,625,507,623,509,563,567,685,453,626,686,452,506,622,568,569,567,627,511,628,510,626,512,570,566,629,688,456,509,689,455,625,572,573,571,631,515,632,514,630,516,633,513,574,570,693,459,692,460,694,575,576,574,634,518,635,517,633,519,636,516,577,573,696,462,695,463,697,578,579,577,638,520,637,521,639,519,636,522,580,576,699,465,700,464,698,581,582,580,641,523,640,524,642,522,639,525,583,579,702,468,703,467,701,585,584,586,645,527,644,528,646,526,587,583,643,707,471,529,706,472,647,588,587,589,648,530,647,531,649,529,586,590,710,474,646,709,475,532,650,713,714,775,651,776,839,777,712,652,774,715,591,840,838,778,841,905,711,716,715,717,779,654,780,653,778,655,718,714,843,594,844,781,593,652,777,719,718,720,782,657,783,656,781,658,717,721,846,597,847,596,784,655,780,722,721,723,785,660,786,659,784,661,724,720,849,600,850,599,787,658,783,726,727,725,789,664,790,663,788,665,724,728,854,791,603,662,853,604,787,729,728,730,792,667,793,666,791,668,731,727,794,665,857,606,856,607,858,732,731,733,795,670,796,669,794,671,797,668,730,734,860,609,859,610,861,735,736,734,798,673,799,672,797,674,800,671,737,733,863,612,864,611,862,738,739,737,801,676,802,675,800,677,803,674,736,740,866,615,867,614,865,741,740,742,804,679,805,678,803,680,806,677,743,739,869,618,870,617,868,744,743,745,807,682,808,681,806,683,809,680,742,746,872,621,873,620,871,748,749,747,812,685,811,686,813,684,810,687,746,750,877,624,876,625,878,751,750,752,815,688,814,689,816,687,813,690,753,749,880,627,879,628,881,754,753,755,818,691,817,692,819,690,816,693,752,756,883,630,882,631,884,757,758,756,821,694,820,695,822,693,819,696,759,755,886,633,887,632,885,760,761,759,824,697,823,698,825,696,758,762,822,699,889,636,890,635,888,763,762,764,827,700,826,701,828,699,765,761,892,825,639,702,893,638,829,767,766,768,831,704,830,705,832,703,765,769,897,642,896,643,829,706,833,770,771,769,834,707,833,708,835,706,772,768,900,645,899,646,832,709,836,773,772,774,837,710,836,711,838,709,775,771,903,648,902,835,649,712,839,906,907,972,840,973,974,1040,841,905,971,908,776,1041,1039,975,1042,1109,904,909,910,908,976,843,977,842,975,844,911,907,1044,779,978,778,1045,841,974,912,911,913,979,846,980,845,978,847,910,914,1047,782,981,781,844,1048,977,916,917,915,983,850,984,849,982,851,914,918,1051,786,985,785,848,1052,981,919,920,918,986,853,987,852,985,854,921,917,1054,988,788,851,789,1055,984,922,923,921,989,856,990,855,988,857,924,920,991,854,791,1057,1058,792,790,925,924,926,992,859,993,858,991,860,994,927,923,857,794,1061,1060,795,793,928,927,929,995,862,996,861,994,863,997,860,926,930,797,1064,1063,798,796,932,931,933,999,866,1000,865,998,867,1001,864,930,934,801,1068,1067,800,802,935,936,934,1002,869,1003,868,1001,870,1004,867,937,933,1071,804,803,1070,1072,938,937,939,1005,872,1006,871,1004,873,1007,870,936,940,1074,807,806,1073,1075,941,940,942,1009,874,1008,875,1010,873,1007,876,939,943,1077,809,810,1078,1076,944,943,945,1012,877,1011,878,1013,876,1010,879,942,946,1080,812,813,1081,1079,947,946,948,1015,880,1014,881,1016,879,1013,882,945,949,815,1083,1084,816,814,951,952,950,1019,884,1018,885,1020,883,1017,886,953,949,819,1087,1088,818,820,954,955,953,1022,887,1021,888,1023,886,1020,952,956,889,822,1090,1091,821,823,957,956,958,1025,890,1024,891,1026,889,955,959,1023,892,825,1094,1093,824,826,960,959,961,1028,893,1027,894,1029,892,958,962,1097,1026,828,895,827,1096,1030,963,962,964,1031,896,1030,897,1032,895,961,965,1100,830,1029,831,898,1099,1033,967,966,968,1035,900,1034,901,1036,899,969,965,1104,834,1033,835,902,1103,1037,970,969,971,1038,903,1037,904,1039,902,968,972,1107,837,1036,838,1106,905,1040,1110,1179,1111,1180,1041,1249,1181,1042,1109,1178,1112,973,1250,1248,1182,1251,1320,1043,1113,1112,1114,1183,1044,1043,1182,1184,1045,1111,1115,1253,976,1042,975,1254,1181,1185,1116,1115,1117,1186,1047,1046,1185,1187,1048,1114,1118,1256,979,1045,978,1257,1184,1188,1120,1121,1119,1190,1051,1050,1191,1189,1052,1122,1118,1260,983,1049,982,1261,1192,1188,1123,1122,1124,1193,1054,1053,1192,1194,1055,1125,1121,1263,986,1052,985,1264,1195,1191,1126,1125,1127,1196,1057,1056,1195,1197,1058,1128,1124,1266,1055,989,988,1267,1194,1198,1129,1130,1128,1199,1060,1059,1200,1198,1061,1131,1127,1058,1269,991,992,1270,1201,1197,1132,1133,1131,1202,1063,1062,1203,1201,1064,1061,1130,1134,1272,994,995,1273,1204,1200,1135,1134,1136,1205,1066,1065,1206,1204,1067,1064,1137,1133,997,1275,1276,998,1207,1203,1139,1138,1140,1209,1070,1069,1208,1210,1071,1068,1137,1141,1001,1279,1280,1002,1207,1211,1142,1143,1141,1212,1073,1072,1213,1211,1074,1071,1144,1140,1004,1282,1283,1005,1214,1210,1145,1146,1144,1215,1076,1075,1216,1214,1077,1074,1147,1143,1007,1286,1285,1217,1213,1008,1148,1147,1149,1218,1078,1079,1217,1219,1077,1080,1150,1146,1010,1289,1288,1009,1216,1220,1151,1152,1150,1221,1081,1082,1222,1220,1080,1083,1153,1149,1013,1292,1291,1012,1223,1219,1155,1154,1156,1225,1085,1086,1224,1226,1084,1087,1153,1157,1017,1296,1295,1016,1223,1227,1158,1159,1157,1228,1088,1089,1227,1229,1087,1090,1160,1156,1299,1020,1019,1298,1230,1226,1161,1160,1162,1231,1091,1092,1230,1232,1090,1159,1163,1093,1302,1023,1022,1301,1229,1233,1164,1163,1165,1234,1094,1095,1233,1235,1093,1162,1166,1305,1096,1025,1026,1304,1232,1236,1167,1168,1166,1237,1097,1098,1238,1236,1096,1169,1165,1308,1028,1099,1029,1307,1239,1235,1170,1171,1169,1240,1100,1101,1241,1239,1099,1168,1172,1311,1031,1102,1032,1310,1242,1238,1174,1173,1175,1244,1104,1105,1245,1243,1103,1172,1176,1315,1035,1106,1036,1314,1246,1242,1177,1176,1178,1247,1107,1108,1246,1248,1106,1175,1179,1318,1038,1109,1039,1317,1245,1249,1321,1322,1392,1393,1250,1394,1464,1251,1320,1323,1391,1465,1180,1395,1463,1466,1537,1252,1324,1325,1323,1396,1253,1252,1397,1395,1254,1326,1322,1468,1183,1251,1182,1469,1398,1394,1327,1328,1326,1399,1256,1255,1400,1398,1257,1329,1325,1471,1186,1254,1185,1472,1401,1397,1330,1329,1331,1402,1259,1258,1401,1403,1260,1328,1332,1474,1189,1257,1188,1475,1404,1400,1334,1333,1335,1406,1263,1262,1405,1407,1264,1336,1332,1478,1193,1261,1192,1479,1408,1404,1337,1336,1338,1409,1266,1265,1410,1408,1267,1339,1335,1481,1264,1196,1195,1482,1407,1411,1340,1339,1341,1412,1269,1268,1413,1411,1270,1338,1342,1267,1484,1198,1199,1485,1410,1414,1343,1344,1342,1415,1272,1271,1414,1416,1273,1270,1341,1345,1487,1201,1202,1488,1413,1417,1346,1347,1345,1418,1275,1274,1419,1417,1276,1273,1348,1344,1204,1490,1491,1205,1420,1416,1349,1350,1348,1421,1278,1277,1422,1420,1279,1276,1347,1351,1207,1493,1494,1208,1419,1423,1352,1351,1353,1424,1281,1280,1423,1425,1282,1279,1354,1350,1210,1496,1497,1211,1426,1422,1355,1356,1354,1427,1284,1283,1428,1426,1285,1282,1353,1357,1213,1499,1500,1214,1429,1425,1359,1360,1358,1431,1287,1288,1432,1430,1286,1289,1361,1357,1217,1504,1503,1216,1433,1429,1362,1363,1361,1434,1290,1291,1435,1433,1289,1292,1364,1360,1220,1507,1506,1219,1436,1432,1365,1364,1366,1437,1293,1294,1436,1438,1292,1295,1367,1363,1223,1510,1509,1222,1439,1435,1368,1367,1369,1440,1296,1297,1439,1441,1295,1298,1366,1370,1226,1513,1512,1225,1438,1442,1371,1370,1372,1443,1299,1300,1442,1444,1298,1301,1373,1369,1516,1229,1228,1515,1445,1441,1374,1375,1373,1446,1302,1303,1447,1445,1301,1376,1372,1304,1519,1232,1231,1518,1444,1448,1377,1378,1376,1449,1305,1306,1450,1448,1304,1379,1375,1522,1307,1234,1235,1521,1451,1447,1380,1379,1381,1452,1308,1309,1451,1453,1307,1378,1382,1525,1237,1310,1238,1524,1450,1454,1384,1383,1385,1456,1312,1313,1455,1457,1311,1382,1386,1529,1241,1314,1242,1528,1454,1458,1387,1386,1388,1459,1315,1316,1460,1458,1314,1389,1385,1532,1244,1317,1245,1531,1461,1457,1390,1391,1389,1462,1318,1319,1463,1461,1317,1392,1388,1535,1247,1320,1248,1534,1464,1460,1611,1612,1683,1684,1538,1757,1685,1539,1610,1613,1682,1758,1465,1686,1756,1540,1609,1831,1614,1613,1615,1541,1687,1688,1540,1542,1686,1612,1616,1468,1761,1689,1762,1539,1543,1467,1617,1618,1616,1544,1690,1691,1545,1543,1689,1619,1615,1471,1764,1692,1765,1542,1546,1472,1621,1620,1622,1548,1694,1695,1547,1549,1693,1619,1623,1475,1768,1696,1769,1546,1550,1474,1624,1623,1625,1551,1697,1698,1550,1552,1696,1626,1622,1478,1771,1699,1772,1549,1553,1477,1627,1628,1626,1554,1700,1701,1553,1555,1699,1629,1625,1481,1774,1702,1775,1556,1552,1482,1630,1631,1629,1557,1703,1704,1556,1558,1702,1705,1628,1632,1484,1777,1778,1555,1559,1485,1633,1632,1634,1560,1706,1707,1559,1561,1705,1708,1631,1635,1487,1780,1781,1558,1562,1486,1636,1637,1635,1563,1709,1710,1564,1562,1708,1711,1638,1634,1490,1783,1784,1565,1561,1491,1640,1641,1639,1567,1713,1714,1568,1566,1712,1715,1642,1638,1494,1787,1788,1565,1569,1495,1643,1644,1642,1570,1716,1717,1571,1569,1715,1718,1645,1641,1497,1790,1791,1572,1568,1498,1646,1645,1647,1573,1719,1720,1572,1574,1718,1721,1644,1648,1500,1793,1794,1571,1575,1501,1649,1650,1648,1576,1723,1722,1575,1577,1724,1721,1651,1647,1503,1797,1796,1578,1574,1502,1652,1653,1651,1579,1726,1725,1580,1578,1727,1724,1654,1650,1506,1800,1799,1581,1577,1507,1655,1654,1656,1582,1729,1728,1583,1581,1730,1727,1657,1653,1509,1803,1802,1584,1580,1510,1659,1658,1660,1586,1733,1732,1585,1587,1734,1731,1657,1661,1513,1807,1806,1584,1588,1512,1662,1663,1661,1589,1736,1735,1588,1590,1737,1734,1660,1664,1516,1810,1809,1591,1587,1517,1665,1666,1664,1592,1739,1738,1593,1591,1740,1737,1663,1667,1519,1813,1812,1594,1590,1520,1668,1667,1669,1595,1742,1741,1594,1596,1743,1666,1670,1522,1816,1740,1815,1593,1597,1521,1671,1672,1670,1598,1745,1744,1599,1597,1746,1669,1673,1525,1819,1743,1818,1596,1600,1524,1674,1673,1675,1601,1748,1747,1602,1600,1749,1676,1672,1528,1822,1746,1821,1603,1599,1527,1678,1679,1677,1605,1752,1751,1606,1604,1753,1676,1680,1532,1826,1750,1825,1607,1603,1533,1681,1680,1682,1608,1755,1754,1609,1607,1756,1683,1679,1535,1829,1753,1828,1606,1610,1534,1832,1905,1833,1906,1758,1831,1759,1907,1978,1834,1904,1979,1684,1760,1830,1757,1685,1980,1835,1836,1834,1761,1909,1908,1762,1760,1910,1833,1837,1687,1982,1907,1759,1763,1981,1688,1838,1837,1839,1764,1912,1911,1765,1763,1913,1836,1840,1690,1985,1910,1984,1766,1762,1691,1842,1841,1843,1768,1916,1915,1767,1769,1917,1844,1840,1694,1989,1914,1988,1770,1766,1695,1845,1844,1846,1771,1919,1918,1770,1772,1920,1843,1847,1697,1992,1917,1991,1769,1773,1696,1848,1849,1847,1774,1922,1921,1773,1775,1923,1850,1846,1700,1995,1920,1994,1776,1772,1701,1851,1852,1850,1777,1925,1924,1778,1776,1926,1853,1849,1703,1923,1998,1997,1779,1775,1704,1855,1854,1856,1781,1929,1928,1780,1782,1930,1927,1853,1857,1707,2002,2001,1779,1783,1708,1858,1857,1859,1784,1932,1931,1783,1785,1933,1930,1856,1860,1710,2005,2004,1782,1786,1709,1861,1860,1862,1787,1935,1934,1786,1788,1936,1933,1859,1863,1713,2008,2007,1785,1789,1712,1864,1865,1863,1790,1938,1937,1789,1791,1939,1936,1866,1862,1716,2011,2010,1792,1788,1717,1867,1868,1866,1793,1941,1940,1794,1792,1942,1939,1865,1869,1719,2014,2013,1795,1791,1720,1871,1870,1872,1797,1944,1945,1796,1798,1943,1946,1869,1873,1723,2017,2018,1795,1799,1722,1874,1875,1873,1800,1947,1948,1801,1799,1946,1949,1876,1872,1726,2020,2021,1802,1798,1727,1877,1876,1878,1803,1950,1951,1802,1804,1949,1952,1875,1879,1729,2023,2024,1801,1805,1728,1880,1879,1881,1806,1953,1954,1805,1807,1952,1955,1878,1882,1732,2026,2027,1804,1808,1731,1883,1884,1882,1809,1956,1957,1810,1808,1955,1958,1885,1881,1735,2029,2030,1811,1807,1736,1887,1888,1886,1813,1960,1961,1814,1812,1959,1889,1885,1739,1962,2033,2034,1815,1811,1740,1890,1891,1889,1816,1963,1964,1815,1817,1962,1888,1892,1742,2036,1965,2037,1814,1818,1741,1893,1894,1892,1819,1966,1967,1820,1818,1965,1895,1891,1745,2039,1968,2040,1821,1817,1746,1896,1895,1897,1822,1969,1970,1821,1823,1968,1894,1898,1748,2042,1971,2043,1820,1824,1747,1900,1901,1899,1826,1973,1974,1825,1827,1972,1898,1902,1752,2046,1975,2047,1824,1828,1753,1903,1904,1902,1829,1976,1977,1830,1828,1975,1905,1901,1755,2049,1978,1831,1827,2050,1756,2052,2053,2124,1979,2125,1980,2051,2126,2196,2054,2123,2197,1906,1981,2050,1907,1978,2198,2055,2056,2054,1982,2128,2127,1983,1981,2129,2057,2053,1909,2200,2126,2199,1984,1980,1908,2058,2059,2057,1985,2131,2130,1986,1984,2132,2060,2056,1912,2203,2129,2202,1987,1983,1911,2062,2061,2063,1989,2135,2134,1988,1990,2136,2060,2064,1916,2207,2133,2206,1987,1991,1917,2065,2064,2066,1992,2138,2137,1991,1993,2139,2067,2063,1919,2210,2136,2209,1994,1990,1918,2068,2069,2067,1995,2141,2140,1994,1996,2142,2070,2066,1922,2213,2139,2212,1997,1993,1921,2071,2072,2070,1998,2144,2143,1999,1997,2145,2069,2073,1925,2142,2216,2215,1996,2000,1926,2074,2073,2075,2001,2147,2146,2002,2000,2148,2145,2072,2076,1928,2219,2218,1999,2003,1927,2077,2078,2076,2004,2150,2149,2005,2003,2151,2148,2079,2075,1931,2222,2221,2006,2002,1932,2081,2082,2080,2008,2154,2153,2009,2007,2155,2152,2079,2083,1935,2226,2225,2006,2010,1936,2084,2085,2083,2011,2157,2156,2012,2010,2158,2155,2086,2082,1938,2229,2228,2013,2009,1939,2087,2086,2088,2014,2160,2159,2013,2015,2161,2158,2085,2089,1941,2232,2231,2012,2016,1940,2090,2089,2091,2017,2162,2163,2016,2018,2161,2164,2092,2088,1944,2234,2235,2019,2015,1945,2093,2094,2092,2020,2165,2166,2021,2019,2164,2167,2095,2091,1947,2237,2238,2022,2018,1946,2096,2095,2097,2023,2168,2169,2022,2024,2167,2170,2098,2094,1950,2240,2241,2021,2025,1949,2100,2099,2101,2027,2172,2173,2026,2028,2171,2174,2098,2102,1954,2244,2245,2025,2029,1953,2103,2102,2104,2030,2175,2176,2029,2031,2174,2177,2101,2105,1957,2247,2248,2032,2028,1956,2106,2107,2105,2033,2178,2179,2034,2032,2177,2108,2104,1960,2180,2250,2251,2035,2031,1959,2109,2108,2110,2036,2181,2182,2035,2037,2180,2107,2111,1963,2253,2183,2254,2034,2038,1962,2112,2113,2111,2039,2184,2185,2040,2038,2183,2114,2110,1966,2256,2186,2257,2041,2037,1967,2115,2116,2114,2042,2187,2188,2043,2041,2186,2113,2117,1969,2259,2189,2260,2040,2044,1968,2119,2118,2120,2046,2191,2192,2045,2047,2190,2117,2121,1973,2263,2193,2264,2048,2044,1972,2122,2121,2123,2049,2194,2195,2048,2050,2193,2120,2124,1976,2266,2196,2267,2047,2051,1975,2269,-1,-1,2339,2270,2197,-1,-1,2198,2268,-1,-1,-1,2271,2338,-1,2125,-1,2272,2273,2271,-1,2200,-1,2201,2199,-1,-1,-1,-1,2270,2274,2128,2202,-1,2129,2275,-1,2276,2274,2203,-1,2204,-1,2202,-1,-1,-1,2277,2273,2131,-1,-1,2205,2278,-1,2279,2277,2206,-1,2207,-1,2205,-1,-1,-1,2280,2276,2134,2208,-1,-1,2281,-1,2282,2280,2209,-1,2210,-1,2208,-1,-1,-1,2283,2279,2137,2211,-1,2138,2284,-1,2283,2285,2212,-1,2213,-1,2211,-1,-1,-1,2282,2286,2140,2214,-1,-1,2288,-1,2289,2287,2216,-1,2217,-1,2215,-1,-1,-1,2218,2290,2286,2144,-1,2145,2291,-1,2290,2292,2219,-1,2220,-1,2218,-1,-1,-1,2221,2289,2293,2147,-1,-1,2294,2293,2295,-1,-1,2222,2223,-1,-1,2221,-1,-1,2224,2296,2292,2150,2151,-1,2297,-1,2298,2296,2225,2226,-1,-1,2224,-1,2227,-1,-1,2299,2295,-1,-1,2153,2300,2301,2299,-1,-1,2228,2229,-1,-1,2227,2230,-1,-1,2302,2298,2156,2157,-1,2303,-1,2304,2302,2231,2232,-1,-1,2230,-1,2233,-1,-1,2305,2301,-1,-1,2159,2306,-1,2307,2305,2235,-1,2234,-1,-1,2236,2233,-1,-1,2308,2304,2163,2162,-1,2309,-1,2308,2310,2238,-1,2237,-1,2239,-1,-1,2236,-1,2307,2311,2166,2165,-1,2312,-1,2311,2313,2241,2240,-1,-1,2242,-1,-1,2239,-1,2310,2314,2169,-1,-1,2315,2314,2316,-1,2244,-1,2243,-1,-1,2245,-1,-1,2242,2317,2313,2172,2171,-1,2318,-1,2317,2319,2247,2246,-1,-1,2248,-1,-1,2245,-1,-1,2316,2320,-1,2175,2321,2320,2322,-1,2250,-1,2249,-1,2251,-1,-1,-1,2248,2319,2323,2178,2177,-1,2325,-1,2326,2324,2254,-1,2253,-1,2255,-1,-1,-1,-1,2327,2323,-1,2182,2252,2328,2329,2327,-1,2257,-1,2256,2258,-1,-1,-1,-1,2330,2326,2185,2255,2184,-1,2331,-1,2332,2330,2260,-1,2259,-1,2261,-1,-1,-1,2333,2329,2188,-1,-1,2258,2334,-1,2335,2333,2263,-1,2262,2264,-1,-1,-1,-1,2336,2332,2191,-1,2261,2190,2337,-1,2338,2336,2266,-1,2265,-1,2267,-1,-1,-1,2339,2335,2194,-1,-1,2264],"visual":[0,5,4,3,1,7,6,2,16,8,17,9,10,15,11,18,14,12,20,37,36,21,8,38,58,19,9,22,35,59,1,39,57,60,85,7,23,22,41,40,10,24,42,9,11,39,21,2,64,63,25,3,43,65,26,25,44,45,12,27,43,13,11,24,46,68,3,69,67,4,42,28,29,28,48,14,49,47,30,27,15,13,50,46,72,73,4,5,74,71,31,32,52,51,16,30,53,15,17,33,50,77,6,78,76,5,54,29,34,35,55,56,18,33,54,17,19,57,36,7,81,82,32,6,53,83,86,117,116,87,150,118,59,85,60,151,115,88,188,152,119,149,37,84,89,120,121,90,88,62,61,119,122,63,155,91,154,87,60,39,156,40,92,124,93,123,91,64,125,65,94,159,63,158,122,66,41,90,42,160,95,127,96,128,67,94,126,68,66,97,162,163,129,44,43,161,93,69,98,99,131,130,70,97,69,132,100,129,71,166,167,46,165,68,45,96,101,102,134,133,135,73,72,100,103,170,74,71,169,171,136,132,48,49,105,104,137,138,75,106,76,136,103,139,74,174,173,50,175,77,51,107,108,141,107,140,78,109,142,77,79,106,178,177,139,52,53,179,110,76,111,144,110,145,112,81,143,80,109,181,82,182,146,79,55,113,54,180,114,148,147,113,115,83,84,149,146,82,185,112,186,116,85,57,184,56,189,230,229,190,273,231,151,274,152,188,320,275,228,191,232,272,117,187,192,233,234,191,193,232,154,153,277,278,155,235,190,194,276,152,231,119,195,236,237,194,196,235,156,157,281,280,238,193,155,158,282,197,122,234,198,239,240,197,199,159,238,160,284,241,158,196,285,283,200,124,161,125,201,243,242,200,202,162,244,161,241,287,288,199,163,286,127,289,160,203,204,246,203,245,247,205,165,164,291,202,244,290,166,292,163,129,248,206,249,207,206,248,250,167,208,168,205,294,295,166,247,293,169,251,132,131,252,209,210,253,251,170,208,211,171,169,297,298,250,254,296,299,134,168,255,212,213,256,254,173,211,172,214,301,300,174,257,302,171,253,136,137,215,258,216,259,257,214,175,176,304,217,260,305,174,303,177,139,256,213,218,261,262,219,217,178,260,179,263,308,307,220,177,309,141,306,180,216,221,265,264,222,220,181,266,180,311,263,182,223,310,312,219,144,179,143,224,268,267,225,223,269,184,183,314,315,266,226,185,182,313,222,146,270,227,271,270,228,226,272,186,187,318,317,185,269,229,225,319,188,273,149,371,321,372,422,370,322,423,274,476,424,320,275,373,421,369,323,230,276,374,324,375,325,323,373,426,277,427,276,376,278,326,425,322,428,372,233,377,378,327,328,326,430,280,376,379,429,279,329,281,431,325,428,278,235,381,330,380,331,382,433,329,283,332,282,434,379,432,284,383,281,238,328,384,333,334,383,385,286,437,436,332,335,285,287,386,382,438,435,284,241,387,337,388,336,386,440,338,289,288,335,439,389,441,290,287,385,244,339,391,390,340,339,341,443,392,389,292,291,444,338,442,293,290,342,445,246,394,343,393,342,344,395,447,295,446,294,392,341,448,296,293,345,445,396,397,346,398,396,345,347,450,297,298,449,451,395,399,344,348,296,299,252,400,349,401,350,348,399,453,300,454,301,402,351,452,299,302,347,455,398,403,404,352,353,351,457,405,402,303,304,456,354,458,302,305,350,455,258,407,355,406,356,408,460,354,306,307,357,461,405,459,305,308,409,260,353,410,359,358,409,411,309,463,464,357,360,310,308,412,408,462,465,311,263,413,362,414,361,412,467,363,312,360,313,466,415,468,311,411,314,266,364,416,417,365,364,366,470,315,418,415,471,316,363,314,469,367,472,317,269,420,368,419,367,369,421,474,318,473,319,418,317,366,475,370,472,422,271,533,477,534,590,532,478,591,650,592,423,476,424,535,589,531,479,593,649,536,480,537,481,535,479,594,595,426,538,593,425,427,482,596,478,534,654,539,540,483,484,598,482,597,538,541,429,599,485,430,428,596,481,658,537,543,542,486,487,601,544,485,600,602,432,541,488,433,431,545,484,599,603,546,489,545,490,547,604,605,488,435,491,603,544,434,436,548,606,665,487,549,493,550,492,548,608,607,494,438,491,609,551,437,439,547,606,668,495,552,553,496,495,611,551,497,612,610,441,554,494,440,442,550,498,613,609,556,555,499,498,614,500,615,557,554,444,613,497,443,445,616,501,675,558,559,502,558,501,560,503,618,617,447,557,619,448,446,500,616,504,561,679,562,505,563,561,506,504,621,622,620,450,449,451,560,564,507,503,619,623,565,508,566,509,564,507,624,625,453,567,623,452,454,510,626,506,563,685,568,569,511,512,628,510,627,567,570,456,629,513,455,457,626,509,689,566,572,571,514,515,631,573,513,630,632,459,570,516,458,460,574,512,633,629,575,517,574,518,576,634,635,516,462,519,633,573,461,463,577,636,696,515,578,521,579,520,577,638,637,522,465,519,639,580,464,466,576,636,699,523,581,582,524,523,641,580,525,642,640,468,583,522,467,469,579,526,639,643,585,584,527,526,644,528,645,586,583,471,643,525,470,472,646,529,706,587,588,530,587,529,589,531,648,647,474,586,649,475,473,528,646,532,590,710,713,651,714,775,776,652,712,839,777,591,774,715,592,650,711,653,840,778,716,717,654,779,715,655,653,780,778,594,718,593,595,656,714,781,652,843,719,720,657,658,782,783,718,656,721,597,781,659,784,598,596,717,847,655,722,723,660,661,786,785,721,659,724,600,787,662,784,599,601,850,658,720,726,725,663,664,789,788,727,724,662,790,665,603,602,604,787,853,728,854,729,728,667,666,792,730,791,793,665,668,727,606,607,605,731,857,856,790,732,731,670,669,733,795,796,671,794,668,609,730,610,608,734,797,860,859,735,673,736,734,672,798,799,674,612,797,671,737,800,611,613,733,863,675,738,739,676,675,802,737,801,677,615,740,803,674,800,616,614,736,866,678,741,742,679,805,678,740,680,804,743,806,618,619,617,677,803,681,870,739,745,744,682,808,681,683,746,743,807,809,621,622,620,680,684,873,806,810,748,747,685,811,686,749,684,812,746,810,624,623,625,687,813,683,876,750,751,750,688,689,814,752,815,687,627,749,813,690,816,628,626,753,880,686,754,691,753,755,692,818,817,690,630,819,693,752,816,629,631,756,883,689,757,758,694,695,756,821,820,693,822,696,633,759,632,634,755,819,886,887,760,761,697,698,824,759,823,825,696,699,762,636,637,635,758,890,889,826,763,764,701,700,827,828,762,765,702,826,699,639,638,640,829,893,761,892,767,766,704,703,830,831,768,705,765,642,829,702,832,643,641,896,706,769,770,769,707,706,834,833,771,708,768,645,835,705,832,644,646,772,899,709,773,772,710,837,774,709,711,836,838,648,771,649,647,708,775,835,712,903,906,973,972,907,840,1040,974,841,905,776,971,908,1041,839,777,904,842,1039,909,910,976,843,908,977,844,842,975,911,779,978,845,1044,780,778,907,1045,912,913,846,979,980,847,911,914,845,978,981,782,848,783,1048,1047,781,910,916,915,983,849,850,982,917,914,984,848,851,785,981,1051,786,784,1050,1052,919,918,986,853,852,920,985,987,854,917,851,788,789,1054,984,921,787,1055,922,921,989,923,856,855,990,988,857,791,920,854,924,792,991,1057,1058,790,925,926,859,992,993,924,858,860,991,927,994,794,795,857,1061,923,1060,793,928,929,996,862,995,927,863,861,930,997,797,994,798,1064,864,860,796,926,932,931,999,865,866,998,933,1000,864,930,800,801,867,1067,997,1068,863,799,935,934,1002,868,869,936,1003,1001,867,933,870,803,804,1071,1004,1070,937,802,938,937,1005,939,871,1006,872,1004,870,873,936,1007,806,807,940,1074,1073,805,941,942,1009,940,875,1008,874,1010,876,873,943,1007,810,809,939,1077,1078,811,944,945,1012,878,877,943,1011,1013,879,946,876,813,812,1080,1010,1081,942,814,947,948,1015,881,880,1016,946,1014,882,949,816,815,879,1084,1017,1083,883,817,951,950,1018,884,1019,952,885,883,949,1017,819,1020,818,1087,886,882,820,953,954,953,887,1022,1021,955,888,886,1023,952,1020,822,821,889,1090,956,1091,823,957,958,1025,956,890,891,1024,1026,889,825,959,892,955,824,1023,1094,1093,826,960,961,1028,893,894,959,1029,1027,892,962,895,828,827,1097,1030,958,829,1096,963,964,1031,897,896,1032,962,965,1030,898,895,831,1033,1100,830,832,1101,1099,967,966,900,1035,1034,899,968,965,901,1036,1033,834,898,833,1103,1104,835,969,970,969,1038,903,971,1037,902,904,1039,968,837,1036,901,1107,836,838,972,1106,1110,1180,1111,1179,1041,1249,1181,1042,1109,1250,1178,1112,973,1320,1251,1248,1182,1043,1113,1183,1114,1184,1044,1112,1045,1182,1043,1115,1253,1185,976,1254,1046,1111,977,975,1116,1117,1186,1187,1047,1048,1115,1185,1118,1046,1188,1256,1257,1049,979,980,978,1114,1120,1119,1190,1189,1050,1051,1121,1118,1191,1188,1049,1052,1260,1259,982,983,1261,981,1123,1122,1193,1192,1054,1124,1053,1194,1121,1055,1052,1263,1191,985,1262,986,1264,1125,1126,1196,1125,1127,1057,1195,1056,1197,1058,1124,1266,1055,1128,988,1267,989,1194,1265,1129,1199,1130,1128,1060,1200,1198,1059,1061,1131,1269,1270,1127,992,1058,991,1201,1197,1132,1133,1202,1203,1063,1131,1062,1201,1064,1134,1273,1204,1272,995,994,1061,1130,1065,1135,1136,1205,1206,1066,1134,1067,1137,1065,1204,1207,1276,998,1275,997,1068,1277,1064,1139,1138,1209,1208,1069,1140,1070,1210,1137,1068,1207,1279,1001,1071,1280,1000,1278,1002,1142,1212,1141,1211,1143,1072,1073,1213,1071,1140,1282,1074,1210,1283,1004,1144,1003,1005,1145,1215,1144,1146,1075,1076,1216,1214,1077,1074,1286,1285,1147,1143,1007,1217,1213,1006,1148,1218,1149,1219,1147,1079,1078,1217,1080,1150,1289,1077,1220,1288,1010,1146,1011,1009,1151,1152,1221,1222,1082,1150,1081,1220,1153,1083,1223,1292,1013,1080,1291,1014,1293,1012,1155,1154,1225,1224,1085,1156,1084,1153,1086,1226,1223,1295,1016,1296,1017,1083,1294,1087,1158,1157,1228,1227,1088,1159,1089,1229,1087,1156,1298,1226,1299,1019,1020,1090,1160,1086,1161,1231,1160,1162,1091,1230,1232,1092,1090,1159,1302,1301,1163,1022,1093,1023,1229,1233,1164,1234,1165,1163,1094,1235,1095,1233,1093,1166,1305,1096,1162,1026,1304,1025,1236,1306,1167,1168,1237,1238,1097,1166,1098,1236,1169,1096,1099,1308,1239,1029,1309,1028,1307,1165,1170,1171,1240,1241,1101,1100,1169,1172,1239,1242,1102,1099,1311,1312,1032,1031,1310,1033,1174,1173,1244,1243,1104,1103,1175,1245,1172,1105,1242,1315,1314,1102,1035,1034,1036,1176,1177,1247,1176,1246,1107,1178,1106,1248,1108,1175,1318,1245,1038,1317,1105,1179,1037,1039,1321,1393,1322,1392,1464,1394,1250,1251,1320,1465,1323,1391,1537,1466,1395,1463,1180,1319,1324,1396,1325,1397,1323,1253,1395,1254,1252,1468,1326,1469,1398,1467,1322,1183,1255,1394,1327,1399,1328,1400,1326,1256,1398,1257,1255,1471,1329,1472,1401,1186,1258,1470,1325,1187,1330,1331,1402,1403,1259,1329,1260,1401,1332,1404,1258,1475,1474,1261,1189,1190,1476,1473,1334,1333,1406,1405,1262,1263,1335,1332,1407,1404,1478,1261,1477,1264,1192,1479,1193,1191,1337,1409,1336,1408,1265,1338,1266,1410,1335,1481,1407,1264,1480,1267,1482,1195,1196,1339,1340,1412,1339,1411,1341,1269,1268,1413,1484,1338,1270,1410,1267,1485,1483,1198,1342,1199,1343,1415,1342,1414,1344,1416,1272,1271,1487,1273,1488,1341,1270,1413,1345,1486,1201,1417,1346,1418,1347,1345,1419,1417,1275,1274,1490,1276,1491,1348,1344,1273,1420,1416,1204,1205,1349,1421,1350,1422,1348,1278,1420,1277,1279,1494,1493,1351,1423,1276,1347,1207,1208,1495,1352,1424,1353,1425,1281,1351,1423,1280,1282,1354,1497,1426,1496,1498,1210,1279,1211,1350,1355,1356,1427,1428,1284,1354,1357,1283,1426,1285,1500,1429,1499,1501,1213,1214,1282,1286,1359,1358,1431,1430,1287,1360,1357,1288,1432,1286,1503,1429,1504,1502,1217,1216,1289,1285,1362,1434,1361,1433,1290,1363,1435,1291,1289,1360,1506,1432,1507,1505,1220,1292,1219,1364,1365,1437,1364,1436,1366,1293,1438,1294,1292,1509,1510,1363,1435,1295,1367,1223,1222,1508,1368,1440,1367,1369,1439,1441,1296,1297,1513,1295,1512,1366,1370,1298,1438,1442,1226,1225,1371,1443,1372,1444,1370,1442,1299,1300,1516,1298,1515,1373,1301,1445,1369,1517,1229,1441,1374,1446,1375,1447,1373,1302,1303,1445,1519,1376,1301,1448,1304,1518,1520,1232,1372,1231,1377,1449,1378,1450,1306,1376,1305,1448,1379,1522,1451,1307,1523,1304,1521,1235,1234,1375,1380,1381,1452,1453,1309,1308,1379,1382,1451,1454,1525,1310,1526,1307,1238,1524,1237,1239,1384,1383,1456,1455,1312,1385,1311,1457,1382,1454,1313,1528,1529,1310,1241,1240,1527,1530,1387,1459,1386,1458,1388,1315,1460,1314,1316,1532,1385,1531,1457,1244,1313,1533,1389,1243,1390,1462,1389,1461,1391,1318,1463,1317,1319,1535,1388,1534,1460,1536,1392,1247,1316,1464,1611,1538,1539,1610,1612,1683,1465,1684,1466,1537,1685,1757,1540,1609,1613,1682,1393,1467,1614,1541,1542,1615,1540,1613,1468,1687,1469,1688,1467,1543,1616,1686,1539,1470,1612,1396,1617,1544,1618,1545,1543,1616,1471,1472,1690,1691,1546,1619,1470,1473,1689,1692,1399,1542,1621,1548,1620,1547,1475,1474,1549,1694,1546,1622,1619,1693,1476,1473,1695,1402,1692,1403,1624,1551,1623,1550,1552,1625,1478,1697,1477,1549,1696,1622,1479,1698,1476,1406,1553,1405,1627,1554,1553,1626,1555,1628,1481,1700,1480,1482,1701,1552,1699,1625,1556,1629,1479,1409,1630,1557,1558,1631,1556,1629,1484,1703,1485,1704,1483,1559,1702,1632,1555,1628,1412,1486,1633,1560,1634,1561,1559,1632,1487,1707,1488,1706,1562,1486,1635,1708,1489,1705,1558,1415,1636,1563,1637,1564,1562,1490,1635,1491,1710,1565,1638,1709,1489,1711,1492,1418,1708,1561,1640,1567,1639,1566,1494,1568,1713,1493,1641,1565,1638,1712,1714,1495,1492,1421,1422,1569,1643,1570,1642,1569,1571,1644,1497,1716,1496,1717,1568,1641,1498,1715,1495,1572,1424,1645,1646,1573,1572,1645,1574,1647,1500,1719,1720,1499,1501,1571,1644,1575,1718,1648,1721,1498,1649,1576,1577,1650,1575,1648,1503,1723,1722,1504,1502,1578,1651,1574,1724,1647,1721,1505,1652,1579,1653,1580,1578,1651,1506,1726,1507,1725,1581,1654,1505,1727,1508,1577,1434,1650,1655,1582,1656,1583,1509,1581,1729,1510,1654,1584,1657,1730,1728,1508,1511,1437,1436,1580,1659,1586,1658,1585,1587,1513,1660,1512,1732,1584,1657,1733,1514,1731,1511,1440,1734,1588,1662,1589,1661,1588,1590,1663,1516,1735,1515,1736,1587,1517,1660,1734,1514,1737,1591,1443,1665,1592,1591,1664,1593,1666,1519,1739,1518,1738,1520,1590,1740,1663,1594,1667,1446,1517,1668,1595,1596,1669,1594,1667,1522,1742,1523,1521,1741,1597,1743,1670,1593,1666,1524,1449,1671,1598,1672,1599,1597,1670,1525,1745,1526,1600,1746,1673,1524,1744,1527,1452,1596,1453,1674,1601,1675,1602,1528,1529,1600,1748,1603,1673,1676,1749,1527,1530,1747,1456,1750,1455,1678,1605,1677,1604,1606,1679,1532,1531,1752,1751,1603,1676,1533,1530,1753,1750,1459,1607,1681,1608,1607,1680,1609,1682,1535,1755,1534,1754,1536,1606,1679,1756,1610,1533,1683,1462,1832,1758,1833,1905,1759,1831,1906,1684,1978,1907,1685,1757,1834,1904,1830,1760,1611,1756,1835,1761,1836,1762,1834,1760,1909,1687,1910,1688,1837,1908,1763,1686,1759,1833,1689,1911,1838,1839,1764,1765,1912,1837,1913,1763,1690,1840,1691,1766,1911,1689,1692,1914,1617,1618,1842,1841,1768,1767,1843,1916,1915,1769,1694,1693,1840,1766,1695,1917,1914,1692,1770,1844,1845,1771,1844,1770,1846,1772,1919,1918,1697,1696,1698,1843,1769,1920,1773,1847,1917,1695,1848,1774,1849,1775,1847,1773,1922,1700,1921,1701,1923,1699,1850,1776,1772,1846,1702,1627,1851,1777,1852,1778,1925,1850,1776,1703,1704,1926,1853,1924,1779,1702,1705,1775,1849,1630,1855,1854,1781,1780,1928,1856,1853,1782,1929,1707,1779,1706,1927,1708,1705,1930,1633,2001,1858,1784,1857,1783,1859,1785,1931,1932,1710,1709,1856,1782,1711,1930,1933,1708,1786,1860,1861,1787,1860,1862,1786,1788,1935,1934,1713,1712,1714,1859,1785,1936,1789,1863,1933,1711,1864,1790,1865,1791,1863,1789,1938,1716,1937,1717,1866,1792,1715,1939,1788,1862,1936,1718,1867,1868,1793,1794,1941,1866,1792,1719,1720,1869,1940,1795,1942,1718,1721,1646,1791,1865,1871,1870,1797,1796,1944,1872,1798,1723,1722,1869,1945,1795,1943,1724,1721,1649,1799,1873,1874,1800,1873,1799,1875,1801,1947,1726,1948,1725,1872,1798,1727,1946,1802,1876,1949,1724,1877,1803,1878,1876,1804,1802,1950,1951,1729,1730,1728,1879,1805,1949,1801,1875,1952,1731,1880,1806,1881,1807,1879,1805,1954,1953,1732,1733,1882,1808,1731,1955,1952,1734,1804,1878,1883,1884,1809,1810,1957,1882,1885,1808,1956,1735,1811,1736,1958,1734,1737,1955,1662,2030,1887,1813,1886,1812,1960,1888,1814,1739,1738,1959,1885,1961,1811,1740,1737,1815,1889,1665,1890,1816,1889,1815,1891,1817,1963,1742,1964,1741,1962,1743,1888,1814,1818,1892,1740,1668,1893,1819,1894,1820,1892,1818,1966,1967,1745,1746,1744,1895,1821,1965,1817,1891,1968,1747,1896,1897,1822,1823,1895,1969,1970,1821,1748,1749,1898,1824,1747,1968,1971,1750,1820,1894,1900,1899,1826,1825,1973,1901,1972,1827,1752,1898,1751,1824,1974,1753,1750,1971,1678,1677,1903,1829,1902,1828,1904,1830,1976,1755,1975,1754,1901,1977,1827,1756,1831,1905,1753,1974,2052,1979,2053,2124,2125,1980,2051,2126,2196,1906,1907,1978,2054,2123,2050,1981,2197,2127,2055,1982,2056,1983,2128,2054,1981,2129,1909,2127,1910,2057,1984,1908,2053,2200,1980,2130,2058,2059,1985,1986,2131,2057,2132,1984,1912,2060,1913,2130,1987,1911,2133,1914,2203,2204,2062,2061,1989,1988,2134,2135,2063,2060,1990,1987,1916,1915,2133,2136,1917,1914,2206,2207,2065,2064,1992,1991,2138,2137,2066,1993,1919,2063,1918,1990,2139,2136,1920,1917,2210,2209,2068,1995,2067,1994,2069,2141,2140,1996,1922,1921,2142,2066,1923,1993,2139,2070,1997,2213,2071,1998,2072,2070,2144,1999,1997,2143,1925,2145,1926,1924,2073,2000,2069,1996,2142,2216,2074,2075,2001,2002,2147,2073,2000,2146,2148,1928,1929,2076,2003,1927,2219,2072,1999,1930,2077,2078,2004,2005,2150,2076,2151,2003,2149,2079,1931,1932,2006,1930,1933,2222,2152,2075,2081,2080,2008,2007,2153,2154,2082,2079,2009,1935,2152,2006,1934,1936,1933,2225,2155,2226,2084,2083,2011,2010,2156,2085,2157,2012,1938,2082,1937,2155,2009,1939,2158,2228,2086,1936,2087,2014,2086,2088,2013,2159,2160,2015,1941,1940,2158,1942,2085,2012,2161,2089,2016,2231,2090,2017,2091,2089,2018,2163,2162,2016,1944,1945,2164,1943,2092,2019,2161,2088,2015,2235,2093,2094,2020,2021,2166,2092,2165,2019,1947,2095,1948,2167,2022,1946,2164,2238,2091,1949,2096,2097,2023,2024,2169,2168,2095,2098,2022,1950,2170,2025,1951,1949,1952,2241,2167,2240,2100,2099,2027,2026,2172,2101,2171,2028,2173,2098,1954,1953,2025,1955,1952,2244,2170,2102,2103,2102,2030,2029,2175,2104,2031,2176,2174,1957,1956,2101,2028,1958,2247,2105,2032,1955,2106,2033,2105,2107,2178,2032,2034,2179,1960,2177,1959,1961,2104,2031,2108,2035,2180,2250,2109,2036,2110,2037,2108,2181,2182,2035,1963,1964,2180,2111,1962,2038,2183,2107,2034,2253,2112,2113,2039,2040,2184,2185,2111,2038,1966,2114,1967,2041,2183,2186,1965,1968,2256,2257,2115,2116,2042,2043,2188,2187,2114,2117,2041,2044,1969,1970,2189,2186,1968,1971,2260,2259,2119,2118,2046,2045,2191,2120,2190,2047,1973,2117,1972,2192,2044,1974,2189,1971,2263,2262,2122,2049,2121,2048,2194,2123,2050,2193,1976,2195,1975,2120,2047,1977,2124,2266,2051,2192,2269,2197,-1,-1,2270,2339,-1,2198,2268,-1,2125,-1,-1,2126,2196,-1,2338,2271,2272,2200,2273,-1,-1,2271,2201,2199,-1,-1,2128,-1,-1,2129,2274,2202,2127,2270,2275,2276,-1,2203,2204,2274,-1,-1,2202,2131,-1,2132,2277,2205,-1,-1,-1,2130,2278,2279,2206,-1,-1,2207,2277,-1,2205,-1,2134,2280,2208,2135,-1,-1,2133,-1,2281,2282,-1,2210,2209,-1,-1,2280,2211,2283,2208,2138,2137,-1,-1,-1,-1,-1,2284,2285,-1,2213,-1,2212,2283,-1,2214,2286,2141,-1,-1,2140,2211,-1,2142,-1,2288,2287,-1,2216,2215,-1,-1,2217,2289,2286,2144,-1,2143,-1,2214,-1,2145,-1,2291,2290,2219,-1,-1,2218,2220,2292,-1,2289,2147,-1,-1,-1,2146,2148,2217,-1,2294,2293,2222,-1,-1,2223,2295,2221,-1,2150,2292,-1,-1,-1,2151,2149,2224,-1,2297,2296,2225,-1,-1,2226,2298,2224,-1,2153,-1,2295,-1,2154,-1,2227,2152,-1,2300,2299,-1,2228,-1,2229,2301,-1,2227,2156,-1,-1,2157,2230,2298,-1,2155,2302,2303,-1,2302,2231,2232,2304,-1,-1,2230,2233,2159,-1,2160,-1,-1,2301,2305,-1,2306,-1,2307,2235,2234,2305,-1,-1,2236,2233,2163,-1,2162,-1,-1,2308,2304,2164,2309,2310,-1,2238,2237,2308,-1,-1,2239,2166,-1,2165,2236,2311,-1,-1,-1,2167,2312,2313,2241,-1,-1,2240,2311,2242,-1,-1,2169,2314,-1,-1,2168,2239,2170,-1,2315,2316,2244,-1,-1,2243,-1,2314,2245,2172,2317,-1,2171,2173,-1,-1,-1,2242,2318,2319,2247,-1,-1,2248,2246,2317,-1,2320,-1,2175,-1,-1,2176,2174,2249,2245,2321,2322,-1,2250,2251,-1,-1,2249,2320,2323,2178,-1,2179,2252,-1,-1,-1,-1,2325,2324,2253,-1,-1,2254,2326,2252,2323,-1,-1,2181,2182,2255,-1,-1,2180,-1,2328,2327,-1,2256,2257,-1,-1,2329,2255,2326,2258,2184,2185,-1,-1,-1,-1,-1,2331,2330,2260,-1,-1,2259,2332,-1,2261,-1,2188,2329,2258,2187,-1,-1,2189,-1,2334,2333,-1,2263,2262,2335,-1,-1,2264,2191,-1,2190,2332,2261,-1,-1,2192,-1,2337,2266,2336,-1,-1,2338,2265,2267,-1,2194,-1,-1,-1,2193,2335,2264,2195,2339]},"4":{"rings":56,"count":4187,"defaultK":17,"kMax":32,"geodesic":[0,5,4,1,2,6,3,7,14,9,19,16,12,17,11,10,18,15,13,8,24,34,21,37,31,27,36,22,29,28,30,32,38,60,39,20,61,88,62,21,37,59,40,8,89,87,63,90,120,22,36,19,9,91,119,64,86,41,58,1,121,122,157,92,42,43,41,66,23,65,24,67,22,64,40,44,10,95,94,68,25,96,11,93,9,21,63,97,39,45,69,92,127,2,128,126,46,47,45,71,26,70,27,72,25,69,44,48,100,12,101,28,99,73,13,102,11,68,24,98,43,49,134,74,133,3,29,103,49,50,48,74,29,75,28,73,76,30,51,47,27,104,14,105,13,103,72,106,77,15,31,102,52,46,26,107,139,138,4,12,53,52,54,79,32,80,31,78,33,81,55,51,110,16,109,30,111,77,15,108,17,82,34,112,56,50,145,76,146,6,29,107,57,58,56,84,35,85,34,83,36,86,59,55,18,115,116,82,33,114,17,117,19,37,87,113,60,54,81,118,152,7,151,153,158,198,159,121,199,200,243,157,122,197,160,89,244,201,242,245,291,156,123,120,90,290,246,196,161,241,202,61,292,119,91,293,162,163,161,203,125,204,124,202,126,205,123,164,160,92,249,248,93,250,91,201,247,206,127,122,94,251,165,159,297,64,90,298,166,165,167,208,128,207,129,209,127,206,164,168,95,253,254,130,96,210,252,94,126,255,205,97,163,169,251,302,131,66,67,303,170,169,171,212,132,213,131,211,133,172,168,214,258,98,99,130,259,257,210,134,97,260,100,256,215,173,167,307,69,129,308,209,217,218,216,263,174,175,264,262,173,176,219,215,265,313,136,312,135,314,261,137,311,172,134,315,177,266,214,220,366,102,138,367,179,178,180,222,140,223,139,221,141,181,177,269,105,268,224,106,220,138,142,270,267,104,107,225,182,176,271,319,219,75,318,266,226,225,227,273,183,182,272,274,184,181,224,228,271,323,143,324,144,322,275,142,325,185,145,321,180,270,229,223,377,108,141,376,187,186,188,231,147,230,148,232,146,185,189,229,278,112,111,149,277,279,233,145,113,276,110,280,228,184,190,329,81,150,328,234,191,192,190,235,151,236,150,234,152,237,193,189,115,283,282,149,114,233,284,116,153,281,238,113,194,188,285,334,148,84,83,333,195,194,196,240,154,239,155,241,153,238,156,193,197,118,287,288,117,286,119,242,289,237,152,157,116,285,192,198,339,86,120,338,399,400,456,344,457,517,458,345,398,401,455,292,518,516,459,581,519,293,343,346,397,580,520,342,294,402,454,244,582,515,460,583,403,402,404,461,348,462,347,460,349,405,401,463,522,296,523,346,295,459,521,350,297,524,294,464,406,400,345,247,520,587,586,248,407,406,408,465,352,466,351,464,353,467,350,409,405,527,299,526,300,528,298,463,525,354,468,301,349,529,404,410,591,297,251,250,411,410,412,470,355,469,356,471,354,468,357,409,413,531,303,532,302,530,304,472,533,353,301,467,358,529,408,414,254,596,595,305,416,415,417,475,360,474,361,476,359,414,418,537,307,473,536,308,362,477,538,358,306,535,309,539,472,413,419,258,601,602,305,363,420,421,419,479,364,480,363,478,365,422,418,541,311,481,542,310,362,477,540,312,366,543,309,539,423,417,482,606,313,261,262,605,424,423,425,483,368,484,367,482,369,485,422,426,366,546,314,545,315,547,481,313,544,370,316,486,365,421,427,265,548,610,611,264,428,427,429,487,488,371,372,486,489,370,373,426,430,318,550,549,551,317,319,485,490,369,374,548,552,316,320,425,431,268,615,614,432,431,433,492,375,491,376,493,374,490,430,434,377,554,322,555,321,553,494,323,556,373,320,489,378,429,435,271,552,620,619,272,436,435,437,496,379,495,380,497,378,434,438,559,325,494,558,326,381,498,560,324,377,557,327,561,433,439,493,624,323,275,274,625,440,439,441,500,383,501,382,499,384,438,442,563,329,502,564,328,381,498,562,385,330,565,327,561,503,443,437,278,629,628,331,380,445,446,444,505,388,506,387,504,389,507,386,447,443,569,333,568,334,570,332,503,567,390,335,508,385,571,442,448,282,634,635,331,449,448,450,510,391,509,392,511,390,508,393,447,451,573,337,574,336,572,338,512,575,389,507,335,394,571,446,452,639,339,285,286,453,452,454,514,395,513,396,515,394,451,455,512,578,340,577,397,341,516,579,393,339,576,342,511,450,456,398,289,580,643,644,288,648,649,716,582,717,787,718,647,583,650,715,518,788,719,786,789,860,581,519,646,584,790,859,580,520,651,714,457,861,785,720,862,652,651,653,721,586,585,722,720,587,650,654,792,522,723,584,521,793,719,791,523,588,794,520,790,655,649,724,865,583,461,460,866,657,656,658,726,591,590,727,725,592,589,728,655,659,526,798,797,527,724,525,799,796,528,593,588,729,654,660,465,871,870,800,524,661,660,662,730,594,595,731,729,593,732,596,663,659,530,802,801,531,529,803,728,800,592,733,597,532,528,804,664,658,875,468,469,665,664,666,598,734,735,599,597,733,736,663,667,806,534,600,533,805,807,535,596,732,737,532,804,808,601,662,668,472,879,536,880,670,669,671,603,740,739,604,602,741,738,668,672,811,538,539,812,605,601,810,537,742,540,813,737,667,673,809,885,476,477,884,606,674,673,675,607,744,743,606,608,745,672,676,742,542,816,815,605,543,541,609,746,817,814,544,741,540,677,671,480,889,604,890,818,678,679,677,748,611,610,747,749,612,680,676,609,546,820,746,819,545,750,547,821,613,818,544,608,822,681,675,745,548,894,484,483,683,684,682,753,615,616,754,752,614,617,685,681,825,550,551,755,751,826,824,549,552,613,618,827,823,686,680,488,899,756,750,900,687,688,686,757,619,620,758,756,618,685,689,621,554,829,759,830,555,755,553,828,617,831,556,622,827,684,690,760,552,903,491,492,691,692,690,623,761,762,624,622,760,693,689,763,558,833,834,625,557,559,621,759,832,835,556,764,560,694,688,495,908,626,907,831,695,694,696,627,765,766,626,628,764,767,693,697,838,562,561,837,625,629,839,563,763,560,836,768,692,698,840,912,499,498,913,624,700,699,701,632,771,770,631,633,772,769,698,702,843,566,630,567,844,842,565,634,773,768,568,845,841,629,697,703,503,918,564,917,704,705,703,775,636,635,774,776,637,773,634,706,702,570,847,848,569,571,846,777,849,638,772,633,568,572,845,707,701,922,507,506,708,709,707,779,639,640,778,780,638,641,777,710,706,574,851,852,573,781,575,850,853,572,637,642,776,711,705,510,926,927,849,576,713,714,712,784,644,645,783,785,643,715,711,857,578,782,646,579,856,786,858,577,642,855,580,859,716,710,781,932,647,514,515,931,936,937,1012,861,1013,1014,1091,862,935,938,1011,788,1092,1090,1015,1172,1093,789,860,863,934,1171,1094,790,859,1010,939,717,1173,1016,1089,1254,940,941,939,1017,865,1018,864,1016,866,942,938,1096,792,1019,1097,863,791,1015,1095,867,793,1098,790,1094,943,937,1020,1177,794,721,720,1178,945,946,944,1022,870,1023,869,1021,871,947,943,1024,868,1101,797,1102,796,1020,1100,872,1103,798,795,1025,867,948,942,725,1183,1182,726,1099,949,950,948,1026,874,1027,873,1025,875,1028,872,951,947,1106,800,1105,801,1107,799,1024,876,1104,802,1029,871,952,946,729,1187,1108,798,1186,953,954,952,1030,878,1031,877,1029,879,1032,876,955,951,1110,804,1109,805,1111,803,1028,880,1033,1108,875,806,1112,802,956,950,1191,733,732,957,958,956,1035,881,1034,882,1036,880,1033,883,959,955,1114,808,1115,807,1113,809,1037,879,1032,1116,884,806,1112,810,954,960,1195,736,1196,962,963,961,1040,886,1039,887,1041,885,1038,888,964,960,1119,813,1120,812,1118,814,1042,884,1121,811,1037,889,965,959,741,1201,1117,1200,815,966,965,967,1044,890,1043,891,1045,889,968,964,1042,1124,816,892,1123,817,1046,1125,888,815,1122,818,1041,893,963,969,1205,745,744,1126,1204,970,971,969,1048,894,1047,895,1049,893,972,968,1128,820,1046,1127,896,821,1050,1129,892,819,1126,822,1130,973,967,1045,1209,748,818,897,749,975,976,974,1053,899,1054,1052,898,900,977,973,1133,825,1055,1134,1051,1132,824,897,826,901,1135,1131,823,827,978,972,753,1215,1214,1056,1050,979,978,980,1057,903,1058,902,1056,904,977,981,1137,829,1059,1138,901,828,1055,1136,905,830,1139,827,1135,976,982,1060,1219,757,831,900,756,983,984,982,1061,907,1062,906,1060,908,985,981,1063,1141,833,905,1142,832,1059,1140,909,834,1143,831,1064,904,986,980,1223,760,761,1139,1224,987,986,988,1065,911,1066,910,1064,912,1067,909,985,989,1146,836,1145,837,1147,835,1063,913,1144,838,1068,908,984,990,764,1227,1148,1228,834,992,991,993,1070,916,1071,915,1069,917,1072,914,990,994,1151,841,1150,842,1152,840,1068,918,1073,1149,913,843,1153,839,989,995,1233,769,1232,996,997,995,1075,919,1074,920,1076,918,1073,921,994,998,1155,845,1156,844,1154,846,1077,917,1072,1157,922,843,1153,847,993,999,1237,772,773,1000,1001,999,1079,923,1078,924,1080,922,1077,925,998,1002,1159,849,1160,848,1158,850,1081,921,1161,847,1076,926,1003,997,776,1241,1157,851,1242,1004,1005,1003,1083,927,1082,928,1084,926,1006,1002,1081,929,1164,852,1163,853,1085,1165,925,1162,851,854,1080,930,1007,1001,780,1245,1246,779,1166,1009,1010,1008,1088,932,1087,933,1089,931,1011,1007,1169,857,1086,1168,934,858,1090,1170,930,856,1167,859,1171,1012,1006,1085,1251,855,784,785,1250,1255,1338,1256,1339,1173,1340,1423,1254,1174,1337,1257,1092,1424,1341,1422,1425,1509,1172,1093,1253,1175,1508,1426,1171,1094,1336,1258,1013,1510,1342,1421,1511,1259,1260,1258,1343,1177,1176,1344,1342,1178,1261,1257,1428,1096,1175,1345,1095,1429,1341,1427,1097,1179,1094,1430,1426,1098,1262,1256,1514,1017,1346,1174,1016,1263,1264,1262,1347,1181,1180,1348,1346,1182,1265,1261,1432,1100,1179,1099,1349,1433,1345,1431,1101,1183,1098,1434,1430,1266,1260,1178,1518,1350,1021,1020,1102,1268,1269,1267,1352,1186,1185,1353,1351,1187,1184,1270,1266,1437,1105,1104,1354,1438,1350,1436,1106,1188,1103,1439,1183,1271,1265,1355,1025,1524,1435,1523,1026,1272,1271,1273,1356,1190,1189,1357,1355,1191,1188,1270,1274,1358,1108,1441,1442,1109,1354,1440,1107,1443,1110,1192,1187,1359,1269,1275,1029,1528,1439,1527,1106,1276,1275,1277,1360,1193,1194,1361,1359,1192,1195,1274,1278,1362,1112,1446,1445,1113,1111,1358,1444,1447,1114,1191,1196,1363,1279,1273,1532,1033,1110,1032,1533,1280,1281,1279,1364,1197,1198,1365,1363,1196,1199,1366,1278,1282,1116,1450,1449,1117,1115,1451,1362,1448,1195,1118,1200,1367,1114,1277,1283,1536,1037,1036,1452,1284,1283,1285,1201,1368,1369,1202,1200,1367,1370,1203,1282,1286,1120,1454,1453,1119,1121,1455,1366,1199,1452,1371,1118,1122,1204,1287,1281,1040,1540,1456,1541,1289,1288,1290,1206,1373,1374,1207,1205,1372,1375,1287,1291,1459,1125,1208,1124,1458,1460,1126,1204,1371,1457,1123,1376,1461,1286,1292,1209,1127,1045,1546,1545,1293,1292,1294,1210,1377,1378,1211,1209,1376,1379,1291,1295,1463,1129,1128,1212,1462,1464,1208,1130,1127,1375,1380,1461,1465,1290,1296,1550,1049,1213,1048,1549,1297,1298,1296,1214,1382,1381,1215,1213,1383,1380,1295,1299,1467,1132,1133,1468,1466,1212,1216,1131,1134,1384,1379,1469,1465,1294,1300,1554,1053,1052,1553,1555,1301,1302,1300,1218,1386,1385,1217,1219,1387,1384,1303,1299,1471,1136,1137,1216,1472,1470,1220,1135,1138,1388,1383,1473,1469,1304,1298,1558,1056,1215,1057,1559,1305,1306,1304,1222,1390,1389,1221,1223,1391,1388,1307,1303,1475,1140,1220,1141,1476,1474,1139,1224,1392,1477,1142,1387,1473,1308,1302,1219,1138,1060,1562,1563,1310,1311,1309,1227,1395,1394,1226,1228,1396,1393,1225,1312,1308,1145,1480,1481,1146,1144,1479,1397,1229,1482,1392,1147,1143,1224,1313,1307,1065,1568,1478,1567,1314,1313,1315,1399,1231,1230,1398,1400,1232,1229,1397,1312,1316,1149,1484,1485,1148,1150,1483,1401,1486,1233,1147,1228,1396,1151,1311,1317,1572,1068,1069,1482,1318,1317,1319,1403,1234,1235,1402,1404,1233,1236,1316,1320,1401,1153,1488,1489,1152,1154,1405,1490,1487,1151,1232,1237,1400,1315,1321,1576,1072,1155,1073,1575,1322,1323,1321,1407,1238,1239,1406,1408,1237,1240,1324,1320,1405,1157,1493,1492,1156,1409,1494,1158,1491,1155,1236,1241,1404,1325,1319,1076,1580,1495,1581,1159,1326,1325,1327,1411,1242,1243,1410,1412,1241,1244,1328,1324,1497,1160,1161,1409,1496,1413,1498,1159,1240,1162,1495,1245,1329,1323,1408,1080,1584,1499,1585,1079,1331,1330,1332,1416,1247,1248,1415,1417,1246,1329,1333,1502,1165,1249,1166,1414,1501,1418,1503,1164,1245,1167,1500,1504,1328,1334,1250,1590,1413,1084,1085,1163,1335,1336,1334,1420,1251,1252,1419,1421,1250,1333,1337,1506,1169,1253,1418,1170,1505,1422,1507,1168,1249,1171,1504,1508,1167,1332,1338,1594,1088,1417,1254,1089,1687,1776,1688,1777,1598,1778,1867,1686,1599,1775,1689,1868,1510,1779,1866,1959,1869,1685,1600,1511,1597,1958,1870,1596,1512,1690,1774,1424,1960,1780,1865,2052,1691,1692,1690,1781,1602,1782,1601,1780,1603,1689,1693,1872,1514,1783,1873,1600,1513,1779,1871,1604,1515,1874,1512,1870,1516,1688,1694,1964,1428,1784,1427,1965,1696,1695,1697,1786,1607,1787,1606,1785,1608,1694,1698,1877,1519,1788,1605,1878,1518,1784,1876,1609,1520,1879,1517,1875,1521,1693,1699,1969,1433,1789,1432,1604,1700,1699,1701,1790,1611,1791,1610,1789,1612,1698,1702,1881,1523,1792,1609,1882,1522,1788,1613,1880,1524,1883,1521,1697,1703,1793,1879,1608,1973,1436,1525,1974,1704,1703,1705,1794,1615,1795,1614,1793,1616,1702,1706,1885,1527,1796,1613,1886,1526,1792,1617,1884,1528,1887,1525,1797,1612,1701,1707,1440,1978,1977,1883,1441,1708,1709,1707,1798,1619,1799,1618,1797,1620,1710,1706,1800,1617,1889,1531,1890,1530,1796,1621,1888,1532,1891,1529,1801,1616,1711,1705,1444,1982,1981,1887,1445,1713,1714,1712,1803,1624,1804,1623,1802,1625,1805,1622,1711,1715,1895,1535,1894,1536,1896,1534,1801,1626,1893,1537,1806,1621,1710,1716,1987,1449,1897,1986,1448,1717,1718,1716,1807,1628,1808,1627,1806,1629,1809,1626,1719,1715,1899,1539,1898,1540,1900,1538,1805,1630,1897,1541,1810,1625,1714,1720,1991,1453,1901,1452,1537,1721,1720,1722,1811,1632,1812,1631,1810,1633,1813,1630,1719,1723,1903,1543,1902,1544,1904,1542,1809,1634,1901,1545,1814,1629,1905,1718,1724,1995,1541,1456,1457,1726,1727,1725,1816,1637,1817,1636,1815,1638,1818,1635,1728,1724,1908,1548,1907,1549,1909,1547,1814,1639,1906,1819,1550,1634,1910,1546,1729,1723,1461,2000,2001,1730,1729,1731,1820,1641,1821,1640,1819,1642,1822,1639,1728,1732,1912,1552,1911,1553,1913,1551,1818,1643,1823,1638,1910,1554,1914,1550,1727,1733,1465,2004,2005,1734,1735,1733,1825,1644,1824,1645,1826,1643,1823,1646,1736,1732,1916,1556,1917,1555,1915,1557,1827,1642,1822,1647,1918,1554,1914,1558,1737,1731,1469,2009,2008,1738,1737,1739,1829,1648,1828,1649,1830,1647,1827,1650,1736,1740,1920,1560,1921,1559,1919,1561,1831,1646,1922,1826,1558,1651,1918,1562,1735,1741,1473,2013,2012,1743,1744,1742,1834,1653,1833,1654,1835,1652,1832,1655,1745,1741,1925,1565,1926,1564,1924,1566,1836,1651,1927,1563,1831,1656,1923,1746,1740,2018,1567,1478,1477,1747,1748,1746,1838,1657,1837,1658,1839,1656,1836,1659,1749,1745,1929,1569,1930,1568,1928,1570,1840,1655,1931,1567,1835,1660,1750,1744,2022,1481,1927,1482,1571,1751,1750,1752,1842,1661,1841,1662,1843,1660,1840,1663,1753,1749,1933,1573,1934,1572,1932,1574,1844,1659,1935,1571,1839,1664,1748,1754,2026,1485,1931,2027,1486,1756,1755,1757,1847,1666,1846,1667,1848,1665,1754,1758,1845,1668,1939,1577,1938,1578,1849,1664,1940,1576,1937,1579,1844,1669,1753,1759,1490,2031,2032,1941,1489,1760,1759,1761,1851,1670,1850,1671,1852,1669,1758,1762,1943,1581,1849,1672,1942,1582,1853,1668,1944,1580,1941,1583,1848,1673,1757,1763,1494,2035,2036,1945,1493,1764,1763,1765,1855,1674,1854,1675,1856,1673,1766,1762,1947,1585,1853,1676,1946,1586,1857,1672,1948,1584,1945,1587,1767,1761,1852,1949,1677,2040,1498,1583,2039,1768,1769,1767,1859,1678,1858,1679,1860,1677,1770,1766,1951,1589,1857,1680,1950,1590,1861,1952,1676,1588,1949,1591,1953,1587,1765,1771,2044,1501,1856,1502,1681,1773,1774,1772,1864,1683,1863,1684,1865,1682,1771,1775,1956,1594,1862,1955,1685,1595,1866,1957,1681,1593,1954,1596,1958,1592,1770,1776,2049,1506,1861,1507,2048,2053,2146,2054,2147,1960,2240,2148,2052,1961,2145,2055,1868,2241,2239,2149,2242,2335,2051,1962,1959,1869,2243,2334,1958,1870,2144,2056,1777,2336,2238,2150,2050,2057,2056,2058,2151,1964,1963,2152,2150,1965,2059,2055,2245,1872,1962,1871,2246,2149,2153,2244,1966,1873,1870,2247,2243,1874,2054,2060,2340,1781,1961,1780,2341,2062,2061,2063,2156,1969,1968,2155,2157,1970,2060,2064,2250,1877,1967,1876,2251,2154,2158,2249,1971,1878,1875,2252,2248,1879,2065,2059,2345,1786,1966,1785,2346,2066,2065,2067,2160,1973,1972,2159,2161,1974,2064,2068,2254,1881,1971,1880,2255,2158,2162,2253,1975,1882,1879,2256,2252,2063,2069,2349,1970,1790,1883,1789,2350,2070,2071,2069,2164,1977,1976,2165,2163,1978,2072,2068,2258,1885,1975,1884,2259,2166,2162,2257,1979,1886,1883,2260,2256,2067,2073,1974,2353,1793,1794,2354,1887,2074,2073,2075,2168,1981,1980,2167,2169,1982,2072,2076,2262,1979,1889,1888,2263,2166,2170,2261,1983,1890,1887,2264,1978,2260,2071,2077,1797,2357,2358,1798,2165,2079,2080,2078,2173,1986,1985,2174,2172,1987,2081,2077,1984,2267,1893,1894,2268,2175,2171,2266,1892,1988,1895,2269,1983,2082,2076,1802,2265,2363,2362,1803,2176,2083,2082,2084,2177,1990,1989,2176,2178,1991,1988,2081,2085,2271,1897,1898,2272,2179,2175,2270,1896,1992,1899,2273,1987,2080,2086,1806,2367,2269,2366,1895,2174,2087,2086,2088,2181,1994,1993,2180,2182,1995,1992,2089,2085,1901,2275,2276,1902,2183,2179,1900,2274,1996,2277,1903,1991,2090,2084,1810,2371,1899,2273,2370,1809,2091,2092,2090,2185,1998,1997,2186,2184,1999,1996,2089,2093,1905,2279,2280,1906,2183,2187,1904,2278,2281,2000,1907,1995,1903,2088,2094,2375,1814,2374,1813,2277,2096,2097,2095,2190,2003,2002,2191,2189,2004,2001,2098,2094,1910,2284,2285,1911,2192,2188,1909,2283,2286,2005,2000,1912,1908,2093,2099,2380,1819,1818,2379,2282,2100,2101,2099,2194,2007,2006,2195,2193,2008,2005,2102,2098,1914,2289,2288,2196,2192,1915,1913,2290,2287,2009,2004,1916,1912,2103,2097,2384,1823,1822,2197,2191,2104,2105,2103,2198,2010,2011,2199,2197,2009,2012,2106,2102,1918,2293,2292,1917,2200,2196,1919,2294,2291,2008,2013,1916,1920,2107,2101,2388,1826,1827,2389,2295,2109,2108,2110,2203,2015,2016,2202,2204,2014,2017,2111,2107,1923,2298,2297,1922,2205,2201,1924,2299,2296,2013,1921,2018,1925,2112,2106,2393,1831,2394,1832,2300,2113,2112,2114,2207,2019,2020,2206,2208,2018,2021,2111,2115,1927,2302,2301,1926,2205,2209,1928,2303,2017,2300,1925,2022,2110,2116,1835,2397,1929,2304,2398,1836,2117,2118,2116,2211,2023,2024,2212,2210,2022,2025,2119,2115,2306,1931,1930,2305,2213,2209,2307,1932,2021,1929,2304,2026,2120,2114,1839,2401,2308,2402,1933,2214,2121,2122,2120,2215,2027,2028,2216,2214,2026,2123,2119,2029,2310,1935,1934,2309,2217,2213,2311,1936,2025,1933,2308,2030,2124,2118,1843,2312,2405,2406,1842,2218,2126,2125,2127,2220,2032,2033,2219,2221,2031,2124,2128,2315,2034,1939,1940,2314,2218,2222,2316,2030,1938,1941,2313,2035,2317,2123,2129,1848,2411,2410,1847,2217,2130,2131,2129,2224,2036,2037,2225,2223,2035,2132,2128,2319,1943,2038,1944,2318,2226,2222,2320,2034,1942,1945,2317,2321,2133,2127,2039,2415,1852,1851,2414,1941,2134,2133,2135,2228,2040,2041,2227,2229,2039,2132,2136,2323,1947,2042,1948,2322,2226,2230,2324,2038,1946,1949,2321,2325,2131,2137,2419,2043,1855,1945,1856,2418,2138,2139,2137,2232,2044,2045,2233,2231,2043,2140,2136,2327,1951,2046,1952,2326,2234,2230,2328,2042,1950,1953,2325,2329,1949,2135,2141,2423,1859,2047,1860,2422,2143,2142,2144,2237,2049,2050,2236,2238,2048,2141,2145,2332,1956,2051,1957,2331,2235,2239,2333,2047,1955,1958,2330,2334,1954,2146,2140,2428,1864,2052,1865,2427,2432,2527,2433,2336,2528,2624,2529,2431,2337,2434,2526,2241,2625,2623,2530,2338,2430,2721,2626,2335,2242,2720,2627,2243,2334,2525,2435,2147,2722,2622,2531,2429,2436,2437,2435,2340,2532,2533,2339,2341,2531,2434,2438,2245,2629,2534,2630,2244,2338,2342,2628,2246,2530,2631,2243,2627,2247,2433,2439,2726,2151,2535,2727,2150,2440,2439,2441,2344,2536,2537,2343,2345,2535,2442,2438,2633,2249,2538,2634,2248,2342,2346,2632,2250,2534,2635,2247,2631,2251,2437,2443,2730,2155,2539,2731,2154,2445,2444,2446,2349,2541,2542,2348,2350,2540,2443,2447,2638,2254,2543,2639,2253,2347,2351,2637,2255,2539,2640,2252,2636,2256,2442,2448,2544,2735,2160,2736,2159,2449,2450,2448,2353,2545,2546,2352,2354,2544,2447,2451,2642,2258,2547,2643,2257,2351,2355,2641,2259,2543,2644,2256,2640,2260,2548,2446,2452,2739,2164,2740,2163,2453,2454,2452,2357,2549,2550,2358,2356,2548,2455,2451,2646,2262,2551,2647,2261,2359,2355,2645,2263,2547,2648,2260,2552,2644,2264,2456,2450,2743,2168,2744,2167,2457,2458,2456,2361,2553,2554,2362,2360,2552,2555,2455,2459,2650,2266,2651,2265,2359,2363,2649,2267,2551,2652,2264,2556,2454,2460,2648,2268,2748,2171,2747,2172,2461,2460,2462,2365,2557,2558,2364,2366,2556,2559,2463,2459,2654,2270,2655,2269,2367,2363,2653,2271,2555,2656,2268,2560,2464,2458,2752,2175,2652,2272,2751,2176,2465,2466,2464,2369,2561,2562,2370,2368,2560,2563,2467,2463,2658,2274,2659,2273,2371,2367,2657,2275,2559,2660,2272,2564,2468,2462,2756,2179,2656,2755,2180,2276,2470,2469,2471,2374,2566,2567,2373,2375,2565,2568,2468,2472,2663,2279,2664,2278,2372,2376,2662,2280,2665,2277,2564,2569,2467,2473,2761,2184,2760,2185,2661,2281,2474,2475,2473,2378,2570,2571,2379,2377,2569,2572,2476,2472,2667,2283,2668,2282,2380,2376,2666,2284,2669,2281,2568,2573,2477,2471,2765,2188,2764,2189,2665,2381,2478,2479,2477,2382,2574,2575,2383,2381,2573,2576,2476,2480,2671,2287,2672,2286,2380,2384,2670,2288,2673,2285,2572,2577,2475,2481,2769,2192,2768,2379,2385,2193,2482,2481,2483,2386,2579,2578,2385,2387,2580,2577,2480,2484,2676,2290,2675,2291,2388,2384,2677,2289,2674,2292,2581,2576,2485,2479,2773,2196,2774,2383,2389,2195,2486,2485,2487,2390,2583,2582,2389,2391,2584,2581,2484,2488,2680,2294,2679,2295,2388,2392,2681,2293,2678,2296,2585,2580,2483,2489,2777,2200,2778,2199,2682,2387,2490,2491,2489,2394,2587,2586,2395,2393,2588,2585,2492,2488,2684,2298,2683,2299,2396,2392,2685,2297,2682,2300,2589,2584,2493,2487,2781,2204,2782,2203,2686,2296,2495,2496,2494,2399,2592,2591,2400,2398,2593,2590,2497,2493,2689,2303,2688,2304,2401,2397,2690,2302,2594,2687,2305,2589,2492,2498,2786,2209,2691,2787,2208,2301,2499,2498,2500,2403,2596,2595,2402,2404,2597,2594,2501,2497,2693,2307,2692,2308,2405,2401,2694,2306,2598,2691,2309,2593,2502,2496,2790,2213,2695,2305,2791,2212,2503,2504,2502,2407,2600,2599,2408,2406,2601,2598,2501,2505,2697,2311,2696,2312,2405,2409,2698,2310,2602,2695,2313,2597,2506,2500,2699,2309,2794,2217,2795,2216,2507,2506,2508,2411,2604,2603,2410,2412,2605,2505,2509,2701,2315,2602,2700,2316,2409,2413,2702,2314,2606,2699,2317,2601,2703,2313,2510,2504,2799,2220,2798,2221,2511,2512,2510,2415,2608,2607,2416,2414,2609,2509,2513,2705,2319,2606,2704,2320,2413,2417,2706,2318,2610,2703,2321,2707,2317,2605,2514,2508,2803,2224,2802,2225,2515,2514,2516,2419,2612,2611,2418,2420,2613,2513,2517,2709,2323,2610,2708,2324,2417,2421,2710,2322,2614,2707,2325,2711,2321,2512,2518,2609,2807,2228,2806,2229,2520,2521,2519,2424,2617,2616,2425,2423,2618,2522,2518,2714,2328,2615,2713,2329,2426,2422,2715,2327,2619,2712,2330,2716,2326,2523,2517,2812,2233,2614,2811,2234,2524,2523,2525,2428,2621,2620,2427,2429,2622,2526,2522,2332,2718,2619,2717,2333,2430,2426,2719,2331,2623,2716,2334,2720,2330,2521,2527,2816,2237,2618,2815,2238,2820,2917,2821,2722,2918,2819,2723,3015,2919,2916,2822,2625,3016,2818,2724,3014,2920,3113,3017,2721,2626,3112,3018,2720,2627,2915,2823,3114,2528,2817,2725,3013,2824,2825,2823,2726,2922,2727,2725,2923,2921,2826,2822,3020,2629,2628,2728,2724,2924,2920,3019,3021,2630,2627,3022,3018,2631,2827,2821,3118,2532,2729,2723,3119,2829,2830,2828,2731,2927,2730,2732,2928,2926,2827,2831,3025,2634,2633,2729,2733,2925,2929,3026,3024,2635,2632,3027,3023,2636,2826,2832,3123,2537,3124,2536,2728,2833,2832,2834,2735,2931,2734,2736,2930,2932,2831,2835,3029,2638,2637,2733,2737,2929,2933,3028,3030,2639,2636,3027,3031,2640,2830,2836,3127,2541,3128,2540,2732,2837,2836,2838,2739,2935,2740,2738,2934,2936,2835,2839,3033,2642,2641,2737,2741,2933,2937,3032,3034,2643,2640,3031,3035,2644,2834,2840,3131,2545,3132,2544,2736,2841,2842,2840,2743,2939,2742,2744,2938,2940,2843,2839,3037,2646,2645,2745,2741,2937,2941,3038,3036,2647,2644,3039,3035,2838,2844,2648,3135,2549,3136,2548,2746,2846,2847,2845,2748,2944,2749,2747,2945,2943,2848,2844,3042,2651,2650,2750,2746,2946,2942,3043,3041,2652,2649,3044,3040,2849,2843,3140,2554,2653,3141,2553,2751,2850,2849,2851,2752,2948,2753,2751,2947,2949,2848,2852,3046,2655,2654,2750,2754,2950,2946,3045,3047,2656,2653,3044,3048,2847,2853,3144,2558,2657,3145,2557,2749,2854,2853,2855,2756,2952,2755,2757,2951,2953,2852,2856,3050,2659,2658,2754,2758,2950,2954,3049,3051,2660,2657,3048,3052,2851,2857,3148,2562,3149,2561,2661,2753,2858,2857,2859,2760,2956,2759,2761,2955,2957,2856,2860,3054,2663,2662,2758,2762,2954,2958,3055,3053,2664,2661,3052,3056,2855,2861,3152,2566,3153,2565,2665,2757,2863,2864,2862,2765,2961,2766,2764,2962,2960,2865,2861,3059,2668,2667,2767,2763,2963,2959,3058,3060,2669,2666,3061,3057,2860,2866,3157,2571,3158,2570,2762,2768,2867,2866,2868,2769,2965,2768,2770,2966,2964,2869,2865,3063,2672,2671,2771,2767,2967,2963,3062,3064,2673,2670,3065,3061,2870,2864,3161,2575,3162,2574,2772,2766,2871,2872,2870,2773,2969,2774,2772,2968,2970,2873,2869,3067,2675,2676,2775,2771,2971,2967,3068,3066,2674,2677,3069,3065,2874,2868,3166,2578,3165,2579,2776,2770,2875,2876,2874,2777,2973,2778,2776,2972,2974,2873,2877,3071,2679,2680,2775,2779,2971,2975,3070,3072,2678,2681,3069,3073,2872,2878,3170,2582,3169,2583,2774,2780,2880,2881,2879,2782,2978,2781,2783,2977,2979,2878,2882,3076,2684,2685,2780,2784,2976,2980,3077,3075,2683,2686,3074,3078,2877,2883,3175,2587,3174,2588,2682,2785,2884,2885,2883,2786,2982,2787,2785,2983,2981,2886,2882,3080,2688,2689,2788,2784,2984,2980,3081,3079,2687,2690,3082,3078,2887,2881,3179,2591,3178,2592,2686,2789,2888,2887,2889,2790,2986,2791,2789,2985,2987,2886,2890,3084,2692,2693,2788,2792,2984,2988,3083,3085,2691,2694,3082,3086,2885,2891,3183,2595,2690,3182,2596,2787,2892,2893,2891,2794,2990,2793,2795,2991,2989,2894,2890,3088,2696,2697,2796,2792,2992,2988,3089,3087,2695,2698,3090,3086,2895,2889,3187,2599,2694,3186,2600,2797,2897,2896,2898,2799,2995,2798,2800,2994,2996,2895,2899,3093,2701,2702,2797,2801,2993,2997,3092,3094,2700,2703,3091,3095,2894,2900,2699,3192,2604,3191,2605,2796,2901,2900,2902,2803,2999,2802,2804,2998,3000,2903,2899,3097,2705,2706,2805,2801,3001,2997,3096,3098,2704,2707,3099,3095,2703,2904,2898,3196,2608,3195,2609,2806,2905,2904,2906,3003,2807,2806,2808,3002,3004,2903,2907,3101,2709,2710,2805,2809,3005,3001,3102,3100,2708,2711,3103,3099,2707,2908,2902,3200,2612,3199,2613,2810,2909,2910,2908,2811,3007,2812,2810,3008,3006,2907,2911,3105,2713,2714,2809,2813,3005,3009,3106,3104,2712,2715,3103,3107,2711,2906,2912,3204,2616,3203,2617,2808,2914,2915,2913,3012,2816,2817,2815,3013,3011,2916,2912,3110,2718,2719,2818,2814,3014,3010,3109,3111,2717,2720,3112,3108,2716,2917,2911,3209,2621,2819,2813,3208,3312,3410,3313,3411,3213,3214,3311,3508,3412,3409,3314,3509,3114,3310,3215,3212,3115,3606,3510,3507,3413,3211,3116,3605,3511,3408,3315,3607,3016,3309,3216,3608,3316,3317,3315,3217,3415,3414,3218,3216,3416,3318,3314,3118,3513,3413,3512,3219,3215,3117,3119,3514,3417,3511,3120,3116,3515,3319,3313,3611,3020,3412,3214,3220,3321,3320,3322,3222,3420,3419,3221,3223,3421,3323,3319,3123,3518,3418,3517,3224,3220,3124,3122,3519,3422,3516,3125,3121,3520,3318,3324,3616,3025,3417,3615,3024,3325,3324,3326,3226,3424,3423,3227,3225,3425,3327,3323,3127,3522,3422,3521,3228,3224,3128,3126,3523,3426,3520,3129,3125,3524,3328,3322,3620,3029,3421,3619,3028,3329,3328,3330,3230,3428,3427,3229,3231,3429,3331,3327,3131,3526,3426,3525,3232,3228,3130,3132,3527,3430,3524,3133,3129,3528,3326,3332,3425,3624,3033,3623,3032,3334,3333,3335,3235,3433,3432,3234,3236,3434,3332,3336,3136,3531,3431,3530,3233,3237,3135,3137,3532,3435,3529,3134,3138,3430,3331,3337,3533,3629,3038,3628,3037,3338,3339,3337,3239,3437,3436,3240,3238,3438,3340,3336,3140,3435,3535,3534,3241,3237,3141,3139,3536,3439,3533,3142,3138,3434,3341,3335,3633,3042,3537,3632,3041,3342,3341,3343,3243,3441,3440,3242,3244,3442,3439,3340,3344,3144,3539,3538,3241,3245,3143,3145,3540,3443,3537,3142,3146,3438,3339,3345,3637,3046,3541,3636,3045,3346,3347,3345,3247,3445,3444,3248,3246,3446,3443,3348,3344,3148,3543,3542,3249,3245,3149,3147,3544,3447,3541,3150,3146,3442,3349,3343,3641,3050,3640,3049,3545,3351,3350,3352,3252,3450,3449,3251,3253,3451,3448,3349,3353,3153,3548,3547,3250,3254,3152,3154,3549,3546,3452,3447,3151,3155,3348,3354,3646,3055,3645,3054,3550,3355,3356,3354,3256,3454,3453,3257,3255,3455,3452,3357,3353,3157,3552,3551,3258,3254,3158,3156,3553,3550,3456,3451,3159,3155,3358,3352,3650,3059,3649,3058,3259,3359,3360,3358,3260,3458,3457,3259,3261,3459,3456,3357,3361,3161,3556,3555,3258,3262,3162,3160,3557,3554,3460,3455,3159,3163,3356,3362,3654,3063,3653,3062,3257,3364,3365,3363,3265,3462,3463,3266,3264,3461,3464,3366,3362,3166,3560,3561,3267,3263,3167,3165,3559,3562,3460,3465,3168,3164,3367,3361,3658,3067,3659,3068,3268,3368,3369,3367,3269,3466,3467,3270,3268,3465,3468,3370,3366,3170,3564,3565,3271,3267,3171,3169,3563,3566,3464,3469,3172,3168,3371,3365,3662,3071,3663,3072,3272,3372,3371,3373,3273,3470,3471,3274,3272,3469,3472,3374,3370,3174,3568,3569,3275,3271,3175,3173,3567,3570,3468,3473,3176,3172,3375,3369,3666,3075,3667,3076,3566,3377,3376,3378,3278,3475,3476,3277,3279,3474,3477,3375,3379,3179,3573,3574,3276,3280,3178,3180,3572,3473,3575,3177,3181,3478,3374,3380,3671,3080,3672,3081,3571,3381,3382,3380,3282,3479,3480,3283,3281,3478,3481,3383,3379,3183,3577,3578,3280,3284,3184,3182,3576,3477,3579,3185,3181,3482,3384,3378,3675,3084,3575,3676,3085,3385,3384,3386,3286,3483,3484,3285,3287,3482,3383,3387,3187,3485,3581,3582,3284,3288,3186,3188,3580,3481,3583,3185,3189,3486,3382,3388,3679,3088,3579,3680,3089,3389,3390,3388,3290,3487,3488,3291,3289,3486,3391,3387,3191,3585,3489,3586,3292,3288,3192,3190,3584,3485,3587,3193,3189,3490,3386,3392,3583,3683,3092,3684,3093,3394,3395,3393,3295,3492,3493,3296,3294,3491,3392,3396,3196,3590,3494,3591,3297,3293,3197,3195,3589,3490,3592,3198,3194,3588,3397,3391,3495,3688,3097,3689,3098,3398,3397,3399,3299,3496,3497,3298,3300,3495,3400,3396,3200,3594,3498,3595,3301,3297,3201,3199,3593,3494,3596,3202,3198,3592,3401,3395,3692,3101,3499,3693,3102,3402,3401,3403,3303,3500,3501,3302,3304,3499,3400,3404,3204,3598,3502,3599,3301,3305,3203,3205,3597,3498,3600,3202,3206,3596,3399,3405,3696,3105,3503,3697,3106,3407,3408,3406,3308,3505,3506,3309,3307,3504,3409,3405,3209,3603,3507,3604,3310,3306,3210,3208,3602,3503,3605,3211,3207,3601,3410,3404,3701,3110,3508,3311,3305,3705,3802,3706,3803,3607,3704,3608,3899,3804,3801,3707,3900,3509,3703,3609,3606,3510,3898,3805,3995,3901,3605,3511,3994,3902,3800,3708,3996,3411,3702,3610,3897,3709,3708,3710,3611,3807,3806,3610,3612,3808,3711,3707,3513,3904,3805,3903,3609,3613,3512,3514,3809,3905,3902,3515,3511,3906,3706,3712,3415,4000,3804,3999,3608,3714,3713,3715,3616,3812,3811,3615,3617,3813,3712,3716,3518,3909,3810,3908,3614,3618,3519,3517,3814,3910,3907,3516,3520,3911,3717,3711,3420,4005,3809,4004,3619,3718,3717,3719,3620,3816,3815,3619,3621,3817,3716,3720,3522,3913,3814,3912,3618,3622,3523,3521,3818,3914,3911,3524,3520,3715,3721,3424,4009,3915,3813,4008,3617,3722,3721,3723,3624,3820,3819,3623,3625,3821,3720,3724,3526,3917,3818,3916,3622,3626,3525,3527,3822,3918,3915,3524,3528,3719,3725,3817,3428,4013,4012,3919,3621,3726,3727,3725,3628,3824,3823,3629,3627,3825,3728,3724,3530,3822,3921,3920,3630,3626,3531,3529,3826,3922,3919,3532,3528,3821,3723,3729,3432,4017,4016,3631,3625,3731,3732,3730,3633,3829,3828,3634,3632,3830,3733,3729,3535,3827,3925,3926,3635,3631,3536,3534,3831,3924,3927,3537,3533,3826,3734,3728,3437,4021,4022,3636,3630,3735,3734,3736,3637,3833,3832,3636,3638,3834,3831,3733,3737,3539,3929,3930,3635,3639,3540,3538,3928,3835,3931,3541,3537,3830,3732,3738,3441,4025,4026,3927,3634,3739,3738,3740,3641,3837,3836,3640,3642,3838,3835,3737,3741,3543,3933,3934,3639,3643,3544,3542,3932,3839,3935,3541,3545,3834,3736,3742,3445,4029,3931,4030,3638,3743,3742,3744,3645,3841,3840,3644,3646,3842,3839,3741,3745,3547,3937,3938,3643,3647,3546,3548,3936,3843,3939,3838,3545,3549,3740,3746,3449,3935,4033,4034,3642,3748,3747,3749,3650,3846,3845,3649,3651,3847,3844,3750,3746,3552,3942,3943,3652,3648,3553,3551,3941,3848,3843,3944,3554,3550,3940,3745,3751,3454,4038,4039,3647,3752,3751,3753,3654,3850,3849,3653,3655,3851,3848,3754,3750,3556,3946,3947,3656,3652,3555,3557,3945,3852,3847,3948,3554,3558,3944,3755,3749,3458,4042,3657,3651,3756,3757,3755,3658,3853,3854,3659,3657,3852,3855,3758,3754,3560,3950,3949,3660,3656,3561,3559,3951,3851,3856,3948,3562,3558,3952,3759,3753,3462,4046,3661,3655,3760,3761,3759,3662,3857,3858,3663,3661,3856,3859,3758,3762,3564,3954,3953,3660,3664,3565,3563,3955,3855,3860,3952,3562,3566,3956,3757,3763,3466,4050,4049,3659,3765,3764,3766,3667,3862,3863,3666,3668,3861,3864,3763,3767,3569,3959,3958,3665,3669,3568,3570,3960,3860,3957,3865,3567,3571,3762,3768,3471,3961,4055,4054,3664,3769,3770,3768,3671,3866,3867,3672,3670,3865,3868,3771,3767,3573,3963,3962,3673,3669,3574,3572,3964,3864,3961,3571,3575,3869,3772,3766,3475,4059,3965,4058,3674,3773,3772,3774,3675,3870,3871,3676,3674,3869,3872,3771,3775,3577,3967,3966,3673,3677,3578,3576,3968,3868,3965,3575,3579,3873,3770,3776,3479,4063,4062,3969,3672,3777,3776,3778,3679,3874,3875,3680,3678,3873,3779,3775,3581,3876,3971,3970,3681,3677,3582,3580,3872,3972,3969,3579,3583,3877,3780,3774,3483,4067,4066,3682,3676,3782,3781,3783,3684,3879,3880,3683,3685,3878,3780,3784,3586,3881,3975,3976,3682,3686,3585,3587,3877,3974,3977,3588,3584,3882,3779,3785,3488,4071,4072,3681,3687,3786,3785,3787,3688,3883,3884,3687,3689,3882,3788,3784,3590,3979,3885,3980,3690,3686,3591,3589,3881,3978,3981,3592,3588,3789,3783,3886,3492,4075,4076,3977,3691,3790,3791,3789,3692,3887,3888,3691,3693,3886,3792,3788,3594,3983,3889,3984,3694,3690,3595,3593,3885,3982,3985,3596,3592,3793,3787,3496,4079,3981,3890,4080,3695,3794,3793,3795,3696,3891,3892,3695,3697,3890,3792,3796,3598,3987,3893,3988,3694,3698,3599,3597,3889,3986,3989,3596,3600,3985,3791,3797,3500,4083,3894,4084,3693,3799,3798,3800,3701,3896,3897,3702,3700,3895,3801,3797,3603,3992,3898,3993,3703,3699,3604,3602,3894,3991,3994,3605,3601,3990,3796,3802,3505,4088,3899,4089,3704,4092,-1,4093,4186,3996,-1,-1,4091,3997,-1,-1,-1,-1,4094,4185,3900,-1,3998,4090,3995,3901,-1,-1,-1,-1,-1,-1,3902,3994,-1,4095,4184,4096,4095,4097,4000,-1,-1,4001,3999,-1,-1,-1,-1,4094,4098,3904,4002,3905,-1,3998,3903,-1,-1,-1,-1,-1,3906,-1,3902,-1,-1,4093,4099,4100,-1,4099,4101,4004,-1,-1,4005,4003,-1,-1,4098,4102,3908,-1,-1,-1,4006,3909,3907,4002,-1,-1,-1,-1,3910,-1,-1,-1,3906,4097,4103,4104,4103,4105,-1,4008,-1,4009,4007,-1,-1,-1,-1,4106,4102,3912,4010,3913,-1,-1,3911,-1,4006,-1,-1,3914,-1,-1,3910,-1,-1,4107,4101,4109,-1,4108,4110,4013,-1,4014,-1,4012,-1,-1,-1,4107,4111,3917,4015,-1,3918,-1,3916,-1,4011,-1,3919,-1,-1,-1,-1,3915,4016,-1,4106,4113,-1,4114,4112,4017,-1,4018,-1,4016,-1,-1,-1,4115,4111,3921,4019,-1,-1,3922,3920,4015,-1,-1,-1,3923,-1,-1,-1,-1,4020,3919,4116,4117,4116,4118,-1,4021,-1,4022,-1,4020,-1,-1,-1,4023,4115,4119,3925,3926,-1,-1,-1,3924,4019,-1,3927,-1,-1,-1,4024,-1,-1,4114,4120,4121,-1,4122,4120,4025,4026,-1,-1,4024,-1,-1,4027,4119,4123,-1,3929,-1,-1,3930,3928,-1,4023,-1,3931,-1,-1,-1,-1,4028,-1,4118,4124,4125,4124,4126,-1,-1,4029,4030,-1,-1,4028,-1,-1,4031,4123,4127,3933,3934,-1,-1,-1,-1,3932,4027,3935,-1,-1,4032,-1,-1,-1,4122,4128,4129,-1,4130,4128,4033,4034,-1,-1,4032,-1,4035,-1,-1,4127,4131,-1,-1,3937,3938,3936,-1,-1,3939,4031,-1,4036,-1,-1,-1,-1,4126,4132,4133,4132,4134,-1,-1,4037,4038,-1,-1,4036,4039,-1,-1,4135,4131,3941,3942,-1,-1,-1,-1,3940,3943,4035,-1,4040,-1,-1,-1,-1,4136,4130,4137,-1,4136,4138,4041,4042,-1,-1,4040,4043,-1,-1,4135,4139,-1,-1,3945,3946,-1,3944,-1,3947,-1,4039,4044,-1,-1,-1,-1,-1,4134,4140,4142,-1,4141,4143,4047,4046,-1,-1,4048,-1,4045,-1,-1,4140,4144,3951,3950,-1,-1,-1,3952,3949,-1,4049,-1,4044,-1,-1,-1,-1,4139,4145,4146,-1,4147,4145,4051,-1,4050,-1,4052,-1,4049,-1,-1,4148,4144,3955,3954,-1,-1,-1,3956,-1,3953,4053,-1,-1,4048,-1,-1,-1,4143,4149,4150,-1,4151,4149,4055,4054,-1,-1,4056,-1,-1,4053,-1,4152,4148,3959,3958,-1,-1,3960,-1,3957,4057,-1,-1,-1,4052,-1,-1,-1,4153,4147,4154,4155,4153,-1,4059,-1,4058,-1,4060,-1,-1,4057,-1,4156,4152,3963,3962,-1,-1,-1,3964,-1,4061,3961,-1,-1,-1,4056,-1,-1,4157,4151,4158,-1,4157,4159,4063,4062,-1,-1,4064,-1,-1,4061,4156,4160,-1,3967,-1,-1,3966,3968,-1,4065,-1,3965,-1,-1,-1,-1,4060,-1,4155,4161,4162,4163,4161,-1,4067,-1,4066,-1,4068,-1,-1,-1,4065,4164,4160,3971,3970,-1,-1,-1,3972,-1,4069,3969,-1,-1,-1,-1,4064,-1,4165,4159,4166,-1,4165,4167,4071,4070,-1,-1,4072,-1,-1,-1,4164,4168,3975,4069,-1,-1,3974,3976,4073,-1,-1,3973,-1,-1,-1,-1,-1,4068,3977,4163,4170,4169,4171,4075,-1,-1,4074,4076,-1,-1,-1,-1,4168,4172,3979,4073,3978,-1,-1,3980,-1,4077,-1,3977,-1,-1,-1,-1,3981,4072,-1,4167,4175,-1,4176,4174,4080,-1,4079,-1,4081,-1,-1,-1,4177,4173,3984,4078,-1,-1,3983,3985,4082,-1,-1,-1,-1,3982,-1,-1,3986,-1,4178,4172,4179,-1,4178,4180,4084,-1,4083,-1,4085,-1,-1,-1,4177,4181,3988,-1,4082,-1,3987,3989,4086,-1,-1,-1,-1,3986,-1,3990,-1,-1,4182,4176,4183,-1,4184,4182,4088,-1,4087,4089,-1,-1,-1,-1,4185,4181,3992,-1,4086,3991,-1,4090,3993,-1,-1,-1,-1,-1,3990,3994,-1,-1,4186,4180],"visual":[0,7,4,2,1,3,6,5,9,10,16,15,8,18,19,17,11,12,13,14,31,20,21,22,23,24,25,26,27,28,29,30,38,61,60,39,20,88,62,21,37,89,59,40,63,87,120,90,8,22,36,19,9,91,119,64,86,41,58,1,121,157,122,118,42,66,41,65,43,23,67,24,22,64,40,94,95,10,44,93,68,96,25,21,9,11,63,39,92,2,127,97,45,128,69,126,46,45,70,71,26,47,69,27,25,44,72,100,99,12,101,68,48,98,28,24,13,11,73,43,102,3,133,97,134,67,4,49,50,49,75,29,74,76,48,51,30,28,105,73,77,106,104,14,31,27,52,47,15,13,107,103,78,72,139,140,4,5,108,102,53,54,80,79,32,52,81,33,31,55,78,110,111,16,109,82,51,112,34,30,15,17,77,56,108,6,146,113,145,83,5,50,57,84,58,85,56,35,83,36,34,86,59,116,115,18,55,117,82,114,33,37,17,19,87,60,118,7,152,113,54,151,81,153,158,199,198,159,200,243,121,244,157,122,245,291,201,242,197,160,89,156,123,290,246,120,90,292,293,343,241,202,196,161,91,119,162,204,203,163,161,125,202,205,124,249,248,126,164,250,160,123,92,247,93,201,206,91,251,127,297,298,165,296,94,122,159,64,166,208,167,209,207,165,128,129,254,253,168,127,206,210,255,130,164,252,95,96,94,302,126,169,303,256,97,205,211,131,251,301,170,212,213,171,169,132,211,214,258,133,259,172,131,257,260,168,99,134,98,215,210,130,173,100,308,307,256,97,261,309,306,69,217,174,175,218,216,136,173,135,263,176,264,137,262,219,215,134,102,265,172,101,177,138,103,261,313,312,220,214,314,100,133,72,178,179,222,221,139,140,177,180,220,223,268,267,269,141,138,105,224,219,176,181,266,270,104,106,318,137,142,319,317,103,107,75,226,183,182,227,225,143,184,144,273,181,272,142,274,228,224,145,108,271,185,109,180,141,107,275,323,324,229,223,322,110,146,78,187,231,230,186,188,147,229,232,278,146,277,185,148,279,276,189,111,145,112,228,233,149,184,110,328,329,280,113,275,327,330,81,191,235,190,234,236,192,151,150,282,283,189,152,237,233,281,149,193,284,115,114,116,334,153,188,333,280,113,238,232,148,285,335,195,240,239,194,196,154,241,238,155,287,288,153,193,286,197,156,118,289,117,242,237,119,285,152,339,338,192,340,116,157,198,86,399,344,400,456,398,345,457,292,517,458,293,343,455,401,397,346,516,459,518,244,294,342,581,519,245,291,402,454,347,396,580,520,403,348,404,347,402,349,461,462,296,295,405,460,346,297,463,401,350,294,523,247,522,248,459,298,406,524,246,521,249,464,345,351,407,352,408,351,406,353,466,465,299,300,409,467,350,298,464,354,301,405,527,251,528,250,468,410,526,252,297,349,302,463,529,249,411,412,356,355,470,357,410,413,303,471,469,304,354,302,358,472,409,305,468,532,254,414,531,255,301,533,253,353,530,256,473,306,416,415,360,359,474,361,417,475,414,307,306,358,473,308,476,362,418,305,536,258,413,537,257,309,357,472,535,259,477,538,256,304,420,364,419,363,421,479,365,478,311,310,418,362,480,312,477,309,422,366,541,261,481,540,262,361,417,542,260,313,308,476,539,263,424,368,367,423,425,483,369,484,314,366,315,482,422,313,426,485,316,370,545,481,265,546,264,365,312,421,544,266,547,263,317,427,428,372,371,429,427,487,488,318,373,370,317,319,430,426,486,489,550,268,316,320,374,369,549,551,267,269,490,485,431,425,548,552,432,375,376,433,431,492,374,491,322,377,321,493,434,323,430,490,320,373,555,494,271,554,272,378,324,435,556,270,553,273,319,429,436,379,437,380,435,496,378,497,325,326,438,381,495,324,498,327,434,377,559,275,494,560,274,382,439,558,276,323,328,499,561,273,440,441,383,384,501,382,439,500,442,329,330,385,502,328,499,381,438,331,564,278,443,563,279,327,386,503,565,277,498,562,280,332,445,444,387,388,505,386,446,443,333,504,506,332,389,334,385,503,447,331,507,568,282,442,569,281,335,567,283,390,570,280,502,330,449,391,448,392,450,390,509,510,337,336,447,508,393,338,511,389,335,451,573,285,572,286,507,446,574,284,339,394,334,512,571,287,453,395,452,396,454,394,514,513,340,341,451,515,397,339,512,455,393,342,577,289,578,288,516,338,450,576,290,579,287,511,398,392,648,582,649,716,717,647,583,787,718,518,650,715,581,519,584,646,788,786,719,789,860,520,580,457,517,458,651,714,859,790,645,585,652,653,586,721,587,722,651,585,654,522,720,723,588,521,523,793,584,792,650,794,655,520,524,719,461,791,724,460,462,589,583,459,657,656,590,726,591,658,725,589,727,655,526,592,525,527,724,797,659,798,588,728,796,654,524,528,465,464,593,799,466,723,795,463,661,660,594,662,595,730,731,593,729,530,596,659,732,663,531,529,802,801,592,728,803,528,532,468,597,469,800,658,733,664,467,470,665,666,599,598,735,664,734,736,600,597,667,534,533,535,733,806,663,807,737,805,596,601,532,536,472,668,473,808,471,732,474,804,670,669,603,602,739,740,671,668,604,738,538,601,537,539,741,811,810,672,737,605,812,667,536,540,476,600,477,809,475,742,813,478,674,673,607,675,606,744,743,608,745,542,672,605,742,543,541,676,815,816,609,814,746,544,540,480,817,479,671,604,741,481,677,478,678,679,611,748,677,610,612,749,747,680,546,609,545,547,676,820,750,613,746,819,821,548,544,484,483,681,818,608,485,822,675,482,683,682,615,753,752,616,614,684,681,550,751,754,549,551,617,613,825,824,685,680,548,552,826,823,487,488,750,755,486,489,618,612,687,686,619,757,688,620,618,756,758,685,554,621,553,555,689,829,755,617,759,830,828,556,552,491,492,684,831,622,490,827,690,493,691,692,623,690,624,761,762,622,760,558,693,625,763,557,559,689,834,833,621,835,759,560,556,495,832,496,694,626,764,494,688,497,695,696,627,628,766,765,694,697,626,767,562,629,563,561,764,838,839,693,768,625,837,698,564,560,499,630,498,840,500,763,836,497,700,699,631,632,770,701,771,769,630,633,698,566,565,567,772,843,702,842,768,844,634,629,568,564,503,697,502,841,504,773,501,845,704,705,636,703,635,775,774,637,776,570,634,706,773,702,571,569,847,848,638,777,846,572,568,507,633,506,849,707,772,701,508,505,708,709,640,779,639,707,780,641,778,710,574,638,575,573,781,852,706,851,642,777,853,711,576,572,510,511,637,850,509,782,854,512,713,712,644,784,643,783,714,645,711,578,785,782,642,579,577,856,646,857,715,855,710,580,576,786,514,858,781,515,513,641,647,516,936,1013,937,1012,861,1014,1091,935,862,1092,938,1011,788,1090,1015,1172,1093,789,860,863,934,790,859,1171,1094,717,1010,939,787,718,1173,864,940,941,1017,1018,865,939,866,864,1016,942,1019,1097,1096,792,867,793,938,791,863,1095,1098,1015,943,794,1020,790,721,868,720,722,1178,1177,945,944,1022,869,1021,870,946,1023,943,868,1101,871,1020,796,797,1100,1102,795,1024,947,867,942,798,1099,1103,872,794,725,1019,724,726,1182,949,948,1026,950,1027,874,873,1025,947,875,872,1106,1105,800,1028,951,801,799,1024,1107,1104,876,871,802,946,729,798,1029,728,730,1187,952,953,954,1031,1030,952,878,877,1032,879,1029,955,1110,876,804,951,805,1109,1111,803,880,1033,806,1028,1108,1112,875,956,733,802,732,950,1191,957,958,1035,882,1034,1036,881,956,883,959,1114,1115,808,880,1033,809,1037,807,955,884,1113,1116,960,810,737,736,879,806,1032,1196,738,1038,962,961,1039,1040,886,963,887,885,1038,960,1041,1119,812,813,1118,1120,888,884,964,811,1037,814,959,1042,1117,1121,741,740,810,1200,889,883,966,1044,965,967,890,1043,891,1045,889,964,1042,1124,1123,968,816,817,892,888,815,1046,1122,1125,818,1041,745,963,744,893,969,814,1205,746,970,971,1048,894,969,1049,895,1047,893,972,1128,896,820,1050,821,1129,1127,968,1046,819,822,892,973,1130,1126,897,749,748,1051,818,1209,1210,975,974,1052,1053,898,899,973,976,1051,1054,897,900,1132,1133,825,824,1131,1134,972,977,826,823,1050,1055,896,901,752,753,1214,827,822,1130,979,978,1057,903,980,1056,902,1058,904,977,1137,901,829,1055,828,1136,1138,981,1059,830,827,905,976,1135,1139,900,756,757,1054,831,1219,1218,983,1061,984,982,907,1062,906,1060,908,985,1063,1142,1141,981,833,832,905,909,834,1059,1140,1143,831,1064,760,986,761,904,980,835,1223,759,987,988,1066,1065,911,986,910,912,1067,989,1064,1146,837,836,1145,1147,913,909,985,838,1068,835,990,1063,1144,1148,764,765,839,1228,914,908,992,991,1070,915,1071,1069,916,993,914,990,1150,1151,841,917,1072,840,1068,842,994,913,1149,1152,989,839,768,769,918,843,1073,1232,767,1067,996,995,1074,1075,997,919,920,1073,918,1076,994,1155,921,845,998,844,1154,1156,846,917,1072,843,1077,1153,1157,922,993,772,847,773,999,1237,1000,1001,1079,999,1078,924,923,1080,1002,922,925,1159,1160,849,1077,998,848,850,1081,1161,1158,921,926,847,1003,776,851,1076,777,775,1241,997,1004,1005,1083,928,1084,927,1003,1082,1006,929,1164,926,1085,853,852,1163,1165,854,1081,1002,930,1007,851,1162,1166,925,855,780,1086,781,779,1246,1009,1008,1088,1087,932,1010,931,933,1089,1007,1086,1169,1168,857,930,856,1011,858,934,1167,1170,1090,1006,855,1085,859,784,929,785,783,1250,1251,1255,1339,1338,1256,1340,1423,1173,1174,1254,1424,1425,1509,1257,1337,1341,1422,1092,1175,1253,1172,1093,1508,1426,1510,1171,1094,1258,1336,1511,1597,1013,1342,1259,1343,1260,1344,1258,1177,1342,1178,1176,1428,1261,1429,1345,1427,1257,1096,1179,1341,1097,1175,1095,1430,1262,1346,1514,1515,1098,1426,1094,1017,1180,1256,1263,1264,1347,1348,1181,1262,1182,1265,1346,1349,1433,1180,1432,1183,1434,1100,1431,1101,1261,1099,1179,1266,1350,1345,1519,1102,1518,1098,1435,1184,1021,1520,1268,1352,1267,1351,1185,1353,1269,1186,1266,1437,1184,1350,1436,1438,1187,1104,1354,1105,1270,1103,1265,1435,1183,1439,1523,1106,1349,1188,1524,1102,1025,1522,1272,1356,1271,1357,1355,1273,1189,1190,1441,1270,1442,1188,1191,1440,1354,1358,1274,1108,1109,1107,1443,1187,1269,1110,1439,1192,1528,1527,1106,1029,1353,1359,1276,1360,1361,1277,1275,1359,1194,1193,1446,1445,1362,1192,1195,1274,1278,1112,1444,1447,1113,1358,1111,1191,1196,1114,1532,1363,1279,1273,1533,1531,1110,1033,1280,1365,1364,1281,1279,1198,1197,1366,1363,1450,1282,1449,1199,1196,1451,1278,1116,1117,1448,1115,1362,1367,1200,1118,1283,1452,1195,1536,1537,1037,1114,1036,1284,1369,1285,1368,1202,1370,1283,1201,1286,1454,1203,1367,1455,1453,1200,1120,1121,1371,1282,1119,1287,1456,1204,1122,1452,1541,1366,1199,1540,1542,1041,1040,1289,1373,1288,1374,1372,1206,1290,1205,1287,1458,1207,1459,1375,1371,1204,1457,1124,1125,1460,1291,1208,1286,1123,1126,1545,1546,1456,1203,1376,1370,1544,1045,1293,1377,1292,1378,1294,1210,1376,1209,1211,1463,1291,1462,1379,1464,1295,1128,1208,1129,1375,1212,1461,1127,1130,1290,1380,1550,1549,1465,1049,1207,1048,1296,1297,1382,1381,1296,1298,1214,1383,1380,1215,1213,1467,1466,1468,1295,1299,1132,1133,1212,1216,1384,1379,1131,1134,1465,1469,1554,1294,1300,1553,1555,1052,1053,1301,1386,1302,1385,1300,1218,1387,1219,1217,1471,1303,1472,1384,1470,1299,1137,1220,1136,1388,1216,1473,1138,1135,1304,1383,1558,1559,1469,1056,1221,1057,1298,1305,1390,1306,1391,1389,1222,1304,1223,1307,1476,1221,1475,1392,1388,1224,1477,1141,1140,1474,1303,1220,1308,1142,1139,1563,1562,1478,1225,1393,1387,1564,1060,1310,1394,1309,1395,1226,1393,1311,1227,1308,1480,1225,1396,1479,1481,1228,1145,1144,1392,1312,1146,1307,1478,1224,1143,1482,1567,1397,1229,1568,1566,1064,1065,1314,1399,1398,1313,1315,1230,1231,1397,1400,1484,1312,1485,1229,1232,1483,1316,1149,1148,1486,1150,1396,1401,1228,1147,1311,1482,1233,1572,1571,1068,1151,1069,1318,1403,1402,1317,1319,1404,1234,1235,1488,1489,1401,1233,1236,1316,1320,1153,1490,1487,1152,1405,1154,1232,1237,1151,1576,1400,1315,1321,1577,1575,1155,1072,1322,1407,1323,1408,1406,1321,1239,1238,1493,1324,1492,1240,1237,1494,1409,1405,1320,1157,1156,1158,1491,1241,1325,1155,1495,1236,1580,1581,1159,1076,1410,1404,1326,1411,1327,1412,1243,1410,1325,1242,1328,1497,1244,1413,1498,1496,1241,1161,1409,1160,1324,1162,1329,1499,1245,1495,1585,1159,1414,1240,1584,1163,1080,1586,1331,1330,1416,1415,1247,1332,1246,1329,1417,1414,1501,1248,1502,1245,1500,1165,1503,1164,1333,1166,1249,1328,1418,1413,1589,1163,1590,1167,1499,1244,1084,1588,1335,1420,1334,1419,1336,1251,1421,1250,1252,1506,1333,1505,1418,1507,1337,1169,1249,1422,1168,1253,1170,1504,1332,1417,1594,1593,1167,1508,1171,1088,1248,1338,1687,1598,1688,1776,1599,1686,1777,1510,1867,1778,1597,1511,1689,1775,1685,1600,1424,1512,1596,1779,1866,1868,1425,1509,1959,1869,1684,1601,1690,1774,1508,1426,1691,1602,1692,1603,1690,1601,1781,1514,1782,1515,1693,1604,1513,1780,1783,1600,1516,1689,1428,1429,1872,1512,1873,1427,1694,1605,1779,1871,1430,1874,1784,1517,1696,1695,1606,1607,1786,1697,1605,1518,1785,1608,1694,1519,1787,1517,1520,1784,1432,1698,1604,1433,1609,1877,1693,1431,1876,1516,1788,1878,1521,1434,1783,1875,1700,1611,1610,1699,1701,1612,1790,1523,1522,1791,1789,1609,1698,1524,1521,1702,1613,1436,1792,1788,1437,1881,1882,1435,1608,1525,1880,1697,1520,1438,1703,1883,1704,1615,1705,1614,1616,1703,1794,1527,1795,1526,1706,1528,1793,1613,1617,1702,1796,1525,1440,1441,1886,1885,1529,1439,1792,1442,1707,1612,1887,1884,1618,1524,1708,1619,1709,1620,1618,1799,1707,1531,1798,1710,1530,1532,1621,1800,1617,1797,1529,1444,1706,1445,1533,1890,1711,1889,1443,1801,1891,1622,1446,1796,1616,1528,1713,1623,1712,1624,1714,1803,1622,1535,1625,1536,1711,1802,1804,1534,1715,1537,1621,1449,1448,1805,1801,1533,1894,1626,1895,1710,1450,1447,1893,1896,1538,1363,1717,1628,1627,1718,1716,1629,1807,1539,1808,1540,1626,1806,1538,1719,1715,1541,1809,1630,1453,1452,1899,1898,1625,1537,1454,1805,1451,1900,1542,1714,1720,1810,1721,1632,1722,1631,1633,1720,1812,1811,1544,1543,1723,1630,1813,1545,1542,1634,1810,1719,1457,1456,1903,1458,1904,1724,1902,1814,1546,1541,1629,1455,1635,1809,1726,1636,1725,1637,1635,1816,1727,1548,1724,1547,1815,1817,1638,1549,1634,1546,1461,1728,1818,1814,1460,1907,1723,1908,1462,1550,1639,1906,1459,1545,1909,1633,1730,1640,1641,1729,1731,1820,1639,1552,1821,1642,1551,1553,1728,1819,1732,1822,1550,1638,1465,1554,1912,1464,1466,1643,1911,1818,1913,1727,1463,1823,1467,1549,1734,1645,1644,1735,1733,1825,1646,1556,1824,1643,1557,1555,1736,1826,1732,1823,1558,1647,1469,1554,1916,1470,1468,1642,1917,1827,1915,1737,1471,1822,1467,1559,1738,1649,1739,1648,1650,1829,1737,1560,1740,1561,1830,1828,1647,1559,1651,1562,1473,1736,1831,1827,1474,1921,1741,1920,1472,1558,1646,1922,1475,1563,1919,1652,1743,1653,1742,1654,1652,1744,1833,1834,1564,1565,1741,1655,1832,1563,1566,1651,1835,1745,1477,1478,1925,1476,1924,1740,1926,1831,1562,1567,1656,1479,1650,1836,1747,1657,1658,1748,1746,1656,1838,1569,1837,1568,1659,1839,1570,1749,1745,1567,1836,1655,1481,1482,1929,1930,1660,1571,1480,1840,1483,1928,1566,1750,1744,1835,1751,1662,1752,1661,1750,1842,1663,1573,1660,1572,1753,1843,1841,1574,1749,1571,1664,1485,1486,1844,1840,1575,1934,1659,1933,1754,1484,1487,1935,1932,1570,1400,1756,1666,1755,1665,1667,1846,1757,1577,1847,1754,1578,1576,1664,1845,1668,1848,1579,1490,1758,1489,1575,1938,1753,1939,1491,1844,1937,1663,1488,1849,1669,1580,1760,1670,1759,1671,1669,1761,1851,1581,1850,1582,1758,1580,1852,1672,1668,1762,1849,1583,1494,1493,1942,1943,1579,1495,1853,1492,1757,1673,1941,1944,1667,1584,1764,1674,1675,1765,1763,1673,1855,1585,1586,1856,1854,1676,1766,1584,1587,1762,1672,1498,1857,1853,1497,1947,1946,1499,1677,1583,1948,1767,1588,1496,1761,1945,1768,1769,1679,1678,1859,1767,1680,1590,1860,1677,1770,1589,1858,1591,1588,1861,1502,1766,1681,1501,1676,1951,1771,1503,1952,1592,1857,1950,1587,1500,1862,1953,1773,1683,1772,1682,1774,1684,1864,1594,1863,1593,1771,1681,1595,1865,1862,1685,1592,1775,1506,1505,1956,1596,1955,1507,1770,1680,1866,1957,1504,1954,1861,1591,2053,1960,2054,2146,2147,2052,1961,2148,2240,1868,1869,1959,2145,2055,2051,1962,2241,2239,2149,2335,2242,1870,1958,1777,1778,1867,2144,2056,2050,1963,2334,2243,2057,2058,1964,1965,2151,2056,2152,1963,2059,1872,2150,1873,1966,1871,2153,2055,2245,1962,2246,1874,1781,2149,2244,1870,2060,1782,1780,1967,2247,2154,1783,1875,2062,2061,1968,1969,2156,2155,2063,2060,1967,1970,1876,1877,2157,2154,1875,2250,1878,2249,2064,1966,2059,1971,1785,2251,1786,2158,1874,2248,1784,2153,1879,1787,2066,2065,1973,1972,2067,2160,2159,1974,2161,1881,1880,2064,1971,2068,2158,1882,1879,2254,1975,2253,2255,2162,1789,1790,1970,2063,1883,1788,1878,1791,2252,2157,2070,1977,2071,2069,2164,1976,1978,2165,2163,1885,1884,2072,1975,2068,1886,1979,2166,2258,1883,2259,2162,1794,2257,1793,1887,2073,2260,1795,1974,1792,2067,1980,2074,2075,1981,1982,2168,2169,2073,1980,2076,1889,2167,1888,1983,1890,2170,1979,2263,2072,2262,1887,1798,2077,1891,1797,2166,2264,2261,1799,1984,2171,1796,1978,2079,2078,1985,1986,2173,2172,2080,1984,2077,1893,1987,2174,1894,1892,2171,2267,2081,1983,2266,1895,2268,1802,2076,1891,1988,2175,1801,1803,2170,2265,1800,2269,2083,1990,2082,1989,2084,2177,2176,1991,2178,1988,1897,1898,2081,2085,1896,2271,2175,1899,2272,2179,1992,1806,2270,1987,1805,1895,1807,2080,2273,2086,1900,1804,2087,2088,1994,1993,2086,2181,1995,2182,2180,1901,1902,2089,1992,2085,2183,1900,1996,1903,2276,2275,2179,1810,1811,2277,1809,2274,2090,1991,1899,1904,2184,1812,2091,2092,1998,1999,2185,1997,2186,2090,2093,1906,1905,2184,2187,2000,1996,1907,2280,1904,2089,2279,2094,2281,1814,1815,2183,1908,1813,2188,2001,2278,1903,1995,2096,2095,2002,2003,2190,2097,2189,2001,2094,1910,2191,2004,1909,1911,2188,2098,2284,2000,2285,1908,2283,2192,1818,1819,1912,2093,2005,1817,2286,1820,2187,1907,2100,2007,2006,2101,2099,2194,2195,2193,2005,2008,1914,1913,1915,2098,2102,2289,2288,2192,2196,2009,2004,1916,1912,1822,1823,2287,2290,1824,1821,2097,2103,2191,2104,2105,2011,2010,2198,2103,2199,2012,2106,1918,2197,2009,1919,1917,2200,2102,2293,2013,2292,1920,2294,2196,1827,1826,1916,2107,2008,1828,2291,1825,2201,1921,2109,2108,2015,2014,2203,2016,2202,2110,2107,1922,1923,2204,2201,2013,2017,1921,2297,1924,2111,2298,2106,2296,1831,1830,2205,1920,1832,2200,2012,2299,1925,2018,2113,2112,2019,2020,2114,2207,2018,2206,2208,1927,1926,2111,2021,2115,2205,1928,2017,1925,2301,2302,2209,1835,1834,2300,1836,2303,2110,2022,1929,1924,2204,1833,2117,2023,2118,2024,2116,2211,2212,2022,2210,2025,1931,1930,2119,2115,1932,2306,2213,1929,2305,2209,2021,1839,2307,2026,1840,1933,1838,2120,2304,2114,1928,1841,2121,2122,2028,2027,2215,2216,2120,2029,2123,1935,2026,2214,1934,1936,2217,2310,2119,2030,2311,1933,2309,1843,2124,1937,2025,2213,1844,1842,2218,2312,1845,2308,2126,2125,2032,2031,2220,2219,2127,2033,2124,1939,2221,1940,2030,1938,2218,2034,2314,2128,2315,1941,1847,2123,1937,1848,2222,2313,2316,1846,2029,2217,1849,2035,2130,2036,2129,2131,2224,2037,2035,2223,2225,1943,1944,2128,2038,2132,1942,2034,2222,2319,1945,2318,2226,1851,2320,1852,1941,2127,2317,1850,2039,1853,2133,2033,2134,2135,2040,2041,2133,2228,2229,2039,2227,1947,1948,2136,2042,2132,2230,1946,1949,2323,2038,2324,2322,2226,1856,1855,2043,2137,1945,1857,1950,1854,2325,2231,2138,2139,2045,2044,2232,2233,2137,2140,2046,2043,1952,1951,2231,2234,1953,2327,1950,2328,2136,2047,2141,2042,1860,2326,1859,2230,1954,2329,1861,2235,1949,1858,2143,2142,2049,2048,2237,2144,2236,2050,2141,1956,2238,1955,2047,1957,2235,2145,2332,2051,2331,1954,1864,2239,2333,1958,2140,1863,1865,2046,2330,2234,1862,1953,2432,2528,2527,2433,2336,2529,2624,2337,2431,2241,2434,2526,2625,2242,2335,2338,2430,2623,2530,2626,2721,2334,2243,2147,2720,2627,2240,2148,2435,2525,2429,2339,2436,2437,2532,2340,2435,2533,2341,2339,2531,2438,2245,2629,2342,2534,2246,2434,2630,2244,2338,2628,2530,2247,2631,2151,2243,2439,2152,2343,2150,2535,2627,2726,2440,2441,2536,2344,2537,2345,2439,2442,2343,2535,2538,2346,2249,2250,2633,2634,2248,2438,2342,2632,2251,2635,2443,2534,2347,2539,2155,2247,2156,2154,2731,2730,2445,2444,2541,2349,2348,2540,2446,2443,2542,2350,2347,2539,2253,2254,2638,2637,2252,2639,2255,2447,2442,2543,2351,2346,2636,2159,2538,2160,2251,2158,2256,2735,2449,2448,2545,2353,2352,2544,2450,2546,2354,2447,2351,2258,2257,2642,2543,2641,2451,2643,2547,2259,2256,2355,2446,2350,2163,2640,2164,2644,2260,2162,2255,2542,2453,2452,2549,2357,2454,2550,2356,2548,2358,2451,2262,2646,2261,2355,2455,2551,2647,2359,2645,2263,2547,2260,2167,2168,2648,2450,2264,2354,2644,2166,2552,2456,2457,2458,2553,2361,2456,2554,2362,2360,2552,2266,2459,2555,2650,2455,2265,2651,2363,2359,2267,2649,2551,2264,2652,2172,2171,2268,2556,2460,2364,2454,2173,2358,2461,2462,2365,2558,2557,2460,2366,2364,2559,2463,2556,2270,2367,2655,2654,2269,2271,2459,2363,2656,2653,2268,2560,2555,2272,2464,2176,2175,2368,2177,2752,2174,2465,2466,2562,2369,2370,2561,2464,2563,2467,2368,2371,2274,2560,2659,2275,2658,2273,2463,2660,2564,2367,2468,2276,2657,2372,2272,2180,2179,2559,2181,2661,2756,2470,2469,2566,2374,2373,2565,2567,2471,2468,2375,2372,2278,2663,2279,2564,2277,2662,2568,2664,2472,2467,2376,2280,2371,2184,2276,2661,2183,2665,2185,2563,2760,2474,2473,2570,2378,2377,2571,2475,2569,2379,2472,2282,2376,2667,2283,2572,2668,2476,2281,2666,2568,2380,2284,2471,2669,2188,2375,2187,2280,2189,2573,2665,2765,2478,2477,2574,2382,2479,2575,2381,2383,2573,2576,2476,2286,2287,2671,2480,2672,2380,2384,2285,2288,2670,2572,2673,2192,2577,2475,2191,2193,2379,2284,2481,2289,2482,2483,2579,2386,2481,2578,2387,2385,2580,2577,2484,2291,2290,2676,2480,2675,2388,2384,2292,2289,2677,2581,2674,2196,2576,2485,2197,2195,2389,2293,2479,2288,2486,2487,2583,2390,2391,2582,2485,2584,2389,2488,2295,2392,2680,2294,2581,2679,2484,2296,2681,2585,2388,2293,2489,2678,2200,2393,2201,2297,2199,2580,2682,2777,2490,2491,2587,2394,2395,2588,2586,2489,2492,2393,2396,2299,2684,2298,2589,2300,2685,2585,2683,2488,2493,2392,2297,2397,2204,2301,2686,2205,2682,2203,2590,2782,2495,2494,2591,2399,2398,2592,2496,2590,2493,2400,2397,2303,2593,2688,2302,2689,2304,2497,2687,2589,2401,2492,2301,2690,2396,2305,2208,2209,2594,2207,2686,2786,2499,2498,2403,2595,2596,2500,2402,2404,2594,2497,2597,2307,2401,2692,2693,2308,2306,2501,2405,2691,2694,2309,2593,2598,2305,2496,2212,2213,2400,2211,2790,2214,2503,2502,2600,2407,2504,2599,2406,2408,2601,2311,2501,2598,2697,2505,2312,2696,2405,2409,2310,2698,2602,2313,2695,2216,2217,2309,2597,2500,2404,2506,2215,2410,2507,2508,2604,2411,2506,2603,2412,2605,2410,2509,2315,2701,2316,2413,2505,2602,2700,2409,2702,2314,2606,2317,2221,2220,2699,2510,2313,2414,2703,2222,2601,2504,2511,2512,2608,2415,2416,2609,2510,2607,2414,2513,2417,2319,2320,2705,2610,2706,2509,2704,2606,2318,2321,2413,2514,2418,2225,2707,2224,2703,2317,2226,2322,2611,2515,2516,2612,2419,2420,2613,2514,2517,2611,2418,2421,2614,2324,2323,2709,2710,2325,2708,2322,2513,2518,2610,2417,2422,2711,2229,2615,2228,2326,2230,2321,2807,2520,2519,2617,2424,2616,2423,2521,2518,2425,2618,2615,2422,2328,2327,2714,2713,2329,2522,2426,2715,2326,2712,2517,2619,2421,2614,2233,2330,2232,2234,2811,2812,2524,2523,2621,2428,2525,2620,2427,2429,2622,2522,2332,2718,2426,2619,2331,2526,2717,2333,2430,2719,2623,2330,2716,2237,2334,2521,2236,2425,2238,2618,2720,2816,2820,2918,2821,2917,3015,2919,2722,2819,2723,3016,2916,2822,3113,3017,2625,3014,2920,2724,2818,2626,2721,3112,3018,2720,2627,3114,2528,2915,2823,3212,3115,2624,2824,2922,2825,2923,2726,2823,2727,2921,2725,2826,3020,2924,3021,2728,2629,3019,2630,2822,2628,2920,2724,3022,2631,2827,3118,2925,2729,3018,3119,2532,2627,2533,2829,2828,2927,2926,2731,2730,2830,2827,2928,2925,3025,3024,2732,2729,2633,2634,3026,3023,2831,2826,2632,2635,2929,2924,2733,2728,3123,3122,2536,2537,2631,3027,2833,2931,2832,2930,2834,2735,2932,2734,2736,3029,2831,3028,2929,2733,2638,3030,2637,2835,2933,2737,2639,3027,2636,2830,3127,3031,2928,2732,2541,2540,3126,2640,2837,2935,2838,2836,2936,2739,2934,2740,2738,3033,2839,3034,2835,3032,2937,2642,2933,2741,2641,2737,2643,3035,2640,3031,3131,2644,2840,2545,3132,2834,2544,2742,2841,2842,2939,2940,2743,2840,2744,2938,2843,2742,3037,2941,3038,2745,2646,3036,2647,2839,2645,2937,3039,2741,2844,2648,2942,2746,2644,3136,3135,2549,3035,2550,2846,2845,2944,2943,2748,2747,2847,2844,2945,2942,3042,3041,2749,2746,2650,2651,3043,3040,2848,2649,2843,2946,2750,2652,2941,2745,3140,2553,3139,2554,2648,3044,2850,2948,2849,2947,2851,2752,2949,2751,2753,3046,2848,3045,2946,3047,2750,2655,2852,2654,2950,2754,2656,2653,3044,2847,3144,3048,2945,2749,2558,2557,3145,3143,2854,2952,2855,2853,2953,2756,2951,2757,2755,3050,2856,3051,2954,2852,3049,2659,2758,2658,2950,2754,2660,3052,2657,3048,2857,3148,3149,2562,2661,2561,2955,2759,2858,2859,2956,2957,2760,2857,2761,2955,2860,3054,2759,2958,3055,2762,2663,3053,2662,2664,2856,3056,2954,2758,2861,2959,2661,2763,2665,3153,2566,3152,3052,2565,2863,2862,2961,2960,2765,2764,2864,2962,2861,2959,3059,2766,3058,2763,2667,2668,3060,2865,2666,3057,2963,2860,2767,2669,2958,2762,3157,2665,2570,3158,2571,3061,2867,2965,2866,2964,2868,2769,2966,2768,2770,3063,2865,3062,2963,3064,2869,2671,2767,2672,2967,2771,2670,2673,3061,3065,2864,3161,3162,2574,2575,2962,2766,2669,2871,2969,2872,2970,2870,2773,2968,2774,2772,3067,2873,3068,2971,3066,2869,2676,2775,2675,2967,2771,2677,2674,3069,3065,2874,3166,3165,2579,2578,2972,2776,2678,2875,2876,2973,2974,2777,2778,2874,2972,2877,2975,3071,2776,3072,2779,2680,2679,3070,2873,2681,3073,2971,2878,2775,2678,2976,2780,3170,2682,2583,3169,2582,3069,2880,2879,2978,2977,2782,2881,2781,2979,2878,3076,2783,2976,3075,2780,2684,3077,2685,2683,2882,3074,2980,2784,2877,2975,2686,2779,2682,3174,2587,3175,3078,2588,2884,2982,2883,2885,2981,2786,2983,2785,2787,3080,2882,3079,2980,2886,3081,2688,2784,2689,2984,2788,2687,3078,2690,3082,2881,3179,3178,2591,2686,2592,2979,2783,2888,2986,2889,2987,2887,2790,2985,2791,2789,3084,2890,3085,2988,3083,2792,2692,2886,2693,2984,2788,2691,2694,3086,2891,3183,3082,2989,2793,2595,2596,3182,3184,2892,2893,2990,2991,2794,2795,2891,2894,2989,2992,3088,3089,2793,2796,2697,2696,3087,3090,2890,2698,2895,2988,2792,2695,2993,2797,3187,2600,3188,2599,2699,3086,2897,2896,2995,2994,2799,2898,2798,2996,2895,2800,3093,2993,3092,2797,2701,3094,2700,2899,2702,2997,3091,2801,2894,2699,2992,2796,2703,3191,3192,2604,3095,2603,2901,2999,2900,2902,2998,2803,3000,2802,2804,3097,2899,3096,2903,3098,2997,2705,3001,2801,2706,2805,2704,3095,2707,3099,3196,2703,2898,2608,3195,2904,2609,2800,2905,3003,2906,3004,2904,2807,3002,2808,2806,3101,2907,3102,3005,2809,2709,3100,2710,2903,3001,2805,2708,3103,2711,2908,3200,3099,3006,2810,2612,2613,3201,2707,2909,2910,3007,3008,2811,2812,2908,2911,3006,3009,3105,3106,2810,2813,2714,2713,3104,3107,2907,2912,2715,2712,3005,3010,2809,2814,3204,3205,2617,2616,2716,3103,2914,3012,2913,3011,2816,2915,2815,3013,2817,2912,3110,3010,3109,2814,2718,3111,2717,2916,2719,3014,2818,3108,2716,2911,3209,3009,2813,3112,3208,2621,2720,2620,3312,3213,3311,3214,3410,3313,3114,3411,3212,3115,3412,3508,3215,3310,3314,3409,3016,3211,3116,3113,3017,3509,3507,3413,3606,3510,3112,3018,3216,3309,3408,3315,3316,3217,3317,3218,3216,3315,3118,3415,3119,3416,3219,3318,3117,3414,3120,3020,3215,3417,3314,3021,3019,3513,3116,3514,3220,3319,3413,3022,3512,3121,3018,2922,3321,3222,3320,3221,3223,3123,3322,3122,3420,3419,3220,3319,3124,3121,3421,3418,3025,3024,3224,3323,3219,3518,3517,3026,3318,3125,3023,3120,3422,3519,3417,3516,3325,3226,3324,3225,3227,3326,3127,3424,3126,3423,3128,3224,3425,3323,3228,3327,3029,3125,3422,3028,3129,3030,3522,3521,3426,3027,3523,3223,3322,3229,3031,2931,3329,3230,3330,3231,3229,3328,3131,3428,3132,3429,3232,3130,3427,3331,3133,3228,3327,3033,3034,3032,3430,3129,3526,3426,3527,3233,3525,3332,3035,3031,3134,2935,3334,3333,3235,3234,3136,3135,3432,3236,3335,3233,3332,3433,3137,3431,3134,3037,3434,3038,3237,3232,3336,3530,3331,3036,3531,3138,3039,3133,3430,3529,2939,3035,3338,3239,3337,3238,3240,3339,3140,3437,3436,3139,3141,3237,3336,3438,3241,3435,3340,3138,3042,3041,3142,3535,3534,3043,3040,3236,3335,3439,3536,3137,3533,3434,3342,3243,3343,3244,3242,3341,3144,3441,3145,3440,3143,3245,3442,3344,3241,3340,3146,3046,3045,3439,3142,3047,3539,3538,3443,3044,3246,3540,3345,3048,3147,2948,3346,3247,3347,3248,3445,3148,3246,3345,3149,3249,3348,3446,3444,3147,3150,3050,3245,3051,3447,3344,3049,3543,3250,3349,3443,3146,3544,3542,3151,3052,3048,2952,3351,3252,3350,3251,3253,3352,3153,3449,3152,3450,3250,3349,3154,3448,3151,3254,3451,3054,3353,3055,3155,3547,3053,3548,3249,3056,3348,3447,3546,3150,2956,3549,3355,3256,3356,3257,3255,3354,3157,3454,3453,3158,3156,3258,3357,3254,3455,3353,3452,3059,3159,3058,3155,3552,3060,3551,3057,3456,3259,3553,3358,3253,3550,3352,3359,3260,3360,3261,3259,3358,3161,3458,3162,3262,3361,3457,3459,3160,3163,3063,3258,3357,3062,3456,3064,3556,3159,3263,3460,3362,3555,3557,3061,3164,3065,2965,3364,3265,3363,3264,3266,3365,3166,3462,3165,3263,3362,3463,3461,3167,3164,3067,3267,3366,3068,3464,3066,3560,3168,3262,3460,3361,3561,3559,3069,3163,3065,2969,3368,3269,3367,3268,3270,3369,3170,3466,3467,3169,3171,3267,3366,3271,3465,3370,3468,3071,3168,3072,3172,3564,3070,3565,3073,3464,3266,3563,3365,3272,3566,3371,3372,3273,3373,3274,3272,3371,3174,3471,3175,3470,3275,3374,3173,3472,3176,3271,3469,3076,3370,3075,3172,3569,3077,3568,3276,3074,3375,3473,3570,3177,2978,3567,3377,3278,3376,3277,3475,3179,3279,3378,3178,3276,3375,3474,3476,3180,3177,3080,3280,3079,3473,3379,3081,3573,3275,3374,3477,3181,3572,3574,3176,3078,3082,2982,3381,3282,3380,3281,3283,3382,3183,3479,3182,3480,3184,3280,3478,3379,3284,3383,3181,3084,3085,3481,3185,3083,3577,3578,3477,3086,3279,3576,3378,3082,3180,2986,3385,3286,3386,3287,3285,3384,3187,3483,3484,3188,3186,3288,3387,3482,3284,3485,3383,3189,3088,3089,3185,3581,3582,3087,3090,3289,3388,3481,3580,3190,3583,3486,3389,3390,3290,3291,3191,3192,3488,3289,3388,3292,3391,3487,3190,3489,3193,3093,3486,3092,3288,3293,3387,3586,3392,3094,3585,3189,3091,3194,3490,3587,2995,3095,3394,3295,3393,3294,3296,3395,3196,3492,3195,3491,3293,3197,3493,3392,3194,3297,3396,3097,3096,3098,3490,3198,3590,3494,3589,3292,3591,3391,3095,3099,3193,2999,3398,3299,3399,3300,3298,3397,3200,3496,3201,3497,3199,3301,3495,3400,3297,3396,3101,3202,3498,3102,3198,3100,3594,3595,3494,3103,3593,3302,3401,3296,3099,3003,3402,3303,3403,3304,3302,3204,3401,3205,3500,3501,3305,3404,3203,3206,3499,3502,3105,3106,3301,3400,3306,3598,3599,3104,3405,3202,3107,3207,3498,3597,3503,3600,3407,3308,3406,3307,3309,3408,3209,3505,3208,3504,3306,3405,3210,3506,3207,3110,3310,3503,3409,3109,3111,3603,3211,3602,3305,3404,3507,3108,3604,3206,3112,3012,3705,3607,3706,3802,3803,3704,3608,3509,3899,3804,3606,3510,3801,3707,3703,3609,3900,3898,3805,3411,3605,3511,3995,3901,3508,3412,3702,3610,3800,3708,3413,3507,3709,3611,3710,3612,3807,3708,3610,3808,3513,3514,3806,3711,3613,3512,3809,3904,3707,3515,3609,3905,3415,3416,3903,3805,3511,3414,3712,3614,3417,3906,3516,3810,3714,3713,3616,3615,3811,3812,3715,3712,3617,3614,3518,3517,3810,3813,3519,3516,3908,3909,3420,3419,3716,3618,3711,3613,3907,3421,3418,3809,3520,3515,3910,3814,3718,3620,3717,3619,3719,3816,3621,3815,3522,3521,3716,3817,3618,3523,3814,3720,3622,3913,3520,3912,3424,3423,3524,3425,3818,3914,3911,3617,3715,3422,3813,3519,3722,3624,3723,3721,3625,3820,3623,3819,3526,3821,3527,3525,3724,3626,3720,3622,3917,3818,3916,3428,3528,3524,3822,3429,3427,3918,3915,3627,3725,3430,3621,3426,3726,3727,3628,3629,3824,3725,3627,3825,3530,3823,3728,3531,3630,3529,3921,3532,3724,3826,3626,3432,3920,3822,3433,3922,3528,3431,3729,3631,3434,3533,3919,3430,3731,3730,3633,3632,3828,3829,3732,3634,3729,3535,3534,3631,3827,3536,3830,3533,3925,3437,3733,3436,3635,3926,3924,3728,3630,3826,3438,3537,3435,3532,3831,3927,3735,3637,3734,3636,3736,3833,3832,3638,3539,3538,3733,3635,3540,3834,3831,3737,3639,3929,3537,3930,3441,3440,3541,3928,3442,3634,3732,3835,3830,3439,3931,3536,3739,3641,3740,3738,3642,3837,3640,3836,3543,3838,3544,3542,3741,3643,3737,3639,3835,3933,3934,3545,3445,3541,3446,3444,3839,3932,3935,3644,3742,3447,3443,3638,3743,3744,3645,3646,3841,3742,3644,3840,3547,3842,3745,3548,3647,3546,3549,3938,3937,3741,3839,3643,3449,3843,3450,3746,3648,3448,3545,3939,3936,3451,3550,3351,3748,3747,3650,3649,3845,3749,3846,3651,3746,3552,3551,3844,3648,3553,3550,3847,3942,3941,3750,3652,3454,3453,3843,3745,3943,3647,3455,3554,3452,3549,3940,3848,3752,3654,3751,3653,3753,3849,3655,3850,3556,3555,3848,3750,3557,3652,3851,3754,3656,3946,3554,3458,3945,3947,3457,3558,3459,3847,3651,3749,3456,3852,3944,3460,3756,3658,3757,3659,3755,3854,3657,3853,3560,3561,3855,3758,3559,3660,3852,3754,3656,3950,3562,3462,3951,3949,3463,3558,3461,3856,3661,3759,3464,3851,3952,3460,3760,3761,3662,3663,3858,3759,3857,3661,3762,3564,3565,3859,3664,3563,3566,3856,3954,3955,3758,3660,3466,3467,3860,3763,3953,3665,3465,3562,3468,3567,3956,3855,3765,3764,3667,3666,3862,3766,3668,3863,3569,3861,3763,3568,3665,3570,3567,3958,3959,3767,3864,3669,3471,3860,3470,3762,3664,3472,3571,3957,3960,3469,3566,3372,3769,3671,3768,3770,3670,3866,3672,3867,3573,3865,3572,3574,3767,3669,3771,3673,3868,3963,3962,3571,3475,3575,3474,3476,3864,3964,3961,3668,3766,3473,3477,3674,3773,3675,3774,3676,3772,3870,3871,3674,3577,3578,3775,3677,3576,3869,3872,3771,3673,3967,3579,3966,3479,3480,3575,3968,3478,3678,3776,3868,3873,3481,3965,3580,3777,3778,3679,3680,3875,3874,3776,3678,3779,3581,3582,3681,3876,3580,3873,3583,3971,3483,3775,3484,3677,3970,3972,3780,3682,3877,3482,3579,3485,3584,3872,3969,3782,3781,3684,3683,3879,3783,3685,3878,3586,3880,3780,3585,3682,3587,3975,3584,3784,3877,3686,3488,3976,3881,3487,3974,3588,3489,3779,3681,3486,3583,3977,3490,3786,3688,3785,3787,3687,3883,3689,3884,3590,3882,3589,3591,3784,3686,3788,3690,3979,3885,3980,3492,3588,3592,3881,3491,3493,3978,3981,3685,3783,3490,3691,3494,3790,3692,3791,3693,3789,3887,3691,3888,3594,3595,3792,3886,3694,3593,3889,3788,3690,3983,3596,3984,3496,3497,3592,3495,3885,3982,3985,3695,3793,3498,3890,3597,3794,3795,3696,3697,3892,3891,3793,3796,3695,3698,3598,3599,3893,3890,3597,3600,3988,3987,3500,3501,3792,3694,3797,3699,3989,3499,3502,3894,3596,3601,3986,3889,3799,3701,3798,3700,3896,3800,3702,3895,3603,3602,3897,3797,3699,3604,3894,3992,3801,3601,3703,3991,3505,3504,3993,3898,3605,3506,3796,3698,3503,3990,3600,3893,4092,3996,-1,4093,4186,-1,-1,4091,3997,3900,-1,-1,-1,3995,3901,-1,4094,4185,-1,4090,3998,-1,3803,3902,3994,-1,-1,3899,3804,-1,-1,-1,4096,4097,4000,-1,-1,4095,4001,3999,-1,3904,-1,-1,4098,-1,3905,4002,3903,4094,-1,3998,-1,-1,3906,3807,-1,3808,3902,-1,-1,3806,-1,4003,4100,4101,4004,-1,-1,4005,4099,-1,4003,-1,4102,3908,-1,4006,3909,-1,3907,-1,4098,3910,-1,-1,4002,3811,-1,3812,-1,4007,-1,4103,3906,3810,4104,4105,-1,4009,4008,-1,-1,4103,4106,4010,4007,-1,3913,3912,-1,-1,-1,-1,3914,3911,4102,3816,-1,4011,3815,4006,4107,-1,-1,3817,-1,-1,4109,4108,-1,4013,4012,-1,-1,4110,4107,4014,3917,-1,-1,3916,4011,-1,3918,-1,-1,3915,4015,-1,4111,3820,4106,3819,-1,-1,3821,4010,-1,-1,4113,4112,4017,-1,-1,4016,4114,4018,-1,4111,-1,3921,-1,-1,3920,4015,3922,-1,4019,-1,4115,-1,3919,-1,3824,3923,3825,4110,-1,3823,-1,-1,4117,4116,4021,-1,-1,4118,4022,4020,-1,3925,-1,4115,-1,3926,-1,3924,-1,4023,-1,4019,4119,-1,3927,3828,3923,3829,-1,-1,-1,3827,-1,4114,4121,-1,4025,4120,4122,-1,4026,-1,4024,3929,-1,3930,-1,4119,-1,4027,3928,-1,4123,-1,4023,3931,-1,3833,3832,-1,3927,-1,-1,-1,4028,3834,4125,4126,4029,-1,-1,4124,4030,4028,-1,-1,3933,4031,3934,-1,-1,4127,4123,3932,-1,-1,3935,-1,-1,4027,3837,3836,4032,-1,-1,3838,3931,-1,4129,4130,-1,4034,4033,-1,4128,-1,4035,4032,3938,-1,3937,4131,-1,-1,-1,4127,3939,-1,3936,-1,4036,3841,4031,3840,-1,3842,-1,-1,-1,4132,4133,4134,-1,4038,4037,-1,4132,-1,4039,4135,3942,-1,3941,4036,-1,-1,-1,3943,-1,4131,4040,3940,-1,3845,3846,-1,-1,4136,3844,3944,-1,4035,4137,4138,4042,-1,-1,4041,4043,4136,-1,4139,-1,3946,-1,-1,3945,3947,4040,4044,-1,-1,-1,4135,3944,-1,3849,3850,4140,3948,-1,-1,3848,-1,4142,4141,4046,-1,-1,4047,4045,4143,-1,4140,3950,-1,-1,-1,3951,3949,4048,-1,4044,-1,-1,4144,3952,3854,3853,4139,3948,-1,-1,-1,-1,3855,4146,4145,-1,4050,4051,-1,-1,4147,4049,4144,3954,-1,3955,4052,-1,-1,-1,-1,3953,4148,4048,3956,3858,-1,-1,3857,-1,4143,3859,3952,4053,-1,4150,4149,-1,4054,4055,-1,4151,-1,4053,-1,4056,3958,3959,-1,4148,-1,-1,4152,3957,3960,-1,-1,4052,3862,-1,4057,3863,-1,3861,-1,-1,4147,4154,-1,4153,4059,4155,4058,-1,-1,4060,-1,3963,4057,-1,3962,-1,4152,4156,3964,-1,3961,-1,-1,4061,3866,-1,3867,4056,-1,-1,3865,-1,3965,4158,-1,4063,4159,4157,4062,-1,-1,4064,3967,-1,3966,4160,4061,-1,-1,-1,-1,3968,4156,4065,3965,3870,3871,-1,-1,-1,3969,-1,4060,-1,3869,4162,4163,4067,-1,-1,4161,4066,4068,-1,3971,-1,4164,-1,-1,3970,3972,4065,-1,4069,4160,-1,-1,3969,3875,3973,3874,-1,-1,-1,3876,-1,4165,4166,4167,4071,-1,-1,4072,4165,4070,-1,4168,-1,3975,-1,-1,3976,4073,3974,-1,4069,-1,-1,4164,3977,3879,-1,3973,3878,4169,-1,3880,-1,-1,4170,4171,-1,4075,4076,-1,-1,4169,4172,4074,3979,-1,3980,4077,-1,-1,-1,-1,3978,3981,4073,4168,3883,-1,4173,3884,-1,-1,3882,4078,3977,-1,4175,4174,-1,4079,4080,-1,4176,-1,4173,4078,4081,3983,-1,3984,-1,-1,-1,3982,-1,3985,4177,-1,3887,4077,3888,4082,4172,-1,-1,-1,-1,3886,4179,4178,4084,-1,-1,4083,4180,4085,-1,-1,4177,3988,-1,4082,3987,-1,3989,-1,4181,-1,3986,-1,4086,-1,3892,3891,-1,-1,4081,4176,3990,3893,4183,4182,-1,4088,4184,-1,4087,-1,4089,3992,-1,4181,3991,-1,-1,4086,3993,-1,4185,-1,4090,3990,-1,3896,3895,-1,3994,-1,-1,3897,-1,4085]}}}
diff --git a/docs/source/_static/css/foveation-viewer.css b/docs/source/_static/css/foveation-viewer.css
new file mode 100644
index 000000000000..8d12840598d8
--- /dev/null
+++ b/docs/source/_static/css/foveation-viewer.css
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+ * All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+/* Interactive sampling-grid and pooling viewers on the Foveated Camera page. */
+
+.fovi-viewer {
+ --fovi-ink: #1f2a37;
+ --fovi-muted: #8a96a8;
+ --fovi-faint: #d7dee8;
+ --fovi-surface: #ffffff;
+ --fovi-panel: #f6f8fb;
+ --fovi-border: #dfe5ec;
+ --fovi-accent: #2458d3;
+ --fovi-camera: #167d72;
+ --fovi-highlight: #d47b00;
+ --fovi-body: #29364b;
+ margin: 1.25rem 0 1.75rem;
+ padding: 1rem;
+ border: 1px solid var(--fovi-border);
+ border-radius: 8px;
+ background: var(--fovi-panel);
+ color: var(--fovi-ink);
+}
+
+html[data-theme="dark"] .fovi-viewer {
+ --fovi-ink: #e3e8ef;
+ --fovi-muted: #7d8899;
+ --fovi-faint: #3a4556;
+ --fovi-surface: #11161d;
+ --fovi-panel: #1a2029;
+ --fovi-border: #343d4b;
+ --fovi-accent: #6d9cff;
+ --fovi-camera: #3cc2ad;
+ --fovi-highlight: #f0a33a;
+ --fovi-body: #5b6f8c;
+}
+
+.fovi-controls {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(12.5rem, 1fr));
+ gap: 0.6rem 1.2rem;
+ align-items: end;
+}
+
+.fovi-control {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ gap: 0.15rem 0.5rem;
+ margin: 0;
+ font-size: 0.85rem;
+}
+
+.fovi-viewer [hidden] {
+ display: none;
+}
+
+.fovi-control-name {
+ grid-column: 1 / -1;
+}
+
+.fovi-control input[type="range"],
+.fovi-control select {
+ width: 100%;
+ min-width: 0;
+ accent-color: var(--fovi-accent);
+}
+
+.fovi-control select {
+ padding: 0.15rem 0.3rem;
+ border: 1px solid var(--fovi-border);
+ border-radius: 4px;
+ background: var(--fovi-surface);
+ color: var(--fovi-ink);
+}
+
+.fovi-control-value {
+ min-width: 3.5rem;
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+}
+
+.fovi-reset {
+ justify-self: start;
+ padding: 0.25rem 0.9rem;
+ border: 1px solid var(--fovi-border);
+ border-radius: 4px;
+ background: var(--fovi-surface);
+ color: var(--fovi-ink);
+ font-size: 0.85rem;
+ cursor: pointer;
+}
+
+.fovi-summary {
+ margin: 0.9rem 0 0.6rem;
+ font-size: 0.9rem;
+}
+
+.fovi-panels {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr));
+ gap: 1rem;
+}
+
+.fovi-panels-stacked {
+ grid-template-columns: 1fr;
+}
+
+.fovi-panels-three {
+ grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr));
+}
+
+.fovi-panel {
+ margin: 0;
+ padding: 0.6rem;
+ border: 1px solid var(--fovi-border);
+ border-radius: 6px;
+ background: var(--fovi-surface);
+}
+
+.fovi-panel-control {
+ max-width: 22rem;
+ margin-bottom: 0.4rem;
+}
+
+.fovi-panel figcaption {
+ margin-bottom: 0.4rem;
+ font-weight: 600;
+ font-size: 0.9rem;
+}
+
+.fovi-views {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.4rem;
+}
+
+.fovi-canvas {
+ display: block;
+ width: 100%;
+ aspect-ratio: 1;
+ touch-action: none;
+}
+
+.fovi-sphere {
+ cursor: grab;
+}
+
+.fovi-panel-labels {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.4rem;
+ color: var(--fovi-muted);
+ font-size: 0.75rem;
+ text-align: center;
+}
+
+.fovi-panel-note {
+ margin: 0.4rem 0 0;
+ font-size: 0.8rem;
+}
+
+.fovi-legend {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.3rem 0.5rem;
+ margin: 0.7rem 0 0;
+ font-size: 0.8rem;
+}
+
+.fovi-key {
+ display: inline-block;
+ width: 0.7rem;
+ height: 0.7rem;
+ margin-left: 0.6rem;
+ border-radius: 50%;
+}
+
+.fovi-key:first-child {
+ margin-left: 0;
+}
+
+.fovi-key-accent {
+ background: var(--fovi-accent);
+}
+
+.fovi-key-muted {
+ background: var(--fovi-muted);
+}
+
+.fovi-key-camera {
+ background: var(--fovi-camera);
+}
+
+.fovi-key-highlight {
+ background: var(--fovi-highlight);
+}
+
+.fovi-legend-note {
+ margin-left: auto;
+ color: var(--fovi-muted);
+}
diff --git a/docs/source/_static/css/foveation-viewer.js b/docs/source/_static/css/foveation-viewer.js
new file mode 100644
index 000000000000..96ce5d224807
--- /dev/null
+++ b/docs/source/_static/css/foveation-viewer.js
@@ -0,0 +1,994 @@
+/*
+ * Copyright (c) 2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+ * All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+// Interactive sampling-grid and pooling viewers for the Foveated Camera page.
+// The sampling follows fovi's SamplingCoords with spherical field geometry, as the camera configures it.
+(() => {
+ "use strict";
+
+ const DEG = Math.PI / 180;
+ const TAU = 2 * Math.PI;
+ // fovi's isotropic pooling neighbourhoods for the pooling viewer, beside this script; fetched only when used.
+ const SCRIPT_URL = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : null;
+ const TABLES_URL = SCRIPT_URL ? new URL("foveation-pooling-isotropic.json", SCRIPT_URL).href : null;
+
+ // -- Sampling geometry -------------------------------------------------------------------------------------------
+
+ // Warped Cartesian grid: an N x N lattice in the native plane, mapped radially by the integrated CMF.
+ // Returns samples in canonical order (x index major), each with normalized visual coordinates s = (x, y) / r_max.
+ const warpedGrid = (fov, a, res) => {
+ const half = fov / 2;
+ const growth = 1 + half / a;
+ const samples = [];
+ for (let i = 0; i < res; i++) {
+ for (let j = 0; j < res; j++) {
+ const cx = -1 + (2 * i + 1) / res;
+ const cy = -1 + (2 * j + 1) / res;
+ const rho = Math.hypot(cx, cy);
+ const r = a * (Math.pow(growth, rho) - 1);
+ const theta = Math.atan2(cy, cx);
+ samples.push({i, j, native: [cx, cy], s: [(r / half) * Math.cos(theta), (r / half) * Math.sin(theta)], valid: rho <= 1 + 1e-12});
+ }
+ }
+ return samples;
+ };
+
+ // Isotropic rings: radii even in cortical distance w = log(r + a), angles per ring matched to the radial step.
+ const isotropicRings = (fov, a, res) => {
+ if (res === 1) {
+ return {radius: [0], count: [1]};
+ }
+ const half = fov / 2;
+ const wMin = Math.log(a);
+ const wDelta = (Math.log(half + a) - wMin) / (res - 1);
+ const radius = Array.from({length: res + 1}, (_, k) => Math.exp(wMin + k * wDelta) - a);
+ const count = [1];
+ for (let k = 1; k < res; k++) {
+ const step = (radius[k + 1] - radius[k - 1]) / 2;
+ const tangential = Math.sin(radius[k] * DEG) / DEG; // spherical field geometry
+ count.push(Math.ceil((TAU * tangential) / step));
+ }
+ return {radius: radius.slice(0, res).map((r) => r / half), count};
+ };
+
+ const isotropicCount = (fov, a, res) => isotropicRings(fov, a, res).count.reduce((sum, n) => sum + n, 0);
+
+ // The camera matches an isotropic retina to foveated_res^2 samples (fovi's auto_match_num_coords).
+ const matchedIsotropicRes = (fov, a, target) => {
+ let left = 1;
+ let right = 1000;
+ let best = 1;
+ let bestDiff = Infinity;
+ while (left <= right) {
+ const mid = (left + right) >> 1;
+ const n = isotropicCount(fov, a, mid);
+ const diff = Math.abs(n - target);
+ if (diff < bestDiff) {
+ bestDiff = diff;
+ best = mid;
+ }
+ if (n < target) {
+ left = mid + 1;
+ } else {
+ right = mid - 1;
+ }
+ }
+ while (best > 1 && isotropicCount(fov, a, best) > target) {
+ best -= 1;
+ }
+ return best;
+ };
+
+ const isotropicSamples = (fov, a, rings) => {
+ const {radius, count} = isotropicRings(fov, a, rings);
+ const samples = [];
+ radius.forEach((r, ring) => {
+ for (let k = 0; k < count[ring]; k++) {
+ const angle = (k * TAU) / count[ring];
+ samples.push({ring, s: [r * Math.cos(angle), r * Math.sin(angle)], valid: true});
+ }
+ });
+ return samples;
+ };
+
+ // Unit ray of a normalized visual coordinate, in the image frame: x right, y down, z forward.
+ const ray = (s, fov) => {
+ const e = Math.hypot(s[0], s[1]) * (fov / 2) * DEG;
+ const theta = Math.atan2(s[1], s[0]);
+ return [Math.sin(e) * Math.cos(theta), -Math.sin(e) * Math.sin(theta), Math.cos(e)];
+ };
+
+ // Pan-then-tilt gaze rotation (row-major), as isaaclab_fovi's gaze kernels: positive tilt looks up, pan left.
+ const gazeRotation = (tilt, pan) => {
+ const x = -Math.cos(tilt * DEG) * Math.sin(pan * DEG);
+ const y = -Math.sin(tilt * DEG);
+ const z = Math.cos(tilt * DEG) * Math.cos(pan * DEG);
+ const pitch = Math.atan2(x, z);
+ const roll = Math.atan2(-y, Math.hypot(x, z));
+ const [cp, sp, cr, sr] = [Math.cos(pitch), Math.sin(pitch), Math.cos(roll), Math.sin(roll)];
+ return [[cp, sp * sr, sp * cr], [0, cr, -sr], [-sp, cp * sr, cp * cr]];
+ };
+
+ const rotate = (m, v) => m.map((row) => row[0] * v[0] + row[1] * v[1] + row[2] * v[2]);
+
+ // An ideal square camera whose field of view spans its side; the retina spans the same angle.
+ const SIDE = 1000;
+ const cameraModels = {
+ fisheye: {
+ label: "Equidistant fisheye",
+ fov: {min: 40, max: 240, initial: 180},
+ focal: (fov) => SIDE / 2 / ((fov / 2) * DEG),
+ project(d, f) {
+ const lateral = Math.hypot(d[0], d[1]);
+ const theta = Math.atan2(lateral, d[2]);
+ if (lateral < 1e-12) {
+ return [SIDE / 2, SIDE / 2];
+ }
+ return [SIDE / 2 + (f * theta * d[0]) / lateral, SIDE / 2 + (f * theta * d[1]) / lateral];
+ },
+ unproject(p, f) {
+ const dx = p[0] - SIDE / 2;
+ const dy = p[1] - SIDE / 2;
+ const theta = Math.hypot(dx, dy) / f;
+ const lateral = Math.hypot(dx, dy) || 1;
+ return [(Math.sin(theta) * dx) / lateral, (Math.sin(theta) * dy) / lateral, Math.cos(theta)];
+ },
+ },
+ pinhole: {
+ label: "Pinhole",
+ fov: {min: 20, max: 170, initial: 80},
+ focal: (fov) => SIDE / 2 / Math.tan((fov / 2) * DEG),
+ project(d, f) {
+ if (d[2] <= 1e-9) {
+ return null;
+ }
+ return [SIDE / 2 + (f * d[0]) / d[2], SIDE / 2 + (f * d[1]) / d[2]];
+ },
+ unproject(p, f) {
+ return normalize([(p[0] - SIDE / 2) / f, (p[1] - SIDE / 2) / f, 1]);
+ },
+ },
+ };
+
+ const normalize = (v) => {
+ const n = Math.hypot(v[0], v[1], v[2]);
+ return [v[0] / n, v[1] / n, v[2] / n];
+ };
+
+ const inImage = (p) => p !== null && p[0] >= 0 && p[0] < SIDE && p[1] >= 0 && p[1] < SIDE;
+
+ const imageBorder = (model, f) => {
+ const points = [];
+ const corners = [[0, 0], [SIDE, 0], [SIDE, SIDE], [0, SIDE], [0, 0]];
+ for (let k = 0; k < 4; k++) {
+ for (let t = 0; t < 40; t++) {
+ const [a, b] = [corners[k], corners[k + 1]];
+ points.push(model.unproject([a[0] + ((b[0] - a[0]) * t) / 40, a[1] + ((b[1] - a[1]) * t) / 40], f));
+ }
+ }
+ points.push(points[0]);
+ return points;
+ };
+
+ // Spacing of neighbouring samples [deg] at the fixation and at the edge of the field.
+ const spacing = (style, fov, a, res) => {
+ const half = fov / 2;
+ if (style === "isotropic") {
+ const step = (Math.log(half + a) - Math.log(a)) / Math.max(res - 1, 1);
+ return [a * (Math.exp(step) - 1), (half + a) * (1 - Math.exp(-step))];
+ }
+ const rate = Math.log(1 + half / a) * (2 / res);
+ return [a * rate, (half + a) * rate];
+ };
+
+ // -- Drawing helpers ---------------------------------------------------------------------------------------------
+
+ const palette = (element) => {
+ const style = getComputedStyle(element);
+ const get = (name, fallback) => style.getPropertyValue(name).trim() || fallback;
+ return {
+ ink: get("--fovi-ink", "#1f2a37"),
+ muted: get("--fovi-muted", "#8a96a8"),
+ faint: get("--fovi-faint", "#d7dee8"),
+ surface: get("--fovi-surface", "#ffffff"),
+ accent: get("--fovi-accent", "#2458d3"),
+ camera: get("--fovi-camera", "#167d72"),
+ highlight: get("--fovi-highlight", "#d47b00"),
+ body: get("--fovi-body", "#29364b"),
+ };
+ };
+
+ const fitCanvas = (canvas) => {
+ const box = canvas.getBoundingClientRect();
+ const ratio = Math.min(window.devicePixelRatio || 1, 2);
+ canvas.width = Math.max(1, Math.round(box.width * ratio));
+ canvas.height = Math.max(1, Math.round(box.height * ratio));
+ const ctx = canvas.getContext("2d");
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ return {ctx, w: box.width, h: box.height};
+ };
+
+ const polyline = (ctx, points, color, width, dash = []) => {
+ if (points.length < 2) {
+ return;
+ }
+ ctx.beginPath();
+ ctx.setLineDash(dash);
+ ctx.strokeStyle = color;
+ ctx.lineWidth = width;
+ points.forEach((p, k) => (k === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1])));
+ ctx.stroke();
+ ctx.setLineDash([]);
+ };
+
+ const dots = (ctx, points, color, radius, alpha = 1) => {
+ ctx.globalAlpha = alpha;
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ for (const p of points) {
+ ctx.moveTo(p[0] + radius, p[1]);
+ ctx.arc(p[0], p[1], radius, 0, TAU);
+ }
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ };
+
+ // Orbiting orthographic view of the viewing sphere; the camera sits at its centre looking along +z.
+ const sphereProjector = (view, w, h) => {
+ const scale = Math.min(w, h) * 0.4;
+ const [cy, sy, cp, sp] = [Math.cos(view.yaw), Math.sin(view.yaw), Math.cos(view.pitch), Math.sin(view.pitch)];
+ return ([x, y, z]) => {
+ const rx = cy * x - sy * z;
+ const rz = sy * x + cy * z;
+ const ry = cp * y - sp * rz;
+ const depth = sp * y + cp * rz;
+ return [w / 2 + rx * scale, h / 2 + ry * scale, depth];
+ };
+ };
+
+ const bindOrbit = (canvas, view, redraw, initial) => {
+ let last = null;
+ canvas.addEventListener("pointerdown", (event) => {
+ last = [event.clientX, event.clientY];
+ canvas.setPointerCapture(event.pointerId);
+ });
+ canvas.addEventListener("pointermove", (event) => {
+ if (!last) {
+ return;
+ }
+ view.yaw += (event.clientX - last[0]) * 0.01;
+ view.pitch = Math.max(-1.5, Math.min(1.5, view.pitch - (event.clientY - last[1]) * 0.01));
+ last = [event.clientX, event.clientY];
+ redraw();
+ });
+ for (const name of ["pointerup", "pointercancel"]) {
+ canvas.addEventListener(name, () => (last = null));
+ }
+ canvas.addEventListener("dblclick", () => {
+ Object.assign(view, initial);
+ redraw();
+ });
+ };
+
+ const drawSphere = (canvas, view, scene, colors) => {
+ const {ctx, w, h} = fitCanvas(canvas);
+ const project = sphereProjector(view, w, h);
+ // The viewer looks from behind the camera, so smaller depths are nearer; nothing is opaque but the camera.
+ const segment = (points, color, width) => polyline(ctx, points.map(project), color, width);
+ const circle = (polar) => Array.from({length: 121}, (_, k) => {
+ const az = (k * TAU) / 120;
+ return [Math.sin(polar) * Math.cos(az), Math.sin(polar) * Math.sin(az), Math.cos(polar)];
+ });
+ for (const polar of [30, 60, 90, 120, 150]) {
+ segment(circle(polar * DEG), colors.faint, polar === 90 ? 1.2 : 0.7);
+ }
+ for (let k = 0; k < 12; k++) {
+ const az = (k * TAU) / 12;
+ segment(Array.from({length: 61}, (_, t) => {
+ const polar = (t * Math.PI) / 60;
+ return [Math.sin(polar) * Math.cos(az), Math.sin(polar) * Math.sin(az), Math.cos(polar)];
+ }), colors.faint, 0.7);
+ }
+ segment(scene.border, colors.camera, 2);
+ const radius = scene.dotRadius;
+ dots(ctx, scene.rays.filter((r) => !r.valid).map((r) => project(r.dir)), colors.muted, radius, 0.5);
+ dots(ctx, scene.rays.filter((r) => r.valid).map((r) => project(r.dir)), colors.accent, radius, 0.7);
+ for (const line of scene.lines) {
+ segment(line, colors.accent, 0.8);
+ }
+ segment(scene.retinaEdge, colors.accent, 1.6);
+ const gaze = project(scene.gaze);
+ dots(ctx, [gaze], colors.surface, 4.5);
+ ctx.beginPath();
+ ctx.arc(gaze[0], gaze[1], 4.5, 0, TAU);
+ ctx.strokeStyle = colors.accent;
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ // Camera housing at the centre.
+ const body = [[-0.09, -0.06, -0.22], [0.09, -0.06, -0.22], [0.09, 0.06, -0.22], [-0.09, 0.06, -0.22],
+ [-0.09, -0.06, -0.06], [0.09, -0.06, -0.06], [0.09, 0.06, -0.06], [-0.09, 0.06, -0.06]];
+ const faces = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
+ .map((face) => face.map((k) => project(body[k])))
+ .sort((a, b) => b.reduce((s, p) => s + p[2], 0) - a.reduce((s, p) => s + p[2], 0));
+ for (const face of faces) {
+ ctx.beginPath();
+ face.forEach((p, k) => (k === 0 ? ctx.moveTo(p[0], p[1]) : ctx.lineTo(p[0], p[1])));
+ ctx.closePath();
+ ctx.fillStyle = colors.body;
+ ctx.fill();
+ ctx.strokeStyle = colors.faint;
+ ctx.lineWidth = 0.6;
+ ctx.stroke();
+ }
+ };
+
+ // -- Sampling viewer ---------------------------------------------------------------------------------------------
+
+ const control = (label, input, output) => {
+ const wrapper = document.createElement("label");
+ wrapper.className = "fovi-control";
+ const name = document.createElement("span");
+ name.className = "fovi-control-name";
+ name.innerHTML = label;
+ wrapper.append(name, input);
+ if (output) {
+ wrapper.append(output);
+ }
+ return wrapper;
+ };
+
+ const slider = (min, max, step, value) => {
+ const input = document.createElement("input");
+ Object.assign(input, {type: "range", min, max, step, value});
+ return input;
+ };
+
+ const select = (options, value) => {
+ const input = document.createElement("select");
+ for (const [key, text] of options) {
+ input.append(new Option(text, key));
+ }
+ input.value = value;
+ return input;
+ };
+
+ const readout = () => {
+ const output = document.createElement("output");
+ output.className = "fovi-control-value";
+ return output;
+ };
+
+ const formatA = (a) => (a >= 100 ? a.toFixed(0) : a >= 10 ? a.toFixed(1) : a >= 1 ? a.toFixed(2) : a.toFixed(3));
+
+ const initSamplingViewer = (root) => {
+ const defaults = {camera: "fisheye", style: "warped_cartesian_as_grid", logA: Math.log10(0.591), res: 32, tilt: 0, pan: 0};
+ const state = {...defaults};
+ const inputs = {
+ camera: select(Object.entries(cameraModels).map(([key, model]) => [key, model.label]), state.camera),
+ style: select([["warped_cartesian_as_grid", "warped_cartesian_as_grid"], ["isotropic", "isotropic"]], state.style),
+ logA: slider(-2, 3, 0.01, state.logA),
+ res: slider(8, 128, 1, state.res),
+ tilt: slider(-60, 60, 1, state.tilt),
+ pan: slider(-60, 60, 1, state.pan),
+ };
+ const outputs = {logA: readout(), res: readout(), tilt: readout(), pan: readout()};
+ const controls = document.createElement("div");
+ controls.className = "fovi-controls";
+ controls.append(
+ control("Physical camera", inputs.camera),
+ control("foveated_style", inputs.style),
+ control("cmf_a_deg", inputs.logA, outputs.logA),
+ control("foveated_res", inputs.res, outputs.res),
+ control("Gaze tilt", inputs.tilt, outputs.tilt),
+ control("Gaze pan", inputs.pan, outputs.pan),
+ );
+ const reset = document.createElement("button");
+ reset.type = "button";
+ reset.className = "fovi-reset";
+ reset.textContent = "Reset";
+ controls.append(reset);
+ const summary = document.createElement("p");
+ summary.className = "fovi-summary";
+ summary.setAttribute("aria-live", "polite");
+ const panels = document.createElement("div");
+ panels.className = "fovi-panels fovi-panels-stacked";
+ const initialView = {yaw: -0.6, pitch: 0.35};
+ const cameras = Object.entries(cameraModels).map(([key, model]) => {
+ const panel = document.createElement("figure");
+ panel.className = "fovi-panel";
+ const title = document.createElement("figcaption");
+ title.textContent = model.label;
+ const sphere = document.createElement("canvas");
+ sphere.className = "fovi-canvas fovi-sphere";
+ sphere.setAttribute("aria-label", `${model.label}: the retina's rays on the viewing sphere. Drag to rotate; double-click to reset.`);
+ const image = document.createElement("canvas");
+ image.className = "fovi-canvas fovi-image";
+ image.setAttribute("aria-label", `${model.label}: where the retina's samples land in the camera image.`);
+ const labels = document.createElement("div");
+ labels.className = "fovi-panel-labels";
+ labels.innerHTML = "Viewing sphere (drag to rotate)Camera image";
+ const views = document.createElement("div");
+ views.className = "fovi-views";
+ views.append(sphere, image);
+ const note = document.createElement("p");
+ note.className = "fovi-panel-note";
+ // Each camera has its own field of view; the retina spans it.
+ const fovInput = slider(model.fov.min, model.fov.max, 1, model.fov.initial);
+ const fovOutput = readout();
+ const fovControl = control("Field of view", fovInput, fovOutput);
+ fovControl.classList.add("fovi-panel-control");
+ panel.append(title, fovControl, views, labels, note);
+ panels.append(panel);
+ const view = {...initialView};
+ // One camera shows at a time; each keeps its own field of view.
+ const camera = {key, model, panel, sphere, image, note, view, fov: model.fov.initial, fovInput, fovOutput};
+ fovInput.addEventListener("input", () => {
+ camera.fov = Number(fovInput.value);
+ sync();
+ });
+ return camera;
+ });
+ const legend = document.createElement("p");
+ legend.className = "fovi-legend";
+ legend.innerHTML = 'retinal sample'
+ + 'outside the camera image (masked with mask_to_sensor_fov)'
+ + 'camera image border';
+ root.append(controls, summary, panels, legend);
+
+ const samplesCache = new Map();
+ const samplesFor = (fov) => {
+ const a = Math.pow(10, state.logA);
+ const key = `${state.style}/${a}/${state.res}/${fov}`;
+ if (samplesCache.has(key)) {
+ return samplesCache.get(key);
+ }
+ let samples;
+ let description;
+ let resolution = state.res;
+ if (state.style === "isotropic") {
+ resolution = matchedIsotropicRes(fov, a, state.res * state.res);
+ samples = isotropicSamples(fov, a, resolution);
+ description = `${samples.length.toLocaleString("en-US")} samples on ${resolution} rings, published as (num_envs, ${samples.length}, 1, C)`;
+ } else {
+ samples = warpedGrid(fov, a, state.res);
+ const valid = samples.filter((s) => s.valid).length;
+ description = `${state.res} × ${state.res} grid, ${valid.toLocaleString("en-US")} samples inside the circular field, published as (num_envs, ${state.res}, ${state.res}, C)`;
+ }
+ const [centre, edge] = spacing(state.style, fov, a, resolution);
+ const entry = {samples: samples.filter((s) => s.valid), all: samples, description, centre, edge};
+ samplesCache.set(key, entry);
+ if (samplesCache.size > 4) {
+ samplesCache.delete(samplesCache.keys().next().value); // keep the recent settings of both cameras
+ }
+ return entry;
+ };
+
+ // The retina's rays, outline and warped-grid lattice lines (every few rows and columns) for a field of view.
+ const retinaFor = (fov, rotation) => {
+ const data = samplesFor(fov);
+ const rays = data.samples.map((s) => rotate(rotation, ray(s.s, fov)));
+ const edge = Array.from({length: 181}, (_, k) => rotate(rotation, ray([Math.cos((k * TAU) / 180), Math.sin((k * TAU) / 180)], fov)));
+ const lines = [];
+ if (state.style !== "isotropic") {
+ const every = Math.max(1, Math.round(state.res / 16));
+ const index = new Map(data.all.map((s) => [s.i * state.res + s.j, s]));
+ for (let fixed = Math.floor(every / 2); fixed < state.res; fixed += every) {
+ for (const transpose of [false, true]) {
+ let run = [];
+ for (let moving = 0; moving < state.res; moving++) {
+ const s = index.get(transpose ? moving * state.res + fixed : fixed * state.res + moving);
+ if (s && s.valid) {
+ run.push(rotate(rotation, ray(s.s, fov)));
+ } else if (run.length) {
+ lines.push(run);
+ run = [];
+ }
+ }
+ if (run.length) {
+ lines.push(run);
+ }
+ }
+ }
+ }
+ return {data, rays, edge, lines};
+ };
+
+ const redraw = () => {
+ const colors = palette(root);
+ const rotation = gazeRotation(state.tilt, state.pan);
+ const gaze = rotate(rotation, [0, 0, 1]);
+ summary.textContent = "The retina spans the physical camera's field of view; switch the camera or move its slider to compare.";
+ for (const camera of cameras) {
+ if (camera.key !== state.camera) {
+ continue;
+ }
+ const {data, rays, edge, lines} = retinaFor(camera.fov, rotation);
+ const count = rays.length;
+ const dotRadius = Math.max(0.6, Math.min(2.4, 70 / Math.sqrt(count)));
+ const f = camera.model.focal(camera.fov);
+ const projected = rays.map((d) => camera.model.project(d, f));
+ const valid = projected.map(inImage);
+ const inside = valid.filter(Boolean).length;
+ drawSphere(camera.sphere, camera.view, {
+ rays: rays.map((dir, k) => ({dir, valid: valid[k]})),
+ border: imageBorder(camera.model, f),
+ lines,
+ retinaEdge: edge,
+ gaze,
+ dotRadius,
+ }, colors);
+ drawImagePlane(camera.image, projected, valid, edge.map((d) => camera.model.project(d, f)), camera.model.project(gaze, f), dotRadius, colors);
+ camera.note.innerHTML = `${data.description}. Sample spacing: ${data.centre.toPrecision(2)}° at the fixation, `
+ + `${data.edge.toPrecision(2)}° at the edge of the ${camera.fov}° field. `
+ + `${inside.toLocaleString("en-US")} of ${count.toLocaleString("en-US")} samples inside the image (${((100 * inside) / count).toFixed(0)}%).`;
+ }
+ };
+
+ const drawImagePlane = (canvas, projected, valid, edge, gaze, radius, colors) => {
+ const {ctx, w, h} = fitCanvas(canvas);
+ const margin = 0.18;
+ const scale = Math.min(w, h) / (SIDE * (1 + 2 * margin));
+ const ox = (w - SIDE * scale) / 2;
+ const oy = (h - SIDE * scale) / 2;
+ const map = (p) => [ox + p[0] * scale, oy + p[1] * scale];
+ ctx.fillStyle = colors.surface;
+ ctx.fillRect(ox, oy, SIDE * scale, SIDE * scale);
+ ctx.strokeStyle = colors.camera;
+ ctx.lineWidth = 2;
+ ctx.strokeRect(ox, oy, SIDE * scale, SIDE * scale);
+ polyline(ctx, [map([SIDE / 2, 0]), map([SIDE / 2, SIDE])], colors.faint, 0.7);
+ polyline(ctx, [map([0, SIDE / 2]), map([SIDE, SIDE / 2])], colors.faint, 0.7);
+ const visible = (p) => p !== null && p[0] > -SIDE && p[0] < 2 * SIDE && p[1] > -SIDE && p[1] < 2 * SIDE;
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(0, 0, w, h);
+ ctx.clip();
+ dots(ctx, projected.filter((p, k) => !valid[k] && visible(p)).map(map), colors.muted, radius, 0.5);
+ dots(ctx, projected.filter((p, k) => valid[k]).map(map), colors.accent, radius, 0.75);
+ const edgeRuns = [];
+ let run = [];
+ for (const p of edge) {
+ if (visible(p)) {
+ run.push(map(p));
+ } else if (run.length) {
+ edgeRuns.push(run);
+ run = [];
+ }
+ }
+ edgeRuns.push(run);
+ for (const r of edgeRuns) {
+ polyline(ctx, r, colors.accent, 1.4);
+ }
+ if (gaze && visible(gaze)) {
+ const g = map(gaze);
+ ctx.beginPath();
+ ctx.arc(g[0], g[1], 4.5, 0, TAU);
+ ctx.fillStyle = colors.surface;
+ ctx.fill();
+ ctx.strokeStyle = colors.accent;
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ }
+ ctx.restore();
+ };
+
+ const sync = () => {
+ const a = Math.pow(10, state.logA);
+ outputs.logA.textContent = `${formatA(a)}°`;
+ outputs.res.textContent = state.res;
+ for (const camera of cameras) {
+ camera.fovOutput.textContent = `${camera.fov}°`;
+ camera.panel.hidden = camera.key !== state.camera;
+ }
+ outputs.tilt.textContent = `${state.tilt}°`;
+ outputs.pan.textContent = `${state.pan}°`;
+ redraw();
+ };
+ for (const [name, input] of Object.entries(inputs)) {
+ input.addEventListener("input", () => {
+ state[name] = name === "style" || name === "camera" ? input.value : Number(input.value);
+ sync();
+ });
+ }
+ reset.addEventListener("click", () => {
+ Object.assign(state, defaults);
+ for (const [name, input] of Object.entries(inputs)) {
+ input.value = state[name];
+ }
+ for (const camera of cameras) {
+ Object.assign(camera.view, initialView);
+ camera.fov = camera.model.fov.initial;
+ camera.fovInput.value = camera.fov;
+ }
+ sync();
+ });
+ for (const camera of cameras) {
+ bindOrbit(camera.sphere, camera.view, redraw, initialView);
+ }
+ new ResizeObserver(() => redraw()).observe(panels);
+ sync();
+ };
+
+ // -- Pooling viewer ----------------------------------------------------------------------------------------------
+
+ // Upright layout of a canonical warped grid (fovi's sampling_as_grid): row = res - 1 - j, column = i.
+ // Pooling windows follow fovi's GridPoolingLayer: stride = resolution multiple, SAME-style padding.
+ const poolingWindow = (lowRes, mult, side, row, col) => {
+ const stride = mult;
+ const before = Math.floor((side - stride) / 2);
+ const cells = [];
+ for (let dr = 0; dr < side; dr++) {
+ for (let dc = 0; dc < side; dc++) {
+ const r = row * stride - before + dr;
+ const c = col * stride - before + dc;
+ if (r >= 0 && r < lowRes * mult && c >= 0 && c < lowRes * mult) {
+ cells.push([r, c]);
+ }
+ }
+ }
+ return cells;
+ };
+
+ const initPoolingViewer = (root) => {
+ const FOV = Number(root.dataset.fov || 90);
+ const A = Number(root.dataset.cmfA || 2);
+ const LOW = Number(root.dataset.res || 16);
+ const defaults = {style: "warped_cartesian_as_grid", mult: 2, side: 2, row: 8, col: 11, k: 4, space: "geodesic", unit: 120};
+ const state = {...defaults};
+ const inputs = {
+ style: select([["warped_cartesian_as_grid", "warped_cartesian_as_grid"], ["isotropic", "isotropic"]], state.style),
+ mult: select([["2", "2"], ["3", "3"], ["4", "4"]], String(state.mult)),
+ side: slider(1, 9, 1, state.side),
+ row: slider(0, LOW - 1, 1, state.row),
+ col: slider(0, LOW - 1, 1, state.col),
+ k: slider(1, 32, 1, state.k),
+ space: select([["geodesic", "geodesic (default)"], ["visual", "visual field (False)"]], state.space),
+ unit: slider(0, 1, 1, state.unit),
+ };
+ const outputs = {side: readout(), row: readout(), col: readout(), k: readout(), unit: readout()};
+ const controls = document.createElement("div");
+ controls.className = "fovi-controls";
+ const gridControls = [
+ control("Window side (pool_k = side²)", inputs.side, outputs.side),
+ control("Pooled sample row", inputs.row, outputs.row),
+ control("Pooled sample column", inputs.col, outputs.col),
+ ];
+ const isotropicControls = [
+ control("pool_k (neighbours)", inputs.k, outputs.k),
+ control("pool_sample_cortex", inputs.space),
+ control("Pooled sample", inputs.unit, outputs.unit),
+ ];
+ controls.append(control("foveated_style", inputs.style), control("pool_res_mult", inputs.mult), ...gridControls, ...isotropicControls);
+ const reset = document.createElement("button");
+ reset.type = "button";
+ reset.className = "fovi-reset";
+ reset.textContent = "Reset";
+ controls.append(reset);
+ const summary = document.createElement("p");
+ summary.className = "fovi-summary";
+ summary.setAttribute("aria-live", "polite");
+ const panels = document.createElement("div");
+ panels.className = "fovi-panels fovi-panels-three";
+ const makePanel = (title, label) => {
+ const panel = document.createElement("figure");
+ panel.className = "fovi-panel";
+ const caption = document.createElement("figcaption");
+ caption.textContent = title;
+ const canvas = document.createElement("canvas");
+ canvas.className = "fovi-canvas fovi-square";
+ canvas.setAttribute("aria-label", label);
+ panel.append(caption, canvas);
+ panels.append(panel);
+ return {panel, canvas};
+ };
+ const nativeView = makePanel("Published grid (click a sample)", "The pooled grid and its photoreceptor grid in the published image layout. Click a pooled sample to select it.");
+ const fieldView = makePanel("Visual field (click a sample)", "Photoreceptor and pooled samples by visual angle. Click a pooled sample to select it.");
+ const zoomView = makePanel("Around the selected sample", "The selected pooled sample's neighbourhood, enlarged.");
+ const legend = document.createElement("p");
+ legend.className = "fovi-legend";
+ legend.innerHTML = 'photoreceptor'
+ + 'pooled into the selected sample'
+ + 'pooled sample'
+ + `Fixed: ${FOV}° field, cmf_a_deg=${A}, foveated_res=${LOW}.`;
+ root.append(controls, summary, panels, legend);
+
+ // fovi's pooling neighbourhoods for the isotropic retina, exported with the camera's own helpers.
+ let isotropicTables = null;
+ if (TABLES_URL) {
+ fetch(TABLES_URL)
+ .then((response) => (response.ok ? response.json() : Promise.reject(new Error(response.statusText))))
+ .then((data) => {
+ if (data.fov !== FOV || data.cmfA !== A || data.res !== LOW) {
+ throw new Error("the exported tables describe another retina");
+ }
+ isotropicTables = data;
+ if (state.style === "isotropic") {
+ sync();
+ }
+ })
+ .catch((error) => {
+ isotropicTables = {error: String(error.message || error)};
+ if (state.style === "isotropic") {
+ sync();
+ }
+ });
+ }
+
+ // Grid retina: samples keyed by their upright (row, column) in the published image.
+ const gridLayout = (res) => {
+ const samples = warpedGrid(FOV, A, res).map((s) => ({...s, row: res - 1 - s.j, col: s.i}));
+ return {samples, at: new Map(samples.map((s) => [`${s.row},${s.col}`, s]))};
+ };
+ const layouts = new Map();
+ const layoutFor = () => {
+ const key = `${state.style}/${state.mult}`;
+ if (layouts.has(key)) {
+ return layouts.get(key);
+ }
+ let layout;
+ if (state.style === "isotropic") {
+ const rings = matchedIsotropicRes(FOV, A, LOW * LOW);
+ const highRings = Math.round(state.mult * rings);
+ layout = {
+ rings,
+ highRings,
+ low: isotropicSamples(FOV, A, rings),
+ high: isotropicSamples(FOV, A, highRings),
+ };
+ } else {
+ layout = {low: gridLayout(LOW), high: gridLayout(LOW * state.mult)};
+ }
+ layouts.set(key, layout);
+ return layout;
+ };
+
+ // The selected pooled sample, the photoreceptors it pools, and a description, for the current style.
+ const selection = (layout) => {
+ if (state.style !== "isotropic") {
+ const unit = layout.low.at.get(`${state.row},${state.col}`);
+ const cells = poolingWindow(LOW, state.mult, state.side, state.row, state.col);
+ const members = cells.map(([r, c]) => layout.high.at.get(`${r},${c}`)).filter((s) => s.valid);
+ const k = state.side * state.side;
+ const text = `pool_k=${k} (window side ${state.side}, stride ${state.mult}); the photoreceptor grid is `
+ + `${LOW * state.mult} × ${LOW * state.mult}`
+ + (k < state.mult * state.mult ? "; a window smaller than the stride skips photoreceptors." : ".");
+ return {unit, members, valid: unit.valid && members.length > 0, text, label: `(${state.row}, ${state.col})`};
+ }
+ const unit = layout.low[state.unit];
+ const table = isotropicTable(layout);
+ if (!table) {
+ return {unit, members: [], valid: false, pending: true, text: "", label: `${state.unit}`};
+ }
+ const members = table.slice(0, state.k).filter((index) => index >= 0).map((index) => layout.high[index]);
+ const text = `pool_k=${state.k} nearest photoreceptors ${state.space === "geodesic" ? "along the cortex" : "in the visual field"}; `
+ + `${layout.high.length.toLocaleString("en-US")} photoreceptors on ${layout.highRings} rings pool into ${layout.low.length} samples on ${layout.rings} rings`
+ + ` (default pool_k ${Math.round(layout.high.length / layout.low.length)}).`;
+ return {unit, members, valid: members.length > 0, text, label: `${state.unit}`};
+ };
+
+ // The selected sample's neighbours, nearest first, from fovi's table for the chosen space.
+ const isotropicTable = (layout) => {
+ const entry = isotropicTables && !isotropicTables.error && isotropicTables.mult[String(state.mult)];
+ if (!entry) {
+ return null;
+ }
+ if (entry.count !== layout.high.length || isotropicTables.count !== layout.low.length) {
+ isotropicTables = {error: "the exported tables do not match this retina"};
+ return null;
+ }
+ return entry[state.space].slice(state.unit * entry.kMax, (state.unit + 1) * entry.kMax);
+ };
+
+ const fieldTransform = (w, h, centre, radius) => {
+ const scale = (Math.min(w, h) / 2 - 8) / radius;
+ return (s) => [w / 2 + (s[0] - centre[0]) * scale, h / 2 - (s[1] - centre[1]) * scale];
+ };
+
+ const redraw = () => {
+ const colors = palette(root);
+ const layout = layoutFor();
+ const isotropic = state.style === "isotropic";
+ const lowSamples = isotropic ? layout.low : layout.low.samples;
+ const highSamples = isotropic ? layout.high : layout.high.samples;
+ const chosen = selection(layout);
+ const members = new Set(chosen.members);
+ const {unit} = chosen;
+ nativeView.panel.hidden = isotropic;
+ // Published-grid view: photoreceptor cells, pooled cell borders, and the window.
+ if (!isotropic) {
+ const highRes = LOW * state.mult;
+ const {ctx, w, h} = fitCanvas(nativeView.canvas);
+ const size = Math.min(w, h) - 8;
+ const ox = (w - size) / 2;
+ const oy = (h - size) / 2;
+ const cell = size / highRes;
+ const windowCells = new Set(poolingWindow(LOW, state.mult, state.side, state.row, state.col).map(([r, c]) => `${r},${c}`));
+ for (const s of highSamples) {
+ const member = windowCells.has(`${s.row},${s.col}`);
+ ctx.fillStyle = member ? colors.highlight : s.valid ? colors.faint : colors.surface;
+ ctx.globalAlpha = member && !s.valid ? 0.35 : 1;
+ ctx.fillRect(ox + s.col * cell + 0.5, oy + s.row * cell + 0.5, Math.max(cell - 1, 0.5), Math.max(cell - 1, 0.5));
+ }
+ ctx.globalAlpha = 1;
+ for (let k = 0; k <= LOW; k++) {
+ polyline(ctx, [[ox + (k * size) / LOW, oy], [ox + (k * size) / LOW, oy + size]], colors.muted, 0.6);
+ polyline(ctx, [[ox, oy + (k * size) / LOW], [ox + size, oy + (k * size) / LOW]], colors.muted, 0.6);
+ }
+ ctx.strokeStyle = colors.accent;
+ ctx.lineWidth = 2.4;
+ ctx.strokeRect(ox + (state.col * size) / LOW, oy + (state.row * size) / LOW, size / LOW, size / LOW);
+ nativeView.canvas.onclick = (event) => {
+ const box = nativeView.canvas.getBoundingClientRect();
+ const col = Math.floor(((event.clientX - box.left - ox) / size) * LOW);
+ const row = Math.floor(((event.clientY - box.top - oy) / size) * LOW);
+ if (row >= 0 && row < LOW && col >= 0 && col < LOW) {
+ choose({row, col});
+ }
+ };
+ }
+ const zoomRegion = () => {
+ const points = chosen.members.map((s) => s.s);
+ points.push(unit.s);
+ const xs = points.map((p) => p[0]);
+ const ys = points.map((p) => p[1]);
+ const centre = [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2];
+ const extent = Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys), 0.002);
+ return [centre, extent * 1.1];
+ };
+ // Visual-field views: the whole retina, and the selected sample's neighbourhood.
+ const drawField = (canvas, centre, radius, showZoomBox) => {
+ const {ctx, w, h} = fitCanvas(canvas);
+ const map = fieldTransform(w, h, centre, radius);
+ const scale = (Math.min(w, h) / 2 - 8) / radius;
+ const dotHigh = Math.max(0.7, Math.min(3, scale * 0.004 * Math.sqrt(1024 / highSamples.length) * 6));
+ const highPoints = highSamples.filter((s) => s.valid);
+ dots(ctx, highPoints.filter((s) => !members.has(s)).map((s) => map(s.s)), colors.muted, dotHigh, 0.55);
+ dots(ctx, highPoints.filter((s) => members.has(s)).map((s) => map(s.s)), colors.highlight, dotHigh * 1.4, 1);
+ dots(ctx, lowSamples.filter((s) => s.valid).map((s) => map(s.s)), colors.accent, dotHigh * 1.2, 0.9);
+ const u = map(unit.s);
+ ctx.beginPath();
+ ctx.arc(u[0], u[1], dotHigh * 1.2 + 4, 0, TAU);
+ ctx.strokeStyle = colors.accent;
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ polyline(ctx, Array.from({length: 181}, (_, k) => map([Math.cos((k * TAU) / 180), Math.sin((k * TAU) / 180)])), colors.camera, 1.2);
+ if (showZoomBox) {
+ const [zc, zr] = zoomRegion();
+ const corner = map([zc[0] - zr, zc[1] + zr]);
+ ctx.strokeStyle = colors.ink;
+ ctx.setLineDash([3, 3]);
+ ctx.lineWidth = 1;
+ ctx.strokeRect(corner[0], corner[1], 2 * zr * scale, 2 * zr * scale);
+ ctx.setLineDash([]);
+ }
+ return map;
+ };
+ const map = drawField(fieldView.canvas, [0, 0], 1, true);
+ fieldView.canvas.onclick = (event) => {
+ const box = fieldView.canvas.getBoundingClientRect();
+ const x = event.clientX - box.left;
+ const y = event.clientY - box.top;
+ let best = null;
+ lowSamples.forEach((s, index) => {
+ if (!s.valid) {
+ return;
+ }
+ const p = map(s.s);
+ const d = Math.hypot(p[0] - x, p[1] - y);
+ if (!best || d < best.d) {
+ best = {d, s, index};
+ }
+ });
+ if (best) {
+ choose(isotropic ? {unit: best.index} : {row: best.s.row, col: best.s.col});
+ }
+ };
+ const [zc, zr] = zoomRegion();
+ drawField(zoomView.canvas, zc, zr, false);
+ const ecc = Math.hypot(unit.s[0], unit.s[1]) * (FOV / 2);
+ const span = chosen.members.length
+ ? Math.max(...chosen.members.map((s) => Math.hypot(s.s[0] - unit.s[0], s.s[1] - unit.s[1]))) * (FOV / 2) * 2
+ : 0;
+ if (chosen.pending) {
+ const reason = isotropicTables && isotropicTables.error ? `could not be loaded (${isotropicTables.error})` : "are loading";
+ summary.innerHTML = `fovi's pooling neighbourhoods ${reason}.`;
+ return;
+ }
+ summary.innerHTML = `Pooled sample ${chosen.label} at ${ecc.toFixed(2)}° eccentricity`
+ + (chosen.valid
+ ? ` averages ${chosen.members.length} photoreceptors spanning about ${span.toPrecision(2)}°. `
+ : " lies outside the retina, so the camera publishes zero there. ")
+ + chosen.text;
+ };
+
+ const choose = (selected) => {
+ Object.assign(state, selected);
+ for (const name of Object.keys(selected)) {
+ inputs[name].value = state[name];
+ }
+ sync();
+ };
+
+ const sync = () => {
+ const isotropic = state.style === "isotropic";
+ for (const element of gridControls) {
+ element.hidden = isotropic;
+ }
+ for (const element of isotropicControls) {
+ element.hidden = !isotropic;
+ }
+ if (isotropic) {
+ const layout = layoutFor();
+ inputs.unit.max = layout.low.length - 1;
+ state.unit = Math.min(state.unit, layout.low.length - 1);
+ inputs.unit.value = state.unit;
+ inputs.k.max = 2 * state.mult * state.mult;
+ state.k = Math.min(state.k, Number(inputs.k.max));
+ inputs.k.value = state.k;
+ }
+ outputs.side.textContent = `${state.side} (pool_k=${state.side * state.side})`;
+ outputs.row.textContent = state.row;
+ outputs.col.textContent = state.col;
+ outputs.k.textContent = state.k;
+ outputs.unit.textContent = state.unit;
+ redraw();
+ };
+ inputs.style.addEventListener("input", () => {
+ state.style = inputs.style.value;
+ sync();
+ });
+ inputs.space.addEventListener("input", () => {
+ state.space = inputs.space.value;
+ sync();
+ });
+ inputs.mult.addEventListener("input", () => {
+ // Keep the default neighbourhood when it was in use: pool_res_mult squared photoreceptors.
+ const defaultSide = state.side === state.mult;
+ const defaultK = state.k === state.mult * state.mult;
+ state.mult = Number(inputs.mult.value);
+ if (defaultSide) {
+ state.side = state.mult;
+ inputs.side.value = state.side;
+ }
+ if (defaultK) {
+ state.k = state.mult * state.mult;
+ }
+ sync();
+ });
+ for (const name of ["side", "row", "col", "k", "unit"]) {
+ inputs[name].addEventListener("input", () => {
+ state[name] = Number(inputs[name].value);
+ sync();
+ });
+ }
+ reset.addEventListener("click", () => {
+ Object.assign(state, defaults);
+ for (const [name, input] of Object.entries(inputs)) {
+ input.value = state[name];
+ }
+ sync();
+ });
+ new ResizeObserver(() => redraw()).observe(panels);
+ sync();
+ };
+
+ const initialize = () => {
+ document.querySelectorAll("[data-fovi-sampling-viewer]").forEach(initSamplingViewer);
+ document.querySelectorAll("[data-fovi-pooling-viewer]").forEach(initPoolingViewer);
+ };
+
+ // Exposed for the documentation's geometry checks.
+ window.FoviViewerGeometry = {warpedGrid, isotropicRings, matchedIsotropicRes, isotropicSamples, ray, gazeRotation, poolingWindow};
+
+ if (typeof document !== "undefined") {
+ if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", initialize);
+ } else {
+ initialize();
+ }
+ }
+})();
diff --git a/docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg b/docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg
new file mode 100644
index 000000000000..40d6786c3d16
Binary files /dev/null and b/docs/source/_static/overview/sensors/foveated_camera_active_gaze.jpg differ
diff --git a/docs/source/_static/overview/sensors/foveated_camera_gaze_mask.jpg b/docs/source/_static/overview/sensors/foveated_camera_gaze_mask.jpg
new file mode 100644
index 000000000000..c6f044485b99
Binary files /dev/null and b/docs/source/_static/overview/sensors/foveated_camera_gaze_mask.jpg differ
diff --git a/docs/source/_static/overview/sensors/foveated_camera_overview.jpg b/docs/source/_static/overview/sensors/foveated_camera_overview.jpg
new file mode 100644
index 000000000000..f8f0e9a8d6c5
Binary files /dev/null and b/docs/source/_static/overview/sensors/foveated_camera_overview.jpg differ
diff --git a/docs/source/_static/overview/sensors/foveated_camera_pooling.jpg b/docs/source/_static/overview/sensors/foveated_camera_pooling.jpg
new file mode 100644
index 000000000000..d5c0ac8ef1bd
Binary files /dev/null and b/docs/source/_static/overview/sensors/foveated_camera_pooling.jpg differ
diff --git a/docs/source/_static/overview/sensors/foveated_camera_renderers.jpg b/docs/source/_static/overview/sensors/foveated_camera_renderers.jpg
new file mode 100644
index 000000000000..f4d013389965
Binary files /dev/null and b/docs/source/_static/overview/sensors/foveated_camera_renderers.jpg differ
diff --git a/docs/source/_static/overview/sensors/foveated_camera_strength.jpg b/docs/source/_static/overview/sensors/foveated_camera_strength.jpg
new file mode 100644
index 000000000000..860c36eca940
Binary files /dev/null and b/docs/source/_static/overview/sensors/foveated_camera_strength.jpg differ
diff --git a/docs/source/api/index.rst b/docs/source/api/index.rst
index 7a927acce711..9fa50b56d6ef 100644
--- a/docs/source/api/index.rst
+++ b/docs/source/api/index.rst
@@ -93,6 +93,19 @@ The following modules are available in the ``isaaclab_contrib`` extension:
rl
sensors
+isaaclab_fovi extension
+-----------------------
+
+The following modules are available in the ``isaaclab_fovi`` extension:
+
+.. currentmodule:: isaaclab_fovi
+
+.. autosummary::
+ :toctree: lab_fovi
+
+ mdp
+ sensors
+
isaaclab_tasks extension
------------------------
diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst
new file mode 100644
index 000000000000..779ad564d64a
--- /dev/null
+++ b/docs/source/api/lab_fovi/isaaclab_fovi.mdp.rst
@@ -0,0 +1,39 @@
+isaaclab_fovi.mdp
+=================
+
+.. automodule:: isaaclab_fovi.mdp
+
+ .. rubric:: Classes
+
+ .. autosummary::
+
+ GazeAction
+ GazeActionCfg
+ gaze_teacher_labels
+
+ .. rubric:: Functions
+
+ .. autosummary::
+
+ gaze_state
+
+Actions
+-------
+
+.. autoclass:: GazeAction
+ :members:
+ :show-inheritance:
+
+.. autoclass:: GazeActionCfg
+ :members:
+ :inherited-members:
+ :show-inheritance:
+ :exclude-members: __init__, class_type
+
+Observations
+------------
+
+.. autofunction:: gaze_state
+
+.. autoclass:: gaze_teacher_labels
+ :show-inheritance:
diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst b/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst
new file mode 100644
index 000000000000..32c513aace16
--- /dev/null
+++ b/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst
@@ -0,0 +1,41 @@
+isaaclab_fovi.sensors
+=====================
+
+.. automodule:: isaaclab_fovi.sensors
+
+ .. rubric:: Classes
+
+ .. autosummary::
+
+ FoveatedCamera
+ FoveatedCameraCfg
+ FoveatedNewtonCamera
+ FoveatedRTXCamera
+
+
+Foveated Camera
+---------------
+
+.. autoclass:: FoveatedCamera
+ :members:
+ :show-inheritance:
+
+.. autoclass:: FoveatedCameraCfg
+ :members:
+ :inherited-members:
+ :show-inheritance:
+ :exclude-members: __init__, class_type
+
+Renderer Implementations
+------------------------
+
+Constructing :class:`FoveatedCamera` returns one of the following implementations, selected by the renderer in
+:attr:`FoveatedCameraCfg.renderer_cfg`.
+
+.. autoclass:: FoveatedNewtonCamera
+ :members:
+ :show-inheritance:
+
+.. autoclass:: FoveatedRTXCamera
+ :members:
+ :show-inheritance:
diff --git a/docs/source/concepts/sensors/camera.rst b/docs/source/concepts/sensors/camera.rst
index 501192cf5bcc..c56585a11997 100644
--- a/docs/source/concepts/sensors/camera.rst
+++ b/docs/source/concepts/sensors/camera.rst
@@ -13,6 +13,9 @@ configuration can work across supported physics and rendering backends.
Isaac Lab batches camera views from cloned environments into tiled render passes.
Each requested output is returned as one GPU buffer with a separate image per view.
+For a retina-like image that is dense where a movable gaze points, see the experimental
+:doc:`foveated camera `.
+
For silent black or corrupted RTX camera images when scaling the workload, see
:ref:`known-issues-rtx-buffer-limit`.
diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst
new file mode 100644
index 000000000000..a37614cb0ef5
--- /dev/null
+++ b/docs/source/experimental-features/foveated_camera.rst
@@ -0,0 +1,133 @@
+.. _concepts_sensors_foveated_camera:
+
+.. currentmodule:: isaaclab_fovi
+
+Foveated Camera
+===============
+
+A :class:`~sensors.FoveatedCamera` samples densely at its fixation and sparsely in the periphery.
+The `fovi `__ library places the viewing rays. Moving the gaze rotates them
+relative to the physical camera's mount. The ``foveated-camera`` example lets you explore the scene below by moving
+the camera and steering its gaze; the bracketed options render the retina with OVRTX, whose first frame can take
+several minutes with a cold shader cache:
+
+.. code-block:: bash
+
+ uv run --extra fovi [--extra ovrtx] isaaclab example foveated-camera [renderer=ovrtx]
+
+The Newton viewer shows the retina. A panel shows the fisheye on a curved viewing sphere beside a magnified retina:
+the green lens boundary follows the camera mount, and the blue gaze circle and sampling grid show the magnified
+retina's coverage. Use WASD or the arrow keys to move and Q/E to lower or raise the camera. I/K tilt the gaze and J/L
+pan it; O/U magnify the panel's retina and zoom back out; H shows or hides the viewer controls. Pass
+``--target power_drill`` to start fixating the drill, or ``env.scene.eye.cmf_a_deg=1000`` for a matched, nearly
+uniform retina.
+
+.. 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.
+
+ A foveated retina behind a 180° fisheye lens, path-traced with OVRTX. Each pair shows the retina's rays on the
+ viewing sphere, faded outside the retina's field, and the rendered image. Fixating the drill puts part of the
+ retina outside the camera's view, and those samples render black.
+
+Sampling
+--------
+
+The retina places its samples by visual angle, with a density that falls off from the fixation as the cortical
+magnification function (CMF) of human vision does. At eccentricity :math:`r` from the fixation, in degrees,
+
+.. math::
+
+ M(r) = \frac{1}{r + a}, \qquad w(r) = \int_0^r M(t)\,dt = \log\left(1 + \frac{r}{a}\right),
+
+where :math:`a` is :attr:`~sensors.FoveatedCameraCfg.cmf_a_deg`, :math:`M` is the cortical distance per degree of
+visual angle, and :math:`w` is the cortical distance from the fixation. Samples spaced evenly in :math:`w` are dense
+near the fixation and sparse far from it.
+
+The default ``foveated_style="warped_cartesian_as_grid"`` warps an :math:`N \times N` lattice, with :math:`N` =
+:attr:`~sensors.FoveatedCameraCfg.foveated_res`, so that its radius :math:`\rho \in [0, 1]` is proportional to
+:math:`w`. A lattice point at radius :math:`\rho` samples the eccentricity
+
+.. math::
+
+ r(\rho) = a\left[\left(1 + \frac{r_{\max}}{a}\right)^{\rho} - 1\right],
+
+where :math:`r_{\max}` is half the retina's field of view, and the camera publishes the lattice as an upright
+``(num_envs, N, N, channels)`` image.
+
+``foveated_style="isotropic"`` instead places rings evenly in :math:`w`, and gives each ring as many samples as keep
+neighbours about equally far apart in every direction:
+
+.. math::
+
+ n_k = \left\lceil \frac{2\pi \rho_k}{\Delta r_k} \right\rceil,
+
+where :math:`\rho_k` is ring :math:`k`'s radius on the viewing sphere and :math:`\Delta r_k` its distance to the
+neighbouring rings. The camera publishes at most :math:`N^2` samples, ``(num_envs, num_samples, 1, channels)``.
+These samples lie on an isotropic manifold in 3D, the viewing sphere, rather than on a 2D image grid, so networks
+process them with kNN convolution, as in `fovi `__. The isotropic mode is supported
+on Newton Warp and OptiX, but not yet recommended on the RTX renderers, whose lens textures and post-processing
+need a 2D grid.
+
+The viewer shows both styles for an equidistant fisheye or a pinhole camera.
+
+.. raw:: html
+
+
+
+Camera and gaze
+---------------
+
+Declare a :class:`~sensors.FoveatedCameraCfg` directly on the scene. For example, a 32 × 32 RGB retina and a
+pooled variant can share the same camera setup.
+
+.. code-block:: python
+
+ from isaaclab.sim import PinholeCameraCfg
+ from isaaclab_fovi.sensors import FoveatedCameraCfg
+
+ camera = FoveatedCameraCfg(
+ prim_path="{ENV_REGEX_NS}/Camera",
+ spawn=PinholeCameraCfg(),
+ foveated_res=32,
+ )
+ pooled_camera = camera.replace(pool_enabled=True)
+
+Newton Warp and OptiX render the retinal rays directly. Isaac RTX and OVRTX use lens lookup textures.
+
+The retinal field of view defaults to the angle across the short side of the physical image. The camera
+uses ideal pinhole optics or supported OpenCV distortion from ``spawn``. Supply
+:attr:`~sensors.FoveatedCameraCfg.camera_model` for explicit calibration or an existing camera prim.
+Use :attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` to shrink this window and
+:attr:`~sensors.FoveatedCameraCfg.image_rotation_deg` to compensate for mount roll.
+
+Call ``camera.set_gaze_angles(angles)`` with shape ``(num_envs, 2)`` in tilt, pan order and in degrees.
+Positive tilt looks up and positive pan looks left. :meth:`~sensors.FoveatedCamera.get_world_poses`
+reports the mount pose. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero rays that fall
+outside the physical image as the gaze moves.
+
+Pooling
+-------
+
+Enable :attr:`~sensors.FoveatedCameraCfg.pool_enabled` to render a denser set of rays and pool their values
+into the published retina. Grid styles pool windows, while sample sets pool nearest neighbours.
+The neighbour metric applies to nearest-neighbour pooling, and Gaussian sigma applies to Gaussian pooling.
+The sensor mask excludes rays outside the physical image from the reduction. Segmentation selects the
+modal label in its original dtype.
+
+.. raw:: html
+
+
+
+Active gaze Cartpole
+--------------------
+
+``IsaacContrib-Cartpole-Camera-Fovi`` uses a 32 × 32 retina and two bounded gaze actions. A pole-tip teacher
+supervises the gaze-action means during training. The gaze dimensions use fixed exploration noise.
+Select ``presets=depth`` for depth images.
+
+.. code-block:: bash
+
+ uv run --extra fovi --extra rsl-rl isaaclab train --rl_library rsl_rl --task IsaacContrib-Cartpole-Camera-Fovi
+
+For other manager-based tasks, use :class:`~mdp.GazeActionCfg` to move gaze, :func:`~mdp.gaze_state` to
+observe it, and :class:`~mdp.gaze_teacher_labels` for optional supervision.
diff --git a/docs/source/how-to/configure_rendering.rst b/docs/source/how-to/configure_rendering.rst
index 18e835ffe0e6..a5334082e8e6 100644
--- a/docs/source/how-to/configure_rendering.rst
+++ b/docs/source/how-to/configure_rendering.rst
@@ -134,6 +134,12 @@ that legacy renderer; use Newton Warp or OVRTX for new Newton and kit-less workl
preserve the color output; the ``simple_shading_*`` output remains available but does not receive
the RTX Minimal performance improvement.
+Render a foveated camera
+------------------------
+
+The experimental :doc:`foveated camera ` (``fovi`` extra) uses the
+same renderer configurations as a regular camera.
+
Overriding Specific Rendering Settings
--------------------------------------
diff --git a/docs/source/isaaclab/installation.rst b/docs/source/isaaclab/installation.rst
index ee176661e500..020776a90928 100644
--- a/docs/source/isaaclab/installation.rst
+++ b/docs/source/isaaclab/installation.rst
@@ -442,6 +442,9 @@ have dedicated commands below.
- The corresponding visualizer.
* - ``mimic`` / ``teleop``
- Isaac Lab Mimic / XR teleoperation. The wheel's ``mimic`` extra does not include Robomimic.
+ * - ``fovi``
+ - The experimental :doc:`foveated camera `
+ (``isaaclab_fovi``), with the `fovi `__ sampling library.
* - ``tetrahedralization`` / ``video``
- Mesh tetrahedralization / video recording.
* - ``leapp``
@@ -455,8 +458,8 @@ have dedicated commands below.
- Developer test tooling.
Use ``all`` for the curated list above. Isaac Sim, standalone importers, specialized extras
-(``optix``, ``skrl-jax``, ``rlinf``, ``mimic``, ``teleop``, ``tetrahedralization``, ``video``,
-``leapp``), and the developer ``test`` tooling remain opt-in.
+(``optix``, ``skrl-jax``, ``rlinf``, ``mimic``, ``teleop``, ``fovi``, ``tetrahedralization``,
+``video``, ``leapp``), and the developer ``test`` tooling remain opt-in.
.. note::
diff --git a/docs/source/refs/troubleshooting.rst b/docs/source/refs/troubleshooting.rst
index 8c5b7abb9d45..252bfdf6f0aa 100644
--- a/docs/source/refs/troubleshooting.rst
+++ b/docs/source/refs/troubleshooting.rst
@@ -41,6 +41,10 @@ install time. Most packages cannot be deselected at all.
checkout's uv environment.
* - ``isaaclab_mimic``, ``isaaclab_teleop``
- Optional integrations. Select the ``mimic`` or ``teleop`` extra for your workflow.
+ * - ``isaaclab_fovi``, ``fovi``
+ - The optional, experimental foveated camera. Select the ``fovi`` extra, for example
+ ``uv run --extra fovi isaaclab example foveated-camera``. Without it, the
+ ``IsaacContrib-Cartpole-Camera-Fovi`` task is not registered.
* - ``rsl_rl``, ``rl_games``, ``skrl``, ``stable_baselines3``
- ``rsl_rl`` is installed by default. Select ``rl-games``, ``skrl``, or ``sb3``
for the other frameworks, for example ``uv run --extra skrl isaaclab train ...``.
diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py
new file mode 100644
index 000000000000..d991cfe032e8
--- /dev/null
+++ b/examples/sensors/foveated_camera.py
@@ -0,0 +1,446 @@
+# 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
+
+"""Explore a cluttered scene through the experimental foveated camera.
+
+The viewer shows the camera's retina; a panel shows the gaze on the viewing sphere beside a magnified retina.
+Use WASD or the arrow keys to move, and Q/E to lower or raise the camera.
+I/K tilt the gaze and J/L pan it. O/U magnify the panel's retina and zoom back out.
+Press H to show or hide the viewer controls.
+Use --target to choose where the retina looks at launch.
+
+.. code-block:: bash
+
+ uv run --extra fovi isaaclab example foveated-camera
+ 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
+"""
+
+from __future__ import annotations
+
+import argparse
+import logging
+import math
+import time
+from collections.abc import Callable
+
+import gymnasium as gym
+import numpy as np
+import torch
+import warp as wp
+from fovi.sensing.projection import gaze_rotation
+from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg
+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.renderers import NewtonWarpRendererCfg
+from isaaclab_ov.renderers import OVRTXRendererCfg
+from PIL import Image, ImageDraw, ImageFont
+
+from pxr import Usd, UsdGeom
+
+import isaaclab.sim as sim_utils
+from isaaclab.app import add_launcher_args, launch_simulation
+from isaaclab.assets import AssetBaseCfg, RigidObjectCfg
+from isaaclab.envs import ManagerBasedEnvCfg
+from isaaclab.scene import InteractiveSceneCfg
+from isaaclab.terrains import TerrainImporterCfg
+from isaaclab.utils import configclass, instantiate
+from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR, retrieve_file_path
+from isaaclab.utils.math import (
+ convert_camera_frame_orientation_convention,
+ create_rotation_matrix_from_view,
+ quat_apply,
+ quat_apply_inverse,
+ quat_from_matrix,
+)
+from isaaclab.visualizers import SceneCameraCfg, VisualizerCfg
+
+from isaaclab_tasks.utils import preset, setup_preset_cli
+from isaaclab_tasks.utils.hydra import resolve_task_config
+from isaaclab_tasks.utils.presets import MultiBackendRendererCfg
+
+logger = logging.getLogger("isaaclab.examples.foveated_camera")
+
+OFFSET = (0.5, 0.5)
+"""Shift of the whole scene [m], which keeps the ground plane's origin marker behind the camera."""
+EYE = (OFFSET[0], OFFSET[1], 0.35)
+LOOK_AT = (OFFSET[0], OFFSET[1] + 1.0, 0.0)
+YCB = f"{ISAAC_NUCLEUS_DIR}/Props/YCB/Axis_Aligned"
+# Docs overview layout: name, USD, azimuth left of centre [deg], distance [m].
+OBJECTS = {
+ "power_drill": (f"{YCB}/035_power_drill.usd", 80.0, 1.0),
+ "foam_brick": (f"{YCB}/061_foam_brick.usd", 74.0, 1.1),
+ "cracker_box": (f"{YCB}/003_cracker_box.usd", 64.0, 0.8),
+ "banana": (f"{YCB}/011_banana.usd", 52.0, 0.38),
+ "pitcher": (f"{YCB}/019_pitcher_base.usd", 40.0, 1.0),
+ "tuna_can": (f"{YCB}/007_tuna_fish_can.usd", 30.0, 0.32),
+ "sugar_box": (f"{YCB}/004_sugar_box.usd", 24.0, 0.6),
+ "bowl": (f"{YCB}/024_bowl.usd", 13.0, 0.85),
+ "mustard_bottle": (f"{YCB}/006_mustard_bottle.usd", 2.0, 0.5),
+ "master_chef_can": (f"{YCB}/002_master_chef_can.usd", -10.0, 0.95),
+ "soup_can": (f"{YCB}/005_tomato_soup_can.usd", -18.0, 0.38),
+ "bleach": (f"{YCB}/021_bleach_cleanser.usd", -30.0, 0.85),
+ "mug": (f"{YCB}/025_mug.usd", -42.0, 0.5),
+ "toy_truck": (f"{ISAACLAB_NUCLEUS_DIR}/Objects/ToyTruck/toy_truck.usd", -54.0, 1.0),
+ "marker": (f"{YCB}/040_large_marker.usd", -64.0, 0.4),
+ "pudding_box": (f"{YCB}/008_pudding_box.usd", -74.0, 0.7),
+ "clamp": (f"{YCB}/051_large_clamp.usd", -86.0, 0.45),
+}
+
+# An ideal equidistant fisheye (an OpenCV fisheye without distortion) whose 1024 px image spans 180 degrees.
+FOCAL = 512.0 / (math.pi / 2)
+FISHEYE = sim_utils.PinholeCameraCfg(
+ clipping_range=(0.02, 100.0),
+ distortion=sim_utils.OpenCvFisheyeDistortionCfg(fx=FOCAL, fy=FOCAL, cx=511.5, cy=511.5, image_size=(1024, 1024)),
+)
+PREVIEW_SIZE = 256
+
+
+def viewing_sphere_rays(screen: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Trace the docs' oblique perspective view from behind the camera mount."""
+ yaw, pitch = -0.55, 0.5
+ cy, sy, cp, sp = math.cos(yaw), math.sin(yaw), math.cos(pitch), math.sin(pitch)
+ inverse = screen.new_tensor(((cy, sy * sp, -sy * cp), (0, cp, sp), (sy, -cy * sp, cy * cp)))
+ eye = inverse @ screen.new_tensor((0, 0, -3)) + screen.new_tensor((0, 0, 0.4))
+ rays = torch.cat((screen / 2.16, torch.ones_like(screen[..., :1])), dim=-1) @ inverse.T
+ return eye, rays
+
+
+def outline(mask: torch.Tensor) -> torch.Tensor:
+ """A one-pixel inner edge of a projected region."""
+ return mask & torch.nn.functional.max_pool2d((~mask)[None, None].float(), 3, 1, 1)[0, 0].bool()
+
+
+parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+parser.add_argument(
+ "--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.")
+add_launcher_args(parser)
+parser.set_defaults(visualizer=["newton"])
+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.")
+
+
+def _eye_rotation() -> torch.Tensor:
+ """Return the camera mount's OpenGL orientation in the scene frame."""
+ rotation = create_rotation_matrix_from_view(torch.tensor([EYE]), torch.tensor([LOOK_AT]), up_axis="Z")
+ return quat_from_matrix(rotation)
+
+
+def _add_clutter(scene_cfg: InteractiveSceneCfg) -> dict[str, tuple[float, float, float]]:
+ """Place the docs assets on the ground and return their centres in the scene frame."""
+ centres = {}
+ for name, (usd, azimuth, distance) in OBJECTS.items():
+ stage = Usd.Stage.Open(retrieve_file_path(usd))
+ cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), [UsdGeom.Tokens.default_, UsdGeom.Tokens.render])
+ bounds = cache.ComputeWorldBound(stage.GetDefaultPrim()).ComputeAlignedRange()
+ yaw = math.radians(azimuth + 180.0)
+ angle = math.radians(azimuth)
+ x = OFFSET[0] - distance * math.sin(angle)
+ y = OFFSET[1] + distance * math.cos(angle)
+ height = -bounds.GetMin()[2]
+ asset = AssetBaseCfg(
+ prim_path=f"{{ENV_REGEX_NS}}/{name}",
+ spawn=sim_utils.UsdFileCfg(usd_path=usd),
+ init_state=AssetBaseCfg.InitialStateCfg(
+ pos=(x, y, height),
+ rot=(0.0, 0.0, math.sin(yaw / 2), math.cos(yaw / 2)),
+ ),
+ )
+ setattr(scene_cfg, name, asset)
+ centres[name] = (x, y, height + bounds.GetMidpoint()[2])
+ return centres
+
+
+@configclass
+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))
+ # Keep one body below the ground for Newton's model.
+ anchor = RigidObjectCfg(
+ prim_path="{ENV_REGEX_NS}/Anchor",
+ spawn=sim_utils.CuboidCfg(
+ size=(0.01, 0.01, 0.01),
+ rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(),
+ mass_props=sim_utils.MassCfg(mass=0.001),
+ collision_props=sim_utils.UsdPhysicsCollisionCfg(),
+ ),
+ init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, -100.0)),
+ )
+ eye = FoveatedCameraCfg(
+ prim_path="{ENV_REGEX_NS}/Eye",
+ data_types=["rgb"],
+ renderer_cfg=MultiBackendRendererCfg(
+ default=NewtonWarpRendererCfg(render_order="pixel_priority"),
+ newton_warp=NewtonWarpRendererCfg(render_order="pixel_priority"),
+ ovrtx=OVRTXRendererCfg(),
+ isaacsim_rtx=IsaacRtxRendererCfg(),
+ ),
+ spawn=FISHEYE,
+ foveated_res=128,
+ mask_to_sensor_fov=True,
+ offset=FoveatedCameraCfg.OffsetCfg(pos=EYE, rot=tuple(_eye_rotation()[0].tolist()), convention="opengl"),
+ )
+
+
+@configclass
+class FoveatedExampleCfg(ManagerBasedEnvCfg):
+ """A static scene; physics initializes it but never advances."""
+
+ decimation = 1
+ actions = {}
+ observations = {}
+ events = None
+ ui_window_class_type = None
+ scene: FoveatedSceneCfg = FoveatedSceneCfg(num_envs=1, env_spacing=0.0)
+ sim: sim_utils.SimulationCfg = sim_utils.SimulationCfg(
+ physics=preset(
+ default=NewtonCfg(solver_cfg=XPBDSolverCfg(), use_cuda_graph=False, load_visual_shapes=True),
+ isaacsim_rtx=PhysxCfg(),
+ ),
+ visualizer_cfgs=VisualizerCfg(cameras=[SceneCameraCfg(prim_path="{ENV_REGEX_NS}/Eye")]),
+ )
+
+
+def gaze_toward(centre: tuple[float, float, float], camera_cfg: FoveatedCameraCfg) -> tuple[float, float]:
+ """Return tilt and pan in degrees in the camera's optical frame."""
+ offset = camera_cfg.offset
+ mount = convert_camera_frame_orientation_convention(
+ torch.tensor([offset.rot]), origin=offset.convention, target="ros"
+ )
+ delta = torch.tensor([centre]) - torch.tensor([offset.pos])
+ x, y, z = quat_apply_inverse(mount, delta)[0].tolist()
+ return -math.degrees(math.atan2(y, math.hypot(x, z))), -math.degrees(math.atan2(x, z))
+
+
+def camera_comparison(
+ camera: FoveatedCamera, overview: FoveatedCamera
+) -> tuple[Callable[[], None], Callable[[torch.Tensor, float], wp.array]]:
+ """Draw the lens and gaze on the viewing sphere used in the docs, beside the retina magnified by a zoom."""
+ size, gap = PREVIEW_SIZE, 6
+ header_height = 28
+ image_width = 2 * size + gap
+ header_color = (25, 28, 32, 255)
+ header = Image.new("RGBA", (image_width, header_height), header_color)
+ draw = ImageDraw.Draw(header)
+ font = ImageFont.load_default(size=17)
+ draw.text((8, header_height / 2), "Viewing sphere", font=font, fill="white", anchor="lm")
+ draw.text((size + gap + 8, header_height / 2), "FoveatedCamera view", font=font, fill="white", anchor="lm")
+ labels = torch.from_numpy(np.array(header)).to(camera.device)
+ divider = labels[:1, size : size + gap].expand(size, -1, -1)
+ displayed_zoom = None
+
+ coords = overview.sampling_coords
+ retina_coords = camera.sampling_coords
+ pixels = torch.arange(size, device=camera.device)
+ center = (pixels + 0.5) * (2 / size) - 1
+ screen = torch.stack(torch.meshgrid(center, center, indexing="xy"), dim=-1)
+ retina_disc = screen.square().sum(-1) <= 1
+ gl_to_ros = screen.new_tensor((1, -1, -1))
+ roll = math.radians(overview.cfg.image_rotation_deg)
+ c, s = math.cos(roll), math.sin(roll)
+ image_roll = screen.new_tensor(((c, -s, 0), (s, c, 0), (0, 0, 1)))
+ eye, observer_rays = viewing_sphere_rays(screen)
+ reference_pos, reference_q = (value[:1].clone() for value in camera.get_world_poses(convention="opengl"))
+ world_axes = quat_apply(reference_q.expand(3, -1), torch.diag(gl_to_ros))
+ lens_color = screen.new_tensor((20, 112, 102))
+ gaze_color = screen.new_tensor((36, 84, 157))
+
+ def prepare() -> None:
+ overview.set_world_poses(*camera.get_world_poses(convention="opengl"), convention="opengl")
+ if camera.supports_batch_update and overview.supports_batch_update:
+ camera.update_batch((camera, overview), 0.0)
+
+ def compose(retina: torch.Tensor, zoom: float) -> wp.array:
+ """The panel for one RGB retina image (H, W, 3): the viewing sphere, then the retina magnified by ``zoom``."""
+ nonlocal displayed_zoom
+ if zoom != displayed_zoom:
+ draw.rectangle((image_width - 68, 0, image_width - 1, header_height - 1), fill=header_color)
+ draw.text((image_width - 8, header_height / 2), f"{zoom:.2f}x", font=font, fill="white", anchor="rm")
+ labels.copy_(torch.from_numpy(np.array(header)))
+ displayed_zoom = zoom
+ detail = torch.cat((retina, torch.full_like(retina[..., :1], 255)), dim=-1)
+ height, width = detail.shape[:2]
+ crop_h, crop_w = max(1, round(height / zoom)), max(1, round(width / zoom))
+ top, left = (height - crop_h) // 2, (width - crop_w) // 2
+
+ # Transform the fixed observer into the live camera frame, independently of active gaze.
+ position, orientation = camera.get_world_poses(convention="opengl")
+ axes = quat_apply_inverse(orientation[:1].expand(3, -1), world_axes) * gl_to_ros
+ offset = quat_apply_inverse(reference_q, position[:1] - reference_pos)[0] * gl_to_ros
+ origin = (eye - 0.22 * torch.tanh(offset / 0.4)) @ axes
+ rays = observer_rays @ axes
+ a = rays.square().sum(-1)
+ b = (rays * origin).sum(-1)
+ discriminant = b.square() - a * (origin.square().sum() - 1)
+ root = discriminant.clamp_min(0).sqrt()
+ near_t, far_t = (-b - root) / a, (-b + root) / a
+ near = origin + near_t[..., None] * rays
+ far = origin + far_t[..., None] * rays
+ _, near_valid = overview.camera_model.project(((near * gl_to_ros) @ image_roll.T) * gl_to_ros)
+ _, far_valid = overview.camera_model.project(((far * gl_to_ros) @ image_roll.T) * gl_to_ros)
+ near_hit = (discriminant >= 0) & (near_t > 0) & near_valid
+ inside = (discriminant >= 0) & (far_t > 0) & far_valid & ~near_hit
+ hit = near_hit | inside
+
+ # The overview texture uses native x/y ordering. Its published image is upright.
+ uv, texture_valid = native_grid_exit_uv(far * gl_to_ros, coords)
+ texture = overview.data.output["rgb"].torch[0, ..., :3]
+ uv = torch.stack((uv[..., 1], 1 - uv[..., 0]), dim=-1)
+ ij = (uv * size).nan_to_num().long().clamp(0, size - 1)
+ rgb = texture[ij[..., 1], ij[..., 0]].float()
+ sampled = inside & texture_valid
+
+ tilt, pan = camera.gaze_angles.torch[0].deg2rad().unbind()
+ direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()))
+ alignment = (far * direction).sum(-1)
+ if retina_coords.style == GRID_STYLE:
+ rotation = gaze_rotation(direction, convention="pan_tilt")
+ grid, _ = native_grid_exit_uv((far @ rotation) * gl_to_ros, retina_coords)
+ radius = torch.linalg.vector_norm(2 * grid - 1, dim=-1)
+ else:
+ radius = torch.acos(alignment.clamp(-1, 1)) / math.radians(retina_coords.fov / 2)
+ in_retina = radius <= min(crop_h / height, crop_w / width)
+
+ # Match the docs: an untextured near shell, a faded peripheral texture, and independent lens/gaze edges.
+ texel = 0.72 * rgb + 0.28 * 255
+ texel = torch.where(in_retina[..., None], texel, 0.45 * texel + 0.55 * 255)
+ shell = torch.where(near_hit, 218.0, 247.0)
+ full = torch.where(sampled[..., None], texel, shell[..., None])
+ if retina_coords.style == GRID_STYLE:
+ cells = torch.floor(grid * 8)
+ lines = torch.zeros_like(hit)
+ lines[:, 1:] |= (cells[:, 1:] != cells[:, :-1]).any(-1)
+ lines[1:, :] |= (cells[1:, :] != cells[:-1, :]).any(-1)
+ lattice = sampled & in_retina & lines
+ full = torch.where(lattice[..., None], torch.lerp(full, gaze_color, 0.42), full)
+ fixation = alignment.masked_fill(~sampled, -torch.inf).argmax()
+ row, col = fixation // size, fixation % size
+ dot = (pixels[None, :] - col).square() + (pixels[:, None] - row).square() <= 9
+ gaze_edge = outline(in_retina) | (dot & (alignment > 0.999))
+ full = torch.where((sampled & gaze_edge)[..., None], gaze_color, full)
+ full = torch.where(outline(hit)[..., None], lens_color, full)
+ full = torch.cat((full.to(torch.uint8), torch.full_like(texture[..., :1], 255)), dim=-1)
+
+ crop = detail[top : top + crop_h, left : left + crop_w].permute(2, 0, 1).unsqueeze(0)
+ detail = torch.nn.functional.interpolate(crop, size=(size, size), mode="nearest")[0].permute(1, 2, 0)
+ detail[..., :3].masked_fill_(~retina_disc[..., None], 0)
+ return wp.from_torch(torch.cat((labels, torch.cat((full, divider, detail), dim=1)), dim=0))
+
+ return prepare, compose
+
+
+def newton_window(visualizer):
+ """The window of a Newton visualizer, which shows the example's panel. Isaac Lab's Newton raycast example reaches it
+ the same way."""
+ return visualizer._viewer
+
+
+def main() -> None:
+ """Render the docs scene and let the viewer drive the camera."""
+ # Config-only registration reuses the standard preset and Hydra override resolver.
+ gym.register(
+ "FoveatedCameraExample",
+ entry_point="isaaclab.envs:ManagerBasedEnv",
+ kwargs={"env_cfg_entry_point": FoveatedExampleCfg},
+ )
+ cfg, _ = resolve_task_config("FoveatedCameraExample", None, overrides=overrides)
+ if cfg.scene.eye.renderer_cfg.renderer_type == "ovrtx":
+ print("Starting OVRTX. The first frame can take several minutes with a cold shader cache.", flush=True)
+ with launch_simulation(cfg, args_cli):
+ visualizer_types = {v.backend.visualizer_type for v in cfg.sim.visualizer_cfgs}
+ if visualizer_types - {"newton"}:
+ logger.warning(
+ "The foveated-camera example's gaze keys and viewing-sphere panel need the Newton visualizer"
+ " (--viz newton). With %s, the gaze stays where it starts (see --target).",
+ ", ".join(sorted(visualizer_types - {"newton"})),
+ )
+ 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,
+ foveated_style="warped_cartesian_as_grid",
+ cmf_a_deg=1.0e5,
+ retinal_window_fraction=1.0,
+ fov_type="circular",
+ radius_norm=2.0,
+ pool_enabled=False,
+ mask_to_sensor_fov=True,
+ data_types=["rgb"],
+ )
+ scene = instantiate(cfg.scene)
+ sim.register_interactive_scene(scene)
+ sim.reset()
+ camera = scene["eye"]
+ gaze = (0.0, 0.0)
+ if args_cli.target is not None:
+ gaze = gaze_toward(centres[args_cli.target], cfg.scene.eye)
+ angles = torch.tensor([gaze], device=sim.device).repeat(scene.num_envs, 1)
+ if args_cli.target is not None:
+ camera.set_gaze_angles(angles)
+ viewers = [v for v in sim.visualizers if v.cfg.backend.visualizer_type == "newton"]
+
+ def set_gaze(value: tuple[float, float]) -> None:
+ nonlocal gaze
+ if gaze == value:
+ return
+ gaze = value
+ angles.copy_(angles.new_tensor(gaze).expand_as(angles))
+ camera.set_gaze_angles(angles)
+ for viewer in viewers:
+ viewer.current_image_view.invalidate()
+
+ if viewers:
+ prepare, compose = camera_comparison(camera, scene["overview"])
+ zoom = 1.0
+
+ last_gaze_update = time.monotonic()
+ 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_gaze_update >= 1 / 30:
+ elapsed = min(now - last_gaze_update, 0.05)
+ last_gaze_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"))
+ magnify = int(viewer.is_key_down("o")) - int(viewer.is_key_down("u"))
+ zoom = max(1.0, min(8.0, zoom * math.exp(1.5 * magnify * elapsed)))
+ if tilt or pan:
+ set_gaze(
+ (
+ max(-85.0, min(85.0, gaze[0] + tilt * 50 * elapsed)),
+ max(-85.0, min(85.0, gaze[1] + pan * 50 * elapsed)),
+ )
+ )
+ scene.update(sim.get_physics_dt())
+ sim.render()
+ if viewers:
+ # The panel follows the retina the viewer shows: the dense overview takes the eye's pose, then both
+ # render, and the panel is drawn from them.
+ prepare()
+ panel = compose(camera.data.output["rgb"].torch[0, ..., :3], zoom)
+ for viewer in viewers:
+ newton_window(viewer).log_image("Foveated camera", panel)
+ if not sim.visualizers:
+ # Without a viewer, explicitly request sensor data to render the frame.
+ _ = camera.data
+ frame += 1
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pyproject.toml b/pyproject.toml
index 8f20b74dcc18..0f47cec1621b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -227,6 +227,11 @@ rlinf = [
leapp = [
"leapp==0.8.1",
]
+# Foveated camera sensors.
+fovi = [
+ "isaaclab-fovi",
+ "fovi>=2.7",
+]
all = [
"isaaclab-dev[sb3,skrl,rl-games,rsl-rl,viser,rerun,ov]",
]
@@ -467,6 +472,7 @@ isaaclab = { path = "source/isaaclab", editable = true }
"isaaclab-assets" = { path = "source/isaaclab_assets", editable = true }
"isaaclab-contrib" = { path = "source/isaaclab_contrib", editable = true }
"isaaclab-experimental" = { path = "source/isaaclab_experimental", editable = true }
+"isaaclab-fovi" = { path = "source/isaaclab_fovi", editable = true }
"isaaclab-mimic" = { path = "source/isaaclab_mimic", editable = true }
"isaaclab-newton" = { path = "source/isaaclab_newton", editable = true }
"isaaclab-ov" = { path = "source/isaaclab_ov", editable = true }
diff --git a/source/isaaclab/changelog.d/foveated-camera-example.added.rst b/source/isaaclab/changelog.d/foveated-camera-example.added.rst
new file mode 100644
index 000000000000..81c392ce7753
--- /dev/null
+++ b/source/isaaclab/changelog.d/foveated-camera-example.added.rst
@@ -0,0 +1,3 @@
+* Added the ``foveated-camera`` example (``isaaclab example foveated-camera``, ``fovi`` extra), which explores a
+ cluttered scene through the experimental foveated camera, with keyboard gaze control and a panel showing the gaze
+ on the fisheye's viewing sphere.
diff --git a/source/isaaclab/changelog.d/foveated-camera-example.minor b/source/isaaclab/changelog.d/foveated-camera-example.minor
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/source/isaaclab/isaaclab/programs.py b/source/isaaclab/isaaclab/programs.py
index a92759f31866..f294536261cc 100644
--- a/source/isaaclab/isaaclab/programs.py
+++ b/source/isaaclab/isaaclab/programs.py
@@ -282,6 +282,13 @@ def _run_script(path: Path) -> None:
"Inspect camera and force-field tactile data.",
**_ISAACSIM,
),
+ ProgramSpec(
+ "foveated-camera",
+ "examples/sensors/foveated_camera.py",
+ "Explore a cluttered scene through an experimental foveated camera.",
+ extras=("fovi",),
+ required_modules=("isaaclab_fovi", "fovi"),
+ ),
)
diff --git a/source/isaaclab/test/app/standalone_script_cases.py b/source/isaaclab/test/app/standalone_script_cases.py
index 1f41ee298160..c4daf63ae919 100644
--- a/source/isaaclab/test/app/standalone_script_cases.py
+++ b/source/isaaclab/test/app/standalone_script_cases.py
@@ -313,6 +313,9 @@ class SmokeResult:
visualizers=(None, "newton", "rerun", "viser"),
),
"examples/demos/microduck_warehouse.py": ScriptOverride(fixed_physics_backend="newton_xpbd"),
+ "examples/sensors/foveated_camera.py": ScriptOverride(
+ fixed_physics_backend="newton_xpbd", visualizers=(None, "newton")
+ ),
"examples/demos/pick_and_place.py": ScriptOverride(visualizers=("kit",)),
"examples/sensors/ppisp_camera.py": ScriptOverride(
args=("--max_steps", "3", "--warmup_steps", "1", "--image_width", "64", "--image_height", "64"),
diff --git a/source/isaaclab/test/cli/test_uv_run_pyproject.py b/source/isaaclab/test/cli/test_uv_run_pyproject.py
index cc7e06e449af..e28b7b4f8132 100644
--- a/source/isaaclab/test/cli/test_uv_run_pyproject.py
+++ b/source/isaaclab/test/cli/test_uv_run_pyproject.py
@@ -123,6 +123,7 @@ def test_all_extra_aggregates_curated_ov_rl_and_visualizer_extras(source_checkou
"tetrahedralization",
"video",
"optix",
+ "fovi",
"leapp",
"wandb",
"test",
diff --git a/source/isaaclab_fovi/changelog.d/fovi-rtx-lens-setup.skip b/source/isaaclab_fovi/changelog.d/fovi-rtx-lens-setup.skip
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst
new file mode 100644
index 000000000000..6fe806778a44
--- /dev/null
+++ b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.added.rst
@@ -0,0 +1,7 @@
+* Introduced ``isaaclab_fovi`` and the ``fovi`` installation extra, providing
+ :class:`~isaaclab_fovi.sensors.FoveatedCamera`, a foveated camera sensor for the Newton (Warp and OptiX),
+ Isaac RTX and OVRTX renderers whose gaze moves inside a physical camera's field of view.
+* Added active-gaze manager terms in :mod:`isaaclab_fovi.mdp`: a gaze action with a fixed or tracked camera mount,
+ a gaze observation, and teacher gaze labels.
+* Added modal-label pooling for segmentation outputs, which keeps their native dtype (``pool_int_mode="modal"``,
+ the only accepted value); ``pool_mode`` pools the other outputs and accepts only fovi's modes.
diff --git a/source/isaaclab_fovi/changelog.d/isaaclab-fovi.minor b/source/isaaclab_fovi/changelog.d/isaaclab-fovi.minor
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/source/isaaclab_fovi/docs/CHANGELOG.rst b/source/isaaclab_fovi/docs/CHANGELOG.rst
new file mode 100644
index 000000000000..9e3a308a2125
--- /dev/null
+++ b/source/isaaclab_fovi/docs/CHANGELOG.rst
@@ -0,0 +1,4 @@
+Changelog
+=========
+
+.. towncrier release notes start
diff --git a/source/isaaclab_fovi/isaaclab_fovi/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/__init__.py
new file mode 100644
index 000000000000..d2ea747c879c
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/__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
+
+"""Foveated cameras for Isaac Lab.
+
+Import camera implementations from :mod:`isaaclab_fovi.sensors` after starting
+the selected simulator runtime.
+"""
diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.py
new file mode 100644
index 000000000000..b2c044ba52d2
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__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
+
+"""Manager terms for active gaze with a foveated camera."""
+
+from isaaclab.utils.module import lazy_export
+
+lazy_export()
diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi
new file mode 100644
index 000000000000..e78c9a3844e8
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/__init__.pyi
@@ -0,0 +1,18 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+__all__ = [
+ "GazeAction",
+ "GazeActionCfg",
+ "gaze_state",
+ "gaze_teacher_labels",
+]
+
+from .gaze import (
+ GazeAction,
+ gaze_state,
+ gaze_teacher_labels,
+)
+from .gaze_cfg import GazeActionCfg
diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py
new file mode 100644
index 000000000000..862897ab93ca
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze.py
@@ -0,0 +1,435 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Active gaze for a foveated camera: a gaze action, its observation, and a teacher's gaze labels.
+
+Gaze angles are (tilt, pan) [deg] from the physical camera's optical axis: positive tilt looks up and positive pan
+looks left, as for :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles`. The policy moves and observes the
+gaze in field radii, half the retina's field of view. Camera-frame directions follow the ROS (OpenCV) convention:
+x right, y down, z forward.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import TYPE_CHECKING, ClassVar
+
+import torch
+import warp as wp
+
+from isaaclab.managers import ActionTerm, ManagerTermBase, ObservationTermCfg, SceneEntityCfg
+from isaaclab.utils.warp import ProxyArray
+
+from ..sensors.gaze_kernels import (
+ DEG_TO_RAD,
+ CameraParams,
+ project_direction,
+ project_directions,
+ record_launch,
+ warp_stream,
+)
+
+if TYPE_CHECKING:
+ from isaaclab.envs import ManagerBasedEnv
+
+ from ..sensors import FoveatedCamera
+ from .gaze_cfg import GazeActionCfg
+
+RAD_TO_DEG = 180.0 / math.pi
+
+
+@wp.func
+def teach(
+ point: wp.vec3f,
+ position: wp.vec3f,
+ mount: wp.quatf,
+ g: wp.vec2f,
+ frame: wp.mat33f,
+ field_radius_deg: wp.float32,
+ step_size: wp.float32,
+ gaze_limit: wp.float32,
+ camera: CameraParams,
+) -> wp.vec4f:
+ """The teacher's action (x, y) toward a point, 1 for a valid target or else 0, and the gaze's error [deg].
+
+ ``frame`` carries the upright image frame, in which gazes are measured, into the physical camera's frame.
+ """
+ d = wp.normalize(wp.quat_rotate_inv(mount, point - position))
+ # The fixation reaches the physical camera at frame * gaze * z, so the gaze looks along frame^T d.
+ u = wp.transpose(frame) * d
+ tilt = -wp.atan2(u[1], wp.sqrt(u[0] * u[0] + u[2] * u[2])) * wp.float32(RAD_TO_DEG)
+ pan = -wp.atan2(u[0], u[2]) * wp.float32(RAD_TO_DEG)
+ desired = wp.vec2f(tilt, pan) / field_radius_deg
+ ok = project_direction(d, camera)[2] > 0.5 and wp.length(desired) <= gaze_limit
+ step = wp.vec2f(0.0, 0.0)
+ if ok:
+ step = wp.vec2f(
+ wp.clamp((desired[0] - g[0]) / step_size, -1.0, 1.0), wp.clamp((desired[1] - g[1]) / step_size, -1.0, 1.0)
+ )
+ g_tilt = g[0] * field_radius_deg * wp.float32(DEG_TO_RAD)
+ g_pan = g[1] * field_radius_deg * wp.float32(DEG_TO_RAD)
+ looking = wp.vec3f(-wp.cos(g_tilt) * wp.sin(g_pan), -wp.sin(g_tilt), wp.cos(g_tilt) * wp.cos(g_pan))
+ # atan2 stays accurate near perfect alignment, unlike acos of the dot product.
+ error = wp.atan2(wp.length(wp.cross(looking, u)), wp.dot(looking, u)) * wp.float32(RAD_TO_DEG)
+ return wp.vec4f(step[0], step[1], wp.where(ok, 1.0, 0.0), error)
+
+
+@wp.kernel(enable_backward=False)
+def teacher_labels_kernel(
+ target_poses: wp.array(dtype=wp.transformf),
+ offset: wp.vec3f,
+ positions: wp.array(dtype=wp.vec3f),
+ mounts: wp.array(dtype=wp.quatf),
+ angles_deg: wp.array(dtype=wp.vec2f),
+ frame: wp.mat33f,
+ field_radius_deg: wp.float32,
+ step_size: wp.float32,
+ gaze_limit: wp.float32,
+ camera: CameraParams,
+ labels: wp.array(dtype=wp.vec3f),
+ log: wp.array(dtype=wp.float32),
+):
+ """Labels (action x, action y, valid) toward the point ``offset`` fixed to each target's frame; and the mean gaze
+ error to valid targets [deg] with the fraction of valid targets.
+
+ ``mounts`` holds each camera's mount (ROS convention); ``angles_deg`` the camera's stored gaze angles [deg].
+ One block labels every environment and reduces the logs itself, so the launch needs no zeroed accumulators.
+ """
+ _block, lane = wp.tid()
+ count = target_poses.shape[0]
+ error_sum = wp.float32(0.0)
+ valid_count = wp.float32(0.0)
+ i = lane
+ 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)
+ labels[i] = wp.vec3f(result[0], result[1], result[2])
+ if result[2] > 0.5:
+ error_sum += result[3]
+ valid_count += 1.0
+ i += wp.block_dim()
+ errors = wp.tile_sum(wp.tile(error_sum))
+ valid = wp.tile_sum(wp.tile(valid_count))
+ if lane == 0:
+ log[0] = errors[0] / wp.max(valid[0], 1.0)
+ log[1] = valid[0] / wp.float32(count)
+
+
+@wp.kernel(enable_backward=False)
+def gaze_reset_kernel(
+ ids: wp.array(dtype=wp.int32),
+ use_ids: wp.int32,
+ start: wp.array(dtype=wp.vec2f),
+ use_start: wp.int32,
+ field_radius_deg: wp.float32,
+ angles_deg: wp.array(dtype=wp.vec2f),
+ state: wp.array(dtype=wp.vec4f),
+):
+ """Put each reset environment's gaze at its start, or on the optical axis, at rest.
+
+ ``state`` holds each gaze and its velocity, in field radii and field radii per second.
+ """
+ k = wp.tid()
+ i = k
+ if use_ids != 0:
+ i = ids[k]
+ g = wp.vec2f(0.0, 0.0)
+ if use_start != 0:
+ g = start[k]
+ angles_deg[i] = g * field_radius_deg
+ state[i] = wp.vec4f(g[0], g[1], 0.0, 0.0)
+
+
+@wp.kernel(enable_backward=False)
+def gaze_step_kernel(
+ actions: wp.array(dtype=wp.vec2f),
+ state: wp.array(dtype=wp.vec4f),
+ angles_deg: wp.array(dtype=wp.vec2f),
+ step_size: wp.float32,
+ gaze_limit: wp.float32,
+ step_dt: wp.float32,
+ field_radius_deg: wp.float32,
+):
+ """Move each gaze by its clamped action and keep it within the limit; record the gaze, velocity and angles.
+
+ The step starts from the camera's stored ``angles_deg``, which own the gaze. ``state`` records each gaze and its
+ velocity, in field radii and field radii per second.
+ """
+ i = wp.tid()
+ a = actions[i]
+ previous = angles_deg[i] / field_radius_deg
+ moved = previous + wp.vec2f(wp.clamp(a[0], -1.0, 1.0), wp.clamp(a[1], -1.0, 1.0)) * step_size
+ current = moved * (gaze_limit / wp.max(wp.length(moved), gaze_limit))
+ rate = (current - previous) / step_dt
+ angles_deg[i] = current * field_radius_deg
+ state[i] = wp.vec4f(current[0], current[1], rate[0], rate[1])
+
+
+def gaze_state(env: ManagerBasedEnv, action_name: str = "gaze") -> torch.Tensor:
+ """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4)."""
+ term: GazeAction = env.action_manager.get_term(action_name)
+ return term.state
+
+
+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.
+
+ With ``mount="fixed"`` the camera keeps the orientation it had when the term was created, and the teacher uses
+ that mount; turning the camera's mount afterwards raises. With ``mount="tracked"`` the camera may ride a moving
+ body, for example a robot's head, and the teacher reads each camera's current mount, so software gaze adds to
+ hardware gaze.
+
+ The camera's stored gaze angles own the gaze: each step and the teacher start from them, so a gaze set directly
+ with :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_gaze_angles` carries on. :attr:`state`, the observation, is
+ the gaze and velocity as of the last step or reset.
+ """
+
+ cfg: GazeActionCfg
+
+ is_graphable: ClassVar[bool] = True
+ """The gaze moves in :meth:`process_actions`, once per environment step; :meth:`apply_actions` does nothing, so
+ physics may record the other terms' actions and its decimation loop into a CUDA graph."""
+
+ def __init__(self, cfg: GazeActionCfg, env: ManagerBasedEnv):
+ super().__init__(cfg, env)
+ camera = self.camera
+ self.tracked_mount = cfg.mount == "tracked"
+ if self.tracked_mount and not camera.turns_pose_by_gaze:
+ raise ValueError(
+ "A tracked gaze mount needs a camera that turns its pose by the gaze every frame: Newton or OVRTX."
+ )
+ if not self.tracked_mount and camera.cfg.prim_path.rpartition("/")[0] not in (
+ "{ENV_REGEX_NS}",
+ env.scene.env_regex_ns,
+ ):
+ # A body's motion turns its camera without set_world_poses, which the fixed mount could not detect.
+ raise ValueError(
+ f"A fixed gaze mount needs a camera mounted on the environment, got {camera.cfg.prim_path!r};"
+ " use mount='tracked' for a camera on a moving body."
+ )
+ # The camera's own geometry, so the teacher and the sensor mask share one projection.
+ frame = camera.image_frame
+ self._frame_torch = torch.tensor(
+ [[frame[row][col] for col in range(3)] for row in range(3)], device=self.device
+ )
+ self.field_radius_deg = camera.sampling_coords.fov / 2
+ """Half the retina's field of view [deg]."""
+ self._fixed_mount = None
+ if not self.tracked_mount:
+ # The fixed-mount teacher keeps the camera's mount as it is now; only later turns invalidate it.
+ mount = camera.ungazed_quat_w_ros()
+ self._fixed_mount = ProxyArray(wp.from_torch(mount.contiguous(), dtype=wp.quatf))
+ self._mount_turns = camera.mount_turns
+ self._raw: torch.Tensor | None = None
+ """Gaze actions of the last step, as supplied to :meth:`process_actions`."""
+ self._state = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec4f, device=self.device))
+ """Gaze and its velocity as of the last step or reset, the gaze observation."""
+ self._velocity = self._state.torch[:, 2:]
+ self._step_launch: tuple[tuple, wp.Launch] | None = None
+ # Each reset copies its environments, and their start gazes if random, into these and replays one launch.
+ self._reset_ids = ProxyArray(wp.zeros(self.num_envs, dtype=wp.int32, device=self.device))
+ self._reset_start = ProxyArray(wp.zeros(self.num_envs, dtype=wp.vec2f, device=self.device))
+ self._reset_launches: dict[tuple[bool, bool], wp.Launch] = {}
+
+ @property
+ def action_dim(self) -> int:
+ return 2
+
+ @property
+ def camera(self) -> FoveatedCamera:
+ """The foveated camera whose gaze the term moves."""
+ return self._asset
+
+ @property
+ def raw_actions(self) -> torch.Tensor:
+ return self._raw if self._raw is not None else torch.zeros_like(self._velocity)
+
+ @property
+ def processed_actions(self) -> torch.Tensor:
+ return self.gaze
+
+ @property
+ def gaze(self) -> torch.Tensor:
+ """Current gaze in field radii, from the camera's stored angles, shape (num_envs, 2)."""
+ return self.angles_deg / self.field_radius_deg
+
+ @property
+ def velocity(self) -> torch.Tensor:
+ """Gaze velocity in field radii per second, shape (num_envs, 2)."""
+ return self._velocity
+
+ @property
+ def state(self) -> torch.Tensor:
+ """Gaze and its velocity, in field radii and field radii per second, shape (num_envs, 4)."""
+ return self._state.torch
+
+ @property
+ def angles_deg(self) -> torch.Tensor:
+ """Current gaze angles [deg], the camera's stored ones, shape (num_envs, 2)."""
+ return self.camera.gaze_angles.torch
+
+ def process_actions(self, actions: torch.Tensor):
+ """Move the gaze by the supplied actions, shape (num_envs, 2).
+
+ The launch reads ``actions`` in place. The action manager hands the term the same slice of its buffer each
+ step, so the launch is recorded once; another buffer records a launch that reads it.
+ """
+ if actions.dtype != torch.float32:
+ actions = actions.float()
+ key = (actions.data_ptr(), actions.stride(), actions.device)
+ if self._step_launch is None or self._step_launch[0] != key:
+ launch = record_launch(
+ gaze_step_kernel,
+ self.num_envs,
+ [
+ wp.from_torch(actions, dtype=wp.vec2f),
+ self._state,
+ self.camera.gaze_angles,
+ self.cfg.step_size,
+ self.cfg.gaze_limit,
+ self._env.step_dt,
+ self.field_radius_deg,
+ ],
+ device=self.device,
+ )
+ self._step_launch = (key, launch)
+ self._raw = actions
+ self._step_launch[1].launch(warp_stream(self.device))
+ self.camera.set_gaze_angles(self.camera.gaze_angles.torch)
+
+ def apply_actions(self):
+ pass
+
+ def reset(self, env_ids=None):
+ # The action manager zeroes the reset environments' actions itself.
+ indexed = env_ids is not None
+ count = self.num_envs
+ if indexed:
+ if isinstance(env_ids, slice):
+ env_ids = torch.arange(*env_ids.indices(self.num_envs), device=self.device)
+ count = len(env_ids)
+ if count == 0:
+ return
+ self._reset_ids.torch[:count] = torch.as_tensor(env_ids, device=self.device)
+ random_start = self.cfg.random_reset
+ if random_start:
+ # A square root gives uniform area density in the gaze disc.
+ radius = self.cfg.gaze_limit * torch.rand(count, device=self.device).sqrt()
+ angle = 2 * math.pi * torch.rand(count, device=self.device)
+ gaze = torch.stack((radius * angle.sin(), radius * angle.cos()), dim=-1)
+ tilt, pan = (gaze * self.field_radius_deg).deg2rad().unbind(-1)
+ direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1)
+ visible = self.visible(direction)
+ self._reset_start.torch[:count] = torch.where(visible[:, None], gaze, 0.0)
+ angles = self.camera.gaze_angles
+ launch = self._reset_launches.get((indexed, random_start))
+ if launch is None:
+ launch = self._reset_launches[(indexed, random_start)] = record_launch(
+ gaze_reset_kernel,
+ self.num_envs,
+ [self._reset_ids, int(indexed), self._reset_start, int(random_start), self.field_radius_deg],
+ [angles, self._state],
+ self.device,
+ )
+ launch.set_dim(count)
+ launch.launch(warp_stream(self.device))
+ # The camera keeps reading the same buffer, which every other environment already holds.
+ self.camera.set_gaze_angles(angles.torch)
+
+ def visible(self, direction: torch.Tensor) -> torch.Tensor:
+ """Whether directions in the upright gaze frame fall inside the physical camera's image."""
+ return project_directions(direction @ self._frame_torch.T, self.camera.projection_params)[1]
+
+ def teacher_mounts(self) -> ProxyArray:
+ """Each camera's mount (x, y, z, w), ROS convention, that the teacher aims from: the current one when
+ tracked, else the one captured when the term was created.
+
+ Raises:
+ RuntimeError: The camera's mount turned while the gaze assumes a fixed mount.
+ """
+ if self.tracked_mount:
+ return self.camera.mount_quat_w_ros
+ if self.camera.mount_turns != self._mount_turns:
+ raise RuntimeError(
+ "The gaze camera's mount turned, so the fixed-mount teacher would aim from its first orientation;"
+ " use GazeActionCfg.mount='tracked'."
+ )
+ return self._fixed_mount
+
+
+class gaze_teacher_labels(ManagerTermBase):
+ """The teacher's gaze action toward a point fixed to an asset, and its validity, shape (num_envs, 3).
+
+ A training label, never a policy input. One launch labels every environment and logs the mean gaze error to valid
+ targets and the fraction of valid targets.
+
+ Args:
+ target_cfg: The asset, and optionally one body by ``body_names``.
+ offset: The point in the root's or the body's frame [m].
+ action_name: The gaze action term.
+ """
+
+ def __init__(self, cfg: ObservationTermCfg, env: ManagerBasedEnv):
+ super().__init__(cfg, env)
+ self._gaze: GazeAction = env.action_manager.get_term(cfg.params.get("action_name", "gaze"))
+ self._labels = ProxyArray(wp.zeros(env.num_envs, dtype=wp.vec3f, device=env.device))
+ self._log = ProxyArray(wp.zeros(2, dtype=wp.float32, device=env.device))
+ """Mean gaze error to valid targets [deg] and the fraction of valid targets."""
+ self._launch: tuple[tuple, wp.Launch] | None = None
+
+ def __call__(
+ self,
+ env: ManagerBasedEnv,
+ target_cfg: SceneEntityCfg,
+ offset: tuple[float, float, float] = (0.0, 0.0, 0.0),
+ action_name: str = "gaze",
+ ) -> torch.Tensor:
+ data = env.scene[target_cfg.name].data
+ # Reading the property refreshes the producer's poses.
+ body_id = None if target_cfg.body_names is None else int(target_cfg.body_ids[0])
+ poses = data.root_pose_w.warp if body_id is None else data.body_pose_w.warp
+ point = tuple(float(value) for value in offset)
+ gaze = self._gaze
+ mounts = gaze.teacher_mounts()
+ camera_positions = gaze.camera.data.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)
+ if self._launch is None or self._launch[0] != key:
+ # Warp runs CPU blocks as one thread.
+ block = 1024 if torch.device(env.device).type == "cuda" else 1
+ launch = record_launch(
+ teacher_labels_kernel,
+ (1, block),
+ [
+ poses if body_id is None else poses[:, body_id],
+ wp.vec3f(*point),
+ camera_positions,
+ mounts,
+ gaze.camera.gaze_angles,
+ gaze.camera.image_frame,
+ gaze.field_radius_deg,
+ gaze.cfg.step_size,
+ gaze.cfg.gaze_limit,
+ gaze.camera.projection_params,
+ ],
+ [self._labels, self._log],
+ env.device,
+ block_dim=block,
+ )
+ self._launch = (key, launch)
+ self._launch[1].launch(warp_stream(env.device))
+ # Each step's log must survive the next write to this buffer.
+ error, fraction = self._log.torch.clone()
+ log = env.extras.setdefault("log", {})
+ log["Gaze/target_error_deg"] = error
+ log["Gaze/valid_target_fraction"] = fraction
+ return self._labels.torch
diff --git a/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py
new file mode 100644
index 000000000000..1d8b75373902
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/mdp/gaze_cfg.py
@@ -0,0 +1,43 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Configuration of the active-gaze action."""
+
+from __future__ import annotations
+
+import math
+from dataclasses import MISSING
+from typing import TYPE_CHECKING
+
+from isaaclab.managers import ActionTermCfg
+from isaaclab.utils import configclass
+
+if TYPE_CHECKING:
+ from .gaze import GazeAction
+
+
+@configclass
+class GazeActionCfg(ActionTermCfg):
+ """Configuration of :class:`~isaaclab_fovi.mdp.gaze.GazeAction`."""
+
+ class_type: type[GazeAction] | str = "{DIR}.gaze:GazeAction"
+ asset_name: str = MISSING
+ """Scene name of the foveated camera whose gaze the action moves."""
+ step_size: float = 0.1
+ """Change of each gaze coordinate per step at an action of 1, in field radii. Positive and finite."""
+ gaze_limit: float = 1.0
+ """Largest distance of the gaze from the camera's optical axis, in field radii. Positive and finite."""
+ random_reset: bool = False
+ """Start episodes at a random gaze the camera sees; otherwise on the optical axis."""
+ mount: str = "fixed"
+ """Teacher's mount: ``"fixed"`` at the action's creation, or ``"tracked"`` on a moving body (Newton, OVRTX)."""
+
+ def validate_config(self):
+ """Reject gaze bounds that would divide by zero and unknown mounts."""
+ for name, value in (("step_size", self.step_size), ("gaze_limit", self.gaze_limit)):
+ if not (isinstance(value, (int, float)) and math.isfinite(value) and value > 0):
+ raise ValueError(f"GazeActionCfg.{name} must be positive and finite, got {value!r}.")
+ if self.mount not in ("fixed", "tracked"):
+ raise ValueError(f"GazeActionCfg.mount must be 'fixed' or 'tracked', got {self.mount!r}.")
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py
new file mode 100644
index 000000000000..04c7baebc966
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.py
@@ -0,0 +1,14 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Foveated camera sensors.
+
+Names are imported on first access, so reading the configuration does not load
+a renderer runtime.
+"""
+
+from isaaclab.utils.module import lazy_export
+
+lazy_export()
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi
new file mode 100644
index 000000000000..09fec5f420b4
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi
@@ -0,0 +1,16 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+__all__ = [
+ "FoveatedCamera",
+ "FoveatedCameraCfg",
+ "FoveatedNewtonCamera",
+ "FoveatedRTXCamera",
+]
+
+from .foveated_camera import FoveatedCamera
+from .foveated_camera_cfg import FoveatedCameraCfg
+from .foveated_newton_camera import FoveatedNewtonCamera
+from .foveated_rtx_camera import FoveatedRTXCamera
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py
new file mode 100644
index 000000000000..8dfa0d0ddc3b
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/calibrated_geometry.py
@@ -0,0 +1,96 @@
+# 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
+
+"""Retinal geometry shared by rendering and image sampling: the physical camera and the gaze frame."""
+
+from __future__ import annotations
+
+import math
+
+import torch
+from fovi.sensing.projection import CameraCalibration, angular_directions
+
+from isaaclab.sim import PinholeCameraCfg
+
+IDEAL_IMAGE_WIDTH = 1024
+"""Pixel width [px] of the image assigned to a camera derived from ideal spawn optics.
+
+The scale is arbitrary: the retinal window and the gaze are angles, so neither depends on it."""
+
+
+def camera_model_from_spawn(spawn: PinholeCameraCfg) -> CameraCalibration:
+ """Describe the camera that the spawn configuration creates as :class:`CameraModel` fields.
+
+ * An OpenCV model in ``spawn.distortion`` gives that calibrated camera. A fisheye
+ model with zero coefficients is an ideal equidistant fisheye.
+ * Plain pinhole optics give an ideal pinhole with the same field of view. Without
+ a vertical aperture, the image is square.
+
+ Raises:
+ ValueError: The spawn configuration is not a camera's, or describes a camera fovi cannot
+ model: a USD fisheye projection, thin-prism distortion, or an aperture offset.
+ """
+ if not isinstance(spawn, PinholeCameraCfg):
+ raise ValueError(f"{type(spawn).__name__} does not spawn a camera; set camera_model instead.")
+ distortion = spawn.distortion
+ if distortion is not None:
+ width, height = distortion.image_size
+ intrinsics = (distortion.fx, distortion.fy, distortion.cx, distortion.cy)
+ if distortion.model == "opencvFisheye":
+ calibration = CameraCalibration(model="fisheye", max_angle_deg=math.degrees(distortion.max_fov) / 2)
+ coefficients = (distortion.k1, distortion.k2, distortion.k3, distortion.k4)
+ elif distortion.model == "opencvPinhole":
+ calibration = CameraCalibration(model="pinhole")
+ coefficients = (
+ distortion.k1,
+ distortion.k2,
+ distortion.p1,
+ distortion.p2,
+ distortion.k3,
+ distortion.k4,
+ distortion.k5,
+ distortion.k6,
+ )
+ thin_prism = (distortion.s1, distortion.s2, distortion.s3, distortion.s4)
+ if distortion.apply_lens_distortion and any(thin_prism):
+ raise ValueError("Thin-prism distortion (s1-s4) is not supported; set camera_model instead.")
+ else:
+ raise ValueError(f"Unsupported lens distortion model {distortion.model!r}.")
+ calibration.update(image_size=(height, width), intrinsics=tuple(float(value) for value in intrinsics))
+ if distortion.apply_lens_distortion and any(coefficients):
+ calibration["distortion"] = tuple(float(value) for value in coefficients)
+ return calibration
+ if spawn.projection_type != "pinhole":
+ raise ValueError(
+ "Only pinhole spawn optics describe a camera; for a fisheye, set spawn.distortion to an "
+ "OpenCvFisheyeDistortionCfg or set camera_model."
+ )
+ if spawn.horizontal_aperture_offset or spawn.vertical_aperture_offset:
+ raise ValueError("Aperture offsets are not supported; set camera_model instead.")
+ vertical_aperture = spawn.vertical_aperture or spawn.horizontal_aperture
+ width = IDEAL_IMAGE_WIDTH
+ height = round(width * vertical_aperture / spawn.horizontal_aperture)
+ focal = spawn.focal_length / spawn.horizontal_aperture * width
+ return CameraCalibration(
+ model="pinhole", image_size=(height, width), intrinsics=(focal, focal, (width - 1) / 2, (height - 1) / 2)
+ )
+
+
+def retinal_directions(cartesian: torch.Tensor, fov_deg: float, image_rotation_deg: float = 0.0) -> torch.Tensor:
+ """Return OpenGL-frame angular rays, including the sensor mount roll."""
+ rays = angular_directions(cartesian, fov_deg)
+ rays = rays * rays.new_tensor((1, -1, -1))
+ angle = rays.new_tensor(image_rotation_deg * torch.pi / 180)
+ x, y, z = rays.unbind(-1)
+ return torch.stack((angle.cos() * x - angle.sin() * y, angle.sin() * x + angle.cos() * y, z), -1)
+
+
+def compose_rotations(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor:
+ """Compose small rotation matrices without TF32 tensor-core rounding.
+
+ Camera transforms need orthonormal rotations even when the surrounding
+ training process enables reduced-precision matrix multiplication.
+ """
+ return (left[..., :, :, None] * right[..., None, :, :]).sum(dim=-2)
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py
new file mode 100644
index 000000000000..afb5459230ba
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py
@@ -0,0 +1,580 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Foveated camera sensor and its virtual gaze."""
+
+from __future__ import annotations
+
+import math
+import warnings
+from collections.abc import Mapping, Sequence
+from typing import TYPE_CHECKING
+
+import torch
+import warp as wp
+from fovi.sensing.projection import CameraModel
+
+from isaaclab.sensors.camera.camera import Camera
+from isaaclab.utils.math import convert_camera_frame_orientation_convention, quat_error_magnitude
+from isaaclab.utils.warp import ProxyArray
+
+from .calibrated_geometry import camera_model_from_spawn, retinal_directions
+from .gaze_kernels import (
+ CameraParams,
+ apply_gaze_indexed_kernel,
+ apply_gaze_kernel,
+ camera_params,
+ publish_grid_kernel,
+ record_launch,
+ sensor_visibility_kernel,
+ set_gaze_kernel,
+ warp_stream,
+)
+from .native_grid import GRID_STYLE, buffer_tensor, native_grid_directions
+from .pooling import (
+ build_retinal_coords,
+ is_segmentation_output,
+ pool_hwc_buffer,
+ pool_segmentation_buffer,
+ segmentation_neighbor_indices,
+)
+
+if TYPE_CHECKING:
+ from .foveated_camera_cfg import FoveatedCameraCfg
+
+MOUNT_TURN_TOLERANCE_RAD = 1e-5
+"""Smallest change of a camera's mount orientation [rad] that counts as a turn; smaller ones are float rounding."""
+
+OPENGL_TO_ROS_AXES = (1.0, -1.0, -1.0)
+"""Axis signs between OpenGL camera-frame directions (x right, y up, -z forward) and ROS ones (x right, y down)."""
+
+
+class FoveatedCamera(Camera):
+ """Camera that samples the scene on a foveated retina instead of a uniform pixel grid.
+
+ The sample layout comes from :class:`fovi.sensing.coords.SamplingCoords`. Constructing this class returns the
+ implementation for the renderer selected by :attr:`FoveatedCameraCfg.renderer_cfg`:
+
+ * ``newton_warp`` and ``newton_optix``: :class:`~isaaclab_fovi.sensors.foveated_newton_camera.FoveatedNewtonCamera`,
+ which injects the foveated rays into Newton's renderer.
+ * ``isaac_rtx`` and ``ovrtx``: :class:`~isaaclab_fovi.sensors.foveated_rtx_camera.FoveatedRTXCamera`, which
+ authors a lens lookup table on the camera prim.
+
+ Both are subclasses of this class and are imported on first use, so selecting one renderer does not load the
+ other's runtime.
+
+ The gaze turns the retina relative to the optical axis of the physical camera it looks through. Newton and OVRTX
+ turn the rendered camera pose by the gaze in each pose update; Isaac RTX writes the turned pose into the camera
+ prims, which Replicator reads.
+ """
+
+ cfg: FoveatedCameraCfg
+
+ def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs):
+ """Create the implementation that matches the configured renderer.
+
+ Args:
+ cfg: Camera configuration with a concrete renderer configuration.
+
+ Raises:
+ ValueError: The configured renderer has no foveated implementation.
+ """
+ if cls is not FoveatedCamera:
+ return super().__new__(cls)
+ renderer_type = cfg.renderer_cfg.renderer_type
+ if renderer_type in ("newton_warp", "newton_optix"):
+ from .foveated_newton_camera import FoveatedNewtonCamera
+
+ return super().__new__(FoveatedNewtonCamera)
+ if renderer_type in ("isaac_rtx", "ovrtx"):
+ from .foveated_rtx_camera import FoveatedRTXCamera
+
+ return super().__new__(FoveatedRTXCamera)
+ raise ValueError(
+ f"Unsupported foveated renderer {renderer_type!r}; select 'newton_warp', 'newton_optix', 'isaac_rtx', or"
+ " 'ovrtx'."
+ )
+
+ def __init__(self, cfg: FoveatedCameraCfg, *, turns_pose_by_gaze: bool = False):
+ """Create the camera.
+
+ Raises:
+ ValueError: A Newton or OVRTX camera without ``update_latest_camera_pose``, whose renderer would never see
+ the gaze.
+ """
+ self._gaze_pose_reads_angles = turns_pose_by_gaze
+ """Whether the camera turns its pose by the stored gaze in each pose update, rather than writing prim poses
+ when the gaze is set; see :attr:`turns_pose_by_gaze`."""
+ if self._gaze_pose_reads_angles and not cfg.update_latest_camera_pose:
+ raise ValueError(
+ "Newton and OVRTX turn the rendered pose by the gaze in each pose update; set"
+ " update_latest_camera_pose=True so the renderer sees the gaze."
+ )
+ # The parent's initialisation updates poses before the gaze exists.
+ self._gaze_written = False
+ self._gaze_angles: ProxyArray | None = None
+ self._gaze_rotation: ProxyArray | None = None
+ self._visibility = None
+ self._grid_publish = None
+ self._published_shape: tuple[int, int] | None = None
+ self._segmentation_neighbors: torch.Tensor | None = None
+ self._sensor_fov_valid: torch.Tensor | None = None
+ self.mount_turns = 0
+ """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount."""
+ super().__init__(cfg)
+
+ @property
+ def image_shape(self) -> tuple[int, int]:
+ """(height, width) of the published outputs: the retina's grid, or (num_samples, 1) for sample sets."""
+ return self._published_shape if self._published_shape is not None else super().image_shape
+
+ @property
+ def sampling_coords(self):
+ """The :class:`SamplingCoords` of the published samples."""
+ return self._sampling_coords
+
+ @property
+ def num_valid_samples(self) -> int:
+ """Number of published foveated samples."""
+ return self._num_valid_samples
+
+ @property
+ def sensor_fov_valid_fraction(self) -> torch.Tensor | None:
+ """Per-environment fraction of samples inside the physical camera, or None before the first masked frame."""
+ return None if self._sensor_fov_valid is None else self._sensor_fov_valid.float().mean(dim=1)
+
+ @property
+ def camera_model(self) -> CameraModel:
+ """The physical camera the retina looks through, as resolved at initialization."""
+ return self._camera_model
+
+ @property
+ def projection_params(self) -> CameraParams:
+ """:attr:`camera_model` as a Warp struct, for kernels that project camera-frame directions."""
+ return self._gaze_camera
+
+ @property
+ def image_frame(self) -> wp.mat33f:
+ """Rotation from the upright image frame, in which gazes are measured, to the physical camera's frame (ROS
+ convention); it undoes ``cfg.image_rotation_deg``."""
+ return self._mask_frame
+
+ @property
+ def turns_pose_by_gaze(self) -> bool:
+ """Whether each pose update turns the rendered pose by the stored gaze (Newton and OVRTX). A writer of
+ :attr:`gaze_angles` then needs no other launch."""
+ return self._gaze_pose_reads_angles
+
+ @property
+ def gaze_angles(self) -> ProxyArray:
+ """The camera's stored gaze angles [deg], shape (num_envs,) of ``vec2f`` (Torch view (num_envs, 2)).
+
+ A writer that moves the gaze every step can update this buffer in place and pass its Torch view to
+ :meth:`set_gaze_angles`, which then copies nothing. Writes take effect when :meth:`set_gaze_angles` is called.
+ """
+ if self._gaze_angles is None:
+ self._allocate_gaze()
+ return self._gaze_angles
+
+ @property
+ def mount_quat_w_ros(self) -> ProxyArray:
+ """World orientation (x, y, z, w) of the physical camera before the gaze turns it, ROS convention, shape
+ (num_envs,) of ``quatf``.
+
+ Refreshed by each pose update that turns the gaze, so it follows a mount that moves, for example a camera on
+ a robot's head. Only cameras whose pose update turns the gaze (Newton and OVRTX) record it.
+ """
+ if not self._gaze_pose_reads_angles:
+ raise RuntimeError("Only cameras whose pose update turns the gaze (Newton, OVRTX) record their mount.")
+ if self._gaze_angles is None:
+ self._allocate_gaze()
+ return self._mount_quat_ros
+
+ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None:
+ """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis.
+
+ Positive tilt looks up and positive pan looks left. Zero looks along the
+ optical axis.
+
+ Args:
+ angles_deg: Gaze angles for every environment [deg], shape (num_envs, 2).
+
+ Raises:
+ ValueError: The angles do not hold one row per camera.
+ """
+ stored = self._gaze_angles is not None and angles_deg is self._gaze_angles.torch
+ if stored and self.turns_pose_by_gaze:
+ # The next pose update reads the stored angles; nothing has to happen now.
+ return
+ count = self._view.count
+ if tuple(angles_deg.shape) != (count, 2):
+ raise ValueError(f"Gaze angles must have shape ({count}, 2), got {tuple(angles_deg.shape)}.")
+ gaze = self.gaze_angles.torch
+ angles = angles_deg if stored else angles_deg.detach().to(device=gaze.device, dtype=torch.float32).contiguous()
+ # Callers usually pass the same buffer every step; record its launch once.
+ key = angles.data_ptr()
+ if key != self._gaze_angles_key:
+ self._gaze_angles_key = key
+ self._set_gaze_launch = record_launch(
+ set_gaze_kernel,
+ count,
+ [wp.from_torch(angles, dtype=wp.vec2f)],
+ [self._gaze_angles, self._gaze_rotation],
+ gaze.device,
+ )
+ self._set_gaze_launch.launch(warp_stream(gaze.device))
+ self._gaze_written = True
+
+ def ungazed_quat_w_ros(self) -> torch.Tensor:
+ """World orientation (x, y, z, w) of the physical camera now, before the gaze turns it, ROS convention, shape
+ (num_envs, 4)."""
+ if self._gaze_pose_reads_angles and self._gaze_angles is not None:
+ # The record starts at the pose before any gaze and follows each pose update.
+ return self._mount_quat_ros.torch.clone()
+ if self._gaze_written:
+ # The prims hold the gaze (Isaac RTX); get_world_poses reports the mount without it.
+ return self.get_world_poses(convention="ros")[1]
+ return self._data.quat_w_ros.torch.clone()
+
+ def set_world_poses(self, positions=None, orientations=None, env_ids=None, convention="ros"):
+ """Move the camera's mount; the gaze stays relative to the new mount.
+
+ Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses`.
+ """
+ if orientations is None:
+ # A position-only move keeps every mount's orientation.
+ super().set_world_poses(positions, orientations, env_ids, convention)
+ return
+ before = self._mount_orientations(env_ids)
+ super().set_world_poses(positions, orientations, env_ids, convention)
+ self._mount_written(env_ids)
+ self._count_mount_turn(before, env_ids)
+
+ def set_world_poses_from_view(self, eyes, targets, env_ids=None):
+ """Point the camera's mount from ``eyes`` at ``targets``; the gaze stays relative to the new mount.
+
+ Args are those of :meth:`isaaclab.sensors.Camera.set_world_poses_from_view`.
+ """
+ before = self._mount_orientations(env_ids)
+ super().set_world_poses_from_view(eyes, targets, env_ids)
+ # Rows whose eye equals their target are skipped by the base method and keep their poses.
+ turned = (self._as_device_tensor(eyes, 3) - self._as_device_tensor(targets, 3)).norm(dim=-1) > 0
+ self._mount_written(self._env_indices(env_ids)[turned])
+ self._count_mount_turn(before, env_ids)
+
+ def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None):
+ """Keep the camera as configured and warn the caller.
+
+ A foveated camera's projection comes from its retina and :attr:`camera_model`, which pinhole intrinsics
+ cannot describe, so this call changes nothing: the rendered rays and the reported intrinsic matrices stay as
+ configured. Stock cameras with an OpenCV lens model handle the call the same way. To change the projection,
+ configure :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.camera_model` (or ``spawn``) and
+ :attr:`~isaaclab_fovi.sensors.FoveatedCameraCfg.cmf_a_deg`.
+
+ Args are those of :meth:`isaaclab.sensors.Camera.set_intrinsic_matrices`.
+ """
+ warnings.warn(
+ "set_intrinsic_matrices() leaves a foveated camera as configured: its retina and camera_model set its"
+ " projection.",
+ UserWarning,
+ stacklevel=2,
+ )
+
+ def _prepare_sampling(self) -> None:
+ """Resolve physical calibration and retinal coordinates before the renderer sizes its buffers."""
+ calibration = self.cfg.camera_model
+ if calibration is None:
+ if self.cfg.spawn is None:
+ raise ValueError("A foveated camera on an existing prim needs camera_model.")
+ calibration = camera_model_from_spawn(self.cfg.spawn)
+ self._camera_model = CameraModel(**calibration)
+ self._sampling_coords, self._sampling_coords_highres = build_retinal_coords(self.cfg, self._camera_model, "cpu")
+ self._ray_coords = self._sampling_coords_highres or self._sampling_coords
+ self._native_grid = self.cfg.foveated_style == GRID_STYLE
+ self._num_valid_samples = len(self._sampling_coords)
+ self._num_ray_samples = len(self._ray_coords)
+
+ def _initialize_sampling(self) -> None:
+ """Move retinal coordinates to the sensor device and prepare the gaze rays and frame conversions."""
+ self._sampling_coords = self._sampling_coords.to(device=self._device)
+ if self._sampling_coords_highres is not None:
+ self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device)
+ self._ray_coords = self._sampling_coords_highres or self._sampling_coords
+ self._gaze_camera = camera_params(self._camera_model)
+ coords = self._ray_coords
+ rotation_deg = self.cfg.image_rotation_deg
+ # The rays as rendered, mount roll included, in the ROS frame the camera model projects.
+ if coords.style == GRID_STYLE:
+ rays = native_grid_directions(coords, image_rotation_deg=rotation_deg)
+ else:
+ rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg)
+ self._gaze_rays = (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous()
+ # No gaze until one is set: the camera looks along its optical axis untouched.
+ self._gaze_angles = None
+ self._gaze_rotation = None
+ self._visibility = None
+ device = self._gaze_rays.device
+ self._gaze_identity = torch.eye(3, device=device)
+ angle = math.radians(rotation_deg)
+ c, s = math.cos(angle), math.sin(angle)
+ # Gaze is defined in the upright image frame; the basis carries it into the rolled OpenGL camera frame.
+ self._gaze_basis = self._gaze_rays.new_tensor(((c, s, 0), (s, -c, 0), (0, 0, -1)))
+ # The same roll in the ROS frame: a rendered ray r reaches the physical camera at K gaze K^T r.
+ self._mask_frame = wp.mat33f(c, s, 0.0, -s, c, 0.0, 0.0, 0.0, 1.0)
+ # Fixed right-multiplied frame changes, on the CPU in float64, where no reduced-precision matmul applies.
+ identity = torch.tensor([[0.0, 0.0, 0.0, 1.0]], dtype=torch.float64)
+ to_opengl = convert_camera_frame_orientation_convention(identity, origin="world", target="opengl")[0].tolist()
+ to_world = convert_camera_frame_orientation_convention(identity, origin="opengl", target="world")[0].tolist()
+ to_ros = convert_camera_frame_orientation_convention(identity, origin="world", target="ros")[0].tolist()
+ self._gaze_frames = (
+ wp.mat33f(*self._gaze_basis.flatten().tolist()),
+ wp.quatf(*to_opengl),
+ wp.quatf(*to_world),
+ wp.quatf(*to_ros),
+ )
+
+ def _allocate_gaze(self) -> None:
+ """Allocate one stored gaze per camera, on the optical axis, its rotation and the mount, on the sensor
+ device."""
+ count, device = self._view.count, str(self._device)
+ self._gaze_angles = ProxyArray(wp.zeros(count, dtype=wp.vec2f, device=device))
+ self._gaze_rotation = ProxyArray(
+ wp.from_torch(torch.eye(3, device=device).repeat(count, 1, 1), dtype=wp.mat33f)
+ )
+ # No gaze has turned the pose yet, so the current orientation is the mount.
+ mount = self._data.quat_w_ros.torch.clone()
+ self._mount_quat_ros = ProxyArray(wp.from_torch(mount, dtype=wp.quatf))
+ self._gaze_angles_key = None
+ self._gaze_pose_launches: dict[str, tuple[wp.Launch, tuple]] = {}
+ self._gaze_no_mask = wp.zeros(1, dtype=wp.bool, device=device)
+
+ def _update_camera_state(
+ self,
+ env_ids: wp.array | None = None,
+ env_mask: wp.array | None = None,
+ pos_src: wp.array | None = None,
+ quat_src: wp.array | None = None,
+ update_pose: bool = False,
+ frame_op: int = 0,
+ ):
+ """Update the camera state; when the pose update turns the gaze, turn freshly read poses before the renderer
+ sees them."""
+ super()._update_camera_state(env_ids, env_mask, pos_src, quat_src, update_pose, frame_op)
+ if update_pose and self._gaze_pose_reads_angles:
+ self._apply_gaze_pose(env_ids, env_mask)
+
+ def _apply_gaze_pose(
+ self, env_ids: Sequence[int] | wp.array | None = None, env_mask: wp.array | None = None
+ ) -> None:
+ """Turn the camera's world orientation by the stored gaze, and record the gaze rotations and the mount."""
+ if self._gaze_angles is None:
+ return
+ orientation = self._data.quat_w_world.warp
+ device = self._gaze_angles.torch.device
+ frames = (self._gaze_angles, *self._gaze_frames)
+ outputs = [orientation, self._gaze_rotation, self._mount_quat_ros]
+ indexed = env_ids is not None and env_mask is None
+ if indexed:
+ # The kernel takes contiguous int32 indices; this converts sequences, slices, tensors and Warp arrays.
+ env_ids = self._resolve_env_ids_wp(env_ids)
+ # Every pose update writes the same pose buffer: for all environments, under the camera's update mask, or
+ # for the indexed ones, whose indices each call swaps in.
+ mode = "ids" if indexed else ("all" if env_mask is None else "mask")
+ launch, sources = self._gaze_pose_launches.get(mode, (None, None))
+ if sources is None or sources[0] is not orientation or (mode == "mask" and sources[1] is not env_mask):
+ if indexed:
+ launch = record_launch(apply_gaze_indexed_kernel, len(env_ids), [*frames, env_ids], outputs, device)
+ else:
+ mask = [self._gaze_no_mask if env_mask is None else env_mask, int(env_mask is not None)]
+ launch = record_launch(apply_gaze_kernel, self._view.count, [*frames, *mask], outputs, device)
+ self._gaze_pose_launches[mode] = (launch, (orientation, env_mask))
+ if indexed:
+ if len(env_ids) == 0:
+ return
+ launch.set_param_by_name("indices", env_ids)
+ launch.set_dim(len(env_ids))
+ launch.launch(warp_stream(device))
+
+ def _mount_orientations(self, env_ids) -> torch.Tensor:
+ """The selected cameras' mount orientations (x, y, z, w), world convention, as :meth:`get_world_poses` reports
+ them."""
+ return self.get_world_poses(env_ids, convention="world")[1].clone()
+
+ def _mount_written(self, env_ids) -> None:
+ """Called after a pose write turned the selected cameras' mounts, before the turn is measured. Cameras that
+ hold the gaze in their prims write it onto the new mounts here."""
+
+ def _count_mount_turn(self, before: torch.Tensor, env_ids) -> None:
+ """Count a mount turn if any selected camera's mount now differs from ``before``.
+
+ The teachers read the camera's live position, so only orientation changes count, and writing back the reported
+ poses does not.
+ """
+ turned = quat_error_magnitude(before, self._mount_orientations(env_ids)) > MOUNT_TURN_TOLERANCE_RAD
+ if bool(turned.any()):
+ self.mount_turns += 1
+
+ def _env_indices(self, env_ids) -> torch.Tensor:
+ """The camera indices that ``env_ids`` selects, as a tensor."""
+ if env_ids is None:
+ return torch.arange(self._view.count, device=self._device)
+ if isinstance(env_ids, slice):
+ return torch.arange(self._view.count, device=self._device)[env_ids]
+ if isinstance(env_ids, wp.array):
+ env_ids = wp.to_torch(env_ids)
+ return torch.as_tensor(env_ids, device=self._device, dtype=torch.long).reshape(-1)
+
+ def _visibility_buffers(self) -> dict:
+ """The sensor mask's camera-owned buffers, allocated once: the rendered rays, an unturned rotation per camera,
+ each sample's visibility and, for the updated rows, which samples to hide."""
+ if self._visibility is None:
+ count, device = self._view.count, self._gaze_rays.device
+ shape = (count, len(self._gaze_rays))
+ self._visibility = {
+ "rays": wp.from_torch(self._gaze_rays, dtype=wp.vec3f),
+ "identity": wp.from_torch(self._gaze_identity.expand(count, -1, -1).contiguous(), dtype=wp.mat33f),
+ "every_env": wp.ones(count, dtype=wp.bool, device=str(device)),
+ "valid": ProxyArray(wp.zeros(shape, dtype=wp.bool, device=str(device))),
+ "hidden": ProxyArray(wp.zeros(shape, dtype=wp.bool, device=str(device))),
+ "launch": None,
+ }
+ return self._visibility
+
+ def _gaze_validity(self, env_mask: wp.array | None = None) -> torch.Tensor:
+ """Which samples the physical camera sees at each updated environment's gaze, shape (num_envs, num_samples).
+
+ Each rendered ray is tested by its center direction. Environments outside ``env_mask`` keep their last
+ visibility; None updates every one.
+ """
+ buffers = self._visibility_buffers()
+ rotation = buffers["identity"] if self._gaze_rotation is None else self._gaze_rotation.warp
+ updated = buffers["every_env"] if env_mask is None else env_mask
+ cached = buffers["launch"]
+ if cached is None or cached[0] is not rotation or cached[1] is not updated:
+ launch = record_launch(
+ sensor_visibility_kernel,
+ buffers["valid"].warp.shape,
+ [buffers["rays"], rotation, self._mask_frame, self._gaze_camera, updated],
+ [buffers["valid"], buffers["hidden"]],
+ self._gaze_rays.device,
+ )
+ buffers["launch"] = cached = (rotation, updated, launch)
+ cached[2].launch(warp_stream(self._gaze_rays.device))
+ return buffers["valid"].torch
+
+ def _apply_sensor_fov_mask(self, outputs: Mapping[str, torch.Tensor], env_mask: wp.array | None = None) -> None:
+ """Zero the samples outside the physical camera at the current gaze in the updated environments' (B, N, 1, C)
+ outputs; None updates every environment."""
+ if not self.cfg.mask_to_sensor_fov:
+ return
+ tensors = {name: buffer_tensor(value) for name, value in outputs.items()}
+ self._sensor_fov_valid = self._gaze_validity(env_mask)
+ hidden = self._visibility["hidden"].torch[:, :, None, None]
+ for name, tensor in tensors.items():
+ if name == "rgb" and "rgba" in tensors:
+ continue
+ tensor.masked_fill_(hidden, 0)
+
+ def _prepare_segmentation_pooling(self, names) -> None:
+ """Take the modal-label neighbourhoods of pooled segmentation outputs among ``names`` from the main pooler."""
+ self._segmentation_neighbors = (
+ segmentation_neighbor_indices(self._pooler) if any(is_segmentation_output(name) for name in names) else None
+ )
+
+ def _pool_output(self, name: str, samples: torch.Tensor) -> torch.Tensor:
+ """Pool one output's high-resolution samples (B, N_hi, 1, C) to the retina's (B, N_lo, 1, C), in its dtype.
+
+ Segmentation takes each sample's modal label in its native dtype; other outputs are pooled in float with
+ ``pool_mode``. With :attr:`~FoveatedCameraCfg.mask_to_sensor_fov`, photoreceptors outside the physical camera's
+ image at the current gaze are left out, so a pooled sample at the image edge is not darkened by them.
+ """
+ visible = self._visibility["valid"].torch if self.cfg.mask_to_sensor_fov else None
+ if is_segmentation_output(name):
+ return pool_segmentation_buffer(self._segmentation_neighbors, samples, visible)
+ pooled = pool_hwc_buffer(self._pooler, samples.float(), visible)
+ if not samples.dtype.is_floating_point:
+ # Round to the nearest value the output can hold, e.g. 0-255 for RGB, rather than truncating.
+ limits = torch.iinfo(samples.dtype)
+ pooled = pooled.round().clamp(limits.min, limits.max)
+ return pooled.to(samples.dtype)
+
+ def _prepare_grid_publish(self, sources: Mapping[str, torch.Tensor]) -> None:
+ """Byte views of each rendered output, shape (num_envs, num_samples, channels), and of its public grid, for
+ :func:`publish_grid_kernel`."""
+ views = []
+ for name, source in sources.items():
+ if name == "rgb" and "rgba" in sources:
+ continue
+ target = self._grid_output[name].view(source.shape[0], -1, source.shape[-1])
+ views.append((wp.from_torch(source.view(torch.uint8)), wp.from_torch(target.view(torch.uint8))))
+ self._grid_indices_wp = wp.from_torch(self._grid_indices.to(torch.int32).contiguous())
+ self._grid_footprint_wp = wp.from_torch(self._ray_coords.valid_mask.contiguous())
+ num_envs = views[0][1].shape[0]
+ if self.cfg.mask_to_sensor_fov:
+ buffers = self._visibility_buffers()
+ self._grid_every_env = buffers["every_env"]
+ self._grid_sensor = (
+ buffers["rays"],
+ buffers["identity"],
+ self._mask_frame,
+ self._gaze_camera,
+ buffers["valid"].warp,
+ )
+ else:
+ self._grid_every_env = wp.ones(num_envs, dtype=wp.bool, device=str(self._device))
+ # Placeholders: the kernel reads none of these without the sensor mask.
+ self._grid_sensor = (
+ wp.zeros(1, dtype=wp.vec3f, device=self._device),
+ wp.zeros(1, dtype=wp.mat33f, device=self._device),
+ wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
+ CameraParams(),
+ wp.zeros((1, 1), dtype=wp.bool, device=self._device),
+ )
+ self._grid_publish = views
+ self._grid_launches = None
+
+ def _publish_grid(self, env_mask: wp.array | None = None) -> None:
+ """Mask and lay out every output of the updated environments in one launch each; the result equals masking,
+ then copying to the grid. The other environments keep their last published frame; None updates every one."""
+ mask = self.cfg.mask_to_sensor_fov
+ env_mask = self._grid_every_env if env_mask is None else env_mask
+ rays, identity, frame, camera, visible = self._grid_sensor
+ rotation = identity if not mask or self._gaze_rotation is None else self._gaze_rotation.warp
+ cached = self._grid_launches
+ if cached is None or cached[0][0] is not rotation or cached[0][1] is not env_mask:
+ launches = [
+ record_launch(
+ publish_grid_kernel,
+ (target.shape[0], target.shape[1]),
+ [
+ source,
+ self._grid_indices_wp,
+ self._grid_footprint_wp,
+ env_mask,
+ rays,
+ rotation,
+ frame,
+ camera,
+ int(mask),
+ int(mask and index == 0),
+ visible,
+ ],
+ [target],
+ self._device,
+ )
+ for index, (source, target) in enumerate(self._grid_publish)
+ ]
+ self._grid_launches = ((rotation, env_mask), launches)
+ stream = warp_stream(self._device)
+ for launch in self._grid_launches[1]:
+ launch.launch(stream)
+ if mask:
+ self._sensor_fov_valid = self._visibility["valid"].torch
+
+ def _set_published_shape(self, outputs: Mapping[str, torch.Tensor]) -> None:
+ """Report the (height, width) of the published outputs, which differ from the rendered ones."""
+ tensor = next(iter(outputs.values())).torch
+ self._published_shape = (int(tensor.shape[1]), int(tensor.shape[2]))
+ self._data.image_shape = self._published_shape
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py
new file mode 100644
index 000000000000..1dc9b4e9533b
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py
@@ -0,0 +1,130 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Configuration for the FoveatedCamera sensor."""
+
+from __future__ import annotations
+
+import math
+from typing import TYPE_CHECKING
+
+from fovi.sensing.coords import RADIUS_NORMS, WARPED_CARTESIAN_STYLES
+from fovi.sensing.projection import CameraCalibration
+
+from isaaclab.sensors.camera.camera_cfg import CameraCfg
+from isaaclab.utils.configclass import configclass
+
+if TYPE_CHECKING:
+ from .foveated_camera import FoveatedCamera
+
+
+POOL_MODES = ("avg", "gaussian", "max", "sum")
+"""fovi pooling modes for the outputs other than segmentation."""
+
+
+@configclass
+class FoveatedCameraCfg(CameraCfg):
+ """Configuration for a foveated camera, whose retina samples densely where it looks and sparsely in the periphery.
+
+ See :ref:`concepts_sensors_foveated_camera` for how each setting shapes the retina.
+ """
+
+ class_type: type[FoveatedCamera] | str = "{DIR}.foveated_camera:FoveatedCamera"
+
+ # -- Foveation parameters ------------------------------------------------
+
+ cmf_a_deg: float = 0.591
+ """CMF constant *a* [deg]: smaller foveates more strongly; the default is an estimate from human vision."""
+
+ camera_model: CameraCalibration | None = None
+ """The physical camera as ``CameraModel`` fields; None uses the camera that :attr:`spawn` creates."""
+
+ foveated_res: int = 60
+ """Grid side of the retina; isotropic retinas use as many rings as keep at most its square of samples."""
+
+ foveated_style: str = "warped_cartesian_as_grid"
+ """Sampling style: the default grid publishes an upright image; sample-set styles publish a list of samples."""
+
+ fov_type: str = "circular"
+ """Region of the visual field the retina covers: ``"circular"``, ``"square"`` or ``"wang"``."""
+
+ radius_norm: float = 2.0
+ """Norm of the warped-Cartesian sampling shells: 2.0 for circular shells, infinity for square ones."""
+
+ isotropic_plotting_type: str = "v1like"
+ """Cortical layout of an isotropic retina's samples: ``"v1like"``, ``"schwartz"`` or ``"warp"``."""
+
+ image_rotation_deg: float = 0.0
+ """Counter-clockwise roll [deg] of the rays about the optical axis that undoes a rolled mount."""
+
+ mask_to_sensor_fov: bool = False
+ """Zero the samples outside the physical camera's image at the current gaze."""
+
+ retinal_window_fraction: float = 1.0
+ """Diameter of the retinal window as a fraction of the reference image side."""
+
+ retinal_window_reference_side: str = "short"
+ """Image side defining the retinal window diameter: ``short`` or ``long``."""
+
+ # -- Optional retinal pooling (photoreceptor -> RGC two-layer sampling) --
+
+ pool_enabled: bool = False
+ """Render a denser photoreceptor grid and pool it to the retina."""
+
+ pool_res_mult: float = 2
+ """How many times denser the photoreceptor grid is than the retina; an integer for grid styles."""
+
+ pool_k: int | None = None
+ """Photoreceptors each sample pools: a square window's area for grid styles, else nearest neighbours."""
+
+ pool_mode: str = "avg"
+ """Pooling of non-segmentation outputs: ``"avg"``, ``"gaussian"``, ``"max"``, or ``"sum"`` for sample sets."""
+
+ pool_sample_cortex: bool | str = "geodesic"
+ """Neighbour distance for sample sets: ``"geodesic"`` on the cortex, ``True`` cortical, ``False`` visual."""
+
+ pool_gauss_sigma: float = 10.0
+ """Gaussian sigma for ``pool_mode="gaussian"``."""
+
+ pool_int_mode: str = "modal"
+ """Pooling of segmentation outputs: ``"modal"``, each sample's most common label among its neighbours."""
+
+ # -- RTX-specific parameters (ignored by Newton backend) ----------------
+
+ exit_texture_size: int | None = None
+ """Side of the RTX inverse lens texture; None uses ``max(128, 4 * grid side)``."""
+
+ # Render dimensions come from the retinal samples. On Newton, these initial dimensions also determine the
+ # aspect ratio used to infer an unspecified vertical aperture when spawning the camera.
+ width: int = 1
+ height: int = 1
+
+ update_latest_camera_pose: bool = True
+ """Update the camera pose every frame. Newton and OVRTX require it: their pose update applies the gaze."""
+
+ def __post_init__(self):
+ super().__post_init__()
+ # Reject incompatible geometry before the renderer creates the retina.
+ if self.radius_norm not in RADIUS_NORMS:
+ raise ValueError(f"radius_norm must be one of {RADIUS_NORMS}, got {self.radius_norm!r}.")
+ if self.radius_norm != 2.0 and self.foveated_style not in WARPED_CARTESIAN_STYLES:
+ raise ValueError("Non-default radius_norm requires a warped_cartesian style.")
+ if self.radius_norm == math.inf and self.fov_type == "wang":
+ raise ValueError("radius_norm=inf does not support fov_type='wang'.")
+ if self.pool_mode not in POOL_MODES:
+ raise ValueError(
+ f"pool_mode must be one of {POOL_MODES}, got {self.pool_mode!r}; segmentation pools with pool_int_mode."
+ )
+ if self.pool_int_mode not in ("modal",):
+ raise ValueError(
+ f"pool_int_mode must be one of ('modal',), got {self.pool_int_mode!r}: segmentation"
+ " pools by modal label, since other modes would mix labels into ones no object has."
+ )
+ # Tensor processors such as PPISP process a pixel image; the camera renders and publishes retinal samples.
+ if self.tensor_processors or self.isp_cfg is not None:
+ raise ValueError(
+ "FoveatedCameraCfg does not support tensor_processors or isp_cfg (for example PPISP): they"
+ " process pixel images, and a foveated camera publishes retinal samples."
+ )
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py
new file mode 100644
index 000000000000..97c7bc35424a
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py
@@ -0,0 +1,191 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Newton foveated camera: Newton's Warp renderer casts one ray per retinal sample."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING
+
+import torch
+import warp as wp
+
+from isaaclab.utils.warp import ProxyArray
+
+from .foveated_camera import OPENGL_TO_ROS_AXES, FoveatedCamera
+from .native_grid import (
+ allocate_outputs,
+ copy_grid_outputs,
+ copy_updated_rows,
+ grid_output_shape,
+ grid_sample_indices,
+ mask_grid_samples,
+ proxy_outputs,
+)
+from .pooling import build_pooler
+
+if TYPE_CHECKING:
+ from .foveated_camera_cfg import FoveatedCameraCfg
+
+logger = logging.getLogger(__name__)
+
+
+def explicit_rays(directions: torch.Tensor, height: int, width: int) -> wp.array:
+ """Newton's ray array, shape (height, width, 1, 2): a zero origin and a unit direction per ray, shared by every
+ camera.
+
+ Args:
+ directions: Unit ray directions in the OpenGL camera frame, in sample order, shape (N, 3).
+ height: Rendered rows.
+ width: Rendered columns; ``height * width`` must cover the N rays. Padding repeats the last ray.
+ """
+ if directions.ndim != 2 or directions.shape[1] != 3:
+ raise ValueError(f"Ray directions must have shape (N, 3), got {tuple(directions.shape)}.")
+ if height * width < len(directions):
+ raise ValueError(f"A {height}x{width} render cannot hold {len(directions)} rays.")
+ index = torch.arange(height * width, device=directions.device).clamp_max(len(directions) - 1)
+ rays = directions.new_zeros(height, width, 1, 2, 3, dtype=torch.float32)
+ rays[..., 1, :] = directions.float()[index].reshape(height, width, 1, 3)
+ # The Warp view keeps the tensor alive.
+ return wp.from_torch(rays, dtype=wp.vec3f)
+
+
+class FoveatedNewtonCamera(FoveatedCamera):
+ """Newton camera that renders with foveated (CMF-distributed) rays.
+
+ Instead of a uniform pixel grid, this sensor shoots *N* rays whose
+ directions are derived from :class:`fovi.sensing.coords.SamplingCoords`
+ and injected into Newton's renderer, with Warp or OptiX traversal. Vector sensors publish
+ ``(B, N, 1, C)``; native grid sensors publish upright ``(B, H, W, C)``.
+
+ The samples cover the retinal window of the physical camera; the gaze turns the rendered camera pose.
+ """
+
+ cfg: FoveatedCameraCfg
+
+ def __init__(self, cfg: FoveatedCameraCfg):
+ super().__init__(cfg, turns_pose_by_gaze=True)
+
+ def _initialize_impl(self):
+ # The pooler's KNN tensors are plain attributes that nn.Module.to() does not move, so the coordinates start on
+ # the CPU and the pooler is built on the sensor device after the parent initializes.
+ self._prepare_sampling()
+ logger.info(
+ "FoveatedNewtonCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg",
+ self._num_valid_samples,
+ self._num_ray_samples,
+ self.cfg.foveated_style,
+ self._sampling_coords.cmf_a,
+ self._sampling_coords.fov,
+ )
+
+ # The parent allocates render buffers for the rendered rays: the high-resolution ones when pooling.
+ self.cfg.height, self.cfg.width = grid_output_shape(self._ray_coords)
+ renderer = self.cfg.renderer_cfg
+ if renderer.render_order == "tiled":
+ tile_width = renderer.tile_rendering_width
+ tile_height = renderer.tile_rendering_height
+ if tile_width <= 0 or tile_height <= 0:
+ raise ValueError("Newton render tile dimensions must be positive.")
+ # A native grid renders at its own size: Newton's tiled kernel skips pixels past a partial tile.
+ if not self._native_grid:
+ # Pack consecutive vector rays into complete tiles. Padding is
+ # private renderer storage and never enters masking or pooling.
+ self.cfg.width = tile_width
+ self.cfg.height = (
+ (self._num_ray_samples + tile_width * tile_height - 1) // (tile_width * tile_height) * tile_height
+ )
+
+ super()._initialize_impl()
+
+ self._initialize_sampling()
+ self._pooler, pool_k = build_pooler(
+ self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device)
+ )
+
+ # The gaze geometry's rendered rays, in canonical sample order and rolled by image_rotation_deg, back in the
+ # OpenGL frame Newton traces.
+ ray_directions = self._gaze_rays * self._gaze_rays.new_tensor(OPENGL_TO_ROS_AXES)
+ self._render_data.camera_rays = explicit_rays(ray_directions, self.cfg.height, self.cfg.width)
+ render_samples = self.cfg.height * self.cfg.width
+ # Renderer buffers remain whole tiles; zero-copy canonical views hide
+ # trailing padding and preserve every output's dtype and sample order.
+ # Keep the backing buffers alive for the renderer's non-owning views.
+ self._render_output = dict(self._data.output)
+ self._flat_render_output = {}
+ for name, value in self._render_output.items():
+ tensor = value.torch
+ flat = tensor.view(tensor.shape[0], render_samples, 1, tensor.shape[-1])
+ self._flat_render_output[name] = ProxyArray(wp.from_torch(flat[:, : self._num_ray_samples]))
+ source = self._flat_render_output
+ if self._pooler is not None:
+ self._pooled_output = allocate_outputs(source, self._num_valid_samples, 1)
+ self._prepare_segmentation_pooling(source)
+ dtypes = {name: str(buf.dtype).removeprefix("torch.") for name, buf in source.items()}
+ logger.info(
+ "FoveatedNewtonCamera: %s pooling (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d) outputs=%s",
+ type(self._pooler).__name__,
+ self.cfg.pool_mode,
+ pool_k,
+ self.cfg.pool_sample_cortex,
+ self._num_ray_samples,
+ self._num_valid_samples,
+ dtypes,
+ )
+ source = self._pooled_output
+ self._sample_output = None
+ if self._pooler is None and not self._native_grid:
+ # Newton redraws every environment, so sample sets publish a copy that changes only on update.
+ self._sample_output = {
+ name: torch.zeros_like(value.torch)
+ for name, value in self._flat_render_output.items()
+ if not (name == "rgb" and "rgba" in self._flat_render_output)
+ }
+ if "rgba" in self._sample_output and "rgb" in self._flat_render_output:
+ self._sample_output["rgb"] = self._sample_output["rgba"][..., :3]
+ source = self._sample_output
+ if self._native_grid:
+ self._grid_output = allocate_outputs(source, *grid_output_shape(self._sampling_coords))
+ self._grid_indices = grid_sample_indices(self._sampling_coords)
+ source = self._grid_output
+ # The buffers the camera publishes: stable for the camera's lifetime and refilled each frame.
+ self._data.output.clear()
+ self._data.output.update(proxy_outputs(source))
+ self._set_published_shape(self._data.output)
+ if self._native_grid and self._pooler is None:
+ self._prepare_grid_publish(
+ {name: value.torch.squeeze(2) for name, value in self._flat_render_output.items()}
+ )
+
+ def _update_buffers_impl(self, env_mask: wp.array):
+ """Render, then mask and publish the updated environments, pooling high-resolution samples if enabled.
+
+ Newton redraws every environment's render buffer, each at the pose and gaze it last received. The sensor mask,
+ its visibility record and the published buffers, which the camera owns, change only for the updated
+ environments.
+ """
+ super()._update_buffers_impl(env_mask)
+ if not self._env_mask_has_any(env_mask):
+ return
+ if self._pooler is None:
+ if self._grid_publish:
+ self._publish_grid(env_mask)
+ else:
+ self._apply_sensor_fov_mask(self._flat_render_output, env_mask)
+ for name, samples in self._sample_output.items():
+ if name == "rgb" and "rgba" in self._sample_output:
+ continue # rgba alias
+ copy_updated_rows(self._flat_render_output[name].torch, samples, env_mask)
+ return
+ mask_grid_samples(self._flat_render_output, self._ray_coords)
+ self._apply_sensor_fov_mask(self._flat_render_output, env_mask)
+ for name, hi in self._flat_render_output.items():
+ if name == "rgb" and "rgba" in self._flat_render_output:
+ continue # rgba alias
+ # Pooling covers every environment; only the updated ones are published.
+ copy_updated_rows(self._pool_output(name, hi.torch), self._pooled_output[name], env_mask)
+ if self._native_grid:
+ copy_grid_outputs(self._pooled_output, self._grid_output, self._grid_indices)
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py
new file mode 100644
index 000000000000..3b58a42c0acf
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_rtx_camera.py
@@ -0,0 +1,338 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""RTX foveated tiled camera sensor.
+
+Subclasses :class:`isaaclab.sensors.Camera` to render foveated images
+via the RTX path tracer using ``OmniLensDistortionLutAPI`` textures.
+Per-sample values are extracted from the rendered 2D texture to produce
+vector ``(B, N, 1, C)`` or upright native-grid ``(B, H, W, C)`` output buffers,
+identical to :class:`FoveatedNewtonCamera`.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+import tempfile
+from collections.abc import Sequence
+from typing import TYPE_CHECKING
+
+import torch
+import warp as wp
+
+from isaaclab import sim as sim_utils
+from isaaclab.sensors.camera.camera import Camera
+from isaaclab.utils import clone
+from isaaclab.utils.math import convert_camera_frame_orientation_convention, matrix_from_quat, quat_from_matrix
+
+from . import lens_lut
+from .calibrated_geometry import compose_rotations, retinal_directions
+from .foveated_camera import FoveatedCamera
+from .native_grid import (
+ allocate_outputs,
+ copy_grid_outputs,
+ copy_updated_rows,
+ grid_output_shape,
+ grid_sample_indices,
+ mask_grid_samples,
+ proxy_outputs,
+)
+from .pooling import build_pooler
+
+if TYPE_CHECKING:
+ from isaaclab.utils.warp import ProxyArray
+
+ from .foveated_camera_cfg import FoveatedCameraCfg
+
+logger = logging.getLogger(__name__)
+
+
+class FoveatedRTXCamera(FoveatedCamera):
+ """RTX camera that renders with foveated (CMF-distributed) rays.
+
+ Instead of Newton's Warp ray arrays, this sensor creates
+ ``OmniLensDistortionLutAPI`` Camera prims with LUT textures that define
+ per-texel ray directions. The RTX path tracer renders a 2D texture
+ which is then sampled at pre-computed UV positions to extract per-sample
+ values, producing ``(B, N, 1, C)`` output buffers.
+
+ Grid styles render straight into their native grid. Sample-set styles are
+ packed onto a cortical disc, which keeps neighbouring samples adjacent for
+ DLSS denoising. Camera motion comes from the prim's parent and from the gaze.
+ """
+
+ cfg: FoveatedCameraCfg
+
+ def __init__(self, cfg: FoveatedCameraCfg):
+ ovrtx = cfg.renderer_cfg.renderer_type == "ovrtx"
+ if ovrtx and cfg.renderer_cfg.async_rendering and cfg.mask_to_sensor_fov:
+ raise ValueError(
+ "OVRTX async_rendering returns the previous capture, which the sensor mask would cut with the current"
+ " gaze. Disable async_rendering or mask_to_sensor_fov."
+ )
+ # The parent ``Camera`` allocates the renderer-bound texture buffers; the published ones follow from them.
+ self._texture_output: dict[str, ProxyArray] = {}
+ self._foveated_output: dict[str, torch.Tensor] = {}
+ self._pooled_output: dict[str, torch.Tensor] | None = None
+ # The projection sets the texture size on the configuration before the parent allocates for it; the caller's
+ # configuration stays untouched.
+ # The textures are square, so the parent's inferred vertical aperture agrees with the lens calibration.
+ cfg = clone(cfg)
+ self.cfg = cfg
+ self._prepare_projection()
+ # OVRTX uses the pose the camera hands it. Replicator reads the camera prims.
+ super().__init__(cfg, turns_pose_by_gaze=ovrtx)
+ # The lens belongs to the camera prims from construction: OVRTX snapshots the stage when the renderer starts.
+ for prim in sim_utils.find_matching_prims(self.cfg.prim_path, self.stage):
+ # A locked camera may be treated as static, which skips the motion vectors that DLSS reprojection needs;
+ # the gaze moves every foveated camera.
+ lock = prim.GetAttribute("omni:kit:cameraLock")
+ if lock.IsValid() and lock.Get():
+ lock.Set(False)
+ lens_lut.apply_lens_lut_to_prim(prim, self._dir_tex_path, self._exit_tex_path)
+
+ def __del__(self, *args, **kwargs):
+ """Release the renderer, then the lens textures it reads."""
+ super().__del__(*args, **kwargs)
+ lut_dir = getattr(self, "_lut_dir", None)
+ if lut_dir is not None:
+ lut_dir.cleanup()
+ self._lut_dir = None
+
+ @property
+ def supports_batch_update(self) -> bool:
+ return True
+
+ def set_gaze_angles(self, angles_deg: torch.Tensor) -> None:
+ super().set_gaze_angles(angles_deg)
+ if not self._gaze_pose_reads_angles:
+ self._write_gaze_local_pose()
+
+ def get_world_poses(self, env_ids=None, convention="ros"):
+ """Read the cameras' mount poses, without the gaze, as every foveated camera reports them.
+
+ Isaac RTX holds the gaze in the camera prims, so it is taken back out; passing the result to
+ :meth:`set_world_poses` keeps the mount and the gaze as they are.
+
+ Args and returns are those of :meth:`isaaclab.sensors.Camera.get_world_poses`.
+ """
+ positions, orientations = super().get_world_poses(env_ids, convention="opengl")
+ if not self._gaze_pose_reads_angles and self._gaze_rotation is not None:
+ # The prims hold the mount turned by the gaze's rotation in their own (OpenGL) frame.
+ basis = self._gaze_basis
+ gaze = self._gaze_rotation.torch[self._env_indices(env_ids)]
+ with torch.autocast(basis.device.type, enabled=False):
+ relative = compose_rotations(compose_rotations(basis, gaze), basis.T)
+ orientations = quat_from_matrix(
+ compose_rotations(matrix_from_quat(orientations), relative.transpose(-1, -2))
+ )
+ return positions, convert_camera_frame_orientation_convention(orientations, origin="opengl", target=convention)
+
+ def process_rendered_frame(self) -> None:
+ """Mask and publish the frame of the environments that scalar or batched rendering updated."""
+ if not self._env_mask_has_any(self._is_outdated):
+ return
+ if self._grid_publish:
+ self._publish_grid(self._is_outdated)
+ return
+ # Only the updated environments' samples change, so pooling and the grid layout reproduce every other
+ # environment's last frame.
+ self._extract_foveated_samples(self._is_outdated)
+ mask_grid_samples(self._foveated_output, self._ray_coords)
+ self._apply_sensor_fov_mask(self._foveated_output, self._is_outdated)
+
+ if self._pooled_output is not None:
+ for name, hi in self._foveated_output.items():
+ if name == "rgb" and "rgba" in self._foveated_output:
+ continue # rgba alias
+ self._pooled_output[name].copy_(self._pool_output(name, hi))
+ if self._native_grid:
+ source = self._pooled_output if self._pooled_output is not None else self._foveated_output
+ copy_grid_outputs(source, self._grid_output, self._grid_indices)
+
+ def _prepare_projection(self) -> None:
+ # The lens textures and sample extraction use the rendered samples: the high-resolution ones when pooling.
+ self._prepare_sampling()
+ ray_coords = self._ray_coords
+
+ size = ray_coords.resolution
+ if not self._native_grid:
+ size = max(64, math.ceil(math.sqrt(4 * self._num_ray_samples / math.pi)))
+ exit_size = self.cfg.exit_texture_size
+ if exit_size is None:
+ exit_size = max(128, 4 * size)
+ if self._native_grid:
+ dir_tex, exit_tex = lens_lut.build_native_grid_textures(
+ ray_coords, image_rotation_deg=self.cfg.image_rotation_deg, exit_size=exit_size
+ )
+ else:
+ # Pack sample sets on the cortical disc so nearby samples stay adjacent for RTX filtering.
+ theta = ray_coords.polar[:, 1].to(torch.float64)
+ if self.cfg.image_rotation_deg:
+ theta = theta + math.radians(float(self.cfg.image_rotation_deg))
+ eccentricity = ray_coords.polar[:, 0].to(torch.float64) * (ray_coords.fov / 2.0)
+ self._sample_uv = lens_lut.samples_uv_cortical_disc(
+ eccentricity, theta, ray_coords.fov, ray_coords.cmf_a, device="cpu"
+ )
+ dirs = retinal_directions(ray_coords.cartesian, ray_coords.fov, self.cfg.image_rotation_deg)
+ dir_tex, exit_tex = lens_lut.build_lut_textures(
+ self._sample_uv, dirs, size, size, exit_size, exit_size, device="cpu"
+ )
+ self._texture_size = size
+
+ # The camera owns its textures' directory, which is removed when the camera is released.
+ self._lut_dir = tempfile.TemporaryDirectory(prefix="rtx_foveated_luts_")
+ self._dir_tex_path, self._exit_tex_path = lens_lut.save_lut_textures(
+ dir_tex, exit_tex, self._lut_dir.name, "foveated"
+ )
+ logger.info(
+ "FoveatedRTXCamera: %d samples (%d rendered), style=%s, cmf_a=%.4g deg, field of view=%.1f deg, "
+ "texture %dx%d, exit lookup %dx%d, lookup textures in %s",
+ self._num_valid_samples,
+ self._num_ray_samples,
+ self.cfg.foveated_style,
+ ray_coords.cmf_a,
+ ray_coords.fov,
+ size,
+ size,
+ exit_size,
+ exit_size,
+ self._lut_dir.name,
+ )
+ self.cfg.height = self.cfg.width = size
+
+ def _initialize_impl(self) -> None:
+ # OVRTX measures distance_to_camera from each camera's near-clipped ray origin, so it needs the near clips.
+ near_clips = None
+ if self.cfg.renderer_cfg.renderer_type == "ovrtx" and "distance_to_camera" in self.cfg.data_types:
+ prims = sim_utils.find_matching_prims(self.cfg.prim_path, self.stage)
+ near_clips = [self._near_clipping_distance(prim) for prim in prims]
+
+ super()._initialize_impl()
+
+ self._near_clip = None
+ if near_clips is not None:
+ self._near_clip = torch.tensor(near_clips, dtype=torch.float32, device=self._device).view(-1, 1, 1, 1)
+
+ # OVRTX owns its runtime; Kit extensions belong only to Isaac RTX.
+ if self.cfg.renderer_cfg.renderer_type == "isaac_rtx":
+ import omni.kit.app
+
+ ext_manager = omni.kit.app.get_app().get_extension_manager()
+ for ext_name in ("omni.sensors.nv.common", "omni.sensors.nv.camera"):
+ if not ext_manager.set_extension_enabled_immediate(ext_name, True):
+ logger.warning("Could not enable Kit extension '%s'; the lens lookup may not render.", ext_name)
+
+ self._initialize_sampling()
+ if not self._gaze_pose_reads_angles:
+ _, local_orientation = self._view.get_local_poses()
+ self._base_local_orientation = matrix_from_quat(local_orientation.torch).clone()
+ self._pooler, pool_k = build_pooler(
+ self.cfg, self._sampling_coords, self._sampling_coords_highres, device=str(self._device)
+ )
+
+ # The renderer keeps writing the texture buffers the parent bound to it; the camera publishes others.
+ self._texture_output = self._data.output
+ textures = {name: tex.torch for name, tex in self._texture_output.items()}
+ # A native grid texture already holds the samples in order, so one kernel per output masks it and lays it
+ # out. OVRTX's camera distance needs its near-plane offset first, and keeps the step-by-step path.
+ fused = self._native_grid and self._pooler is None and self._near_clip is None
+ if fused:
+ count = self._num_ray_samples
+ samples = {name: tex.reshape(tex.shape[0], count, tex.shape[-1]) for name, tex in textures.items()}
+ self._grid_output = allocate_outputs(samples, *grid_output_shape(self._sampling_coords))
+ self._grid_indices = grid_sample_indices(self._sampling_coords)
+ self._prepare_grid_publish(samples)
+ published = self._grid_output
+ else:
+ if not self._native_grid:
+ uv_gpu = self._sample_uv.to(self._device)
+ size = self._texture_size
+ self._extract_px = (uv_gpu[:, 0] * size).long().clamp(0, size - 1)
+ self._extract_py = (uv_gpu[:, 1] * size).long().clamp(0, size - 1)
+ self._foveated_output = allocate_outputs(textures, self._num_ray_samples, 1)
+ published = self._foveated_output
+ self._pooled_output = None
+ if self._pooler is not None:
+ published = self._pooled_output = allocate_outputs(published, self._num_valid_samples, 1)
+ self._prepare_segmentation_pooling(published)
+ logger.info(
+ "FoveatedRTXCamera: %s pooling (mode=%s k=%s sample_cortex=%s N_hi=%d -> N_lo=%d)",
+ type(self._pooler).__name__,
+ self.cfg.pool_mode,
+ pool_k,
+ self.cfg.pool_sample_cortex,
+ self._num_ray_samples,
+ self._num_valid_samples,
+ )
+ if self._native_grid:
+ self._grid_output = allocate_outputs(published, *grid_output_shape(self._sampling_coords))
+ self._grid_indices = grid_sample_indices(self._sampling_coords)
+ published = self._grid_output
+ # ``CameraData.output`` is read-only, so its backing field is replaced.
+ self._data._output = proxy_outputs(published)
+ self._set_published_shape(self._data._output)
+
+ def _near_clipping_distance(self, prim) -> float:
+ """Near clipping distance [m] of the camera, from its spawn configuration or else its prim."""
+ if self.cfg.spawn is not None:
+ return float(self.cfg.spawn.clipping_range[0])
+ from pxr import UsdGeom
+
+ clipping = UsdGeom.Camera(prim).GetClippingRangeAttr().Get()
+ return float(clipping[0]) if clipping is not None else 0.0
+
+ def _mount_written(self, env_ids) -> None:
+ """Save the moved prims' orientations as their bare mounts and write the gaze on top of them again."""
+ if self._gaze_pose_reads_angles:
+ return # The pose update turns the new mount by the gaze.
+ ids = self._env_indices(env_ids)
+ _, local_orientation = self._view.get_local_poses()
+ self._base_local_orientation[ids] = matrix_from_quat(local_orientation.torch[ids])
+ if self._gaze_rotation is not None:
+ self._write_gaze_local_pose()
+
+ def _write_gaze_local_pose(self) -> None:
+ # Replicator reads camera prims, not update_camera's pose arguments.
+ # Write when the command arrives, before a visualizer can render the step.
+ # The saved local base prevents accumulation and preserves parent motion.
+ basis = self._gaze_basis
+ with torch.autocast(basis.device.type, enabled=False):
+ relative = compose_rotations(compose_rotations(basis, self._gaze_rotation.torch), basis.T)
+ local_orientation = quat_from_matrix(compose_rotations(self._base_local_orientation, relative))
+ self._view.set_local_poses(orientations=wp.from_torch(local_orientation.contiguous(), dtype=wp.vec4f))
+
+ def _update_buffers_impl(self, env_mask: wp.array):
+ if not self._env_mask_has_any(env_mask):
+ return
+ # The renderer writes the texture buffers bound at creation, whatever ``self._data.output`` publishes.
+ super()._update_buffers_impl(env_mask)
+ self.process_rendered_frame()
+
+ def _extract_foveated_samples(self, env_mask: wp.array):
+ """Extract the updated environments' per-sample values from the rendered 2D textures into the (B, N, 1, C)
+ buffers; the other environments keep their last samples."""
+ for name, tex in self._texture_output.items():
+ if name == "rgb" and "rgba" in self._texture_output:
+ continue # rgba alias
+ fov = self._foveated_output[name] # (B, N, 1, C)
+ tensor = tex.torch
+ if self._native_grid:
+ samples = tensor.reshape_as(fov)
+ else:
+ samples = tensor[:, self._extract_py, self._extract_px, :].unsqueeze(2)
+ if name == "distance_to_camera" and self._near_clip is not None:
+ # OVRTX measures the distance from the near-clipped ray origin.
+ samples = samples + self._near_clip.to(samples.dtype)
+ copy_updated_rows(samples, fov, env_mask)
+
+ @staticmethod
+ def _update_buffers_batch_impl(sensors: Sequence[FoveatedRTXCamera]) -> None:
+ Camera._update_buffers_batch_impl(sensors)
+ if sim_utils.SimulationContext.instance() is None:
+ return # The base implementation already invoked scalar capture.
+ for sensor in sensors:
+ sensor.process_rendered_frame()
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py
new file mode 100644
index 000000000000..63beb9bbe386
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_kernels.py
@@ -0,0 +1,332 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Warp kernels of the virtual gaze, one launch each per camera pose update and published output.
+
+:func:`project_direction` follows :meth:`fovi.sensing.projection.CameraModel.project` operation for operation, in
+float32. Camera-frame directions follow the ROS (OpenCV) convention: x right, y down, z forward.
+"""
+
+from __future__ import annotations
+
+import math
+
+import torch
+import warp as wp
+from fovi.sensing.projection import CameraModel
+
+vec8f = wp.types.vector(length=8, dtype=wp.float32)
+
+FLOAT32_EPS = float(torch.finfo(torch.float32).eps)
+DEG_TO_RAD = math.pi / 180.0
+
+
+_WARP_STREAMS: dict[tuple[int, int], wp.Stream] = {}
+"""Warp streams by the CUDA device index and stream handle of the PyTorch stream they launch on; default streams of
+different devices share a handle."""
+
+
+def warp_stream(device: torch.device | str) -> wp.Stream | None:
+ """The Warp stream of PyTorch's current stream on a CUDA device, or None on the CPU."""
+ device = torch.device(device)
+ if device.type != "cuda":
+ wp.init()
+ return None
+ torch_current = torch.cuda.current_stream(device)
+ key = (torch_current.device_index, torch_current.cuda_stream)
+ stream = _WARP_STREAMS.get(key)
+ if stream is None:
+ wp.init()
+ stream = wp.get_stream(wp.device_from_torch(device))
+ # A temporary alias of a live Warp-owned stream would unregister it when destroyed; cached aliases persist.
+ if stream.cuda_stream != key[1]:
+ stream = wp.stream_from_torch(torch_current)
+ _WARP_STREAMS[key] = stream
+ return stream
+
+
+def torch_stream(device: torch.device | str) -> wp.ScopedStream | wp.ScopedDevice:
+ """Scope that launches Warp kernels on the tensors' device and, on CUDA, PyTorch's current stream."""
+ stream = warp_stream(device)
+ if stream is None:
+ return wp.ScopedDevice(wp.device_from_torch(torch.device(device)))
+ return wp.ScopedStream(stream, sync_enter=False, sync_exit=False)
+
+
+def record_launch(
+ kernel, dim, inputs, outputs=(), device: torch.device | str = "cpu", block_dim: int = 256
+) -> wp.Launch:
+ """A launch recorded once and replayed each step with :meth:`warp.Launch.launch`, skipping argument packing."""
+ wp.init()
+ return wp.launch(
+ kernel, dim=dim, inputs=inputs, outputs=outputs, device=str(device), block_dim=block_dim, record_cmd=True
+ )
+
+
+@wp.struct
+class CameraParams:
+ """A :class:`~fovi.sensing.projection.CameraModel` for Warp kernels."""
+
+ fisheye: wp.int32
+ focal: wp.vec2f
+ center: wp.vec2f
+ size: wp.vec2f
+ """Image width and height [px]."""
+ distortion: vec8f
+ """Pinhole (k1, k2, p1, p2, k3, k4, k5, k6) or fisheye (k1, k2, k3, k4), zero-padded."""
+ has_circle: wp.int32
+ circle: wp.vec3f
+ max_angle: wp.float32
+ """Largest angle from the optical axis [rad]."""
+
+
+def camera_params(model: CameraModel) -> CameraParams:
+ """The Warp form of a camera model."""
+ params = CameraParams()
+ params.fisheye = int(model.model == "fisheye")
+ fx, fy, cx, cy = model.intrinsics
+ params.focal = wp.vec2f(fx, fy)
+ params.center = wp.vec2f(cx, cy)
+ height, width = model.image_size
+ params.size = wp.vec2f(width, height)
+ params.distortion = vec8f(*model.distortion, *([0.0] * (8 - len(model.distortion))))
+ params.has_circle = int(model.image_circle is not None)
+ params.circle = wp.vec3f(*(model.image_circle or (0.0, 0.0, 1.0)))
+ # fovi compares float32 angles against the limit converted to float32.
+ params.max_angle = float(torch.tensor(math.radians(model.max_angle_deg), dtype=torch.float32))
+ return params
+
+
+@wp.func
+def project_direction(d: wp.vec3f, camera: CameraParams) -> wp.vec3f:
+ """Pixel (x, y) of a camera-frame direction, and 1 where the camera sees it, else 0."""
+ eps = wp.float32(FLOAT32_EPS)
+ z = d[2]
+ lateral = wp.sqrt(d[0] * d[0] + d[1] * d[1])
+ theta = wp.atan2(lateral, z)
+ k = camera.distortion
+ x = wp.float32(0.0)
+ y = wp.float32(0.0)
+ if camera.fisheye == 0:
+ depth = wp.max(z, eps)
+ u = d[0] / depth
+ v = d[1] / depth
+ r2 = u * u + v * v
+ radial = (1.0 + r2 * (k[0] + r2 * (k[1] + r2 * k[4]))) / (1.0 + r2 * (k[5] + r2 * (k[6] + r2 * k[7])))
+ x = u * radial + 2.0 * k[2] * u * v + k[3] * (r2 + 2.0 * u * u)
+ y = v * radial + k[2] * (r2 + 2.0 * v * v) + 2.0 * k[3] * u * v
+ else:
+ t2 = theta * theta
+ radius = theta * (1.0 + t2 * (k[0] + t2 * (k[1] + t2 * (k[2] + t2 * k[3]))))
+ scale = 1.0 / wp.max(z, eps)
+ if lateral > eps:
+ scale = radius / wp.max(lateral, eps)
+ x = d[0] * scale
+ y = d[1] * scale
+ px = x * camera.focal[0] + camera.center[0]
+ py = y * camera.focal[1] + camera.center[1]
+ valid = wp.isfinite(px) and wp.isfinite(py)
+ valid = valid and px >= -0.5 and px < camera.size[0] - 0.5 and py >= -0.5 and py < camera.size[1] - 0.5
+ if camera.has_circle != 0:
+ dx = px - camera.circle[0]
+ dy = py - camera.circle[1]
+ valid = valid and dx * dx + dy * dy <= camera.circle[2] * camera.circle[2]
+ valid = valid and theta <= camera.max_angle
+ if camera.fisheye == 0:
+ valid = valid and z > 0.0
+ return wp.vec3f(px, py, wp.where(valid, 1.0, 0.0))
+
+
+@wp.func
+def gaze_rotation(angles_deg: wp.vec2f) -> wp.mat33f:
+ """Pan-then-tilt rotation of a gaze (tilt, pan) [deg], as :func:`fovi.sensing.projection.gaze_rotation`."""
+ tilt = angles_deg[0] * wp.float32(DEG_TO_RAD)
+ pan = angles_deg[1] * wp.float32(DEG_TO_RAD)
+ x = -wp.cos(tilt) * wp.sin(pan)
+ y = -wp.sin(tilt)
+ z = wp.cos(tilt) * wp.cos(pan)
+ pitch = wp.atan2(x, z)
+ roll = wp.atan2(-y, wp.sqrt(x * x + z * z))
+ cp = wp.cos(pitch)
+ sp = wp.sin(pitch)
+ cr = wp.cos(roll)
+ sr = wp.sin(roll)
+ return wp.mat33f(cp, sp * sr, sp * cr, 0.0, cr, -sr, -sp, cp * sr, cp * cr)
+
+
+@wp.func
+def gaze_pose(
+ orientation: wp.quatf, gaze: wp.mat33f, basis: wp.mat33f, to_opengl: wp.quatf, to_world: wp.quatf
+) -> wp.quatf:
+ """The world orientation (world convention) of a camera at ``orientation`` turned by a gaze rotation."""
+ relative = basis * gaze * wp.transpose(basis)
+ return wp.normalize(orientation * (to_opengl * wp.quat_from_matrix(relative) * to_world))
+
+
+@wp.kernel(enable_backward=False)
+def set_gaze_kernel(
+ angles_deg: wp.array(dtype=wp.vec2f),
+ stored_angles: wp.array(dtype=wp.vec2f),
+ rotation: wp.array(dtype=wp.mat33f),
+):
+ """Store each environment's gaze angles and their gaze rotation."""
+ i = wp.tid()
+ angles = angles_deg[i]
+ stored_angles[i] = angles
+ rotation[i] = gaze_rotation(angles)
+
+
+@wp.func
+def turn_pose(
+ i: wp.int32,
+ gaze: wp.mat33f,
+ basis: wp.mat33f,
+ to_opengl: wp.quatf,
+ to_world: wp.quatf,
+ to_ros: wp.quatf,
+ orientation: wp.array(dtype=wp.quatf),
+ mount: wp.array(dtype=wp.quatf),
+):
+ """Record camera ``i``'s mount in the ROS convention, then turn its world orientation by its gaze."""
+ base = orientation[i]
+ mount[i] = wp.normalize(base * to_ros)
+ orientation[i] = gaze_pose(base, gaze, basis, to_opengl, to_world)
+
+
+@wp.kernel(enable_backward=False)
+def apply_gaze_kernel(
+ angles_deg: wp.array(dtype=wp.vec2f),
+ basis: wp.mat33f,
+ to_opengl: wp.quatf,
+ to_world: wp.quatf,
+ to_ros: wp.quatf,
+ mask: wp.array(dtype=wp.bool),
+ use_mask: wp.int32,
+ orientation: wp.array(dtype=wp.quatf),
+ rotation: wp.array(dtype=wp.mat33f),
+ mount: wp.array(dtype=wp.quatf),
+):
+ """Turn each camera's world orientation by its gaze, or only the masked ones, and record their mounts and gaze
+ rotations; every other camera keeps the rotation its pose was turned by."""
+ i = wp.tid()
+ if use_mask == 0 or mask[i]:
+ gaze = gaze_rotation(angles_deg[i])
+ rotation[i] = gaze
+ turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount)
+
+
+@wp.kernel(enable_backward=False)
+def apply_gaze_indexed_kernel(
+ angles_deg: wp.array(dtype=wp.vec2f),
+ basis: wp.mat33f,
+ to_opengl: wp.quatf,
+ to_world: wp.quatf,
+ to_ros: wp.quatf,
+ indices: wp.array(dtype=wp.int32),
+ orientation: wp.array(dtype=wp.quatf),
+ rotation: wp.array(dtype=wp.mat33f),
+ mount: wp.array(dtype=wp.quatf),
+):
+ """Turn the indexed cameras' world orientations by their gaze, and record their mounts and gaze rotations."""
+ i = indices[wp.tid()]
+ gaze = gaze_rotation(angles_deg[i])
+ rotation[i] = gaze
+ turn_pose(i, gaze, basis, to_opengl, to_world, to_ros, orientation, mount)
+
+
+@wp.func
+def sees(ray: wp.vec3f, gaze: wp.mat33f, frame: wp.mat33f, camera: CameraParams) -> wp.bool:
+ """Whether the physical camera sees a rendered ray (ROS frame) turned by a gaze; ``frame`` is the mount roll."""
+ return project_direction(frame * gaze * wp.transpose(frame) * ray, camera)[2] > 0.5
+
+
+@wp.kernel(enable_backward=False)
+def sensor_visibility_kernel(
+ rays: wp.array(dtype=wp.vec3f),
+ rotation: wp.array(dtype=wp.mat33f),
+ frame: wp.mat33f,
+ camera: CameraParams,
+ updated: wp.array(dtype=wp.bool),
+ valid: wp.array2d(dtype=wp.bool),
+ hidden: wp.array2d(dtype=wp.bool),
+):
+ """Whether the physical camera sees each rendered ray turned by each updated environment's gaze, and which
+ updated samples it does not see; other environments keep their last visibility and hide nothing."""
+ env, sample = wp.tid()
+ if not updated[env]:
+ hidden[env, sample] = False
+ return
+ seen = sees(rays[sample], rotation[env], frame, camera)
+ valid[env, sample] = seen
+ hidden[env, sample] = not seen
+
+
+@wp.kernel(enable_backward=False)
+def publish_grid_kernel(
+ source: wp.array3d(dtype=wp.uint8),
+ indices: wp.array(dtype=wp.int32),
+ footprint: wp.array(dtype=wp.bool),
+ updated: wp.array(dtype=wp.bool),
+ rays: wp.array(dtype=wp.vec3f),
+ rotation: wp.array(dtype=wp.mat33f),
+ frame: wp.mat33f,
+ camera: CameraParams,
+ mask_to_sensor: wp.int32,
+ record_visible: wp.int32,
+ visible: wp.array2d(dtype=wp.bool),
+ target: wp.array3d(dtype=wp.uint8),
+):
+ """Copy the updated environments' rendered samples into the upright grid, zeroing samples outside the footprint
+ or, when masking, the physical camera's view.
+
+ ``source`` and ``target`` hold each sample's channels as raw bytes, so one kernel serves every output type.
+ When masking, the first output records visibility and the other outputs reuse it on the same stream.
+ """
+ env, cell = wp.tid()
+ if not updated[env]:
+ return
+ sample = indices[cell]
+ keep = footprint[sample]
+ if mask_to_sensor != 0:
+ if record_visible != 0:
+ seen = sees(rays[sample], rotation[env], frame, camera)
+ visible[env, sample] = seen
+ else:
+ seen = visible[env, sample]
+ keep = keep and seen
+ for k in range(target.shape[2]):
+ if keep:
+ target[env, cell, k] = source[env, sample, k]
+ else:
+ target[env, cell, k] = wp.uint8(0)
+
+
+@wp.kernel(enable_backward=False)
+def project_directions_kernel(
+ directions: wp.array(dtype=wp.vec3f),
+ camera: CameraParams,
+ pixels: wp.array(dtype=wp.vec2f),
+ valid: wp.array(dtype=wp.bool),
+):
+ i = wp.tid()
+ result = project_direction(directions[i], camera)
+ pixels[i] = wp.vec2f(result[0], result[1])
+ valid[i] = result[2] > 0.5
+
+
+def project_directions(directions: torch.Tensor, camera: CameraParams) -> tuple[torch.Tensor, torch.Tensor]:
+ """Project (..., 3) camera-frame directions to (..., 2) pixels and (...,) validity, in one launch."""
+ flat = directions.detach().reshape(-1, 3).float().contiguous()
+ pixels = torch.empty(len(flat), 2, dtype=torch.float32, device=flat.device)
+ valid = torch.empty(len(flat), dtype=torch.bool, device=flat.device)
+ if len(flat):
+ with torch_stream(flat.device):
+ wp.launch(
+ project_directions_kernel,
+ dim=len(flat),
+ inputs=[wp.from_torch(flat, dtype=wp.vec3f), camera],
+ outputs=[wp.from_torch(pixels, dtype=wp.vec2f), wp.from_torch(valid, dtype=wp.bool)],
+ )
+ return pixels.reshape(*directions.shape[:-1], 2), valid.reshape(directions.shape[:-1])
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py
new file mode 100644
index 000000000000..e011da58e632
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/lens_lut.py
@@ -0,0 +1,308 @@
+# 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
+
+"""
+Lens lookup tables for RTX's ``OmniLensDistortionLutAPI`` (``omni:lensdistortion:model = "lut"``).
+
+A lookup-table lens is defined by two HDR textures attached to a camera prim:
+
+* **rayEnterDirectionTexture** ``(H × W, RGB float32)``
+ Maps each sensor texel NDC ``(u, v)`` → unit ray direction in camera space.
+
+* **rayExitPositionTexture** ``(EW × EH, RG float32)``
+ Inverse map: given a ray direction (octahedral-encoded over ``[0,1]²``),
+ returns the sensor NDC ``(u, v)`` of the nearest sample.
+
+Isaac RTX and OVRTX both render through this API; the legacy generalized-projection camera attributes are not used.
+
+Coordinate conventions:
+
+* **Camera space**: X right, Y up, −Z forward (OpenGL / USD).
+ Spherical grid padding may extend behind the optical hemisphere.
+* **NDC**: ``u ∈ [0,1]`` = column (left → right),
+ ``v ∈ [0,1]`` = row (top → bottom).
+"""
+
+from __future__ import annotations
+
+import math
+import os
+import struct
+import zlib
+from typing import TYPE_CHECKING
+
+import numpy as np
+import torch
+from fovi.sensing.coords import SamplingCoords
+
+from .native_grid import native_grid_directions, native_grid_exit_uv
+
+if TYPE_CHECKING:
+ from pxr import Usd
+
+
+EXR_ZIP_LINES = 16
+"""Scanlines per chunk of a ZIP-compressed EXR file."""
+
+
+def _exr_attribute(name: str, kind: str, value: bytes) -> bytes:
+ """One EXR header attribute: its name, type, size and value."""
+ return name.encode() + b"\0" + kind.encode() + b"\0" + struct.pack(" bytes:
+ """EXR ZIP compression of one chunk: its even bytes then its odd bytes, delta-encoded, then deflated."""
+ data = np.frombuffer(raw, np.uint8)
+ reordered = np.concatenate((data[0::2], data[1::2]))
+ predicted = reordered.copy()
+ predicted[1:] = (reordered[1:].astype(np.int16) - reordered[:-1] + 128).astype(np.uint8)
+ return zlib.compress(predicted.tobytes())
+
+
+def save_exr(path: str, data: torch.Tensor) -> None:
+ """Save a ``(H, W, C)`` float32 tensor, ``C`` in {2, 3}, as a ZIP-compressed scanline EXR file.
+
+ The channels are named ``R``, ``G`` and ``B``. The file follows the OpenEXR format for single-part scanline
+ images, written with NumPy and zlib.
+ """
+ image = np.ascontiguousarray(data.detach().cpu().numpy(), dtype="= len(raw):
+ packed = raw # A chunk that does not shrink is stored uncompressed.
+ chunks.append(struct.pack(" tuple[torch.Tensor, torch.Tensor]:
+ """Build native direction texels and an analytic octahedral inverse map."""
+ directions = native_grid_directions(coords, image_rotation_deg=image_rotation_deg).reshape(
+ coords.resolution, coords.resolution, 3
+ )
+ decoded = torch.stack(_octahedral_decode(exit_size, exit_size, device=coords.device), -1)
+ uv, valid = native_grid_exit_uv(decoded, coords, image_rotation_deg=image_rotation_deg)
+ # Out-of-sensor rays must not be projected into the fovea by the inverse LUT.
+ exit_texture = torch.where(valid[..., None], uv, torch.full_like(uv, -1))
+ return directions, exit_texture
+
+
+def build_lut_textures(
+ samples_uv: torch.Tensor,
+ ray_directions: torch.Tensor,
+ texture_width: int,
+ texture_height: int,
+ exit_width: int,
+ exit_height: int,
+ chunk: int = 8192,
+ *,
+ device: torch.device | str,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Build direction and exit LUT tensors from a labelled set of sensor samples.
+
+ Both tensors are filled by **nearest-neighbour assignment**.
+
+ Args:
+ samples_uv: ``(N, 2)`` float32. NDC ``(u, v)`` per sample.
+ ray_directions: ``(N, 3)`` float32. Unit ray direction per sample.
+ texture_width, texture_height: Direction LUT dimensions.
+ exit_width, exit_height: Exit LUT dimensions.
+ chunk: NN search batch size.
+ device: Torch device.
+
+ Returns:
+ ``(direction_texture, exit_texture)`` —
+ ``(H, W, 3)`` and ``(EH, EW, 2)`` float32 tensors.
+ """
+ uv_t = _t(samples_uv, torch.float32, device)
+ dirs_t = _t(ray_directions, torch.float32, device)
+ N = uv_t.shape[0]
+
+ # Direction texture.
+ dir_out = torch.zeros(texture_height, texture_width, 3, dtype=torch.float32, device=device)
+ dir_out[:, :, 2] = -1.0
+
+ if N > 0:
+ # Each texel takes the ray of the sample nearest it in UV, whatever order the samples come in.
+ u_t = (torch.arange(texture_width, dtype=torch.float32, device=device) + 0.5) / texture_width
+ v_t = (torch.arange(texture_height, dtype=torch.float32, device=device) + 0.5) / texture_height
+ U = u_t.unsqueeze(0).expand(texture_height, texture_width)
+ V = v_t.unsqueeze(1).expand(texture_height, texture_width)
+ texel_uv = torch.stack([U.reshape(-1), V.reshape(-1)], dim=1)
+ k_nn = _nn_chunk(texel_uv, uv_t, chunk)
+ dir_out.reshape(-1, 3)[:] = dirs_t[k_nn]
+
+ # Exit texture: only texels whose direction lies within the samples' field (r <= max_r) map to a sample; the rest
+ # hold the invalid UV (-1, -1), as in native-grid LUTs, so rays outside the field never reach the fovea.
+ d = dirs_t.to(torch.float64)
+ r_s = (torch.atan2((d[:, 0] ** 2 + d[:, 1] ** 2).sqrt(), (-d[:, 2]).clamp(min=1e-20)) * (180.0 / math.pi)).float()
+ th_s = torch.atan2(d[:, 1], d[:, 0]).float()
+ xs = r_s * th_s.cos()
+ ys = r_s * th_s.sin()
+ max_r = float(r_s.max().item()) if N > 0 else 0.0
+
+ oct_x, oct_y, oct_z = _octahedral_decode(exit_width, exit_height, device=device)
+ r_q = (torch.atan2((oct_x**2 + oct_y**2).sqrt(), (-oct_z).clamp(min=1e-20)) * (180.0 / math.pi)).float()
+ th_q = torch.atan2(oct_y.float(), oct_x.float())
+ xq = r_q * th_q.cos()
+ yq = r_q * th_q.sin()
+
+ odz_f = oct_z.float()
+ valid = (r_q <= max_r) & (odz_f < -1e-9)
+
+ exit_u = torch.full((exit_height, exit_width), -1.0, dtype=torch.float32, device=device)
+ exit_v = torch.full((exit_height, exit_width), -1.0, dtype=torch.float32, device=device)
+
+ if N > 0 and valid.any():
+ sample_cart = torch.stack([xs, ys], dim=1)
+ vf = valid.reshape(-1)
+ query_cart = torch.stack([xq.reshape(-1)[vf], yq.reshape(-1)[vf]], dim=1)
+ k_exit = _nn_chunk(query_cart, sample_cart, chunk)
+ eu_flat = exit_u.reshape(-1)
+ ev_flat = exit_v.reshape(-1)
+ eu_flat[vf] = uv_t[k_exit, 0]
+ ev_flat[vf] = uv_t[k_exit, 1]
+
+ return dir_out, torch.stack([exit_u, exit_v], dim=2)
+
+
+def save_lut_textures(
+ direction_texture: torch.Tensor,
+ exit_texture: torch.Tensor,
+ output_dir: str,
+ basename: str,
+) -> tuple[str, str]:
+ """Save direction and exit LUT tensors as EXR files.
+
+ Returns:
+ ``(direction_path, exit_path)`` — absolute paths to the written files.
+ """
+ os.makedirs(output_dir, exist_ok=True)
+ dir_path = os.path.join(output_dir, f"{basename}_ray_enter_direction.exr")
+ exit_path = os.path.join(output_dir, f"{basename}_ray_exit_position.exr")
+ save_exr(dir_path, direction_texture)
+ save_exr(exit_path, exit_texture)
+ return os.path.abspath(dir_path), os.path.abspath(exit_path)
+
+
+def apply_lens_lut_to_prim(
+ prim: Usd.Prim,
+ direction_texture_path: str,
+ exit_texture_path: str,
+) -> None:
+ """Apply native OmniLensDistortion LUT textures to an existing USD Camera."""
+ from pxr import Sdf
+
+ # RTX reads explicitly authored metadata and attributes without USD schema registration.
+ prim.AddAppliedSchema("OmniLensDistortionLutAPI")
+ prim.CreateAttribute("omni:lensdistortion:model", Sdf.ValueTypeNames.Token).Set("lut")
+ prim.CreateAttribute("omni:lensdistortion:lut:rayEnterDirectionTexture", Sdf.ValueTypeNames.Asset).Set(
+ direction_texture_path
+ )
+ prim.CreateAttribute("omni:lensdistortion:lut:rayExitPositionTexture", Sdf.ValueTypeNames.Asset).Set(
+ exit_texture_path
+ )
+
+
+def samples_uv_cortical_disc(
+ r_deg,
+ theta_rad,
+ fov_deg: float,
+ cmf_a: float,
+ device: torch.device | str,
+) -> torch.Tensor:
+ """Map samples to NDC using the cortical polar disc layout.
+
+ ``ρ = log((r + a) / a)``, mapped to a centered disc.
+ Foveal centre ``r=0`` → disc centre ``(0.5, 0.5)``.
+
+ Returns:
+ ``(N, 2)`` float32 NDC tensor.
+ """
+ rho_max = math.log((fov_deg / 2.0 + cmf_a) / cmf_a)
+ r = _t(r_deg, torch.float64, device)
+ th = _t(theta_rad, torch.float64, device)
+ rho = ((r + cmf_a) / cmf_a).clamp(min=1e-30).log()
+ u = (rho * th.cos() / (2.0 * rho_max) + 0.5).float()
+ v = (-rho * th.sin() / (2.0 * rho_max) + 0.5).float()
+ return torch.stack([u, v], dim=1)
+
+
+def _t(x, dtype: torch.dtype, device) -> torch.Tensor:
+ """Convert array-like or tensor *x* to a ``torch.Tensor`` on *device*."""
+ if isinstance(x, torch.Tensor):
+ return x.to(dtype=dtype, device=device)
+ return torch.as_tensor(np.asarray(x), dtype=dtype, device=device)
+
+
+def _octahedral_decode(
+ width: int,
+ height: int,
+ device: torch.device | str,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Decode octahedral-LUT texel centres to unit directions (camera −Z convention).
+
+ Returns:
+ Three ``(height, width)`` float64 tensors ``(dx, dy, dz)``.
+ """
+ u = (torch.arange(width, dtype=torch.float64, device=device) + 0.5) / width
+ v = (torch.arange(height, dtype=torch.float64, device=device) + 0.5) / height
+ px = u.unsqueeze(0).expand(height, width) * 2.0 - 1.0
+ py = v.unsqueeze(1).expand(height, width) * 2.0 - 1.0
+ dz = 1.0 - px.abs() - py.abs()
+ sx = torch.sign(px)
+ sy = torch.sign(py)
+ dx = torch.where(dz <= 0.0, (1.0 - py.abs()) * sx, px)
+ dy = torch.where(dz <= 0.0, (1.0 - px.abs()) * sy, py)
+ n = torch.clamp((dx**2 + dy**2 + dz**2).sqrt(), min=1e-20)
+ return dx / n, dy / n, -dz / n
+
+
+def _nn_chunk(query: torch.Tensor, keys: torch.Tensor, chunk: int) -> torch.Tensor:
+ """Chunked nearest-neighbour search via ``torch.cdist``.
+
+ Chunk size is capped so the float32 distance matrix stays within 2 GiB.
+
+ Returns:
+ ``(M,)`` int64 index of the closest key for each query row.
+ """
+ N = keys.shape[0]
+ safe_chunk = max(1, (2 << 30) // (4 * max(N, 1)))
+ effective = min(chunk, safe_chunk)
+ M = query.shape[0]
+ idx = torch.empty(M, dtype=torch.long, device=query.device)
+ for s in range(0, M, effective):
+ e = min(s + effective, M)
+ idx[s:e] = torch.cdist(query[s:e], keys).argmin(dim=1)
+ return idx
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py
new file mode 100644
index 000000000000..a57952ed05cd
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/native_grid.py
@@ -0,0 +1,201 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Native warped-grid rendering geometry and public image layout."""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Mapping
+
+import torch
+import warp as wp
+from fovi.sensing.coords import SamplingCoords
+
+from isaaclab.utils.warp import ProxyArray
+from isaaclab.utils.warp.memory import make_masked_copy
+
+from .gaze_kernels import warp_stream
+
+GRID_STYLE = "warped_cartesian_as_grid"
+
+
+def buffer_tensor(value: torch.Tensor | ProxyArray) -> torch.Tensor:
+ """Get a renderer or public tensor without copying."""
+ return value if isinstance(value, torch.Tensor) else value.torch
+
+
+def proxy_outputs(outputs: Mapping[str, torch.Tensor | ProxyArray]) -> dict[str, ProxyArray]:
+ """Wrap output buffers as zero-copy :class:`ProxyArray` values, as :class:`CameraData` publishes them."""
+ return {
+ name: ProxyArray(wp.from_torch(value)) if isinstance(value, torch.Tensor) else value
+ for name, value in outputs.items()
+ }
+
+
+def copy_updated_rows(source: torch.Tensor, target: torch.Tensor, rows: wp.array) -> None:
+ """Copy the environments that ``rows`` selects from ``source`` into ``target``, shape (num_envs, N, 1, C).
+
+ The other environments keep their values. The masked copy needs no full-batch temporary and no host sync.
+
+ Args:
+ source: The new samples; may be a strided view.
+ target: The published samples, written in place.
+ rows: Which environments to copy, shape (num_envs,) of ``bool``.
+ """
+ source3, target3 = source.squeeze(2), target.squeeze(2)
+ dtype = wp.dtype_from_torch(target.dtype)
+ wp.launch(
+ make_masked_copy(dtype, 3),
+ dim=tuple(target3.shape),
+ inputs=[wp.from_torch(source3, dtype=dtype), rows, None],
+ outputs=[wp.from_torch(target3, dtype=dtype)],
+ device=str(target.device),
+ stream=warp_stream(target.device),
+ )
+
+
+def bounded_angular_radius(radius: torch.Tensor, half_fov_rad: float) -> torch.Tensor:
+ """Continue angular padding monotonically toward the antipode.
+
+ The nominal visual disc is unchanged. Outside it, the continuation has
+ matching value and derivative at the rim and never wraps around the sphere.
+ """
+ if not 0 < half_fov_rad < math.pi:
+ raise ValueError("Spherical grid half FoV must lie strictly between zero and pi.")
+ remaining = math.pi - half_fov_rad
+ excess = (radius - 1).clamp_min(0) * half_fov_rad
+ padding = half_fov_rad + remaining * excess / (remaining + excess)
+ return torch.where(radius <= 1, radius * half_fov_rad, padding)
+
+
+def unbounded_angular_radius(angle: torch.Tensor, half_fov_rad: float) -> torch.Tensor:
+ """Invert :func:`bounded_angular_radius` for angles below the antipode."""
+ remaining = math.pi - half_fov_rad
+ fraction = ((angle - half_fov_rad) / remaining).clamp(0, 1 - torch.finfo(angle.dtype).eps)
+ padding = 1 + remaining * fraction / ((1 - fraction) * half_fov_rad)
+ return torch.where(angle <= half_fov_rad, angle / half_fov_rad, padding)
+
+
+def native_grid_directions(coords: SamplingCoords, *, image_rotation_deg: float = 0.0) -> torch.Tensor:
+ """Return canonical ordered OpenGL rays for a warped Cartesian grid.
+
+ Grid radius is proportional to visual angle, and the padding outside the
+ nominal field continues toward the antipode without wrapping.
+ """
+ _require_spherical(coords)
+ cartesian = coords.cartesian.to(torch.float64)
+ radius = torch.linalg.vector_norm(cartesian, dim=-1)
+ boundary_radius, boundary_angle = _angular_padding_boundary(coords)
+ angle = bounded_angular_radius(radius / boundary_radius, boundary_angle)
+ scale = torch.where(radius > 0, angle.sin() / radius.clamp_min(1e-30), angle.new_zeros(()))
+ xy = cartesian * scale[:, None]
+ z = -angle.cos()
+ angle = math.radians(image_rotation_deg)
+ x, y = xy.unbind(-1)
+ rays = torch.stack(
+ (math.cos(angle) * x - math.sin(angle) * y, math.sin(angle) * x + math.cos(angle) * y, z),
+ -1,
+ )
+ return torch.nn.functional.normalize(rays, dim=-1).float()
+
+
+def native_grid_exit_uv(
+ directions: torch.Tensor, coords: SamplingCoords, *, image_rotation_deg: float = 0.0
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Analytically map OpenGL rays to native texture UV and visibility.
+
+ Texture rows and columns follow canonical vector order: native x then y.
+ The public image applies Fovi's upright grid permutation after rendering.
+ """
+ _require_spherical(coords)
+ angle = math.radians(image_rotation_deg)
+ x, y, z = directions.to(torch.float64).unbind(-1)
+ xy = torch.stack((math.cos(angle) * x + math.sin(angle) * y, -math.sin(angle) * x + math.cos(angle) * y), -1)
+ lateral = torch.linalg.vector_norm(xy, dim=-1)
+ theta = torch.atan2(lateral, -z)
+ boundary_radius, boundary_angle = _angular_padding_boundary(coords)
+ radius = unbounded_angular_radius(theta, boundary_angle) * boundary_radius
+ cartesian = xy * (radius / lateral.clamp_min(1e-30))[..., None]
+ visible = theta < math.pi - 1e-8
+ native = coords.visual_to_native(cartesian)
+ uv = (native.flip(-1) + 1) / 2
+ visible = visible & (uv >= 0).all(-1) & (uv <= 1).all(-1)
+ return uv.float(), visible
+
+
+def grid_output_shape(coords: SamplingCoords) -> tuple[int, int]:
+ """Resolve public image dimensions, preserving vector cameras' shape."""
+ if coords.style == GRID_STYLE:
+ return coords.resolution, coords.resolution
+ return len(coords), 1
+
+
+def mask_grid_samples(outputs: Mapping[str, torch.Tensor | ProxyArray], coords: SamplingCoords) -> None:
+ """Zero samples outside the configured footprint before pooling or publication."""
+ if coords.style != GRID_STYLE:
+ return
+ invalid = ~coords.valid_mask[None, :, None, None]
+ for name, value in outputs.items():
+ if name == "rgb" and "rgba" in outputs:
+ continue
+ tensor = buffer_tensor(value)
+ tensor.masked_fill_(invalid, 0)
+
+
+def allocate_outputs(
+ outputs: Mapping[str, torch.Tensor | ProxyArray], height: int, width: int
+) -> dict[str, torch.Tensor]:
+ """Allocate BHWC buffers with the source channels, dtype, device and RGB view of RGBA."""
+ result: dict[str, torch.Tensor] = {}
+ for name, value in outputs.items():
+ if name == "rgb" and "rgba" in outputs:
+ continue
+ tensor = buffer_tensor(value)
+ result[name] = tensor.new_zeros((tensor.shape[0], height, width, tensor.shape[-1]))
+ if "rgb" in outputs and "rgba" in result:
+ result["rgb"] = result["rgba"][..., :3]
+ return result
+
+
+def grid_sample_indices(coords: SamplingCoords) -> torch.Tensor:
+ """Resolve the public image permutation once, outside rendering updates."""
+ return coords.as_grid(torch.arange(len(coords), device=coords.device)).reshape(-1)
+
+
+def copy_grid_outputs(
+ source: Mapping[str, torch.Tensor | ProxyArray],
+ target: dict[str, torch.Tensor],
+ indices: torch.Tensor,
+) -> None:
+ """Update stable public image buffers without changing sample ordering."""
+ for name, value in source.items():
+ if name == "rgb" and "rgba" in source:
+ continue
+ tensor = buffer_tensor(value)
+ flat_source = tensor.reshape(tensor.shape[0], -1, tensor.shape[-1])
+ flat_target = target[name].view(tensor.shape[0], -1, tensor.shape[-1])
+ torch.index_select(flat_source, 1, indices, out=flat_target)
+
+
+def _require_spherical(coords: SamplingCoords) -> None:
+ if coords.field_geometry != "spherical":
+ raise ValueError(f"Foveated cameras sample spherical coordinates, got {coords.field_geometry!r}.")
+
+
+def _angular_padding_boundary(coords: SamplingCoords) -> tuple[float, float]:
+ if coords.fov_type == "circular":
+ radius = 1.0
+ elif coords.fov_type == "square":
+ radius = math.sqrt(2)
+ elif coords.fov_type == "wang":
+ corner = coords.cartesian.new_tensor([[1.0, 1.0]])
+ radius = float(torch.linalg.vector_norm(coords.native_to_visual(corner)).item())
+ else:
+ raise ValueError(f"Unsupported native grid footprint {coords.fov_type!r}.")
+ angle = radius * math.radians(coords.fov) / 2
+ if angle >= math.pi:
+ raise ValueError("Spherical native grid footprint reaches the antipode; reduce FoV or use circular coverage.")
+ return radius, angle
diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py
new file mode 100644
index 000000000000..3735e297f46c
--- /dev/null
+++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/pooling.py
@@ -0,0 +1,273 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Shared retinal-pooling helpers for FoveatedCamera backends.
+
+Builds a pair of (lowres, highres) :class:`SamplingCoords` and a retinal
+pooler analogous to :class:`fovi.sensing.samplers.PoolingGridSampler`, but driven by a
+:class:`FoveatedCameraCfg` and operating on rays rather than images.
+
+Key deviation from ``PoolingGridSampler``: the highres grid shares ``cmf_a`` with
+the lowres grid (no ``cmf_a_mult``). Only ``res`` is scaled by
+``pool_res_mult`` so the photoreceptor and RGC layers represent the same
+visual-field geometry at different densities.
+
+Construction happens in two stages to accommodate Isaac's sensor init order:
+1. ``build_retinal_coords`` runs *before*
+ ``super()._initialize_impl()`` (CPU) so the backend can size its render
+ buffers from the highres sample count.
+2. ``build_pooler`` runs *after* coords have been moved to the sensor's
+ device, so the KNN indices/distances/Gaussian weights materialise on the
+ correct device (they are plain tensor attributes and are not moved by
+ ``nn.Module.to``).
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import torch
+from fovi.arch.knn import KNNPoolingLayer
+from fovi.arch.pooling import GridPoolingLayer, build_retinal_pooler
+from fovi.sensing.coords import SamplingCoords, auto_match_num_coords
+from fovi.sensing.projection import CameraModel
+
+if TYPE_CHECKING:
+ from .foveated_camera_cfg import FoveatedCameraCfg
+
+
+# Upper bound on ``batch * outputs * k`` elements per modal-pooling chunk. Each chunk holds about ten
+# int64 tensors of this size, so peak scratch memory stays near 300 MB regardless of the batch size.
+_MODAL_CHUNK_ELEMENTS = 2**22
+
+
+def build_retinal_coords(
+ cfg: FoveatedCameraCfg, camera: CameraModel, device: str
+) -> tuple[SamplingCoords, SamplingCoords | None]:
+ """Build the public retina and, when pooling, the denser retina with the same angular geometry."""
+ fov = camera.field_of_view(cfg.retinal_window_reference_side, cfg.retinal_window_fraction)
+
+ matched_res, _ = auto_match_num_coords(
+ fov,
+ cfg.cmf_a_deg,
+ cfg.foveated_res,
+ cfg.foveated_style,
+ 1,
+ device,
+ quiet=True,
+ fov_type=cfg.fov_type,
+ radius_norm=cfg.radius_norm,
+ field_geometry="spherical",
+ )
+ lowres = SamplingCoords(
+ fov=fov,
+ cmf_a=cfg.cmf_a_deg,
+ res=matched_res,
+ device=device,
+ style=cfg.foveated_style,
+ isotropic_plotting_type=cfg.isotropic_plotting_type,
+ fov_type=cfg.fov_type,
+ radius_norm=cfg.radius_norm,
+ field_geometry="spherical",
+ )
+ highres = None
+ if cfg.pool_enabled:
+ # Fractional ratios (e.g. sqrt(2) for twice as many samples) still need an integer radial resolution.
+ highres = lowres.clone(resolution=int(round(cfg.pool_res_mult * lowres.resolution)))
+ return lowres, highres
+
+
+def build_pooler(
+ cfg: FoveatedCameraCfg,
+ lowres: SamplingCoords,
+ highres: SamplingCoords | None,
+ device: str,
+) -> tuple[KNNPoolingLayer | GridPoolingLayer | None, int | None]:
+ """Build the retinal pooling layer of ``cfg.pool_mode``, which pools every output except segmentation. Both coord
+ sets must already be on ``device``.
+
+ Segmentation pools by modal label over this pooler's neighbourhoods: pass :func:`segmentation_neighbor_indices` of
+ it to :func:`pool_segmentation_buffer`.
+ """
+ if highres is None:
+ return None, None
+ return build_retinal_pooler(
+ highres,
+ lowres,
+ k=cfg.pool_k,
+ mode=cfg.pool_mode,
+ device=device,
+ sample_cortex=cfg.pool_sample_cortex,
+ gauss_sigma=cfg.pool_gauss_sigma,
+ )
+
+
+def segmentation_neighbor_indices(pooler: KNNPoolingLayer | GridPoolingLayer) -> torch.Tensor:
+ """Return a pooler's ``(k, N_lo)`` neighbour table in tie-break order.
+
+ Entries are input-sample indices; ``N_hi`` (the number of input samples)
+ marks a neighbour excluded by the pooler (spatial padding or a masked input
+ sample), and every slot of a masked output sample is excluded.
+
+ * :class:`KNNPoolingLayer`: its padded KNN indices, nearest neighbour first.
+ * :class:`GridPoolingLayer`: the samples in each pooling window (same
+ padding, stride and masks as the pooler), ordered by distance from the
+ window centre and then in row-major window order.
+ """
+ if isinstance(pooler, KNNPoolingLayer):
+ return pooler.knn_indices_pad_token
+ if not isinstance(pooler, GridPoolingLayer):
+ raise TypeError(f"Modal pooling needs a KNN or grid pooler, got {type(pooler).__name__}")
+
+ num_inputs = len(pooler.in_coords)
+ device = pooler.input_mask.device
+ # Pool sample indices (float64 is exact for any realistic count) with the pooler's own padding;
+ # -1 marks padding and masked samples.
+ grid = pooler.in_coords.as_grid(torch.arange(num_inputs, device=device, dtype=torch.float64)[None, None])
+ grid = pooler._pad(torch.where(pooler.input_mask, grid, -1.0), -1.0)
+ side, stride = pooler.kernel_size, pooler.stride
+ windows = grid[0, 0].unfold(0, side, stride).unfold(1, side, stride) # (H_lo, W_lo, side, side)
+ windows = windows.flatten(-2).permute(2, 0, 1) # (k, H_lo, W_lo)
+ axis = torch.arange(side, device=device, dtype=torch.float64) - (side - 1) / 2
+ radius = (axis[:, None].square() + axis[None, :].square()).flatten()
+ windows = windows[torch.sort(radius, stable=True).indices]
+ windows = torch.where(pooler.output_mask[0], windows, -1.0)
+ if not pooler.polar:
+ # Invert the upright Cartesian layout produced by ``as_grid``, as GridPoolingLayer.forward does.
+ windows = windows.flip(-2).transpose(-2, -1)
+ indices = windows.flatten(-2).long()
+ return torch.where(indices < 0, num_inputs, indices)
+
+
+def is_segmentation_output(name: str) -> bool:
+ """Whether a sensor output holds segmentation labels, which pool with ``pool_int_mode``, the modal label
+ (:func:`pool_segmentation_buffer`).
+
+ Uses the key name (``"segmentation" in name``) rather than the dtype: every Isaac Lab segmentation variant
+ (``semantic_segmentation``, ``instance_segmentation_fast``, ``instance_id_segmentation_fast``) holds labels that
+ averaging would corrupt, whether stored as integer IDs or colorized RGBA.
+ """
+ return "segmentation" in name
+
+
+def pool_hwc_buffer(
+ pooler: KNNPoolingLayer | GridPoolingLayer, buf: torch.Tensor, visible: torch.Tensor | None = None
+) -> torch.Tensor:
+ """Pool a ``(B, N_hi, 1, C)`` sensor buffer into ``(B, N_lo, 1, C)``.
+
+ Both poolers expect ``(B, C, N)`` inputs, so we permute in and out.
+
+ Args:
+ pooler: The retinal pooler.
+ buf: ``(B, N_hi, 1, C)`` floating-point samples.
+ visible: ``(B, N_hi)`` photoreceptors the physical camera sees, or None for all. The others are left out of
+ each pooled sample, as the pooler leaves out photoreceptors outside the retina, and a pooled sample that
+ sees none is zero.
+ """
+ B, N_hi, one, C = buf.shape
+ assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}"
+ x = buf[:, :, 0, :].transpose(1, 2).contiguous() # (B, C, N_hi)
+ if visible is None:
+ y = pooler(x) # (B, C, N_lo)
+ else:
+ seen = visible[:, None, :]
+ weight = seen.to(x.dtype)
+ if pooler.mode == "sum":
+ y = pooler(x * weight)
+ else:
+ # Pool the samples with their visibility in one call: a weighted mean over the visible photoreceptors is
+ # the pooled masked samples over the pooled mask, and a max over them ignores -inf.
+ masked = torch.where(seen, x, -torch.inf) if pooler.mode == "max" else x * weight
+ pooled = pooler(torch.cat((masked, weight), dim=1))
+ values, coverage = pooled[:, :C], pooled[:, C:]
+ if pooler.mode != "max":
+ values = values / coverage.clamp_min(torch.finfo(x.dtype).tiny)
+ y = torch.where(coverage > 0, values, 0)
+ return y.transpose(1, 2).unsqueeze(2).contiguous() # (B, N_lo, 1, C)
+
+
+def pool_segmentation_buffer(
+ neighbors: torch.Tensor, buf: torch.Tensor, visible: torch.Tensor | None = None
+) -> torch.Tensor:
+ """Pool a ``(B, N_hi, 1, C)`` segmentation buffer into ``(B, N_lo, 1, C)`` by majority vote.
+
+ Each output sample takes the most common full channel vector among its
+ pooling neighbours (so neighbours ``[0, 0, 0]``, ``[0, 0, 0]``,
+ ``[0, 0, 1]`` give ``[0, 0, 0]``), keeping the buffer's dtype: values are
+ compared bitwise and copied from an input sample, never converted or mixed.
+ This holds for integer IDs of any width and for colorized RGBA vectors.
+
+ Ties go to the value whose first occurrence comes earliest in the pooler's
+ neighbour order (see :func:`segmentation_neighbor_indices`; the nearest
+ neighbour wins for KNN pooling). Neighbours the pooler excludes, or the
+ physical camera does not see, do not vote, and outputs without any valid
+ neighbour are zero, as in fovi.
+
+ Args:
+ neighbors: ``(k, N_lo)`` neighbour table from :func:`segmentation_neighbor_indices`, on the buffer's device.
+ buf: ``(B, N_hi, 1, C)`` buffer of any dtype.
+ visible: ``(B, N_hi)`` photoreceptors the physical camera sees, or None for all.
+
+ Returns:
+ ``(B, N_lo, 1, C)`` pooled buffer with the dtype of ``buf``.
+ """
+ B, N_hi, one, C = buf.shape
+ assert one == 1, f"expected (B, N, 1, C) buffer, got {buf.shape}"
+ indices = neighbors # (k, N_lo), N_hi = excluded
+ k, N_lo = indices.shape
+ values = buf[:, :, 0, :].contiguous() # (B, N_hi, C)
+ # Equality keys, padded with one never-voting sample at index N_hi.
+ keys = torch.nn.functional.pad(_equality_keys(values), (0, 1)) # (B, N_hi + 1)
+ valid = (indices != N_hi).T # (N_lo, k)
+ table = indices.T # (N_lo, k)
+ chunk_size = max(1, _MODAL_CHUNK_ELEMENTS // max(1, N_lo * k))
+ # Visibility, padded like the keys; the never-voting sample is unseen.
+ seen = None if visible is None else torch.nn.functional.pad(visible, (0, 1)).split(chunk_size)
+ slots = []
+ for index, chunk in enumerate(keys.split(chunk_size)):
+ chunk_valid = valid if seen is None else valid & seen[index][:, table] # (N_lo, k) or (b, N_lo, k)
+ slots.append(_modal_slot(chunk[:, table], chunk_valid))
+ slot = torch.cat(slots) # (B, N_lo); k where no neighbour is valid
+ has_value = slot < k
+ # (B, N_lo) input sample index; outputs without a value read sample 0 and are zeroed below.
+ source = table.gather(1, slot.clamp(max=k - 1).T).T.clamp(max=N_hi - 1)
+ pooled = values.gather(1, source.unsqueeze(-1).expand(-1, -1, C))
+ pooled = torch.where(has_value.unsqueeze(-1), pooled, torch.zeros((), dtype=buf.dtype, device=buf.device))
+ return pooled.unsqueeze(2)
+
+
+def _equality_keys(values: torch.Tensor) -> torch.Tensor:
+ """Map ``(B, N, C)`` channel vectors to ``(B, N)`` int64 keys that are equal iff the vectors are bitwise equal.
+
+ Vectors of at most 8 bytes are packed into the key directly; wider vectors
+ fall back to dense ranks from :func:`torch.unique`.
+ """
+ B, N, _ = values.shape
+ raw = values.view(torch.uint8) if values.dtype != torch.bool else values.to(torch.uint8)
+ num_bytes = raw.shape[-1]
+ if num_bytes <= 8:
+ return torch.nn.functional.pad(raw, (0, 8 - num_bytes)).view(torch.int64).reshape(B, N)
+ return torch.unique(raw.reshape(B * N, num_bytes), dim=0, return_inverse=True)[1].reshape(B, N)
+
+
+def _modal_slot(keys: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
+ """Pick the modal neighbour slot of ``(B, N_lo, k)`` keys; ``valid`` is the ``(N_lo, k)`` or ``(B, N_lo, k)``
+ voting mask.
+
+ Returns the ``(B, N_lo)`` earliest slot holding the most common valid key,
+ or ``k`` where no slot is valid.
+ """
+ k = keys.shape[-1]
+ sorted_keys, order = torch.sort(keys, dim=-1)
+ # Label equal-key runs in sorted order, then count valid votes and find the earliest valid slot per run.
+ new_run = torch.ones_like(sorted_keys, dtype=torch.bool)
+ new_run[..., 1:] = sorted_keys[..., 1:] != sorted_keys[..., :-1]
+ run = new_run.cumsum(-1) - 1
+ valid_sorted = valid.expand_as(order).gather(-1, order)
+ votes = torch.zeros_like(run).scatter_add_(-1, run, valid_sorted.long())
+ earliest = torch.full_like(run, k).scatter_reduce_(-1, run, torch.where(valid_sorted, order, k), "amin")
+ # Most votes first, then earliest slot; runs without valid votes score zero.
+ best = (votes * (k + 1) + (k - earliest)).argmax(-1, keepdim=True)
+ return earliest.gather(-1, best).squeeze(-1)
diff --git a/source/isaaclab_fovi/pyproject.toml b/source/isaaclab_fovi/pyproject.toml
new file mode 100644
index 000000000000..b182018f8f78
--- /dev/null
+++ b/source/isaaclab_fovi/pyproject.toml
@@ -0,0 +1,39 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+[build-system]
+requires = ["setuptools>=70.0,<82.0.0", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "isaaclab_fovi"
+version = "0.1.0"
+description = "Foveated camera sensors for the Newton and RTX renderers, and active-gaze manager terms."
+license = {text = "BSD-3-Clause"}
+authors = [{name = "Isaac Lab Project Developers"}]
+maintainers = [{name = "Isaac Lab Project Developers"}]
+keywords = ["robotics", "simulation", "rendering", "camera", "foveation"]
+requires-python = ">=3.12"
+# Only interpackage dependencies should go here.
+dependencies = [
+ "isaaclab",
+]
+
+[tool.uv.sources]
+isaaclab = { path = "../isaaclab", editable = true }
+
+[project.urls]
+Homepage = "https://github.com/isaac-sim/IsaacLab"
+Repository = "https://github.com/isaac-sim/IsaacLab"
+
+[tool.setuptools]
+include-package-data = true
+
+[tool.setuptools.packages.find]
+where = ["."]
+include = ["isaaclab_fovi", "isaaclab_fovi.*"]
+
+[tool.setuptools.package-data]
+"*" = ["*.pyi"]
diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py
new file mode 100644
index 000000000000..ea9e21197784
--- /dev/null
+++ b/source/isaaclab_fovi/test/foveated_render_cases.py
@@ -0,0 +1,283 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Render cases for the foveated camera, shared by the render tests of each renderer.
+
+A camera looks down at the ground plane and renders distance. The ground distance along any camera
+ray is known in closed form, so the images check the sampling geometry without reference images.
+
+:func:`ground_scene` builds one scene per backend (the physics configuration, the renderer configuration class, and
+the camera class the renderer selects), which every case renders in turn; each case sets the gaze and mounts it
+needs. Import this module after the test has launched its simulation app, if it needs one.
+"""
+
+import math
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+import numpy as np
+import pytest
+import torch
+from fovi.sensing.coords import SamplingCoords
+from fovi.sensing.projection import angular_directions
+from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg
+
+import isaaclab.sim as sim_utils
+from isaaclab.assets import AssetBaseCfg, RigidObjectCfg
+from isaaclab.scene import InteractiveScene, InteractiveSceneCfg
+from isaaclab.sim import SimulationCfg, build_simulation_context
+from isaaclab.terrains import TerrainImporterCfg
+from isaaclab.test.utils.devices import resolve_test_sim_device
+from isaaclab.utils.configclass import configclass
+from isaaclab.utils.math import create_rotation_matrix_from_view, quat_from_matrix
+
+DEVICE = resolve_test_sim_device()
+WARMUP_STEPS = 4
+RESOLUTION = 32
+
+# The physical camera the retina looks through: a 640x480 pinhole.
+WIDTH, HEIGHT = 640, 480
+FOCAL, CX, CY = 550.0, 319.5, 239.5
+CLIPPING_RANGE = (0.001, 20.0)
+CAMERA_MODEL = {"model": "pinhole", "image_size": (HEIGHT, WIDTH), "intrinsics": (FOCAL, FOCAL, CX, CY)}
+
+# The same camera as the spawned camera's OpenCV model, from which the foveated camera derives its camera model.
+SPAWNED_CAMERA = dict(
+ camera_model=None,
+ spawn=sim_utils.PinholeCameraCfg(
+ clipping_range=CLIPPING_RANGE,
+ distortion=sim_utils.OpenCvPinholeDistortionCfg(fx=FOCAL, fy=FOCAL, cx=CX, cy=CY, image_size=(WIDTH, HEIGHT)),
+ ),
+)
+
+# The camera looks down at the ground plane; its optical axis meets the ground at the target.
+CAM_EYE = (0.0, 0.0, 2.5)
+CAM_TARGET = (1.75, 0.0, 0.0)
+
+
+@configclass
+class _GroundSceneCfg(InteractiveSceneCfg):
+ """A ground plane, a foveated camera, and an off-screen body; Newton cannot build an empty model."""
+
+ ground = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane")
+ dome_light = AssetBaseCfg(
+ prim_path="/World/DomeLight",
+ spawn=sim_utils.DomeLightCfg(intensity=2000.0, color=(0.9, 0.9, 0.9)),
+ )
+ anchor = RigidObjectCfg(
+ prim_path="{ENV_REGEX_NS}/Anchor",
+ spawn=sim_utils.CuboidCfg(
+ size=(0.01, 0.01, 0.01),
+ rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(),
+ mass_props=sim_utils.MassCfg(mass=0.001),
+ collision_props=sim_utils.UsdPhysicsCollisionCfg(),
+ ),
+ init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, -100.0)),
+ )
+ camera = FoveatedCameraCfg(
+ prim_path="{ENV_REGEX_NS}/Camera",
+ update_period=0.0,
+ data_types=["distance_to_camera"],
+ spawn=sim_utils.PinholeCameraCfg(clipping_range=CLIPPING_RANGE),
+ camera_model=CAMERA_MODEL,
+ foveated_res=RESOLUTION,
+ mask_to_sensor_fov=True,
+ )
+
+
+def _look_at(eye, target) -> tuple[float, float, float, float]:
+ """OpenGL camera orientation (x, y, z, w) at ``eye`` looking at ``target`` with world +Z up."""
+ matrix = create_rotation_matrix_from_view(torch.tensor([eye]), torch.tensor([target]), up_axis="Z")
+ return tuple(quat_from_matrix(matrix)[0].tolist())
+
+
+def _ground_distance_along_gaze(tilt_deg: float, pan_deg: float, eye=CAM_EYE, target=CAM_TARGET) -> float:
+ """Distance [m] from the camera to the ground along the gaze (tilt, pan) [deg]; up and left are positive."""
+ tilt, pan = math.radians(tilt_deg), math.radians(pan_deg)
+ # OpenGL camera frame: +X right, +Y up, looking along -Z.
+ ray_camera = np.array((-math.cos(tilt) * math.sin(pan), math.sin(tilt), -math.cos(tilt) * math.cos(pan)))
+ eye = np.asarray(eye)
+ forward = np.asarray(target) - eye
+ z_axis = -forward / np.linalg.norm(forward)
+ x_axis = np.cross(np.array((0.0, 0.0, 1.0)), z_axis)
+ x_axis /= np.linalg.norm(x_axis)
+ y_axis = np.cross(z_axis, x_axis)
+ ray_world = np.column_stack((x_axis, y_axis, z_axis)) @ ray_camera
+ return float(-eye[2] / ray_world[2])
+
+
+def _cell_angles(field: torch.Tensor, fov: float) -> torch.Tensor:
+ """Angles (tilt, pan) [deg] of each grid cell's ray from the gaze, from fovi's angular projection."""
+ # Each cell's camera-frame ray (OpenCV: x right, y down, z forward).
+ x, y, z = angular_directions(field.double(), fov).unbind(-1)
+ return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg().float()
+
+
+NUM_ENVS = 3
+"""Environments of the shared scene: the moved-mounts case turns one camera and shifts another."""
+
+
+class GroundScene:
+ """A ground scene shared by the render cases of one backend: per environment, a camera with an explicit camera model
+ and one derived from the spawned camera's OpenCV model, at the same mount."""
+
+ def __init__(self, sim, scene: InteractiveScene):
+ self.sim = sim
+ self.scene = scene
+ self.calibrated: FoveatedCamera = scene["camera"]
+ self.spawned: FoveatedCamera = scene["spawned"]
+
+ def reset_mounts(self, camera: FoveatedCamera) -> None:
+ """Put every environment's camera back at the shared mount."""
+ positions = self.scene.env_origins + torch.tensor([CAM_EYE], device=self.sim.device)
+ orientations = torch.tensor([_look_at(CAM_EYE, CAM_TARGET)], device=self.sim.device).repeat(NUM_ENVS, 1)
+ camera.set_world_poses(positions, orientations, convention="opengl")
+
+ def move_mount(self, camera: FoveatedCamera, env: int, eye, target) -> None:
+ """Move one environment's camera to ``eye`` looking at ``target``; a target of None moves only its position."""
+ position = self.scene.env_origins[env : env + 1] + torch.tensor([eye], device=self.sim.device)
+ orientation = None if target is None else torch.tensor([_look_at(eye, target)], device=self.sim.device)
+ camera.set_world_poses(position, orientation, env_ids=[env], convention="opengl")
+
+ def render(
+ self, camera: FoveatedCamera, frames: int = WARMUP_STEPS
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, float]:
+ """Render ``frames`` frames and return the camera's ground distance.
+
+ Returns:
+ The distance images [m], shape (num_envs, H, W), the visual-field position of each grid cell, shape
+ (H, W, 2), the angles (tilt, pan) [deg] of each grid cell's ray from the gaze, shape (H, W, 2), and the
+ retina's field of view [deg].
+ """
+ for _ in range(frames):
+ self.sim.step()
+ camera.update(self.sim.get_physics_dt(), force_recompute=True)
+ distance = camera.data.output["distance_to_camera"].torch[..., 0].detach().cpu().float().clone()
+ coords = camera.sampling_coords
+ field = coords.as_grid(coords.cartesian, sample_dim=0).detach().cpu().float().clone()
+ return distance, field, _cell_angles(field, coords.fov), float(coords.fov)
+
+
+@contextmanager
+def ground_scene(backend: tuple) -> Iterator[GroundScene]:
+ """Build the ground scene once for ``backend``, so its render cases share it instead of rebuilding it."""
+ physics_cfg, renderer_cfg, camera_class = backend
+ sim_cfg = SimulationCfg(physics=physics_cfg, device=DEVICE)
+ with build_simulation_context(device=DEVICE, sim_cfg=sim_cfg) as sim:
+ sim._app_control_on_stop_handle = None
+ scene_cfg = _GroundSceneCfg(num_envs=NUM_ENVS, env_spacing=20.0)
+ scene_cfg.camera.renderer_cfg = renderer_cfg()
+ rot = _look_at(CAM_EYE, CAM_TARGET)
+ scene_cfg.camera.offset = FoveatedCameraCfg.OffsetCfg(pos=CAM_EYE, rot=rot, convention="opengl")
+ scene_cfg.spawned = scene_cfg.camera.replace(prim_path="{ENV_REGEX_NS}/Spawned", **SPAWNED_CAMERA)
+ scene = InteractiveScene(scene_cfg)
+ for name in ("camera", "spawned"):
+ assert isinstance(scene[name], camera_class)
+ sim.reset()
+ yield GroundScene(sim, scene)
+
+
+def foveated_camera_follows_gaze(ground: GroundScene):
+ """The retina's centre sees the ground along the gaze, from the first frame after the gaze changes.
+
+ The environments render along the optical axis, then one turns 16 degrees to the right, as a gaze action does
+ every step. The camera is the spawned camera's OpenCV model. The reference is the analytic ground distance along
+ each gaze direction.
+ """
+ camera = ground.spawned
+ camera.set_gaze_angles(torch.zeros(NUM_ENVS, 2, device=ground.sim.device))
+ ground.render(camera)
+ # The first frame rendered after the command must already show the new gaze.
+ later = torch.tensor([[0.0, 0.0], [0.0, -16.0], [0.0, 0.0]])
+ camera.set_gaze_angles(later.to(ground.sim.device))
+ distance, field, _, _ = ground.render(camera, frames=1)
+
+ assert distance.shape == (NUM_ENVS, RESOLUTION, RESOLUTION)
+ assert torch.isfinite(distance).all()
+
+ # The grid cell closest to the centre of the visual field.
+ row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2])
+ for env, (tilt, pan) in enumerate(later.tolist()):
+ assert float(distance[env, row, column]) == pytest.approx(_ground_distance_along_gaze(tilt, pan), rel=0.01)
+
+ # The image is upright: the top looks farther along the ground than the bottom.
+ centred = distance[0]
+ seen = centred > 0
+ top = centred[: RESOLUTION // 2][seen[: RESOLUTION // 2]].mean()
+ bottom = centred[RESOLUTION // 2 :][seen[RESOLUTION // 2 :]].mean()
+ assert top > bottom + 0.25
+ # The camera has no roll, so the left and right halves see the same distances.
+ left = centred[:, : RESOLUTION // 2][seen[:, : RESOLUTION // 2]].mean()
+ right = centred[:, RESOLUTION // 2 :][seen[:, RESOLUTION // 2 :]].mean()
+ assert float(left) == pytest.approx(float(right), rel=0.01)
+
+ # Looking right moves part of the retina past the edge of the physical camera, and those samples are zeroed.
+ assert (distance[1] == 0).sum() > (distance[0] == 0).sum()
+
+
+def gaze_stays_relative_to_moved_mounts(ground: GroundScene):
+ """Moving a camera keeps its gaze relative to the new mount; moving only its position keeps its orientation, so the
+ gaze is not applied a second time; and the camera that did not move is left alone."""
+ camera = ground.calibrated
+ ground.reset_mounts(camera)
+ camera.set_gaze_angles(torch.tensor([[0.0, -10.0]], device=ground.sim.device).repeat(NUM_ENVS, 1))
+ turned_eye, turned_target = (0.3, -0.4, 3.2), (2.0, 0.3, 0.0)
+ shifted_eye = (0.4, -0.3, 3.0)
+ shifted_target = tuple(e + t - c for e, t, c in zip(shifted_eye, CAM_TARGET, CAM_EYE))
+ ground.move_mount(camera, 1, turned_eye, turned_target)
+ ground.move_mount(camera, 2, shifted_eye, None)
+ distance, field, _, _ = ground.render(camera)
+
+ row, column = np.unravel_index(int(field.norm(dim=-1).argmin()), field.shape[:2])
+ for env, (eye, target) in enumerate(
+ ((CAM_EYE, CAM_TARGET), (turned_eye, turned_target), (shifted_eye, shifted_target))
+ ):
+ expected = _ground_distance_along_gaze(0.0, -10.0, eye, target)
+ assert float(distance[env, row, column]) == pytest.approx(expected, rel=0.01), env
+
+
+def _relative_errors(distance: torch.Tensor, angles: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Relative error of the rendered distance of each seen cell from the ground along the cell's own ray.
+
+ Args:
+ distance: Rendered distance image [m], shape (H, W).
+ angles: Angles (tilt, pan) [deg] of each cell's ray, shape (H, W, 2), with the gaze on the optical axis.
+
+ Returns:
+ The relative errors and the eccentricities [deg] of the rays of the cells the camera sees.
+ """
+ expected = torch.tensor([_ground_distance_along_gaze(tilt, pan) for tilt, pan in angles.view(-1, 2).tolist()])
+ tilt, pan = angles.view(-1, 2).deg2rad().unbind(-1)
+ eccentricity = torch.acos(tilt.cos() * pan.cos()).rad2deg()
+ distance = distance.flatten()
+ seen = torch.isfinite(distance) & (distance > 0)
+ return ((distance - expected).abs() / expected)[seen], eccentricity[seen]
+
+
+def foveated_camera_samples_densest_at_the_fixation(ground: GroundScene):
+ """Samples are densest at the fixation and each renders along its own ray.
+
+ The rendered distances match the ground along each sample's ray well off the centre, and not along the rays of an
+ even grid with the same resolution and field of view, so a renderer that traced an even grid instead fails.
+ """
+ camera = ground.calibrated
+ ground.reset_mounts(camera)
+ camera.set_gaze_angles(torch.zeros(NUM_ENVS, 2, device=ground.sim.device))
+ distance, field, angles, fov = ground.render(camera)
+ steps = field[RESOLUTION // 2, :, 0].diff()
+ assert float(steps[len(steps) // 2] / steps[-1]) < 0.2
+
+ errors, eccentricity = _relative_errors(distance[0], angles)
+ # Most of the grid is seen, and the checked rays reach far from the centre of the field.
+ assert len(errors) > RESOLUTION**2 // 2
+ assert (eccentricity > 10.0).sum() > RESOLUTION**2 // 4
+ assert float(eccentricity.max()) > 20.0
+ assert float(errors.median()) < 0.01
+ assert float((errors < 0.03).float().mean()) > 0.98
+
+ even = SamplingCoords(fov, 1000.0, RESOLUTION, style="warped_cartesian_as_grid", field_geometry="spherical")
+ even_angles = _cell_angles(even.as_grid(even.cartesian, sample_dim=0).float(), fov)
+ errors, _ = _relative_errors(distance[0], even_angles)
+ assert float((errors < 0.03).float().mean()) < 0.5
diff --git a/source/isaaclab_fovi/test/test_active_gaze.py b/source/isaaclab_fovi/test/test_active_gaze.py
new file mode 100644
index 000000000000..43de48eb44d9
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_active_gaze.py
@@ -0,0 +1,267 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""The gaze action, its observation and its teacher, without a simulator."""
+
+import math
+from types import SimpleNamespace
+
+import pytest
+import torch
+import warp as wp
+from fovi.sensing.projection import CameraModel
+from isaaclab_fovi.mdp.gaze import (
+ GazeAction,
+ gaze_reset_kernel,
+ gaze_state,
+ gaze_step_kernel,
+ gaze_teacher_labels,
+)
+from isaaclab_fovi.mdp.gaze_cfg import GazeActionCfg
+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.warp import ProxyArray
+
+pytestmark = pytest.mark.kitless
+
+DEVICES = test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)
+
+
+def angles_to_direction(angles_deg: torch.Tensor) -> torch.Tensor:
+ """Camera-frame unit directions of gaze angles [deg], shape (..., 2) to (..., 3): up and left are positive."""
+ tilt, pan = angles_deg.deg2rad().unbind(-1)
+ return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1)
+
+
+def direction_to_angles(direction: torch.Tensor) -> torch.Tensor:
+ """Gaze angles [deg] of camera-frame directions, shape (..., 3) to (..., 2): the reference for the kernels."""
+ x, y, z = direction.unbind(-1)
+ return torch.stack((-torch.atan2(y, torch.sqrt(x.square() + z.square())), -torch.atan2(x, z)), -1).rad2deg()
+
+
+def clamp_gaze(gaze: torch.Tensor, limit: float) -> torch.Tensor:
+ """Gazes scaled back onto the circle of radius ``limit`` when they leave it: the reference for the step kernel."""
+ return gaze * (limit / gaze.norm(dim=-1, keepdim=True).clamp_min(limit))
+
+
+@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
+ # and a strided pose view, including the CUDA block reduction when a GPU is available.
+ camera = CameraModel("pinhole", (480, 640), (400.0, 400.0, 319.5, 239.5), distortion=(-0.1, 0.02, 0.0, 0.0))
+ field_radius, step, limit = 30.0, (2.0 if body_id is None else 0.1), 1.0
+ roll = math.radians(120.0 if body_id is None else 35.0)
+ c, s = math.cos(roll), math.sin(roll)
+ frame = torch.tensor([[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]])
+ generator = torch.Generator().manual_seed(5)
+ count = 4099
+ # Each camera has its own mount, as on a moving head.
+ mount = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1)
+ positions = torch.randn(count, 3, generator=generator)
+ lateral = torch.randn(count, 2, generator=generator) * 0.6
+ local = torch.cat((lateral, torch.rand(count, 1, generator=generator) + 0.2), -1)
+ targets = positions + quat_apply(mount, local)
+ orientations = torch.nn.functional.normalize(torch.randn(count, 4, generator=generator), dim=-1)
+ offset = torch.tensor([0.0, 0.0, 0.3])
+ gaze = torch.zeros(count, 2) if body_id is None else (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.7
+
+ # The torch path the kernel replaces: the point fixed to each target, the teacher, then the labels and logs.
+ points = targets + quat_apply(orientations, offset.expand(count, -1))
+ direction = torch.nn.functional.normalize(quat_apply_inverse(mount, points - positions), dim=-1)
+
+ def teachable(direction: torch.Tensor) -> torch.Tensor:
+ # Gazes are measured in the upright image frame, which the frame carries into the physical camera's.
+ desired = direction_to_angles(direction @ frame) / field_radius
+ return camera.project(direction)[1] & (desired.norm(dim=-1) <= limit)
+
+ upright = direction @ frame
+ desired = direction_to_angles(upright) / field_radius
+ valid = teachable(direction)
+ # A target within 1e-4 rad of the image edge, the lens's widest angle or the gaze limit may land on either side
+ # in float32; every other target must agree exactly.
+ nudges = 1e-4 * torch.cat((torch.eye(3), -torch.eye(3)))
+ decisive = torch.stack(
+ [teachable(torch.nn.functional.normalize(direction + nudge, dim=-1)) == valid for nudge in nudges]
+ ).all(0)
+ delta = (desired - gaze) / step
+ action = torch.where(valid[:, None], delta.clamp(-1, 1), 0.0)
+ looking = angles_to_direction(gaze * field_radius)
+ error = torch.atan2(torch.cross(looking, upright, dim=-1).norm(dim=-1), (looking * upright).sum(-1)).rad2deg()
+ expected = torch.cat((action, valid[:, None].float()), dim=-1)
+
+ poses = torch.cat((targets, orientations), dim=-1).to(device)
+ target = SceneEntityCfg("target")
+ with torch_stream(device):
+ if body_id is None:
+ asset_data = SimpleNamespace(root_pose_w=ProxyArray(wp.from_torch(poses, dtype=wp.transformf)))
+ else:
+ target.body_names, target.body_ids = ["pole"], [body_id]
+ 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))
+ sensor = SimpleNamespace(
+ data=SimpleNamespace(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),
+ )
+ gaze_term = SimpleNamespace(
+ camera=sensor,
+ teacher_mounts=lambda: mounts,
+ field_radius_deg=field_radius,
+ cfg=GazeActionCfg(asset_name="camera", step_size=step),
+ )
+ env = SimpleNamespace(
+ device=device,
+ num_envs=count,
+ scene={"target": SimpleNamespace(data=asset_data)},
+ action_manager=SimpleNamespace(get_term=lambda name: gaze_term),
+ extras={},
+ )
+ teacher = gaze_teacher_labels(ObservationTermCfg(func=gaze_teacher_labels), env)
+ labels = teacher(env, target, offset=tuple(offset.tolist())).cpu()
+ assert valid[decisive].any() and (~valid[decisive]).any() and decisive.float().mean() > 0.99
+ torch.testing.assert_close(labels[decisive], expected[decisive], atol=1e-4, rtol=0)
+ labelled = labels[:, 2] > 0.5
+ reachable = labelled & decisive & (delta.abs().amax(dim=-1) < 1.0)
+ assert reachable.any()
+ fixation = angles_to_direction((gaze + labels[:, :2] * step) * field_radius) @ frame.T
+ torch.testing.assert_close(fixation[reachable], direction[reachable], atol=1e-5, rtol=0)
+ log = env.extras["log"]
+ assert float(log["Gaze/valid_target_fraction"]) == pytest.approx(float(labelled.float().mean()))
+ assert float(log["Gaze/target_error_deg"]) == pytest.approx(float(error[labelled].mean()), rel=1e-4)
+
+
+def test_gaze_config_rejects_bounds_that_divide_by_zero_and_unknown_mounts():
+ GazeActionCfg(asset_name="camera").validate_config()
+ GazeActionCfg(asset_name="camera", mount="tracked").validate_config()
+ for field, value in (
+ ("step_size", 0.0),
+ ("step_size", float("nan")),
+ ("gaze_limit", math.inf),
+ ("gaze_limit", "1.0"),
+ ("mount", "head"),
+ ):
+ cfg = GazeActionCfg(asset_name="camera")
+ setattr(cfg, field, value)
+ with pytest.raises(ValueError, match=field):
+ 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
+
+
+def test_process_actions_moves_the_gaze_by_the_supplied_actions():
+ """The term reads whatever actions it is handed: the manager's slice in place, or another tensor; and its step
+ kernel matches the torch update."""
+ num_envs = 4
+ angles = ProxyArray(wp.zeros(num_envs, dtype=wp.vec2f, device="cpu"))
+ set_angles = []
+ camera = SimpleNamespace(gaze_angles=angles, set_gaze_angles=lambda value: set_angles.append(value))
+ term = object.__new__(GazeAction)
+ term._env = SimpleNamespace(num_envs=num_envs, device="cpu", step_dt=0.5)
+ term.cfg = GazeActionCfg(asset_name="camera", step_size=0.1, gaze_limit=1.0)
+ term._asset = camera
+ term.field_radius_deg = 20.0
+ term._state = ProxyArray(wp.zeros(num_envs, dtype=wp.vec4f, device="cpu"))
+ term._velocity = term._state.torch[:, 2:]
+ term._step_launch = term._raw = None
+
+ manager_actions = torch.zeros(num_envs, 5)
+ manager_actions[:, 2:4] = torch.tensor([[1.0, 0.0], [0.0, -1.0], [0.5, 0.5], [3.0, 0.0]])
+ term.process_actions(manager_actions[:, 2:4])
+ expected = clamp_gaze(manager_actions[:, 2:4].clamp(-1, 1) * 0.1, 1.0)
+ torch.testing.assert_close(term.gaze, expected)
+ torch.testing.assert_close(term.velocity, expected / 0.5)
+ torch.testing.assert_close(angles.torch, expected * 20.0)
+ assert set_angles[-1] is angles.torch
+ assert term.raw_actions.data_ptr() == manager_actions[:, 2:4].data_ptr()
+
+ supplied = torch.tensor([[-1.0, 0.0]]).repeat(num_envs, 1)
+ term.process_actions(supplied)
+ torch.testing.assert_close(term.gaze, clamp_gaze(expected - 0.1 * supplied.abs(), 1.0))
+ assert term.raw_actions is supplied
+ torch.testing.assert_close(
+ gaze_state(SimpleNamespace(action_manager=SimpleNamespace(get_term=lambda name: term))), term.state
+ )
+
+ # A gaze set on the camera directly is where the next step starts.
+ angles.torch.copy_(torch.tensor([[10.0, 0.0]]).repeat(num_envs, 1))
+ term.process_actions(torch.zeros(num_envs, 2))
+ torch.testing.assert_close(term.gaze, torch.tensor([[0.5, 0.0]]).repeat(num_envs, 1))
+
+ # The step kernel against the torch update, over many gazes.
+ generator = torch.Generator().manual_seed(4)
+ count, step, limit, dt, radius = 2048, 0.1, 1.0, 1 / 60, 23.6
+ actions = torch.randn(count, 2, generator=generator) * 1.5
+ gaze = (torch.rand(count, 2, generator=generator) * 2 - 1) * 0.75
+ expected = clamp_gaze(gaze + actions.clamp(-1, 1) * step, limit)
+ expected_velocity = (expected - gaze) / dt
+
+ # The step starts from the camera's stored angles, not from the state it records.
+ state = torch.randn(count, 4, generator=generator)
+ angles = gaze * radius
+ with torch_stream("cpu"):
+ wp.launch(
+ gaze_step_kernel,
+ dim=count,
+ inputs=[
+ wp.from_torch(actions, dtype=wp.vec2f),
+ wp.from_torch(state, dtype=wp.vec4f),
+ wp.from_torch(angles, dtype=wp.vec2f),
+ step,
+ limit,
+ dt,
+ radius,
+ ],
+ )
+ torch.testing.assert_close(state[:, :2], expected, atol=1e-6, rtol=1e-6)
+ torch.testing.assert_close(state[:, 2:], expected_velocity, atol=2e-3, rtol=1e-5)
+ torch.testing.assert_close(angles, expected * radius, atol=1e-5, rtol=1e-6)
+
+
+@pytest.mark.parametrize(("ids", "random_start"), [(None, False), ([3, 0, 7], True)])
+def test_gaze_reset_kernel_matches_the_torch_reset(ids, random_start):
+ count, radius = 10, 23.6
+ generator = torch.Generator().manual_seed(6)
+ angles, state = (torch.randn(count, size, generator=generator) for size in (2, 4))
+ selected = torch.arange(count) if ids is None else torch.tensor(ids)
+ start = torch.randn(len(selected), 2, generator=generator) if random_start else torch.zeros(len(selected), 2)
+ expected_angles, expected_state = angles.clone(), state.clone()
+ # The torch reset the kernel replaces: the gaze at its start, at rest.
+ expected_state[selected] = torch.cat((start, torch.zeros_like(start)), dim=-1)
+ expected_angles[selected] = start * radius
+
+ with torch_stream("cpu"):
+ wp.launch(
+ gaze_reset_kernel,
+ dim=len(selected),
+ inputs=[
+ wp.from_torch(selected.to(torch.int32)) if ids is not None else wp.zeros(1, dtype=wp.int32),
+ int(ids is not None),
+ wp.from_torch(start, dtype=wp.vec2f) if random_start else wp.zeros(1, dtype=wp.vec2f),
+ int(random_start),
+ radius,
+ ],
+ outputs=[wp.from_torch(angles, dtype=wp.vec2f), wp.from_torch(state, dtype=wp.vec4f)],
+ )
+ torch.testing.assert_close(angles, expected_angles, atol=0, rtol=0)
+ torch.testing.assert_close(state, expected_state, atol=0, rtol=0)
+
+
+def test_fixed_mount_teacher_rejects_only_turns_after_capture():
+ """The fixed-mount teacher aims from the captured mount while the camera has turned its mount as many times as
+ when the term captured it, and refuses once a later turn makes the capture stale."""
+ term = object.__new__(GazeAction)
+ term.tracked_mount = False
+ term._mount_turns = 2
+ term._fixed_mount = "captured"
+ term._asset = SimpleNamespace(mount_turns=2)
+ assert GazeAction.teacher_mounts(term) == "captured"
+ term._asset.mount_turns = 3
+ with pytest.raises(RuntimeError, match="mount='tracked'"):
+ GazeAction.teacher_mounts(term)
diff --git a/source/isaaclab_fovi/test/test_camera_cfg.py b/source/isaaclab_fovi/test/test_camera_cfg.py
new file mode 100644
index 000000000000..b85d6837d1e2
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_camera_cfg.py
@@ -0,0 +1,218 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""The foveated camera's configuration: Isaac Lab camera configs it reads, its validation, renderer dispatch, and its
+import boundary."""
+
+import math
+import subprocess
+import sys
+from dataclasses import dataclass
+from types import SimpleNamespace
+
+import pytest
+import torch
+from fovi.sensing.projection import CameraModel
+from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg
+from isaaclab_fovi.sensors.calibrated_geometry import camera_model_from_spawn
+from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera
+from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera
+from isaaclab_isaacsim.renderers import IsaacRtxRendererCfg
+from isaaclab_newton.renderers import NewtonWarpRendererCfg
+from isaaclab_ov.renderers import OVRTXRendererCfg
+
+import isaaclab.sim as sim_utils
+from isaaclab.sensors.camera.camera import Camera
+from isaaclab.sensors.camera.camera_isp import CameraISPMode
+from isaaclab.sim import (
+ CuboidCfg,
+ FisheyeCameraCfg,
+ OpenCvFisheyeDistortionCfg,
+ OpenCvPinholeDistortionCfg,
+ PinholeCameraCfg,
+)
+from isaaclab.utils.tensor_processors.tensor_processor_cfg import TensorProcessorCfg
+
+pytestmark = pytest.mark.kitless
+
+CAMERA_MODEL = {"model": "pinhole", "image_size": (480, 640), "intrinsics": (550.0, 550.0, 319.5, 239.5)}
+
+
+def make_cfg(**kwargs) -> FoveatedCameraCfg:
+ return FoveatedCameraCfg(prim_path="/World/Camera", **kwargs)
+
+
+def ray_angle_deg(camera, pixel: tuple[float, float]) -> float:
+ """Angle [deg] between the optical axis and the ray through a source pixel (x, y)."""
+ direction, valid = camera.unproject(torch.tensor([pixel], dtype=torch.float64))
+ assert valid.all()
+ return math.degrees(math.acos(float(direction[0, 2])))
+
+
+def test_defaults_are_grid_sampling_at_the_human_cmf_estimate() -> None:
+ cfg = FoveatedCameraCfg()
+ assert cfg.foveated_style == "warped_cartesian_as_grid"
+ assert cfg.cmf_a_deg == 0.591
+ assert cfg.camera_model is None
+
+
+def test_pinhole_spawn_describes_an_ideal_pinhole_across_its_short_side() -> None:
+ spawn = PinholeCameraCfg()
+ expected = math.degrees(2 * math.atan(spawn.horizontal_aperture / (2 * spawn.focal_length)))
+ camera = CameraModel(**camera_model_from_spawn(spawn))
+ assert camera.field_of_view("short") == pytest.approx(expected, rel=1e-6)
+ assert camera.model == "pinhole"
+ assert camera.distortion == ()
+ # Without a vertical aperture the image is square; with one, the retina spans the short (vertical) side.
+ assert camera.image_size[0] == camera.image_size[1]
+ spawn = PinholeCameraCfg(focal_length=10.0, horizontal_aperture=20.0, vertical_aperture=10.0)
+ camera = CameraModel(**camera_model_from_spawn(spawn))
+ assert camera.field_of_view("short") == pytest.approx(math.degrees(2 * math.atan(0.5)), rel=1e-6)
+
+
+def test_opencv_pinhole_spawn_gives_that_calibrated_camera() -> None:
+ distortion = OpenCvPinholeDistortionCfg(
+ fx=500.0, fy=510.0, cx=320.0, cy=240.0, image_size=(640, 480), k1=-0.1, k2=0.01, p1=0.001, k4=0.002
+ )
+ camera = CameraModel(**camera_model_from_spawn(PinholeCameraCfg(distortion=distortion)))
+ assert camera.model == "pinhole"
+ # Isaac Lab sizes are (width, height); fovi's are (height, width).
+ assert camera.image_size == (480, 640)
+ assert camera.intrinsics == (500.0, 510.0, 320.0, 240.0)
+ assert camera.distortion == (-0.1, 0.01, 0.001, 0.0, 0.0, 0.002, 0.0, 0.0)
+
+ distortion.apply_lens_distortion = False
+ assert CameraModel(**camera_model_from_spawn(PinholeCameraCfg(distortion=distortion))).distortion == ()
+
+
+def test_zero_coefficient_opencv_fisheye_is_an_ideal_equidistant_fisheye() -> None:
+ # The image edge is 320 / 250 rad (73 deg) off axis, inside the default 180 deg lens.
+ focal = 250.0
+ distortion = OpenCvFisheyeDistortionCfg(fx=focal, fy=focal, cx=319.5, cy=319.5, image_size=(640, 640))
+ camera = CameraModel(**camera_model_from_spawn(PinholeCameraCfg(distortion=distortion)))
+ assert camera.model == "fisheye"
+ assert camera.distortion == ()
+ assert camera.max_angle_deg == pytest.approx(90.0)
+ # Equidistant: the angle off the optical axis grows linearly with image radius.
+ for radius in (50.0, 150.0, 310.0):
+ assert ray_angle_deg(camera, (319.5 + radius, 319.5)) == pytest.approx(math.degrees(radius / focal), rel=1e-6)
+ assert camera.field_of_view("short") == pytest.approx(math.degrees(640 / focal), rel=1e-6)
+
+
+def test_explicit_camera_model_wins_over_the_spawn() -> None:
+ for spawn in (PinholeCameraCfg(), None):
+ camera = SimpleNamespace(cfg=make_cfg(spawn=spawn, camera_model=CAMERA_MODEL, foveated_res=8))
+ FoveatedCamera._prepare_sampling(camera)
+ assert camera._camera_model == CameraModel(**CAMERA_MODEL)
+
+
+def test_cameras_fovi_cannot_model_are_rejected() -> None:
+ thin_prism = OpenCvPinholeDistortionCfg(fx=1.0, fy=1.0, cx=1.0, cy=1.0, image_size=(4, 4), s1=0.1)
+ for spawn, message in (
+ (None, "existing prim needs camera_model"),
+ (CuboidCfg(size=(1.0, 1.0, 1.0)), "does not spawn a camera"),
+ (FisheyeCameraCfg(), "OpenCvFisheyeDistortionCfg"),
+ (PinholeCameraCfg(horizontal_aperture_offset=1.0), "Aperture offsets"),
+ (PinholeCameraCfg(distortion=thin_prism), "Thin-prism"),
+ ):
+ with pytest.raises(ValueError, match=message):
+ FoveatedCamera._prepare_sampling(SimpleNamespace(cfg=make_cfg(spawn=spawn)))
+
+
+def test_config_validates_pooling_and_shell_settings() -> None:
+ assert make_cfg(pool_mode="gaussian").pool_mode == "gaussian"
+ with pytest.raises(ValueError, match="pool_mode must be one of"):
+ make_cfg(pool_mode="median")
+ # Segmentation pools only by modal label: other modes would mix labels into ones no object has.
+ assert make_cfg().pool_int_mode == "modal"
+ with pytest.raises(ValueError, match="pool_int_mode must be one of"):
+ make_cfg(pool_int_mode="avg")
+ # Square shells need a square or circular footprint and a grid style.
+ grid = dict(foveated_style="warped_cartesian_as_grid", radius_norm=math.inf)
+ assert make_cfg(**grid, fov_type="square").fov_type == "square"
+ with pytest.raises(ValueError, match="wang"):
+ make_cfg(**grid, fov_type="wang")
+ for kwargs in (
+ dict(radius_norm=1.0, foveated_style="warped_cartesian_as_grid"),
+ dict(radius_norm=math.inf, foveated_style="isotropic"),
+ ):
+ with pytest.raises(ValueError, match="radius_norm"):
+ make_cfg(**kwargs)
+ # Image processors such as PPISP need a pixel image, which a foveated camera does not publish.
+ for kwargs in (
+ dict(tensor_processors=[TensorProcessorCfg(func="isaaclab_ppisp:PpispProcessor")]),
+ dict(isp_cfg=CameraISPMode.AUTO_CAMERA),
+ ):
+ with pytest.raises(ValueError, match="tensor_processors or isp_cfg"):
+ make_cfg(**kwargs)
+
+
+@dataclass
+class RendererSelection:
+ renderer_type: str
+
+
+@dataclass
+class CameraSelection:
+ renderer_cfg: RendererSelection
+
+
+def test_renderer_selects_the_implementation() -> None:
+ def dispatch(cfg) -> type:
+ return type(FoveatedCamera.__new__(FoveatedCamera, cfg))
+
+ # The default renderer is Isaac RTX.
+ assert dispatch(make_cfg()) is FoveatedRTXCamera
+ for renderer_type, expected in (
+ ("ovrtx", FoveatedRTXCamera),
+ ("newton_warp", FoveatedNewtonCamera),
+ ("newton_optix", FoveatedNewtonCamera),
+ ):
+ assert dispatch(CameraSelection(RendererSelection(renderer_type))) is expected
+ with pytest.raises(ValueError, match="Unsupported foveated renderer"):
+ FoveatedCamera(CameraSelection(RendererSelection("unknown")))
+
+
+def test_cameras_that_turn_their_pose_by_the_gaze_need_per_frame_pose_updates(monkeypatch) -> None:
+ """Newton and OVRTX turn the rendered pose by the gaze in each pose update, so without pose updates the renderer
+ would never see the gaze; Isaac RTX writes the gaze into its camera prims instead."""
+ monkeypatch.setattr(Camera, "__init__", lambda self, cfg: setattr(self, "stage", None))
+ monkeypatch.setattr(Camera, "__del__", lambda self: None)
+ monkeypatch.setattr(FoveatedRTXCamera, "_prepare_projection", lambda self: None)
+ monkeypatch.setattr(sim_utils, "find_matching_prims", lambda *args: [])
+
+ def cfg(renderer_cfg) -> FoveatedCameraCfg:
+ return make_cfg(spawn=PinholeCameraCfg(), renderer_cfg=renderer_cfg, update_latest_camera_pose=False)
+
+ for renderer in (NewtonWarpRendererCfg(), OVRTXRendererCfg()):
+ with pytest.raises(ValueError, match="update_latest_camera_pose=True"):
+ FoveatedCamera(cfg(renderer))
+ assert not FoveatedCamera(cfg(IsaacRtxRendererCfg())).turns_pose_by_gaze
+
+
+IMPORT_BOUNDARY = """
+import importlib, importlib.abc, sys
+
+# Kit, fovi's research modules and training frameworks must not load with the sensor package.
+BLOCKED = ("isaacsim", "omni", "fovi.models", "fovi.training", "ffcv", "wandb", "lightning", "timm")
+
+
+class Block(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ if any(fullname == prefix or fullname.startswith(prefix + ".") for prefix in BLOCKED):
+ raise AssertionError(f"imported {fullname}")
+
+
+sys.meta_path.insert(0, Block())
+for module in ("isaaclab_fovi", "isaaclab_fovi.sensors", "isaaclab_fovi.sensors.pooling", "isaaclab_fovi.mdp"):
+ importlib.import_module(module)
+print("import boundary passed")
+"""
+
+
+def test_sensor_package_imports_without_kit_or_fovi_research_modules() -> None:
+ result = subprocess.run([sys.executable, "-c", IMPORT_BOUNDARY], capture_output=True, text=True, timeout=120)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "import boundary passed" in result.stdout
diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py
new file mode 100644
index 000000000000..7905155aca64
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_camera_gaze.py
@@ -0,0 +1,540 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""The camera's gaze, mount and sensor mask, and the Warp kernels behind them, without launching a simulator."""
+
+import math
+from dataclasses import asdict
+from types import SimpleNamespace
+
+import pytest
+import torch
+import warp as wp
+from fovi.sensing.coords import SamplingCoords
+from fovi.sensing.projection import CameraModel, gaze_rotation
+from fovi.sensing.retina import RetinalTransform
+from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions
+from isaaclab_fovi.sensors.foveated_camera import FoveatedCamera
+from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera
+from isaaclab_fovi.sensors.gaze_kernels import (
+ camera_params,
+ project_directions,
+ publish_grid_kernel,
+ set_gaze_kernel,
+ torch_stream,
+)
+from isaaclab_fovi.sensors.native_grid import GRID_STYLE, grid_sample_indices, native_grid_directions
+from isaaclab_fovi.sensors.pooling import build_retinal_coords
+
+from isaaclab.sensors.camera.camera import Camera
+from isaaclab.sensors.camera.camera_data import CameraData
+from isaaclab.test.utils import DeviceScope, test_devices
+from isaaclab.utils.math import (
+ convert_camera_frame_orientation_convention,
+ create_rotation_matrix_from_view,
+ matrix_from_quat,
+ quat_from_matrix,
+ quat_mul,
+)
+from isaaclab.utils.warp import ProxyArray
+
+pytestmark = pytest.mark.kitless
+
+CUDA = test_devices(DeviceScope.DEFAULT_CUDA)
+"""The kernels and their Python paths are the same on every device; the default GPU is what simulations use."""
+
+
+@pytest.fixture
+def tf32_enabled():
+ previous = torch.get_float32_matmul_precision()
+ torch.set_float32_matmul_precision("high")
+ try:
+ yield
+ finally:
+ torch.set_float32_matmul_precision(previous)
+
+
+def camera_config() -> SimpleNamespace:
+ camera = CameraModel("fisheye", (80, 120), (55, 55, 59.5, 39.5), (0.02, -0.003, 0, 0))
+ return SimpleNamespace(
+ camera_model=asdict(camera),
+ cmf_a_deg=2.5,
+ spawn=None,
+ retinal_window_reference_side="long",
+ retinal_window_fraction=0.75,
+ foveated_res=12,
+ foveated_style="isotropic",
+ fov_type="circular",
+ radius_norm=2.0,
+ isotropic_plotting_type="v1like",
+ image_rotation_deg=0.0,
+ pool_enabled=False,
+ )
+
+
+def test_rendering_and_software_sampling_share_window_and_nodes() -> None:
+ cfg = camera_config()
+ camera = CameraModel(**cfg.camera_model)
+ fov = camera.field_of_view("long", 0.75)
+ coords, _ = build_retinal_coords(cfg, camera, "cpu")
+ assert coords.fov == pytest.approx(fov)
+ assert coords.cmf_a == 2.5
+ retina = RetinalTransform(
+ fov=fov,
+ cmf_a=2.5,
+ resolution=12,
+ device="cpu",
+ field_geometry="spherical",
+ camera_model=camera,
+ gaze_convention="pan_tilt",
+ )
+ torch.testing.assert_close(coords.cartesian, retina.sampler.coords.cartesian)
+
+
+class GazeHarness(FoveatedCamera):
+ """The foveated camera's gaze state and kernels on stand-in pose buffers, without a simulator."""
+
+ def __new__(cls, *args, **overrides):
+ return object.__new__(cls)
+
+ def __init__(self, count: int = 2, device: str = "cpu", **overrides) -> None:
+ self.cfg = camera_config()
+ for name, value in overrides.items():
+ setattr(self.cfg, name, value)
+ self._view = SimpleNamespace(count=count)
+ self._device = device
+ self._ALL_INDICES = wp.array(list(range(count)), dtype=wp.int32, device=device)
+ self._prepare_sampling()
+ # The camera's own pose buffers, at the identity orientation, with their world-to-ROS conversion.
+ self._data = CameraData()
+ self._data.create_buffers(count, device)
+ self._data.quat_w_world.torch[:, 3] = 1.0
+ # Isaac RTX's behaviour; Newton and OVRTX turn the pose by the gaze in their pose update.
+ self._gaze_pose_reads_angles = False
+ self._gaze_written = False
+ self._initialize_sampling()
+
+ @property
+ def orientation(self) -> torch.Tensor:
+ """The camera's world orientation (x, y, z, w), world convention, shape (count, 4)."""
+ return self._data.quat_w_world.torch
+
+ def __del__(self) -> None:
+ """The harness registers no simulator callbacks to release."""
+
+
+class PrimView:
+ """Camera prims under an unturned parent: their world poses are their local poses (x, y, z, w), OpenGL."""
+
+ def __init__(self, orientations: torch.Tensor) -> None:
+ self.count = len(orientations)
+ self.local = orientations.clone()
+
+ def get_world_poses(self, indices=None):
+ ids = slice(None) if indices is None else wp.to_torch(indices).long()
+ orientations = self.local[ids].contiguous()
+ positions = torch.zeros(len(orientations), 3)
+ return ProxyArray(wp.from_torch(positions, dtype=wp.vec3f)), ProxyArray(
+ wp.from_torch(orientations, dtype=wp.quatf)
+ )
+
+ def get_local_poses(self):
+ return None, ProxyArray(wp.from_torch(self.local.clone(), dtype=wp.quatf))
+
+ def set_local_poses(self, *, orientations) -> None:
+ self.local = wp.to_torch(orientations).clone()
+
+
+class RtxGazeHarness(GazeHarness, FoveatedRTXCamera):
+ """The Isaac RTX camera's prim-writing gaze on stand-in camera prims."""
+
+ def __init__(self, mount_opengl: torch.Tensor) -> None:
+ super().__init__(count=len(mount_opengl))
+ self._view = PrimView(mount_opengl)
+ self._base_local_orientation = matrix_from_quat(mount_opengl)
+ self.mount_turns = 0
+
+
+MOUNT = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1)
+"""Two cameras' mount orientations (x, y, z, w), OpenGL convention, for the prim-writing harness."""
+
+
+def write_view(camera, eyes, targets, env_ids=None):
+ """Stand-in for the stock look-at write on :class:`RtxGazeHarness`: each row whose eye differs from its target
+ looks at it; the others keep their poses."""
+ rotation = create_rotation_matrix_from_view(eyes, targets, "Z")
+ looks = ~torch.isnan(rotation).any(dim=(-2, -1))
+ ids = camera._env_indices(env_ids)[looks]
+ camera._view.local[ids] = quat_from_matrix(rotation[looks])
+
+
+def write_prims(camera, positions=None, orientations=None, env_ids=None, convention="ros"):
+ """Stand-in for the stock pose write on :class:`RtxGazeHarness`: the orientations become the prims' poses."""
+ if orientations is not None:
+ ids = slice(None) if env_ids is None else torch.as_tensor(env_ids)
+ camera._view.local[ids] = convert_camera_frame_orientation_convention(orientations, convention, "opengl")
+
+
+def gaze_direction(angles_deg: torch.Tensor) -> torch.Tensor:
+ """OpenCV camera-frame unit direction of (tilt, pan) gaze angles [deg]: up and left are positive."""
+ tilt, pan = angles_deg.deg2rad().unbind(-1)
+ return torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1)
+
+
+def angles_toward(camera: CameraModel, pixel: tuple[float, float]) -> torch.Tensor:
+ """(tilt, pan) gaze angles [deg] that look along the ray through a source pixel (x, y)."""
+ direction, _ = camera.unproject(torch.tensor([pixel]))
+ x, y, z = direction.unbind(-1)
+ return torch.stack((-torch.atan2(y, torch.sqrt(x * x + z * z)), -torch.atan2(x, z)), -1).rad2deg()
+
+
+@pytest.mark.parametrize("device", CUDA)
+@pytest.mark.parametrize(
+ "mode, autocast",
+ [
+ ("spherical", False),
+ ("spherical", True),
+ ("spherical_ids", False),
+ ("spherical_warp_ids", False),
+ ("spherical_slice", False),
+ ("spherical_mask", False),
+ ],
+)
+def test_gaze_preserves_camera_rotation_with_tf32(device: str, autocast: bool, mode: str, tf32_enabled) -> None:
+ batch_size = 48
+ source_gl = torch.tensor([[0.4625, 0.4940, -0.5341, 0.5067]], device=device).repeat(batch_size, 1)
+ conversion = source_gl.new_tensor([[0, 0, -1], [-1, 0, 0], [0, 1, 0]]).double()
+ source = quat_from_matrix(matrix_from_quat(source_gl.double()) @ conversion.T).float()
+ original = source.clone()
+ angles = torch.tensor([[7.5, -12.0]], device=device).repeat(batch_size, 1)
+ angles[1::2] = 0
+ expected = matrix_from_quat(source.double()) @ conversion
+ camera = GazeHarness(count=batch_size, device=device)
+ camera.orientation.copy_(source)
+ # The gaze turns the camera's own pose buffer in place.
+ source = camera.orientation
+ camera._gaze_basis = camera._gaze_basis.to(device)
+ camera.set_gaze_angles(angles)
+ basis = camera._gaze_basis.double()
+ expected = expected @ basis @ camera._gaze_rotation.torch.double() @ basis.T @ conversion.T
+ selected = torch.arange(batch_size, device=device) % 2 == 0
+ with torch.autocast(device, dtype=torch.bfloat16, enabled=autocast):
+ if mode == "spherical_ids":
+ camera._apply_gaze_pose(torch.nonzero(selected).flatten())
+ elif mode == "spherical_warp_ids":
+ # An int64 Warp selector, which the kernel's int32 indices must not reinterpret.
+ camera._apply_gaze_pose(wp.from_torch(torch.nonzero(selected).flatten(), dtype=wp.int64))
+ elif mode == "spherical_slice":
+ camera._apply_gaze_pose(slice(0, None, 2))
+ elif mode == "spherical_mask":
+ camera._apply_gaze_pose(env_mask=wp.from_torch(selected))
+ else:
+ camera._apply_gaze_pose()
+ if mode != "spherical":
+ torch.testing.assert_close(source[~selected], original[~selected], atol=0, rtol=0)
+ source = source[selected]
+ expected = expected[selected]
+ assert source.dtype == torch.float32
+ assert torch.isfinite(source).all()
+ torch.testing.assert_close(source.norm(dim=-1), torch.ones(len(source), device=device), atol=1e-6, rtol=0)
+ torch.testing.assert_close(matrix_from_quat(source.double()), expected, atol=1e-6, rtol=0)
+ assert torch.get_float32_matmul_precision() == "high"
+
+
+def test_sensor_mask_checks_the_rendered_rays_of_a_rolled_mount() -> None:
+ """The mask sees exactly the rays the turned camera renders, found here through the camera pose instead."""
+ rotation_deg = 30.0
+ # An off-center, wide image makes a roll change which samples the camera sees.
+ model = CameraModel("pinhole", (80, 120), (60.0, 60.0, 45.0, 30.0))
+ camera = GazeHarness(camera_model=asdict(model), image_rotation_deg=rotation_deg)
+ camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]]))
+ mount = camera.orientation.clone()
+ camera._apply_gaze_pose()
+
+ # Rendered rays leave the turned camera along its OpenGL frame; express them in the mount's OpenGL frame.
+ def opengl(orientation: torch.Tensor) -> torch.Tensor:
+ return matrix_from_quat(convert_camera_frame_orientation_convention(orientation, "world", "opengl"))
+
+ turn = opengl(mount).transpose(-1, -2) @ opengl(camera.orientation)
+ coords = camera._sampling_coords
+ rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg)
+ seen = (turn[:, None] @ rays[None, :, :, None]).squeeze(-1) * torch.tensor([1.0, -1.0, -1.0])
+ expected = model.project(seen)[1]
+ assert expected.any() and (~expected).any()
+ assert (camera._gaze_validity() == expected).float().mean() > 0.999
+
+
+def test_gaze_angles_need_one_row_per_camera() -> None:
+ camera = GazeHarness()
+ with pytest.raises(ValueError, match=r"shape \(2, 2\)"):
+ camera.set_gaze_angles(torch.zeros(3, 2))
+ assert camera._gaze_angles is None
+
+
+def test_mount_record_starts_at_the_current_pose() -> None:
+ """Allocating the gaze before any pose update records the camera's current, ungazed mount, not zeros."""
+ camera = GazeHarness()
+ camera._gaze_pose_reads_angles = True
+ mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1)
+ camera.orientation.copy_(mount)
+ camera.gaze_angles
+ expected = convert_camera_frame_orientation_convention(mount, "world", "ros")
+ torch.testing.assert_close(
+ matrix_from_quat(camera.ungazed_quat_w_ros()), matrix_from_quat(expected), atol=1e-6, rtol=0
+ )
+
+
+def test_prim_writing_camera_reads_its_mount_before_and_after_a_gaze() -> None:
+ """Isaac RTX writes the gaze into its prims; its mount reads the same before and after a gaze is set, so a
+ fixed-mount teacher created after a gaze aims from the real mount."""
+ camera = RtxGazeHarness(MOUNT)
+ # The last pose update read the bare mount.
+ camera.orientation.copy_(convert_camera_frame_orientation_convention(MOUNT, "opengl", "world"))
+ expected = matrix_from_quat(convert_camera_frame_orientation_convention(MOUNT, "opengl", "ros"))
+ torch.testing.assert_close(matrix_from_quat(camera.ungazed_quat_w_ros()), expected, atol=1e-6, rtol=0)
+ camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]]))
+ assert not torch.allclose(matrix_from_quat(camera._view.local), matrix_from_quat(MOUNT), atol=1e-3)
+ torch.testing.assert_close(matrix_from_quat(camera.ungazed_quat_w_ros()), expected, atol=1e-6, rtol=0)
+
+
+def test_pose_update_records_the_mount_before_the_gaze() -> None:
+ camera = GazeHarness()
+ mount = torch.nn.functional.normalize(torch.tensor([[0.2, -0.4, 0.1, 0.9], [0.0, 0.3, -0.5, 0.6]]), dim=-1)
+ camera.orientation.copy_(mount)
+ camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]]))
+ camera._apply_gaze_pose()
+ expected = convert_camera_frame_orientation_convention(mount, "world", "ros")
+ torch.testing.assert_close(
+ matrix_from_quat(camera._mount_quat_ros.torch), matrix_from_quat(expected), atol=1e-6, rtol=0
+ )
+ assert not torch.allclose(camera.orientation, mount)
+ # An indexed pose update turns only the selected cameras.
+ untouched = camera.orientation[1].clone()
+ camera.orientation[0] = mount[0]
+ camera._apply_gaze_pose([0])
+ torch.testing.assert_close(camera.orientation[1], untouched)
+
+
+@pytest.mark.parametrize("device", CUDA)
+def test_rtx_gaze_pose_writer_is_stable_inside_model_autocast(device: str, tf32_enabled) -> None:
+ camera = GazeHarness(count=48, device=device)
+ camera._gaze_basis = camera._gaze_basis.to(device)
+ camera._base_local_orientation = matrix_from_quat(
+ torch.tensor([[-0.4625, -0.4940, 0.5341, -0.5067]], device=device).repeat(48, 1)
+ )
+ written = []
+ camera._view = SimpleNamespace(
+ count=48,
+ set_local_poses=lambda *, orientations: written.append(torch.utils.dlpack.from_dlpack(orientations).clone()),
+ )
+ # Policy outputs may themselves be BF16; both paths use the same input values.
+ angles = torch.tensor([[-0.006677, -0.010717]], device=device, dtype=torch.bfloat16).repeat(48, 1)
+ for enabled in [False, True]:
+ with torch.autocast(device, dtype=torch.bfloat16, enabled=enabled):
+ camera.set_gaze_angles(angles)
+ FoveatedRTXCamera._write_gaze_local_pose(camera)
+ assert torch.isfinite(written[1]).all()
+ assert written[1].dtype == torch.float32
+ torch.testing.assert_close(written[1].norm(dim=-1), torch.ones(48, device=device))
+ torch.testing.assert_close(written[1], written[0])
+
+
+def test_rtx_world_poses_are_the_mount_and_only_a_turned_mount_is_recorded(monkeypatch) -> None:
+ """Isaac RTX holds the gaze in its prims; its world poses still report the bare mount, as the other renderers'
+ do, so writing them back (as a viewer navigating the camera does) neither moves the mount nor doubles the gaze.
+
+ The fixed-mount teacher reads the live camera position, so only writes that turn a mount count: not a position
+ move, and not writing back the reported mount (of either quaternion sign), even with a gaze held in the prims."""
+ monkeypatch.setattr(Camera, "set_world_poses", write_prims)
+ camera = RtxGazeHarness(MOUNT)
+ mount = MOUNT
+ camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]]))
+ gazed = camera._view.local.clone()
+ assert not torch.allclose(matrix_from_quat(gazed), matrix_from_quat(mount), atol=1e-3)
+
+ _, orientations = camera.get_world_poses(env_ids=[1], convention="ros")
+ expected = convert_camera_frame_orientation_convention(mount[1:], "opengl", "ros")
+ torch.testing.assert_close(matrix_from_quat(orientations), matrix_from_quat(expected), atol=1e-6, rtol=0)
+
+ _, orientations = camera.get_world_poses(convention="world")
+ camera.set_world_poses(orientations=orientations, convention="world")
+ torch.testing.assert_close(camera._base_local_orientation, matrix_from_quat(mount), atol=1e-6, rtol=0)
+ torch.testing.assert_close(matrix_from_quat(camera._view.local), matrix_from_quat(gazed), atol=1e-6, rtol=0)
+
+ # Only a write that turns a mount counts as a turn.
+ monkeypatch.setattr(Camera, "set_world_poses_from_view", write_view)
+ eyes = torch.zeros(2, 3)
+ targets = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
+
+ def view_twice(camera):
+ # Looking again from the same eye at the same target leaves the mount where the first view put it.
+ camera.set_world_poses_from_view(eyes, targets)
+ camera.mount_turns = 0
+ camera.set_world_poses_from_view(eyes, targets)
+
+ def reported(camera, env_ids=None):
+ return camera.get_world_poses(env_ids, convention="ros")[1]
+
+ def turn_second(camera):
+ # One degree about the second camera's optical axis.
+ half = torch.tensor(math.radians(1.0) / 2)
+ roll = torch.tensor([[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, float(half.sin()), float(half.cos())]])
+ camera.set_world_poses(orientations=quat_mul(reported(camera), roll))
+
+ for move, turned in (
+ (lambda camera: camera.set_world_poses(positions=torch.zeros(2, 3)), False),
+ (lambda camera: camera.set_world_poses(orientations=reported(camera)), False),
+ (lambda camera: camera.set_world_poses(orientations=-reported(camera, [1]), env_ids=[1]), False),
+ (turn_second, True),
+ (lambda camera: camera.set_world_poses_from_view(eyes, eyes), False),
+ (lambda camera: camera.set_world_poses_from_view(eyes, targets), True),
+ (view_twice, False),
+ ):
+ camera = RtxGazeHarness(MOUNT)
+ camera.set_gaze_angles(torch.tensor([[6.0, -11.0], [-9.0, 17.0]]))
+ move(camera)
+ assert camera.mount_turns == int(turned)
+
+
+@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA))
+def test_gaze_kernels_preserve_shared_stream_for_warp_capture(device: str) -> None:
+ wp.init()
+ stream = wp.Stream(device)
+ with wp.ScopedStream(stream), torch.cuda.stream(wp.stream_to_torch(stream)):
+ camera = GazeHarness(device=device)
+ camera.set_gaze_angles(torch.tensor([[5.0, -8.0], [0.0, 0.0]], device=device))
+ valid = camera._gaze_validity()
+ target = wp.zeros(valid.shape, dtype=wp.bool, device=device)
+ # Physics must still be able to capture after the camera's temporary stream scopes exit.
+ with wp.ScopedCapture(stream=stream) as capture:
+ wp.copy(target, wp.from_torch(valid))
+ wp.capture_launch(capture.graph)
+ torch.testing.assert_close(wp.to_torch(target), valid)
+ assert valid[1].any()
+
+
+# -- The gaze kernels against fovi's camera geometry ------------------------------------------------------------------
+
+KERNEL_DEVICE = next(iter(CUDA), "cpu")
+"""The run's default GPU, or the CPU when the run selects none."""
+
+KERNEL_CAMERAS = {
+ "distorted pinhole": CameraModel(
+ "pinhole",
+ (480, 640),
+ (520.0, 515.0, 322.0, 241.0),
+ distortion=(-0.28, 0.09, 0.001, -0.002, -0.01, 0.02, -0.01, 0.005),
+ ),
+ "fisheye with image circle": CameraModel(
+ "fisheye",
+ (800, 800),
+ (230.0, 230.0, 399.5, 399.5),
+ distortion=(0.02, -0.01, 0.003, -0.001),
+ image_circle=(399.5, 399.5, 380.0),
+ max_angle_deg=95.0,
+ ),
+}
+
+
+def set_gaze(angles: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """The stored angles and gaze rotations :func:`set_gaze_kernel` writes."""
+ stored = torch.empty_like(angles)
+ rotation = torch.empty(len(angles), 3, 3, device=angles.device)
+ with torch_stream(angles.device):
+ wp.launch(
+ set_gaze_kernel,
+ dim=len(angles),
+ inputs=[wp.from_torch(angles.contiguous(), dtype=wp.vec2f)],
+ outputs=[wp.from_torch(stored, dtype=wp.vec2f), wp.from_torch(rotation, dtype=wp.mat33f)],
+ )
+ return stored, rotation
+
+
+@pytest.mark.parametrize("name", KERNEL_CAMERAS)
+def test_projection_kernel_matches_fovi(name: str) -> None:
+ """The sensor mask projects with fovi's camera model, as the software sampler does on a real camera."""
+ camera = KERNEL_CAMERAS[name]
+ generator = torch.Generator().manual_seed(0)
+ directions = torch.randn(20000, 3, generator=generator)
+ directions[:, 2] = directions[:, 2].abs() * 1.5 # mostly forward, some sideways and behind
+ directions[:2000, 2] *= -1
+ directions = torch.nn.functional.normalize(directions, dim=-1).to(KERNEL_DEVICE)
+ expected_pixels, expected_valid = camera.project(directions)
+ pixels, valid = project_directions(directions, camera_params(camera))
+ # Float32 rounding may flip a sample that lies on the image edge, nothing more.
+ assert (valid == expected_valid).float().mean() > 0.9995
+ assert expected_valid.any() and (~expected_valid).any()
+ both = valid & expected_valid
+ torch.testing.assert_close(pixels[both], expected_pixels[both], rtol=1e-4, atol=1e-2)
+
+
+def test_gaze_rotation_follows_fovis_pan_tilt_convention() -> None:
+ """The gaze turns the rays as fovi's software sampler turns them, so a policy sees the same retina on hardware."""
+ angles = ((torch.rand(64, 2, generator=torch.Generator().manual_seed(1)) * 2 - 1) * 40).to(KERNEL_DEVICE)
+ stored, rotation = set_gaze(angles)
+ tilt, pan = angles.deg2rad().unbind(-1)
+ direction = torch.stack((-tilt.cos() * pan.sin(), -tilt.sin(), tilt.cos() * pan.cos()), -1)
+ torch.testing.assert_close(stored, angles, atol=0, rtol=0)
+ torch.testing.assert_close(rotation, gaze_rotation(direction, "pan_tilt"), atol=1e-5, rtol=0)
+
+
+def test_publish_kernel_matches_masking_then_copying_to_the_grid() -> None:
+ camera = KERNEL_CAMERAS["distorted pinhole"]
+ coords = SamplingCoords(
+ camera.field_of_view("short"), 0.591, 24, style=GRID_STYLE, field_geometry="spherical", device=KERNEL_DEVICE
+ )
+ rays = (native_grid_directions(coords) * coords.cartesian.new_tensor((1, -1, -1))).float().contiguous()
+ generator = torch.Generator().manual_seed(2)
+ angles = ((torch.rand(6, 2, generator=generator) * 2 - 1) * 25).to(KERNEL_DEVICE)
+ _, rotation = set_gaze(angles)
+ count = len(coords)
+ outputs = {
+ "rgba": torch.randint(1, 255, (6, count, 1, 4), generator=generator, dtype=torch.uint8).to(KERNEL_DEVICE),
+ "depth": (torch.rand(6, count, 1, 1, generator=generator) + 0.5).to(KERNEL_DEVICE),
+ }
+ valid = camera.project(rays @ rotation.transpose(-1, -2))[1]
+ # Environments 1 and 4 were not rendered this frame and keep their previous image.
+ updated = torch.tensor([True, False, True, True, False, True], device=KERNEL_DEVICE)
+
+ # The sequence the kernel replaces: footprint mask, sensor mask, then the upright layout. The layout comes from
+ # fovi's own grid reshaping rather than the index permutation the kernel uses.
+ keep = valid & coords.valid_mask[None]
+ expected_grid = {
+ name: coords.as_grid(value.squeeze(2) * keep[..., None], sample_dim=1) for name, value in outputs.items()
+ }
+ indices = grid_sample_indices(coords).to(torch.int32).contiguous()
+ visible = torch.zeros(6, count, dtype=torch.bool, device=KERNEL_DEVICE)
+ identity = wp.mat33f(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
+ # Only the first output receives the real gaze. Reprojecting depth instead of reusing the first launch's
+ # visibility would point the depth rays the wrong way and hide visible samples.
+ _, looking_away = set_gaze(torch.tensor([[0.0, 180.0]], device=KERNEL_DEVICE).repeat(6, 1))
+ for index, (name, value) in enumerate(outputs.items()):
+ previous = torch.full_like(expected_grid[name], 7)
+ target = previous.clone()
+ with torch_stream(KERNEL_DEVICE):
+ wp.launch(
+ publish_grid_kernel,
+ dim=(6, count),
+ inputs=[
+ wp.from_torch(value.squeeze(2).view(torch.uint8)),
+ wp.from_torch(indices),
+ wp.from_torch(coords.valid_mask.contiguous()),
+ wp.from_torch(updated),
+ wp.from_torch(rays, dtype=wp.vec3f),
+ wp.from_torch(rotation if index == 0 else looking_away, dtype=wp.mat33f),
+ identity,
+ camera_params(camera),
+ 1,
+ int(index == 0),
+ wp.from_torch(visible),
+ ],
+ outputs=[wp.from_torch(target.view(6, count, -1).view(torch.uint8))],
+ )
+ # Float32 rounding may flip a sample on the image edge, nothing more.
+ assert (target[updated] == expected_grid[name][updated]).all(-1).float().mean() > 0.999
+ assert torch.equal(target[~updated], previous[~updated])
+ assert (visible[updated] == valid[updated]).float().mean() > 0.999
+ assert not visible[~updated].any()
+ assert valid.any() and (~valid).any()
diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py
new file mode 100644
index 000000000000..4f8862871c08
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py
@@ -0,0 +1,65 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Render tests for the foveated camera on the Newton (Warp and OptiX) and Isaac RTX renderers.
+
+The cases live in :mod:`foveated_render_cases`; OVRTX runs them without Kit in ``test_foveated_camera_render_ovrtx``.
+"""
+
+import os
+
+from isaaclab.test.utils import launch_test_simulation
+
+launch_test_simulation(enable_cameras=True)
+
+import foveated_render_cases as cases # noqa: E402
+import pytest # noqa: E402
+from isaaclab_fovi.sensors import FoveatedNewtonCamera, FoveatedRTXCamera # noqa: E402
+from isaaclab_isaacsim.physics import PhysxCfg # noqa: E402
+from isaaclab_isaacsim.renderers import IsaacRtxRendererCfg # noqa: E402
+from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg # noqa: E402
+from isaaclab_newton.renderers import NewtonOptixRendererCfg, NewtonWarpRendererCfg # noqa: E402
+
+pytestmark = [pytest.mark.integration, pytest.mark.rendering, pytest.mark.isaacsim_ci]
+
+# Each backend pairs a physics engine with the renderer under test and the implementation it selects.
+BACKENDS = {
+ "newton_warp": (NewtonCfg(solver_cfg=MJWarpSolverCfg()), NewtonWarpRendererCfg, FoveatedNewtonCamera),
+ "newton_optix": (NewtonCfg(solver_cfg=MJWarpSolverCfg()), NewtonOptixRendererCfg, FoveatedNewtonCamera),
+ "isaac_rtx": (PhysxCfg(), IsaacRtxRendererCfg, FoveatedRTXCamera),
+}
+
+
+def backend_cfg(name: str):
+ """The backend, after checking that its renderer can run here.
+
+ OptiX needs the ``optix`` extra and a driver that supports its ABI; without them its cases skip, unless
+ ``ISAACLAB_TEST_REQUIRE_OPTIX`` is set, as in Isaac Lab's own OptiX rendering tests.
+ """
+ if name == "newton_optix":
+ if os.environ.get("ISAACLAB_TEST_REQUIRE_OPTIX"):
+ import optix # noqa: F401
+ else:
+ pytest.importorskip("optix", exc_type=ImportError)
+ return BACKENDS[name]
+
+
+@pytest.fixture(scope="module", params=list(BACKENDS))
+def ground(request):
+ """One ground scene per backend, which every case below renders in turn."""
+ with cases.ground_scene(backend_cfg(request.param)) as scene:
+ yield scene
+
+
+def test_foveated_camera_follows_gaze(ground):
+ cases.foveated_camera_follows_gaze(ground)
+
+
+def test_gaze_stays_relative_to_moved_mounts(ground):
+ cases.gaze_stays_relative_to_moved_mounts(ground)
+
+
+def test_foveated_camera_samples_densest_at_the_fixation(ground):
+ cases.foveated_camera_samples_densest_at_the_fixation(ground)
diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py
new file mode 100644
index 000000000000..e72878601758
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py
@@ -0,0 +1,49 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Render tests for the foveated camera on the OVRTX renderer, with Newton physics.
+
+Runs without Kit: ``ovrtx`` and Isaac Sim Kit ship conflicting RTX libraries that cannot load in one process. The
+cases live in :mod:`foveated_render_cases`.
+"""
+
+import importlib.util
+
+import pytest
+
+pytestmark = [pytest.mark.integration, pytest.mark.rendering, pytest.mark.ov]
+
+_REQUIRED_MODULES = ("isaaclab_ov", "ovrtx", "isaaclab_newton")
+_MISSING_MODULES = [module for module in _REQUIRED_MODULES if importlib.util.find_spec(module) is None]
+pytestmark.append(
+ pytest.mark.skipif(bool(_MISSING_MODULES), reason=f"requires optional modules: {', '.join(_MISSING_MODULES)}")
+)
+
+if not _MISSING_MODULES:
+ import foveated_render_cases as cases
+ from isaaclab_fovi.sensors import FoveatedRTXCamera
+ from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg
+ from isaaclab_ov.renderers import OVRTXRendererCfg
+
+ BACKEND = (NewtonCfg(solver_cfg=MJWarpSolverCfg()), OVRTXRendererCfg, FoveatedRTXCamera)
+
+
+@pytest.fixture(scope="module")
+def ground():
+ """One ground scene, which every case below renders in turn."""
+ with cases.ground_scene(BACKEND) as scene:
+ yield scene
+
+
+def test_foveated_camera_follows_gaze(ground):
+ cases.foveated_camera_follows_gaze(ground)
+
+
+def test_gaze_stays_relative_to_moved_mounts(ground):
+ cases.gaze_stays_relative_to_moved_mounts(ground)
+
+
+def test_foveated_camera_samples_densest_at_the_fixation(ground):
+ cases.foveated_camera_samples_densest_at_the_fixation(ground)
diff --git a/source/isaaclab_fovi/test/test_native_grid.py b/source/isaaclab_fovi/test/test_native_grid.py
new file mode 100644
index 000000000000..996b73089881
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_native_grid.py
@@ -0,0 +1,186 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""The native grid's rays, lens textures and published layout agree with independent geometry."""
+
+import math
+
+import pytest
+import torch
+from fovi.sensing.coords import SamplingCoords
+from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions
+from isaaclab_fovi.sensors.lens_lut import build_native_grid_textures
+from isaaclab_fovi.sensors.native_grid import (
+ allocate_outputs,
+ bounded_angular_radius,
+ copy_grid_outputs,
+ grid_output_shape,
+ grid_sample_indices,
+ mask_grid_samples,
+ native_grid_directions,
+ native_grid_exit_uv,
+ unbounded_angular_radius,
+)
+
+from isaaclab.test.utils import DeviceScope, test_devices
+
+pytestmark = pytest.mark.kitless
+
+
+def make_coords(resolution: int = 64, coverage: str = "circular", field: str = "spherical") -> SamplingCoords:
+ """A wide grid; ``"square_shells"`` is the square footprint with square (infinity-norm) shells."""
+ fov = 80.0 if coverage == "wang" else 170.0
+ square_shells = coverage == "square_shells"
+ return SamplingCoords(
+ fov=fov,
+ cmf_a=0.036021 * fov,
+ res=resolution,
+ style="warped_cartesian_as_grid",
+ fov_type="square" if square_shells else coverage,
+ radius_norm=math.inf if square_shells else 2.0,
+ field_geometry=field,
+ device="cpu",
+ )
+
+
+def texel_centers(resolution: int) -> torch.Tensor:
+ """Native texture UV of each canonical sample: columns follow native x, rows native y."""
+ axis = (torch.arange(resolution) + 0.5) / resolution
+ row, col = torch.meshgrid(axis, axis, indexing="ij")
+ return torch.stack((col, row), -1).reshape(-1, 2)
+
+
+def eccentricity_rays(visual: torch.Tensor, fov_deg: float, rotation_deg: float = 0.0) -> torch.Tensor:
+ """OpenGL rays for visual-chart points: angle off the axis is the visual radius times the half field of view."""
+ visual = visual.to(torch.float64)
+ theta = torch.linalg.vector_norm(visual, dim=-1) * math.radians(fov_deg) / 2
+ phi = torch.atan2(visual[..., 1], visual[..., 0]) + math.radians(rotation_deg)
+ return torch.stack((theta.sin() * phi.cos(), theta.sin() * phi.sin(), -theta.cos()), -1)
+
+
+@pytest.mark.parametrize(
+ ("coverage", "resolution", "rotation"),
+ # Circular padding outside the field, and odd square-shell grids with a texel on the axis, under a roll.
+ [("circular", 64, 0.0), ("square_shells", 15, 37.0)],
+)
+def test_every_texel_roundtrips(coverage: str, resolution: int, rotation: float) -> None:
+ coords = make_coords(resolution, coverage)
+ rays = native_grid_directions(coords, image_rotation_deg=rotation)
+ uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation)
+ assert valid.all()
+ torch.testing.assert_close(uv, texel_centers(resolution), atol=2e-6, rtol=0)
+ torch.testing.assert_close(rays.norm(dim=-1), torch.ones(len(coords)), atol=1e-6, rtol=0)
+
+
+@pytest.mark.parametrize(("coverage", "rotation"), [("wang", 180.0), ("square_shells", 37.0)])
+def test_inverse_maps_independent_rays_to_their_texels(coverage: str, rotation: float) -> None:
+ coords = make_coords(64, coverage)
+ half_fov = math.radians(coords.fov) / 2
+ # Rays through fovi's own sample positions inside the field land on those samples' texels.
+ inside = torch.linalg.vector_norm(coords.cartesian, dim=-1) <= (math.sqrt(2) if coverage == "square_shells" else 1)
+ rays = eccentricity_rays(coords.cartesian[inside], coords.fov, rotation)
+ uv, valid = native_grid_exit_uv(rays, coords, image_rotation_deg=rotation)
+ assert inside.sum() > len(coords) // 2
+ assert valid.all()
+ torch.testing.assert_close(uv, texel_centers(64)[inside], atol=2e-6, rtol=0)
+ # The optical axis is the texture centre and the nominal rim along each rolled native axis is its edge.
+ roll = math.radians(rotation)
+ rim = [
+ (math.sin(half_fov) * math.cos(angle), math.sin(half_fov) * math.sin(angle), -math.cos(half_fov))
+ for angle in (roll, roll + math.pi / 2)
+ ]
+ hand_rays = torch.tensor([(0.0, 0.0, -1.0), *rim], dtype=torch.float64)
+ uv, _ = native_grid_exit_uv(hand_rays, coords, image_rotation_deg=rotation)
+ torch.testing.assert_close(uv, torch.tensor([[0.5, 0.5], [0.5, 1.0], [1.0, 0.5]]), atol=1e-6, rtol=0)
+
+
+def test_valid_samples_match_the_software_sampler_rays() -> None:
+ """The renderer's rays are the ones fovi's software sampler uses on a real camera's images."""
+ coords = make_coords()
+ actual = native_grid_directions(coords)
+ expected = retinal_directions(coords.cartesian[coords.valid_mask], coords.fov)
+ torch.testing.assert_close(actual[coords.valid_mask], expected, atol=3e-7, rtol=0)
+ with pytest.raises(ValueError, match="spherical"):
+ native_grid_directions(make_coords(16, field="planar"))
+
+
+def test_spherical_padding_matches_rim_slope_and_does_not_wrap() -> None:
+ radius = torch.tensor([0.0, 0.99999, 1.0, 1.00001, 2.0, 10.0], dtype=torch.float64)
+ half_fov = math.radians(170) / 2
+ angles = bounded_angular_radius(radius, half_fov)
+ assert (angles[1:] > angles[:-1]).all()
+ assert (angles < math.pi).all()
+ left = (angles[2] - angles[1]) / (radius[2] - radius[1])
+ right = (angles[3] - angles[2]) / (radius[3] - radius[2])
+ torch.testing.assert_close(left, right, atol=2e-5, rtol=0)
+ torch.testing.assert_close(unbounded_angular_radius(angles, half_fov), radius, atol=1e-10, rtol=0)
+
+
+@pytest.mark.parametrize(("coverage", "rotation"), [("circular", 0.0), ("square_shells", 37.0)])
+def test_textures_match_independent_geometry(coverage: str, rotation: float) -> None:
+ coords = make_coords(64, coverage)
+ size = 256
+ direction, inverse = build_native_grid_textures(coords, image_rotation_deg=rotation, exit_size=size)
+ assert direction.shape == (64, 64, 3) and inverse.shape == (size, size, 2)
+ inside = coords.valid_mask & (torch.linalg.vector_norm(coords.cartesian, dim=-1) <= math.sqrt(2))
+ expected = eccentricity_rays(coords.cartesian[inside], coords.fov, rotation).float()
+ torch.testing.assert_close(direction.reshape(-1, 3)[inside], expected, atol=1e-6, rtol=0)
+ # Forward-hemisphere octahedral texel centres decode to (x, y, -(1 - |x| - |y|)) before normalization.
+ axis = (torch.arange(size, dtype=torch.float64) + 0.5) / size * 2 - 1
+ y, x = torch.meshgrid(axis, axis, indexing="ij")
+ forward = x.abs() + y.abs() < 1
+ texel_rays = torch.nn.functional.normalize(torch.stack((x, y, x.abs() + y.abs() - 1), -1), dim=-1)
+ # Each stored UV, mapped back through fovi's native-to-visual warp, must look along its texel's ray.
+ stored = forward & (inverse[..., 0] >= 0)
+ native = (inverse[stored].to(torch.float64) * 2 - 1).flip(-1)
+ visual = coords.native_to_visual(native)
+ # Circular grids pad outside the nominal field on another curve; square shells reach their corners linearly.
+ linear = torch.ones(len(visual), dtype=torch.bool)
+ if coverage == "circular":
+ linear = torch.linalg.vector_norm(visual, dim=-1) <= 1
+ assert linear.sum() > 1000
+ torch.testing.assert_close(
+ eccentricity_rays(visual[linear], coords.fov, rotation), texel_rays[stored][linear], atol=1e-5, rtol=0
+ )
+ # The antipode lies outside every grid.
+ assert (inverse[0, 0] == -1).all() and (inverse[-1, -1] == -1).all()
+ assert torch.isfinite(inverse).all()
+
+
+def test_upright_grid_masks_aliases_and_graph_capture() -> None:
+ coords = make_coords(16)
+ # Coordinate channels make rotation/transposition failures observable.
+ values = torch.cat((coords.cartesian, torch.ones(len(coords), 2)), -1)[None, :, None]
+ source = {"rgba": values.clone()}
+ source["rgb"] = source["rgba"][..., :3]
+ mask_grid_samples(source, coords)
+ target = allocate_outputs(source, *grid_output_shape(coords))
+ copy_grid_outputs(source, target, grid_sample_indices(coords))
+ expected = coords.as_grid(source["rgba"][:, :, 0], sample_dim=1)
+ torch.testing.assert_close(target["rgba"], expected)
+ assert target["rgb"].untyped_storage().data_ptr() == target["rgba"].untyped_storage().data_ptr()
+ assert target["rgba"][0, :, :, 0][8, 4] < target["rgba"][0, :, :, 0][8, 11]
+ assert target["rgba"][0, :, :, 1][4, 8] > target["rgba"][0, :, :, 1][11, 8]
+ assert (target["rgba"][0][~coords.as_grid(coords.valid_mask)] == 0).all()
+ # The publication copy is graph-capturable on CUDA.
+ for device in test_devices(DeviceScope.DEFAULT_CUDA):
+ coords = make_coords(16).to(device=device)
+ source = {
+ "value": torch.arange(3 * len(coords) * 4, device=device).to(torch.uint8).reshape(3, len(coords), 1, 4)
+ }
+ target = allocate_outputs(source, *grid_output_shape(coords))
+ indices = grid_sample_indices(coords)
+ copy_grid_outputs(source, target, indices)
+ torch.testing.assert_close(
+ target["value"], coords.as_grid(source["value"][:, :, 0], sample_dim=1), atol=0, rtol=0
+ )
+ torch.cuda.synchronize()
+ graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(graph):
+ copy_grid_outputs(source, target, indices)
+ source["value"].zero_()
+ graph.replay()
+ torch.cuda.synchronize()
+ assert torch.count_nonzero(target["value"]) == 0
diff --git a/source/isaaclab_fovi/test/test_newton_buffers.py b/source/isaaclab_fovi/test/test_newton_buffers.py
new file mode 100644
index 000000000000..b937b07fd904
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_newton_buffers.py
@@ -0,0 +1,304 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""The Newton foveated camera's render layout and publication, on stand-in renderer buffers."""
+
+from collections.abc import Callable
+from dataclasses import asdict
+from types import SimpleNamespace
+
+import pytest
+import torch
+import warp as wp
+from fovi.sensing.coords import SamplingCoords
+from fovi.sensing.projection import CameraModel
+from isaaclab_fovi.sensors import foveated_camera as base_camera
+from isaaclab_fovi.sensors import foveated_newton_camera as newton_camera
+from isaaclab_fovi.sensors.foveated_newton_camera import FoveatedNewtonCamera, explicit_rays
+from isaaclab_fovi.sensors.native_grid import native_grid_directions
+from isaaclab_fovi.sensors.pooling import pool_segmentation_buffer
+
+from isaaclab.sensors.camera.camera import Camera
+from isaaclab.test.utils import DeviceScope, test_devices
+from isaaclab.utils.warp import ProxyArray
+
+pytestmark = pytest.mark.kitless
+
+DEVICE = next(iter(test_devices(DeviceScope.DEFAULT_CUDA)), "cpu")
+TILES = SimpleNamespace(render_order="tiled", tile_rendering_width=8, tile_rendering_height=8)
+
+
+def stub_camera(
+ monkeypatch,
+ coords: SamplingCoords,
+ outputs: dict[str, tuple[int, torch.dtype]],
+ render: Callable[[FoveatedNewtonCamera, wp.array], None] | None = None,
+ *,
+ highres: SamplingCoords | None = None,
+ pooler: torch.nn.Module | None = None,
+ **cfg,
+) -> FoveatedNewtonCamera:
+ """An initialized Newton camera whose renderer writes ``camera.renderer[name]``, shape (2, H, W, C), for each
+ output (channels, dtype); rgb is a view of rgba when both are requested, as the renderer publishes it.
+
+ ``render(camera, env_mask)`` fills the renderer buffers each update.
+ """
+ monkeypatch.setattr(base_camera, "build_retinal_coords", lambda *args, **kwargs: (coords, highres))
+ monkeypatch.setattr(newton_camera, "build_pooler", lambda *args, **kwargs: (pooler, 4))
+
+ def initialize_renderer(camera):
+ camera.renderer = {}
+ for name, (channels, dtype) in outputs.items():
+ if name == "rgb" and "rgba" in outputs:
+ continue
+ camera.renderer[name] = torch.zeros((2, camera.cfg.height, camera.cfg.width, channels), dtype=dtype)
+ if "rgb" in outputs and "rgba" in outputs:
+ camera.renderer["rgb"] = camera.renderer["rgba"][..., :3]
+ camera._data = SimpleNamespace(
+ output={name: ProxyArray(wp.from_torch(t)) for name, t in camera.renderer.items()}
+ )
+ camera._render_data = SimpleNamespace(camera_rays=None)
+ camera._renderer = SimpleNamespace(cfg=TILES, cleanup=lambda render_data: None)
+
+ monkeypatch.setattr(Camera, "_initialize_impl", initialize_renderer)
+ monkeypatch.setattr(Camera, "_update_buffers_impl", render or (lambda camera, env_mask: None))
+ # The state the constructor sets and the handles the destructor reads.
+ camera = object.__new__(FoveatedNewtonCamera)
+ camera._gaze_angles = camera._gaze_rotation = camera._visibility = camera._grid_publish = None
+ camera._published_shape = camera._segmentation_neighbors = None
+ camera._initialize_handle = camera._invalidate_initialize_handle = camera._prim_deletion_handle = None
+ camera._view = camera._renderer = None
+ camera._device = "cpu"
+ camera.cfg = SimpleNamespace(
+ camera_model=asdict(CameraModel("pinhole", (480, 640), (300.0, 300.0, 319.5, 239.5))),
+ foveated_style=coords.style,
+ mask_to_sensor_fov=False,
+ cmf_a_deg=0.591,
+ pool_enabled=highres is not None,
+ pool_mode="avg",
+ pool_sample_cortex=False,
+ image_rotation_deg=0,
+ update_period=0.0,
+ data_types=list(outputs),
+ renderer_cfg=TILES,
+ )
+ for name, value in cfg.items():
+ setattr(camera.cfg, name, value)
+ camera._initialize_impl()
+ return camera
+
+
+def updated(*rows: bool) -> wp.array:
+ return wp.array(list(rows), dtype=wp.bool, device="cpu")
+
+
+def test_native_grid_render_layout_preserves_rays_and_upright_outputs(monkeypatch) -> None:
+ """A pooled native grid renders its photoreceptor rays in order, and publishes the pooled retina upright."""
+ coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu")
+ highres = coords.clone(resolution=32)
+
+ def render(camera, env_mask):
+ assert camera._data.output["rgba"] is public_rgba
+ rgba = camera.renderer["rgba"]
+ rgba.copy_((torch.arange(rgba.numel()).reshape(rgba.shape) + camera.frame_offset).to(torch.uint8))
+
+ camera = stub_camera(
+ monkeypatch,
+ coords,
+ {"rgba": (4, torch.uint8), "rgb": (3, torch.uint8)},
+ render,
+ highres=highres,
+ pooler=torch.nn.AdaptiveAvgPool1d(len(coords)),
+ )
+ # Newton launches image tiles; a vector-shaped width of one is not valid.
+ assert camera.renderer["rgba"].shape[1:3] == (highres.resolution, highres.resolution)
+ rays = wp.to_torch(camera._render_data.camera_rays)
+ assert rays.shape == (highres.resolution, highres.resolution, 1, 2, 3)
+ torch.testing.assert_close(
+ rays.reshape(-1, 2, 3)[:, 1], native_grid_directions(highres, image_rotation_deg=0).float()
+ )
+ public_rgba = camera._data.output["rgba"]
+ camera.frame_offset = 0
+ camera._update_buffers_impl(updated(True, True))
+ expected = camera.renderer["rgba"].reshape(2, len(highres), 1, 4).clone()
+ expected[:, ~highres.valid_mask] = 0
+ # AdaptiveAvgPool1d maps the 4 * N_lo canonical samples to N_lo by averaging each run of four, which the camera
+ # rounds to the nearest uint8 value.
+ expected = expected.reshape(2, len(coords), 4, 1, 4).float().mean(dim=2).round().to(torch.uint8)
+ expected = coords.as_grid(expected.squeeze(2), sample_dim=1)
+ torch.testing.assert_close(camera._data.output["rgba"].torch, expected, rtol=0, atol=0)
+ # The published buffers are stable across frames, and rgb shares rgba's memory.
+ assert camera._data.output["rgba"] is public_rgba
+ torch.testing.assert_close(camera._data.output["rgb"].torch, expected[..., :3], rtol=0, atol=0)
+ assert camera._data.output["rgb"].warp.ptr == public_rgba.warp.ptr
+
+ # Newton redraws every row, but only the updated environment's publication changes.
+ camera.frame_offset = 1
+ camera._update_buffers_impl(updated(False, True))
+ published = camera._data.output["rgba"].torch
+ torch.testing.assert_close(published[0], expected[0], rtol=0, atol=0)
+ assert not torch.equal(published[1], expected[1])
+
+
+def test_sample_set_publication_and_sensor_mask_follow_the_published_frame(monkeypatch) -> None:
+ """A sample-set camera publishes its own buffers, and its sensor mask reuses one visibility buffer: Newton redraws
+ every row, but an environment that was not updated keeps its published samples and the visibility that masked
+ them."""
+ coords = SamplingCoords(60.0, 0.591, 8, style="isotropic", field_geometry="spherical", device="cpu")
+
+ def render(camera, env_mask):
+ camera.renderer["distance_to_camera"].fill_(camera.frame_value)
+
+ camera = stub_camera(
+ monkeypatch, coords, {"distance_to_camera": (1, torch.float32)}, render, mask_to_sensor_fov=True
+ )
+ camera._view = SimpleNamespace(count=2, close=lambda: None)
+ camera._data.quat_w_ros = ProxyArray(wp.from_torch(torch.tensor([[0.0, 0.0, 0.0, 1.0]] * 2), dtype=wp.quatf))
+ published = camera._data.output["distance_to_camera"]
+ assert published.torch.shape == (2, len(coords), 1, 1)
+ assert published.warp.ptr != camera._flat_render_output["distance_to_camera"].warp.ptr
+
+ # The second camera looks away from the physical camera's image, so it sees nothing.
+ camera.set_gaze_angles(torch.tensor([[0.0, 0.0], [0.0, 180.0]]))
+ camera.frame_value = 1.0
+ camera._update_buffers_impl(updated(True, True))
+ visibility = camera._visibility["valid"].torch
+ seen = camera.sensor_fov_valid_fraction.clone()
+ assert seen[0] > 0.5 and seen[1] == 0
+ sample = published.torch[..., 0, 0]
+ assert bool((sample[0] == visibility[0].float()).all()) and not sample[1].any()
+
+ # Both look ahead now, but only the first camera's frame is published: the second keeps its samples and visibility.
+ camera.set_gaze_angles(torch.zeros(2, 2))
+ camera.frame_value = 2.0
+ camera._update_buffers_impl(updated(True, False))
+ assert camera._data.output["distance_to_camera"] is published
+ assert camera._visibility["valid"].torch is visibility
+ assert not published.torch[1].any()
+ torch.testing.assert_close(camera.sensor_fov_valid_fraction, seen)
+ first = published.torch[0].clone()
+
+ # Now only the second camera's frame is published, and the first keeps its samples.
+ camera.frame_value = 3.0
+ camera._update_buffers_impl(updated(False, True))
+ torch.testing.assert_close(published.torch[0], first)
+ assert bool((published.torch[1][camera._visibility["valid"].torch[1]] == 3.0).all())
+ assert camera.sensor_fov_valid_fraction[1] > 0.5
+
+
+def test_modal_pooling_preserves_ids_above_float_precision(monkeypatch) -> None:
+ """Segmentation keeps each pooled sample's majority label exactly, IDs above float precision included: on the
+ camera's published output, and for wider IDs and multi-channel labels in the pooling itself."""
+ coords = SamplingCoords(60.0, 0.591, 16, style="warped_cartesian_as_grid", field_geometry="spherical", device="cpu")
+ highres = coords.clone(resolution=32)
+ runs = torch.arange(len(coords))
+ # Each pooled sample's neighbours are a run of four rendered samples, nearest first.
+ monkeypatch.setattr(
+ base_camera, "segmentation_neighbor_indices", lambda pooler: torch.stack([4 * runs + j for j in range(4)])
+ )
+ # In each run, three samples share a label above 2**24 and one differs; float32 would merge neighbouring labels.
+ majority = 2**24 + 1 + 2 * runs
+ labels = majority[:, None].repeat(1, 4)
+ labels[:, 2] = 2**30 + runs
+ labels = torch.stack((labels.reshape(-1), (labels + 7).reshape(-1)))
+
+ def render(camera, env_mask):
+ target = camera.renderer["semantic_segmentation"]
+ target.copy_(labels.to(torch.int32).reshape(target.shape))
+
+ camera = stub_camera(
+ monkeypatch,
+ coords,
+ {"rgba": (4, torch.uint8), "semantic_segmentation": (1, torch.int32)},
+ render,
+ highres=highres,
+ pooler=torch.nn.AdaptiveAvgPool1d(len(coords)),
+ )
+ camera._update_buffers_impl(updated(True, True))
+ # The modal label of each run after the footprint mask zeroes samples outside the retina, ties to the nearest.
+ rendered = labels.clone()
+ rendered[:, ~highres.valid_mask] = 0
+ expected = torch.zeros(2, len(coords), dtype=torch.int64)
+ for env in range(2):
+ for sample in range(len(coords)):
+ run = rendered[env, 4 * sample : 4 * sample + 4].tolist()
+ expected[env, sample] = max(run, key=lambda label: (run.count(label), -run.index(label)))
+ published = camera._data.output["semantic_segmentation"].torch
+ assert published.dtype == torch.int32
+ torch.testing.assert_close(published[..., 0].long(), coords.as_grid(expected, sample_dim=1), rtol=0, atol=0)
+ assert camera.image_shape == (16, 16) and camera._data.image_shape == (16, 16)
+
+ # Three outputs over five inputs; 5 marks an excluded neighbour.
+ table = torch.tensor([[0, 3, 5], [1, 4, 5], [2, 5, 5]], device=DEVICE)
+ # 2**24 + 1 and 2**24 + 3 round to other values in float32; int64 IDs must come back exactly.
+ big = 2**40
+ ids = torch.tensor([2**24 + 1, 2**24 + 1, 2**24 + 3, big + 7, big + 7], dtype=torch.int64)
+ pooled = pool_segmentation_buffer(table, torch.stack([ids, ids.flip(0)])[:, :, None, None].to(DEVICE))
+ assert pooled.dtype == torch.int64
+ assert torch.equal(pooled[..., 0, 0].cpu(), torch.tensor([[2**24 + 1, big + 7, 0], [big + 7, 2**24 + 1, 0]]))
+ # Two int64 channels exceed the 8-byte packed key; vectors differing only in the second channel stay distinct.
+ vectors = torch.tensor([[1, 2**40], [1, 2**40 + 1], [1, 2**40 + 1], [5, 6], [7, 8]], dtype=torch.int64)
+ pooled = pool_segmentation_buffer(table, vectors[None, :, None, :].to(DEVICE))
+ assert torch.equal(pooled[0, :, 0].cpu(), torch.tensor([[1, 2**40 + 1], [5, 6], [0, 0]]))
+
+
+def test_explicit_rays_keep_sample_order_and_pad_whole_tiles() -> None:
+ """Newton receives one ray per sample from the optical centre, in sample order, padded to whole tiles."""
+ wp.init()
+ directions = torch.nn.functional.normalize(torch.randn(5, 3, generator=torch.Generator().manual_seed(0)), dim=-1)
+ rays = explicit_rays(directions, 2, 4)
+ assert rays.shape == (2, 4, 1, 2) and rays.dtype == wp.vec3f
+ rays = wp.to_torch(rays).reshape(8, 2, 3)
+ torch.testing.assert_close(rays[:5, 1], directions)
+ torch.testing.assert_close(rays[5:, 1], directions[-1].expand(3, -1))
+ assert not rays[:, 0].any()
+ with pytest.raises(ValueError, match="shape"):
+ explicit_rays(torch.zeros(3, 2), 3, 1)
+ with pytest.raises(ValueError, match="cannot hold"):
+ explicit_rays(torch.zeros(5, 3), 2, 2)
+
+
+def test_pooled_rgb_is_the_view_of_pooled_rgba(monkeypatch) -> None:
+ """The renderer publishes rgb as a view of rgba even when only rgba is requested, and so do pooled sample sets."""
+ coords = SamplingCoords(60.0, 0.591, 16, style="isotropic", field_geometry="spherical", device="cpu")
+
+ def render(camera, env_mask):
+ camera.renderer["rgba"].copy_(torch.tensor([10, 20, 30, 255], dtype=torch.uint8))
+
+ camera = stub_camera(
+ monkeypatch,
+ coords,
+ {"rgba": (4, torch.uint8), "rgb": (3, torch.uint8)},
+ render,
+ highres=coords.clone(resolution=32),
+ pooler=torch.nn.AdaptiveAvgPool1d(len(coords)),
+ data_types=["rgba"],
+ )
+ camera._update_buffers_impl(updated(True, True))
+ rgb, rgba = camera._data.output["rgb"].torch, camera._data.output["rgba"].torch
+ assert rgb.any()
+ torch.testing.assert_close(rgb, rgba[..., :3], rtol=0, atol=0)
+ # rgb is a view of rgba, not a copy: a write to rgba shows through it.
+ assert rgb.data_ptr() == rgba.data_ptr()
+ rgba[..., 0] = 7
+ assert bool((rgb[..., 0] == 7).all())
+
+
+def test_runtime_intrinsics_leave_the_retinas_rays_alone(monkeypatch) -> None:
+ """The retina sets a foveated camera's rays, so runtime intrinsics, such as a viewer's zoom sets, leave the camera
+ as configured with a warning to the caller, rather than reaching the renderer, which would replace the rays with a
+ pinhole's."""
+
+ def replace_rays(*args, **kwargs):
+ raise AssertionError("the stock setter replaces the renderer's rays")
+
+ monkeypatch.setattr(Camera, "set_intrinsic_matrices", replace_rays)
+ camera = object.__new__(FoveatedNewtonCamera)
+ camera._initialize_handle = camera._invalidate_initialize_handle = camera._prim_deletion_handle = None
+ camera._view = camera._renderer = None
+ with pytest.warns(UserWarning, match="leaves a foveated camera as configured") as caught:
+ camera.set_intrinsic_matrices(torch.eye(3).repeat(2, 1, 1))
+ # The warning points at the caller's line.
+ assert caught[0].filename == __file__
diff --git a/source/isaaclab_fovi/test/test_pooling.py b/source/isaaclab_fovi/test/test_pooling.py
new file mode 100644
index 000000000000..c8590e2715cb
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_pooling.py
@@ -0,0 +1,152 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""The camera's pooling of its sensor buffers, segmentation and sensor mask, without a simulator.
+
+fovi's poolers are tested in fovi; these tests cover what the camera builds on them.
+"""
+
+import pytest
+import torch
+from fovi.sensing.projection import CameraModel
+from isaaclab_fovi.sensors import FoveatedCameraCfg, pooling
+from isaaclab_fovi.sensors.pooling import (
+ build_pooler,
+ build_retinal_coords,
+ pool_hwc_buffer,
+ pool_segmentation_buffer,
+ segmentation_neighbor_indices,
+)
+
+from isaaclab.test.utils import DeviceScope, test_devices
+
+pytestmark = pytest.mark.kitless
+
+DEVICE = next(iter(test_devices(DeviceScope.DEFAULT_CUDA)), "cpu")
+"""The modal pooling runs the same tensor operations on every device; the default GPU is what simulations use."""
+
+CAMERA_MODEL = CameraModel("pinhole", (1024, 1024), (512.0, 512.0, 511.5, 511.5))
+
+
+def pooling_cfg(**overrides) -> FoveatedCameraCfg:
+ """A pooled foveated camera configuration for the pooling helpers, with ``overrides`` applied.
+
+ A CMF constant of a tenth of the 90 degree pinhole window, and a small isotropic retina pooled from three
+ visual-field neighbours.
+ """
+ values = dict(
+ prim_path="/World/Camera",
+ cmf_a_deg=9.0,
+ foveated_res=8,
+ foveated_style="isotropic",
+ pool_enabled=True,
+ pool_k=3,
+ pool_sample_cortex=False,
+ )
+ return FoveatedCameraCfg(**{**values, **overrides})
+
+
+def test_camera_pools_its_buffers_by_its_config() -> None:
+ cfg = pooling_cfg(pool_mode="max")
+ lowres, highres = build_retinal_coords(cfg, CAMERA_MODEL, "cpu")
+ # The photoreceptor grid shares the retina's geometry at a higher resolution, and the pooler takes the config.
+ assert len(highres) > len(lowres) and highres.cmf_a == lowres.cmf_a and highres.fov == lowres.fov
+ pooler, neighbors = build_pooler(cfg, lowres, highres, "cpu")
+ assert neighbors == 3 and pooler.mode == "max"
+ # Pooling keeps each environment's channels apart and in order.
+ constants = torch.tensor([[0.25, 0.5, 0.75], [3.0, 6.0, 9.0]])
+ rendered = constants[:, None, None, :].expand(2, len(highres), 1, 3).clone()
+ actual = pool_hwc_buffer(pooler, rendered)
+ assert actual.dtype == rendered.dtype
+ torch.testing.assert_close(actual, constants[:, None, None, :].expand(2, len(lowres), 1, 3))
+ # Without pooling there is no photoreceptor grid.
+ cfg = pooling_cfg(pool_enabled=False)
+ _, highres = build_retinal_coords(cfg, CAMERA_MODEL, "cpu")
+ assert highres is None
+
+
+# Three output samples over five input samples; 5 marks an excluded neighbour. Columns are outputs, rows are
+# neighbour slots nearest first.
+HAND_TABLE = torch.tensor([[0, 3, 5], [1, 4, 5], [2, 5, 5]])
+
+
+def reference_modal_pool(table: torch.Tensor, values: torch.Tensor) -> torch.Tensor:
+ """Brute-force modal pooling of ``(B, N_hi, C)`` values over a ``(k, N_lo)`` neighbour table."""
+ batch, num_inputs, channels = values.shape
+ out = torch.zeros(batch, table.shape[1], channels, dtype=values.dtype)
+ for b in range(batch):
+ for n in range(table.shape[1]):
+ neighbours = [tuple(values[b, i].tolist()) for i in table[:, n].tolist() if i != num_inputs]
+ if neighbours:
+ # max() keeps the first of equally common values, i.e. the earliest neighbour slot.
+ out[b, n] = torch.tensor(max(neighbours, key=neighbours.count), dtype=values.dtype)
+ return out
+
+
+def test_modal_pooling_keeps_the_majority_label_over_the_poolers_neighbourhoods(monkeypatch) -> None:
+ # Output 0 sees [0,0,0,255] twice and [0,0,1,255] once; a per-channel max would give [0,0,1,255].
+ # Output 1 sees one vote each for two colors (its third slot is excluded): the nearest neighbour wins.
+ # Output 2 has no valid neighbour and is zero.
+ colors = torch.tensor(
+ [[0, 0, 0, 255], [0, 0, 0, 255], [0, 0, 1, 255], [10, 20, 30, 255], [200, 100, 0, 255]], dtype=torch.uint8
+ )
+ rendered = colors[None, :, None, :].to(DEVICE)
+ pooled = pool_segmentation_buffer(HAND_TABLE.to(DEVICE), rendered)
+ expected = torch.tensor([[0, 0, 0, 255], [10, 20, 30, 255], [0, 0, 0, 0]], dtype=torch.uint8)
+ assert pooled.dtype == torch.uint8
+ assert torch.equal(pooled.cpu(), expected[None, :, None, :])
+ # Swapping the tied neighbours' order flips the winner.
+ swapped = HAND_TABLE[[1, 0, 2]].to(DEVICE)
+ assert torch.equal(pool_segmentation_buffer(swapped, rendered)[0, 1, 0].cpu(), colors[4])
+
+ # Segmentation pools over the same neighbourhoods as the camera's other outputs: grid windows or KNN.
+ for style, pool_k, sample_cortex in (("warped_cartesian_as_grid", 9, False), ("isotropic", 3, False)):
+ cfg = pooling_cfg(foveated_style=style, pool_k=pool_k, pool_sample_cortex=sample_cortex, pool_mode="max")
+ lowres, highres = build_retinal_coords(cfg, CAMERA_MODEL, "cpu")
+ pooler, k = build_pooler(cfg, lowres, highres, "cpu")
+ table = segmentation_neighbor_indices(pooler)
+ assert table.shape == (k, len(lowres))
+ # The table holds exactly the samples the max pooler reduces over: a max over the table matches it.
+ values = torch.rand(1, len(highres), 1, 1, generator=torch.Generator().manual_seed(0)) + 1
+ padded = torch.cat([values[0, :, 0, 0], torch.zeros(1)])
+ torch.testing.assert_close(padded[table].max(dim=0).values, pool_hwc_buffer(pooler, values)[0, :, 0, 0])
+
+ # Few labels so neighbourhoods hold repeats and ties; tiny chunks exercise the batched loop.
+ monkeypatch.setattr(pooling, "_MODAL_CHUNK_ELEMENTS", 1)
+ labels = torch.randint(0, 3, (3, len(highres), 1, 2), generator=torch.Generator().manual_seed(1)).to(
+ torch.uint8
+ )
+ pooled = pool_segmentation_buffer(table, labels)
+ assert torch.equal(pooled[:, :, 0], reference_modal_pool(table, labels[:, :, 0]))
+
+
+@pytest.mark.parametrize(("style", "pool_k", "mode"), [("warped_cartesian_as_grid", 9, "avg"), ("isotropic", 6, "max")])
+def test_pooling_leaves_out_photoreceptors_the_camera_does_not_see(style: str, pool_k: int, mode: str) -> None:
+ cfg = pooling_cfg(foveated_style=style, pool_mode=mode, pool_k=pool_k)
+ lowres, highres = build_retinal_coords(cfg, CAMERA_MODEL, DEVICE)
+ pooler, _ = build_pooler(cfg, lowres, highres, DEVICE)
+ # The camera's image edge cuts the retina at x = 0.3 in the first environment; the second sees everything.
+ visible = torch.stack([highres.cartesian[:, 0] < 0.3, torch.ones(len(highres), dtype=torch.bool, device=DEVICE)])
+ # The camera zeroes unseen photoreceptors before pooling. A negative value lets those zeros win a plain max.
+ value = -0.7 if mode == "max" else 0.7
+ values = torch.where(visible, value, 0.0)[:, :, None, None]
+ pooled = pool_hwc_buffer(pooler, values, visible)[:, :, 0, 0]
+ unseen = pool_hwc_buffer(pooler, visible.float()[:, :, None, None], visible)[:, :, 0, 0] == 0
+ # Some outputs straddle the edge: plain pooling lets the mask's zeros into them.
+ straddling = (pool_hwc_buffer(pooler, values)[0, :, 0, 0] - value).abs() > 0.01
+ assert (straddling & ~unseen[0] & lowres.valid_mask).any()
+ # Each output pools only what the camera sees: the constant where it sees any photoreceptor, zero where it sees
+ # none or lies outside the retina.
+ expected = torch.where(unseen | ~lowres.valid_mask, 0.0, value)
+ torch.testing.assert_close(pooled, expected)
+ assert unseen[0].any() and not unseen[1, lowres.valid_mask].any()
+
+
+def test_modal_pooling_leaves_out_labels_the_camera_does_not_see() -> None:
+ # Output 0 sees labels [1, 1, 2]; hiding the two 1s leaves 2. Output 1 sees [4, 5]; hiding both leaves nothing.
+ labels = torch.tensor([1, 1, 2, 4, 5], dtype=torch.int32)[None, :, None, None].expand(2, -1, -1, -1)
+ visible = torch.tensor([[False, False, True, False, False], [True, True, True, True, True]])
+ pooled = pool_segmentation_buffer(HAND_TABLE, labels, visible)[..., 0, 0]
+ assert torch.equal(pooled, torch.tensor([[2, 0, 0], [1, 4, 0]], dtype=torch.int32))
diff --git a/source/isaaclab_fovi/test/test_rtx_camera.py b/source/isaaclab_fovi/test/test_rtx_camera.py
new file mode 100644
index 000000000000..1d666a4c3877
--- /dev/null
+++ b/source/isaaclab_fovi/test/test_rtx_camera.py
@@ -0,0 +1,262 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""RTX camera contracts that need no renderer: construction, lens textures and their USD schema, and capture."""
+
+import math
+import struct
+import tempfile
+import zlib
+from pathlib import Path
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+import torch
+import warp as wp
+from fovi.sensing.projection import CameraModel
+from isaaclab_fovi.sensors import foveated_rtx_camera, lens_lut
+from isaaclab_fovi.sensors.foveated_camera_cfg import FoveatedCameraCfg
+from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera
+from isaaclab_fovi.sensors.lens_lut import apply_lens_lut_to_prim, build_lut_textures
+from isaaclab_ov.renderers import OVRTXRendererCfg
+
+from isaaclab.sensors.camera.camera import Camera
+from isaaclab.sim import PinholeCameraCfg
+from isaaclab.utils.warp import ProxyArray
+
+pytestmark = pytest.mark.kitless
+
+
+def test_async_ovrtx_with_the_sensor_mask_is_rejected(monkeypatch) -> None:
+ # The camera never initializes, so its destructor has nothing to release.
+ monkeypatch.setattr(FoveatedRTXCamera, "__del__", lambda self: None, raising=False)
+ renderer = SimpleNamespace(renderer_type="ovrtx", async_rendering=True)
+ with pytest.raises(ValueError, match="async_rendering"):
+ FoveatedRTXCamera(SimpleNamespace(renderer_cfg=renderer, mask_to_sensor_fov=True))
+
+
+def test_near_clip_comes_from_spawn_or_else_the_camera_prim() -> None:
+ pxr = pytest.importorskip("pxr")
+ stage = pxr.Usd.Stage.CreateInMemory()
+ camera = pxr.UsdGeom.Camera.Define(stage, "/Camera")
+ camera.GetClippingRangeAttr().Set(pxr.Gf.Vec2f(0.05, 100.0))
+ prim = camera.GetPrim()
+
+ existing = SimpleNamespace(cfg=SimpleNamespace(spawn=None))
+ assert FoveatedRTXCamera._near_clipping_distance(existing, prim) == pytest.approx(0.05)
+ spawned = SimpleNamespace(cfg=SimpleNamespace(spawn=SimpleNamespace(clipping_range=(0.01, 20.0))))
+ assert FoveatedRTXCamera._near_clipping_distance(spawned, prim) == pytest.approx(0.01)
+
+
+@pytest.mark.parametrize("native_grid", [False, True])
+def test_partial_capture_extracts_only_the_updated_environments(native_grid) -> None:
+ """Environments outside the update mask keep their samples, and each camera's near-plane offset is added once."""
+ height, width = 4, 5
+ texture = torch.arange(3 * height * width, dtype=torch.float32).reshape(3, height, width, 1)
+ if native_grid:
+ texels = [(py, px) for py in range(height) for px in range(width)]
+ else:
+ texels = [(3, 1), (0, 4), (2, 0), (1, 3), (3, 4), (0, 2), (2, 2)]
+ camera = SimpleNamespace(
+ cfg=SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")),
+ # An OVRTX camera with distance_to_camera output adds each camera's near clip.
+ _native_grid=native_grid,
+ _near_clip=torch.tensor([0.25, 0.5, 0.75]).view(-1, 1, 1, 1),
+ # The renderer-bound texture buffers are ProxyArrays, as the parent camera allocates them.
+ _texture_output={"distance_to_camera": ProxyArray(wp.from_torch(texture))},
+ _foveated_output={"distance_to_camera": torch.full((3, len(texels), 1, 1), -1.0)},
+ _extract_py=torch.tensor([py for py, _ in texels]),
+ _extract_px=torch.tensor([px for _, px in texels]),
+ )
+ updated = wp.array([True, False, True], dtype=wp.bool, device="cpu")
+ for _ in range(2):
+ FoveatedRTXCamera._extract_foveated_samples(camera, updated)
+ samples = camera._foveated_output["distance_to_camera"]
+ for env, near_clip in ((0, 0.25), (2, 0.75)):
+ expected = torch.tensor([float(texture[env, py, px, 0]) + near_clip for py, px in texels])
+ torch.testing.assert_close(samples[env, :, 0, 0], expected, atol=0, rtol=0)
+ assert bool((samples[1] == -1.0).all())
+
+
+def test_releasing_the_camera_removes_its_lens_textures(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(Camera, "__del__", lambda self, *args, **kwargs: None)
+ camera = object.__new__(FoveatedRTXCamera)
+ camera._lut_dir = tempfile.TemporaryDirectory(dir=tmp_path)
+ directory = Path(camera._lut_dir.name)
+ (directory / "foveated_ray_enter_direction.exr").write_bytes(b"")
+ camera.__del__()
+ assert not directory.exists() and camera._lut_dir is None
+
+
+def test_construction_authors_the_lens_and_unlocks_cameras_without_changing_the_config(monkeypatch):
+ """Construction authors the lens lookup on every camera prim and unlocks it, since the gaze moves every foveated
+ camera; the caller's configuration, spawn and texture size included, stays as it was."""
+ pxr = pytest.importorskip("pxr")
+ stage = pxr.Usd.Stage.CreateInMemory()
+ prims = [pxr.UsdGeom.Camera.Define(stage, f"/World/envs/env_{i}/Camera").GetPrim() for i in range(2)]
+ for prim in prims:
+ prim.CreateAttribute("omni:kit:cameraLock", pxr.Sdf.ValueTypeNames.Bool).Set(True)
+
+ def construct(self, cfg):
+ self.cfg = cfg
+ self.stage = stage
+ self._device = "cpu"
+ # The stock camera infers the vertical aperture using the allocated texture dimensions.
+ self.cfg.spawn.vertical_aperture = cfg.spawn.horizontal_aperture * cfg.height / cfg.width
+
+ field_of_view = CameraModel.field_of_view
+ sampling_models = []
+
+ def measure_window(model, *args):
+ sampling_models.append(model)
+ return field_of_view(model, *args)
+
+ build_directions = lens_lut.native_grid_directions
+ ray_builds = []
+
+ def measure_directions(*args, **kwargs):
+ rays = build_directions(*args, **kwargs)
+ ray_builds.append(rays)
+ return rays
+
+ texture_paths = ("/textures/enter.exr", "/textures/exit.exr")
+ monkeypatch.setattr(Camera, "__init__", construct)
+ monkeypatch.setattr(CameraModel, "field_of_view", measure_window)
+ # Count at both import locations so evaluating a second ray grid in the camera fails this check.
+ monkeypatch.setattr(lens_lut, "native_grid_directions", measure_directions)
+ monkeypatch.setattr(foveated_rtx_camera, "native_grid_directions", measure_directions, raising=False)
+ monkeypatch.setattr(lens_lut, "save_lut_textures", lambda *args: texture_paths)
+ monkeypatch.setattr(FoveatedRTXCamera, "__del__", lambda self, *args, **kwargs: None)
+ cfg = FoveatedCameraCfg(
+ prim_path="/World/envs/env_.*/Camera",
+ spawn=PinholeCameraCfg(),
+ renderer_cfg=OVRTXRendererCfg(),
+ data_types=["rgb"],
+ foveated_res=16,
+ )
+ assert cfg.spawn.lock_camera
+ camera = FoveatedRTXCamera(cfg)
+ for prim in prims:
+ assert prim.GetAttribute("omni:kit:cameraLock").Get() is False
+ assert prim.GetAttribute("omni:lensdistortion:model").Get() == "lut"
+ assert prim.GetAttribute("omni:lensdistortion:lut:rayEnterDirectionTexture").Get().path == "/textures/enter.exr"
+ assert camera.cfg is not cfg and (camera.cfg.height, camera.cfg.width) == (16, 16)
+ assert len(ray_builds) == 1
+ camera._initialize_sampling()
+ assert len(sampling_models) == 1 and camera.camera_model is sampling_models[0]
+ assert camera.camera_model.image_size == (1024, 1024)
+ assert cfg.spawn.lock_camera and cfg.spawn.vertical_aperture is None and (cfg.height, cfg.width) == (1, 1)
+
+
+def _c_string(data: bytes, at: int) -> tuple[str, int]:
+ """The NUL-terminated string at ``at``, and the offset after it."""
+ end = data.index(b"\0", at)
+ return data[at:end].decode(), end + 1
+
+
+def read_exr(path: Path) -> tuple[dict[str, bytes], dict[str, int], np.ndarray]:
+ """Decode a single-part scanline EXR of FLOAT channels, uncompressed or ZIP, following the OpenEXR file layout.
+
+ Returns the header attributes by name, each channel's pixel type by name in file order, and each channel's
+ ``(H, W)`` image by name.
+ """
+ data = path.read_bytes()
+ assert struct.unpack_from(" None:
+ # Smooth rows compress and noisy rows are stored raw; heights off a multiple of 16 end in a partial chunk.
+ image = torch.randn(shape, generator=torch.Generator().manual_seed(0))
+ image[: shape[0] // 2] = torch.linspace(-1, 1, shape[1])[:, None]
+ lens_lut.save_exr(str(tmp_path / "texture.exr"), image)
+ attributes, types, planes = read_exr(tmp_path / "texture.exr")
+ # The format requires the channel list in alphabetical order, so R, G, B are stored as B, G, R.
+ assert list(types) == sorted("RGB"[: shape[2]]) and set(types.values()) == {2} # FLOAT
+ window = struct.pack(" None:
+ pxr = pytest.importorskip("pxr")
+ stage = pxr.Usd.Stage.CreateInMemory()
+ prim = pxr.UsdGeom.Camera.Define(stage, "/Camera").GetPrim()
+ apply_lens_lut_to_prim(prim, "/tmp/direction.exr", "/tmp/exit.exr")
+ restored = pxr.Usd.Stage.CreateInMemory()
+ restored.GetRootLayer().ImportFromString(stage.GetRootLayer().ExportToString())
+ prim = restored.GetPrimAtPath("/Camera")
+ assert "OmniLensDistortionLutAPI" in prim.GetMetadata("apiSchemas").GetAppliedItems()
+ assert prim.GetAttribute("omni:lensdistortion:model").Get() == "lut"
+ assert prim.GetAttribute("omni:lensdistortion:lut:rayEnterDirectionTexture").Get().path == "/tmp/direction.exr"
+ assert prim.GetAttribute("omni:lensdistortion:lut:rayExitPositionTexture").Get().path == "/tmp/exit.exr"
+ for name in (
+ "cameraProjectionType",
+ "generalizedProjectionDirectionTexturePath",
+ "generalizedProjectionNDCTexturePath",
+ ):
+ assert not prim.HasProperty(name), name
+
+
+def test_sample_set_lens_textures_place_samples_and_mark_rays_outside_the_field() -> None:
+ # A sample set with one sample per texel, in shuffled order, puts each sample's ray at its own texel.
+ size = 4
+ axis = (torch.arange(size) + 0.5) / size
+ row, col = torch.meshgrid(axis, axis, indexing="ij")
+ centres = torch.stack((col, row), -1).reshape(-1, 2)
+ order = torch.randperm(size * size, generator=torch.Generator().manual_seed(0))
+ directions = torch.nn.functional.normalize(torch.randn(size * size, 3, generator=torch.Generator().manual_seed(1)))
+ direction_texture, _ = build_lut_textures(centres[order], directions, size, size, 16, 16, device="cpu")
+ texels = (centres[order] * size).long()
+ torch.testing.assert_close(direction_texture[texels[:, 1], texels[:, 0]], directions)
+
+ # The inverse lookup sends each in-field ray to its nearest sample, and every other ray to the invalid UV, never
+ # to the fovea. Three samples: the optical axis (OpenGL -z) and two rays 10 degrees off it.
+ angle = math.radians(10.0)
+ directions = torch.tensor(
+ [[0.0, 0.0, -1.0], [math.sin(angle), 0.0, -math.cos(angle)], [0.0, math.sin(angle), -math.cos(angle)]]
+ )
+ uv = torch.tensor([[0.5, 0.5], [0.9, 0.5], [0.5, 0.9]])
+ _, exit_texture = build_lut_textures(uv, directions, 8, 8, 32, 32, device="cpu")
+ texels = exit_texture.reshape(-1, exit_texture.shape[-1])[:, :2]
+ invalid = (texels == -1.0).all(dim=-1)
+ # Rays outside the 10 degree field outnumber those inside it on the hemisphere's octahedral grid.
+ assert invalid.float().mean() > 0.5 and (~invalid).any()
+ assert all(any(torch.equal(texel, sample) for sample in uv) for texel in texels[~invalid])
+ # The octahedral centre is the optical axis, which reaches the axis sample.
+ torch.testing.assert_close(exit_texture[exit_texture.shape[0] // 2, exit_texture.shape[1] // 2, :2], uv[0])
diff --git a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst
new file mode 100644
index 000000000000..94b3efa5d3dc
--- /dev/null
+++ b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.added.rst
@@ -0,0 +1,3 @@
+* Added the ``IsaacContrib-Cartpole-Camera-Fovi`` task in :mod:`isaaclab_tasks.contrib.active_gaze`: the Cartpole
+ camera task with a foveated camera whose gaze the policy moves, trained with gaze-supervised PPO and a fixed gaze
+ action noise. It is registered when the ``fovi`` extra is installed.
diff --git a/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor b/source/isaaclab_tasks/changelog.d/active-gaze-cartpole.minor
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/source/isaaclab_tasks/changelog.d/fovi-cartpole-observations.skip b/source/isaaclab_tasks/changelog.d/fovi-cartpole-observations.skip
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py
new file mode 100644
index 000000000000..9d0c06d83e82
--- /dev/null
+++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/__init__.py
@@ -0,0 +1,29 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Active vision with a foveated camera: the policy moves the camera's gaze.
+
+The camera is :class:`isaaclab_fovi.sensors.FoveatedCamera`, from the optional ``fovi`` extra
+(``uv sync --extra fovi``). The task is registered only when that extra is installed.
+"""
+
+from importlib.util import find_spec
+
+import gymnasium as gym
+
+ISAACLAB_FOVI_AVAILABLE = find_spec("isaaclab_fovi") is not None and find_spec("fovi") is not None
+"""Whether the ``fovi`` extra is installed: the foveated camera package and the fovi library it builds on."""
+
+if ISAACLAB_FOVI_AVAILABLE:
+ gym.register(
+ id="IsaacContrib-Cartpole-Camera-Fovi",
+ entry_point="isaaclab.envs:ManagerBasedRLEnv",
+ disable_env_checker=True,
+ kwargs={
+ "env_cfg_entry_point": f"{__name__}.cartpole_camera_fovi_env_cfg:CartpoleCameraFoviEnvCfg",
+ "rsl_rl_cfg_entry_point": f"{__name__}.agents:CartpoleCameraFoviPPORunnerCfg",
+ "default_agent": "rsl_rl",
+ },
+ )
diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py
new file mode 100644
index 000000000000..2fbd3d34b9e2
--- /dev/null
+++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/active_gaze_cfg.py
@@ -0,0 +1,37 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Observation groups for active-gaze camera tasks."""
+
+from __future__ import annotations
+
+from dataclasses import MISSING
+
+from isaaclab_fovi import mdp
+
+from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg
+from isaaclab.utils import configclass
+
+
+@configclass
+class GazeObservationsCfg(ObservationGroupCfg):
+ """The gaze, in field radii, and its velocity, in field radii per second."""
+
+ state = ObservationTermCfg(func=mdp.gaze_state)
+
+ def __post_init__(self):
+ self.enable_corruption = False
+ self.concatenate_terms = True
+
+
+@configclass
+class OracleObservationsCfg(ObservationGroupCfg):
+ """The teacher's gaze labels. Training labels, never a policy input."""
+
+ labels: ObservationTermCfg = MISSING
+
+ def __post_init__(self):
+ self.enable_corruption = False
+ self.concatenate_terms = True
diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py
new file mode 100644
index 000000000000..8e87239597b8
--- /dev/null
+++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/agents.py
@@ -0,0 +1,34 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""RSL-RL agents of the active-gaze tasks: the stock PPO with gaze supervision and a fixed gaze noise."""
+
+from isaaclab.utils import configclass
+
+from isaaclab_tasks.core.cartpole.agents.rsl_rl_ppo_cfg import CartpoleCameraPPORunnerCfg
+
+from .gaze_distribution_cfg import GazeGaussianDistributionCfg
+from .gaze_supervised_ppo_cfg import GazeSupervisedPPOCfg
+
+_STOCK_RUNNER = CartpoleCameraPPORunnerCfg()
+_STOCK_DISTRIBUTION = _STOCK_RUNNER.actor.distribution_cfg
+
+
+@configclass
+class CartpoleCameraFoviPPORunnerCfg(CartpoleCameraPPORunnerCfg):
+ """The stock Cartpole camera PPO with gaze supervision; the actor and critic also see the gaze."""
+
+ experiment_name = "cartpole_camera_fovi"
+ obs_groups = {"actor": ["policy", "gaze"], "critic": ["critic", "gaze"]}
+ actor = _STOCK_RUNNER.actor.replace(
+ distribution_cfg=GazeGaussianDistributionCfg(
+ init_std=_STOCK_DISTRIBUTION.init_std,
+ std_type=_STOCK_DISTRIBUTION.std_type,
+ std_range=_STOCK_DISTRIBUTION.std_range,
+ )
+ )
+ algorithm = GazeSupervisedPPOCfg(
+ **{name: value for name, value in vars(_STOCK_RUNNER.algorithm).items() if name != "class_name"}
+ )
diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py
new file mode 100644
index 000000000000..323686a067df
--- /dev/null
+++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/cartpole_camera_fovi_env_cfg.py
@@ -0,0 +1,88 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Cartpole with a foveated camera, in RGB or depth.
+
+The stock camera task with the camera foveated and two gaze actions. The teacher looks at the pole's tip. The retina
+is :data:`RETINA_RES` samples across, enough for a task that only needs to see a bar. The policy gets two gaze actions,
+whose noise is fixed, and the teacher's gaze labels supervise them during training.
+"""
+
+from isaaclab_fovi import mdp
+from isaaclab_fovi.sensors import FoveatedCameraCfg
+
+from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, SceneEntityCfg
+from isaaclab.utils import configclass
+
+from isaaclab_tasks.core.cartpole.cartpole_common import CartpoleTiledCameraCfg
+from isaaclab_tasks.core.cartpole.cartpole_manager_camera_env_cfg import (
+ CartpoleCameraEnvCfg,
+ CartpoleCameraSceneCfg,
+ image_observations_cfg,
+)
+from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import ActionsCfg as CartpoleActionsCfg
+from isaaclab_tasks.utils import PresetCfg, preset
+
+from .active_gaze_cfg import GazeObservationsCfg, OracleObservationsCfg
+
+POLE_TIP = (0.0, 0.0, 1.0)
+"""The pole's tip in the pole's frame [m]."""
+
+RETINA_RES = 32
+"""Retina samples across; the stock camera is 96 pixels across."""
+
+_STOCK_CAMERA = CartpoleTiledCameraCfg().rgb
+_RGB_OBSERVATIONS = image_observations_cfg("rgb")
+_RGB_CAMERA = FoveatedCameraCfg(
+ prim_path=_STOCK_CAMERA.prim_path,
+ offset=_STOCK_CAMERA.offset,
+ spawn=_STOCK_CAMERA.spawn,
+ renderer_cfg=_STOCK_CAMERA.renderer_cfg,
+ data_types=["rgb"],
+ foveated_res=RETINA_RES,
+ mask_to_sensor_fov=True,
+)
+
+
+@configclass
+class ObservationsCfg:
+ policy: ObservationGroupCfg = _RGB_OBSERVATIONS.policy
+ critic: ObservationGroupCfg = _RGB_OBSERVATIONS.critic
+ gaze: ObservationGroupCfg = GazeObservationsCfg()
+ oracle: ObservationGroupCfg = OracleObservationsCfg(
+ labels=ObservationTermCfg(
+ func=mdp.gaze_teacher_labels,
+ params={"target_cfg": SceneEntityCfg("robot", body_names="pole"), "offset": POLE_TIP},
+ )
+ )
+
+
+@configclass
+class SceneCfg(CartpoleCameraSceneCfg):
+ tiled_camera = preset(
+ default=_RGB_CAMERA,
+ depth=_RGB_CAMERA.replace(data_types=["depth"]),
+ rgb=_RGB_CAMERA,
+ )
+
+
+@configclass
+class ActionsCfg(CartpoleActionsCfg):
+ # The gaze must be the last action term.
+ gaze = mdp.GazeActionCfg(asset_name="tiled_camera")
+
+
+@configclass
+class CartpoleCameraFoviEnvCfg(PresetCfg):
+ """Cartpole with a foveated camera; ``presets=depth`` selects depth images."""
+
+ @configclass
+ class BaseCfg(CartpoleCameraEnvCfg.BaseCartpoleCameraEnvCfg):
+ scene: SceneCfg = SceneCfg(num_envs=512, env_spacing=20.0)
+ actions: ActionsCfg = ActionsCfg()
+
+ rgb = BaseCfg(observations=ObservationsCfg())
+ depth = BaseCfg(observations=ObservationsCfg(policy=image_observations_cfg("depth").policy))
+ default = rgb
diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py
new file mode 100644
index 000000000000..9829707c282f
--- /dev/null
+++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution.py
@@ -0,0 +1,61 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Gaussian action head whose gaze actions have a fixed standard deviation."""
+
+from __future__ import annotations
+
+import math
+
+import torch
+from rsl_rl.modules.distribution import GaussianDistribution
+from torch.distributions import Normal
+
+GAZE_ACTIONS = 2
+"""The gaze actions (tilt, pan) are the policy's last two actions."""
+
+
+class GazeGaussianDistribution(GaussianDistribution):
+ """Gaussian action head with a learned standard deviation for every action but the gaze, the last two, whose
+ standard deviation is fixed at ``gaze_std``.
+
+ The gaze step clamps each gaze action to [-1, 1], so beyond that range a wider gaze distribution changes neither
+ the reward nor PPO's surrogate, and the entropy bonus grows a learned standard deviation without bound; the sampled
+ gaze then random-walks however well its mean follows the teacher.
+
+ Args:
+ output_dim: Number of actions, the two gaze actions included.
+ init_std: Initial standard deviation of the other actions.
+ std_range: (min, max) clamp of the other actions' standard deviation.
+ std_type: Parameterization of the other actions' standard deviation: ``"scalar"`` or ``"log"``.
+ learn_std: Whether the other actions' standard deviation is learned.
+ gaze_std: Fixed standard deviation of the gaze actions.
+ """
+
+ def __init__(
+ self,
+ output_dim: int,
+ init_std: float = 1.0,
+ std_range: tuple[float, float] = (1e-6, 1e6),
+ std_type: str = "scalar",
+ learn_std: bool = True,
+ gaze_std: float = 0.1,
+ ) -> None:
+ if output_dim <= GAZE_ACTIONS:
+ raise ValueError(f"The gaze head needs actions besides the {GAZE_ACTIONS} gaze actions, got {output_dim}.")
+ if not (math.isfinite(gaze_std) and gaze_std > 0):
+ raise ValueError(f"gaze_std must be positive and finite, got {gaze_std!r}.")
+ # The learned parameter covers the other actions only.
+ super().__init__(output_dim - GAZE_ACTIONS, init_std, std_range, std_type, learn_std)
+ self.output_dim = output_dim
+ self.register_buffer("gaze_std", torch.full((GAZE_ACTIONS,), float(gaze_std)))
+
+ def update(self, mlp_output: torch.Tensor) -> None:
+ """Update the distribution from the MLP output: learned noise for the other actions, fixed for the gaze."""
+ if self.std_type == "scalar":
+ std = self.std_param.clamp(self.std_range[0], self.std_range[1])
+ else:
+ std = self.log_std_param.clamp(self.log_std_range[0], self.log_std_range[1]).exp()
+ self._distribution = Normal(mlp_output, torch.cat((std, self.gaze_std)))
diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py
new file mode 100644
index 000000000000..fac45da54582
--- /dev/null
+++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_distribution_cfg.py
@@ -0,0 +1,24 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Configuration of :class:`~isaaclab_tasks.contrib.active_gaze.gaze_distribution.GazeGaussianDistribution`."""
+
+from __future__ import annotations
+
+from isaaclab.utils import configclass
+
+from isaaclab_rl.rsl_rl import RslRlMLPModelCfg
+
+
+@configclass
+class GazeGaussianDistributionCfg(RslRlMLPModelCfg.GaussianDistributionCfg):
+ """Gaussian action head whose gaze actions, the last two, have a fixed standard deviation.
+
+ ``init_std``, ``std_type`` and ``std_range`` apply to the other actions.
+ """
+
+ class_name: str = "isaaclab_tasks.contrib.active_gaze.gaze_distribution:GazeGaussianDistribution"
+ gaze_std: float = 0.1
+ """Fixed standard deviation of the gaze actions. One action moves the gaze by the gaze action's ``step_size``."""
diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py
new file mode 100644
index 000000000000..d7633f9e6c18
--- /dev/null
+++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo.py
@@ -0,0 +1,139 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""PPO with gaze supervision by a teacher, for RSL-RL.
+
+The update follows :meth:`rsl_rl.algorithms.PPO.update` (BSD-3-Clause) for feedforward models without RND or
+symmetry, and adds the teacher's gaze loss to the PPO loss.
+"""
+
+from __future__ import annotations
+
+import math
+
+import torch
+from rsl_rl.algorithms import PPO
+from torch import nn
+
+from .gaze_distribution import GAZE_ACTIONS
+
+
+def gaze_loss(mean: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
+ """Mean distance between the policy's gaze-action means and the teacher's, over valid labels.
+
+ Args:
+ mean: The policy's gaze-action means, shape (batch, 2).
+ labels: The teacher's gaze actions and their validity, shape (batch, 3).
+ """
+ valid = labels[:, 2] > 0.5
+ # Invalid rows may hold NaN; replacing it keeps their (discarded) residuals finite, so no NaN reaches the gradients.
+ residual = torch.where(valid[:, None], mean - torch.nan_to_num(labels[:, :2]), 0.0)
+ return residual.norm(dim=-1).sum() / valid.sum().clamp_min(1)
+
+
+class GazeSupervisedPPO(PPO):
+ """PPO whose loss also pulls the policy's gaze toward a teacher's.
+
+ The gaze is the last two actions. The teacher's labels are the observation group ``oracle_group``, as
+ :class:`isaaclab_fovi.mdp.gaze_teacher_labels` computes them; they never enter the actor or the critic. Only the
+ means of the gaze actions are supervised; pair it with
+ :class:`~isaaclab_tasks.contrib.active_gaze.gaze_distribution.GazeGaussianDistribution`, which fixes their noise.
+
+ Args:
+ oracle_loss_coef: Weight of the gaze loss. Zero trains plain PPO.
+ oracle_group: Observation group of the teacher's labels.
+ """
+
+ def __init__(
+ self,
+ actor,
+ critic,
+ storage,
+ *,
+ oracle_loss_coef: float = 1.0,
+ oracle_group: str = "oracle",
+ **kwargs,
+ ):
+ if actor.is_recurrent or critic.is_recurrent or kwargs.get("rnd_cfg") or kwargs.get("symmetry_cfg"):
+ raise ValueError("GazeSupervisedPPO supports feedforward models without RND or symmetry.")
+ if not math.isfinite(oracle_loss_coef) or oracle_loss_coef < 0:
+ raise ValueError("oracle_loss_coef must be finite and nonnegative.")
+ super().__init__(actor, critic, storage, **kwargs)
+ self.oracle_loss_coef = oracle_loss_coef
+ self.oracle_group = oracle_group
+
+ def update(self) -> tuple[dict[str, float], dict[str, float]]:
+ totals = torch.zeros(5, device=self.device)
+ generator = self.storage.mini_batch_generator(self.num_mini_batches, self.num_learning_epochs)
+ for batch in generator:
+ if self.normalize_advantage_per_mini_batch and batch.advantages.numel() > 1:
+ with torch.no_grad():
+ batch.advantages = (batch.advantages - batch.advantages.mean()) / (batch.advantages.std() + 1e-8)
+ with torch.amp.autocast(
+ device_type=torch.device(self.device).type, enabled=self.use_mixed_precision, dtype=torch.bfloat16
+ ):
+ self.actor(batch.observations, stochastic_output=True)
+ log_prob = self.actor.get_output_log_prob(batch.actions)
+ values = self.critic(batch.observations)
+ entropy_loss = -self.actor.output_entropy.mean()
+ if self.desired_kl is not None and self.schedule == "adaptive":
+ self._adapt_learning_rate(batch.old_distribution_params, self.actor.output_distribution_params)
+ ratio = torch.exp(log_prob - batch.old_actions_log_prob.squeeze(-1))
+ advantages = batch.advantages.squeeze(-1)
+ surrogate = torch.max(
+ -advantages * ratio, -advantages * ratio.clamp(1.0 - self.clip_param, 1.0 + self.clip_param)
+ ).mean()
+ value_error = (values - batch.returns).pow(2)
+ if self.use_clipped_value_loss:
+ clipped = batch.values + (values - batch.values).clamp(-self.clip_param, self.clip_param)
+ value_error = torch.max(value_error, (clipped - batch.returns).pow(2))
+ value_loss = value_error.mean()
+ loss = surrogate + self.value_loss_coef * value_loss + self.entropy_coef * entropy_loss
+ if self.oracle_loss_coef > 0:
+ labels = batch.observations[self.oracle_group].float()
+ oracle = gaze_loss(self.actor.output_mean[:, -GAZE_ACTIONS:].float(), labels)
+ valid = (labels[:, 2] > 0.5).float().mean()
+ loss = loss + self.oracle_loss_coef * oracle
+ else:
+ # Plain PPO: the teacher's labels are neither needed nor read.
+ oracle = valid = torch.zeros((), device=self.device)
+ self.optimizer.zero_grad()
+ loss.backward()
+ if self.is_multi_gpu:
+ self.reduce_parameters()
+ nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm)
+ nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm)
+ self.optimizer.step()
+ totals += torch.stack((value_loss, surrogate, entropy_loss, oracle, valid)).detach().float()
+ obs = self.storage.observations.flatten(0, 1)
+ self.actor.update_normalization(obs)
+ self.critic.update_normalization(obs)
+ self.storage.clear()
+ num_updates = self.num_learning_epochs * self.num_mini_batches
+ value, surrogate, entropy, oracle, oracle_valid = (totals / num_updates).tolist()
+ return {"value": value, "surrogate": surrogate, "entropy": entropy, "oracle": oracle}, {
+ "Optimizer/learning_rate": self.learning_rate,
+ "Model/mean_policy_std": self.actor.output_std.mean().item(),
+ "Loss/oracle_valid": oracle_valid,
+ }
+
+ def _adapt_learning_rate(self, old_params, new_params):
+ """Adapt the learning rate to the policy's KL divergence, as PPO's adaptive schedule does."""
+ with torch.inference_mode():
+ kl = self.actor.get_kl_divergence(old_params, new_params).mean()
+ if self.is_multi_gpu:
+ torch.distributed.all_reduce(kl, op=torch.distributed.ReduceOp.SUM)
+ kl /= self.gpu_world_size
+ if self.gpu_global_rank == 0:
+ if kl > self.desired_kl * 2.0:
+ self.learning_rate = max(1e-5, self.learning_rate / 1.5)
+ elif 0.0 < kl < self.desired_kl / 2.0:
+ self.learning_rate = min(1e-2, self.learning_rate * 1.5)
+ if self.is_multi_gpu:
+ rate = torch.tensor(self.learning_rate, device=self.device)
+ torch.distributed.broadcast(rate, src=0)
+ self.learning_rate = rate.item()
+ for group in self.optimizer.param_groups:
+ group["lr"] = self.learning_rate
diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py
new file mode 100644
index 000000000000..907dc6773afb
--- /dev/null
+++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/active_gaze/gaze_supervised_ppo_cfg.py
@@ -0,0 +1,26 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Configuration of :class:`~isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo.GazeSupervisedPPO`."""
+
+from __future__ import annotations
+
+from isaaclab.utils import configclass
+
+from isaaclab_rl.rsl_rl import RslRlPpoAlgorithmCfg
+
+
+@configclass
+class GazeSupervisedPPOCfg(RslRlPpoAlgorithmCfg):
+ """PPO whose loss also pulls the policy's gaze toward a teacher's.
+
+ See :class:`~isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo.GazeSupervisedPPO`.
+ """
+
+ class_name: str = "isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo:GazeSupervisedPPO"
+ oracle_loss_coef: float = 1.0
+ """Weight of the gaze loss. Zero trains plain PPO."""
+ oracle_group: str = "oracle"
+ """Observation group of the teacher's labels."""
diff --git a/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py b/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py
new file mode 100644
index 000000000000..9d66d185e75e
--- /dev/null
+++ b/source/isaaclab_tasks/test/contrib/test_active_gaze_ppo.py
@@ -0,0 +1,128 @@
+# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
+# All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Gaze-supervised PPO and the fixed-noise gaze head of the active-gaze tasks, without a simulator."""
+
+import pytest
+import torch
+from rsl_rl.algorithms import PPO
+from rsl_rl.models import MLPModel
+from rsl_rl.storage import RolloutStorage
+from tensordict import TensorDict
+
+from isaaclab_tasks.contrib.active_gaze.gaze_distribution import GazeGaussianDistribution
+from isaaclab_tasks.contrib.active_gaze.gaze_distribution_cfg import GazeGaussianDistributionCfg
+from isaaclab_tasks.contrib.active_gaze.gaze_supervised_ppo import GazeSupervisedPPO, gaze_loss
+
+pytestmark = pytest.mark.kitless
+
+NUM_ENVS = 64
+STEPS = 8
+
+
+def test_gaze_loss_ignores_invalid_labels():
+ mean = torch.tensor([[0.0, 0.0], [1.0, 1.0]], requires_grad=True)
+ labels = torch.tensor([[0.3, 0.4, 1.0], [float("nan"), float("nan"), 0.0]])
+ loss = gaze_loss(mean, labels)
+ loss.backward()
+ assert float(loss.detach()) == pytest.approx(0.5)
+ assert torch.isfinite(mean.grad).all() and not mean.grad[1].any()
+
+
+def _algorithm(
+ oracle_loss_coef: float = 1.0, with_labels: bool = True, stock: bool = False, gaze_head: bool = False
+) -> tuple[PPO | GazeSupervisedPPO, TensorDict]:
+ torch.manual_seed(0)
+ labels = torch.rand(NUM_ENVS, 3) * 2 - 1
+ labels[:, 2] = (torch.arange(NUM_ENVS) % 4 != 0).float()
+ labels[labels[:, 2] == 0, :2] = float("nan")
+ groups = {"policy": torch.randn(NUM_ENVS, 6)} | ({"oracle": labels} if with_labels else {})
+ obs = TensorDict(groups, batch_size=[NUM_ENVS])
+ model_groups = {"actor": ["policy"], "critic": ["policy"]}
+ distribution = {"class_name": "GaussianDistribution", "init_std": 1.0}
+ if gaze_head:
+ head = GazeGaussianDistributionCfg(init_std=1.0, gaze_std=0.1)
+ distribution = {"class_name": head.class_name, "init_std": 1.0, "gaze_std": head.gaze_std}
+ actor = MLPModel(obs, model_groups, "actor", 3, hidden_dims=[32], distribution_cfg=distribution)
+ critic = MLPModel(obs, model_groups, "critic", 1, hidden_dims=[32])
+ storage = RolloutStorage("rl", NUM_ENVS, STEPS, obs, [3], "cpu")
+ settings = dict(num_learning_epochs=4, num_mini_batches=4, learning_rate=3e-3, schedule="fixed", device="cpu")
+ if stock:
+ return PPO(actor, critic, storage, **settings), obs
+ return GazeSupervisedPPO(actor, critic, storage, oracle_loss_coef=oracle_loss_coef, **settings), obs
+
+
+def _train(algorithm: PPO, obs: TensorDict, iterations: int) -> tuple[dict[str, float], dict[str, float]]:
+ for _ in range(iterations):
+ for _ in range(STEPS):
+ with torch.inference_mode():
+ algorithm.act(obs)
+ algorithm.process_env_step(obs, torch.zeros(NUM_ENVS), torch.zeros(NUM_ENVS), {})
+ algorithm.compute_returns(obs)
+ result = algorithm.update()
+ return result
+
+
+def test_update_pulls_the_gaze_toward_the_teacher():
+ algorithm, obs = _algorithm()
+ valid = obs["oracle"][:, 2] > 0.5
+
+ def distance() -> float:
+ with torch.no_grad():
+ mean = algorithm.actor(obs)[:, -2:]
+ return float((mean - obs["oracle"][:, :2])[valid].norm(dim=-1).mean())
+
+ before = distance()
+ _, stats = _train(algorithm, obs, 40)
+ assert stats["Loss/oracle_valid"] == pytest.approx(0.75)
+ assert all(torch.isfinite(p).all() for p in algorithm.actor.parameters())
+ assert distance() < 0.7 * before
+
+
+def test_zero_coefficient_update_matches_stock_ppo_without_labels():
+ def updated(stock: bool) -> tuple[list[torch.Tensor], list[torch.Tensor], dict[str, float], dict[str, float]]:
+ algorithm, obs = _algorithm(oracle_loss_coef=0.0, with_labels=False, stock=stock)
+ modules = (algorithm.actor, algorithm.critic)
+ initial = [p.detach().clone() for module in modules for p in module.parameters()]
+ torch.manual_seed(1)
+ losses, stats = _train(algorithm, obs, 1)
+ return initial, [p.detach().clone() for module in modules for p in module.parameters()], losses, stats
+
+ initial, gaze_params, losses, stats = updated(stock=False)
+ stock_initial, stock_params, stock_losses, stock_stats = updated(stock=True)
+ assert losses == pytest.approx(stock_losses | {"oracle": 0.0}, rel=1e-6, abs=1e-7)
+ assert stats == pytest.approx(stock_stats | {"Loss/oracle_valid": 0.0})
+ for start, stock_start in zip(initial, stock_initial, strict=True):
+ torch.testing.assert_close(start, stock_start, atol=0, rtol=0)
+ for param, stock_param in zip(gaze_params, stock_params, strict=True):
+ torch.testing.assert_close(param, stock_param, atol=0, rtol=0)
+ assert all(not torch.equal(param, start) for param, start in zip(gaze_params, initial, strict=True))
+
+
+def test_gaze_head_keeps_the_gaze_noise_fixed_while_ppo_learns_the_rest():
+ """The entropy bonus and the surrogate move the other actions' noise, never the gaze's."""
+ algorithm, obs = _algorithm(gaze_head=True)
+ algorithm.entropy_coef = 0.5
+ head = algorithm.actor.distribution
+ assert isinstance(head, GazeGaussianDistribution)
+ assert head.std_param.shape == (1,)
+ _train(algorithm, obs, iterations=3)
+ with torch.no_grad():
+ head.update(torch.zeros(1, 3))
+ std = head.std[0]
+ torch.testing.assert_close(std[1:], torch.full((2,), 0.1))
+ assert abs(float(std[0]) - 1.0) > 1e-3
+ # The gaze noise is part of the saved policy, so a checkpoint restores it.
+ assert torch.equal(head.state_dict()["gaze_std"], torch.full((2,), 0.1))
+
+
+def test_gaze_head_fixes_the_last_two_actions_noise_and_rejects_invalid_settings():
+ head = GazeGaussianDistribution(5, init_std=2.0, std_type="log", gaze_std=0.05)
+ assert head.input_dim == 5
+ head.update(torch.zeros(3, 5))
+ torch.testing.assert_close(head.std, torch.tensor([[2.0, 2.0, 2.0, 0.05, 0.05]]).expand(3, -1))
+ for output_dim, gaze_std in ((5, 0.0), (5, float("inf")), (2, 0.1)):
+ with pytest.raises(ValueError, match="gaze"):
+ GazeGaussianDistribution(output_dim, gaze_std=gaze_std)
diff --git a/uv.lock b/uv.lock
index 15161ac8e229..8d0ff67198f5 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 3
+revision = 5
requires-python = "==3.12.*"
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
@@ -891,6 +891,7 @@ dependencies = [
wheels = [
{ url = "https://files.pythonhosted.org/packages/d3/8c/5fe3f6719c2d4560c79c62ef6d9b7d6c34d145879ddc0c1a41f8153ad0a6/cupy_cuda12x-14.2.0-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:b74340aa7271f0f081f77e2e5107bac75af19b86df29213db7ada90e14428efe", size = 147490427, upload-time = "2026-08-20T02:40:00.196Z" },
{ url = "https://files.pythonhosted.org/packages/7c/5b/65124de2dbaf2e85109f611a41947e39acd6dd938751c04b4c4d7bf6fc82/cupy_cuda12x-14.2.0-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:f82141761f2c81905d49387464ae29438887956d99063381c93a1d5d1b7d32e8", size = 136111459, upload-time = "2026-08-20T02:40:04.909Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/18/ddea819204701024bef7fa748730702245d803847c841b737723b94fd091/cupy_cuda12x-14.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:c9571d3b5f2e65758137e210f7fb3c3b34767f0af6b6ca04035a244b6141ee12", size = 98780018, upload-time = "2026-08-20T02:40:09.465Z" },
]
[[package]]
@@ -1286,6 +1287,28 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c7/4e/ce75a57ff3aebf6fc1f4e9d508b8e5810618a33d900ad6c19eb30b290b97/fonttools-4.61.1-py3-none-any.whl", hash = "sha256:17d2bf5d541add43822bcf0c43d7d847b160c9bb01d15d5007d84e2217aaa371", size = 1148996, upload-time = "2025-12-12T17:31:21.03Z" },
]
+[[package]]
+name = "fovi"
+version = "2.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cupy-cuda12x" },
+ { name = "einops" },
+ { name = "ipython" },
+ { name = "numpy" },
+ { name = "pillow" },
+ { name = "scipy" },
+ { name = "torch" },
+ { name = "torchvision" },
+ { name = "tqdm" },
+ { name = "trimesh" },
+ { name = "warp-lang" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b8/0f/787082f650d1ae57a420b868edb4e25953eadc569793003fe5257848b674/fovi-2.7.0.tar.gz", hash = "sha256:506faffe547f31db4a4e4ea24b124d918ad8fc7fc2cdcab6822f6f960b75b74a", size = 67610838, upload-time = "2026-11-23T22:02:14.2Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/02/e8/70ec00f724b8df673c5b50eb3e9f3de729f09aa4fb5e71caa1cd642fcd50/fovi-2.7.0-py3-none-any.whl", hash = "sha256:46ec4c489af8925bdcf2dc4017847f1cfa34b6eb0ad5378771ba105a451278ec", size = 330543, upload-time = "2026-11-23T22:02:10.796Z" },
+]
+
[[package]]
name = "frozenlist"
version = "1.5.0"
@@ -1795,16 +1818,16 @@ source = { editable = "source/isaaclab_assets" }
dependencies = [
{ name = "isaaclab" },
{ name = "isaaclab-contrib" },
- { name = "isaaclab-newton" },
{ name = "isaaclab-isaacsim" },
+ { name = "isaaclab-newton" },
]
[package.metadata]
requires-dist = [
{ name = "isaaclab", editable = "source/isaaclab" },
{ name = "isaaclab-contrib", editable = "source/isaaclab_contrib" },
- { name = "isaaclab-newton", editable = "source/isaaclab_newton" },
{ name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" },
+ { name = "isaaclab-newton", editable = "source/isaaclab_newton" },
]
[[package]]
@@ -1840,9 +1863,9 @@ dependencies = [
{ name = "isaaclab-assets" },
{ name = "isaaclab-contrib" },
{ name = "isaaclab-experimental" },
+ { name = "isaaclab-isaacsim" },
{ name = "isaaclab-newton" },
{ name = "isaaclab-ov" },
- { name = "isaaclab-isaacsim" },
{ name = "isaaclab-ppisp" },
{ name = "isaaclab-rl" },
{ name = "isaaclab-tasks" },
@@ -1926,6 +1949,10 @@ dev = [
{ name = "sphinxcontrib-bibtex" },
{ name = "sphinxemoji" },
]
+fovi = [
+ { name = "fovi" },
+ { name = "isaaclab-fovi" },
+]
importers = [
{ name = "isaacsim-asset-isolated" },
{ name = "tinyobjloader" },
@@ -2049,7 +2076,7 @@ requires-dist = [
{ name = "botocore" },
{ name = "coacd", specifier = ">=1.0.7" },
{ name = "coverage", marker = "extra == 'test'", specifier = ">=7.6.1" },
- { name = "daqp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')", specifier = "==0.8.5" },
+ { name = "daqp", marker = "(platform_machine == 'aarch64' or platform_machine == 'x86_64') and sys_platform == 'linux'", specifier = "==0.8.5" },
{ name = "decord2", marker = "extra == 'rlinf'" },
{ name = "dex-retargeting", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'teleop'", specifier = "==0.5.0" },
{ name = "diffusers", marker = "extra == 'rlinf'", specifier = ">=0.35.0" },
@@ -2058,6 +2085,7 @@ requires-dist = [
{ name = "fast-simplification", specifier = ">=0.1.11" },
{ name = "filelock" },
{ name = "flaky", marker = "extra == 'test'" },
+ { name = "fovi", marker = "extra == 'fovi'", specifier = ">=2.7" },
{ name = "gitpython", specifier = ">=3.1.60" },
{ name = "gym", marker = "extra == 'rl-games'" },
{ name = "gymnasium", specifier = ">=1.2.0" },
@@ -2075,11 +2103,12 @@ requires-dist = [
{ name = "isaaclab-dev", extras = ["sb3", "skrl", "rl-games", "rsl-rl", "viser", "rerun", "ov"], marker = "extra == 'all'" },
{ name = "isaaclab-dev", extras = ["test"], marker = "extra == 'dev'" },
{ name = "isaaclab-experimental", editable = "source/isaaclab_experimental" },
+ { name = "isaaclab-fovi", marker = "extra == 'fovi'", editable = "source/isaaclab_fovi" },
+ { name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" },
{ name = "isaaclab-mimic", marker = "extra == 'mimic'", editable = "source/isaaclab_mimic" },
{ name = "isaaclab-mimic", marker = "extra == 'teleop'", editable = "source/isaaclab_mimic" },
{ name = "isaaclab-newton", editable = "source/isaaclab_newton" },
{ name = "isaaclab-ov", editable = "source/isaaclab_ov" },
- { name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" },
{ name = "isaaclab-ppisp", editable = "source/isaaclab_ppisp" },
{ name = "isaaclab-rl", editable = "source/isaaclab_rl" },
{ name = "isaaclab-tasks", editable = "source/isaaclab_tasks" },
@@ -2105,7 +2134,7 @@ requires-dist = [
{ name = "numpy", specifier = ">=2" },
{ name = "numpydantic", marker = "extra == 'rlinf'", specifier = ">=1.7.0" },
{ name = "onnx", specifier = ">=1.18.0" },
- { name = "open3d", marker = "(python_full_version < '3.13' and platform_machine != 'aarch64') or (python_full_version < '3.13' and sys_platform != 'linux')", specifier = ">=0.19.0" },
+ { name = "open3d", marker = "python_full_version < '3.13' and (platform_machine != 'aarch64' or sys_platform != 'linux')", specifier = ">=0.19.0" },
{ name = "ovphysx", marker = "extra == 'ov'", specifier = "==0.8.0.43443703471", index = "https://pypi.org/simple" },
{ name = "ovphysx", marker = "extra == 'ovphysx'", specifier = "==0.8.0.43443703471", index = "https://pypi.org/simple" },
{ name = "ovrtx", marker = "extra == 'ov'", specifier = "==0.7.0.1794596436", index = "https://pypi.org/simple" },
@@ -2120,8 +2149,8 @@ requires-dist = [
{ name = "physx-usd-schemas", marker = "extra == 'ov'", specifier = "==25.11.2.72696984", index = "https://pypi.org/simple" },
{ name = "physx-usd-schemas", marker = "extra == 'ovphysx'", specifier = "==25.11.2.72696984", index = "https://pypi.org/simple" },
{ name = "pillow", specifier = ">=12.3.0" },
- { name = "pin", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
- { name = "pin-pink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')", specifier = "==3.3.0" },
+ { name = "pin", marker = "(platform_machine == 'aarch64' or platform_machine == 'x86_64') and sys_platform == 'linux'" },
+ { name = "pin-pink", marker = "(platform_machine == 'aarch64' or platform_machine == 'x86_64') and sys_platform == 'linux'", specifier = "==3.3.0" },
{ name = "prettytable", specifier = ">=3.3.0" },
{ name = "protobuf", specifier = ">=4.25.8,!=5.26.0" },
{ name = "psutil" },
@@ -2178,7 +2207,7 @@ requires-dist = [
{ name = "wandb", marker = "extra == 'wandb'", specifier = ">=0.13.11" },
{ name = "warp-lang", specifier = "==1.17.0" },
]
-provides-extras = ["tetrahedralization", "video", "optix", "importers", "test", "dev", "sb3", "skrl", "skrl-jax", "rl-games", "wandb", "rsl-rl", "torchrl", "viser", "rerun", "isaacsim", "ov", "ovphysx", "ovrtx", "mimic", "teleop", "ovxr", "rlinf", "leapp", "all"]
+provides-extras = ["tetrahedralization", "video", "optix", "importers", "test", "dev", "sb3", "skrl", "skrl-jax", "rl-games", "wandb", "rsl-rl", "torchrl", "viser", "rerun", "isaacsim", "ov", "ovphysx", "ovrtx", "mimic", "teleop", "ovxr", "rlinf", "leapp", "fovi", "all"]
[[package]]
name = "isaaclab-experimental"
@@ -2195,6 +2224,28 @@ requires-dist = [
{ name = "isaaclab-newton", editable = "source/isaaclab_newton" },
]
+[[package]]
+name = "isaaclab-fovi"
+version = "0.1.0"
+source = { editable = "source/isaaclab_fovi" }
+dependencies = [
+ { name = "isaaclab" },
+]
+
+[package.metadata]
+requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }]
+
+[[package]]
+name = "isaaclab-isaacsim"
+version = "13.2.0"
+source = { editable = "source/isaaclab_isaacsim" }
+dependencies = [
+ { name = "isaaclab" },
+]
+
+[package.metadata]
+requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }]
+
[[package]]
name = "isaaclab-mimic"
version = "2.1.7"
@@ -2238,17 +2289,6 @@ requires-dist = [
{ name = "ovstage", specifier = "==0.4.0.1794520352" },
]
-[[package]]
-name = "isaaclab-isaacsim"
-version = "13.2.0"
-source = { editable = "source/isaaclab_isaacsim" }
-dependencies = [
- { name = "isaaclab" },
-]
-
-[package.metadata]
-requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }]
-
[[package]]
name = "isaaclab-ppisp"
version = "0.3.2"
@@ -3868,6 +3908,7 @@ dependencies = [
{ name = "configargparse" },
{ name = "dash" },
{ name = "flask" },
+ { name = "ipywidgets" },
{ name = "matplotlib" },
{ name = "nbformat" },
{ name = "numpy" },