upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorAlmogaver295 <133548141+guimsolutions@users.noreply.github.com>2026-11-23 23:53:36 +0100
committerAlmogaver295 <133548141+guimsolutions@users.noreply.github.com>2026-11-23 23:53:36 +0100
commit33f4a5aedeb48e27b004efe5d6ae306130d55cdd (patch)
tree08361685151a2a6a4ecf9156955fabb35b4b570c /docs
parent57cb669f52ba6ca4bb58bf2e09492ffbe2b8ee60 (diff)
parent5d74c272363f2703265d44e6aaab1a1df8ddfaf3 (diff)
Merge upstream main and preserve 1D UAV clear compatibilityold-pr/9948
Diffstat (limited to 'docs')
-rw-r--r--docs/README.md31
-rw-r--r--docs/animation.md280
-rw-r--r--docs/audio.md42
-rw-r--r--docs/audio_config.md170
-rw-r--r--docs/audio_hal_exe_calls.md79
-rw-r--r--docs/awc_shorts.md3
-rw-r--r--docs/boot.md54
-rw-r--r--docs/buffer_formats.md177
-rw-r--r--docs/bvh.md722
-rw-r--r--docs/character_models.md266
-rw-r--r--docs/character_skeleton.md69
-rw-r--r--docs/d3d12_command_objects.md71
-rw-r--r--docs/d3d12_vulkan.md876
-rw-r--r--docs/d3d12_xs_surface.md109
-rw-r--r--docs/design.md232
-rw-r--r--docs/dev-tools.md93
-rw-r--r--docs/embedded_shaders.md220
-rw-r--r--docs/first_light.md88
-rw-r--r--docs/fspx.md102
-rw-r--r--docs/fssm_crosscheck.md43
-rw-r--r--docs/gamedata.md558
-rw-r--r--docs/gamedata_graph.md3
-rw-r--r--docs/gameinput.md37
-rw-r--r--docs/gbuffer.md52
-rw-r--r--docs/gpu_test_results.md33
-rw-r--r--docs/i18n/README.md16
-rw-r--r--docs/i18n/ar/quickstart.md6
-rw-r--r--docs/i18n/de/quickstart.md73
-rw-r--r--docs/i18n/es/quickstart.md119
-rw-r--r--docs/i18n/fr/quickstart.md71
-rw-r--r--docs/i18n/it/quickstart.md4
-rw-r--r--docs/i18n/ja/quickstart.md4
-rw-r--r--docs/i18n/pl-PL/quickstart.md132
-rw-r--r--docs/i18n/pt-BR/quickstart.md25
-rw-r--r--docs/i18n/ru/quickstart.md57
-rw-r--r--docs/i18n/tr/quickstart.md16
-rw-r--r--docs/i18n/zh-CN/quickstart.md54
-rw-r--r--docs/isa_coverage.md72
-rw-r--r--docs/material_pass_replay.md2
-rw-r--r--docs/mission_logic.md4
-rw-r--r--docs/modding.md6
-rw-r--r--docs/models.md198
-rw-r--r--docs/movies.md152
-rw-r--r--docs/navmesh.md301
-rw-r--r--docs/page_directory.md35
-rw-r--r--docs/ped_catalogues.md172
-rw-r--r--docs/pipeline_check.md143
-rw-r--r--docs/progress_dashboard.md6
-rw-r--r--docs/psin.md117
-rw-r--r--docs/pso_cache.md242
-rw-r--r--docs/rbf0.md7
-rw-r--r--docs/related_projects.md51
-rw-r--r--docs/restofworld.md26
-rw-r--r--docs/retail_boot_chain.md102
-rw-r--r--docs/rpf.md26
-rw-r--r--docs/rsc8_audio.md62
-rw-r--r--docs/runtime_imports.md324
-rw-r--r--docs/saves.md34
-rw-r--r--docs/shader_inputs.md74
-rw-r--r--docs/shader_library.md172
-rw-r--r--docs/shader_validation.md538
-rw-r--r--docs/story.md74
-rw-r--r--docs/strand_grooms.md320
-rw-r--r--docs/testing.md294
-rw-r--r--docs/text.md4
-rw-r--r--docs/textures.md57
-rw-r--r--docs/textures_arrays.md33
-rw-r--r--docs/weather.md137
-rw-r--r--docs/world.md82
-rw-r--r--docs/world_lights_paths.md4
-rw-r--r--docs/world_names.md2
-rw-r--r--docs/xbox_d3d12_xs.md895
-rw-r--r--docs/xcl_compare.md75
-rw-r--r--docs/xdxr.md13
-rw-r--r--docs/xmem_exe_calls.md111
75 files changed, 8936 insertions, 1018 deletions
diff --git a/docs/README.md b/docs/README.md
index a5bd39f35..a78f03359 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -12,15 +12,19 @@ method, scope and caveats. No game data is included.
12| [related_projects.md](related_projects.md) | Prior art we may read and the licence boundaries on it. | 12| [related_projects.md](related_projects.md) | Prior art we may read and the licence boundaries on it. |
13| [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. | 13| [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. |
14| [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, running without a GPU on Mesa llvmpipe, and known problems. | 14| [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, running without a GPU on Mesa llvmpipe, and known problems. |
15| [modding.md](modding.md) | The mod format: `mods/<folder>/mod.json`, checked and loaded in name order by `gta6rt`; a swap takes effect once the game's archetype lookup is hooked (needs the executable, RT-5). A mod names game models and holds no game data. |
15| [progress_dashboard.md](progress_dashboard.md) | A local page of what works, what changed since it last passed and what blocks next: unit and runtime tests, the translator contract by confirmation method, measured imports, corpus counts and, with `--github`, CI and the D3D- items (`tools/progress_dashboard.py`). | 16| [progress_dashboard.md](progress_dashboard.md) | A local page of what works, what changed since it last passed and what blocks next: unit and runtime tests, the translator contract by confirmation method, measured imports, corpus counts and, with `--github`, CI and the D3D- items (`tools/progress_dashboard.py`). |
16 17
17## Archives and assets 18## Archives and assets
18 19
19| Document | Measured content | 20| Document | Measured content |
20|---|---| 21|---|---|
21| [models.md](models.md) | 382,781 models (0 decode failures) at the `e293917` pin, including 159,511 drawable-dictionary children; the other archives measure 4,686 fragments, 30,343 bone-bound and 126,301,454 triangles, while the `levels.rpf` geometry cells are not independently reproduced (**†**); the re-count table is in models.md. | 22| [models.md](models.md) | 382,781 models (0 decode failures) at the `e293917` pin, including 159,511 drawable-dictionary children; 55,417 fragments, 89,887 bone-bound and 2,636,248,990 triangles over all ten archives (`levels.rpf` from a full export); the re-count table is in models.md. |
23| [strand_grooms.md](strand_grooms.md) | GPU strand grooms (`smh`): hair, beards, brows and fur are groom LOD resources consumed by the `smh_*` compute passes, not triangle drawables (each is a one-triangle stub); the measured resource layout, the Class 0 strand scattering RNG and barycentric strand interpolation, decoded by `tools/smh_groom.py`. |
22| [character_models.md](character_models.md) | `packs.rpf` character parts at `e293917`: 26,585 rows / 11,335 unique names, 2,865 fragments (all a flat 25-vertex / 32-triangle 5x5 bounds grid at z=0), Lucia's 22 named records and the decoded 13-part export, the `player_story000_00` drawable set, slot-name token counts, texture coverage (184/215), and what is not decoded (fragment children, ped variation, hair, bind pose). | 24| [character_models.md](character_models.md) | `packs.rpf` character parts at `e293917`: 26,585 rows / 11,335 unique names, 2,865 fragments (all a flat 25-vertex / 32-triangle 5x5 bounds grid at z=0), Lucia's 22 named records and the decoded 13-part export, the `player_story000_00` drawable set, slot-name token counts, texture coverage (184/215), and what is not decoded (fragment children, ped variation, hair, bind pose). |
23| [character_skeleton.md](character_skeleton.md) | Character `.#ft` fragments: the 597-name shared skeleton table (596 `joaat32` hashes), the 597-record instance tree with 580 measured parents, the model-side bone-hash mapping, and the measured vertex joint-index/skin-weight layouts (`tools/skin_streams.py`); the default bone transforms compose to the stored inverse bind matrices, and `tools/anim_glb.py` exports a skinned part with clips as an animated GLB. | 25| [character_skeleton.md](character_skeleton.md) | Character `.#ft` fragments: the 597-name shared skeleton table (596 `joaat32` hashes), the 597-record instance tree with 580 measured parents, the model-side bone-hash mapping, and the measured vertex joint-index/skin-weight layouts (`tools/skin_streams.py`); the default bone transforms compose to the stored inverse bind matrices, and `tools/anim_glb.py` exports a skinned part with clips as an animated GLB. |
26| [ped_catalogues.md](ped_catalogues.md) | Ped and wardrobe appearance catalogues (`0x8dcb4cf5`) in both framings: 2,716 catalogues and 632,778 presets (612,950 in resource-packed `0DRP`, 19,828 in one standalone `PSIN`), 345,780 presets with a parent (chain depth 3, 0 cycles), 896,115 `0x37e52277` states resolved, 0 parse errors (`tools/ped_catalogues.py`). |
27| [strand_grooms.md](strand_grooms.md) | GPU strand grooms (`smh`): 5,751 assets / 20,046 LOD resources, 0 decode errors, 902,456,856 GPU buffer bytes and 112,491,621 strands; the `smh_gen_1` Class 0 RNG, the barycentric interpolation and split-chain rejoin, and a GLB export (`tools/smh_groom.py`). |
24| [resource_names.md](resource_names.md) | RPF9 named-resource index: bounded-inflate lookup for `name.#dr`/`#ft`/`#dd` without the TOC. | 28| [resource_names.md](resource_names.md) | RPF9 named-resource index: bounded-inflate lookup for `name.#dr`/`#ft`/`#dd` without the TOC. |
25| [sgd5_render_states.md](sgd5_render_states.md) | The three effect-local render-state indices in an SGD5 pass, checked across all 28,798 passes. | 29| [sgd5_render_states.md](sgd5_render_states.md) | The three effect-local render-state indices in an SGD5 pass, checked across all 28,798 passes. |
26| [textures.md](textures.md) | 357,115 TTPF descriptors across 57 pools: `rpf9dump` (`e293917`) decodes 354,991 strict-clean (99.41%) directly including BCPack BC1/BC3/BC4/BC5; `tools/bcpack.py` decodes all six BCPack modes (BC1–BC7). | 30| [textures.md](textures.md) | 357,115 TTPF descriptors across 57 pools: `rpf9dump` (`e293917`) decodes 354,991 strict-clean (99.41%) directly including BCPack BC1/BC3/BC4/BC5; `tools/bcpack.py` decodes all six BCPack modes (BC1–BC7). |
@@ -31,16 +35,19 @@ method, scope and caveats. No game data is included.
31| [rbf0.md](rbf0.md) | 1,263 RBF0 resources, 475,461 elements; UI/Scaleform definitions, not a sectioned container; strict JSON/CSV/XML tree decoder. | 35| [rbf0.md](rbf0.md) | 1,263 RBF0 resources, 475,461 elements; UI/Scaleform definitions, not a sectioned container; strict JSON/CSV/XML tree decoder. |
32| [gamedata.md](gamedata.md) | `common.rpf`: 954 streams, 266 XML documents / 118 roots; 0 RBF0/PSIN; a streaming reader (`gamedata_reader.py`) converts 259 documents by root and `type`. | 36| [gamedata.md](gamedata.md) | `common.rpf`: 954 streams, 266 XML documents / 118 roots; 0 RBF0/PSIN; a streaming reader (`gamedata_reader.py`) converts 259 documents by root and `type`. |
33| [gamedata_graph.md](gamedata_graph.md) | `common.rpf` mount graph: 25 manifest documents, 30 content-set ids, 14 include refs (12 resolve), 3,386 target refs, 0 cycles. | 37| [gamedata_graph.md](gamedata_graph.md) | `common.rpf` mount graph: 25 manifest documents, 30 content-set ids, 14 include refs (12 resolve), 3,386 target refs, 0 cycles. |
38| [weather.md](weather.md) | The weather document measured: 168 types (151 tagged / 17 untagged, a family split), exact-case `Mod*` vocabulary mismatches, axis-to-field Spearman (niceness tracks its field, `Rain` is a 7-of-25 data-set split), `TimeMult` and the inert `Honor*` values. |
34| [world.md](world.md) | `levels.rpf` placement: 9,918 map files / 680,228 entities measured in 55% of the archive (lower bound; estimate 16k-39.6k / 1.03M-2.64M); `0x7a` resource layout. Building a placed world from entity rows (`world_build.py --placements`): shared geometry per chunk (`EXT_mesh_gpu_instancing`), bounded memory for the whole archive, and per-tier LOD chunk sets with distance bands (`--lod-sets`). | 39| [world.md](world.md) | `levels.rpf` placement: 9,918 map files / 680,228 entities measured in 55% of the archive (lower bound; estimate 16k-39.6k / 1.03M-2.64M); `0x7a` resource layout. Building a placed world from entity rows (`world_build.py --placements`): shared geometry per chunk (`EXT_mesh_gpu_instancing`), bounded memory for the whole archive, and per-tier LOD chunk sets with distance bands (`--lod-sets`). |
35| [world_census.md](world_census.md) | Full `levels.rpf` pass: 23,535 maps / 1,670,442 entities, 98.32% stream coverage, sharded and exact; the SixNG 30,785-map difference reconciled map by map (interiors and entity groups). | 40| [world_census.md](world_census.md) | Full `levels.rpf` pass: 23,535 maps / 1,670,442 entities, 98.32% stream coverage, sharded and exact; the SixNG 30,785-map difference reconciled map by map (interiors and entity groups). |
36| [world_names.md](world_names.md) | Name resolution: `archetypeName` and map `name`/`parent` are lower-cased joaat; 64-bit keys are MurmurHash3 x64 low 64. With `rpf9_names.py` names, 99.85% of the 1,670,435 entities a whole-archive `world_index` run reads resolve (64-bit verified); 5/23,535 map names, all five confirmed by the map 64-bit key. | 41| [world_names.md](world_names.md) | Name resolution: `archetypeName` and map `name`/`parent` are lower-cased joaat; 64-bit keys are MurmurHash3 x64 low 64. With `rpf9_names.py` names, 99.85% of the 1,670,435 entities a whole-archive `world_index` run reads resolve (64-bit verified); 5/23,535 map names, all five confirmed by the map 64-bit key. |
37| [world_lights_paths.md](world_lights_paths.md) | Map lights (`CExtensionDefLightEffect`/`CLightAttrDef`, 280,105 lights, placed through map entities) and the vehicle lane graph (63,808 nodes, 145,518 links, 1,546 junctions, 369 signalised); identical to SixNG on the lane graph, lights reconciled resource by resource. | 42| [world_lights_paths.md](world_lights_paths.md) | Map lights (`CExtensionDefLightEffect`/`CLightAttrDef`, 280,105 lights, placed through map entities) and the vehicle lane graph (63,808 nodes, 145,518 links, 1,546 junctions, 369 signalised); identical to SixNG on the lane graph, lights reconciled resource by resource. |
38| [page_directory.md](page_directory.md) | RPF9 `0DRP`: 0x60-byte header, `q38` 16-byte records; 15,768 pages / 60,880 records in `data.rpf`; targets and sizes, names still TOC-only. | 43| [page_directory.md](page_directory.md) | RPF9 `0DRP`: 0x60-byte header, `q38` 16-byte records; 15,768 pages / 60,880 records in `data.rpf`; targets and sizes, names still TOC-only. |
39| [text.md](text.md) | 30,349 localized string tables (hash table, index, UTF-8 blob in `0DRP` resources) and the dialogue table: 138,104 lines joined to their subtitles in every language; language guessed per table. | 44| [text.md](text.md) | 30,511 localized string tables (hash table, index, UTF-8 blob in `0DRP` resources) and the dialogue table: 138,104 lines joined to their subtitles in every language; language guessed per table. |
40| [psin.md](psin.md) | PSIN metadata container: header, section walk, `LSCH`/`LENM` schema, and the instance data (block table, pointers, arrays, maps) read through it on 17,507 containers, 99.986% of block bytes reached; hash-typed members resolved to resource names. | 45| [psin.md](psin.md) | PSIN metadata container: header, section walk, `LSCH`/`LENM` schema, and the instance data (block table, pointers, arrays, maps) read through it on 17,507 containers, 99.986% of block bytes reached; hash-typed members resolved to resource names. |
46| [ped_catalogues.md](ped_catalogues.md) | Ped and wardrobe appearance catalogues: one schema rooted at struct `0x8dcb4cf5`, in `0DRP` v122 resources in `packs.rpf` and in the standalone `PSIN` player/wardrobe catalogue; both framings' 1-based block table and 64-bit pointer encoding (`block = ptr & 0xfffff`, `offset = ptr >> 20`). |
41| [story.md](story.md) | `story000.rpf` 18.65 GiB mixed: 264 Bink 2 streams / 3.33 GB, 225,281 `RSC8` headers, 442 nested RPF9; `story000_script` PSIN, `shared_minigame` mixed content. | 47| [story.md](story.md) | `story000.rpf` 18.65 GiB mixed: 264 Bink 2 streams / 3.33 GB, 225,281 `RSC8` headers, 442 nested RPF9; `story000_script` PSIN, `shared_minigame` mixed content. |
42| [restofworld.md](restofworld.md) | Six rest-of-world/script archives, 1.57 GB total: `core_restofworld` 1.21 GB (11 Bink 2, 37 models, 958 graphics pages), `story000_script` PSIN, small `appdata0`/licences. | 48| [restofworld.md](restofworld.md) | Six rest-of-world/script archives, 1.57 GB total: `core_restofworld` 1.21 GB (11 Bink 2, 37 models, 958 graphics pages), `story000_script` PSIN, small `appdata0`/licences. |
43| [movies.md](movies.md) | Bink 2 streams and audio tracks; decode through the real loader and `Bink2Scarlett.dll`; stream names from the mount lists. | 49| [movies.md](movies.md) | Bink 2 streams and audio tracks; decode through the real loader and `Bink2Scarlett.dll`; stream names from the mount lists. |
50| [pso_cache.md](pso_cache.md) | The PSO/shader cache: 0x80 header, 25,471 graphics and 2,693 compute records, two 8-byte index tables, meta chunk types 0x41/0x42/0x43 and 26,092 `s_endpgm`; `tools/psocache_extract.py` carves it, `tools/psocache_inspect.py --meta` decodes the chunks and `tools/psocache_usersig.py` maps the graphics user data to root parameters. |
44 51
45## Audio 52## Audio
46 53
@@ -49,7 +56,7 @@ method, scope and caveats. No game data is included.
49| [audio.md](audio.md) | AWC banks: Opus, PCM and XMA2; lossless Ogg Opus repack and WAV paths; stream names from dictionary hits with a salted control; names and subtitles written into the Ogg Opus tags. | 56| [audio.md](audio.md) | AWC banks: Opus, PCM and XMA2; lossless Ogg Opus repack and WAV paths; stream names from dictionary hits with a salted control; names and subtitles written into the Ogg Opus tags. |
50| [rsc8_audio.md](rsc8_audio.md) | 641,428 `RSC8` v8001 resources across 4 archives: 100% AWC tag `0x5c` facial/lip-sync `crClipDictionary` paired with 48 kHz mono Opus dialogue, 0 hidden audio containers; the undocumented `0x5a`/`0xd9` companion tags (1,185 `audio.rpf` streams) decoded structurally. | 57| [rsc8_audio.md](rsc8_audio.md) | 641,428 `RSC8` v8001 resources across 4 archives: 100% AWC tag `0x5c` facial/lip-sync `crClipDictionary` paired with 48 kHz mono Opus dialogue, 0 hidden audio containers; the undocumented `0x5a`/`0xd9` companion tags (1,185 `audio.rpf` streams) decoded structurally. |
51| [awc_shorts.md](awc_shorts.md) | Export short streamed-music idents/stings by duration; stereo-aware, no re-encode. | 58| [awc_shorts.md](awc_shorts.md) | Export short streamed-music idents/stings by duration; stereo-aware, no re-encode. |
52| [audio_config.md](audio_config.md) | The music/radio record table: 1,589 records, exact durations, AWC stream ids; no start offsets. | 59| [audio_config.md](audio_config.md) | The music/radio record table: 1,589 records, exact durations, AWC stream ids; no start offsets. AWC tag `0xBD`: 16-byte marker events on 938 of the 3,008 streamed-music banks, track markers in five long mixes. |
53| [radio_stations.md](radio_stations.md) | Audio-config station blocks: 19 records, boundary u32, content-id lists; VCRR 80/80 mapping; no start offsets. | 60| [radio_stations.md](radio_stations.md) | Audio-config station blocks: 19 records, boundary u32, content-id lists; VCRR 80/80 mapping; no start offsets. |
54 61
55## Runtime, GPU and validation 62## Runtime, GPU and validation
@@ -58,26 +65,34 @@ method, scope and caveats. No game data is included.
58|---|---| 65|---|---|
59| [d3d12_vulkan.md](d3d12_vulkan.md) | Xbox D3D12 to Vulkan plan and status; device proxy, queues, command lists, barriers, copies. | 66| [d3d12_vulkan.md](d3d12_vulkan.md) | Xbox D3D12 to Vulkan plan and status; device proxy, queues, command lists, barriers, copies. |
60| [boot.md](boot.md) | The first real boot: the `gta6rt --trace`/`--trace-d3d12` runbook, the startup + D3D12 trace summary (`tools/boot_trace.py`), the triage order and the Q1–Q22 checklist. | 67| [boot.md](boot.md) | The first real boot: the `gta6rt --trace`/`--trace-d3d12` runbook, the startup + D3D12 trace summary (`tools/boot_trace.py`), the triage order and the Q1–Q22 checklist. |
68| [retail_boot_chain.md](retail_boot_chain.md) | How far `gta6rt --run` gets with the retail executable: the stops in order and what clears each, the physical-page export shapes, and device slots 26, 48 and 73. |
69| [modding.md](modding.md) | The mod format: a `mods/<folder>/mod.json` next to `gta6rt.exe` or under `--mods DIR`, swapping a named (or `joaat`) archetype for another; load order, the start-up log, and the fact that a swap waits for the executable's archetype lookup address (RT-5). |
61| [descriptor_lookup_apple.md](descriptor_lookup_apple.md) | M3 Max GPU timings for texture and sampler descriptor lookups at 1k, 10k and 100k live entries. | 70| [descriptor_lookup_apple.md](descriptor_lookup_apple.md) | M3 Max GPU timings for texture and sampler descriptor lookups at 1k, 10k and 100k live entries. |
62| [descriptor_lookup_ada.md](descriptor_lookup_ada.md) | RTX 4070 SUPER (Ada, Windows) timings for the same lookups in VRAM, host-visible and ReBAR memory. | 71| [descriptor_lookup_ada.md](descriptor_lookup_ada.md) | RTX 4070 SUPER (Ada, Windows) timings for the same lookups in VRAM, host-visible and ReBAR memory. |
63| [descriptor_lookup_intel.md](descriptor_lookup_intel.md) | Intel UHD Graphics 770 (Xe-LP, Windows, driver 101.6129) timings for the same lookups at 1k–100k live entries; both memory placements within 0.6% of each other. | 72| [descriptor_lookup_intel.md](descriptor_lookup_intel.md) | Intel UHD Graphics 770 (Xe-LP, Windows, driver 101.6129) timings for the same lookups at 1k–100k live entries; both memory placements within 0.6% of each other. |
64| [d3d12_xs_surface.md](d3d12_xs_surface.md) | The 116-slot `d3d12_xs.dll` export surface; 83/83 standard GUIDs match the PC SDK. | 73| [d3d12_xs_surface.md](d3d12_xs_surface.md) | The 116-slot `d3d12_xs.dll` export surface; 83/83 standard GUIDs match the PC SDK. |
65| [xdxr.md](xdxr.md) | `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) from `XboxBvhBuilder.dll`'s reads; stream records' offsets and defaults; offline statistics not in the package. | 74| [xdxr.md](xdxr.md) | `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) from `XboxBvhBuilder.dll`'s reads; stream records' offsets and defaults; offline statistics not in the package. |
66| [d3d12_command_objects.md](d3d12_command_objects.md) | Measured command queue/list/fence/`PresentX` surface; verified vs prior art vs open. | 75| [d3d12_command_objects.md](d3d12_command_objects.md) | Measured command queue/list/fence/`PresentX` surface; verified vs prior art vs open. |
76| [xbox_d3d12_xs.md](xbox_d3d12_xs.md) | The `d3d12_xs` graphics ABI quoted from Microsoft's public GDK reference: root signatures, state objects, DXIL libraries, hit groups, shader cache sessions; which pages are missing or NDA-gated. |
67| [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. | 77| [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. |
68| [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | 78| [xmem_exe_calls.md](xmem_exe_calls.md) | How the retail executable calls `xmem.dll`: call sites and constant arguments per import (`tools/import_call_sites.py`), the 23 `XMemVirtualAlloc` calls that all pass an attribute word, and the inferred shape of the physical-page family. |
79| [audio_hal_exe_calls.md](audio_hal_exe_calls.md) | How the retail executable calls the 22 audio coprocessor, texture layout and DirectStorage imports that have no shim: call sites, constant arguments, and the four calls with a negative-result branch. |
80| [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. |
81| [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. |
69| [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | 82| [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). |
70| [pipeline_check.md](pipeline_check.md) | Driver-level corpus check: 10/12 shards, 22,092 modules, 2,217 compute pipelines, 0 failures. | 83| [pipeline_check.md](pipeline_check.md) | Driver-level corpus check: the full corpus, 26,503 of 26,503 modules and pipelines, 0 failures (RTX 4060 Ti); an earlier 10/12-shard run, 22,092 modules and 2,217 compute pipelines, also had 0 failures. Driver-level corpus check: 10/12 shards, 22,092 modules, 2,217 compute pipelines, 0 failures. |
71| [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. | 84| [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. |
72| [shader_validation.md](shader_validation.md) | Differential CPU/GPU validation design and the current CPU interpreter prototype. | 85| [shader_validation.md](shader_validation.md) | Differential CPU/GPU validation design and the current CPU interpreter prototype. |
73| [isa_coverage.md](isa_coverage.md) | RDNA2 ISA coverage of the translator against AMD's machine-readable XML: which of its 1,153 instructions have a rule, and which matched names are not RDNA2. | 86| [isa_coverage.md](isa_coverage.md) | RDNA2 ISA coverage of the translator against AMD's machine-readable XML: which of its 1,153 instructions have a rule, and which matched names are not RDNA2. |
74| [buffer_bounds.md](buffer_bounds.md) | V# `OOB_SELECT` bounds measured natively: RDNA2 (gfx1036) follows Mesa's GFX11 column (729/732 cases), not GFX10; raw mode also counts `soffset`. | 87| [buffer_bounds.md](buffer_bounds.md) | V# `OOB_SELECT` bounds measured natively: RDNA2 (gfx1036) follows Mesa's GFX11 column (729/732 cases), not GFX10; raw mode also counts `soffset`. |
88| [buffer_formats.md](buffer_formats.md) | Every GFX10 buffer data format a V# or MTBUF can name, loaded and stored, measured on a Radeon 880M (RDNA3.5, not RDNA2): 1.33 million validated elements, 0 mismatches; SCALED stores convert as NORM, float stores round toward zero. |
75| [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. | 89| [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. |
76| [fspx.md](fspx.md) | `FSPX`, the FidelityFX DLL's native compute programs (its shaders' `ACCC` part): directory as the DLL reads it, kind-0 dispatch state, the hash prologue, `gfx1030` for its `v_dot4` code; 13 of 29 translate with `tools/fspx_unpack.py`. | 90| [fspx.md](fspx.md) | `FSPX`, the FidelityFX DLL's native compute programs (its shaders' `ACCC` part): directory as the DLL reads it, kind-0 dispatch state, the hash prologue, `gfx1030` for its `v_dot4` code; 13 of 29 translate with `tools/fspx_unpack.py`. |
77| [first_light.md](first_light.md) | The first draw of a real game model with its own translated VS/PS on a GPU: 4,213 vertices / 7,968 triangles, 78.1% coverage on an RTX 2060 SUPER; `tools/first_light.py`, the `vk_harness` mesh mode, and the same draw through the D3D12 layer (`d3d12_first_light`). | 91| [first_light.md](first_light.md) | Draw an exported model's UVs or sample a supplied texture with `--dds`. The UV draw covered 78.1% on an RTX 2060 SUPER (4,213 vertices, 7,968 triangles). The first draw of a real game model with its own translated VS/PS on a GPU: 4,213 vertices / 7,968 triangles, 78.1% coverage on an RTX 2060 SUPER; `tools/first_light.py`, the `vk_harness` mesh mode, and the same draw through the D3D12 layer (`d3d12_first_light`). |
78| [material_pass_replay.md](material_pass_replay.md) | How one authored mesh writes packed draw indices, how six compute programs read the layout, and which sibling passes read the surface material. | 92| [material_pass_replay.md](material_pass_replay.md) | How one authored mesh writes packed draw indices, how six compute programs read the layout, and which sibling passes read the surface material. |
79| [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool and the one rule still missing. | 93| [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool, the one rule still missing, and the build step and run-time lookup of the builder's programs (`<shaders>/bvh/index.json`). |
80| [shader_inputs.md](shader_inputs.md) | Inputs that specific game shaders need to be right, as a first check for a black frame or a device-lost: the studio-shot lighting shader's 512-byte light records, eight-light loop, plane count at +0x4C (#1892 said +0x40), profile table and shadow-strength byte; the ACES LUT bakes' two tone-curve splines (reference order at +0x00, points-first at +0x70 behind the +0x118 switch), the +0x13C luminance mode and the quasi-log addressing (#1896); the sky LUT order and the +0xD0 dword that picks RGB9E5 or float outputs (#1897). | 94| [shader_library.md](shader_library.md) | The pipeline library in `shaders.rpf`'s zlib part, which the carve doesn't read: 25,471 graphics and 2,693 compute pipeline records (stage slots: PS, VS, MS) and 21,522 native programs, 21,509 of them pipeline builds of 6,522 carved shaders (named by their `HASH` digest); `tools/shader_library.py`. |
95| [shader_inputs.md](shader_inputs.md) | Inputs that specific game shaders need to be right, as a first check for a black frame or a device-lost: the studio-shot lighting shader's 512-byte light records, eight-light loop, plane count at +0x4C (#1892 said +0x40), profile table and shadow-strength byte; the ACES LUT bakes' two tone-curve splines (reference order at +0x00, points-first at +0x70 behind the +0x118 switch), the +0x13C luminance mode and the quasi-log addressing (#1896); the sky LUT order and the +0xD0 dword that picks RGB9E5 or float outputs (#1897); the shared atmosphere constant buffer, its table slots (+0x220, +0xC60) and the layout with the two scale-height dwords no pass consumes (#3990). |
81| [sandbox.md](sandbox.md) | Placed world props through one translated VS/PS pair with a real camera, TTPF albedo and the game's sampler: 442 of 446 draws textured; fly/walk/drive window, `tools/sandbox.py --check`. | 96| [sandbox.md](sandbox.md) | Placed world props through one translated VS/PS pair with a real camera, TTPF albedo and the game's sampler: 442 of 446 draws textured; fly/walk/drive window, `tools/sandbox.py --check`. |
82| [coder.md](coder.md) | The compressed mass in `story000_script.rpf`: entry framing (`align16(entry+8)` payload), the 32-value tag alphabet, deflate-shaped but proprietary, variable-length 7/8-bit LSB-first codes with no stored table, and the `n7 = 116..127` search that finishes it. | 97| [coder.md](coder.md) | The compressed mass in `story000_script.rpf`: entry framing (`align16(entry+8)` payload), the 32-value tag alphabet, deflate-shaped but proprietary, variable-length 7/8-bit LSB-first codes with no stored table, and the `n7 = 116..127` search that finishes it. |
83| [mission_logic.md](mission_logic.md) | Mission state tables: 0x20 record layout (band counter, byte offsets), the 64-byte pool element with world transforms, case-folding joaat keys, 53.5 % of states named, 113 state-set clusters covering 82.4 % of files. | 98| [mission_logic.md](mission_logic.md) | Mission state tables: 0x20 record layout (band counter, byte offsets), the 64-byte pool element with world transforms, case-folding joaat keys, 53.5 % of states named, 113 state-set clusters covering 82.4 % of files. |
diff --git a/docs/animation.md b/docs/animation.md
index 018a6e6b3..ad13ec99b 100644
--- a/docs/animation.md
+++ b/docs/animation.md
@@ -149,7 +149,7 @@ The `SKEL_<region>_<part>` shape is the conventional RAGE bone naming. The anima
149to the bones, but a skeleton carries its own names (`joaat32` at bone record `+0x1C`, name at `+0x30`, 149to the bones, but a skeleton carries its own names (`joaat32` at bone record `+0x1C`, name at `+0x30`,
150[character_skeleton.md](character_skeleton.md)), so the match is measured: see 150[character_skeleton.md](character_skeleton.md)), so the match is measured: see
151[Bone tables and motion matchers](#bone-tables-and-motion-matchers). 151[Bone tables and motion matchers](#bone-tables-and-motion-matchers).
152The `SKEL_<region>_<part>` shape is the conventional RAGE bone naming. Measured across all `SKEL_*` streams in 152Measured across all `SKEL_*` streams in
153`anim.rpf` (`177` streams, `118` distinct `SKEL_*` tokens) against the decoded skeleton name tables in 153`anim.rpf` (`177` streams, `118` distinct `SKEL_*` tokens) against the decoded skeleton name tables in
154`packs.rpf` (`2,866` `SKEL_`-bearing streams, `691` distinct `SKEL_*` tokens) using `tools/anim_skeleton_match.py`: 154`packs.rpf` (`2,866` `SKEL_`-bearing streams, `691` distinct `SKEL_*` tokens) using `tools/anim_skeleton_match.py`:
155`117` of `118` (`99.2%`) match by exact case and all `118` of `118` (`100%`) match case-insensitively (and by 155`117` of `118` (`99.2%`) match by exact case and all `118` of `118` (`100%`) match case-insensitively (and by
@@ -484,15 +484,50 @@ u32; u32 count}` with `Entry {u64 key; T *value; Entry *next}`. Hashes are `joaa
484| | `+0x120` pointer (`+0x58` = 2) | a block whose `+0x18` points at the parameter node | 484| | `+0x120` pointer (`+0x58` = 2) | a block whose `+0x18` points at the parameter node |
485| | `+0x138` pointer (`+0x58` = 1) | the parameter node: `{u64 0; u32 type; u32 0; ...}` | 485| | `+0x138` pointer (`+0x58` = 1) | the parameter node: `{u64 0; u32 type; u32 0; ...}` |
486| parameter node, type 3 | `+0x10` array of u32, `+0x20` array of 8-byte items, `+0x30`/`+0x34` f32 | one sampled axis: its name hash(es), then `{u32 sample index; f32 value}` sorted by value, then min and max | 486| parameter node, type 3 | `+0x10` array of u32, `+0x20` array of 8-byte items, `+0x30`/`+0x34` f32 | one sampled axis: its name hash(es), then `{u32 sample index; f32 value}` sorted by value, then min and max |
487| `.motionmatcher` (`+0x20` is a pointer) | `+0x28` 16 bytes, `+0x38` atString | an id, then `pack:/<name>.motionmatcher`; the rest is not decoded | 487| `.motionmatcher` (`+0x20` is a pointer) | `+0x20` pointer | the feature object (below) |
488| | `+0x28` 16 bytes, `+0x38` atString | an id, then `pack:/<name>.motionmatcher` |
489| | `+0x58` pointer, u32 count at `+0x54` | records `{f32; f32; f32 −1.0; u32 clip index; u64 0}`, 24 bytes. A `.motionmatcher` array keeps its u32 count just before the pointer, and a u32 capacity before that |
490| | `+0x68` pointer, count at `+0x64` | u32 offsets, one more than the records, from 0 and never decreasing |
491| | `+0x78` pointer, count at `+0x74` | u16, one per clip and then the record count: each clip's first record |
492| | `+0xB8` pointer, count at `+0xB4` | u8, 0 or 1, one per clip |
493| | `+0x98` pointer, count at `+0x94` | on 36 of 180: one `{u64 0; u32 clip hash; u32 dictionary hash}` per clip, like `.motion` children |
494| | `+0xA0` u32 groups, `+0xA4` u32 entries, `+0xA8` pointer | a hash table of the clips: per group 16 control bytes (0x80 empty, below 0x80 full), then 16 slots `{u32 clip hash; u32 dictionary key; u32 clip index; u32 0}` |
495| | `+0x170`/`+0x174`/`+0x178` | the same kind of table with 8-byte slots `{u32 hash; u32 index}` |
496| | `+0x188` u32, `+0x18C` u32 | the clip's own hash and the dictionary's `joaat32(name)`, as `.motion` has at `+0x28`/`+0x2C` |
497| | `+0x48` pointer, count at `+0x44` | one 40-byte item, zero except a u32 1 at its `+0x20` (`+0x40` holds the name's length and capacity, measured separately) |
498| | `+0x118` pointer, count at `+0x114` | one u32: the pose sample count |
499| | `+0x128` pointer, count at `+0x124` | one u16, 0 |
500| matcher feature object | `+0x18` u32, `+0x28` pointer, `+0x30` pointer or null | 1 (measured separately), then the skeleton and the `+0x30` object (both below) |
501| | `+0x40` pointer, count at `+0x3C` | pointers to the features, 0x30 bytes each: `{+0x08 u32 column; +0x0C u16 width; +0x0E u16 (1 or 5); +0x18 u32 name hash (a bone with 1); +0x1C u32 kind bits}` |
502| | `+0x48` u32 groups, `+0x4C` u32 entries, `+0x50` pointer | a hash table like the clip table, 8-byte slots `{u32 hash; u32 feature index}` |
503| | `+0xF0` pointer, count at `+0xEC` | the pose matrix, f16, in 32-byte chunks: one row of feature values per sample (layouts below) |
504| | with `+0x30`: `+0xF8` u32, `+0xFC` u32, `+0x100` u32 | samples, columns, 32-byte chunks per row (rows are padded to 16 columns) |
505| | with `+0x30`: `+0xA8` pointer, count at `+0xA4` | one 48-byte `{f32 quaternion[4]; f32 vec3; f32 0; f32 1, 1, 1; f32 0}` per sample |
506| | without `+0x30`: `+0xFC` u32, `+0x128` u32 | columns, samples (the matrix is in blocks of 8 samples) |
507| | `+0x98` pointer, count at `+0x94` | one u32 per sample: a bit mask over the matcher's key table indices, the same for every sample of a record |
508| | `+0xB8` pointer, count at `+0xB4` (32-byte chunks) | one f32 weight per pose column, 8 to a chunk, zero after the last column |
509| | `+0xC0` f32, `+0xC4` f32, `+0xC8` u32 | not decoded, then 1.0, then 1 with rows and 3 with blocks of 8 |
510| matcher `+0x30` object (112 bytes, measured separately) | `+0x08` u32 | its form: 1 or 2 |
511| | form 2: `+0x10`/`+0x14` u32, `+0x18`/`+0x1C` f32 | two bones (`joaat32` of their names) and their weights |
512| | form 2: `+0x30` 0x30 bytes, `+0x68` u32, `+0x6C` u16 | a copy of the clip's first feature (its kind at `+0x4C`), that feature's width, a flag (6 or 9) |
513| | form 1: `+0x10` f32[4], `+0x60` u32 | a unit quaternion (a reference rotation), a flag (6 or 7) |
514| | form 1: `+0x40` {u32 n; u32 n; pointer}, `+0x50` the same | n u32 bones (`joaat32` of their names), then n f32 weights |
515| matcher skeleton (feature object `+0x28`) | `+0x18` u32 slots, `+0x1C` u32 entries, `+0x20` pointer | tag table, 8-byte slots `{u32 tag; u32 bone}`, empty tag 0xFFFFFFFF |
516| | `+0x28` pointer, `+0x6C` u16 count (`+0x6E` the same, measured separately) | the bones, 80 bytes each: `{f32 rotation quaternion[4]; f32 translation[3]; 4 bytes; f32 1.0[4]; char *name at +0x30; s16 parent at +0x46; u16 index at +0x48 and +0x4C; u16 bone id at +0x4A}` (the 1.0s and the two indices on 180 of 180, measured separately) |
517| | `+0x30`, `+0x38` pointers | per bone a 4x4 f32 matrix: the inverse bind matrix, and the local matrix (row vectors, translation in row 3) |
518| | `+0x40` pointer | the parents, one s16 per bone, −1 for the root |
519| | `+0x48` pointer | a prefix tree of the bone names: `{u16 n; u16 size}`, nodes from `+4` `{u16 next sibling; u16 first child; s16 value; char text[]}` (offsets relative to the node), then n u16 bone indices at `+size` |
488| animation | `+0x24` u16 | frame count | 520| animation | `+0x24` u16 | frame count |
489| | `+0x28` f32 | duration = (frames − 1) / fps | 521| | `+0x28` f32 | duration = (frames − 1) / fps |
490| | `+0x50` array | sequence pointers | 522| | `+0x50` array | sequence pointers |
491| | `+0x60` array, 12-byte items | tracks `{u32 bone hash; u32 track type; u32 format}` | 523| | `+0x60` array, 12-byte items | tracks `{u32 bone hash; u32 track type; u32 format}` |
492 524
493A clip plays its animations at the same time, each over its own `[start, end]` window at its rate: animation time 525A clip plays its animations at the same time, each over its own `[start, end]` window at its rate: animation time
494`t` is clip time `(t − start) / rate`, and `(end − start) / rate` equals the clip's `+0x78` duration (4,471 of 4,471 526`t` is clip time `(t − start) / rate`, and `(end − start) / rate` equals the clip's `+0x78` duration: over all
495entries in 300 sampled dictionaries). In the samples, the animations of one clip covered different bones and could 52761,505 dictionaries of `anim.rpf` (`tools/anim_clips.py`, `clip_windows`), 784,562 of the 785,174 animation entries of
528ordinary clips match to float32 precision (relative 1e-5) and the other 612 within 2.2e-4 relative, 581 of them in
529one-frame (0.033 s) clips where the rounding shows most; none has rate 0 (the first check, 300 sampled
530dictionaries, had 4,471 of 4,471). In the samples, the animations of one clip covered different bones and could
496have different frame rates. `tools/anim_glb.py` plays clips on a fragment skeleton and writes them as glTF 531have different frame rates. `tools/anim_glb.py` plays clips on a fragment skeleton and writes them as glTF
497animations; see [character_skeleton.md](character_skeleton.md#animated-gltf-export). 532animations; see [character_skeleton.md](character_skeleton.md#animated-gltf-export).
498 533
@@ -635,7 +670,13 @@ fields are in the object table above. Measured on all 17,247 `.motion` clips:
635 sample count at `+0x90`, `+0x90`, `+0x50` and `+0xA0`: on all 2,281 of them that are a `.motion`'s only node, it 670 sample count at `+0x90`, `+0x90`, `+0x50` and `+0xA0`: on all 2,281 of them that are a `.motion`'s only node, it
636 equals the number of `+0x90` sample lists below. The word list resolves 1,135 of their 8,404 axis names, the same 671 equals the number of `+0x90` sample lists below. The word list resolves 1,135 of their 8,404 axis names, the same
637 names as type 3 (`verticalheight`, `yawangle`, `surfaceincline` the most); `anim_clips.py` counts them as 672 names as type 3 (`verticalheight`, `yawangle`, `surfaceincline` the most); `anim_clips.py` counts them as
638 `motion_node_axis_name:<type>:<name or unresolved>`. 673 `motion_node_axis_name:<type>:<name or unresolved>`. Types 4–8 have a second `{ptr, count}` array at `+0x20`
674 (found by @ismailchaka1): null on all 2,644 type-4 nodes and on 431 of the 482 type-5 nodes, present on the other
675 51 type-5 nodes and on every type-6 (295) and type-8 (98) node. On all 393 type-6 and type-8 nodes its 16-byte
676 items read `{u32, u32 0, u32, u32 0}` and none of those words is one of the node's axis names or the `.motion`'s
677 child or dictionary hashes; on type 5 only 2 of the 51 arrays have that shape. The item count is 5 on 184 type-6 nodes, 3 on 57, 2 on 44; 9 on 47 type-8 nodes and 6 on 42.
678 It equals the child count on only 5 of the 444 nodes. Not decoded; `anim_clips.py` counts the item counts as
679 `motion_node_pairs:<type>:<count or null>`.
639- **Type 3: one sampled axis.** It has one axis entry, then 1–16 `{u32 sample index, f32 value}` items and the 680- **Type 3: one sampled axis.** It has one axis entry, then 1–16 `{u32 sample index, f32 value}` items and the
640 axis min and max. On all 10,171 (29,123 samples), the items are sorted by value, min and max are the first and 681 axis min and max. On all 10,171 (29,123 samples), the items are sorted by value, min and max are the first and
641 last values, and the sample indices are 0..n−1 in some order. They are not child indices: the sample count 682 last values, and the sample indices are 0..n−1 in some order. They are not child indices: the sample count
@@ -663,7 +704,132 @@ fields are in the object table above. Measured on all 17,247 `.motion` clips:
663The 180 `.motionmatcher` clips sit in 142 dictionaries that hold only `.motionmatcher` clips and no local pack. 704The 180 `.motionmatcher` clips sit in 142 dictionaries that hold only `.motionmatcher` clips and no local pack.
664The three motion matcher streams in [Bone tables and motion matchers](#bone-tables-and-motion-matchers) 705The three motion matcher streams in [Bone tables and motion matchers](#bone-tables-and-motion-matchers)
665(`0x101c379a0`, `0x101c41d50`, `0x101ea66c0`) are the second system pages of three of those dictionaries, with 2, 1 and 2 706(`0x101c379a0`, `0x101c41d50`, `0x101ea66c0`) are the second system pages of three of those dictionaries, with 2, 1 and 2
666`.motionmatcher` clips. Their layout after the name is not decoded. 707`.motionmatcher` clips.
708
709A `.motionmatcher` object has fields up to `+0x18F`; they are in the object table above, and `anim_clips.py` decodes them
710(`parse_matcher`) and counts them as `matcher_*`. Measured by `parse_matcher` on the pages of all 142 dictionaries
711(180 clips):
712
713- **Arrays** keep a u32 count at pointer − 4 and a u32 capacity at pointer − 8, not the `{ptr; u16 count}` of the
714 rest of the dictionary.
715- **Records (`+0x58`).** 4,562 records (1–346 per clip, measured separately). The third float is −1.0 in all of
716 them, and the u32 is the record's position on 175 of 180 clips. The first float is 0 or 0.03–2.37 and the second
717 one of 2.5, 5, 6.667, 10, 15, 20, 30 or 40 (also measured separately); that they are a start time and a sample
718 rate is a hypothesis.
719- **Offsets (`+0x68`).** One more than the records on 180 of 180, starting at 0 and never decreasing, so an offset
720 table into data not decoded here.
721- **Clip table (`+0xA0`).** An open-addressing hash table: the group count is a power of two (2 on 151 clips,
722 measured separately), every control byte is 0x80 or below 0x80, the last word of every slot is 0 (measured
723 separately), and the full slots equal the entry count on 180 of 180. Its 4,381 slots hold a clip hash that is a
724 clip in anim.rpf (4,381 of 4,381) and a clip index; the indices are 0..n−1 over the entries on 180 of 180. The
725 matcher's clips are these n entries, and its records are cut from them: a record's fourth word is its clip's
726 index and the record lies in that clip's `+0x78` range on 180 of 180 (`matcher_record_clip_in_its_u16_78_range`).
727 There is one clip per record on 175; on the other 5 some clips have several records. The second word names the
728 clip's dictionary: measured separately against the 60,778 dictionary names of anim.rpf, it is `joaat32` of the
729 dictionary's name behind a fixed 8-character prefix on 4,356 of 4,381 entries (the slot's clip is in that
730 dictionary on 4,349), the plain dictionary hash on 18, and neither on 7. 177 of 180 matchers resolve all their
731 entries this way.
732- **References (`+0x98`).** 36 clips have one `{clip hash, dictionary hash}` per clip (439). All 439 resolve to a
733 clip of that dictionary in anim.rpf, and the item at each table slot's clip index names that slot's clip on all
734 36. On those 36, the dictionary the second word names is the reference's on 438 of 439 (measured separately), so
735 the table gives the dictionary for the other 144 too.
736- **Key table (`+0x170`).** The same table with 8-byte slots, 2 groups on all 180: 403 entries of `{u32 hash, u32
737 index}`, the indices 0..n−1 on 180 of 180. 38 entries are clip hashes in anim.rpf; there are 23 distinct hashes
738 (measured separately).
739- **Where an entry sits.** Every entry is where its hash h puts it: control byte h & 0x7F, in group
740 (h >> 7) & (groups − 1), or, when that group is full, in a later one with every group in between full (linear
741 probing), on 180 of 180 for each of the three tables (`table_placed_by_key`). The key table and the features'
742 `+0x48` table hash an entry by its own first u32. The clip table hashes the u64 of its first two words (clip
743 hash low, second word high) with MurmurHash3's 64-bit finaliser (`fmix64`, `clip_slot_hash`): 4,351 of its
744 4,381 entries sit in their home group and the other 30 after full groups (measured separately).
745- **Self (`+0x188`).** The clip's own hash and the dictionary's `joaat32(name)` on 180 of 180.
746- **`+0x78` and `+0xB8`.** The u16 array has one item per clip and then one more, on 180 of 180: it starts at 0,
747 never decreases and ends at the record count, so item i is clip i's first record. The u8 array has one item per
748 clip on 180 of 180 and is 0 or 1; 16 items are 1. (With one clip per record, on 175, both also fit "one per
749 record".)
750- **Features (`+0x20`).** Each matcher points to a feature object with a list of features: 1,873 in all, distinct
751 name hashes within each clip on 180 of 180 (1–21 per clip and 53 distinct names overall, measured separately). Widths are multiples of 3 on 180 of 180
752 (3, 6, 9 or 12, measured separately), and the columns chain from 0 (each feature starts where the one before
753 ends) on 180 of 180, so a clip's features fill 6–126 columns (11,616 in all; the range measured separately),
754 and the pose matrix below has one column per feature column. The `+0x48` table has one slot per feature, with the indices 0..F−1 on
755 180 of 180; its hashes are not the `+0x18` name hashes (0 of 180, measured separately). `+0x0E` is 1 on 1,842
756 features and 5 on 31, all 31 in clips with the blocks layout (measured separately). With 1, the name hash is
757 `joaat32` of a bone name of the clip's skeleton on 1,842 of 1,842, and `+0x1C` is a set of bits that gives the
758 width: 3 columns for bit 0, 3 for bit 1 and 6 for bit 3, on 1,842 of 1,842 (kinds 1, 3, 9 and 11 are seen,
759 measured separately). That bit 0 is the bone's position, bit 1 its velocity and bit 3 a rotation written as two
760 vectors is a hypothesis; the pose check below supports it for position and rotation. With 5, `+0x18` names no
761 bone (0 of 31): `+0x1C` is 0 on 20 and `+0x18` is 0 on the other 11. Measured separately, the nonzero words of
762 the 30 three-column ones are `joaat32` of names that are not bones (a word list resolves some of them).
763- **Skeleton (feature object `+0x28`).** 3,918 bones over the 180 clips. One root and every parent before its
764 child on 180 of 180, the bones' parent field is the `+0x40` array, and the tag table holds exactly two tags per
765 bone, `joaat32` of its name and its u16 id, on 180 of 180. The root's id is 0 and every other bone's is the ELF
766 hash of its upper-cased name, mod 0xFE8F, plus 0x170, on 180 of 180 (3,738 bones; `bone_id`). The local
767 matrix is the bone's rotation and translation, and the inverse bind matrix times the product of the local
768 matrices up the chain is the identity (to 2e-3), on 180 of 180. `+0x48` is a prefix tree of the bone names
769 (shared prefixes stored once): walking it, a node whose value lands in the u16 array after the tree names the
770 bone in that slot, and every bone's name leads to that bone, on 180 of 180 (`skeleton_name_tree`). The array
771 lists the bones in tree order (measured separately). `parse_matcher` returns it all as `skeleton`.
772- **Per sample (`+0x98`).** In both layouts, one u32 per sample, the same for every sample of a record, on 180 of
773 180. It is a bit mask over the key table's indices: the bits set over all samples are exactly bits 0..K−1, with
774 K the key table's entries, on 180 of 180 (`matcher_sample_u32_bits_are_key_indices`), so each record carries the
775 set of keys (tags) that apply to it.
776- **Pose matrix (feature object `+0xF0`).** One row of f16 values per sample, one column per feature column. The
777 sample count equals the last `+0x68` offset on 180 of 180 (36,436 samples), so record i owns the rows from
778 offset i to offset i+1, and the column count is the features' total on 180 of 180. Two layouts, told apart by
779 the feature object's `+0x30` object (149 with it, 31 without):
780 - **Rows** (149): row-major, each row padded with zero columns to the next multiple of 16 (`+0x100` chunks of 16).
781 - **Blocks of 8** (31): 8 samples at a time, column-major inside a block, so column c of sample r is at
782 `(r // 8) · D' · 8 + c · 8 + r mod 8`, with D' the column count rounded up to even (the spare column is zero).
783 The lanes after the last sample repeat it.
784
785 The sizes fit these layouts on 180 of 180 (`parse_matcher` refuses one that doesn't), every value is finite and
786 the padding is as described on 180 of 180. On the 149 with rows, `+0xA8` has one 48-byte item per sample: a
787 unit quaternion, a vec3 and a scale of (1, 1, 1) on 149 of 149. It is the sample's reference frame: the
788 quaternion is a rotation about z only on 30,946 of the 30,962 samples, and the frame comes from the `+0x30`
789 object's weighted bones (below). `anim_clips.matcher_pose` reads one row.
790
791 Measured separately by decoding the clips' own keyframes at each sample's time (up to two clips per matcher,
792 285 clips; record start + j / the record's rate), a feature holds its bone's pose in that frame:
793 - position columns are the bone's model-space position minus the frame's vec3, rotated by the frame's inverse,
794 on 11,469 of 12,873 samples (to 0.01 m);
795 - the two vectors of bit 3 are rows 0 and 1 of the bone's model-space rotation, in the same frame, on 2,233 of
796 2,544 (to 0.02);
797 - the frame's x and y are the weighted centroid of the object's bones on 1,148 of 1,233 samples; its z is the
798 centroid's z with flag 6, and −1.0 on every sample on 29 of the 32 form 1 matchers with flag 7 (all 149
799 matchers counted);
800 - its yaw is the heading from the first to the second bone with form 2 (682 of 752), and the z-twist of the
801 reference rotation's inverse times the bone's rotation with a one-bone form 1 (89 of 89).
802
803 Velocity columns (bit 1) fit a plain difference of the model-space position on only 1,960 of 9,366 samples, so
804 they are not decoded. A record's rows cover part of its clip, not all of it:
805 with rows 1 / (the record's second float) seconds apart, they fit inside the clip's duration on 2,108 of the
806 2,155 records whose clip duration is known without ambiguity (measured separately), which fits the sample-rate
807 hypothesis above. Which part of the clip they cover is not decoded.
808- **One-item arrays.** The matcher's `+0x48` is one 40-byte item, zero except a u32 1 at `+0x20`; `+0x118` is
809 one u32 equal to the pose sample count; `+0x128` is one u16, 0; each on 180 of 180.
810- **`+0x30` object.** On the 149 clips that have it, its `+0x08` is 2 on 93 and 1 on 56. It names the bones the
811 pose frame is built from (above). With 2: two distinct bones of the clip's skeleton by `joaat32` of their names
812 at `+0x10`/`+0x14` (93 of 93), and at `+0x30` a copy of the clip's first feature (its `+0x0E`, name hash and
813 kind, 93 of 93) whose width is at `+0x68` (by the bit rule above, 93 of 93); the u16 at `+0x6C` is 6 on 92 and
814 9 on 1. With 1: the arrays at `+0x40` and `+0x50` have the same count n (1, 3, 4 or 6, measured separately), and
815 the first holds bones of the skeleton by `joaat32` of their names (56 of 56); `+0x10` is a unit quaternion (56
816 of 56), and the u32 at `+0x60` is 6 on 24 and 7 on 32. Its weights (form 2: the f32s at `+0x18`/`+0x1C`; form
817 1: the second array) are positive and sum to 1 on 149 of 149.
818- **Column weights (`+0xB8`).** One f32 per pose column, stored 8 to a 32-byte chunk with zeros after the last
819 column (the count at `+0xB4` is the chunks), on 180 of 180. They are positive and sum to 1, and the three
820 columns of each vec3 have the same weight, on 180 of 180 (`matcher_column_weights_*`). They are not the
821 reciprocal, the deviation or the variance of their columns over the samples (measured separately), and a
822 clip's weights and `+0xC0` are the same for every clip with the same features on 20 of 23 feature sets
823 (measured separately), so they look like settings, not statistics. `+0xC4` is 1.0, and `+0xC8` is 1 with rows
824 and 3 with blocks of 8, on 180 of 180.
825- Not decoded: the hash of the features' `+0x48` table. It is a function of the feature's `+0x0E` and `+0x18`
826 only (53 distinct pairs, no conflict), and, measured separately, it is not case-sensitive or case-folded
827 joaat32 (with any constant seed or prefix, or a suffix of up to 3 characters), one-at-a-time, FNV-1/1a 32 or 64,
828 ELF, CRC-32, MurmurHash3 32, MurmurHash64A, or `fmix32`/`fmix64` of the name hash or the bone id. Also not
829 decoded: the velocity columns, the yaw rule of a form 1 object with several bones (the z-twist of their
830 weighted inverse-bind rotations fits only to 0.15 rad, 353 of 392 samples), why form 1's quaternion is not
831 the blend of its bones' bind rotations (15 of 56), the width-9 feature with `+0x0E` = 5, and the f32 at
832 `+0xC0`.
667 833
668### Other archives 834### Other archives
669 835
@@ -883,6 +1049,87 @@ state-machine and motion-tree hierarchy (**1,616** containers across the 324 res
883 (20-byte unary node, 48), `Type 5` (44-byte blend, 42), and `Type 23` (8-byte identity pose leaf, 20), plus 13 1049 (20-byte unary node, 48), `Type 5` (44-byte blend, 42), and `Type 23` (8-byte identity pose leaf, 20), plus 13
884 rarer operator types (`6, 8, 18, 25, 27, 31, 32, 34, 36, 37, 39, 40, 41`, 53 total). 1050 rarer operator types (`6, 8, 18, 25, 27, 31, 32, 34, 36, 37, 39, 40, 41`, 53 total).
885 1051
1052## `MoVE` state-machine containers
1053
1054`tools/anim_move.py` decodes all 324 `MoVE` (version 19) resources in `anim.rpf` (ASSET-86):
1055
1056```powershell
1057python -I tools/anim_move.py <package>\anim.rpf <work>\anim-move.json
1058```
1059
1060All 324 resources (325 zlib streams, 331,771 stored / 1,494,188 inflated bytes once the 64 KiB stream at
1061`0x105a7d000` is joined with its 5,563-byte continuation stream at `0x105a7f9c0`) decode with 0 errors. Unlike clip
1062dictionaries and `0DRP` resources, a `MoVE` resource has no virtual `0x50xxxxxx` pointers or RAGE page map: every
1063internal cross-reference is a signed 32-bit self-relative byte offset (`target = field_offset + rel_i32`).
1064
1065### Header and variable preamble
1066
1067After the fixed 32-byte header (`"MoVE"`, `u32 version = 19`, three zero `u32`s, `u32 network_hash` at `+0x14`,
1068`u32 body_size` at `+0x18`, `u32 0` at `+0x1C`), a variable-length preamble starts at `+0x20`:
1069
1070| Field | Type | Measured across 324 resources |
1071|---|---|---|
1072| `N_req`, `requests` | `u32`, `N_req × u32` | `0..16` request hashes (`> 0` in 149 resources, 543 entries total) |
1073| `N_flag`, `flags` | `u32`, `N_flag × u32` | `0..27` flag hashes (`> 0` in 123 resources, 687 entries total) |
1074| `preamble_mode` | `u32` | `0` in 225 resources, `1` in 91, `2` in 8 |
1075| `N_desc`, `descriptors_5b` | `u32`, `N_desc × {u32 hash; u8 kind}` | `0` in 184 resources, `1..15` in 140 (272 entries total; `kind` = `0`: 20, `1`: 92, `2`: 74, `4`: 1, `7`: 85) |
1076| `tail` | `{u16 sub_flag; u32 ref_hash_0; u32 ref_hash_1}` | 10 zero bytes whenever `preamble_mode` is `0` or `1` (316/316); `sub_flag = 1` with two non-zero reference hashes when `preamble_mode == 2` (8/8) |
1077
1078The root state container starts immediately after the 10-byte tail at
1079`node_start = 48 + 4 * (N_req + N_flag) + 5 * N_desc` (`58..244` bytes). `body_size` at `+0x18` counts the
1080request/flag arrays, three `u32` preamble words and the entire state graph (`body_size == 12 + 4 * (N_req + N_flag) +
1081graph_bytes`), excluding the 46 fixed/tail bytes and the `5 * N_desc` descriptor table:
1082
1083$$\text{total\_bytes} = 46 + 5 \cdot N_{\text{desc}} + \text{body\_size}$$
1084
1085holds exactly for **324 of 324** resources.
1086
1087### Recursive state containers (`Type 1`, `Type 3`, `Type 22`)
1088
1089Every node in the graph starts with `{u16 type; u16 index; u32 name_hash}`. Three container types form the recursive
1090state-machine and motion-tree hierarchy (**1,616** containers across the 324 resources). All three share a 36-byte
1091(`0x24`) common prefix:
1092
1093```
1094+0x00 u16 type (1 = StateMachine, 3 = InlinedStateMachine, 22 = MotionTree)
1095+0x02 u16 index (0 on root/child states; node index inside an enclosing MotionTree)
1096+0x04 u32 name_hash (joaat32; e.g. joaat32("statemachine") = 0x1997df3c, joaat32("motiontree") = 0x8d398f99)
1097+0x08 i32 init_or_root_rel (target = off + 0x08 + init_or_root_rel)
1098+0x0c u32 flags (0 or 1)
1099+0x10 u8 b10, u8 b11, u8 n_children, u8 n_transitions
1100+0x14 four u32 words (0 in all measured Type 1 and Type 3 headers)
1101```
1102
1103| Container type | Instances | Header & body layout after `+0x24` |
1104|---|---:|---|
1105| `Type 1` (`StateMachine`) | 230 (63 at file root, 167 nested) | `0x58`-byte header: `+0x24` `i32 transitions_rel` (`off + 0x58 + 8 * n_children` when `n_transitions > 0`, or `0`), `+0x44` `f32 1.0`, `+0x50` `u32 n_default_transitions`, `+0x54` `i32 default_transitions_rel`. At `+0x58`: `n_children` 8-byte child directory entries `{u32 child_hash; i32 child_rel}` (`target = entry + 4 + child_rel`, 747 child states total), then `n_transitions` outgoing transitions, `n_default_transitions` default transitions, and the `n_children` child state containers (`Type 1` or `Type 22`). In 230 of 230 instances, `init_target` is in the child directory and every child's `+0x04` hash matches its directory `child_hash`. |
1106| `Type 3` (`InlinedStateMachine`) | 132 (all inside a `MotionTree`, 332 child states) | Same header as `Type 1` through `+0x54`, plus `u32 n_inputs` at `+0x58` (`1..2`, 151 inputs total) and `n_inputs × i32 input_rel` at `+0x5c` (`target = (off + 0x5c + 4*i) + input_rel`, pointing to the input pose node in the enclosing `MotionTree`). The `n_children × 8`-byte child directory follows at `off + 0x5c + 4 * n_inputs`, then `n_default_transitions` (114 total) and the `n_children` child states. |
1107| `Type 22` (`MotionTree`) | 1,254 (261 at file root, 993 nested) | `0x30`-byte header: `+0x24` `i32 transitions_rel` (always `0x0c`, so transitions start at `off + 0x30`), `+0x28` `i32 param_blocks_rel`, `+0x2c` `u32 n_param_blocks`. Followed by `n_transitions` outgoing transitions, `n_param_blocks` length-prefixed parameter blocks, and the motion-tree node arena (`3,875` declared children; first node has `index == 0`, root expression node is at `off + 0x08 + init_or_root_rel`). |
1108
1109### Transitions, parameter blocks and motion-tree nodes
1110
1111- **Outgoing state transitions (1,097 total: 77 on `Type 1`, 1,020 on `Type 22`):** each transition record carries its
1112 own byte length as `u32 size` at `+0x10` (`size >= 0x4c`; `76`, `84`, `88`, `92`, `96`, ... bytes), a signed relative
1113 offset to the target state at `+0x48`, and (when `size >= 0x50`) a `u32 condition_kind` at `+0x4c` followed by
1114 `size - 0x50` bytes of condition hashes and thresholds. Summing `size` across `n_transitions` matches the exact
1115 transition block span in **100%** of containers.
1116- **Default / any-state transitions (491 total: 377 on `Type 1`, 114 on `Type 3`):** each record starts with
1117 `{u16 size; u16 condition_count; i32 target_rel}` (`size >= 16`). Summing `size` across `n_default_transitions`
1118 matches `first_child - def_tr_start` in **100%** of containers.
1119- **MotionTree parameter blocks (2,104 total across the 1,254 `MotionTree`s):** each block starts with
1120 `{u32 block_size; u8 index, b1, b2, b3, b4, b5, b6, b7}` (`b7 == 0` in all 2,104), followed by
1121 `(b1 + b2 + b3 + b4)` 16-byte parameter/signal bindings (`3,683` total), `b5` 8-byte output/event bindings (`591`
1122 total), and `b6` variable-length curve/expression sub-records (`632` total, each carrying `u16 sub_size` at `+0x04`).
1123 The byte identity
1124 $$\text{block\_size} = 12 + 16(b_1 + b_2 + b_3 + b_4) + 8b_5 + \sum_{k=1}^{b_6} \text{sub\_size}_k$$
1125 holds in **2,104 of 2,104 (100%)** blocks.
1126- **MotionTree root expression nodes (1,254 total):** the root node at `init_target` is most commonly `Type 11`
1127 (clip leaf, 216), `Type 4` (2-way blend, 193), `Type 3` (`InlinedStateMachine`, 132), `Type 2` (12-byte output leaf,
1128 116), `Type 28` (filter/modifier, 94), `Type 9` (directional blend, 83), `Type 1` (nested `StateMachine`, 81),
1129 `Type 10` (N-way blend, 72), `Type 12` (parameterized motion, 55), `Type 19` (additive blend, 49), `Type 15`
1130 (20-byte unary node, 48), `Type 5` (44-byte blend, 42), and `Type 23` (8-byte identity pose leaf, 20), plus 13
1131 rarer operator types (`6, 8, 18, 25, 27, 31, 32, 34, 36, 37, 39, 40, 41`, 53 total).
1132
886## Readable, compressed and still opaque 1133## Readable, compressed and still opaque
887 1134
888- **Readable:** all 273 name tables (2,298 paths), the `0DRP` version/page count, 1,371 type-hash headers, 1135- **Readable:** all 273 name tables (2,298 paths), the `0DRP` version/page count, 1,371 type-hash headers,
@@ -901,7 +1148,7 @@ state-machine and motion-tree hierarchy (**1,616** containers across the 324 res
901 sampled positions. 1148 sampled positions.
902 No Oodle signature is known from these bytes; none is guessed. 1149 No Oodle signature is known from these bytes; none is guessed.
903- **Still opaque:** high-entropy blocks inside `other` and zero-prefixed pages (4 KiB blocks up to 7.96 1150- **Still opaque:** high-entropy blocks inside `other` and zero-prefixed pages (4 KiB blocks up to 7.96
904 bits/byte), the `0DRP` root objects and the packed component coding of their 1,781 clip-stream pages, the 1151 bits/byte), the `0DRP` root objects and the meaning of their auxiliary payloads, the
905 56 empty rig sets, the RBF0 numeric fields, and 1152 56 empty rig sets, the RBF0 numeric fields, and
906 the rig→skeleton link (0 measured matches). Of the 30 bone names, 19 have a confirmed stored hash and 11 do 1153 the rig→skeleton link (0 measured matches). Of the 30 bone names, 19 have a confirmed stored hash and 11 do
907 not; the four motionmatcher paths bind to embedded tables, but not to an RBF0 rig. 1154 not; the four motionmatcher paths bind to embedded tables, but not to an RBF0 rig.
@@ -914,7 +1161,6 @@ state-machine and motion-tree hierarchy (**1,616** containers across the 324 res
914- None of the 1,350 model names occurs in the 8,020 animation paths collected here, and none occurs in the 1161- None of the 1,350 model names occurs in the 8,020 animation paths collected here, and none occurs in the
915 `RBF0` rig metadata either. The sampled clip hash `0x25ed0554e58ba1fc` and the recurring `0x98e1750c` are 1162 `RBF0` rig metadata either. The sampled clip hash `0x25ed0554e58ba1fc` and the recurring `0x98e1750c` are
916 absent from all manifest names and integer/string values. A real cross-check needs the full model export 1163 absent from all manifest names and integer/string values. A real cross-check needs the full model export
917 (350,251 models per `docs/design.md`) and the rig table.
918 (382,781 models at `e293917` per `docs/design.md`) and the rig table. 1164 (382,781 models at `e293917` per `docs/design.md`) and the rig table.
919- `common.rpf` is the readable metadata layer. It carved to 781 streams, 710 of them XML-ish. Strict keyword 1165- `common.rpf` is the readable metadata layer. It carved to 781 streams, 710 of them XML-ish. Strict keyword
920 occurrences: `clip` 734, `anim` 1,131, `motion` 237, `gesture` 2, `bone` 428 (214 `<Bones>` open/close 1166 occurrences: `clip` 734, `anim` 1,131, `motion` 237, `gesture` 2, `bone` 428 (214 `<Bones>` open/close
@@ -937,9 +1183,7 @@ The bytes support **new RAGE resource pages**, not the GTA V `YCD`/`RSC7` family
937- `MoVE` (version 19) and the 2/3 clip streams as the animation payloads; neither is zlib inside the page. 1183- `MoVE` (version 19) and the 2/3 clip streams as the animation payloads; neither is zlib inside the page.
938- No `YCD`, `YDD`, `YLD`, `YFD`, `RSC7` or `RSC8` at any stream start. 1184- No `YCD`, `YDD`, `YLD`, `YFD`, `RSC7` or `RSC8` at any stream start.
939 1185
940`MoVE` (version 19) is a flat relative-offset state-machine and motion-tree graph (`tools/anim_move.py`). The 2/3 1186`MoVE` (version 19) is a flat relative-offset state-machine and motion-tree graph (`tools/anim_move.py`).
941streams are probably packed clips inside `0DRP` resources, but only the bytes above are measured; treat that label as
942a hypothesis until a decoder reads a known `0DRP` clip.
943 1187
944### What the bytes do not prove 1188### What the bytes do not prove
945 1189
@@ -948,9 +1192,8 @@ a hypothesis until a decoder reads a known `0DRP` clip.
948- `MoVE` v19's container layout, preamble tables, recursive state containers (`Type 1`, `Type 3`, `Type 22`), 1192- `MoVE` v19's container layout, preamble tables, recursive state containers (`Type 1`, `Type 3`, `Type 22`),
949 transitions and parameter blocks are decoded (`tools/anim_move.py`), while the unhashed source names of most 1193 transitions and parameter blocks are decoded (`tools/anim_move.py`), while the unhashed source names of most
950 network/request/flag hashes and the evaluation semantics of the rarest leaf operator node types remain unmapped. 1194 network/request/flag hashes and the evaluation semantics of the rarest leaf operator node types remain unmapped.
951- The 2/3 streams expose header variants, track arrays and bone masks. They are the second system pages of `0DRP` 1195- The two- and three-entry auxiliary tables bound their tagged payloads. Their contents have yet to be linked
952 resources, whose root objects and packed coding are not decoded. The keyframes of the clip dictionaries are 1196 to a clip. The clip dictionaries' keyframes are decoded in [Keyframe decoding](#keyframe-decoding).
953 decoded; see [Keyframe decoding](#keyframe-decoding).
954- The `RBF0` rig-set/rig/group entries are parsed. The numeric fields, the schema type table and the 1197- The `RBF0` rig-set/rig/group entries are parsed. The numeric fields, the schema type table and the
955 rig→skeleton reference are not; the measured skeleton match is 0. 1198 rig→skeleton reference are not; the measured skeleton match is 0.
956- The three motion matcher streams embed bone tables, but whether those define a full skeleton or only the 1199- The three motion matcher streams embed bone tables, but whether those define a full skeleton or only the
@@ -975,15 +1218,12 @@ a hypothesis until a decoder reads a known `0DRP` clip.
975 the stem (path without `pack:/` and without the final extension). The record stride varies (16 or 32 bytes in 1218 the stem (path without `pack:/` and without the final extension). The record stride varies (16 or 32 bytes in
976 sampled tables), so do not assume one layout. The recurring `0x98e1750c` is `joaat32("bonerotation")`, a 1219 sampled tables), so do not assume one layout. The recurring `0x98e1750c` is `joaat32("bonerotation")`, a
977 track type. 1220 track type.
9785. **Join rigs to clips, then decode a known `0DRP` clip.** Two named clips are already followed to page-0 payloads 12215. **Trace the auxiliary payloads to their consumers.** Use the parent's `+0x40` table to bound each payload
979 (durations and track arrays above). The missing link is the **page → packed stream**: none of the 1,781 1222 before checking its fields against the root object's schema. The table framing alone establishes no
980 packed streams contains the 30 known bone hashes or the nine tested clip hashes. Map the track records and 1223 association with the two named page-0 clips. (`MoVE` v19 is now decoded separately by `tools/anim_move.py`.)
981 the 16-byte `(hash, 0, index, 0)` tables first, then test a component count/order/delta coding against a
982 unit-quaternion norm. (`MoVE` v19 is now decoded separately by `tools/anim_move.py`.)
9836. **Keep the compression boundary explicit.** Outer RPF9 zlib is understood. Do not add a zlib pass inside a 12246. **Keep the compression boundary explicit.** Outer RPF9 zlib is understood. Do not add a zlib pass inside a
984 page without evidence; the sampled pages had no valid nested stream. 1225 page without evidence; the sampled pages had no valid nested stream.
9857. **Re-run the model cross-check with the full export.** The current 1,350-model data.rpf manifest has bone 12267. **Re-run the model cross-check with the full export.** The current 1,350-model data.rpf manifest has bone
986 bindings but no bone names or hashes. The full 350,251-model export plus the `RBF0` rig table is needed to
987 bindings but no bone names or hashes. The full 382,781-model export plus the `RBF0` rig table is needed to 1227 bindings but no bone names or hashes. The full 382,781-model export plus the `RBF0` rig table is needed to
988 match skeletons to models. 1228 match skeletons to models.
989 1229
diff --git a/docs/audio.md b/docs/audio.md
index e4141a706..cb6b3fad8 100644
--- a/docs/audio.md
+++ b/docs/audio.md
@@ -55,7 +55,9 @@ The exporters use three tag types:
55 55
56`tools/rsc8_audio.py` additionally decodes the speech companions `0x36` (peaks), `0xa3` (seek 56`tools/rsc8_audio.py` additionally decodes the speech companions `0x36` (peaks), `0xa3` (seek
57table), `0xb2` (loudness), `0xbd` (cue records) and the two structural tags below; every other tag type 57table), `0xb2` (loudness), `0xbd` (cue records) and the two structural tags below; every other tag type
58is skipped. 58is skipped. The `0xbd` record layout is in [rsc8_audio.md](rsc8_audio.md#the-0xbd-cue-records); the music banks
59have the tag too (945 tags in 938 of the 3,008 streamed-music banks, counted by `tools/awc_markers.py`), and
60what their records mark is in [audio_config.md](audio_config.md#marker-events-awc-tag-0xbd).
59 61
60| Tag | Meaning | 62| Tag | Meaning |
61|---|---| 63|---|---|
@@ -154,6 +156,15 @@ When exporting a directory, `awc_opus.py` keeps the path to each bank below the
154`a/music.awc` writes under `<out>/a/music/`. Passing that file on its own writes under `<out>/music/`. 156`a/music.awc` writes under `<out>/a/music/`. Passing that file on its own writes under `<out>/music/`.
155To regenerate a flat export from an earlier version, run `awc_opus.py` with the original bank directory and a fresh output directory. 157To regenerate a flat export from an earlier version, run `awc_opus.py` with the original bank directory and a fresh output directory.
156 158
159To import music cues into Audacity, run
160`python -I tools/awc_cue_labels.py <bank>/cue_regions.json <new-label-directory>` on a sheet
161exported by `awc_opus.py --cue-sheet`. Open the channel Ogg in Audacity at time zero, then use
162**File > Import > Labels** to load the matching `.txt` by filename stem. Each region shows its
163hexadecimal cue hash followed by its one-based row number in the bank sheet. Overlapping and
164repeated regions keep individual labels. Start and end times use nine decimal places in seconds
165so rounding back to the nearest 48 kHz frame recovers both endpoints.
166[Audacity label file format](https://manual.audacityteam.org/man/importing_and_exporting_labels.html)
167
157`audio_manifest.json` is the bank index: each bank's `Path`, `Offset`, `Size`, and its `Streams` with `Index`, 168`audio_manifest.json` is the bank index: each bank's `Path`, `Offset`, `Size`, and its `Streams` with `Index`,
158`Id` (hex), `Codec`, `Channels`, `SampleRate`, `DurationSeconds` and `IsStreamed`. For streamed music, 169`Id` (hex), `Codec`, `Channels`, `SampleRate`, `DurationSeconds` and `IsStreamed`. For streamed music,
159`Channels` is the Opus packet channel count and `DurationSeconds` is per channel: the tag `0x48` descriptor's 170`Channels` is the Opus packet channel count and `DurationSeconds` is per channel: the tag `0x48` descriptor's
@@ -208,7 +219,8 @@ programming is assembled by the game from many assets, so a lone AWC is rarely a
208 219
209The music/radio **config table** is a separate structure: 1,589 records with exact durations, AWC stream ids, 220The music/radio **config table** is a separate structure: 1,589 records with exact durations, AWC stream ids,
210contiguous station grouping and no per-track start offsets. See [audio_config.md](audio_config.md) for the record 221contiguous station grouping and no per-track start offsets. See [audio_config.md](audio_config.md) for the record
211layout and the station-content references. 222layout, the station-content references and the marker events (tag `0xBD`) that mark track boundaries in five
223long mixes.
212 224
213## Mission music: Home Sweet Home 225## Mission music: Home Sweet Home
214 226
@@ -301,9 +313,11 @@ The dictionary comes from two kinds of input:
301 they give 138,104 wave names. 313 they give 138,104 wave names.
302 314
303Measured on the 1.0.2.1 package (2026-11-22) with 2,455,498 distinct lowercase words: identifiers harvested from the 315Measured on the 1.0.2.1 package (2026-11-22) with 2,455,498 distinct lowercase words: identifiers harvested from the
304carved archives (by a scan like `hashdict.py`, not `hashdict.py` itself) plus the conversation waves: 316carved archives (by a scan like `hashdict.py`, not `hashdict.py` itself) plus the conversation waves. The columns are
317the ones the tool prints per source, so the second one is its distinct bank/ID pairs: an id that appears in two banks
318counts once in each (`Index.streams` in `tools/awc_names.py`):
305 319
306| Archive | Banks | Distinct ids | Named | Dialogue | Family | Control (expected false) | 320| Archive | Banks | Distinct bank/ID pairs | Named | Dialogue | Family | Control (expected false) |
307|---|---:|---:|---:|---:|---:|---:| 321|---|---:|---:|---:|---:|---:|---:|
308| `audio.rpf` | 7,162 | 1,606,237 | 92,043 | 0 | 92,043 | 352 | 322| `audio.rpf` | 7,162 | 1,606,237 | 92,043 | 0 | 92,043 | 352 |
309| `story000.rpf` | 63,861 | 234,458 | 173,800 | 120,511 | 53,289 | 62 | 323| `story000.rpf` | 63,861 | 234,458 | 173,800 | 120,511 | 53,289 | 62 |
@@ -326,6 +340,11 @@ Each positional source is reported and thresholded on its own. A source is a dir
326bank, or an `audio_manifest.json` from `rpf9dump audio` (read without opening the banks). Pure Python; the run above 340bank, or an `audio_manifest.json` from `rpf9dump audio` (read without opening the banks). Pure Python; the run above
327took about 3 minutes on one core. 341took about 3 minutes on one core.
328 342
343The dictionary is also readable the other way, which needs no carve folder:
344`python -I tools/hashdict.py --lookup <temp>/hashes.json <hash>...` takes a dictionary path followed by one or more
34532-bit hashes in hexadecimal and prints each with the name the dictionary holds for it, or `?` when it holds none
346(`tools/hashdict.py:70,82-93`). That answers "which wave is this id" when another tool prints a hash and no name.
347
329You can also pass the JSON inventory written by `awc_manifest.py --out inventory.json`. The naming tool reads 348You can also pass the JSON inventory written by `awc_manifest.py --out inventory.json`. The naming tool reads
330the plain stream IDs and streamed-music channel IDs directly from its rows. Bank labels keep the nested path 349the plain stream IDs and streamed-music channel IDs directly from its rows. Bank labels keep the nested path
331and drop the `.awc` extension to match the export folders. Banks with no stream rows have no names in this inventory. 350and drop the `.awc` extension to match the export folders. Banks with no stream rows have no names in this inventory.
@@ -348,6 +367,10 @@ out. A file is matched by its stream id and its bank: the folder below the Opus
348folders removed, so one Opus folder can hold several archives' exports. `--source` limits the names to one source 367folders removed, so one Opus folder can hold several archives' exports. `--source` limits the names to one source
349label of the names CSV. 368label of the names CSV.
350 369
370Dialogue wave names are matched without case. Repeated rows are accepted when they produce identical tags,
371including after subtitle markup is removed. Conflicting labels, speakers or subtitles stop the pass with a CSV
372line diagnostic before any Ogg file is modified; this also applies to `--dry-run`.
373
351```sh 374```sh
352python -I tools/opus_tags.py <work>/assets/audio/ogg --names <temp>/awc_names.csv --dialogue <temp>/dialogue.csv 375python -I tools/opus_tags.py <work>/assets/audio/ogg --names <temp>/awc_names.csv --dialogue <temp>/dialogue.csv
353``` 376```
@@ -389,3 +412,14 @@ the audio itself is not. See the ground rules in [design.md](design.md#ground-ru
389 412
390The tools export the streams and channels as stored. They do not reconstruct runtime mixing, looping, ducking or 413The tools export the streams and channels as stored. They do not reconstruct runtime mixing, looping, ducking or
391music-segment selection; that belongs to the game's audio system. 414music-segment selection; that belongs to the game's audio system.
415
416## Streamed-music cue sheets
417
418Run `python -I tools/awc_opus.py <bank-or-directory> <output> --cue-sheet` to write
419`cue_regions.json` next to the Ogg files for each bank with verified regions. Each row names
420a sibling audio file and the hexadecimal cue-name hash. The integer interval
421`[start_sample, end_sample)` counts 48 kHz frames per channel from the start of playback.
422Overlapping regions keep their original endpoints. The exporter pairs consecutive same-name
423start/end records within one ordered marker tag. It requires a unique stream entry and
424descriptor channel with the same ID, exported packets, and endpoints within the declared
425and exported audio. A rerun with the option refreshes an existing sheet even if it becomes empty.
diff --git a/docs/audio_config.md b/docs/audio_config.md
index 5c0f018bc..e3d6b1275 100644
--- a/docs/audio_config.md
+++ b/docs/audio_config.md
@@ -59,8 +59,10 @@ stride or a hard-coded stream offset.
59On the measured package: 59On the measured package:
60 60
61- **1,589 records**, 1,589 distinct ids, range `0xB422`–`0xBFC6`, 272,442.8 s total. 61- **1,589 records**, 1,589 distinct ids, range `0xB422`–`0xBFC6`, 272,442.8 s total.
62- **1,584 of 1,589** durations equal `AWC manifest duration / 2` within 0.01 s. The five exceptions 62- **1,584 of 1,589** durations matched the AWC stream length within 0.01 s. The original
63 are duplicate-title or placeholder hash collisions. 63 comparison halved the legacy manifest values to get the per-channel duration. The current
64 manifest reports the per-channel duration directly. The five exceptions are duplicate-title
65 or placeholder hash collisions.
64- **All 1,589** records map to an AWC stream id; the ids are the music streams exported by 66- **All 1,589** records map to an AWC stream id; the ids are the music streams exported by
65 `tools/awc_opus.py`. 67 `tools/awc_opus.py`.
66- The records are grouped by contiguous id ranges that follow station order. The same config also 68- The records are grouped by contiguous id ranges that follow station order. The same config also
@@ -69,7 +71,163 @@ On the measured package:
69 71
70It does **not** give per-track start offsets. Id order is not mix order, and the schedule-like 72It does **not** give per-track start offsets. Id order is not mix order, and the schedule-like
71structures in the config carry constant template fields, not cue times. A continuous radio mix must 73structures in the config carry constant template fields, not cue times. A continuous radio mix must
72be matched in the audio (`docs/music.md` if present, or the local radio-timing tools). 74be matched in the audio (a music page under docs/ if one is added, or the local radio-timing tools), except where
75the bank itself carries track markers: see [Marker events](#marker-events-awc-tag-0xbd) below.
76
77## Marker events (AWC tag `0xBD`)
78
79The cue times the config lacks are partly in the banks. AWC tag `0xBD` is a headerless array of
8016-byte cue records; [rsc8_audio.md](rsc8_audio.md#the-0xbd-cue-records) has the layout over all 420,168 tags of
81`audio.rpf`, counted by `tools/rsc8_audio.py`. This section is about the 945 of them in the streamed-music banks,
82which that count does not separate, and about what their records mark. The fields are the same four; the names
83used here (with the other page's in brackets) are type (`name`), value, time (`offset`) and flags (`extra`).
84
85In a streamed-music bank (one with a `0x48` descriptor, [audio.md](audio.md#streamed-music-0x48))
86the tag is the only tag of a channel's own stream-table entry: the entry whose id is the descriptor's channel id.
87The `0x48` stream itself (id 0) never has one. Those entries have no `0x76` format tag, so the check of the
88offsets against the `0x76` sample count on the other page does not reach them; here they are checked against
89the descriptor's length.
90
91| Offset | Size | Field | Confidence |
92|---:|---:|---|---|
93| 0 | 4 | type (u32 name hash) | measured: 17 distinct values over the music banks, table below |
94| +4 | 4 | value (f32; for six types a second u32 name hash) | measured per type; what the number means is a hypothesis except where the table says otherwise |
95| +8 | 4 | time (u32), 48 kHz frames per channel from the start of the stream | measured: never decreases inside a chunk and never passes the stream length (945 of 945); the unit follows from that, see below |
96| +12 | 4 | flags (u32) | measured: 0 in all 31,330 music events; meaning unknown |
97
98One event, with made-up values (type `0x11111111`, value 1234.0, time 96,000 = 2.0 s, flags 0):
99
100```text
10111 11 11 11 00 40 9a 44 00 77 01 00 00 00 00 00
102```
103
104**The time unit.** The stream length is the descriptor's interleaved sample count divided by the packet
105channel count (the record table's duration). Against that length the last event of a chunk is at a median
1060.997 of the stream and at 0.99 or more in 771 of 945 chunks, on 934 stereo and 11 mono streams, and it is
107never past the end. Interleaved samples would run to twice the length on the stereo streams, and
108milliseconds would stop at 2% of it, so the unit is per-channel frames at 48 kHz. All 3,116 descriptor
109channels declare 48,000 Hz.
110
111### Whole-corpus counts
112
113Every `ADAT` bank of `audio.rpf` (7,162 banks, 1,606,241 streams), split by whether the bank has a `0x48`
114descriptor:
115
116| | Streamed-music banks | Other banks |
117|---|---:|---:|
118| Banks | 3,008 | 4,154 |
119| Banks with a `0xBD` chunk | 938 | 1,019 |
120| `0xBD` chunks | 945 | 419,223 |
121| Events | 31,330 | 750,020 |
122| Chunk size not a multiple of 16 | 0 | 0 |
123| Events per chunk (min / median / max) | 1 / 23 / 1,435 | 1 / 2 / 3 |
124| Chunks where the time decreases | 0 | 0 |
125| Chunks whose last time is past the stream length | 0 of 945 | 0 of 419,222 |
126| Distinct types | 17 | 153 |
127| Events with non-zero flags | 0 | 418,184 |
128
129- 928 of the 2,958 one-channel music banks have a chunk, and 10 of the 50 multi-channel banks (17 chunks; in the
130 four banks with more than one, every channel holds the same events).
131- 923 of the 945 music chunks sit on a stream whose id is one of the 1,589 config records.
132- The streams with a chunk run from 25.5 s to 7,231.7 s (median 224.0 s; 17 are under 60 s). Of the 2,070
133 music banks without one, 1,713 are under 60 s and 106 are over 120 s: the short idents and stings
134 ([awc_shorts.md](awc_shorts.md)) mostly have no markers.
135- The finding that reported this chunk counted 873 of 2,684 banks, 16 types, 16,207 events of type
136 `0xE89AE78C` and 981 of type `0xA6D93246` in 849 banks. Those six numbers are exactly the streamed-music
137 banks 323 to 3,006 of the 3,008 in archive order, so that count seems to have left out the first 322 banks and
138 the last 2 (why is not known);
139 the layout it gives is the one measured here.
140
141### Event types in the music banks
142
143| Type | Events | Chunks | Chunks with one | Most in a chunk | Value |
144|---|---:|---:|---:|---:|---|
145| `0xE89AE78C` | 17,770 | 809 | 21 | 868 | integers 0 to 14,459 (314 distinct; 8, 4 and 16 are the most common) |
146| `0x74E06FAC` | 3,139 | 778 | 67 | 96 | 0.0 |
147| `0x08DBA0F8` | 2,969 | 755 | 0 | 4 | one of 4 name hashes |
148| `0x3A423FE8` | 2,322 | 681 | 51 | 81 | 0.0 |
149| `0x0C801D6C` | 1,561 | 656 | 250 | 45 | 0.0 |
150| `0xA6D93246` | 1,042 | 910 | 905 | 41 | integers 1,001 to 15,102 (865 distinct): a track number |
151| `0xDA8F5F53` | 835 | 804 | 801 | 16 | 0.0 |
152| `0x5D40B28D` | 825 | 797 | 795 | 15 | 0.0 |
153| `0xDA559149` | 393 | 22 | 0 | 161 | one of 2 name hashes |
154| `0x1DF219EC` | 202 | 1 | 0 | 202 | the same 2 name hashes |
155| `0x77EDD3A2` | 109 | 1 | 0 | 109 | the same 2, and a third once |
156| `0x994EE645` | 98 | 1 | 0 | 98 | the same 2 name hashes |
157| `0xCCB465D1` | 39 | 1 | 0 | 39 | the same 2 name hashes |
158| `0x00000000` | 15 | 13 | 12 | 3 | 0.0 |
159| `0x7A495DB3` | 6 | 6 | 6 | 1 | 113.0, 131.0 or 158.0 |
160| `0x2AC28E32` | 4 | 4 | 4 | 1 | 0.0 |
161| `0x12067E90` | 1 | 1 | 1 | 1 | 0.0 |
162
163The types are `joaat` name hashes (`tools/audio_config.py`, the helper the record table uses). Hashing plain
164lowercase words: the seven the finding proposed all hit (7 of 7), and 89 further words tried here gave two
165more type hits, so 9 of the 16 non-zero types resolve and 7 do not; type 0 is the hash of the empty string.
166The value hashes of the six hash-valued types are 7 distinct values, and 6 of them resolve the same way; the
167seventh occurs once. This page keeps to the hashes: the words are generic marker labels, none is a track or
168station name, and the tool prints none.
169
170### Track markers (`0xA6D93246`)
171
172The type is the hash of `trackid`, one of the four names [rsc8_audio.md](rsc8_audio.md#the-0xbd-cue-records) gives.
173Measured:
174
175- 905 chunks carry exactly one, at time 0 in 900 and within 0.35 s of it in the other five. 35 chunks carry none.
176- Five chunks carry 22, 24, 25, 25 and 41, on streams of 2,386.0 s, 3,004.7 s, 5,014.1 s (two streams with
177 different ids and different other events) and 7,231.7 s. These are the long mixes; the first marker is at
178 0.0 s in four and at 0.9 s in one, and consecutive markers are 3.3 s to 325.6 s apart.
179- 64 of the 137 markers in those five chunks have the `value` of a one-marker bank (32 of 41, 22 of 22,
180 10 of 24, 0 of 25, 0 of 25), so the value links a stretch of a mix to the standalone bank of the same track
181 number. 101 values occur in more than one chunk.
182
183Not confirmed:
184
185- **That a marker is the audible start of the track.** The finding checked that against the decoded audio
186 (most markers within 3 s of a strong spectral change); that was not repeated here.
187- **The length of a stretch.** For the 64 linked markers, the stretch up to the next marker (or the end of the
188 stream) is within 1 s of the linked bank's length for none and within 5 s for 6; it is shorter for 59, at a
189 median 0.63 of it. Without the link, 41 of the 137 stretches are within 0.05 s of *some* config duration, but
190 so are 47 of 137 stretches lengthened by a random 20 to 40 s, so that is chance. A mix plays part of a
191 track, or the marker is a cue and not a cut: the record table's durations do not give the mix positions,
192 and the markers do not come from them.
193- What the other types mark, and the meaning of their values.
194
195So the statement above stands for the config, and for the mixes without markers. For the five marked mixes a
196runtime can read the track boundaries and track numbers from the bank.
197
198### Other banks
199
200The 419,223 tags outside the music banks are the ones [rsc8_audio.md](rsc8_audio.md#the-0xbd-cue-records)
201describes, and the counts here agree with that page where they overlap (945 + 419,223 = 420,168 tags,
20231,330 + 750,020 = 781,350 records, 17 + 153 types with three in both groups = 167, 363,166 records with
203flags 0). Two things it does not have:
204
205- In the 418,838 records of type `0xE5C74063` the value is an integer 0.0 to 6.0 and the flags field equals
206 that integer (418,838 of 418,838). These are the only non-zero flags in the archive.
207- The 330,756 records of type `0xDBEDD43C` are all at time 0, with integer values 33 to 1,467.
208
209The three types found in both groups are `0x00000000`, `0x0C801D6C` and `0x7A495DB3`.
210
211### Reproduce
212
213```powershell
214python -I tools/awc_markers.py <game>\audio.rpf --out <temp>\awc_markers.json
215```
216
217`tools/awc_markers.py` walks the archive for `ADAT` banks with the header parser of `tools/rsc8_audio.py`
218(the same 7,162 banks), jumps over each parsed bank and reads only the `0xBD` chunks and the stream lengths:
219under a minute for the 28.5 GB archive on an NVMe drive (10 s once the file is cached). It prints the two
220groups and their 20 most frequent types; the JSON has every type with its events, chunks, value range and,
221for a type with at most 8 distinct values, the value bits. It also takes one `.awc` bank or a directory of
222them. The report is counts, hashes and numeric ranges; it has no names and no audio.
223`tests/test_awc_markers.py` builds its banks by hand.
224
225Not reproduced by the tool: the track-marker cross-checks (the link by `value`, the stretch lengths, the
226comparison with the config durations) and the name-hash trials. They joined the decoded events with
227`audio_config.py --join --json` in a local script that is not committed, because it works on per-event rows:
228link = equal `value`, stretch = next marker time minus this one, tolerances as stated.
229be matched in the audio itself; no tool in this repository does that yet. The station graphs in
230[radio_stations.md](radio_stations.md#why-this-is-not-a-start-table) are not a start table either.
73 231
74## Tool 232## Tool
75 233
@@ -92,7 +250,8 @@ python -I tools/audio_config.py <carve dir or blob> [--json] [--names FILE] [--j
92 `{records, summary}`. 250 `{records, summary}`.
93 251
94`--names` is optional. The package's debug name stream and the localization credits are local game 252`--names` is optional. The package's debug name stream and the localization credits are local game
95files; nothing from them is committed. 253files; nothing from them is committed. Its strings are read as latin-1 bytes, the same bytes `joaat`
254hashes, so a title with an accented character resolves to the hash a record carries.
96 255
97## Limits 256## Limits
98 257
@@ -102,7 +261,8 @@ files; nothing from them is committed.
102- The first ~19.5 MiB bound is specific to this package. A different build can put the AWC start at 261- The first ~19.5 MiB bound is specific to this package. A different build can put the AWC start at
103 another offset; `rpf9_carve.py --until-adat` finds it (the first AWC bank whose header parses). 262 another offset; `rpf9_carve.py --until-adat` finds it (the first AWC bank whose header parses).
104- No start offsets, no play order and no playlists are stored here. The config's station content 263- No start offsets, no play order and no playlists are stored here. The config's station content
105 lists reference records, but the mix order is assembled at runtime. 264 lists reference records, but the mix order is assembled at runtime. Five long mixes carry track
265 markers in their own bank (tag `0xBD`, above).
106- A marker is reported only when at least 20 bytes follow it in the scanned input, as before. 266- A marker is reported only when at least 20 bytes follow it in the scanned input, as before.
107- `--join` memory: at most two read blocks of input (`JOIN_BLOCK_BYTES`, 1 MiB each) plus a 267- `--join` memory: at most two read blocks of input (`JOIN_BLOCK_BYTES`, 1 MiB each) plus a
108 24-byte carry, one name and start offset per part, and the record list. The non-joined scan 268 24-byte carry, one name and start offset per part, and the record list. The non-joined scan
diff --git a/docs/audio_hal_exe_calls.md b/docs/audio_hal_exe_calls.md
new file mode 100644
index 000000000..c04943c7d
--- /dev/null
+++ b/docs/audio_hal_exe_calls.md
@@ -0,0 +1,79 @@
1# The audio coprocessor, texture layout and DirectStorage imports: how the retail executable calls them (RT-5)
2
3`gta6rt --dry-run` leaves 30 of `game_scarlett_master.exe`'s imports unimplemented
4(the section on the retail executable in `docs/runtime_imports.md`, #6715). Eight are `xmem.dll` and `d3d12_xs.dll` and are
5in [`xmem_exe_calls.md`](xmem_exe_calls.md). The other 22 are the audio coprocessor (`AcpHal.dll`, `xapu.dll`,
6`chad.dll`: 19), the texture layout library (`xg_xs.dll`: 2) and DirectStorage (`XCRDAPI.dll`: 1). No public
7documentation of the audio functions exists, so this page records, from the file alone, how the executable calls them:
8how many call sites each has, the constants those sites pass, and how each site uses the result. Nothing was run, and no
9code or data of the executable is quoted. Measured at `main` `1cc6e3c1` with `tools/import_call_sites.py`; the argument
10registers before each call were read by hand.
11
12```powershell
13python -I tools/import_call_sites.py game_scarlett_master.exe --dll AcpHal.dll --dll xapu.dll --dll chad.dll `
14 --dll xg_xs.dll --dll XCRDAPI.dll
15```
16
17The counts are direct calls and tail jumps to each import's thunk (22 imports, 36 sites; the tool's own caveats apply).
18Every one of the 22 has at least one site, so none is dead code the linker kept.
19
20## `AcpHal.dll` (9 imports, 16 sites)
21
22| Import | Sites | What the sites show |
23|---|---:|---|
24| `AcpHalCreate` | 1 | first argument is the address of a global that is read right after the call (an out parameter); second is 0. The result is tested for a negative value and a negative one jumps to a cleanup path |
25| `AcpHalAllocateShapeContexts` | 1 | first argument is the address of another global, read afterwards; the result is tested for a negative value like the one above |
26| `AcpHalReleaseShapeContexts` | 1 | called with a handle read from the first global; result not used |
27| `ApuCreateHeap` | 1 | second argument `0x226e00`; the result is tested for a negative value |
28| `ApuAlloc` | 1 | second argument `0`, third a computed value, fourth `0x800`; the result is not used at the site |
29| `ApuFree` | 1 tail jump | no call, only a tail jump from a wrapper |
30| `ApuIsVirtualAddressValid` | 4 | second argument `0x40`, `0x80`, `0x800`, `0x800`; the result byte is tested |
31| `ApuMapVirtualAddress` | 4 | the same pointer and the same four constants as `ApuIsVirtualAddressValid`, one after the other; the 32-bit result is stored in a per-entry record |
32| `ApuMapApuAddress` | 2 | the argument is a 32-bit value read from those records; the result is tested for null, so it is a pointer |
33
34The four `ApuIsVirtualAddressValid`/`ApuMapVirtualAddress` pairs and the two `ApuMapApuAddress` calls are consistent with
35a title that checks that a CPU buffer can be seen by the coprocessor, takes its coprocessor-side 32-bit address, and later
36turns such an address back into a pointer. That is an inference from the shapes; the meaning of the sizes is unmeasured.
37
38## `xapu.dll` (5 imports, 8 sites) and `chad.dll` (5 imports, 5 sites)
39
40| Import | Sites | What the sites show |
41|---|---:|---|
42| `XApuConnect` | 1 | no argument loaded in the lines before the call was read |
43| `XApuDisconnect` | 1 | first argument a handle read from a global, second `0x20`; the global is set to 0 right after |
44| `XApuEnqueueCommand` | 4 | the same global handle, a pointer to a stack-built command, and 0 |
45| `XApuDequeueResult` | 1 | the same global handle and a second argument; the result is tested for a negative value |
46| `XApuGetResultCount` | 1 | no argument read |
47| `XDspConnectWithMaximumStreamLimit` | 1 | fourth argument `0x80`; the result is compared with 0 and turned into a boolean that is true for 0 |
48| `XDspActivate` | 1 | the result is tested |
49| `XDspSubmitCommand` | 1 | two arguments, both taken from registers; not read further |
50| `XDspDeactivate`, `XDspDisconnect` | 1 tail jump each | no call |
51
52`XApuEnqueueCommand` and `XApuDequeueResult` share one handle global, which `XApuDisconnect` clears: a command queue
53with a result queue, connected once and torn down once. How `chad.dll`'s handle relates to it is not read.
54
55## `xg_xs.dll` and `XCRDAPI.dll`
56
57| Import | Sites | What the sites show |
58|---|---:|---|
59| `XGCreateTextureComputer` | 4 | argument shapes differ between sites; not read further |
60| `XGSuggestSwizzleMode` | 2 | not read further |
61| `DStorageGetFactory` | 1 | the first argument is the address of a constant (an interface id) and the second the address of a global; the global is loaded afterwards and tested for null |
62
63`DStorageGetFactory` has the shape of the public DirectStorage function `DStorageGetFactory(REFIID, void**)`. #4348 is an
64open pull request for it.
65
66## What the executable already does about a failure
67
68Four of the calls above have a branch for a negative result: `AcpHalCreate`, `AcpHalAllocateShapeContexts`,
69`ApuCreateHeap` and `XApuDequeueResult`. An unimplemented import under `LEONIDA_UNIMPLEMENTED=log` returns 0, so a caller
70that tests for a negative result sees success with its outputs unset; under `fail` only imports `classify_import`
71knows to return an `HRESULT` get `E_NOTIMPL`, and none of these four is on that list (it names only functions the public
72documentation describes). So today neither mode makes the executable take its own failure path for the audio hardware.
73Whether the title survives that path, or needs the coprocessor, is **unmeasured**: it takes a run to find out, and the
74first run reported in #6603 stops earlier, in `D3D12ConfigureVirtualMemoryX`.
75
76## What this does not show
77
78Nothing here says that the boot reaches these calls, in what order, or what the commands and results carry. A site is code
79that can call; the first trace (`--trace`, `unimplemented_call` events) is the signal for which of them run.
diff --git a/docs/awc_shorts.md b/docs/awc_shorts.md
index a7b439200..dc8d59417 100644
--- a/docs/awc_shorts.md
+++ b/docs/awc_shorts.md
@@ -9,6 +9,9 @@ python -I tools\awc_shorts.py <bank.awc | directory> <out> `
9 --min-seconds 5 --max-seconds 60 --jobs 8 9 --min-seconds 5 --max-seconds 60 --jobs 8
10``` 10```
11 11
12If two banks would share an output folder (for example `clip.awc` and `clip.AWC`), the scan is refused
13before writing clips or replacing the catalog. Rename a bank or export the two to separate output roots.
14
12The output is `<out>\<bank>\<stream id>.ogg` plus `<out>\shorts.csv` with bank, stream id, duration, 15The output is `<out>\<bank>\<stream id>.ogg` plus `<out>\shorts.csv` with bank, stream id, duration,
13packet channel count, packet count and relative path. For a directory scan, `<bank>` keeps the 16packet channel count, packet count and relative path. For a directory scan, `<bank>` keeps the
14path relative to the source directory, without the `.awc` extension. For example, a nested 17path relative to the source directory, without the `.awc` extension. For example, a nested
diff --git a/docs/boot.md b/docs/boot.md
index 4738b9a73..16cbb80ee 100644
--- a/docs/boot.md
+++ b/docs/boot.md
@@ -1,8 +1,12 @@
1# First boot: the runbook and the two traces 1# First boot: the runbook and the two traces
2 2
3**Status: prepared, not yet run against the retail executable.** The package in the repository's test corpus does 3**Status: `--dry-run` and `--init` have been run on the retail executable; `--run` has not.** The package in the
4not contain `game_scarlett_master.exe` (RT-5), so this page is the procedure and the trace tool for the day it 4repository's test corpus does not contain `game_scarlett_master.exe` (RT-5); the dry-run on an executable supplied
5arrives. Nothing here quotes game data; a real trace stays on the player's machine. 5separately maps it and leaves 30 imports unimplemented, and `--init` runs its TLS callbacks and the package DLLs'
6`DllMain`s without an exception
7([`runtime_imports.md`](runtime_imports.md#the-retail-executable-rt-5)), so this page is still the procedure and the
8trace tool for the first boot. The executable's `ws2_32.dll` imports bind to the host's, so run `--run` with the
9network off. Nothing here quotes game data; a real trace stays on the player's machine.
6 10
7## 1. What the first boot produces 11## 1. What the first boot produces
8 12
@@ -36,14 +40,15 @@ $exe = "C:\path\to\game_scarlett_master.exe"
36$pkg = "C:\path\to\the\package" 40$pkg = "C:\path\to\the\package"
37$trace = Join-Path $env:TEMP boot.jsonl 41$trace = Join-Path $env:TEMP boot.jsonl
38$log = Join-Path $env:TEMP d3d12.log 42$log = Join-Path $env:TEMP d3d12.log
39.\runtime\build\gta6rt.exe --run $exe --game-dir $pkg --trace $trace --trace-d3d12 2> $log 43.\runtime\build\gta6rt.exe --run $exe --game-dir $pkg --trace $trace --trace-d3d12 2>&1 |
44 ForEach-Object { $_.ToString() } |
45 Out-File -LiteralPath $log -Width 4096 -Encoding utf8
40python -I tools\boot_trace.py $trace --d3d12 $log 46python -I tools\boot_trace.py $trace --d3d12 $log
41``` 47```
42 48
43Windows PowerShell 5.1 writes `2>` as UTF-16LE; the tool names that file instead of parsing it. Use 49The capture pipeline writes each message as text to avoid PowerShell 5.1 wrapping the first stderr record at a
44`2>&1 | Out-File -Encoding utf8 $log` there, or PowerShell 7, which defaults to UTF-8. The tool strips the BOM that 50narrow output width. The tool also reads existing UTF-16LE logs saved with `2>` in PowerShell 5.1 and recognizes
455.1 writes with `utf8`, and accepts the `program.exe : ` prefix 5.1 puts in front of the first stderr line when it 51the `program.exe : ` prefix on the first stderr line.
46turns it into an error record, so that call is not lost. `cmd /c` writes the lines unchanged.
47 52
48Linux under Wine (a cross build made with xwin, or the `runtime-windows` artifact; the backend must be Vulkan): 53Linux under Wine (a cross build made with xwin, or the `runtime-windows` artifact; the backend must be Vulkan):
49 54
@@ -67,6 +72,10 @@ Useful switches:
67 printing the caller's `module+RVA` and the argument registers (with a debugger attached it breaks instead). Start 72 printing the caller's `module+RVA` and the argument registers (with a debugger attached it breaks instead). Start
68 with `log`, then use `stop` to pin the first blocker and `fail` to see how the game's own failure path reacts. 73 with `log`, then use `stop` to pin the first blocker and `fail` to see how the game's own failure path reacts.
69 This switch covers imports only; it does not affect the D3D12 outcomes. 74 This switch covers imports only; it does not affect the D3D12 outcomes.
75* `LEONIDA_SKIP_INT3=1` (with `--trace`) steps over each int3 in guest code and logs it once per address as an
76 `int3_skipped` event, so a boot can be followed past soft asserts (an int3 followed by code that carries on).
77 Diagnostic only: a correct run reaches none, so each skipped address is a finding, not a fix. A failed guest file
78 open is always traced as `file_open_failed` (path, error, caller) when `--trace` is on.
70* `LEONIDA_VK_VALIDATION=1` enables the Khronos validation layer with the Vulkan backend (startup overhead; it is a 79* `LEONIDA_VK_VALIDATION=1` enables the Khronos validation layer with the Vulkan backend (startup overhead; it is a
71 diagnostic). 80 diagnostic).
72* `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` when MSI Afterburner or OBS is installed; their 81* `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` when MSI Afterburner or OBS is installed; their
@@ -84,20 +93,31 @@ Read the startup trace first; the first event that is not the expected one is th
84 deliberate failure in `runtime/shims/registry.cpp`; rerun with `LEONIDA_UNIMPLEMENTED=stop` to halt at the first 93 deliberate failure in `runtime/shims/registry.cpp`; rerun with `LEONIDA_UNIMPLEMENTED=stop` to halt at the first
85 remaining blocker. 94 remaining blocker.
863. **`tls_callback` / `dllmain`** — a failed DllMain, or a TLS callback that faults, usually points at the CRT or 953. **`tls_callback` / `dllmain`** — a failed DllMain, or a TLS callback that faults, usually points at the CRT or
87 TLS index; the loader's own TLS is checked by `run_tiny_game_tls`. 96 TLS index. The summary shows the address and phase of the last observed TLS callback
97 (`last_tls_callback` in JSON). The loader records it before invoking the callback, so the record gives no
98 completion result. The loader's own TLS is checked by `run_tiny_game_tls`.
884. **`exception`** — code, `at`, access/address and the stack frames. The loader's vectored handler only records, 994. **`exception`** — code, `at`, access/address and the stack frames. The loader's vectored handler only records,
89 so the process behaviour is the same with or without the trace. 100 so the process behaviour is the same with or without the trace. When the report reaches `--limit`, it reserves
101 the final slot for the last observed exception. The trace also includes handled exceptions, so the last
102 observation alone does not establish what caused the run to stop.
905. **`exit` / `error`** — a clean exit is not a correct frame; continue to the D3D12 trace. 1035. **`exit` / `error`** — a clean exit is not a correct frame; continue to the D3D12 trace.
916. **D3D12 trace** — the `failed`, `unsupported` and `refused` lines name the method. Compare its position with 1046. **D3D12 trace** — the `failed`, `unsupported`, `refused` and `partial` lines name the method. A `partial`
92 the public SDK vtable; an unknown slot is expected until the executable names it (Q2, Q6). The `[rt]` lines in 105 submission ran the supported commands from a list. The runtime's `[rt]` diagnostic names the command it left out.
93 the same log carry what the trace does not: the 24 device words, feature ids, warnings. 106 Compare the method's position with the public SDK vtable. An unknown slot is expected until the executable names it
107 (Q2, Q6). The `[rt]` lines in the same log carry the 24 device words, feature IDs and warnings.
108 The summary expects `#1` first, then one more than the last observed number. It counts each mismatch once and
109 shows up to `--limit` expected/observed pairs. A break can reflect an excerpt, restart, duplicate or reordered
110 line; it is not a count of missing calls.
947. **First frame** — after the device and queues, the first `CreateRootSignature`, PSO, `Draw*` and `PresentX` (or 1117. **First frame** — after the device and queues, the first `CreateRootSignature`, PSO, `Draw*` and `PresentX` (or
95 DXGI) calls are the frame's critical path. The layer's M0–M4 tests already exercise the offscreen parts; the 112 DXGI) calls are the frame's critical path. The layer's M0–M4 tests already exercise the offscreen parts; the
96 present slots are the part that cannot be measured from the package alone. 113 present slots are the part that cannot be measured from the package alone.
97 114
98The trace tool prints the first call per method and the `unsupported`/`failed`/`refused` lists; `--json` gives the 115The trace tool prints the first call per method and the `unsupported`/`failed`/`refused`/`partial` lists. The `--json`
99same summary for a script. Share that summary's **counts and error classes**, not the trace file or its debug 116option gives the same summary for a script. Share only the summary's **counts and error classes**.
100strings. 117
118If startup stops before the first D3D12 call, the combined command still prints the startup report. A missing
119or invalid requested trace is reported on stderr and sets exit code 2. In a partial JSON report that section
120is `null`; if neither input yields a report, stdout is empty.
101 121
102## 4. The open questions, and the trace signal for each 122## 4. The open questions, and the trace signal for each
103 123
@@ -106,7 +126,7 @@ the de-duplicated 1–22. It maps each question to the event to look for; it doe
106 126
107| # | Question | Signal in the first trace | 127| # | Question | Signal in the first trace |
108|---|---|---| 128|---|---|---|
109| 1 | `D3D12XboxCreateDevice` 24-word params and flags | first `D3D12XboxCreateDevice` in the D3D12 trace; the shim prints the 24 words only when `--trace-d3d12` is off, so run once without it (or grep `^\[rt\]`); accept unknown flags | 129| 1 | `D3D12XboxCreateDevice` 24-word params and flags | first `D3D12XboxCreateDevice` in the D3D12 trace; the shim prints the 24 words as an `[rt]` line in the same log, with or without `--trace-d3d12` (grep `^\[rt\]`); accept unknown flags |
110| 2 | Xbox device/heap/queue/command-list slots | queue, fence and allocator method names in the D3D12 trace; device slots past the PC vtable print an `[rt] d3d12_xs: device slot …` line instead and record nothing; compare with the SDK vtable | 130| 2 | Xbox device/heap/queue/command-list slots | queue, fence and allocator method names in the D3D12 trace; device slots past the PC vtable print an `[rt] d3d12_xs: device slot …` line instead and record nothing; compare with the SDK vtable |
111| 3 | Root signature → `s0..s31` | `CreateRootSignature`, `SetGraphicsRootSignature`, then the shader's user-SGPR reads; mask `0x03000000` on a copy | 131| 3 | Root signature → `s0..s31` | `CreateRootSignature`, `SetGraphicsRootSignature`, then the shader's user-SGPR reads; mask `0x03000000` on a copy |
112| 4 | Descriptor bytes and heap increments | first `CreateShaderResourceView`/`CreateSampler` and the first draw; dump the heap bytes and compare with the T#/S# parser | 132| 4 | Descriptor bytes and heap increments | first `CreateShaderResourceView`/`CreateSampler` and the first draw; dump the heap bytes and compare with the T#/S# parser |
diff --git a/docs/buffer_formats.md b/docs/buffer_formats.md
new file mode 100644
index 000000000..6b45f1821
--- /dev/null
+++ b/docs/buffer_formats.md
@@ -0,0 +1,177 @@
1# Typed buffer formats: every GFX10 code a V# or MTBUF can name
2
3What `buffer_load_format_*`, `buffer_store_format_*` and `tbuffer_load_format_*` do for each GFX10 buffer data format
4(V# word 3 `FORMAT` [18:12], or the `format:` modifier of an MTBUF instruction), measured on a Radeon 880M and on a real RDNA2
5(gfx1036) and held against the translator. The contract row is "Typed buffer formats" in [design.md](design.md); the code is
6`Gen.FORMATS`, `Gen.decode_format` and `Gen.encode_format` in `tools/rdna2spirv.py`; the oracle is
7`tools/buffer_format_fuzz.py`.
8
9**Where it was measured.** Locally only on the Radeon 880M (gfx1150, RDNA3.5, GFX11), which numbers its formats differently
10(8_8_8_8_UNORM is 56 on GFX10 and 42 on GFX11), so every format there is mapped by name (`GFX11_CODES` in the tool, taken from
11what the AMD assembler encodes for `format:[BUF_FMT_<name>]`). @AwkGrep256 then ran the same tool on a real **RDNA2, gfx1036**
12(Ryzen 7 9800X3D iGPU, Linux DRM backend of #1265, native GFX10 numbers; see the comment on
13[#2022](https://github.com/ItsNotRexed/Leonida/pull/2022)): 1,330,469 elements of the 63 formats GFX11 has with 0 mismatches,
14and 199,144 elements of the 14 codes only GFX10 has with 0 mismatches. The 880M and gfx1036 agree on everything below. The
15console's own gfx1013 (GFX10.1) is the same generation but not the same chip, and was not measured; nor were the d16 forms.
16
17## Which codes there are
18
19GFX10's `FORMAT` is 7 bits, so a buffer can carry codes 1..77 (the table in `tools/gfx10_formats.json` goes to 292
20because images use 9 bits; 128 and up are image-only: sRGB, BC, depth, 5_6_5, 1_5_5_5, 5_5_5_1, 4_4_4_4, 5_9_9_9, 6E4).
21There are no 5_6_5-style formats for buffers. **All 77 are in `Gen.FORMATS`**: every f32/u32/i32 code, the 8/16-bit and
228_8/16_16/8_8_8_8/16_16_16_16 families in all of UNORM, SNORM, USCALED, SSCALED, UINT, SINT (and FLOAT for 16-bit), the
2310_11_11 (30..36) and 11_11_10 (37..43) families (only the FLOAT ones exist on GFX11) and the 10_10_10_2 (44..49) and
242_10_10_10 (50..55) families in all six numeric formats. Codes outside the table (0, 78..127) decode to 0 and store nothing.
25
26The 14 codes GFX11 lacks (30..35, 37..42, 46, 47) could not be measured on the 880M; the layout and conversions of the
27model were validated on gfx1036. The GFX11-only look of a code number is never relied on: the translator reads the GFX10
28numbering, as the console does.
29
30## Names and bit order
31
32Names list the component widths from the top bit down, so the **last** number is `x` in bit 0: `2_10_10_10` (50) is
33R10G10B10A2 with x in bits 9:0 and a 2-bit alpha on top, `10_10_10_2` (44) has a 2-bit x. `10_11_11_FLOAT` (36) is x =
3411 bits [10:0], y = 11 bits [21:11], z = 10 bits [31:22]; `11_11_10_FLOAT` (43) is x = 10 bits, y and z 11 bits each.
35Both GPUs confirmed all of these.
36
37## Loads (measured)
38
39Every result word of an `xyzw` load of all formats the GPU has, through a V# (`DST_SEL` = XYZW) and through tbuffer's own format
40(with a V# that names 32_FLOAT), equals the model below on both GPUs. Per format: every value of every field up to 12 bits (and all
4165,536 half floats), edge values (0, 1, max, signed min and its neighbours), random values above that, and random bytes
42past the element.
43
44| Format class | Result |
45|---|---|
46| UNORM | correctly rounded f32 of x / (2ⁿ−1) |
47| SNORM | correctly rounded x / (2ⁿ⁻¹−1); the most negative code is −1.0 |
48| USCALED / SSCALED | the integer, as a float, **not** divided (exact: at most 16 bits) |
49| UINT / SINT | the zero-extended / sign-extended integer, in the integer register |
50| 16_FLOAT | the half as f32; a NaN keeps its sign and payload (`0x7C01` gives `0x7F802000`, **not quieted**) |
51| 10_11_11 / 11_11_10 FLOAT | unsigned float, 5 exponent bits, bias 15, 6 (11-bit field) or 5 (10-bit field) mantissa bits, no sign. Exponent 0: m·2⁻²⁰ (m·2⁻¹⁹ for 5 bits), a denormal that is **kept**. Exponent 31: infinity, or a NaN whose payload is the mantissa shifted up (`0x7C1` gives `0x7F820000`), unquieted |
52| channels the format lacks | through a V#: component *c* mod *n* repeats (the translator's existing rule, SHADER-86, now also measured on gfx1150); through tbuffer: 0 (the instruction names `X000`, `XY00`, `XYZ0` or `XYZW` by the format's component count, and the V# `DST_SEL` is ignored) |
53
54## Stores (measured)
55
56`buffer_store_format_xyzw` and `_xy` (and the tbuffer forms) of every format into a buffer pre-filled with `0xDEAD0000`, the
57whole 16 bytes compared, so a byte written outside the element shows up.
58
59| Format class | Result |
60|---|---|
61| UINT | saturates to the field width (min(x, 2ⁿ−1)) |
62| SINT | saturates to the signed range of the field |
63| UNORM | clamp to [0, 1], then the **exact** product x·(2ⁿ−1) rounded to nearest even; a NaN stores 0 |
64| SNORM | clamp to [−1, 1], then the exact product x·(2ⁿ⁻¹−1) rounded to nearest even, **except the 2-bit field** (10_10_10_2 and 2_10_10_10 SNORM), where a half rounds away from zero (0.5 gives 1, −0.5 gives −1; nearest even would give 0) |
65| **USCALED / SSCALED** | **converted as UNORM / SNORM**: storing 200.0 into 8_USCALED writes 255, storing 0.5 into 8_SSCALED writes 64. The SCALED formats are for loads; a store does not undo the "not divided" |
66| 16_FLOAT, 10_11_11 / 11_11_10 FLOAT | **round toward zero** (not nearest): 0.49999997 gives `0x37FF`, not `0x3800`. A value too large for the format gives the **largest finite** value, not infinity: 65520.0 and 1e30 give `0x7BFF` for halves; only a real +infinity stores infinity. Denormals are produced. The unsigned floats store 0 for every negative number, −0 and −infinity |
67| NaN into a float format | stays a NaN: the sign (halves only) and the top mantissa bits of the payload, or 1 when those are all zero (`0x7F800001` gives `0x7C01`) |
68| a format with two components | **`buffer_store_format_*` through a V# with the identity selectors (XYZW) takes channels (x, w), not (x, y)**: `8_8_UINT` of (0x11, 0x22, 0x33, 0x44) writes 0x11, 0x44, and `buffer_store_format_xy` into it writes 0x11 and 0 (w is not supplied). **With the selectors the runtime gives a two-component format (X, Y, 0, 1, `gfx10_descriptors.h`) it takes (x, y)**, as the narrow-integer fixtures measured on gfx1036 (`test_buffer_format_narrow_int.py`). On the 880M the second component is y exactly when DST_SEL_Y is Y and DST_SEL_Z is a constant (XY01, XY0W, XY00), and w for the other thirteen selector sets tried (XYZW, XYZ1, XYZ0, X001, X0ZW, ...). **`tbuffer_store_format_*` takes (x, y)** whatever the V# says. 1-, 3- and 4-component formats take x, xyz and xyzw (`_xy` into them: x, y, then 0). The translator follows this rule (`Gen.format_encode_call`); d16 forms and `_xyz` into a two-component format were not measured. Selectors with a swapped pair, e.g. YXZW, reorder the channels in ways that are not modelled |
69
70`DST_SEL` also reorders a store's channels on the 880M in a way that is not a plain swizzle (`xzwy` stores `zxyw`); only
71the identity and the B/R swap (`zyxw`, the 8_8_8_8 and 2_10_10_10 UNORM case the translator already handles) are modelled.
72
73## What ran
74
75`python -I tools/buffer_format_fuzz.py --oracle hw --budget 40 --seed 7` (loads and stores, V# and tbuffer, stores as `_xyzw` and
76`_xy` with a different value in every register, and for the two-component formats once more with the runtime's X,Y,0,1 selectors):
77
78- **Radeon 880M (gfx1150):** 1,390,400 validated elements, 0 mismatches (63 formats; the table below).
79- **Radeon (gfx1036, RDNA2), by @AwkGrep256 on the older tool that counted the (x, w) routing apart:** 1,330,469 validated
80 and 26,523 known-difference elements, 0 mismatches, i.e. 1,356,992 elements all equal to this model; and
81 199,144 elements of the 14 GFX10-only codes (`--formats 30,31,32,33,34,35,37,38,39,40,41,42,46,47`), 0 mismatches.
82- `--negative-control` shows the harness is not vacuous (a kernel whose V# names another format differs on all but one or
83 two elements of five formats). `--self-test` checks the model without a GPU.
84
85| Code | Format | Translator | V# loads | tbuffer loads | V# stores (xyzw and xy) | tbuffer stores (xyzw and xy) |
86|---|---|---|---|---|---|---|
87| 1 | `8_UNORM` | before | 338 | 338 | 3,024 | 3,024 |
88| 2 | `8_SNORM` | before | 338 | 338 | 3,024 | 3,024 |
89| 3 | `8_USCALED` | added | 338 | 338 | 1,864 | 1,864 |
90| 4 | `8_SSCALED` | added | 338 | 338 | 1,864 | 1,864 |
91| 5 | `8_UINT` | added | 338 | 338 | 1,688 | 1,688 |
92| 6 | `8_SINT` | added | 338 | 338 | 1,688 | 1,688 |
93| 7 | `16_UNORM` | before | 606 | 606 | 3,024 | 3,024 |
94| 8 | `16_SNORM` | before | 606 | 606 | 3,024 | 3,024 |
95| 9 | `16_USCALED` | added | 606 | 606 | 1,864 | 1,864 |
96| 10 | `16_SSCALED` | added | 606 | 606 | 1,864 | 1,864 |
97| 11 | `16_UINT` | added | 606 | 606 | 1,688 | 1,688 |
98| 12 | `16_SINT` | added | 606 | 606 | 1,688 | 1,688 |
99| 13 | `16_FLOAT` | before | 65,618 | 65,618 | 1,864 | 1,864 |
100| 14 | `8_8_UNORM` | before | 594 | 594 | 3,024 | 3,024 |
101| 15 | `8_8_SNORM` | before | 594 | 594 | 3,024 | 3,024 |
102| 16 | `8_8_USCALED` | added | 594 | 594 | 1,864 | 1,864 |
103| 17 | `8_8_SSCALED` | added | 594 | 594 | 1,864 | 1,864 |
104| 18 | `8_8_UINT` | added | 594 | 594 | 1,688 | 1,688 |
105| 19 | `8_8_SINT` | added | 594 | 594 | 1,688 | 1,688 |
106| 20 | `32_UINT` | before | 357 | 357 | 1,688 | 1,688 |
107| 21 | `32_SINT` | before | 357 | 357 | 1,688 | 1,688 |
108| 22 | `32_FLOAT` | before | 357 | 357 | 1,864 | 1,864 |
109| 23 | `16_16_UNORM` | before | 1,130 | 1,130 | 3,024 | 3,024 |
110| 24 | `16_16_SNORM` | before | 1,130 | 1,130 | 3,024 | 3,024 |
111| 25 | `16_16_USCALED` | added | 1,130 | 1,130 | 1,864 | 1,864 |
112| 26 | `16_16_SSCALED` | added | 1,130 | 1,130 | 1,864 | 1,864 |
113| 27 | `16_16_UINT` | before | 1,130 | 1,130 | 1,688 | 1,688 |
114| 28 | `16_16_SINT` | added | 1,130 | 1,130 | 1,688 | 1,688 |
115| 29 | `16_16_FLOAT` | before | 131,154 | 131,154 | 1,864 | 1,864 |
116| 36 | `10_11_11_FLOAT` | added | 5,202 | 5,202 | 1,864 | 1,864 |
117| 43 | `11_11_10_FLOAT` | added | 5,202 | 5,202 | 1,864 | 1,864 |
118| 44 | `10_10_10_2_UNORM` | before | 3,158 | 3,158 | 3,224 | 3,224 |
119| 45 | `10_10_10_2_SNORM` | added | 3,158 | 3,158 | 3,224 | 3,224 |
120| 48 | `10_10_10_2_UINT` | added | 3,158 | 3,158 | 1,688 | 1,688 |
121| 49 | `10_10_10_2_SINT` | added | 3,158 | 3,158 | 1,688 | 1,688 |
122| 50 | `2_10_10_10_UNORM` | before | 3,158 | 3,158 | 3,224 | 3,224 |
123| 51 | `2_10_10_10_SNORM` | added | 3,158 | 3,158 | 3,224 | 3,224 |
124| 52 | `2_10_10_10_USCALED` | added | 3,158 | 3,158 | 1,864 | 1,864 |
125| 53 | `2_10_10_10_SSCALED` | added | 3,158 | 3,158 | 1,864 | 1,864 |
126| 54 | `2_10_10_10_UINT` | added | 3,158 | 3,158 | 1,688 | 1,688 |
127| 55 | `2_10_10_10_SINT` | added | 3,158 | 3,158 | 1,688 | 1,688 |
128| 56 | `8_8_8_8_UNORM` | before | 1,106 | 1,106 | 3,024 | 3,024 |
129| 57 | `8_8_8_8_SNORM` | before | 1,106 | 1,106 | 3,024 | 3,024 |
130| 58 | `8_8_8_8_USCALED` | added | 1,106 | 1,106 | 1,864 | 1,864 |
131| 59 | `8_8_8_8_SSCALED` | added | 1,106 | 1,106 | 1,864 | 1,864 |
132| 60 | `8_8_8_8_UINT` | before | 1,106 | 1,106 | 1,688 | 1,688 |
133| 61 | `8_8_8_8_SINT` | added | 1,106 | 1,106 | 1,688 | 1,688 |
134| 62 | `32_32_UINT` | before | 632 | 632 | 1,688 | 1,688 |
135| 63 | `32_32_SINT` | before | 632 | 632 | 1,688 | 1,688 |
136| 64 | `32_32_FLOAT` | before | 632 | 632 | 1,864 | 1,864 |
137| 65 | `16_16_16_16_UNORM` | before | 2,178 | 2,178 | 3,024 | 3,024 |
138| 66 | `16_16_16_16_SNORM` | before | 2,178 | 2,178 | 3,024 | 3,024 |
139| 67 | `16_16_16_16_USCALED` | added | 2,178 | 2,178 | 1,864 | 1,864 |
140| 68 | `16_16_16_16_SSCALED` | added | 2,178 | 2,178 | 1,864 | 1,864 |
141| 69 | `16_16_16_16_UINT` | before | 2,178 | 2,178 | 1,688 | 1,688 |
142| 70 | `16_16_16_16_SINT` | added | 2,178 | 2,178 | 1,688 | 1,688 |
143| 71 | `16_16_16_16_FLOAT` | before | 262,226 | 262,226 | 1,864 | 1,864 |
144| 72 | `32_32_32_UINT` | before | 907 | 907 | 1,688 | 1,688 |
145| 73 | `32_32_32_SINT` | before | 907 | 907 | 1,688 | 1,688 |
146| 74 | `32_32_32_FLOAT` | before | 907 | 907 | 1,864 | 1,864 |
147| 75 | `32_32_32_32_UINT` | before | 1,182 | 1,182 | 1,688 | 1,688 |
148| 76 | `32_32_32_32_SINT` | before | 1,182 | 1,182 | 1,688 | 1,688 |
149| 77 | `32_32_32_32_FLOAT` | before | 1,182 | 1,182 | 1,864 | 1,864 |
150
151"before" means the format was in `Gen.FORMATS` before the SCALED / SINT / small-float change. (Codes 5, 6, 11, 12, 18, 19, 28,
15261 and 70, the narrow UINT and SINT ones, were added to main's table by a parallel change, measured on gfx1036, while that branch
153was open; they are marked "added" here because the 880M run covers them too and the table entries are identical.) Codes
15430..35, 37..42, 46 and 47 have no GFX11 form and are not in this table; gfx1036 ran them.
155
156## Where the translator stood, and what changed
157
158Decode of every older format matched the 880M word for word from the start. **Three places in the older stores differed
159from the hardware; they follow it now** (each pinned in `tests/semantic/test_buffer_formats_all.py`, `StoresOfTheOlderFormats`,
160and in the GPU fixtures), on the evidence of both GPUs (gfx1036 by @AwkGrep256, #2022):
161
1621. **16_FLOAT, 16_16_FLOAT and 16_16_16_16_FLOAT stores** rounded to nearest even and overflowed to infinity; the hardware
163 rounds toward zero and saturates to ±65504 (0.49999997 gives `0x37FF`, 65520.0 and 1e30 give `0x7BFF`), a NaN stays a NaN
164 and keeps its sign. This is the f16 *format* store; the d16 *data* rounding of BUILD-161 (#1759) is not touched. In a
165 200-row sample of edge-heavy inputs 89 of 200 (16_FLOAT), 132 and 174 rows had differed.
1662. **UNORM and SNORM stores** multiplied in f32 and rounded that, which rounds twice (0.3·65535 is 19660.5008 exactly and
167 19660.5 in f32, a tie that went to 19660; the hardware stores 19661). They now round the exact product once, by integer
168 arithmetic (`Gen.encode_norm_bits`), for every NORM and SCALED format.
1693. **A two-component format stored through a V#** took (x, y) always. With identity selectors (XYZW) hardware takes (x, w) (`_xy`: (x, 0)); with the runtime's XY01 it takes (x, y), which is what the game's descriptors have, so the translator now chooses by DST_SEL_Y and DST_SEL_Z. tbuffer stores keep (x, y). **The first reading of this finding, "(x, w) on RDNA2", came from a probe that only used XYZW; the narrow-integer fixtures, measured on gfx1036 with XY01, showed it does not hold for the runtime's selectors.**
170
171The 12 codes that were missing (30..35, 37..42) are in the table now.
172
173## Not measured
174
175The console's own gfx1013; `d16` loads and stores of the new kinds and of the two-component routing (they use the same
176d16 path as the existing formats: SINT saturates signed, UINT unsigned; BUILD-161 owns d16 rounding); `_xyz` stores into a
177two-component format; formats on unaligned addresses beyond what the existing tests cover; swizzled V#s.
diff --git a/docs/bvh.md b/docs/bvh.md
index f764967e0..203a88c2d 100644
--- a/docs/bvh.md
+++ b/docs/bvh.md
@@ -107,6 +107,25 @@ is source type `int32_t`, so the indexer keeps it signed. `offsetToParents` is s
107indexer keeps its raw value; it is a signed offset from the start of the structure (RT-151: rehydrated console BLASes 107indexer keeps its raw value; it is a signed offset from the start of the structure (RT-151: rehydrated console BLASes
108have it negative), and only the entries from the header end to `offsetToElements` are stored. 108have it negative), and only the entries from the header end to `offsetToElements` are stored.
109 109
110**Measured over every stream (ASSET-329):** 272,864 complete `bvh4` streams, 271,627 in `core_bvh4.rpf` and 1,237 in
111`shared_minigame000_bvh4.rpf` (`story000_bvh4.rpf` has none), indexed with `tools/bvh_index.py`. Counts only.
112
113| word | holds on |
114|---|---|
115| `offsetToPrimRemap` (`0x12c`) is 0 | 272,864 / 272,864 |
116| `rootNodePtr` (`0x130`) is valid, and `(ptr >> 3) * 64` (64-byte units from `0x100`) lies in `[offsetToNodes, 0x40 + 64 * totalSizeIn64BNodes)` | 272,848 (types: `box16` 272,821, `box32` 27) |
117| the other 16: `numElements` = 1, no node region, root is a `tri0` leaf in the element region | 16 (all in `core_bvh4.rpf`) |
118| `offsetToElements` (`0x134`) and `offsetToNodes` are 128-byte aligned, and `offsetToNodes - offsetToElements` = `numElements * 64` rounded up to 128 | 272,864 |
119| `offsetToParents` (`0x138`) is a multiple of 4 | 272,864 |
120| `offsetToParents` is negative as `int32` | 237,347 |
121
122So the "`u16` table at header `0x130`" of section 4 is not a table: it is these three header words read as `u16`s
123(a root pointer, the element offset and the parent offset, the last usually negative; hence "often monotonic"). With `offsetToPrimRemap` 0 everywhere there is no
124primitive remap table either, and the element region allocates 64 bytes per element, `numElements` of them, padded
125to 128 bytes (a stride, not a record layout: section 4a describes the packed arrays inside it).
126**Open:** where the parent array starts and how big it is. Neither `offsetToParents + 4 * unit` against the header end
127or `offsetToElements`, nor a size of `4 *` the node or element count, holds on every stream.
128
110The `flags` word has version `6` in its low 16 bits. It also sets `0x80000000` (bottom level), `0x00020000` 129The `flags` word has version `6` in its low 16 bits. It also sets `0x80000000` (bottom level), `0x00020000`
111(offline) and `0x01000000` (dehydrated). It does not set `0x00010000` (compressed). The sample is therefore a 130(offline) and `0x01000000` (dehydrated). It does not set `0x00010000` (compressed). The sample is therefore a
112bottom-level, offline, dehydrated BVH, not a ready-to-traverse runtime tree. 131bottom-level, offline, dehydrated BVH, not a ready-to-traverse runtime tree.
@@ -163,8 +182,9 @@ The same file defines the packed records: `XboxBvh4NodePacked` at L2326, `XboxBv
163 182
164The layouts above are source definitions. The dehydrated stream is not a contiguous array of runtime `Node16` 183The layouts above are source definitions. The dehydrated stream is not a contiguous array of runtime `Node16`
165records. Its element and box packing is measured in §4a: a CPU model that reads it reproduces the library's 184records. Its element and box packing is measured in §4a: a CPU model that reads it reproduces the library's
166rehydrated output byte for byte. The `BVVDHeader` table is not used by the samples there and stays **Open**. A 185rehydrated output byte for byte, and its structure holds on all 272,874 streams of the two packs. The
167decoder must not feed the dehydrated root to the runtime traversal path; it has to rehydrate first. 186`BVVDHeader` table is not used by the samples there and stays **Open**. A decoder must not feed the dehydrated root
187to the runtime traversal path; it has to rehydrate first.
168 188
169### 3.2 Instance descriptor (208 bytes) 189### 3.2 Instance descriptor (208 bytes)
170 190
@@ -175,7 +195,7 @@ is fixed and was identical in all 269,106 records (and in all 1,233 records of t
175|---|---| 195|---|---|
176| `0x00` | zero `u64` | 196| `0x00` | zero `u64` |
177| `0x08` | `0x50000080`, zero high word | 197| `0x08` | `0x50000080`, zero high word |
178| `0x10` | `1` | 198| `0x10` | `1`: the slot count N of §3.2a |
179| `0x18` | `0x500000A0` | 199| `0x18` | `0x500000A0` |
180| `0x20` | `0x60000000` | 200| `0x20` | `0x60000000` |
181| `0x28` | `0x500000B0` | 201| `0x28` | `0x500000B0` |
@@ -183,20 +203,208 @@ is fixed and was identical in all 269,106 records (and in all 1,233 records of t
183| `0x38` | `0x50000050` | 203| `0x38` | `0x50000050` |
184| `0x40` | 64-bit object key (235,533 distinct values in core) | 204| `0x40` | 64-bit object key (235,533 distinct values in core) |
185| `0x50` | 3x4 float transform (last column zero; identity in 178,867 of 269,106): the geometry transform the BLAS was built with, §4a | 205| `0x50` | 3x4 float transform (last column zero; identity in 178,867 of 269,106): the geometry transform the BLAS was built with, §4a |
186| `0x88` | `0x00000101` | 206| `0x88` | `0x00000101`, the page word of the 32-byte block at `0x80` (§3.2a) |
187| `0xA0` | 64-byte-aligned offset within the following chunk, equal to the declared node end plus 0, 64, 128 or 192 | 207| `0xA0` | the size of the following BLAS: its declared end rounded up to 256 bytes, so the declared node end plus 0, 64, 128 or 192 (269,106/269,106, §3.2a) |
188| `0xA4` | two `u16` counts, high and low; multiples of 256 and 64 in the sample | 208| `0xA4` | high word of the entry at `0xA0`, undecoded; its low `u16` is a multiple of 64 (§3.2a) |
189 209
190The `0x5000xxxx` words are constant across records and point at offsets inside the same 208-byte template 210The `0x5000xxxx` words are constant across records and point at offsets inside the same 208-byte template
191(`0x50`, `0x80`, `0xa0`, `0xb0`, `0xc0`). They behave like serialized GPU virtual addresses built on a fixed 211(`0x50`, `0x80`, `0xa0`, `0xb0`, `0xc0`). They behave like serialized virtual addresses built on a fixed
192`0x50000000` base, but that reading is **speculative**. They are not per-object pointers: the same constants occur 212`0x50000000` base, and `0x60000000` at `0x20` like the base of a second (physical) segment. That reading is a
193in every record. 213**hypothesis** (the RAGE resource convention); what is measured is that every such pointer resolves inside its own
214stream, and §3.2a measures what the template does. They are not per-object pointers: the same constants occur in
215every record.
216
217### 3.2a Descriptor templates and grouping (ASSET-321)
218
219**Status: measured** on all 24,832 "other descriptor" streams of `core_bvh4.rpf` and all 85 of
220`shared_minigame000_bvh4.rpf`, with `tools/bvh_groups.py` (below). Counts, offsets and widths only.
221
222All of them start with a zero `u64` and a `0x5000xxxx` word at `0x08`, as the 208-byte record does. That word
223points at a 32-byte block inside the stream whose `u32` at `+8` (the "page word") is `0x101` or `0x1`; the other
22428 bytes are zero. The streams fall into exactly two templates, and the page word separates them:
225
226| template | page word | streams (core) | sizes (bytes) | count field | followed by |
227|---|---|---:|---|---|---|
228| instance, N = 1 (`instance208`) | `0x101` | 269,106 | 208 | N = 1 | `bvh4` 269,096, `bvh4-chunk` 10 |
229| instance, N > 1 | `0x101` | 2,531 | 256 to 6,544 (9 sizes) | N = 2 to 89 | `bvh4` 2,531 |
230| table | `0x1` | 22,301 | 160 to 10,096 | K = 1 to 227 | descriptor 22,183, `instance208` 118 |
231
2322,531 + 22,301 = 24,832. N is 2 in 1,972 streams, 3 in 263, 6 in 249, 4 in 32, 5 in 8, 89 in 3, 13 in 2, and 7
233and 25 in one each. Every stream with page word `0x101` is followed by a BVH stream (271,637/271,637) and no stream
234with `0x1` is (0/22,301). Read with the hypothesis above, `0x101` is one virtual and one physical page and `0x1`
235one virtual page only: the BVH buffer is the physical segment, and a table stream has none.
236
237**Instance template.** The 208-byte record is its N = 1 case. The N > 1 streams are the census's "4x4 matrix"
238streams: they hold N 3x4 matrices back to back. Pointers, not fixed offsets, place the regions after `0x50`; each
239region is padded to 16 bytes, and matrices, entries, the two arrays and the map block tile the stream with no gap
240or overlap in 2,531/2,531 N > 1 streams and 269,106/269,106 records. The order is matrices, map, entries, arrays in
241269,106 + 1,972 streams and matrices, entries, arrays, map in 559.
242
243| offset | width | contents | value range (core) |
244|---|---|---|---|
245| `0x00` | `u64` | zero | constant |
246| `0x08` | `u64` | `0x5000xxxx` pointer to the 32-byte map block | page word `0x101` at `+8` |
247| `0x10` | `u64` | N, the number of BLAS slots | 1 to 89 |
248| `0x18` | `u64` | pointer to N `u64` entries | |
249| `0x20` | `u64` | `0x60000000` | constant |
250| `0x28`, `0x30` | `u64` each | pointers to two N x `u64` arrays | every element zero in all 271,637 streams |
251| `0x38` | `u64` | pointer to the N matrices | `0x50000050` in all 271,637 |
252| `0x40` | `u64` | key | 2,469 distinct in the 2,531 N > 1 streams |
253| `0x48` | `u64` | zero | constant |
254| `0x50` | N x 48 | N 3x4 `f32` matrices | |
255| entry | `u64` | low `u32`: BLAS size in bytes, 0 for an empty slot; high `u32`: undecoded | low `u16` of the high word a multiple of 64, 256 to 38,976, in all 275,807 non-zero entries |
256
257**Grouping rule (decoded).** The stream after an instance descriptor holds the BLAS of its non-zero entries back
258to back. The first starts at offset 0, each next one where the previous non-zero entry's low `u32` ends, and each
259non-zero low `u32` equals that BLAS's declared end (`u32@0x20` of its own wrapper, §3.1) rounded up to 256 bytes.
260Each BLAS found there has the full §3.1 signature at its own offset (`0x81020006` at `+0x100`,
261`0x140 + 64*n == u32@+0x20`, `u32@+0x28 == u32@+0x20 - 0x100`), and the bytes after the last one are zero.
262
263* N > 1: 2,531/2,531 descriptors pass, which ties **6,701 BLAS** in 2,531 buffers to their descriptor. 13 of the
264 descriptors have empty slots (19 entries whose low `u32` is 0; in 11 of the 13 an empty entry keeps a non-zero
265 high word). With the empty entries skipped they pass like the rest. All 2,531 following streams were inflated whole for this check.
266* N = 1: the low `u32` of the entry at `0xA0` equals the declared end of the following BLAS rounded up to 256 in
267 269,106/269,106 records (the "declared node end plus 0, 64, 128 or 192" of the table in §3.2).
268
269Before this the 2,531 were tied to their buffers only as "followed by". The census counted 2,528 plus 3 preceded
270by other streams; this walk, with `bvh_index.classify`, finds all 2,531 followed by a `bvh4`, and all 271,637 BVH
271streams preceded by an instance descriptor (269,106 + 2,531). The 3 are not reproduced. What is new is what such a
272buffer holds: N BLAS, not one. 4,170 of the 6,701 BLAS sit past the first header of their stream, where an index
273that reads only the first `0x140` bytes of each stream does not see them. The descriptor stores one matrix per
274slot. ASSET-520 tests whether each matrix is the geometry transform of the BLAS at that position, as section 4a
275measured for N = 1.
276
277**Multi-slot geometry comparison.** Generate a local stream index with
278`python -I tools/rpf9_carve.py <core_bvh4.rpf> <index-dir> --index-only`. Supply that index and the manifests
279from one or more primary-LOD `rpf9dump models` exports, with each manifest beside its OBJs.
280
281```text
282python -I tools/bvh_slot_check.py <core_bvh4.rpf> <index-dir>/index.json <models>/manifest.json [...]
283```
284
285For incremental scans, pass `--save-evidence <private-file>` when checking a window. Add another
286manifest with `--prior <private-file>`, or combine independent saved scans by repeating `--prior`
287without any manifests. Either form can save the combined evidence. Keep these files local.
288Each run still checks the core archive and carve index. Evidence is tied to the index bytes, the
289multi-slot descriptor and BLAS contents, and the evidence-format version. A SHA-256 digest over the
290ordered, length-prefixed candidate buffers identifies repeats across scans. Two distinct candidates
291leave the slot ambiguous even if their matrix verdicts agree. `manifest_items` counts entries read
292across the input histories, including overlaps. The CLI prints an aggregate report to stdout.
293
294The tool splits each descriptor's following buffer by the low entry sizes, preserving empty slot indices.
295For descriptors with distinct matrices it searches the supplied drawables for an ordered sequence of geometries
296within one model. Triangle counts must agree per geometry, and the BLAS must have at least 30 paired leaves.
297In every pair, the two indexed triangles must share exactly two indices and the corner selected by the stored
298vertex-order byte must be the unshared vertex of the second triangle. A source is eligible only if this leaves
299one distinct sequence of float32 vertex and uint32 index buffers across the supplied exports. Additional exports
300can reveal a second source with the same topology. No transform, bounds or internal area enters this choice.
301
302For an eligible source the tool calls `bvh_geometry_check.check` with each distinct matrix in the descriptor,
303keeping the vertex and index buffers fixed. An `own_only` result requires the slot matrix to pass, every
304different matrix to fail and the passing matrix to occur in just one slot. Identical matrices or several passing
305slot choices that include the proposed one are non-discriminating. The output counts competing-only passes and
306cases where no matrix passes separately. A missing or ambiguous source leaves the slot unknown.
307
308On Xbox 1.0.2.1 the full core scan covered 2,531 descriptors, 6,701 occupied slots and 19 empty slots.
309Four primary-LOD export windows supplied 7,513 drawable manifest entries. Ten occupied slots across five
310descriptors passed with their own matrix and failed with the other distinct matrix. Zero passed only with an
311alternative. This supports positional pairing for those ten slots. In 2,679 slots all descriptor matrices were
312identical, 308 slots lacked sufficient topology, 3,694 had no topology match in these exports, and 10 had
313multiple distinct source buffers. Pairing remains unknown for those 6,691 slots.
314
315Two additional 1 GiB primary-LOD windows brought the total to 15,064 manifest entries. In the
316six-window scan, 43 slots in 25 descriptors passed only their own matrix, each rejecting one
317distinct alternative. Zero passed only an alternative. Of the remaining 6,658 occupied slots,
3182,679 had identical matrices, 308 lacked sufficient topology, 3,659 had no source match, 11 had
319multiple source buffers and one passed multiple matrix choices. Source uniqueness is relative
320to these exports.
321
322**Table template** (22,301 streams in core, 81 in the shared pack). Two arrays, each a pointer followed by a
323`u16 count, u16 capacity` pair:
324
325| offset | width | contents | value range (core) |
326|---|---|---|---|
327| `0x00` | `u64` | zero | constant |
328| `0x08` | `u64` | pointer to the 32-byte map block | page word `0x1` at `+8` |
329| `0x10` | `u64` | zero | constant |
330| `0x18` | `u64` | 1 | constant |
331| `0x20` | `u64` | pointer to K `u32` values | |
332| `0x28` | `u16`, `u16` | K, capacity | count = capacity, 1 to 227 |
333| `0x30` | `u64` | pointer to K item pointers | |
334| `0x38` | `u16`, `u16` | K, capacity | equal to `0x28` in 22,301/22,301 |
335| item | 32 bytes | a `u64` at `+0x10`; the other 24 bytes zero | both halves of the `u64` non-zero |
336
337In all 22,301 streams the K values are strictly ascending, the K pointers address items exactly 32 bytes apart in
338pointer order, and the items, the map block, the pointer array and the value array (each padded to 16 bytes) tile
339`0x40` to the end of the stream. A larger stream is a larger K: the census's "8-byte keys followed by a table of
340self-pointers" are the items and the pointer array. There are 130,179 items; K is 4 in 11,953 streams, 1 in 3,888,
3412 in 1,953 and 16 in 846. The 22,301 streams are all distinct, the 130,179 item `u64`s are distinct across the
342pack, and each of their 64 bits is set in 50% of them.
343
344**What does not tie a table stream to anything (tested over the whole pack).** For random 32-bit values the
345expected number of matches between two sets is `|A| * |B| / 2^32`; a relation only counts if it beats that.
346
347| candidate | observed | expected by chance |
348|---|---:|---:|
349| a table value (104,795 distinct) equals a BLAS `crc32` (199,615 distinct) | 7 | 4.9 |
350| a table value equals a half of an instance key (475,168 distinct halves) | 6 | 11.6 |
351| an item `u64` equals an instance key at `0x40` (238,000 distinct) | 0 | 0 |
352| a half of an item `u64` (260,357 distinct) equals a BLAS `crc32` | 17 | 12.1 |
353| a half of an item `u64` equals a half of an instance key | 30 | 28.8 |
354| K equals the number of instance descriptors after or before the run | 0 of 119 runs | |
355
356A BVH stream carries no key to match: in all 271,637 the first `0x100` bytes are zero except the wrapper words at
357`0x20` and `0x28`. In archive order the table streams sit in 119 runs (15 of them 277 streams long, the longest
3582,152); every run follows a `bvh4` stream and is followed by an `instance208` (118) or an N > 1 descriptor (1).
359That is position, not a link.
360
361**Open:** what the table streams map (a sorted `u32` lookup to a 64-bit value; both look like hashes, and names are
362only in the encrypted TOC, so that is not tested here); the high `u32` of an instance entry; what the two zero
363arrays of the instance template hold when they are not zero; whether the N matrices are the per-slot geometry
364transforms. None of the 22,301 table streams can be tied to a BVH buffer with what the pack shows, and by the page
365word they own none.
366
367```powershell
368python -I tools/bvh_groups.py <core_bvh4.rpf> --json <temp>/groups.json # the template, page word and buffer counts
369python -I tests/test_bvh_groups.py
370```
194 371
195The 24,832 "other descriptor" streams are the same family at other sizes (160, 192, 256, 272, 368, ... bytes): 372The tool walks the archive with `bvh_index`'s own decompressor and classifier, parses each descriptor, inflates the
196first eight bytes zero, a `0x5000xxxx` word at `0x08`, and zero at `0x0C`. Some carry a full 4x4 matrix instead of 373stream after each instance descriptor and checks it against the entries. Its rows and summary hold offsets, sizes,
197the 3x4 transform; the larger ones (e.g. 272 and 368 bytes) contain several 8-byte keys followed by a table of 374counts and check results, never a key, value or payload byte. The chance table, the duplicate counts, the region
198`0x5000xxxx` self-pointers. 2,528 of them are immediately followed by a BVH buffer. Their exact grouping semantics 375orders, the run lengths and the preamble count came from scratch scripts over the same parse and are not in the
199are **Open**. 376tool.
377
378#### The `0x40` key (ASSET-350, measured; what it hashes is **Open**)
379
380Measured over all 269,106 descriptors of `core_bvh4.rpf`, each paired with the `bvh4` stream that follows it; a
381BLAS is identified by that stream's crc32 (197,324 distinct).
382
383* **Two populations.** 144,471 keys are below 2^55 (the top 9 bits zero; about 244 would be by chance) and
384 124,635 use all 64 bits, with the top 9 bits spread evenly over the other 511 values. Inside each population
385 every bit is set about half the time, and splitting the key at any of 12 points (8 to 48 bits) gives as many
386 distinct high and low parts as uniform values would: no packed field, both read as hash output.
387* **The population follows the BLAS.** Only 28 of the 197,324 BLAS occur with keys of both kinds. The 55-bit keys
388 sit on smaller BLAS (median 191 elements against 2,802) and the two kinds come in runs in file order (44,156
389 runs; about 133,800 for a random interleave).
390* **Key to geometry.** A key always comes with one (BLAS, transform) pair, with the one exception already noted
391 in the ASSET-350 finding. The reverse does not hold: 11,209 of the 211,407 (crc32, transform) pairs carry more
392 than one key, up to 743.
393* **Not a name hash.** 0 of the 235,533 keys equal a hash of any of the 318,149 distinct drawable names of the 343,327
394 models `rpf9dump models` reads from `levels.rpf`, as is, lower-cased, with `.ydr` or with the `.#dr` suffix,
395 under Murmur3 x64-128 (either half), xxh64, FNV-1/FNV-1a 64, joaat64, CRC-64 (ECMA and ISO), djb2/sdbm 64 and
396 the first 8 bytes of MD5, SHA-1, SHA-256 and BLAKE2b (both byte orders), compared in full, masked to 55 bits
397 and shifted right by 9. 32-bit joaat, FNV-1a and CRC32 of the names match either key half at the chance rate.
398 The name set is close to complete: the same Murmur3 h1 reproduces 228,610 of the 228,681 distinct archetype keys
399 (`c8a7b90a`, [world_names.md](world_names.md)).
400* **Not an entity field.** 0 keys equal any entity id (`1b60404d`, 1,664,626 distinct) or archetype key
401 (`c8a7b90a`, 228,681 distinct) of the 1,670,435 entities a whole-archive `world_index.py` run reads, also
402 byte-swapped, with the halves swapped or masked to 55 bits.
403* **Not shared with the other descriptors.** 2 of the keys occur in the 24,832 other descriptor streams (both
404 256-byte records, at `+0x40`); those streams hold no entity id or archetype key at any 8-byte-aligned offset.
405
406Since the packs are baked offline, the key may be assigned at build time rather than derived from a name the
407package stores.
200 408
201### 3.3 Fill and node occupancy 409### 3.3 Fill and node occupancy
202 410
@@ -222,6 +430,20 @@ Scans of the inflated payloads found no `RSC7`, `RSC8`, `BVH4`, `BVH`, `0DRP`, `
222shared, 4 in story) and the strings inside those manifests, including the substring `bvh` in the per-tile 430shared, 4 in story) and the strings inside those manifests, including the substring `bvh` in the per-tile
223`*_bvh.rpf` entries. No DXBC/DXIL shader container starts any chunk in the header census. 431`*_bvh.rpf` entries. No DXBC/DXIL shader container starts any chunk in the header census.
224 432
433### 3.5 The nested packs of core_bvh4.rpf
434
435`core_bvh4.rpf` is a container of nested files, not one pack. Its last streams hold a changeset (section 5) that
436registers 1,276 names. A nested file starts with a 16-byte entry header whose first four bytes are `9FPR`, then a
437TOC of `u32@+4` bytes, then its streams. The container's own header is at 0, outside the data area; the first nested
438entry is at `0x10000`, 0x200 bytes after the data-start and on a 64 KiB boundary. Entries are page aligned: of the
4391,282 `9FPR` tags in the data area, 1,281 are 16-byte aligned and 1,260 start a 4 KiB page. A filter on a plausible
440TOC size (`u32@+4` below `0x10000` with the entry template at `+0x18`) accepts 1,191 tags. That filter is narrower
441than a tag search, so 1,191 counts template matches, not packs.
442
443The counts do not reconcile: 1,276 names against 1,282 tags, 85 names without an entry and 6 tags without a name.
444The names stay encrypted and the TOCs are not decrypted, so a file is attached by position, not by name; the first
445changeset name is `int_abd_interiors` at the first entry.
446
225## 4. Format family 447## 4. Format family
226 448
227**Verified by bytes:** the archives are prebuilt BVH4-style acceleration data, not shader payloads and not a 449**Verified by bytes:** the archives are prebuilt BVH4-style acceleration data, not shader payloads and not a
@@ -234,8 +456,8 @@ their source geometry, `RehydrateRaytracingAccelerationStructureX` returns `S_OK
234model of the packing gives the same bytes. Whether the game's runtime calls that path or rebuilds from source 456model of the packing gives the same bytes. Whether the game's runtime calls that path or rebuilds from source
235geometry is still **Open**; `docs/d3d12_vulkan.md` §4.8/§7.2 lists that call-path question. 457geometry is still **Open**; `docs/d3d12_vulkan.md` §4.8/§7.2 lists that call-path question.
236 458
237**Not present as a whole:** source vertex/index meshes. The only geometry-like structure is the `u16` table at 459**Not present as a whole:** source vertex/index meshes. The `u16` "table" at header `0x130` once read as a remap table is the
238header `0x130`, whose size is even and which is often monotonic; it is a candidate remap/primitive table. No 460`rootNodePtr`/`offsetToElements`/`offsetToParents` words, and `offsetToPrimRemap` is 0 on every stream (§3.1). No
239vertex-format header, index-format header or RSC resource container was found. The leaves carry primitive 461vertex-format header, index-format header or RSC resource container was found. The leaves carry primitive
240references only; the triangles come from the drawables in `levels.rpf`, in the frame of the instance descriptor's 462references only; the triangles come from the drawables in `levels.rpf`, in the frame of the instance descriptor's
241transform (§4a). 463transform (§4a).
@@ -254,8 +476,8 @@ it to return `S_OK`. It decodes standard DXGI vertex and index formats only, and
254geometry index the leaves use; fewer makes it read past the array. 476geometry index the leaves use; fewer makes it read past the array.
255 477
256**The packing (completes §3.1).** A CPU model that reads the dehydrated stream as below writes the same bytes as the 478**The packing (completes §3.1).** A CPU model that reads the dehydrated stream as below writes the same bytes as the
257library on the 8 samples whose geometry is identified (0 differing bytes; 384 to 2,512,512 bytes per structure, 2 to 479library on the 8 samples whose geometry was identified first (0 differing bytes; 384 to 2,512,512 bytes per
25821,814 leaves). 480structure, 2 to 21,814 leaves). The other two were identified later (below) and have not been run through the library.
259 481
260* *Elements* start at `offsetToElements`, in chunks of 2,048 leaves at a 128 KiB stride. A chunk is five arrays, 482* *Elements* start at `offsetToElements`, in chunks of 2,048 leaves at a 128 KiB stride. A chunk is five arrays,
261 one entry per leaf: geometry index (3 bytes), flags (1 byte), base primitive (3 bytes), second primitive (3 bytes, 483 one entry per leaf: geometry index (3 bytes), flags (1 byte), base primitive (3 bytes), second primitive (3 bytes,
@@ -274,15 +496,57 @@ library on the 8 samples whose geometry is identified (0 differing bytes; 384 to
274 where the bounds do not straddle zero; bits 24-29 select one of 64 rotations, `Rz * Ry * Rx` in steps of pi/8 496 where the bounds do not straddle zero; bits 24-29 select one of 64 rotations, `Rz * Ry * Rx` in steps of pi/8
275 about each axis (index 0, the identity, on every sample). 497 about each axis (index 0, the identity, on every sample).
276 498
499**The packing holds on every stream (structure only).** The byte-exact match above covers 8 samples.
500`tools/bvh_packing_check.py` reads every stream with the same packing, without geometry (§7). It checks that the
501bytes form exactly one tree:
502
503* the level table is in order and ends before itself;
504* every group fits in the bytes its nodes occupy;
505* every node has 1 to 4 children and no override bit past them;
506* a box pointer names a node of its own width on a lower level;
507* a TRI0 pointer names a leaf slot `offsetToElements + 64 * k` with `k < numElements`;
508* nothing points to the root, and every other node and every leaf has exactly one parent;
509* every vertex-order byte is a permutation;
510* every stored override lies inside `sceneBounds` in the leaf frame.
511
512Result: **272,874 of 272,874** streams pass. That is 271,627 complete streams and 10 split ones (joined) in
513`core_bvh4.rpf`, plus 1,237 in `shared_minigame000_bvh4.rpf`.
514
515In `core_bvh4.rpf`:
516
517| | count |
518|---|---:|
519| box nodes | 413,539,798 |
520| leaves | 1,068,494,700 |
521| stored override components | 17,082,560 |
522| nodes with 2 / 3 / 4 children | 54,219,680 / 63,956,971 / 295,363,147 |
523| nodes with 1 child | 0 |
524| child pointers to BOX16 / BOX32 / TRI0 | 48,220,482 / 365,047,695 / 1,068,494,684 |
525| child pointers of any other type | 0 |
526| levels per structure | 1 to 19 (mode 7) |
527
528Roots:
529
530* 271,594 are BOX16 and 27 are BOX32. Each is the last node of a top level that holds only it.
531* The other 16 structures are a single TRI0 leaf with no box levels.
532* No root stores an override. Its box is therefore always recomputed from its children, and `sceneBounds` cannot be
533 compared with stored values alone.
534
277**The instance transform.** The 3x4 at descriptor `+0x50` is applied to the geometry, `x' = M * x`, before the BLAS 535**The instance transform.** The 3x4 at descriptor `+0x50` is applied to the geometry, `x' = M * x`, before the BLAS
278is built. The samples carry the identity or an axis-aligned 90-degree rotation. Without it, most leaves of the 536is built. The samples carry the identity or a rotation that permutes the axes: 4 of the 10, three of them a
53790-degree turn about one axis and one a 180-degree turn about a diagonal. Without it, most leaves of the
279rotated samples fall outside `sceneBounds` (175 of 181 and 207 of 273); with it, none do. The transposed matrix does 538rotated samples fall outside `sceneBounds` (175 of 181 and 207 of 273); with it, none do. The transposed matrix does
280not fit. 539not fit.
281 540
282**Where the triangles come from.** A leaf's geometry index is a position in the geometry list of a drawable's 541**Where the triangles come from.** A leaf's geometry index is a position in the geometry list of one model of a
283primary-LOD model in `levels.rpf`, counting only the geometries whose shader the BVH keeps. On the 8 BLAS whose 542drawable in `levels.rpf`, counting only the geometries whose shader the BVH keeps: a model of its primary LOD on
284drawable is a single resource, a geometry is left out exactly when its shader is one of two shaders: 48 geometries, 543the 10 samples, of its second LOD for most of the interior's other BLAS (below). Over the 10 samples a geometry
2858 distinct shaders, no exception. The two name hashes stay out of this repository (§8). They are the shader-group 544is left out exactly when its shader is one of a set of shaders: the 65 geometries left out use 7 shader hashes, the
54567 kept use 8 others, and no hash is in both. Two of the 7 cover 54 of the 65; the other five occur only in the two
546drawables that hold decals and baked room dressing. (On the 8 samples identified first, the skipped geometries were
547read as using only two shaders; the decals drawable among them skips geometries of all 7.) The 7 hashes are not the
548rule: the material's render bucket is (ASSET-349, "Which geometries the BVH leaves out" below). The hashes stay out of
549this repository (§8). They are the shader-group
286hashes (first word of the shader record; shader group at drawable `+0x10`, pointer array at group `+0x10`, `u16` 550hashes (first word of the shader record; shader group at drawable `+0x10`, pointer array at group `+0x10`, `u16`
287count at `+0x18`, shader index per geometry in the model's `u16` array at `+0x20`) that only skipped geometries 551count at `+0x18`, shader index per geometry in the model's `u16` array at `+0x20`) that only skipped geometries
288carry, so any identified BLAS that skips a geometry lets a user recover them locally. The positions in the samples 552carry, so any identified BLAS that skips a geometry lets a user recover them locally. The positions in the samples
@@ -291,6 +555,42 @@ then one contiguous stream of 8-byte records; the other vertex attributes follow
291per vertex of the whole block are not a position stride. The leaves address triangles in primitive order of the 555per vertex of the whole block are not a position stride. The leaves address triangles in primitive order of the
292meshlet index buffer. 556meshlet index buffer.
293 557
558**Which geometries the BVH leaves out (ASSET-349, measured; one rule with known exceptions).** The choice follows the
559render bucket of the geometry's material: the byte at `+57` of the shader record, with the bucket mask at `+60`
560(`third_party/rpf9-explorer/Core/RageModelDecoder.cs:680`; `rpf9dump models` writes the byte as `RenderBucket`). A
561geometry is kept when the low 7 bits of that byte are 0 or 3 and left out otherwise; bit 7 does not change the
562choice. What the buckets mean is not measured here (in earlier RAGE games 1 and 2 are the alpha and decal buckets;
563that is a hypothesis for this one).
564
565* *The 10 samples:* 132 of 132 geometries follow it (all 65 left out are bucket 1 or 2, all 67 kept bucket 0 or 3),
566 and for each of the 10 the kept geometries are exactly the BLAS's signature, with one consistent drawable each
567 (re-run against the 3 GiB window export).
568* *The whole archive:* a `rpf9dump models` export of all of `levels.rpf` (343,327 drawables, 346,785 models,
569 2,251,094 materials, 3,854,587 geometries; first LOD only) has bucket bytes 0-6 and 128-131: 3,091,235 geometries
570 kept by the rule and 763,352 left out, 70,334 models with both. Bit 7 is set on 35,339 materials.
571* *Signature equality over every stream:* of the 271,637 BVH streams of `core_bvh4.rpf`, 242,388 have a model whose
572 rule-kept triangle counts equal the stream's signature exactly (96,267 of the 125,180 streams with at least two
573 geometries and 64 triangles). Every other bucket set scores lower: keeping 0 and 3 but not 128 and 131 gives
574 240,984; keeping every geometry 197,117; keeping bucket 0 only 208,364; adding 1 to the kept set 228,214; adding 2
575 204,227; adding any of 4, 5, 6, 129 or 130 lowers the count by 5 to 128 streams. Second-LOD BLAS and drawables
576 outside the export cannot match a first-LOD export, so the rest are not counted against the rule.
577* *Geometry check:* of 300 random exact hits (at least two geometries, at most 40,000 triangles), 241 pass
578 `bvh_geometry_check.py` with the instance transform, and 59 do not. Those 59 have the same triangle counts as a
579 drawable that is not where the BLAS is (the check tests the geometry, not the counts); the checker tries at most 8
580 models per stream.
581* *Exceptions:* 511 such streams have no exact hit but match a model with one geometry's choice flipped. For 22 of
582 them that flipped candidate passes the geometry check: 34 geometries of bucket 1 (13) or 2 (21) that the BVH keeps.
583 No consistent candidate leaves out a bucket-0 or bucket-3 geometry. So the rule fails on at least 22 BLAS, always by
584 keeping a bucket-1 or bucket-2 geometry. What else marks those geometries is **open**.
585* *Shader hashes:* of the 309 shader-group hashes the export's geometries use, 212 occur only in kept buckets, 96 only
586 in left-out ones, and 1 in both (87 geometries in bucket 0, 1 each in buckets 1 and 2). That is why a hash list
587 cannot express the rule, and it is probably the one hash below that the interior's 130 BLAS both keep and leave out.
588 The note below says those 3 left-out geometries have the same bucket as the kept ones; that was not re-measured
589 here, and if it holds they belong with the exceptions above.
590
591`tools/bvh_match.py` applies the rule by default whenever every geometry of a model has a bucket in the manifest
592(`--no-bucket-rule` turns it off; `--skip-shaders` still adds hashes on top).
593
294**How a match is verified.** A byte-identical library result checks the packing, not the geometry: the model and 594**How a match is verified.** A byte-identical library result checks the packing, not the geometry: the model and
295the library agree on any input. These checks use what the dehydrated stream recorded from the true geometry: 595the library agree on any input. These checks use what the dehydrated stream recorded from the true geometry:
296 596
@@ -304,12 +604,140 @@ the library agree on any input. These checks use what the dehydrated stream reco
304 test needs no positions. 604 test needs no positions.
305 605
306With these, 8 of the 10 BLAS each have exactly one matching drawable among all candidates of their triangle-count 606With these, 8 of the 10 BLAS each have exactly one matching drawable among all candidates of their triangle-count
307signature (up to 467), and the library output equals the model on all 8. The other two are interior rooms that 607signature (up to 467 in that first pass), and the library output equals the model on all 8.
308aggregate props from several drawables in room-local coordinates: test 4 finds three of their pieces exactly, but 608
309placing them needs the interior's entity list (`CMloArchetypeDef`, see #1981), which the BLAS does not store. 609**None of the 10 is an aggregated room (ASSET-322).** Two of them were first read as interior rooms that aggregate
310 610props from several drawables, in room-local coordinates. They are not: every one of the 10 is one drawable, built
311**Open:** what the two excluded shaders are; the placement of aggregated rooms; whether the runtime rehydrates 611the same way, as the window measurement in §7 also found. The 10 are the first 10 BVH streams of `core_bvh4.rpf`
312these packs at all (above). 612(archive offsets 69,728 to 720,992). Re-measured on a `rpf9dump models` export of the whole `levels.rpf` (343,327
613models, with the per-geometry counts that `bvh_match.py` needs), each has exactly one consistent drawable, and all 10
614drawables belong to one interior:
615
616| leaves | what the drawable is | geometries kept / in the model | triangles kept / in the model | candidates | outside, gap, overrides |
617|---:|---|---|---|---:|---|
618| 181 | room shell | 3 / 3 | 350 / 350 | 69 | 0, 1.4e-7, 0 / 0 |
619| 21,814 | ceiling dressing | 12 / 13 | 37,088 / 37,090 | 1 | 0, 4.2e-8, 335 / 0 |
620| 273 | fitting | 3 / 7 | 542 / 980 | 21 | 0, 1.7e-7, 0 / 0 |
621| 1,844 | ceiling panels | 7 / 8 | 3,352 / 3,440 | 1 | 0, 1.4e-7, 69 / 0 |
622| 2 | light proxy | 1 / 1 | 2 / 2 | 17 (interior only) | 0, 0, 0 / 0 |
623| 138 | decals | 2 / 35 | 236 / 1,965 | 848 | 0, 4.2e-8, 2 / 0 |
624| 62,479 | room dressing (props baked into one model) | 29 / 42 | 113,165 / 123,175 | 1 | 0, 4.0e-8, 1,328 / 0 |
625| 566 | decals | 3 / 12 | 1,127 / 2,173 | 37 | 0, 0, 0 / 0 |
626| 1,700 | room dressing | 6 / 10 | 3,242 / 3,426 | 1 | 0, 4.7e-8, 23 / 0 |
627| 103 | suspended ceiling | 1 / 1 | 201 / 201 | 4,173 | 0, 4.7e-8, 0 / 0 |
628
629"Candidates" are the (drawable, model) pairs whose geometry counts contain the BLAS's signature; one of them passes
630the checks. The 2-triangle light proxy matches every geometry of two triangles in the archive, so it was checked
631against the 141 drawables of the interior's 143 archetypes that the export holds. The kept geometries are an ordered
632subsequence of the model's list (the 62,479-leaf BLAS keeps geometries 0-22, 33-36, 38 and 41).
633
634Which two were the "aggregated rooms" follows from the counts. The 8 matched first span 2 to 21,814 leaves, so one was
635the 62,479-leaf BLAS, which skips 13 geometries. The 10 skip 65 in all and the first 8 skipped 48, so the other one
636skips 4: the 273-leaf or the 1,700-leaf BLAS. The 273-leaf one is in the rotation test above, so its geometry was
637known, and the second was the 1,700-leaf one. Rehydrated with `bvh_rehydrate.py`, both pass `xdxr_bvh.py validate`
638apart from children wider than the slot that points at them: 1,310 and 27 such slots, where they store 1,328 and 23 box
639overrides. The 21,814-leaf BLAS, which the library reproduces byte for byte, gives 282 such reports for its 335
640overrides: a stored override tightens the slot below its child's own box.
641
642**Placement comes from the interior, not from the BLAS.** The 10 drawables are entities of one interior archetype
643(`CMloArchetypeDef`, read with the interior reader of #1981, not merged yet). It has 242 entities: 11 in its base
644list and the others in three entity sets of 2, 77 and 152. 3 of the 10 are in the base list, 4 in the 77-entity set
645and 3 in the 152-entity set. The instance's `defaultEntitySets` lists the 152-entity set and the 2-entity one, not the
64677-entity set, so 4 of the 10 BLAS belong in the scene only while that set is active. The interior is placed once in
647the map (`CMloInstanceDef`). The join from drawable to entity is the joaat of the drawable's name; each of the 10
648entities' 64-bit `key` is also the Murmur3 key of that name (measured here; #3813 measured the same rule on
649`CMloArchetypeDef` keys). The descriptor's key at `+0x40` is not, nor the joaat or Murmur3 of the drawable name, so
650the BLAS does not name its entity.
651
652A BLAS's `sceneBounds` are in the space of its descriptor transform `M` (`x' = M * x`, above), so the BLAS sits in
653interior space at `E * M^-1`, with `E` the entity's translation and rotation (the conjugate of the stored quaternion,
654as for map entities). `M` is a rotation in all 10, so `M^-1 = M^T`. Mapped that way, the eight corners of each of the
65510 `sceneBounds` lie inside the interior's `bbMin`/`bbMax` (0 m outside), and their union reaches the interior's top
656exactly (3.459 m). This is a weak test: the interior box probably comes from its entities, 9 of the 10 entities have
657the identity rotation, and with the stored quaternion the one turned 90 degrees about z ends only 1.6 cm outside. A
658TLAS instance for one of these BLAS would therefore be `I * E * M^-1`, with `I` the interior instance's transform;
659its world-to-object record would also fold in the leaf frame (`compressionParams`), as the console's `LoadInstances`
660does in #4011 (open). That the game builds its instances this way is not observed.
661
662**Where the other entities' BLAS are (ASSET-351).** The 10 streams above cover 10 of the interior's 242 entities.
663Every BVH stream of `core_bvh4.rpf` (271,637) and of `shared_minigame000_bvh4.rpf` (1,237) was matched against the
664141 drawables of the interior that the export holds, with the signature and the checks of
665`bvh_geometry_check.py`; `story000_bvh4.rpf` holds no BVH (§5). `rpf9dump models` decodes only a drawable's first
666LOD (the LOD pointer at drawable `+0x50`), so the drawables were also exported at their second, third and fourth LOD
667(`+0x58`, `+0x60`, `+0x68`) with a local change to the decoder that follows the other pointer; 117, 90 and 67 of the
668141 decode at those LODs. The second LOD was suggested by streams whose `sceneBounds` equal, within 2 mm and up to an
669axis permutation, the box of an unmatched first-LOD drawable's kept geometry while holding fewer triangles (a quarter
670to a half in most cases).
671
672| | archetypes | entities |
673|---|---:|---:|
674| BLAS built from the first LOD | 23 | 32 |
675| BLAS built from the second LOD | 101 | 188 |
676| 2-triangle light proxy, cannot be attributed | 1 | 1 |
677| no BLAS, drawable exported | 16 | 19 |
678| no BLAS, drawable not in the export | 2 | 2 |
679| total | 143 | 242 |
680
681* **All of them are in `core_bvh4.rpf`.** The shared pack has no stream consistent with any of the 141 drawables at
682 any LOD.
683* **One BLAS per drawable, not per entity.** The 31 matched archetypes that the interior places more than once (127
684 entities, up to 18 of one archetype) have 32 streams between them; 120 of the 124 archetypes have exactly one
685 stream, 4 have 2 to 4. Every one of the 130 streams follows a 208-byte instance descriptor (§3.2), 57 of them with a
686 transform that is not the identity.
687* **Entity sets.** The base list has 9 of its 11 entities with a BLAS (plus the light proxy), the 2-entity set 2 of 2,
688 the 77-entity set 67 of 77 and the 152-entity set 142 of 152.
689* **LOD.** Of the 130 streams, 25 fit only the first LOD, 103 only the second, and 2 fit more than one (the first to
690 third, and the second and third). The third LOD adds no archetype and the fourth fits no stream. The 9 drawables of
691 the first 10 streams other than the light proxy are first-LOD; 17 of the other 121 streams are.
692* **Position in the pack.** The other 121 streams are not next to the first 10. They lie between BVH stream 231,012 and
693 261,585 (archive offsets 7,662,866,512 to 7,948,582,992), in 85 runs of 1 to 6 consecutive streams. The band holds
694 30,574 streams, so this interior is about 0.4 % of it. A pack is therefore not one block per interior: the 10
695 drawables of the table above (from the base list and two entity sets) open the pack, and the interior's other 115
696 archetypes with a BLAS are some 231,000 streams later, among streams this measurement does not attribute; no
697 archetype has a stream in both places. The data area also holds 1,282 `9FPR` tags after the file's own (1,281 of
698 them 16-byte aligned), which read as nested packs: taking each tag as the start of one, the first 10 streams are
699 the whole first nested pack, and the other 121 lie in 31 other packs, up to 19 in one; one archetype has streams
700 in two of those 31 packs.
701* **The light proxy.** 21 streams fit its 2-triangle drawable, 20 of them with the same header, one of which is
702 stream 4; a quad of that size cannot be told from another drawable's.
703* **No BLAS.** Of the 16 exported archetypes without one, 11 have only geometries whose shaders the matched drawables
704 leave out, so the rule predicts none; 4 have a geometry with a shader that other drawables keep, and 1 has only
705 shaders that occur in none of the matched drawables.
706* **The shader rule is not a list of shaders alone.** Over the 130 streams, 267 geometries are kept and 114 left out;
707 the kept ones use 14 shader hashes, the left-out ones 13, and one hash is in both: kept in 171 geometries of 86
708 drawables, left out in 3 geometries of 3 drawables, whose materials have the same render bucket and preset as kept
709 ones.
710
711How specific the matches are: of the first-LOD streams, the 12 with at most 3,000 candidates in the whole export have
712exactly one consistent drawable among its 343,327 models each; the other 13 (3,951 to 47,664 candidates) and all
713second-LOD matches were checked against the interior's drawables only, where no stream fits two archetypes. A drawable
714elsewhere with the same geometry would fit as well.
715
716**The descriptor key (`+0x40`).** Over all 269,106 single-BLAS descriptors of `core_bvh4.rpf` and the BVH stream
717after each (the 235,533 distinct keys of §3.2; the descriptors that group several BLAS, #4199, are not counted here),
7182,873 keys occur more than once, 33,573 repeats in all, one key 3,198 times. A key always comes with
719the same transform, and with the same BLAS header (sizes, bounds, `crc32`) in all but one case: a 3-leaf BLAS seen 4
720times under one key, with the same sizes and bounds each time and a different `crc32` in one of the four. The
721converse fails: 1,008 (BLAS header, transform) pairs occur under more than one key, up to 60 keys. So distinct keys
722can share both the BLAS and its transform: the key identifies something finer than that pair. What it hashes is open;
723#4199 (open) finds no more matches between these keys and the values of the table descriptors than chance gives.
724
725**Open:** why the BVH keeps the bucket-1 and bucket-2 geometries of at least 22 BLAS (ASSET-349 above); what decides the LOD a BLAS is built from; what the rest of the band of streams 231,012
726to 261,585 holds, and how the pack is ordered; why 4 exported archetypes with a kept shader have no BLAS; what
727the descriptor key at `+0x40` hashes; how the game picks the entity of a BLAS when the BLAS does not name it (the
728drawable match does it here); whether the game composes TLAS instances as `I * E * M^-1`; whether the runtime
729rehydrates these packs at all (above).
730
731## Where BLAS live
732
733* **Per stream:** the 208-byte instance descriptor immediately precedes its `bvh4` stream, 269,106 of 269,106 in
734 `core_bvh4.rpf` (section 3.2).
735* **Per interior:** one interior file is one cell and holds only the entities that have their own acceleration
736 structure. The §4a sample's first file is exactly ten pairs, and its other entities' streams lie in 31 other
737 packs (§4a). The BLAS itself stores no interior or entity list, so placing an interior's pieces needs its entity
738 list (`CMloArchetypeDef`, #1981).
739* **Per tile:** the nested files are per tile; the final changeset lists the `*_bvh.rpf` packs per tile and
740 `story000_bvh4.rpf` registers them without data (section 5).
313 741
314## 5. Cross-check of the small packs 742## 5. Cross-check of the small packs
315 743
@@ -333,8 +761,11 @@ into three 64 KiB/26 KiB chunks. These list the per-tile BVH packs; they are the
3332. **Concatenate split files.** A `bvh4-chunk` (10 in core) is the first 8 MiB of a larger payload; append the 7612. **Concatenate split files.** A `bvh4-chunk` (10 in core) is the first 8 MiB of a larger payload; append the
334 following continuation chunks until the declared `u32@0x20` end is reached before reading nodes. 762 following continuation chunks until the declared `u32@0x20` end is reached before reading nodes.
3353. **Pair descriptor to buffer.** The 208-byte descriptor precedes its BVH chunk in stream order in 7633. **Pair descriptor to buffer.** The 208-byte descriptor precedes its BVH chunk in stream order in
336 269,106/269,106 cases. The other descriptor sizes account for 2,528 more BVH buffers; 3 more are preceded by 764 269,106/269,106 cases. The 2,531 instance descriptors with N > 1 precede the other 2,531 BVH streams, each of
337 other streams. 765 which holds N BLAS back to back at the offsets the descriptor's entries give (§3.2a); read all of them, not only
766 the header at `0x100`. The 22,301 table descriptors own no BVH buffer.
7673. **Pair descriptor to buffer.** The other descriptor sizes account for 2,528 more BVH buffers; 3 more are preceded
768 by other streams. The 208-byte pairing is in "Where BLAS live".
3384. **Parse the header, then stop guessing.** The exact header table, node pointer encoding and runtime 7694. **Parse the header, then stop guessing.** The exact header table, node pointer encoding and runtime
339 `Node16`/`Node32`/`Leaf` records are in section 3.1, and the dehydrated element and box packing in §4a; do not 770 `Node16`/`Node32`/`Leaf` records are in section 3.1, and the dehydrated element and box packing in §4a; do not
340 infer a runtime child array from the `0x140` slot space. 771 infer a runtime child array from the `0x140` slot space.
@@ -363,8 +794,8 @@ python -I tests/test_bvh_index.py
363 794
364`--start` must be 0 or more, and `--limit` and `--max-inflate` at least 1. A value outside that, or a `--start` past 795`--start` must be 0 or more, and `--limit` and `--max-inflate` at least 1. A value outside that, or a `--start` past
365the end of the archive, stops the tool with a one-line error and exit code 2. An empty archive, or one shorter 796the end of the archive, stops the tool with a one-line error and exit code 2. An empty archive, or one shorter
366than its 8-byte header, has no streams. In directory mode an archive that cannot be read is reported on stderr as 797than its 8-byte header, has no streams. In directory mode an archive that cannot be read, or a sub-folder that cannot be listed, is reported on stderr as
367`skipped` and the other archives are still indexed. 798`skipped` and the other archives are still indexed; the run then ends with an "incomplete" line and exit code 1.
368 799
369The `bvh4` signature is reported only when `flags == 0x81020006`, the `0x140 + 64*n == end` formula and the 800The `bvh4` signature is reported only when `flags == 0x81020006`, the `0x140 + 64*n == end` formula and the
370`u32@0x28 == end - 0x100` wrapper relation all hold; a larger payload whose declared end is past the chunk but 801`u32@0x28 == end - 0x100` wrapper relation all hold; a larger payload whose declared end is past the chunk but
@@ -375,9 +806,13 @@ template, XML and XML fragments, the two-stream advance bug and CSV/JSON output.
375Measured with the tool on `shared_minigame000_bvh4.rpf`: 2,560 streams, 59,142,787 stored, 970,044,012 inflated, 806Measured with the tool on `shared_minigame000_bvh4.rpf`: 2,560 streams, 59,142,787 stored, 970,044,012 inflated,
3761,237 complete `bvh4`, 1,233 `instance208`, 85 descriptors, 5 XML. That matches the carver summary exactly. 8071,237 complete `bvh4`, 1,233 `instance208`, 85 descriptors, 5 XML. That matches the carver summary exactly.
377 808
809`tools/bvh_groups.py` (standard library only) parses the descriptor streams into the two templates of §3.2a and
810checks every instance descriptor against the BVH stream after it: N BLAS at the offsets its entries give. On the
811shared pack it reports 1,233 + 4 instance descriptors (1,233 + 8 BLAS tied) and 81 table streams with 317 items.
812
378`tools/bvh_rehydrate.py` (standard library only) turns a dehydrated BLAS back into the runtime layout on the CPU, 813`tools/bvh_rehydrate.py` (standard library only) turns a dehydrated BLAS back into the runtime layout on the CPU,
379from float3 vertices, `uint16`/`uint32` or no indices and an optional 3x4 geometry transform, following the packing 814from float3 vertices, `uint16`/`uint32` or no indices and an optional 3x4 geometry transform, following the packing
380in §4a. On the 8 measured samples whose geometry is identified, its output is byte-identical to what 815in §4a. On the 8 samples whose geometry was identified first, its output is byte-identical to what
381`XboxBvhBuilder.dll`'s `RehydrateRaytracingAccelerationStructureX` writes (384 to 2,512,512 bytes per structure). It 816`XboxBvhBuilder.dll`'s `RehydrateRaytracingAccelerationStructureX` writes (384 to 2,512,512 bytes per structure). It
382is the reference for checking the builder's `Box16Rehydration`, `Box32Rehydration` and `LeafRehydration` programs on 817is the reference for checking the builder's `Box16Rehydration`, `Box32Rehydration` and `LeafRehydration` programs on
383a GPU ([embedded_shaders.md](embedded_shaders.md)). Its tests are synthetic. 818a GPU ([embedded_shaders.md](embedded_shaders.md)). Its tests are synthetic.
@@ -396,7 +831,7 @@ python -I tests/test_bvh_rehydrate.py
396`tools/bvh_geometry_check.py` says whether the geometry given to a rehydration is the geometry the BLAS was built 831`tools/bvh_geometry_check.py` says whether the geometry given to a rehydration is the geometry the BLAS was built
397from, using what the dehydrated stream stores (§4a): leaves inside and equal to `sceneBounds`, stored box overrides 832from, using what the dehydrated stream stores (§4a): leaves inside and equal to `sceneBounds`, stored box overrides
398consistent with the rehydrated slots, and paired leaves sharing an edge in the index buffer, which needs no positions. 833consistent with the rehydrated slots, and paired leaves sharing an edge in the index buffer, which needs no positions.
399On the 8 samples the right geometry passes every check and a wrong decode fails (175 of 181 leaves outside, or 11 of 834On the 10 samples the right geometry passes every check and a wrong decode fails (175 of 181 leaves outside, or 11 of
40023 overrides inconsistent). 83523 overrides inconsistent).
401 836
402```powershell 837```powershell
@@ -404,17 +839,45 @@ python -I tools/bvh_geometry_check.py <dehydrated.bin> --geom <vertices.f32>[,<i
404python -I tests/test_bvh_geometry_check.py 839python -I tests/test_bvh_geometry_check.py
405``` 840```
406 841
842`tools/bvh_packing_check.py` checks the §4a packing on every stream of a pack, without geometry. The checks are
843listed in §4a and in the tool's docstring. It scans an `.rpf` the way `tools/bvh_index.py` does, in parallel windows
844(a stream belongs to the window it starts in). A `bvh4-chunk` is joined with the streams after it up to its
845declared end. The joined streams are counted as `continuation`, once each, even when one starts in the next window.
846The tool also takes carved stream files (`--header-offset 256` for a whole payload).
847
848The JSON report holds offsets and counts only: stream kinds, streams checked and passed, and failures per reason
849with up to 20 example offsets. It also holds summed statistics: nodes, leaves, child pointers by type, child counts,
850levels, overrides, and where the root sits.
851
852Measured on Windows with 14 workers:
853
854| pack | time | streams passed |
855|---|---:|---:|
856| `core_bvh4.rpf` | 235 s | 271,637 / 271,637 |
857| `shared_minigame000_bvh4.rpf` | 3 s | 1,237 / 1,237 |
858
859The exit status is 1 when a stream fails.
860
861```powershell
862python -I tools/bvh_packing_check.py <core_bvh4.rpf> --json <temp>/packing.json
863python -I tools/bvh_packing_check.py <stream.bin> --header-offset 256
864python -I tests/test_bvh_packing_check.py
865```
866
407`tools/bvh_match.py` finds the drawable geometry a dehydrated BLAS was built from, on top of `rpf9dump`'s model 867`tools/bvh_match.py` finds the drawable geometry a dehydrated BLAS was built from, on top of `rpf9dump`'s model
408export rather than a second decoder. It reads the leaf signature (triangles per geometry index, a leaf that holds two 868export rather than a second decoder. It reads the leaf signature (triangles per geometry index, a leaf that holds two
409primitives counting as two), keeps every (drawable, model) of a `rpf9dump models` manifest whose per-geometry triangle 869primitives counting as two), keeps every (drawable, model) of a `rpf9dump models` manifest whose per-geometry triangle
410counts contain that signature as an ordered subsequence, and checks the survivors with 870counts contain that signature as an ordered subsequence, and checks the survivors with
411`tools/bvh_geometry_check.py` from the model's exported OBJ and the 3x4 at `+0x50` of the instance descriptor. The 871`tools/bvh_geometry_check.py` from the model's exported OBJ and the 3x4 at `+0x50` of the instance descriptor. The
412geometries of the two shaders the BVH leaves out are filtered with `--skip-shaders`: those name hashes are game data, 872geometries the BVH leaves out are filtered by render bucket (§4a, ASSET-349: kept when the low 7 bits are 0 or 3);
413as §4a says, so the rule is off unless the user passes them. A geometry whose shader index the manifest cannot resolve 873`--no-bucket-rule` turns that off and `--skip-shaders` adds shader name hashes on top (game data, local use only). A
414keeps its place and the checks decide. Measured on the ten BLAS of the sample pack, against the first 1 GiB window of 874model with a geometry whose bucket the manifest cannot resolve keeps every geometry and the checks decide. Measured on the ten BLAS of the sample pack, against the first 1 GiB window of
415`levels.rpf` cut at 3 GB (exported as a whole slice): 1,228 models, 1 to 374 candidates from the signature per BLAS, 875`levels.rpf` cut at 3 GB (exported as a whole slice): 1,228 models, 1 to 374 candidates from the signature per BLAS,
416and exactly one consistent candidate each. A window holds one region's drawables, so a BLAS whose drawable is 876and exactly one consistent candidate each. A window holds one region's drawables, so a BLAS whose drawable is
417elsewhere in the archive finds no candidate in it at all, and the tool says so instead of reporting a rejection. 877elsewhere in the archive finds no candidate in it at all, and the tool says so instead of reporting a rejection. The
878same holds for a BLAS built from another LOD: `rpf9dump models` decodes only the first LOD of a drawable (`+0x50`),
879and 101 of the 124 archetypes of the §4a interior that have a BLAS are built from the second (`+0x58`), so an export
880of the whole archive finds no candidate for them either.
418 881
419`rpf9dump models` and `rpf9dump textures` take `--start`/`--length` to export a window of a file. A window need not be a 882`rpf9dump models` and `rpf9dump textures` take `--start`/`--length` to export a window of a file. A window need not be a
420valid archive - a slice of `levels.rpf` cut at an offset has no `9FPR` header - because both modes read every resource 883valid archive - a slice of `levels.rpf` cut at an offset has no `9FPR` header - because both modes read every resource
@@ -423,7 +886,7 @@ from its own compression blocks; a sub-range is never written to the index cache
423```powershell 886```powershell
424dotnet build tools/rpf9dump/rpf9dump.csproj -c Release 887dotnet build tools/rpf9dump/rpf9dump.csproj -c Release
425dotnet tools/rpf9dump/bin/Release/net8.0/rpf9dump.dll models <levels.rpf> <out> --start 3221225472 --length 1073741824 888dotnet tools/rpf9dump/bin/Release/net8.0/rpf9dump.dll models <levels.rpf> <out> --start 3221225472 --length 1073741824
426python -I tools/bvh_match.py <dehydrated.bin> <out>/levels/models/manifest.json --descriptor <instance208.bin> [--skip-shaders H,H] 889python -I tools/bvh_match.py <dehydrated.bin> <out>/levels/models/manifest.json --descriptor <instance208.bin> [--no-bucket-rule] [--skip-shaders H,H,...]
427python -I tests/test_bvh_match.py 890python -I tests/test_bvh_match.py
428``` 891```
429 892
@@ -439,13 +902,35 @@ repository:
4394. `tools/bvh_rehydrate.py` on the same stream with those buffers and `--transform` gives the runtime layout, 9024. `tools/bvh_rehydrate.py` on the same stream with those buffers and `--transform` gives the runtime layout,
440 byte-identical to what `XboxBvhBuilder.dll` writes on these samples (§4a). 903 byte-identical to what `XboxBvhBuilder.dll` writes on these samples (§4a).
441 904
442With the two excluded shader hashes the run answers with one consistent candidate per sample; without them every 905With the excluded shader hashes the run answers with one consistent candidate per sample; without them every
443candidate is checked and the checks decide. Measured on the window above: 1,228 models in the export, 1 to 374 906candidate is checked and the checks decide. Measured on the window above: 1,228 models in the export, 1 to 374
444candidates from the signature per sample, and a rehydrated structure of `64 * (totalSizeIn64BNodes + 1)` bytes from 907candidates from the signature per sample, and a rehydrated structure of `64 * (totalSizeIn64BNodes + 1)` bytes from
445the header. Its root parent-table entry is `0xFFFFFFFF` in all eight identified samples (the entry at 908the header. Its root parent-table entry is `0xFFFFFFFF` in all eight samples identified first (the entry at
446`offsetToParents` read signed, plus `4 * ((root - offsetToElements) / 64)`), which is what the GPU builder writes 909`offsetToParents` read signed, plus `4 * ((root - offsetToElements) / 64)`), which is what the GPU builder writes
447for a root and what `tools/xdxr_bvh.py validate` requires since #2625. 910for a root and what `tools/xdxr_bvh.py validate` requires since #2625.
448 911
912`tools/image_bvh_census.py` (standard library only) counts how the game's shaders call `image_bvh*_intersect_ray`:
913sites per form, the descriptor fields at each site, and how the four result words are read, as ratio (divided by word
9141), high_half (`sext(w1[31:16])` into `v_mul_i32_i24`), raw integer, raw float, raw other or select. It walks forward
915from each call with an EXEC lane rule (its docstring has the rule and the categories), and it prints counts,
916mnemonics and field values only. On the 1.0.2.1 disassembly: 716 sites in 64 CS (638 `image_bvh_intersect_ray`, 78
917`image_bvh64_intersect_ray`). The descriptor has box_grow 0, box_sort_en 1, size all ones, triangle_return_mode 1,
918llc_noalloc 0, big_page 1 and type 8 at all 716 sites. On every path from the call, 397 sites take `v_rcp_f32` of
919word 1 and multiply word 0 by it (`v_mul_f32` 244, `v_mul_legacy_f32` 153), 335 of them words 2 and 3 as well, and
920they read the high half of word 1. That high half's product is compared with `v_cmp_lt_i32` against -1 at 319 sites
921and `v_cmp_gt_i32` against 0 at 78. All 716 read the words as integers: 397 sites through `v_lshlrev_b32`,
922`v_and_or_b32`, `v_lshl_or_b32` and `v_or3_b32`, and 319 through `v_cmp_eq_u32` only. No site reads a word as an
923undivided float, a memory operand or a select on every path. These are static candidates, not traces. 633 sites also
924have reads on some paths only, where the register can also hold another value, and the census leaves them
925unclassified. Of the 548 sites with such a raw-float read, 506 have every one after a later call in program order and
92642 have one before the next call. The census does not follow the next pass of a loop around the call, or a value that
927goes through memory.
928
929```powershell
930python -I tools/image_bvh_census.py <work>/shaders/dxbc/disasm --out <temp>/image_bvh_census.json
931python -I tests/test_image_bvh_census.py
932```
933
449## 7a. Building runtime BVHs: `tools/xdxr_bvh.py` 934## 7a. Building runtime BVHs: `tools/xdxr_bvh.py`
450 935
451The Vulkan layer has to write acceleration structures in this runtime layout, because the game's traversal shaders 936The Vulkan layer has to write acceleration structures in this runtime layout, because the game's traversal shaders
@@ -480,6 +965,14 @@ nodes: slots (0, 1, 2) for every type and (V, W) as the barycentrics, because RA
480node. It now reads the slots of the node type and applies the remap byte. AMD GPURT 965node. It now reads the slots of the node type and applies the remap byte. AMD GPURT
481(`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the XDXR path agree on both. TRI1 nodes 966(`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the XDXR path agree on both. TRI1 nodes
482therefore traverse to the right triangle (docs/design.md, Ray tracing row; `tests/semantic/test_image_bvh_tri.py`). 967therefore traverse to the right triangle (docs/design.md, Ray tracing row; `tests/semantic/test_image_bvh_tri.py`).
968Its four triangle words are the ones native RDNA2 returns (docs/design.md, Ray tracing row; measured on an RX 6800
969with the kernels `tools/bvh_tri_probe.py` builds, `tests/semantic/test_image_bvh_tri_hw.py`): k·(T, det, b_i, b_j)
970with k = |d[kz]|³ on a hit, and on a miss copysign(inf, k·det) in word 0 with the other three kept, where the step
971above returns (inf, 1, 0, 0). A ray exactly on an edge or a vertex follows RDNA2's tie rule (docs/design.md, Ray
972tracing row): the zero edge from P to Q passes when ty = 0 ? sign(det)·tx > 0 : sign(d[kz])·sign(det)·ty > 0, with
973(tx, ty) = Q′ − P′ sheared and the d[kz] < 0 swap undone. It was read off measured x/y-dominant rows and then predicted
974the z-dominant rows before they ran; the step above and RADV break those ties differently. Measured on gfx1030 only,
975with dyadic inputs.
483 976
484**GPU builder.** `runtime/src/xdxr_build.comp` with `xdxr_build.h` writes the same layout on the GPU, straight into 977**GPU builder.** `runtime/src/xdxr_build.comp` with `xdxr_build.h` writes the same layout on the GPU, straight into
485the destination buffer: 978the destination buffer:
@@ -489,9 +982,50 @@ the destination buffer:
4892. a 30-bit Morton key of each box centre, then a stable sort: up to 1,024 keys in one workgroup's shared memory 9822. a 30-bit Morton key of each box centre, then a stable sort: up to 1,024 keys in one workgroup's shared memory
490 (one dispatch), more with a radix sort of 8 passes of 4-bit digits over 256-element tiles (24 dispatches 983 (one dispatch), more with a radix sort of 8 passes of 4-bit digits over 256-element tiles (24 dispatches
491 whatever the count, no padding to a power of two); 984 whatever the count, no padding to a power of two);
4923. BOX32 nodes, built level by level from four consecutive sorted children, with the parent table and each 9853. a binary radix tree over the sorted keys (Karras 2012; equal keys are told apart by their sorted position), one
493 instance's `ParentNode`; 986 thread per inner node;
4944. the header. 9874. the inner nodes: those at an even depth of the binary tree, each taking the children of its children (two to
988 four), numbered in sorted order by a scan, so the root is node 0; with the parent table. They are BOX32, or
989 BOX16 (below), and TRI1 pairing (below) happens here;
9905. the boxes, bottom-up in one dispatch: each element writes its box into its parent's slot and merges it into the
991 parent's accumulator; the last child to arrive carries on with the parent's box. The invocations meet only
992 through atomics ordered by `memoryBarrierBuffer`, so no plain load reads another workgroup's store of the same
993 dispatch. An instance's `ParentNode` is written here;
9946. the header.
995
996The tree used to group four consecutive sorted elements per node, level by level. Those groups ignore where the
997Morton prefix changes, so sibling boxes overlapped and a ray took about twice as many steps (found by DaniSBR1 on
998D3D-410). Measured with `xdxr_bvh.py check-build`, which counts the traversal steps (one per node or triangle
999tested, the work of one `image_bvh_intersect_ray`) over 1,000 random rays per case:
1000
1001| Case | Steps per ray, four consecutive | Steps per ray, radix tree |
1002|---|---|---|
1003| `blas_three_sort_tiles` (5,000 random triangles) | 42.0 | 23.0 |
1004| `blas_box16_sort_tiles` (the same, BOX16) | 43.9 | 23.7 |
1005| `blas_paired_sort_tiles` (7,200-triangle grid, TRI1 pairing) | 37.6 | 19.5 |
1006| `blas_random` (1,000 random triangles) | 24.1 | 16.0 |
1007| `blas_grid_u16_stride16` (288-triangle height grid) | 11.0 | 8.0 |
1008| `blas_refit_in_place` (3,000 triangles, refitted after moving) | 74.8 | 55.5 |
1009| `tlas` (4 instances) | 26.3 | 18.1 |
1010
1011Every ray finds the same hit as brute force in both. A CPU model of the choice (a scratch script, not kept) gave
101235.1 steps per ray for a greedy surface-area collapse of the same radix tree, 35.8 for the largest-subtree one and
101335.7 for the even-depth one this builder uses, against 76.8 for four consecutive elements (5,000 random triangles;
101411.2, 11.4, 11.5 and 24.4 on a height field). The even-depth collapse is the only one of the three that needs no
1015pass from the top down.
1016
1017The cost is in the build and in memory. Wall clock of `vk_xdxr_build_test <dir> <n>` (random triangles, best of 3):
1018
1019| GPU | Triangles | Build before → after (ms) | Refit before → after (ms) |
1020|---|---|---|---|
1021| RTX 5090 | 1,000 | 0.17 → 0.17 | 0.10 → 0.09 |
1022| RTX 5090 | 1,000,000 | 5.50 → 5.99 | 4.12 → 4.28 |
1023| Radeon iGPU (gfx1036) | 1,000 | 0.17 → 0.23 | 0.09 → 0.10 |
1024| Radeon iGPU (gfx1036) | 1,000,000 | 133 → 180 | 41.8 → 62.2 |
1025
1026On the iGPU about half of the refit's increase is the accumulator atomics (measured before BOX16 and pairing). The tree has more nodes: about one per
1027two elements, against one per three. A build writes 137,856 bytes for 1,000 triangles where it wrote 113,536, and
1028the layout leaves room for the most a tree can have.
495 1029
496The radix sort's scan writes the prefix sums of the digit counts to their own scratch array, not over the counts. 1030The radix sort's scan writes the prefix sums of the digit counts to their own scratch array, not over the counts.
497No invocation of the builder stores to a word and then uses a value it loaded from that word earlier. SPIRV-Cross 1031No invocation of the builder stores to a word and then uses a value it loaded from that word earlier. SPIRV-Cross
@@ -506,8 +1040,56 @@ MoltenVK: `xdxr_build_check` found about 130 of 200 rays wrong in `blas_three_so
506KosmicKrisp and on llvmpipe. A pointer from `OpConvertUToPtr`, which the translator uses, kept its load before the 1040KosmicKrisp and on llvmpipe. A pointer from `OpConvertUToPtr`, which the translator uses, kept its load before the
507store in the same test. 1041store in the same test.
508 1042
509The tree's shape depends only on the element count. `XdxrLayout` therefore computes the result and scratch sizes 1043**BOX16 nodes.** A bottom-level build with `MINIMIZE_MEMORY` writes BOX16 inner nodes: 64 bytes, not 128, so a BLAS
510exactly when the build is recorded, and the same numbers can answer `GetRaytracingAccelerationStructurePrebuildInfo`. 1044is about a fifth smaller (39,040 bytes against 48,768 for the 428-triangle BLAS of `d3d12_xdxr_rt_test`). The tree
1045is the same; only the node records and their offsets change, and
1046`GetRaytracingAccelerationStructurePrebuildInfo` gives the smaller size when it gets the same flag. Each child box
1047is rounded outward to halves (min toward -inf, max toward +inf) from the exact box, which the builder keeps in its
1048accumulators, so the rounding does not add up from level to level. The rounding is integer code, because `packHalf2x16`
1049rounds in an implementation-defined way (AMD's driver rounds toward zero). Beyond the half range a bound becomes
1050+-inf on its outward side and +-65504 on its inward side, so an empty slot (min +inf, max -inf) is still empty. A
1051bound smaller than the smallest normal half (2^-14) in magnitude becomes 0 or +-2^-14, whichever is on its outward
1052side, never a half denormal: a decoder that flushes those to zero would make the box smaller. `tools/xdxr_bvh.py`
1053`half_round` does the same, and `check-build` compares every BOX16 word bit for bit with `encode_box16` of the exact
1054box of the triangles under that child. Top-level builds keep BOX32 whatever the flags, because they are in world
1055space, where a half's step reaches 2 m at 2,048 m and 4 m at 4,096 m. An update must pass the same flags as its
1056build (D3D12 requires it), so a refit keeps the node type. **ASSUMPTION:** that `MINIMIZE_MEMORY` is the console's
1057switch for BOX16. The offline BLASes in the `*_bvh4.rpf` packs have BOX16 roots (§3.1), but `XboxBvhBuilder.dll`'s
1058choice between the two at run time is not traced. The one traced datum points at a finer rule: `docs/xdxr.md` §3
1059finds a different bottom-level path that needs `MINIMIZE_MEMORY` and a stream setting (type 0, `+0x08`) above 10.0,
1060so the flag alone may not be the switch. A bottom-level structure authored in world coordinates gets looser boxes
1061from BOX16 the same way a top-level one would: slower to trace, never wrong. A BOX16 build ends with one spare,
1062zeroed 64-byte unit after the last node it wrote, and the header's size counts it: the translator's
1063`image_bvh_intersect_ray` loads a box node's 112 bytes of BOX32 bounds before it checks the type, so the last
106464-byte node would otherwise be read past the structure, or past a compacted copy of it.
1065
1066**TRI1 pairing.** A bottom-level build without `ALLOW_UPDATE` pairs triangles into TRI0/TRI1 leaves, as the console
1067builder does in its offline BLASes (§4a, check 4 of "How a match is verified"). The pass that writes the nodes
1068pairs each triangle child of a node with a later triangle child of the same node (among its at most four children)
1069when four things hold. The two must share an edge in opposite directions, with the same two vertices bit for bit. They must come from
1070the same geometry, since a leaf holds one `GeometryIndexAndFlags`. And both must be active. The first triangle is
1071rotated so the shared edge is slots 1 -> 2, the sibling's third vertex goes in slot 3, its primitive index in
1072`PrimitiveIndex2`, and each node type's remap byte returns D3D12's barycentrics for its own vertex order. The node
1073still has one child per triangle, each with its own box: the TRI1 child points at the first triangle's leaf, and the
1074sibling's own leaf is left unused. The tree, the layout and the sizes are therefore the same as without pairing.
1075Nothing is saved yet: reclaiming the unused leaves would need a compaction that moves records and rewrites pointers,
1076and compaction here copies bytes. What pairing gives is the console's leaf format, with a pair's two triangles in
1077one 64-byte record. Because pairs never cross nodes, one thread owns each leaf it rewrites, and both pointers of a
1078pair have the same parent, so the parent table has one writer per entry. The pass records each triangle's pointer
1079(TRI0, or TRI1 for the sibling) in scratch, so the bottom-up box pass finds the sibling's slot through the first
1080triangle's leaf. On a sorted grid of 7,200 triangles, 2,208 of the 3,600 possible pairs form (2,625 with the tree of four
1081consecutive elements: a radix-tree node often has an inner node among its children, and only triangle children
1082pair). A refit rewrites every leaf as one triangle, so a structure that may be updated is
1083not paired. **ASSUMPTION:** that pairing only siblings is close enough. The console builder's pairing rule is not
1084traced; `tools/xdxr_bvh.py` `build_blas(pair=True)` pairs greedily over the whole mesh instead, and both traverse
1085the same way. `check-build` compares barycentrics as well as hits, and checks that a paired case has TRI1 nodes and
1086that cases that must not pair (other geometry, same direction) have none.
1087
1088The node count depends on the keys. A kept node has two children only when both of its binary children are
1089elements, so with N elements there are at most (3N - 2) / 4 nodes. `XdxrLayout` computes the result and scratch
1090sizes for that many when the build is recorded, and the same numbers answer
1091`GetRaytracingAccelerationStructurePrebuildInfo`. The header's `totalSizeIn64BNodes` counts only the nodes the build
1092wrote.
511A triangle with a NaN vertex gets an empty box (D3D12 treats it as inactive). So do an instance with mask 0, one with 1093A triangle with a NaN vertex gets an empty box (D3D12 treats it as inactive). So do an instance with mask 0, one with
512no BLAS and one with a singular transform. An instance record holds its BLAS address in 256-byte units in 32 bits, 1094no BLAS and one with a singular transform. An instance record holds its BLAS address in 256-byte units in 32 bits,
513so BLAS addresses must be below 2^40, as console GPU addresses are. Where device addresses are wider (llvmpipe's are 1095so BLAS addresses must be below 2^40, as console GPU addresses are. Where device addresses are wider (llvmpipe's are
@@ -522,23 +1104,25 @@ scene. `xdxr_bvh.py check-build <dir>` validates them and traces rays against br
522`xdxr_build` and `xdxr_build_check`. 1104`xdxr_build` and `xdxr_build_check`.
523 1105
524**Updates** (D3D12 `PERFORM_UPDATE`) refit: the source structure is copied to the destination unless it is the 1106**Updates** (D3D12 `PERFORM_UPDATE`) refit: the source structure is copied to the destination unless it is the
525destination, the elements are rewritten at their slots, and each node's boxes are recomputed bottom-up from the 1107destination (as many bytes as its header gives, so a compacted source works too), the elements are rewritten at
526children it already points to. The tree is kept, so a refit is valid for any motion and skips the Morton pass and 1108their slots, and each node's boxes are recomputed bottom-up from the children it already points to, through the
527the sort. It takes 0.07 ms for 1,000 triangles and 9.8 ms for 1,000,000 on an RTX 2050, against 0.19 ms and 22 ms for 1109parent table, by the same pass as a build. The tree is kept, so a refit is valid for any motion and skips the Morton pass and
528a build, but the tree traverses more slowly as the geometry moves away from where it was built. 1110the sort. It took 0.07 ms for 1,000 triangles and 9.8 ms for 1,000,000 on an RTX 2050, against 0.19 ms and 22 ms for
1111a build, with the tree of four consecutive elements (the radix tree's times are above). The tree traverses more
1112slowly as the geometry moves away from where it was built.
529 1113
530**Copies and postbuild info.** `CopyRaytracingAccelerationStructure` with `CLONE` or `COMPACT` copies the 1114**Copies and postbuild info.** `CopyRaytracingAccelerationStructure` with `CLONE` or `COMPACT` copies the
531structure's bytes. The records are position-independent: node pointers count from the structure's start, and a TLAS 1115structure's bytes. The records are position-independent: node pointers count from the structure's start, and a TLAS
532names its BLASes by address, which a clone keeps. The size comes from the source header (`totalSizeIn64BNodes`), so 1116names its BLASes by address, which a clone keeps. The size comes from the source header (`totalSizeIn64BNodes`), so
533a copy can follow a build in the same command list, and it is bounded by the destination resource. A build is 1117a copy can follow a build in the same command list, and it is bounded by the destination resource. A build's size
534already exactly its layout's size, so `COMPACTED_SIZE` and `CURRENT_SIZE` (from 1118is the nodes it wrote, so `COMPACTED_SIZE` and `CURRENT_SIZE` (from
535`EmitRaytracingAccelerationStructurePostbuildInfo` or the postbuild descs of a build) are both 1119`EmitRaytracingAccelerationStructurePostbuildInfo` or the postbuild descs of a build) are both
536`64 * (totalSizeIn64BNodes + 1)`, and compaction saves nothing. Serialization, deserialization and the tools-visualization 1120`64 * (totalSizeIn64BNodes + 1)`, and compaction gives back the room the layout left for more nodes. Serialization, deserialization and the tools-visualization
537mode are refused at replay as unsupported, not faked. In `LEONIDA_RT_AS=khr` mode the postbuild descs stay ignored, 1121mode are refused at replay as unsupported, not faked. In `LEONIDA_RT_AS=khr` mode the postbuild descs stay ignored,
538as before. 1122as before.
539 1123
540Not done yet: pairing triangles into TRI1 leaves, BOX16 nodes, serialization. A higher-quality build (SAH) would also 1124Not done yet: serialization; a compaction that reclaims the leaves that pairing leaves unused. A surface-area
541come later. 1125collapse of the radix tree, or treelet restructuring, would trim a few more steps.
542 1126
543```powershell 1127```powershell
544python -I tools/xdxr_bvh.py selftest --seed 1 --rays 400 # build BLASes, compare closest hits with brute force 1128python -I tools/xdxr_bvh.py selftest --seed 1 --rays 400 # build BLASes, compare closest hits with brute force
@@ -546,6 +1130,32 @@ python -I tools/xdxr_bvh.py validate <dumped BVH buffer> # structural check o
546python -I tests/test_xdxr_bvh.py 1130python -I tests/test_xdxr_bvh.py
547``` 1131```
548 1132
1133## 7b. The first real pack BLAS on a GPU
1134
1135Measured on the 1.0.2.1 package with the tools above; counts and offsets only.
1136
1137* `core_bvh4.rpf` indexes to **271,637 BVH4 streams / 1,896,784,254 nodes (121.4 GB inflated)** in 1,034 s.
1138* The first BLAS (stream at `0x12060`, 39,257 nodes, 2,512,512 bytes rehydrated) matches **one** drawable among the
1139 258,037 models an export of `levels.rpf` produced: 12 geometries, 21,814 leaves, 0 leaves outside, 335/0
1140 overrides, area ratio 1.000 (`bvh_match.py`, `bvh_geometry_check.py`, `bvh_rehydrate.py` on the user's copy).
1141* The rehydrated header's `rootNodePtr` is the **dehydrated** root; the runtime root is the first node of the last
1142 entry of the level table at the end of the structure. The leaves are in the leaf frame (`(R*v - t)*s`): the header
1143 `sceneBounds` are the pre-frame AABB (±2.5), the leaf vertices are scaled (≈19,040), so test rays are built from a
1144 leaf's own vertices.
1145* Descriptor base: the descriptor's dword0 is the base in **256-byte units**; the game passes `ptr >> 8` there, and
1146 the `| 0x30` its shader ORs is only the temporary address it uses for the `rootNodePtr` load, not the descriptor
1147 base. Measured at base 0 and at base 0x1000 (structure copied to VA 0x1000, dword0 `0x10`): the game's RT shadow
1148 CS (`deferred_tiled` family, 32-bit form) on the RTX 2060 returns the CPU walker's children in the same order at
1149 both. Its second traversal site still needs the executable.
1150* The base and the address formula were also measured on the **native instruction**, with no emulation in the path:
1151 `tools/hw_oracle` ran `image_bvh_intersect_ray` and `image_bvh64_intersect_ray` on gfx1036 (Ryzen 9 9950X3D iGPU,
1152 driver 32.0.21030.2001) over hand-built box32 nodes, a decoy node at the buffer start and the real one at +0x1000.
1153 dword0 `(P >> 8) + 0x10` with node `0|5`, and dword0 `(P >> 8) + 0x08` with node `0x800>>3|5`, both traverse the
1154 node at `P + 0x1000`: address = base × 256 + (node & ~7) × 8, and the base and the node offset add. The control
1155 (base `P >> 8`, node `0|5`) reads the decoy. Both instruction widths agree. Not exercised: descriptor bits 39:32
1156 (the buffer fits in 32 bits), nodes other than box32, and a `0x1030`-style dword0, which the hardware would read as
1157 base 0x103000.
1158
549## 8. No-sharing rule 1159## 8. No-sharing rule
550 1160
551Nothing from the packs may be committed: no `.rpf`, carved stream, decompressed buffer, XML text, tile list, 1161Nothing from the packs may be committed: no `.rpf`, carved stream, decompressed buffer, XML text, tile list,
diff --git a/docs/character_models.md b/docs/character_models.md
index adfb161da..ff1fe1dee 100644
--- a/docs/character_models.md
+++ b/docs/character_models.md
@@ -12,9 +12,6 @@ No game data is reproduced here.
12- A `.#ft` fragment carries the shared 597-name humanoid skeleton and the character's bounds. The 12- A `.#ft` fragment carries the shared 597-name humanoid skeleton and the character's bounds. The
13 measured skeleton is in [character_skeleton.md](character_skeleton.md). 13 measured skeleton is in [character_skeleton.md](character_skeleton.md).
14 14
15The current exporter writes every fragment as a **25-vertex bounds cube** with `Embedded: null`
16(2,865 of 2,865). Fragment child drawables are not walked, so a part that exists only as a
17fragment child is not in the OBJ/GLB output even though its parent fragment is.
18The current exporter writes every fragment as a **flat 25-vertex / 32-triangle bounds grid** (a 5x5 15The current exporter writes every fragment as a **flat 25-vertex / 32-triangle bounds grid** (a 5x5
19grid at z=0, `Min`/`Max` z = 0) with `Embedded: null` (2,865 of 2,865). Fragment child drawables 16grid at z=0, `Min`/`Max` z = 0) with `Embedded: null` (2,865 of 2,865). Fragment child drawables
20are not walked, so a part that exists only as a fragment child is not in the OBJ/GLB output even 17are not walked, so a part that exists only as a fragment child is not in the OBJ/GLB output even
@@ -32,8 +29,8 @@ The decoded export used by the previews contains 13 parts:
32| head L2 | same | 599 | 514 | same preset | 29| head L2 | same | 599 | 514 | same preset |
33| eyes | `…_head_fr1_lat_000_m_eyes.#dr` | 434 | 816 | `0x429453B7A2EB9980` (sRGB + alpha) | 30| eyes | `…_head_fr1_lat_000_m_eyes.#dr` | 434 | 816 | `0x429453B7A2EB9980` (sRGB + alpha) |
34| eyecap | `…_head_fr1_lat_000_m_eyecap.#dr` | 214 | 304 | `0x5CE55BAA340248BD` (sRGB + alpha) | 31| eyecap | `…_head_fr1_lat_000_m_eyecap.#dr` | 214 | 304 | `0x5CE55BAA340248BD` (sRGB + alpha) |
35| hands | `hand_fr1_000_nude_cull.#dr` | 10,440 | 13,534 | none in the package — `0x4D89F2311DBBB7A8` is in no TTPF pool (see [Hands and feet](#hands-and-feet)) | 32| hands | `hand_fr1_000_nude_cull.#dr` | 10,440 | 13,534 | no exact hit for `0x4D89F2311DBBB7A8` in the 57 scanned TTPF pools (see [Hands and feet](#hands-and-feet)) |
36| feet | `feet_fr1_000_full.#dr` | 2,309 | 4,082 | none in the package — `0xA54D9F8B51CA6034` is in no TTPF pool (see [Hands and feet](#hands-and-feet)) | 33| feet | `feet_fr1_000_full.#dr` | 2,309 | 4,082 | no exact hit for `0xA54D9F8B51CA6034` in the 57 scanned TTPF pools (see [Hands and feet](#hands-and-feet)) |
37| body (legacy) | `cs_lucia_legacypedcs_fr1_000_fullbody_ws00_full.#dr` | 874 | 908 | `0x996FDBA2DB30CC12` | 34| body (legacy) | `cs_lucia_legacypedcs_fr1_000_fullbody_ws00_full.#dr` | 874 | 908 | `0x996FDBA2DB30CC12` |
38| legacy head | `cs_lucia_legacyheadcs_fr1_001_regular_ws00_full.#dr` | 592 | 1,028 | `0x707771F769AA3542` | 35| legacy head | `cs_lucia_legacyheadcs_fr1_001_regular_ws00_full.#dr` | 592 | 1,028 | `0x707771F769AA3542` |
39| jacket (biker) | `cs_lucia_jacketbiker_fr1_000_regular_c_hl_long_full.#dr` | 9,818 | 10,837 | none — `speculartex` only (`0xF5073AA039BB3CED`) | 36| jacket (biker) | `cs_lucia_jacketbiker_fr1_000_regular_c_hl_long_full.#dr` | 9,818 | 10,837 | none — `speculartex` only (`0xF5073AA039BB3CED`) |
@@ -130,7 +127,7 @@ the export binds the slot (1,372 of 1,372). Both keys are 512x256 `BC3_UNORM_SRG
130other textures (`0x93CB433D30220BA6` and `0x5D237CCCD91F8E4D`, 256x128 `BC7_UNORM`), where the 127other textures (`0x93CB433D30220BA6` and `0x5D237CCCD91F8E4D`, 256x128 `BC7_UNORM`), where the
131jacket's and the crop tee's table keys are `BC7_UNORM` `speculartex` sheets themselves. 128jacket's and the crop tee's table keys are `BC7_UNORM` `speculartex` sheets themselves.
132 129
133The hands and feet bind an albedo key that is not in the package (see [Hands and feet](#hands-and-feet)). 130The hands and feet bind albedo keys with no exact hit in the scanned TTPF catalogs (see [Hands and feet](#hands-and-feet)).
134The head drawable has no material texture reference, but its face is selected by 131The head drawable has no material texture reference, but its face is selected by
135a **head-skin preset** keyed by the head name's `joaat32`: 132a **head-skin preset** keyed by the head name's `joaat32`:
136 133
@@ -144,22 +141,27 @@ The preset library covers 897 heads; `cs_lucia_head_fr1_lat_000_y_full` is not i
144### Hands and feet 141### Hands and feet
145 142
146Measured against the catalogs of all 57 TTPF pools (357,115 textures). The hands and the feet bind 143Measured against the catalogs of all 57 TTPF pools (357,115 textures). The hands and the feet bind
147the four maps on the same two shaders (`210FBC6A`, `8D69EDAB`), and **only the normal maps are in 144the four maps on the same two shaders (`210FBC6A`, `8D69EDAB`); for the two examples below,
148the package**: 145**only the normal-map keys have exact catalog hits**. "None" means no matching full 64-bit
146`AssetKey` in these scanned catalogs, not proof that no runtime source exists:
149 147
150| Part | `diffusetex` | `speculartex` | `bumptex` (normal) | `speculartex2` (ORM) | 148| Part | `diffusetex` | `speculartex` | `bumptex` (normal) | `speculartex2` (ORM) |
151|---|---|---|---|---| 149|---|---|---|---|---|
152| hands (`hand_fr1_000_*`) | `0x4D89F2311DBBB7A8` — none | `0xA805B9A446CCE950` — none | `0x9D337DABCA636906` — `ttdb_peds_2_3`, 512×1024 BC5 | `0x09D2C98C5B40D16C` — none | 150| hands (`hand_fr1_000_*`) | `0x4D89F2311DBBB7A8` — none | `0xA805B9A446CCE950` — none | `0x9D337DABCA636906` — `ttdb_peds_2_3`, 512×1024 BC5 | `0x09D2C98C5B40D16C` — none |
153| feet (`feet_fr1_000_*`) | `0xA54D9F8B51CA6034` — none | `0x752EA8A7A086558F` — none | `0x5091E86DE6196BC3` — `ttdb_peds_3_3`, 512×1024 BC7 | `0xD5C8D2A180326DE7` — none | 151| feet (`feet_fr1_000_*`) | `0xA54D9F8B51CA6034` — none | `0x752EA8A7A086558F` — none | `0x5091E86DE6196BC3` — `ttdb_peds_3_3`, 512×1024 BC7 | `0xD5C8D2A180326DE7` — none |
154 152
155Each material has ten slots; the other six bind `0x5D7A3A87CC19967D` on both shaders, which is in 153Each material has ten slots; the other six bind `0x5D7A3A87CC19967D` on both shaders, with no
156no pool either: it reads as an engine-supplied default, not a missing asset. 154exact pool hit. The [independent indexed-record check](https://github.com/ItsNotRexed/Leonida/pull/3256#pullrequestreview-6014627459)
155found this same reference in all 176 material
156rows, including the 12 positive-control rows whose four named maps all resolve. An engine-supplied
157default is a hypothesis: the repeated unresolved reference alone does not establish its runtime use.
157 158
158**They are not textured on their own.** The hands and feet share their maps with the body skin 159**Shared static material references.** The hands and feet have bindings in common with body skin
159pieces in `pack/core_restofworld/core_restofworld.rpf`: 160pieces in `pack/core_restofworld/core_restofworld.rpf`; these references do not establish runtime
161sheet selection:
160 162
161- `bodynipplesgen_fr1_000_regular_ws00_full`, the female upper body, binds **the same four keys** 163- `bodynipplesgen_fr1_000_regular_ws00_full`, the female upper body, binds **the same four keys**
162 as the hands, on the same two shaders. The hands are drawn with the upper-body skin sheet. 164 as the hands, on the same two shaders.
163- `bodygenitalsgen_f{r,b,o}1_008_regular_ws00_full`, the female lower body (and the `fr1` 165- `bodygenitalsgen_f{r,b,o}1_008_regular_ws00_full`, the female lower body (and the `fr1`
164 `_alt_00`–`_02` variants), binds the feet's 166 `_alt_00`–`_02` variants), binds the feet's
165 `speculartex`, `bumptex` and `speculartex2`, and its own `diffusetex` `0x5B6829CFEC0F41A1`, also in 167 `speculartex`, `bumptex` and `speculartex2`, and its own `diffusetex` `0x5B6829CFEC0F41A1`, also in
@@ -167,20 +169,22 @@ pieces in `pack/core_restofworld/core_restofworld.rpf`:
167- The male lower body, `bodygenitalsgen_mr1_000_*`, has all four maps in the pools 169- The male lower body, `bodygenitalsgen_mr1_000_*`, has all four maps in the pools
168 (`diffusetex` `0xBCE4D91DA23689C7`). 170 (`diffusetex` `0xBCE4D91DA23689C7`).
169 171
170So the female body skin has no albedo, specular or ORM map in the package, for the hands and feet 172The unresolved female-body albedo, specular and ORM references above also have no exact hit in
171and for the body pieces that share their sheets. The skin colour has to come from data outside these 173these pools. The recorded search found none of these keys in another resource of `data.rpf`,
172materials, as the face comes from the head-skin preset. That data was not found: none of the keys 174`common.rpf`, `script.rpf`, `packs.rpf`,
173above appears in another resource of `data.rpf`, `common.rpf`, `script.rpf`, `packs.rpf`,
174`anim.rpf`, `core_restofworld.rpf` or `core_restofworld001.rpf` (`story000.rpf` and 175`anim.rpf`, `core_restofworld.rpf` or `core_restofworld001.rpf` (`story000.rpf` and
175`story000_restofworld.rpf` recover no entries with this reader). 176`story000_restofworld.rpf` recover no entries with this reader). These are static lookup results;
177the source of skin colour and the runtime's sheet selection remain open.
176 178
177The pattern holds across the set. Of the 56 `hand_`/`feet_` drawables in `packs.rpf`, 52 bind only a 179Across 162 indexed records (176 material rows, 56 distinct `hand_`/`feet_` drawable names), all
178`diffusetex` key that is in no pool; the four exceptions with all four maps shipped are 180176 rows carry the four named references. Of the 56 names in `packs.rpf`, 52 have no exact
181diffuse-key hit in the scanned pools; the four exceptions with all four maps resolved are
179`hand_fsk1_000_nude_cull`, `feet_fsk1_000_nude_cull` and the first-person hands 182`hand_fsk1_000_nude_cull`, `feet_fsk1_000_nude_cull` and the first-person hands
180`hand_mb1_000_nude_cull_fp` and `hand_mo1_000_nude_cull_fp`. The male hands and feet 183`hand_mb1_000_nude_cull_fp` and `hand_mo1_000_nude_cull_fp`. The male hands and feet
181(`hand_mr1_000_nude_cull`, `feet_mr1_000_nude_cull`) also ship only their normal maps, and male and 184(`hand_mr1_000_nude_cull`, `feet_mr1_000_nude_cull`) also have exact hits only for their normal
182female feet bind the same `diffusetex` key. Until the skin data is decoded, render these parts with 185maps, and male and female feet bind the same `diffusetex` key. For previews, use the resolved normal
183their normal map and a flat skin tone; do not borrow another part's albedo. 186map and a flat skin tone; this is a fallback, not a reconstruction of the runtime's skin colouring.
187Do not borrow another part's albedo.
184 188
185## Materials 189## Materials
186 190
@@ -213,10 +217,6 @@ mesh.
213 217
214A raw RSC8 scan of **862,555** resources across all 13 indexed RPF9 archives (every `rageobj` 218A raw RSC8 scan of **862,555** resources across all 13 indexed RPF9 archives (every `rageobj`
215entry, unnamed pages and the >3 MiB band included; 25.6 GB compressed / 56.3 GB inflated) found 219entry, unnamed pages and the >3 MiB band included; 25.6 GB compressed / 56.3 GB inflated) found
216453 ped-skeleton resources: 342 animal bounds, 2,212 `char_bipedbounds_*` fragments, 4 mannequins
217and 73 anim clips. **0** combined a ped skeleton with the skin/flesh shader, and 0 of the 908
218resources on that shader contained a single `SKEL_*` bone name. The unnamed-resource route
219therefore does not add a body.
2202,631 ped-skeleton resources: 342 animal bounds, 2,212 `char_bipedbounds_*` fragments, 2202,631 ped-skeleton resources: 342 animal bounds, 2,212 `char_bipedbounds_*` fragments,
2214 mannequins and 73 anim clips. **0** combined a ped skeleton with the skin/flesh shader, and 2214 mannequins and 73 anim clips. **0** combined a ped skeleton with the skin/flesh shader, and
2220 of the 908 resources that use the skin/flesh shader contained a single `SKEL_*` bone name. 2220 of the 908 resources that use the skin/flesh shader contained a single `SKEL_*` bone name.
@@ -246,6 +246,140 @@ clothed, so it is not a high-detail nude body. A flat-skin render of the 874-v b
246normal map disconnected still shows the modelled top, shorts and ankle boots, so the clothing 246normal map disconnected still shows the modelled top, shorts and ankle boots, so the clothing
247silhouette is geometry, not a painted-on atlas. 247silhouette is geometry, not a painted-on atlas.
248 248
249## Modular ped construction pipeline and body assembly
250
251RAGE 9 constructs human peds from modular streamed slots rather than monolithic rigged meshes.
252Spawning a character resolves a five-stage data graph across `packs.rpf`, `data.rpf`, `common.rpf`,
253`anim.rpf` and `data/ttdb/peds/*.ttpf`:
254
2551. **Identity and archetype table.** `packs.rpf` archetype PSO (`00011d1ff000.pso`, root
256 `0xdd77771e`, 2,714 records, 384 B/record) holds each archetype's `joaat32` hash (`+0x08`) and
257 voice/short name (`+0x174`).
2582. **Outfit slot resolution.** `packs.rpf` outfit-slot PSO (`00011cfbf000.pso`, root `0x890aca98`,
259 2,713 archetypes -> 33,621 outfit hashes) maps each archetype to valid outfit slot hashes with a
260 1:1 link to compiled `0DRP` appearance catalogues.
2613. **Compiled appearance catalogues (`0DRP`) and variation pools.** 2,709 resource-packed `0DRP`
262 catalogues (`0x8dcb4cf5`, v122), the wardrobe catalogue (`00011ccb2000.pso`, 19,827 presets) and
263 80 `0x1edee47e` variation PSOs resolve 88 B presets (`0xf795e8ba`) and 184 B wearable states
264 (`0x37e52277`) to `murmur64` drawable, albedo, normal and `cull_drawable` (`0x46e1a048`) keys.
2654. **Modular geometry, skeleton, deformation and strand grooms.** Three streamed geometry LOD tiers
266 per slot, master `crSkeletonData` in `ambient_*` fragments (454–596 named bones; see
267 [character_skeleton.md](character_skeleton.md#master-skeletons-and-standing-space)),
268 `char_bipedbounds_*` collision rigs, 6,756 quantized blend-shape delta buffers, 449 ML Deformer
269 weight models and 5,751 `smh` GPU strand grooms (20,046 LOD resources; hair drawables in
270 `packs.rpf` are 3-vertex / 1-triangle stubs).
2715. **GPU compute skinning, morphing and deferred/RT shading.** `ped_morphable_model_cs` ->
272 `ped_standard_head_cs` (blendshapes, sticky lips, per-meshlet stretch/wrinkles) ->
273 `ped_skinning_cs` -> `ped_skin_processing` / `ped_standard_skin_tattoo_bake` -> `bvh_skinning`
274 -> `meshlet_culling` (`CS_BatchCullPreSkinnedMeshlets`) -> deferred G-buffer, GPU subsurface
275 scattering and ray-tracing resolve.
276
277### Standing-space coordinate convention
278
279All human modular drawables share a single standing skeleton space anchored at
280**`SKEL_ROOT = (0, 0, +1.0 m)`** in RAGE Z-up (`(0, +1.0 m, 0)` in glTF Y-up). Vertex buffers
281store root-relative bind positions (feet sit near `Z = -1.0 m`), while drawable bounding boxes
282(`root + 0x30..0x4f`) store standing-space bounds. Translating skinned parts by `(0, 0, +1.0 m)`
283aligns `head`, `eyes`, `eyecap`, `teeth`, `hand_*_nude_cull`, `feet_*_nude_cull`,
284`bodynipplesgen_*`, `bodygenitalsgen_*` and garments to sub-millimetre precision without per-slot
285offset tables. Disabled slots use `<12 cm` at-root stub meshes at `(0, 0, -1.0 m)`.
286
287### Modular body slots, `_nude_cull` islands and watertight stitching
288
289Despite their legacy `hand_` and `feet_` prefixes, the canonical base nude body drawables cover the
290entire torso and pelvis:
291
292- **Upper body (`hand_<rig>_000_nude_cull`):** torso, chest, shoulders, arms and hands (first-person
293 arms ship separately as `hand_<rig>_000_nude_cull_fp`).
294- **Lower body (`feet_<rig>_000_nude_cull`):** pelvis, hips, buttocks, legs and feet.
295- **Female nipples (`bodynipplesgen_fr1_000_regular_ws00_full`):** separate `fr1` chest patch
296 sharing the `hand_fr1` `512×1024` UV layout (male `mr1` torsos bake nipples directly into
297 `hand_mr1_000_nude_cull`).
298- **Adult genitals (`bodygenitalsgen_fr1_008_*` and `bodygenitalsgen_mr1_000_*`):** modular `fr1`
299 and `mr1` pelvic patches with four geometry variants (`base`, `_alt_00`, `_alt_01`, `_alt_02`;
300 female depth `6.83–7.58 cm`, male resting `8.9–9.0 cm` and extended `13.4–13.5 cm`).
301
302RAGE 9 uses a two-level culling architecture to prevent skin poke-through without runtime mesh
303rebuilds:
304
3051. **Catalogue swaps (`0x46e1a048` = `"cull_drawable"`):** 385 unique drawables carry `_cull`
306 suffixes — 351 `_cull_00` garments (348/351 paired directly with a `_full` sibling) plus 28
307 `_nude_cull` / `_nude_cull_fp` base skin meshes across the 12 rigs. Wearable states in `0DRP`
308 catalogues map `0x46e1a048` to `0x3d780b74` records (`25,292` resolving to `*_cull*` drawables).
3092. **Physical `_nude_cull` cull islands and coplanar overlap bands:** Base nude drawables are
310 physically split into hundreds of disconnected island patches along garment cuts:
311
312| Drawable | Physical cull islands | Tier 0 V / T | Measured coplanar overlap |
313|---|---:|---:|---|
314| `hand_fr1_000_nude_cull` | **449** | 10,440 / 13,534 | **258** waist tris (`Z = 0.8981..1.0367 m`, 13.86 cm) + **26** nipple tris |
315| `hand_mr1_000_nude_cull` | **290** | 9,914 / 13,534 | **258** waist tris (`Z = 0.9346..1.0739 m`, 13.93 cm) |
316| `feet_fr1_000_nude_cull` | **257** | 4,103 / 4,462 | **64** female genital tris behind `bodygenitalsgen_fr1_008_*` |
317| `feet_mr1_000_nude_cull` | **264** | 4,107 / 4,462 | shares the 258-tri waist band (`<1.5 mm` apart) |
318
319At runtime, an outfit occlusion mask suppresses the overlapping waist strip on one mesh plus any
320islands hidden under garments or modular chest/pelvic patches. Rendering both `hand_*_nude_cull`
321and `feet_*_nude_cull` offline without culling causes Z-fighting on those 258 waist triangles (and
322on the 26 nipple and 64 female genital backing triangles). Culling the coplanar overlapping
323triangles stitches the body with **0 boundary-edge holes** (watertight on both `fr1` and `mr1`).
324`tools/ped_assemble.py` implements standing-space alignment, canonical vertex-key plus
325coplanar-centroid/normal overlap culling and multi-part glTF 2.0 export, verified on synthetic
326overlapping body meshes in `tests/test_ped_assemble.py`:
327
328```powershell
329python -I tools/ped_assemble.py assemble <parts...> -o <out.glb>
330python -I tools/ped_assemble.py cull-overlap --target <upper> --ref <lower> -o <out.glb>
331python -I tools/ped_assemble.py inspect-seams <parts...>
332```
333
334### 15-channel meshlet vertex layout
335
336Character geometry uses GPU meshlets (16-byte headers, up to 128 local vertices per meshlet,
33732-bit packed triangles `7b a | 7b b | 7b c | 11b meshlet_id` plus `uint16` vertex remap). The
33823-slot vertex buffer header (`0x00..0x5b`) carries 15 active streams on modern character heads:
339
340| Slot | Format | Stride | Purpose |
341|---:|---|---:|---|
342| `0` | `0x42` (`0x4042`) | 8 B | Quantized 16-bit XYZ position (`base + q * step`) |
343| `2` | `0x21` | 4 B | Packed octahedral normal + 15-bit tangent frame |
344| `18` / `19` | `0x27` | 4 B | Secondary tangent / rest-pose octahedral normal (`19` heads, `18` body skin) |
345| `6`, `7` | `0x26` | 4 + 4 B | Skinning blend weights (up to 8 influences per vertex) |
346| `8`, `9` | `0x8c` or `0x25` | 16 + 16 B or 4 + 4 B | Bone indices: extended 32 B/vert (`0x8c`, hero heads) vs 8 B/vert (`0x25`, body skin / ambient) |
347| `1`, `12`, `13` | `0x26` | 4 + 4 + 4 B | Three `RGBA8` vertex color / AO / blend-mask / skin-curvature channels |
348| `3`, `4`, `14`, `15` | `0x28` / `0x42` | 4–8 B each | Four UV channels (`UV0` albedo, `UV1` tattoo/suntan/damage, `UV2` wrinkle/micro-detail, `UV3` morphable-model) |
349| `17` | `0x84` | 16 B | Per-vertex basis / blend-shape / ML-deformer stream |
350
351The ped importer and exporter preserve authored `TEXCOORD_1` and higher sets alongside
352`TEXCOORD_0`, including normalized integer input accessors. Ped JSON stores these extra
353sets in `uvs_extra`, an object whose keys are the positive set indices (`"1"`, `"2"`,
354and so on); `uvs` remains set 0. Overlap culling and vertex compaction keep each set
355aligned with the surviving vertices. This preserves vertex data without expanding
356the material importer's supported texture-coordinate bindings.
357
358### 3-tier LOD budgets and thresholds
359
360Modular ped drawables in `packs.rpf` stream three separate dictionary tiers per item name plus a
361fourth `slod_human` crowd proxy. Body skin, eyes, teeth, genitals, nipples and garments encode
362`rmcDrawable` `m_LodDist[4]` (`root + 0x70..0x7f`) as **`15.0 m` (LOD 0 -> 1), `30.0 m` (LOD 1 -> 2),
363`60.0 m` (LOD 2 -> 3/SLOD), `9998.0 m`**; heads and `slod_human` store `(9998.0, 9998.0, 9998.0,
3649998.0)` because head tier selection is driven dynamically by the ped component LOD manager.
365
366| Component | Tier 0 (High) | Tier 1 (Med) | Tier 2 (Low) | Notes |
367|---|---:|---:|---:|---|
368| Human head (canonical) | 8,983 v / 13,320 t | 2,958 v / 3,362 t | 599 v / 514 t | Shared topology across 1,600+ modern heads |
369| Eyes (`*_eyes_full`) | 434 v / 816 t | 230 v / 398–408 t | 50–55 v / 80 t | Dual eyeball + cornea |
370| Teeth (`teethmodular_*`) | 3,628 v / 5,582 t | 1,359 v / 2,144 t | 373 v / 556 t | Upper/lower arches + gums + tongue |
371| Upper body nude (`hand_fr1_000_nude_cull`) | 10,440 v / 13,534 t | 5,821 v / 5,168 t | 2,365 v / 1,392 t | `hand_mr1`: 9,914 v / 13,534 t |
372| Lower body nude (`feet_fr1_000_nude_cull`) | 4,103 v / 4,462 t | 2,794 v / 2,112 t | 1,134 v / 606 t | `feet_mr1`: 4,107 v / 4,462 t |
373| First-person arms (`hand_*_nude_cull_fp`) | 8,127 v / 12,342 t | 4,337–4,360 v / 6,000 t | 932–934 v / 1,266 t | Dedicated close-up FP arms |
374| Genitals — female (`bodygenitalsgen_fr1_008_*`) | 267 v / 356 t | 132–139 v / 153–170 t | 35 v / 38 t | Identical across `base`, `alt_00..02` |
375| Genitals — male (`bodygenitalsgen_mr1_000_*`) | 246 v / 352 t | 113–115 v / 176 t | 22 v / 35–36 t | Resting + extended `alt_00..02` |
376| Nipples — female (`bodynipplesgen_fr1_000_*`) | 106 v / 182 t | 90 v / 118 t | 3 v / 1 t | Collapses to 1-tri stub at Tier 2 |
377| SLOD far crowd proxy (`slod_human`) | 392 v / 338 t | — | — | Whole distant character (-99.1%) |
378
379Assembled nude adult budget: ~**27,300–28,000 v / 38,000–38,250 t** at Tier 0 -> ~**13,400 t** at
380Tier 1 (-65%) -> ~**3,200 t** at Tier 2 (-92%) -> **338 t** at SLOD (-99.1%). Clothed characters
381typically span ~**35,000–55,000 t** at Tier 0 excluding GPU hair strands.
382
249## What is not decoded 383## What is not decoded
250 384
251- **Fragment children.** A raw child-array walk (`tools/fragment_children.py`) covers every fragment 385- **Fragment children.** A raw child-array walk (`tools/fragment_children.py`) covers every fragment
@@ -288,15 +422,12 @@ silhouette is geometry, not a painted-on atlas.
288 `ambient_female` drawable; the Lucia and Mandy hits are props (photos, frames, luggage, a 422 `ambient_female` drawable; the Lucia and Mandy hits are props (photos, frames, luggage, a
289 curtain). The only human-skeleton meshes in `levels.rpf` are the generic mannequin pair in 423 curtain). The only human-skeleton meshes in `levels.rpf` are the generic mannequin pair in
290 **Bodies**. 424 **Bodies**.
291- **Bind pose and skinning.** The delivered GLBs are static: they contain **0 skins, 0 `JOINTS_0` 425- **Bind pose and skinning in static exports.** The static preview and `rpf9dump` GLBs do not apply
292 and 0 `WEIGHTS_0`**, so there are no inverse-bind matrices to apply. The reference TRS is the 426 the 8-influence bone-palette skinning (preview GLBs carry 0 skins, 0 `JOINTS_0` and 0 `WEIGHTS_0`;
293 only exported pose, and the meshes are not skinned to the 596-bone ped skeleton. A rigged export 427 `rpf9dump` emits identity inverse-bind matrices). The real inverse bind matrices are at skeleton
294 is still open; this is a data omission, not identity inverse-bind matrices. 428 header `+0x30` (drawable `+0x18` points at the header) and agree with the default bone transforms;
295- **Bind pose and full skinning.** The `rpf9dump` GLBs use identity inverse-bind matrices and do 429 `tools/anim_glb.py`, `tools/skinned_glb.py` and `tools/ped_assemble.py` export glTF skins with
296 not apply the 8-influence bone-palette skinning. The inverse bind matrices are at skeleton header 430 those matrices (see [character_skeleton.md](character_skeleton.md#animated-gltf-export)).
297 `+0x30` (the drawable's `+0x18` points at the header) and agree with the default bone transforms;
298 `tools/anim_glb.py` exports a part with them as a glTF skin, with clips (see
299 [character_skeleton.md](character_skeleton.md#animated-gltf-export)).
300 431
301## Reproduce 432## Reproduce
302 433
@@ -309,26 +440,6 @@ The second command prints the fragment and child-drawable totals quoted under "F
309reads the archive in place (about 22 minutes for `levels.rpf` with 12 workers over a WSL mount of 440reads the archive in place (about 22 minutes for `levels.rpf` with 12 workers over a WSL mount of
310the dump) and writes nothing else. 441the dump) and writes nothing else.
311 442
312```python
313import json
314
315items = json.load(open(r"<outdir>/packs/models/manifest.json", encoding="utf-8"))["Items"]
316names = sorted({i["Name"] for i in items})
317print(len(items), len(names))
318print(sum(1 for i in items if i.get("IsFragment")), "fragments")
319print([n for n in names if "lucia" in n.lower()])
320```
321
322```python
323import json
324
325items = json.load(open(r"<outdir>/packs/models/manifest.json", encoding="utf-8"))["Items"]
326names = sorted({i["Name"] for i in items})
327print(len(items), len(names))
328print(sum(1 for i in items if i.get("IsFragment")), "fragments")
329print([n for n in names if "lucia" in n.lower()])
330```
331
332The material rows are in the same manifest, one per shader of a record, each with the texture 443The material rows are in the same manifest, one per shader of a record, each with the texture
333references by slot: 444references by slot:
334 445
@@ -346,19 +457,50 @@ A key's size and format come from the pool that holds it: the `AssetKey`, `Width
346`DxgiFormat` and `Mips` fields of the manifest `rpf9dump ttpf <pool.ttpf> <outdir>` writes. 457`DxgiFormat` and `Mips` fields of the manifest `rpf9dump ttpf <pool.ttpf> <outdir>` writes.
347 458
348The [Hands and feet](#hands-and-feet) tables also need `core_restofworld.rpf` and the 57 pool 459The [Hands and feet](#hands-and-feet) tables also need `core_restofworld.rpf` and the 57 pool
349catalogs (`AssetKey` in each pool's `manifest.json`): 460catalogs (`AssetKey` in each pool's `manifest.json`).
461
462`rpf9dump ttpf` writes a pool's catalog to `<output root>\<pool basename>\manifest.json`, and pool
463basenames repeat: the 57 pools in [`game/xbox-1.0.2.1.json`](../game/xbox-1.0.2.1.json) have 51
464distinct basenames (`ttdb_maps` and `ttdb_terrain_image_based` twice, `ttdb_ui` and `ttdb_vfx` three
465times). With one output root for all of them, later pools overwrite earlier catalogs. Give each pool
466its package-relative parent folder under `<outdir>\ttpf` as its output root:
350 467
351```powershell 468```powershell
352rpf9dump models <pack\core_restofworld\core_restofworld.rpf> <outdir> 469$game = (Resolve-Path "<game root>").Path.TrimEnd("\")
353rpf9dump ttpf <each .ttpf under data\ttdb and pack\*\data\ttdb> <outdir>\ttpf\<pool> 470rpf9dump models "$game\pack\core_restofworld\core_restofworld.rpf" <outdir>
471Get-Item "$game\data\ttdb", "$game\pack\*\data\ttdb" | Get-ChildItem -Recurse -File -Filter *.ttpf | ForEach-Object {
472 rpf9dump ttpf $_.FullName "<outdir>\ttpf\$($_.DirectoryName.Substring($game.Length + 1))"
473}
354``` 474```
355 475
476Each catalog records its source pool in `src`. The lookup finds catalogs at any depth under
477`<outdir>\ttpf` and stops unless their sources are exactly the 57 pools of the game root, so a
478catalog that was overwritten, exported in another layout or taken from another folder is caught
479before an absent key is read as a lookup miss:
480
356```python 481```python
357import glob, json 482import json
483import os
484from pathlib import Path
358 485
359maps = {"C8E8C282": "diffusetex", "C6F46E79": "speculartex", "1E77BF4C": "bumptex", "739E3D0D": "speculartex2"} 486maps = {"C8E8C282": "diffusetex", "C6F46E79": "speculartex", "1E77BF4C": "bumptex", "739E3D0D": "speculartex2"}
360pooled = {t["AssetKey"] for m in glob.glob(r"<outdir>/ttpf/*/manifest.json") 487game = Path(r"<game root>")
361 for t in json.load(open(m, encoding="utf-8"))["Textures"]} 488pool_root = Path(r"<outdir>/ttpf")
489
490
491def source(path):
492 return os.path.normcase(os.path.abspath(path))
493
494
495pools = {source(p) for pattern in ("data/ttdb/**/*.ttpf", "pack/*/data/ttdb/**/*.ttpf") for p in game.glob(pattern)}
496sources, pooled = set(), set()
497for m in pool_root.rglob("manifest.json"):
498 catalog = json.loads(m.read_text(encoding="utf-8"))
499 sources.add(source(catalog.get("src", m)))
500 pooled.update(t["AssetKey"] for t in catalog.get("Textures", []))
501if len(pools) != 57 or sources != pools:
502 raise ValueError(f"{len(pools)} pools under {game} (expected 57); {len(pools - sources)} have no catalog "
503 f"under {pool_root}, {len(sources - pools)} catalogs come from other sources")
362items = [i for m in (r"<outdir>/packs/models/manifest.json", r"<outdir>/core_restofworld/models/manifest.json") 504items = [i for m in (r"<outdir>/packs/models/manifest.json", r"<outdir>/core_restofworld/models/manifest.json")
363 for i in json.load(open(m, encoding="utf-8"))["Items"]] 505 for i in json.load(open(m, encoding="utf-8"))["Items"]]
364for name in ("hand_fr1_000_nude_cull.#dr", "feet_fr1_000_full.#dr", "bodynipplesgen_fr1_000_regular_ws00_full.#dr", 506for name in ("hand_fr1_000_nude_cull.#dr", "feet_fr1_000_full.#dr", "bodynipplesgen_fr1_000_regular_ws00_full.#dr",
diff --git a/docs/character_skeleton.md b/docs/character_skeleton.md
index 18fede113..7261e7584 100644
--- a/docs/character_skeleton.md
+++ b/docs/character_skeleton.md
@@ -124,6 +124,49 @@ largest difference between a joint's composed origin and the one its inverse bin
124matrices are row-vector (D3D) matrices; stored row by row they are glTF's column-major layout as 124matrices are row-vector (D3D) matrices; stored row by row they are glTF's column-major layout as
125is. `tools/anim_glb.py` exports them as the glTF skin's `inverseBindMatrices` and checks them. 125is. `tools/anim_glb.py` exports them as the glTF skin's `inverseBindMatrices` and checks them.
126 126
127## Master skeletons and standing space
128
129Master `crSkeletonData` tables (`root + 0x18`, bone count `u16` at `skel + 0x6c`, `0x50`-byte
130`crBoneData` records at `skel + 0x28`, inverse bind matrices at `skel + 0x30`) live inside the 22
131`ambient_*` ped fragment resources in `packs.rpf`. They fall into five master skeleton classes:
132
133| Master skeleton fragment | Rig token | Named bones | `SKEL_*` | `BM_*` | `MH_*` | `FB_*` | `PH_*` | `OH_*` | `HH_*` | `RB_*` | `SEC_*` |
134|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
135| `ambient_femalebody` / `femalexxl` | `fr1` / `fo1` | **596** | 78 | 131 | 151 | 56 | 51 | 40 | 23 | 22 | 4 |
136| `ambient_femalebb` | `fb1` | **574** | 78 | 131 | 134 | 54 | 50 | 40 | 23 | 22 | 4 |
137| `ambient_malebody` / `malexxl` / `alien` | `mr1` / `mo1` | **560** | 78 | 131 | 129 | 46 | 51 | 40 | 23 | 22 | 4 |
138| `ambient_malebb` | `mb1` | **552** | 78 | 130 | 126 | 44 | 49 | 40 | 23 | 22 | 4 |
139| `ambient_kidbody` / `infantbody` | `mk1` / `mi1` | **454** | 78 | 104 | 124 | 44 | 15 | 36 | 0 | 22 | 4 |
140
141Subsystem roles (counts shown for the 596-bone `ambient_femalebody` master rig):
142
143- **`SKEL_*` (78):** Core animation tree — `SKEL_ROOT`, `SKEL_Pelvis`, a 7-segment spine
144 (`SKEL_Spine_Root`, `SKEL_Spine0..6`), a 3-segment neck (`SKEL_Neck0..2`), `SKEL_Head`,
145 clavicles, scapulae, limbs, 4-joint fingers (`Finger00..43`) and 3-part toes (`Toe0`, `Toe10`,
146 `Toe20`).
147- **`BM_*` (131):** Body-morph and anatomical definition drivers (`BM_L/R_Bicep`, `BM_L/R_Deltoid*`,
148 `BM_L/R_Breast*`, `BM_Cleavage`, `BM_L/R_Butt`, `BM_Stomach*`, `BM_Spine0..5`).
149- **`MH_*` (151 female / 129 male):** Muscle/crease helpers (`MH_L_KneeCrease`, `MH_L_PecUpper`,
150 `MH_L_Butt`) and garment/jewelry anchors (`MH_BraStrap`, `MH_BeltLoop`, `MH_Necklace_*`,
151 `MH_Choker_Spr_01`).
152- **`FB_*` (56 female / 46 male):** Oral, jaw and mask rig — `FB_Root`, `FB_Jaw`, 24 individual
153 tooth bones, an 11-bone articulated tongue, mouth bags, plus female mask and earring anchors.
154- **`PH_*` (51) and `HH_*` (23):** Prop, weapon, ground-contact and holster attachment bones.
155- **`OH_*` (40) and `RB_*` (22):** Orientation/recoil helpers and limb twist/roll bones.
156- **`SEC_*` (4):** Dedicated secondary-motion breast physics bones (`SEC_L/R_Full_Breast`,
157 `SEC_L/R_Mid_Breast`); buttocks and belly have zero `SEC_*` / `SPR_*` bones.
158- **Ear and specialised helpers (40):** `EarRig_*` (10), `EarJaw_*` (2), `TGT_*` (2), `XH_*` (5),
159 `EO_*` (4), `IK_*` (4), `Tuck_L/R_Tgt` (2), `CH_*`/`WH_*` (4), `UV_L/R_Scapular` (2), plus watch,
160 ponytail, capsule-offset and camera-attach helpers. The 36-bone female-over-male delta is 39
161 female clothing/jewelry/mask/scapular helpers minus 3 male-only bones (`MH_L/R_Toe`, `PH_HAT_LOC`).
162
163**Standing-space coordinate convention:** In bind space, bipedal feet sit near `Z = -1.0 m` below
164`SKEL_ROOT` at the origin, whereas modular drawable bounds (`root + 0x30..0x4f`) are authored in
165standing space with **`SKEL_ROOT = (0, 0, +1.0 m)`** in RAGE Z-up (`(0, +1.0 m, 0)` in glTF Y-up)
166so feet rest on the ground plane. Translating the skeleton root node (or static mesh vertices) by
167`+1.0 m` vertically aligns all modular ped parts without per-slot offset tables; see
168`tools/ped_assemble.py` and [character_models.md](character_models.md#standing-space-coordinate-convention).
169
127## Model-side bone mapping 170## Model-side bone mapping
128 171
129Each character drawable's `grmModel` header points at a **bone-hash array** (at `+0x28`, as 172Each character drawable's `grmModel` header points at a **bone-hash array** (at `+0x28`, as
@@ -257,8 +300,8 @@ it does and why:
257 the track's bone hash. Bone hash 0 drives a `mover` node above the skeleton (root motion; 300 the track's bone hash. Bone hash 0 drives a `mover` node above the skeleton (root motion;
258 `--no-root-motion` leaves it out). Other track types are counted, not exported. A clip entry 301 `--no-root-motion` leaves it out). Other track types are counted, not exported. A clip entry
259 plays its animation's `[start, end]` window at `rate`, so animation time `t` is clip time 302 plays its animation's `[start, end]` window at `rate`, so animation time `t` is clip time
260 `(t − start) / rate`. In 300 sampled dictionaries, `(end − start) / rate` equals the clip's 303 `(t − start) / rate`. `(end − start) / rate` equals the clip's `+0x78` duration for all 785,174
261 `+0x78` duration for all 4,471 entries. 304 entries of all 61,505 dictionaries, to within 2.2e-4 relative (see [animation.md](animation.md#clip-dictionaries-are-rage-resources)).
262- The whole skeleton sits under one node that turns RAGE Z-up into glTF Y-up. Skinned mesh nodes 305- The whole skeleton sits under one node that turns RAGE Z-up into glTF Y-up. Skinned mesh nodes
263 sit at the scene root, because glTF ignores a skinned mesh node's own transform. 306 sit at the scene root, because glTF ignores a skinned mesh node's own transform.
264 307
@@ -341,6 +384,20 @@ exported, and no body or other unrequested component is assembled. No game data
341GLB is stored in the repository; `tests/test_skinned_glb.py` builds its own skeleton, skin 384GLB is stored in the repository; `tests/test_skinned_glb.py` builds its own skeleton, skin
342buffer and GLB. 385buffer and GLB.
343 386
387`python -I tools/glb_inspect.py out.glb` reads the written file back with no glTF library and
388prints its mesh, skin (joint count) and animation counts, the POSITION bounding box and any
389field the exporter dropped; [models.md](models.md#skinned-glb-export) lists what the rest of
390the report carries.
391
392`python -I tools/glb_skinning.py out.glb` checks the skin data itself: each skin's joint and
393`inverseBindMatrices` counts, the accessor types and finite values, which primitives carry
394skinning data and which are static, `JOINTS_n`/`WEIGHTS_n` pairing, every vertex's weight sum
395as FLOAT or normalized `UNSIGNED_BYTE`/`UNSIGNED_SHORT`, the joint-index range and the POSITION
396bounds computed from the accessor. A malformed container, a file with no skin, or a skin whose
397`inverseBindMatrices` count differs from its joint count exits nonzero; `--json report.json`
398writes the same report as LF-only JSON. `python -I tests/test_glb_skinning.py` runs its 17
399synthetic tests and needs no game files.
400
344## Texture parameter split 401## Texture parameter split
345 402
346The character material blocks carry several 32-bit parameter hashes before each 64-bit asset 403The character material blocks carry several 32-bit parameter hashes before each 64-bit asset
@@ -427,16 +484,12 @@ shared base is `cs_lucia_legacypedcs`
427about 25 million generated strings — gives **0/18** exact matches. The sibling nine-entry table 484about 25 million generated strings — gives **0/18** exact matches. The sibling nine-entry table
428resolves 9 of 18 values to `joaat("outfit_01")` … `joaat("outfit_10")` (frequency corroborates 485resolves 9 of 18 values to `joaat("outfit_01")` … `joaat("outfit_10")` (frequency corroborates
429it), so the table stores build-time design labels, not shipped asset names; the 18 component 486it), so the table stores build-time design labels, not shipped asset names; the 18 component
430values are not recoverable by name enumeration. `common.rpf` contains one variation manager,
431`CPedVariationBodyTypeManager` (77,422 bytes, 67 keys). Its keys are literal model names;
432`joaat32` of all 67 keys gives 0 hits against the 18. The `3cba3fe6` float (0.942 / 0.971 for
433Lucia and Monalisa) is a body/height scale, not a name. There is no component/outfit-name
434manager in `common.rpf`; `outfit_NN` exists only as a hash in the packs table.
435values are not recoverable by name enumeration. `common.rpf` holds `CPedVariationBodyTypeManager` 487values are not recoverable by name enumeration. `common.rpf` holds `CPedVariationBodyTypeManager`
436(77,422 bytes, 67 keys) and `CPedComponentSetManager`; neither maps a variation index to a 488(77,422 bytes, 67 keys) and `CPedComponentSetManager`; neither maps a variation index to a
437drawable plus texture. The first manager's keys are literal model names, and `joaat32` of all 489drawable plus texture. The first manager's keys are literal model names, and `joaat32` of all
43867 gives 0 hits against the 18. The `3cba3fe6` float (0.942 / 0.971 for Lucia and Monalisa) is a 49067 gives 0 hits against the 18. The `3cba3fe6` float (0.942 / 0.971 for Lucia and Monalisa) is a
439per-character scale, not a name; `outfit_NN` exists only as a hash in the packs table. 491per-character body/height scale, not a name; there is no component/outfit-name manager in
492`common.rpf`, and `outfit_NN` exists only as a hash in the packs table.
440 493
441The entities linked to Mandy carry three different per-state archetype hashes 494The entities linked to Mandy carry three different per-state archetype hashes
442(`0x18BB2550`, `0x73E83886`, `0x57DDFFC2`), which fits her outfit changing between states, not 495(`0x18BB2550`, `0x73E83886`, `0x57DDFFC2`), which fits her outfit changing between states, not
diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md
index 0c94f58c7..5a214e325 100644
--- a/docs/d3d12_command_objects.md
+++ b/docs/d3d12_command_objects.md
@@ -270,6 +270,41 @@ shipped modules, not a claim that the game never queries for them.
270The `GraphicsCommandList` ASCII string occurs 30 times in `XboxBvhBuilder.dll` (type/debug 270The `GraphicsCommandList` ASCII string occurs 30 times in `XboxBvhBuilder.dll` (type/debug
271names); `PresentX` does not occur in any of the 16 DLLs. 271names); `PresentX` does not occur in any of the 16 DLLs.
272 272
273
274### 3.2a No shipped module passes an unknown GUID at a call site
275
276Section 3.2's byte scan can only recognise *known* IIDs; a console-only GUID (the four list IIDs of
277[`d3d12_xs_surface.md §4`](d3d12_xs_surface.md)) would scan as anonymous data. The call-site scan closes
278that hole: `tools/d3d12_guid_sites.py` enumerates every 16-byte constant a module's code can name —
279RIP-relative `lea` targets in data sections, absolute pointers stored in data, two adjacent
280`movabs` immediates that inline a GUID without a constant pool, and `mov reg, [rip+...]` loads
281through import slots (a GUID imported as data) — and reports which are GUID-shaped. Over all 16
282modules of the 1.0.2.1 package:
283
284| Binary | GUID-shaped constants the code references |
285|---|---|
286| `XboxBvhBuilder.dll` | 2: `IID_ID3D12RootSignature`, `IID_ID3D12PipelineState` (the same pair as §3.2) |
287| `amd_fidelityfx_upscaler_xbox.dll` | 8: the §3.2 set, nothing else |
288| `amd_fidelityfx_loader_xbox.dll` | 0 |
289| the other 13 modules | 0–44 GUIDs each (six have none); where present they are HTTP, WinRT and CRT interfaces — none of these modules imports `d3d12_xs.dll`, so none can call D3D12 at all |
290
291No module loads a GUID through an import slot, and no `movabs` pair inlines one. As a control, the
292upscaler's single `IID_ID3D12Device` reference (rva `0x482f0`) is the IID of a real slot-0
293`QueryInterface` call (`(this, &IID, &out)`, decompiled at rva `0xde66`). So the only
294interfaces any shipped module can name at a `QueryInterface` or a creation call are the ten it
295already uses; a console compute/copy list IID cannot appear in the package, statically, in any
296form. The same scan looks for code-referenced static `D3D12_COMMAND_QUEUE_DESC` windows
297`{Type, Priority, Flags, NodeMask}`: 10 windows in 3 modules survive the shape filter, every one with
298`Type` 1 — a PC enum value — and all of them offset tables read by stride arithmetic, not queue
299descriptions (checked by decompiling the referencing function of the upscaler's six). None has a
300value past `VIDEO_DECODE` (4), so the DMA type's numeric value has no static source in the package
301either.
302
303Reproduce: `python -I tools/d3d12_guid_sites.py <package>/*.dll --known
304IID_ID3D12ConsDmaCommandList=30bc77b9-8379-4b25-95de-b8588c42275d` (prints GUID values and counts
305only). The four list IIDs and the DMA type remain reachable only through the running title, as
306[`d3d12_xs_surface.md §4`](d3d12_xs_surface.md) already requires for the IIDs.
307
273### 3.3 The BVH builder's command-list call sites 308### 3.3 The BVH builder's command-list call sites
274 309
275The exported `BuildRaytracingAccelerationStructure` (ordinal 3, RVA `0x21610`) copies the input 310The exported `BuildRaytracingAccelerationStructure` (ordinal 3, RVA `0x21610`) copies the input
@@ -466,9 +501,16 @@ vtable pointer of a public object.
466 at `+0x18`, a copy of the kind-6 program at `+0x28` with its exact size at `+0x30`, and kind 7 at `+0x38` 501 at `+0x18`, a copy of the kind-6 program at `+0x28` with its exact size at `+0x30`, and kind 7 at `+0x38`
467 ([fspx.md](fspx.md)). The proxy maps the console desc to `D3D12_COMPUTE_PIPELINE_STATE_DESC` and routes it to 502 ([fspx.md](fspx.md)). The proxy maps the console desc to `D3D12_COMPUTE_PIPELINE_STATE_DESC` and routes it to
468 `CreateComputePipelineState` (PC slot 11). On a PC device that call fails (`E_FAIL`) because the code is not a PC 503 `CreateComputePipelineState` (PC slot 11). On a PC device that call fails (`E_FAIL`) because the code is not a PC
469 shader, so the DLL falls back to slot 62; its message for that failure calls the fallback "NewBE". The Vulkan 504 shader, so the DLL falls back to slot 62; its message for that failure calls the fallback "NewBE". With kind 0 in
470 device takes the bare kind-6 program and finds its translated module by `fspx_code_sha256` ([fspx.md](fspx.md), 505 the description (always, from this DLL) the proxy passes all four pairs on as one `FSPX` payload, checking each pair
471 "Build and run-time lookup"), for the programs the build translated. 506 before reading it. The Vulkan device then finds the translated module by `fspx_code_sha256` and `fspx_state_sha256`
507 ([fspx.md](fspx.md), "Build and run-time lookup"), for the programs the build translated.
508 - **The layout is pinned from the DLL's code:** its FSPX reader (`0x1a20`), the same loop inline for a container,
509 and the copy into the description. The kind 0 and kind 6 of one call come from the same payload. With the
510 reader run on all 29 programs, every translated program resolves to its own entry ([fspx.md](fspx.md), "How
511 the table was pinned").
512 - **A failed call is logged with its number** (`slot 67 call N failed`). The DLL creates its pipelines one after
513 another, so a miss is not necessarily the first call's.
472- **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC 514- **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC
473 runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns 515 runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns
474 `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a 516 `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a
@@ -482,9 +524,20 @@ vtable pointer of a public object.
482 the largest value (`+0x10f8`). Before a dispatch whose pipeline has a non-zero value (`0x64d3`; zero skips the 524 the largest value (`+0x10f8`). Before a dispatch whose pipeline has a non-zero value (`0x64d3`; zero skips the
483 binding), the DLL creates the scratch buffer once, `largest * 0xd0` bytes rounded up to 64 KiB, through device 525 binding), the DLL creates the scratch buffer once, `largest * 0xd0` bytes rounded up to 64 KiB, through device
484 slot 27 in state `UNORDERED_ACCESS` (`0x65ab`), names it `FFX_XBox_ComputeScratch`, and binds it with list slot 526 slot 27 in state `UNORDERED_ACCESS` (`0x65ab`), names it `FFX_XBox_ComputeScratch`, and binds it with list slot
485 141 `(2, GPU VA, buffer size, this pipeline's value)` (`0x65f8`). Measured: the calls and the arithmetic. Open: 527 141 `(2, GPU VA, buffer size, this pipeline's value)` (`0x65f8`). Measured: the calls and the arithmetic.
486 what the slot-11 object is, the unit of its dword (the factor 1024 suggests KiB), the meaning of `0xd0`, and 528 - **Failure and zero (measured, `0x585c` to `0x58b1`).** The value at `+0x44` is set to 0 before the call. A failed
487 of the leading `2`. 529 HRESULT or a null `obj` skips to the function's success return with the value still 0, so pipeline creation does
530 not depend on slot 11. At dispatch a value of 0 skips both the scratch buffer and list slot 141 (`0x64d6`).
531 - **The object (measured shape, hypothesis about its type).** Slot 3 is called with no arguments and its result is
532 read as a pointer to the dword; slot 2 releases it. That is the shape of `ID3DBlob::GetBufferPointer` and
533 `Release`.
534 - **No per-program size (measured on the 29 programs).** `COMPUTE_PGM_RSRC2.SCRATCH_EN` is clear in all 29, no
535 program has a `scratch_*` or `flat_scratch` instruction, and kind-0 words 0, 1 and 2 are each one value across
536 all 29.
537 - **Implemented.** The Vulkan device's pipeline answers slot 11 with a blob holding 0; console slots 9 and 10
538 return `E_NOTIMPL`. A translated module keeps its private data in SPIR-V, not in a console scratch buffer.
539 - **Open.** What the console returns there for these programs, the unit of the dword (the factor 1024 suggests
540 KiB), the meaning of `0xd0`, and of the leading `2`.
488- The DLL's 29 shaders are `DXBC` containers with `SFI0`, `ISG1`, `OSG1`, `PSV0`, `RTS0`, `HASH` and `ACCC` parts 541- The DLL's 29 shaders are `DXBC` containers with `SFI0`, `ISG1`, `OSG1`, `PSV0`, `RTS0`, `HASH` and `ACCC` parts
489 and no `DXIL`. The `ACCC` payload starts with the tag `FSPX` in all 29; the game's own native shaders are `FSSM` 542 and no `DXIL`. The `ACCC` payload starts with the tag `FSPX` in all 29; the game's own native shaders are `FSSM`
490 inside `XBCH` ([design.md](design.md)). `FSPX` is a directory around an uncompressed RDNA2 program and its 543 inside `XBCH` ([design.md](design.md)). `FSPX` is a directory around an uncompressed RDNA2 program and its
@@ -664,7 +717,8 @@ Even taking both projects at face value, the following remain **Open**:
664- the Xbox queue vtable beyond the public chain (`PresentX`, `SuspendX`, `ResumeX`); 717- the Xbox queue vtable beyond the public chain (`PresentX`, `SuspendX`, `ResumeX`);
665- the `PresentX` signature, plane struct, resource/view arrays and swapchain parameters; 718- the `PresentX` signature, plane struct, resource/view arrays and swapchain parameters;
666- the command-list extension slots other than the ones sections 3.3a and 3.5a measured (71, 73, 80, 85, 141, 146, 148); 719- the command-list extension slots other than the ones sections 3.3a and 3.5a measured (71, 73, 80, 85, 141, 146, 148);
667- the DMA list type's real numeric value and the compute/copy console list IIDs; 720- the DMA list type's real numeric value and the compute/copy console list IIDs, which the package
721 itself cannot supply (§3.2a): they need the running title or a vendor runtime;
668- any Xbox-specific return convention on these interfaces. 722- any Xbox-specific return convention on these interfaces.
669 723
670## 5. What a runtime can do without the executable 724## 5. What a runtime can do without the executable
@@ -780,7 +834,8 @@ command object.
780| `SuspendX` / `ResumeX` | No slot or signature. | 834| `SuspendX` / `ResumeX` | No slot or signature. |
781| Xbox queue/list/fence/allocator slot deviations | No runtime binary and no game executable; the package has no queue, fence or allocator client, and its only command-list client is the BVH builder. | 835| Xbox queue/list/fence/allocator slot deviations | No runtime binary and no game executable; the package has no queue, fence or allocator client, and its only command-list client is the BVH builder. |
782| Builder's list field `+0x350` | Read once (`0x1d877`) and not explained by the inline buffer of section 3.5a, which covers `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and `+0x544`. | 836| Builder's list field `+0x350` | Read once (`0x1d877`) and not explained by the inline buffer of section 3.5a, which covers `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and `+0x544`. |
783| DMA list use/value | The IID is prior art; type 6 is derived; no shipped module uses it. | 837| DMA list use/value | The IID is prior art; type 6 is derived; no shipped module uses it, and no module can name any GUID at a call site beyond its known ten or holds a static queue description with a non-PC type (§3.2a). |
838| Compute/copy console list IIDs | Not exported (see #3520) and not present at any call site (§3.2a); only the running title can supply them. |
784 839
785### 5.4 GCL8 (resolved in PR #164) 840### 5.4 GCL8 (resolved in PR #164)
786 841
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index b64400076..4e7a82b85 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -145,6 +145,19 @@ The design is therefore an **IR per command list**:
145 compared. 145 compared.
146- `Close` freezes the IR. `ExecuteBundle` is accepted only on a direct list, with an already-closed bundle as its callee; the bundle's recorded commands and calls are replayed at the call site, so the source can be reused or reset without changing the parent. Command-list creation and reset require an allocator of the same type. A bundle cannot be submitted directly to a command queue. 146- `Close` freezes the IR. `ExecuteBundle` is accepted only on a direct list, with an already-closed bundle as its callee; the bundle's recorded commands and calls are replayed at the call site, so the source can be reused or reset without changing the parent. Command-list creation and reset require an allocator of the same type. A bundle cannot be submitted directly to a command queue.
147- Bundle restrictions are checked while recording for the IR operations currently implemented here (barriers, clears, copies, resolves, `SetPredication`, `DiscardResource`, the atomic copies, `RSSetViewports`, `RSSetScissorRects`, `OMSetRenderTargets` and `ClearState`; `WriteBufferImmediate` is allowed in a bundle); those calls are not legal inside a D3D12 bundle and make `Close` return `E_INVALIDARG`. `d3d12_bundle_forbidden_test` measured the last four on the PC runtime without the debug layer: the bundle's `Close` fails (`E_FAIL`, where this layer gives `E_INVALIDARG`) on the default adapter and on WARP, and executing a bundle whose `Close` failed crashes the runtime, so the layer refuses it in `ExecuteBundle` instead. A bundle has no render targets, viewport or root signature of its own, so its state calls (pipeline state, root signature and arguments, vertex and index buffers, topology, blend factor, stencil references) and its draws and dispatches are kept as they were called, and `ExecuteBundle` plays them on the parent through the same members the application would have called. A draw then snapshots the parent's state plus what the bundle set, and what the bundle set stays on the parent afterwards. Commands that need no state (markers, immediate writes) are copied between them in order. `d3d12_bundle_test` measured the rule on the PC runtime, where the default adapter (an RTX 4060 Ti) and WARP drew the same picture in every case it ran. A bundle's draws see the parent's render targets, viewport and scissor, root signature and arguments (also when the bundle sets the same root signature first, so those arguments stay), and vertex and index buffers. A bundle starts with the pipeline state it was created or reset with, not the parent's. After `ExecuteBundle` the parent has that pipeline state and whatever else the bundle set: topology, root arguments, vertex and index buffers, and a different root signature with the bundle's arguments in place of the parent's. Topology: the default adapter takes the parent's when the bundle sets none. That is more lenient than Microsoft's stated rule (topology is undefined when a bundle begins), and WARP follows the rule by removing the device when a bundle draws or hands back without one, so a bundle should set it; the layer follows the default adapter. A bundle that sets a root argument before any root signature crashes the NVIDIA driver (the layer applies it to the parent's signature). The deferred calls are checked when they play, against the parent's root signature, so a bad one makes the parent's `Close` fail, not the bundle's. A per-list state setter must go through the deferred path (`defer()` in `d3d12_com.cpp`, replaying through a private member that does not trace) to work in a bundle. Not deferred yet: `ExecuteIndirect` in a bundle, and bundle `Dispatch` has no GPU test. 147- Bundle restrictions are checked while recording for the IR operations currently implemented here (barriers, clears, copies, resolves, `SetPredication`, `DiscardResource`, the atomic copies, `RSSetViewports`, `RSSetScissorRects`, `OMSetRenderTargets` and `ClearState`; `WriteBufferImmediate` is allowed in a bundle); those calls are not legal inside a D3D12 bundle and make `Close` return `E_INVALIDARG`. `d3d12_bundle_forbidden_test` measured the last four on the PC runtime without the debug layer: the bundle's `Close` fails (`E_FAIL`, where this layer gives `E_INVALIDARG`) on the default adapter and on WARP, and executing a bundle whose `Close` failed crashes the runtime, so the layer refuses it in `ExecuteBundle` instead. A bundle has no render targets, viewport or root signature of its own, so its state calls (pipeline state, root signature and arguments, vertex and index buffers, topology, blend factor, stencil references) and its draws and dispatches are kept as they were called, and `ExecuteBundle` plays them on the parent through the same members the application would have called. A draw then snapshots the parent's state plus what the bundle set, and what the bundle set stays on the parent afterwards. Commands that need no state (markers, immediate writes) are copied between them in order. `d3d12_bundle_test` measured the rule on the PC runtime, where the default adapter (an RTX 4060 Ti) and WARP drew the same picture in every case it ran. A bundle's draws see the parent's render targets, viewport and scissor, root signature and arguments (also when the bundle sets the same root signature first, so those arguments stay), and vertex and index buffers. A bundle starts with the pipeline state it was created or reset with, not the parent's. After `ExecuteBundle` the parent has that pipeline state and whatever else the bundle set: topology, root arguments, vertex and index buffers, and a different root signature with the bundle's arguments in place of the parent's. Topology: the default adapter takes the parent's when the bundle sets none. That is more lenient than Microsoft's stated rule (topology is undefined when a bundle begins), and WARP follows the rule by removing the device when a bundle draws or hands back without one, so a bundle should set it; the layer follows the default adapter. A bundle that sets a root argument before any root signature crashes the NVIDIA driver (the layer applies it to the parent's signature). The deferred calls are checked when they play, against the parent's root signature, so a bad one makes the parent's `Close` fail, not the bundle's. A per-list state setter must go through the deferred path (`defer()` in `d3d12_com.cpp`, replaying through a private member that does not trace) to work in a bundle. Not deferred yet: `ExecuteIndirect` in a bundle, and bundle `Dispatch` has no GPU test.
148- What `Close` returns after one recorded call is compared with the PC runtime over WARP (no debug layer) by
149 `d3d12_close_parity_test`, 100 cases on fresh lists, nothing executed. 62 agree; the other 38 are listed in the
150 test as known differences. In 23 the layer fails a list WARP closes: draws and dispatches with no pipeline,
151 root arguments before a root signature, a `CopyTextureRegion` box that is empty or inverted, footprint to
152 footprint or at an unaligned footprint offset or pitch, `CopyResource` of a resource onto itself,
153 `ClearDepthStencilView` with no flag, an unknown flag or a depth outside 0..1, vertex-buffer slots past 31,
154 17 viewports, an `OCCLUSION` query ended as `BINARY_OCCLUSION`, and `WriteBufferImmediate` at an address that
155 is not 4-aligned. Since one failed list fails the whole `ExecuteCommandLists`, each of these drops a submission
156 D3D12 would run. In 15 the layer closes a list WARP fails (redundant or out-of-range barriers, copies past a
157 resource's end or between formats of another family, resolves the PC runtime refuses, a query index past the
158 heap); what the layer does with those at execution is not part of this test. A refused list's code is always
159 `E_INVALIDARG` here, where the PC runtime also answers `E_FAIL`, so the test compares the verdict and prints both
160 codes.
148- A queue's `ExecuteCommandLists` submits in order with one timeline semaphore signal. `Wait`/`Signal` become 161- A queue's `ExecuteCommandLists` submits in order with one timeline semaphore signal. `Wait`/`Signal` become
149 timeline-semaphore waits/signals. `Present` queues after the frame's work. 162 timeline-semaphore waits/signals. `Present` queues after the frame's work.
150 163
@@ -182,6 +195,10 @@ What is implemented (all of it testable without the game):
182 `DiscardResource`, `WriteBufferImmediate` and `AtomicCopyBufferUINT` / `AtomicCopyBufferUINT64`, and `BeginQuery` / 195 `DiscardResource`, `WriteBufferImmediate` and `AtomicCopyBufferUINT` / `AtomicCopyBufferUINT64`, and `BeginQuery` /
183 `EndQuery` / `ResolveQueryData` (section 4.6). 196 `EndQuery` / `ResolveQueryData` (section 4.6).
184 Views and rectangles are copied while recording, so the CPU descriptor slot can be rewritten afterwards. 197 Views and rectangles are copied while recording, so the CPU descriptor slot can be rewritten afterwards.
198 A `ClearDepthStencilView` flag for a plane the view's format doesn't have is ignored, as the PC runtime (WARP)
199 does: `STENCIL` on a `D32_FLOAT` view clears nothing and `DEPTH | STENCIL` clears the depth plane. Until 2026-11-23
200 `prepare` returned `invalid_clear` for it and the whole list was dropped (D3D-437); `d3d12_clear_test` compares three
201 such cases with WARP.
185- **Replay** (`runtime/src/vulkan_replay.h`): `prepare` resolves and checks a list without writing anything, `emit` 202- **Replay** (`runtime/src/vulkan_replay.h`): `prepare` resolves and checks a list without writing anything, `emit`
186 writes it. Legacy states map through the section 4.3 table (`vulkan_access`), enhanced barriers through 203 writes it. Legacy states map through the section 4.3 table (`vulkan_access`), enhanced barriers through
187 `vulkan_sync` / `vulkan_barrier_access` / `vulkan_layout` to `vkCmdPipelineBarrier2`. Whole-view clears are 204 `vulkan_sync` / `vulkan_barrier_access` / `vulkan_layout` to `vkCmdPipelineBarrier2`. Whole-view clears are
@@ -262,6 +279,21 @@ What is implemented (all of it testable without the game):
262 with a raw Vulkan program (a 4x D32 attachment, render area (2,1) 5x4 of 8x6, `MIN`, `MAX` and `SAMPLE_ZERO`, 279 with a raw Vulkan program (a 4x D32 attachment, render area (2,1) 5x4 of 8x6, `MIN`, `MAX` and `SAMPLE_ZERO`,
263 store `NONE` or `STORE`): MoltenVK writes all 48 destination texels, KosmicKrisp only the 20 inside. No device 280 store `NONE` or `STORE`): MoltenVK writes all 48 destination texels, KosmicKrisp only the 20 inside. No device
264 property reports it, so nothing is gated. The format is the depth 281 property reports it, so nothing is gated. The format is the depth
282 format or the plane's own (`R32_FLOAT`, `R24_UNORM_X8_TYPELESS`, `X24_TYPELESS_G8_UINT`, and for D32S8
283 `R32_FLOAT_X8X24_TYPELESS` and `X32_TYPELESS_G8X24_UINT`; all compared with the PC runtime, TEST-847). A depth-only source above array layer 0 is resolved in a
284 `VkRenderPass` with a framebuffer of the same two views instead of the rendering scope, on every GPU (D3D-417, a
285 driver workaround): AMD's Windows driver (32.0.21042.62, Ryzen 7 9700X iGPU) resolves a dynamic-rendering depth
286 attachment from layer 0 of the image when the multisampled view starts at another layer, while it honours the
287 resolve view's first layer. Measured with a raw Vulkan program on a 4x D32 image of four layers: a layer range
288 cleared with `vkCmdClearDepthStencilImage`, a `CLEAR` load or `vkCmdClearAttachments` reads back right through a
289 `texelFetch` of every sample, through a resolve of all four layers in one scope and through a copy of the layer
290 into a one-layer image that is then resolved, but a one-layer view resolved in a rendering scope gives layer 0
291 for every layer (view type `2D` or `2D_ARRAY`, store `NONE` or `STORE`), and views of layers 1-3 resolved in one
292 scope give layers 0-2. The render pass gives the right layer there; an RTX 3070 (610.74) does in every variant.
293 `d3d12_view_slices_test` reads a 4x D32 array back slice by slice. A depth-stencil source above layer 0 still
294 uses the rendering scope, because its two planes can be in different layouts, which the render pass's attachment
295 description cannot say without the planes' layouts at recording; a 4x D24S8 or D32S8 array is still read back
296 as its slice 0 on that driver (measured). The format is the depth
265 format or the plane's own (`R32_FLOAT`, `R24_UNORM_X8_TYPELESS`, `X24_TYPELESS_G8_UINT`, and the D32S8 pair, untested). 297 format or the plane's own (`R32_FLOAT`, `R24_UNORM_X8_TYPELESS`, `X24_TYPELESS_G8_UINT`, and the D32S8 pair, untested).
266 What the PC runtime accepts was measured on an RTX 5070 (driver 621.24) and on WARP: `MIN` and `MAX` of either 298 What the PC runtime accepts was measured on an RTX 5070 (driver 621.24) and on WARP: `MIN` and `MAX` of either
267 plane by either format, and `AVERAGE` of the depth plane by its own format only (its `Close` fails for `AVERAGE` 299 plane by either format, and `AVERAGE` of the depth plane by its own format only (its `Close` fails for `AVERAGE`
@@ -271,8 +303,10 @@ What is implemented (all of it testable without the game):
271 destination offset other than the source rectangle's corner is refused, as is a mode missing from the device's 303 destination offset other than the source rectangle's corner is refused, as is a mode missing from the device's
272 `supportedDepthResolveModes`/`supportedStencilResolveModes` (queried at device creation; one plane per scope, so 304 `supportedDepthResolveModes`/`supportedStencilResolveModes` (queried at device creation; one plane per scope, so
273 `independentResolve` never applies). Refused calls fail `Close` and record nothing. `d3d12_depth_resolve_test` 305 `independentResolve` never applies). Refused calls fail `Close` and record nothing. `d3d12_depth_resolve_test`
274 compares D32 and D24S8 resolves (typed and typeless resources, whole and rectangle) with the PC runtime; clears give 306 compares D32, D24S8 and D32S8 resolves (typed and typeless resources, whole and rectangle) with the PC runtime and
275 every sample of a pixel one value, so the modes over differing samples are not checked yet. `DECOMPRESS`, 307 WARP. Its edge cases (TEST-848) draw a triangle over the cleared 4x source first (depth 0.5, stencil 0x44): the
308 pixels on its diagonal edge hold differing samples, and MIN, MAX and AVERAGE over them match the PC runtime on an
309 RTX 5070 (driver 621.01) and WARP byte for byte. `DECOMPRESS`,
276 `ResolveSubresource` of depth (which D3D12 does not offer) and resolves between two formats of one typeless family 310 `ResolveSubresource` of depth (which D3D12 does not offer) and resolves between two formats of one typeless family
277 remain open. A multisampled texture copies only to one with the same sample count 311 remain open. A multisampled texture copies only to one with the same sample count
278 and has no footprint. 312 and has no footprint.
@@ -344,15 +378,19 @@ What is implemented (all of it testable without the game):
344 - descriptor heaps whose slots are 32 bytes (`GetDescriptorHandleIncrementSize`; the console's increments are 378 - descriptor heaps whose slots are 32 bytes (`GetDescriptorHandleIncrementSize`; the console's increments are
345 question 4). RTV/DSV slots hold a `TargetView`; shader-visible heaps return a GPU handle, but nothing reads it 379 question 4). RTV/DSV slots hold a `TargetView`; shader-visible heaps return a GPU handle, but nothing reads it
346 yet; 380 yet;
347 - `CreateRenderTargetView` / `CreateDepthStencilView` for whole resources, `TEXTURE2D`, `TEXTURE2DMS`, 381 - `CreateRenderTargetView` / `CreateDepthStencilView` for whole resources, `TEXTURE1D`, `TEXTURE1DARRAY` (D3D-63),
348 `TEXTURE2DARRAY` and `TEXTURE2DMSARRAY` (a slice range; 1D and 1D-array DSVs wait for 1D textures, D3D-63); 382 `TEXTURE2D`, `TEXTURE2DMS`, `TEXTURE2DARRAY` and `TEXTURE2DMSARRAY` (a slice range; `ArraySize` -1 is every
383 slice from the first on, as on the host, `d3d12_view_slices_test`);
349 - `CopyDescriptors` / `CopyDescriptorsSimple`. A descriptor is the bytes of its slot, so a copy is a byte copy: 384 - `CopyDescriptors` / `CopyDescriptorsSimple`. A descriptor is the bytes of its slot, so a copy is a byte copy:
350 the destination and source range lists are walked together, one descriptor at a time, and null size arrays 385 the destination and source range lists are walked together, one descriptor at a time, and null size arrays
351 mean one descriptor per range; 386 mean one descriptor per range;
352 - committed buffers (upload and readback heaps mapped persistently and zeroed), 1D textures and 1D arrays, and 387 - committed buffers (upload and readback heaps mapped persistently and zeroed), 1D textures and 1D arrays (render
388 targets and depth-stencils too: their attachment views are `VK_IMAGE_VIEW_TYPE_1D_ARRAY`), and
353 2D textures in the common render-target, depth and texture formats (typeless families become mutable-format 389 2D textures in the common render-target, depth and texture formats (typeless families become mutable-format
354 images), plus non-attachment 3D textures with mipmapped upload, image copy and readback, and multisampled 2D 390 images; `R24G8_TYPELESS` and `R32G8X24_TYPELESS` are depth-stencil images with or without
355 textures (single-mip render targets or depth-stencils, in the sample counts the GPU has for the format); 391 `ALLOW_DEPTH_STENCIL`, as Vulkan has no colour format with their layout), plus non-attachment 3D textures with
392 mipmapped upload, image copy and readback, and multisampled 2D textures (single-mip render targets or
393 depth-stencils, in the sample counts the GPU has for the format);
356 - packed `R9G9B9E5_SHAREDEXP` textures map to `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` for uploads and sampled views. 394 - packed `R9G9B9E5_SHAREDEXP` textures map to `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` for uploads and sampled views.
357 When `ALLOW_UNORDERED_ACCESS` is requested on a GPU whose `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` lacks native 395 When `ALLOW_UNORDERED_ACCESS` is requested on a GPU whose `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` lacks native
358 `STORAGE_IMAGE` support (for example NVIDIA), the layer backs the texture with a mutable `VK_FORMAT_R32_UINT` 396 `STORAGE_IMAGE` support (for example NVIDIA), the layer backs the texture with a mutable `VK_FORMAT_R32_UINT`
@@ -374,7 +412,9 @@ What is implemented (all of it testable without the game):
374 format then decides the alpha: a `B8G8R8X8` view of a `B8G8R8A8` texture reads 1, a `B8G8R8A8` view of a 412 format then decides the alpha: a `B8G8R8X8` view of a `B8G8R8A8` texture reads 1, a `B8G8R8A8` view of a
375 `B8G8R8X8` one the stored byte. It decides the channel order too: an `R8G8B8A8` texture whose list names 413 `B8G8R8X8` one the stored byte. It decides the channel order too: an `R8G8B8A8` texture whose list names
376 `B8G8R8A8` or `B8G8R8X8` reads red and blue swapped through those views, as on the host (both orders share one 414 `B8G8R8A8` or `B8G8R8X8` reads red and blue swapped through those views, as on the host (both orders share one
377 T# format code, so the T#'s swizzle carries the order). As on the host runtime, the family has no typed UAV, and a typed `B8G8R8X8` 415 T# format code, so the T#'s swizzle carries the order). An RTV in a format the list names stores clears and
416 draws in the view's channel order and encoding, as on the host (see the castable-list RTVs under D3D-275 below).
417 As on the host runtime, the family has no typed UAV, and a typed `B8G8R8X8`
378 texture cannot allow unordered access (the host accepts one whose castable-format list names `B8G8R8A8`; the 418 texture cannot allow unordered access (the host accepts one whose castable-format list names `B8G8R8A8`; the
379 layer doesn't yet). Blending into a `B8G8R8X8` render target reads destination 419 layer doesn't yet). Blending into a `B8G8R8X8` render target reads destination
380 alpha as 1, as WARP and AMD's D3D12 driver do: the PSO turns `DEST_ALPHA` into `ONE`, `INV_DEST_ALPHA` into 420 alpha as 1, as WARP and AMD's D3D12 driver do: the PSO turns `DEST_ALPHA` into `ONE`, `INV_DEST_ALPHA` into
@@ -421,7 +461,9 @@ What is implemented (all of it testable without the game):
421 Swapchain backbuffers are real `ID3D12Resource` COM objects (`BackBufferResource` inheriting from 461 Swapchain backbuffers are real `ID3D12Resource` COM objects (`BackBufferResource` inheriting from
422 `ID3D12ResourceStubs`) registered directly with `VulkanContext`, supporting `CreateSwapChainForHwnd`, 462 `ID3D12ResourceStubs`) registered directly with `VulkanContext`, supporting `CreateSwapChainForHwnd`,
423 `GetCurrentBackBufferIndex`, `GetBuffer`, `CreateRenderTargetView`, `Present`, and `ResizeBuffers` (preserving 463 `GetCurrentBackBufferIndex`, `GetBuffer`, `CreateRenderTargetView`, `Present`, and `ResizeBuffers` (preserving
424 explicit buffer dimensions even when the HWND client size is unchanged via an offscreen backbuffer + blit path). 464 explicit buffer dimensions even when the HWND client size is unchanged via an offscreen backbuffer + blit path,
465 and exposing exactly the requested `BufferCount` even when Vulkan's native image count differs, in which case the
466 offscreen ring is the app-visible swapchain and each present blits the current slot into the acquired image).
425 The factory answers up to `IDXGIFactory7` (D3D-2). `EnumAdapterByGpuPreference` returns the one Vulkan adapter 467 The factory answers up to `IDXGIFactory7` (D3D-2). `EnumAdapterByGpuPreference` returns the one Vulkan adapter
426 at index 0 for every preference. It accepts a preference outside the enum, as the host does, and gives 468 at index 0 for every preference. It accepts a preference outside the enum, as the host does, and gives
427 `DXGI_ERROR_INVALID_CALL` for a null `out` and `DXGI_ERROR_NOT_FOUND` past the end. The adapter list never 469 `DXGI_ERROR_INVALID_CALL` for a null `out` and `DXGI_ERROR_NOT_FOUND` past the end. The adapter list never
@@ -521,11 +563,13 @@ What is implemented (all of it testable without the game):
521 submission ends with a barrier to the host, so a readback buffer holds the GPU's writes once the fence wait 563 submission ends with a barrier to the host, so a readback buffer holds the GPU's writes once the fence wait
522 returns. Children hold a reference to the proxy, not 564 returns. Children hold a reference to the proxy, not
523 the inner device, so `GetDevice` always returns the Xbox-ABI object. Each live D3D12 queue leases a distinct 565 the inner device, so `GetDevice` always returns the Xbox-ABI object. Each live D3D12 queue leases a distinct
524 graphics-family `VkQueue`; the standalone device requests up to 16. The queues still share a submit lock for 566 `VkQueue` while one is free (its own type's family first, then the graphics family); the standalone device
567 requests up to 16 per family. The queues still share a submit lock for
525 replay state, but Wait-before-Signal between them can make progress (D3D-97), and a batch that waits for a Signal 568 replay state, but Wait-before-Signal between them can make progress (D3D-97), and a batch that waits for a Signal
526 not yet submitted is held on the CPU so layouts follow dependency order (section 4.4). Caller-owned Vulkan devices can 569 not yet submitted is held on the CPU so layouts follow dependency order (section 4.4). Caller-owned Vulkan devices can
527 supply additional handles through `VulkanDeviceInfo::command_queues`; without them they retain legacy single-queue 570 supply additional handles through `VulkanDeviceInfo::command_queues`; without them they retain legacy single-queue
528 behavior. When supplied handles are exhausted, `CreateCommandQueue` fails instead of silently sharing a queue. 571 behavior. When every handle is in use, the new D3D12 queue shares the `VkQueue` that has the fewest D3D12 queues
572 (section 4.4, "More D3D12 queues than Vulkan queues"); it used to fail with `E_OUTOFMEMORY`.
529 Dedicated compute/transfer 573 Dedicated compute/transfer
530 *families* would also require resource queue-family ownership handling and remain future work. 574 *families* would also require resource queue-family ownership handling and remain future work.
531 575
@@ -585,10 +629,10 @@ side inwards:
585 the key cannot resolve to it, which is accepted. Erasing a key empties its slot and moves no other entry 629 the key cannot resolve to it, which is accepted. Erasing a key empties its slot and moves no other entry
586 (every lookup, CPU and shader, compares all eight probe slots and never stops at an empty one), so it is 630 (every lookup, CPU and shader, compares all eight probe slots and never stops at an empty one), so it is
587 uploaded like an add. Replacing a live key's index, an insert that relocates a live entry, and a table that 631 uploaded like an add. Replacing a live key's index, an insert that relocates a live entry, and a table that
588 has grown (a new buffer behind binding 2) change what running lookups see: `flush_needs_idle()` says when a 632 has grown (a new buffer behind binding 2) change what running lookups see: `flush_replaces_table()` says when a
589 flush would do one of those, and the layer waits for the device to be idle before flushing in that case. 633 flush would do one of those, and the flush then makes a new generation instead of writing in place (D3D-314; see the
590 Erasing used to compact the probe cluster, which moved other keys and made every texture release wait for 634 paragraph on the flush at every `ExecuteCommandLists`, below). Erasing used to compact the probe cluster, which
591 the whole GPU. 635 moved other keys and made every texture release wait for the whole GPU.
592- **`runtime/src/gfx10_descriptors.h`**: the T#, S# and V# structures (section 5.3), encoded and decoded, with 636- **`runtime/src/gfx10_descriptors.h`**: the T#, S# and V# structures (section 5.3), encoded and decoded, with
593 their mapping to Vulkan formats, view types, component mappings and samplers. Field positions are Mesa's 637 their mapping to Vulkan formats, view types, component mappings and samplers. Field positions are Mesa's
594 (`src/amd/registers/gfx10-rsrc.json`) and agree with what the translator and the GPU tests already use. Bits 638 (`src/amd/registers/gfx10-rsrc.json`) and agree with what the translator and the GPU tests already use. Bits
@@ -646,11 +690,49 @@ the game writes itself, which need
646the execute-time scan of section 3.4 (only descriptors made through the device are registered); the literal S#s of shaders (`literal_samplers` in the index), 690the execute-time scan of section 3.4 (only descriptors made through the device are registered); the literal S#s of shaders (`literal_samplers` in the index),
647which `rt::d3d12::register_samplers` registers without a heap slot but which nothing passes to it yet (the call at 691which `rt::d3d12::register_samplers` registers without a heap slot but which nothing passes to it yet (the call at
648pipeline creation comes with the shader index, #291); 692pipeline creation comes with the shader index, #291);
649custom border colours without `VK_EXT_custom_border_color`, and minimum/maximum filters, anisotropy or mirror-once 693custom border colours without VK_EXT_custom_border_color, and minimum/maximum filters, anisotropy or mirror-once addressing without the Vulkan
650addressing without the corresponding Vulkan feature, each logged and approximated. In Vulkan, 694feature, each logged and approximated (note: in Vulkan, `VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT` is
651`VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT` is per-format; because bindless set 0 hashes T# and S# 695per-format; because bindless set 0 hashes `T#` and `S#` independently in the shader, `bind_sampler` cannot know
652independently, `bind_sampler` cannot know which format the sampler will be paired with. On tested Radeon iGPUs 696which image format a sampler will be paired with — on Radeon iGPUs `BC*` formats lack `MINMAX` while uncompressed
653`BC*` formats lacked `MINMAX` while uncompressed formats supported it; RTX supported all queried formats. 697formats support it, whereas RTX supports all queried formats); the storage arrays hold 255 images a dimension at the default counts, more
698where the device has room (4095 2D and 1023 2D-array on an RTX 5070); nothing writes through a
699storage view in a D3D12-level test yet (`vk_bindless_test` goes through the storage bindings at the Vulkan
700level). The set is flushed at every `ExecuteCommandLists`. A flush that moves the table to a larger buffer, changes
701the index of a live key or relocates one (`BindlessSet::flush_replaces_table()`) does not write in place and does not
702wait (D3D-314; D3D-76 first waited for the whole device, which stalled every queue and would have at every texture
703release of a game that churns textures). It makes a new generation: new table buffers (the whole table uploaded to
704them in that submission's command buffer), a new one-set descriptor pool and set (binding 2 names the new table, and
705every descriptor written so far is written again from a CPU shadow of the set, in runs, so unwritten elements stay
706unwritten under `partially_bound`), and replay binds that set at the dispatches and draws of the submission
707(`ReplayFunctions::bindless_set`; the pipelines' own `bindless_set` only marks that they use one). Submissions made
708before keep reading the old set and table, which nothing writes again. The old generation is stamped with the
709latest submission ticket and freed at a later `ExecuteCommandLists` (and at device teardown) once
710`completed_retire_ticket()` has reached it. Those tickets are the layer's per-submission records of (queue timeline
711semaphore, value): the stamp is therefore the latest submitted value of every queue that could have bound the
712set, and the free waits until each of those timelines has passed its value; nothing is waited for. The completed
713prefix is global and in order, so a queue blocked on a fence only delays the free, never another queue. The stamp
714is taken under `tracker_mutex_`, which `execute()` holds from the flush to the end of its submit, so no submission
715that bound the old set is unsubmitted when it is read. `LEONIDA_BINDLESS_IDLE_WAIT=1` restores the old wait
716(a counted `vkDeviceWaitIdle` before the flush) to compare frame times; nothing else uses it. The cost of the new
717path is a full upload of the table and a rewrite of the set's descriptors per replacing flush, where the old one
718uploaded the changed slots after the stall; `d3d12_bindless_churn_test` prints both.
719
720The pattern is the one vkd3d-proton uses to retire GPU-visible objects without a device idle (approach only, no
721code taken): stamp the object with what every queue has submitted and free it at a later submit once those
722submissions have completed. Two further rules come with it here. The submission that carries a new generation's
723table upload makes every other queue's next submission wait for its timeline value (`bindless_upload_semaphore_`,
724like the storage-image initialisation), because that submission is the first to bind the new set and a queue with no
725D3D12 fence on it could otherwise run before the copy; the table's buffers need no ownership transfer because every
726D3D12 queue of the device is made in `info.queue_family`. And at most 8 retired generations are kept: past that, the
727next flush waits (logged once, with the descriptor lock released) for the submissions up to the oldest one's ticket,
728which is a wait for those queues' timelines and not for the device. The commit of a submit's result runs under
729`tracker_mutex_`, so a later flush never sees an earlier submit's outcome unrecorded. If the new generation cannot be
730made (out of memory) the flush leaves the in-use set and the pending writes alone and fails.
731Two bindless hazards that vkd3d-proton documents for games and that this change does not remove: descriptors
732written for resources allocated after the submit that reads them, and an image and a buffer descriptor aliasing one
733heap slot (vkd3d-proton PR #3033, https://github.com/HansKristian-Work/vkd3d-proton/pull/3033). Future path, not
734implemented: `VK_EXT_descriptor_heap` (https://www.khronos.org/blog/vulkan-introduces-roadmap-2026-and-new-descriptor-heap-extension)
735would replace descriptor sets with application-sized heaps.
654 736
655A typed 3D color target supports default and explicit RTVs. The default covers mip 0; `FirstWSlice` and 737A typed 3D color target supports default and explicit RTVs. The default covers mip 0; `FirstWSlice` and
656`WSize` select the depth slices in an explicit view's mip. `d3d12_clear_test --volume` checks full and 738`WSize` select the depth slices in an explicit view's mip. `d3d12_clear_test --volume` checks full and
@@ -670,10 +752,21 @@ The compute path, end to end:
670 and an integer field outside 0..2^32−1 reads as 0. 752 and an integer field outside 0..2^32−1 reads as 0.
671- Root signatures use the model already on `main` (`runtime/src/root_signature.h`, `rt::rootsig`): `parse_rts0` 753- Root signatures use the model already on `main` (`runtime/src/root_signature.h`, `rt::rootsig`): `parse_rts0`
672 reads the serialized blob and `pack()` lays out the 32 user-data dwords by the section 3.5 default mapping, 754 reads the serialized blob and `pack()` lays out the 32 user-data dwords by the section 3.5 default mapping,
673 refusing anything that would spill. 755 refusing anything that would spill. `pack_stage()` lays them out in the console layout of one stage (section 3.5,
756 D3D-448); the compute bind point uses it.
674- **GPU address arena** (section 3.3, when the device has `bufferDeviceAddress`): one host-visible, 757- **GPU address arena** (section 3.3, when the device has `bufferDeviceAddress`): one host-visible,
675 device-addressable buffer, 256 MiB by default (`LEONIDA_ARENA_MB`, at most 4095 MiB, so every VA fits 32-bit 758 device-addressable buffer, 256 MiB by default (`LEONIDA_ARENA_MB`, at most 4095 MiB, so every VA fits 32-bit
676 table pointers). 759 table pointers).
760 - It is also no larger than the device's `maxBufferSize` (Vulkan 1.3) and, counting the buffer's memory
761 requirement, `maxMemoryAllocationSize` (Vulkan 1.1), whichever is smaller (`runtime/src/arena_size.h`). When a
762 limit cuts the request, one log line names the limit and the size used. `arena_size_test` (CPU) checks the
763 decision on synthetic limits; `d3d12_compute_test` checks the arena against the device's limits and a simulated
764 32 MiB `maxMemoryAllocationSize`.
765 - The RX 6800 (RDNA2, AMD driver 26.11.2, Windows 11, measured 2026-11-22) reports 2 GiB for both, so
766 `LEONIDA_ARENA_MB` above 2048 gets a 2048 MiB arena there.
767 - Before the cap, that driver did create a 3000 MiB arena. Buffers placed past 2 GiB in it (VA 0x89820000) were
768 written by a compute shader and read back correctly, but the validation layer reports the allocation as over
769 `maxMemoryAllocationSize`. Nothing relies on this out-of-spec behaviour.
677 - The device logs the arena's high-water mark when it is destroyed: the peak end offset against the size, the 770 - The device logs the arena's high-water mark when it is destroyed: the peak end offset against the size, the
678 most bytes live at once (by use: buffers, descriptor heaps, shaders, heaps), allocations and refusals (D3D-55). 771 most bytes live at once (by use: buffers, descriptor heaps, shaders, heaps), allocations and refusals (D3D-55).
679 `LEONIDA_ARENA_LOG=1` also logs one line per VA handed out, per refused allocation, and per upload or readback 772 `LEONIDA_ARENA_LOG=1` also logs one line per VA handed out, per refused allocation, and per upload or readback
@@ -683,8 +776,11 @@ The compute path, end to end:
683 so descriptor bytes the application writes itself are what shaders load. 776 so descriptor bytes the application writes itself are what shaders load.
684 - Upload and readback buffers keep their own memory, and their VA is their device address minus the heap base. 777 - Upload and readback buffers keep their own memory, and their VA is their device address minus the heap base.
685 - Shader programs (FSSM blobs) are copied in as the code base. 778 - Shader programs (FSSM blobs) are copied in as the code base.
686- **`CreateRootSignature`** parses the blob with `parse_rts0` and keeps each parameter's place from `pack()`; a 779- **`CreateRootSignature`** parses the blob with `parse_rts0` and keeps each parameter's place in two layouts:
687 signature `pack()` refuses (more than 32 user dwords: the spill layout is open) is refused with its reason. Before 780 `pack()` for the graphics bind point and `pack_stage(Stage::Compute)` for the compute one (from s4, one dword per
781 table; section 3.5, D3D-448). A signature neither can place (more than 32 user dwords: the spill layout is open; the
782 translated shaders have no below-base spill-pointer candidates) is refused with both reasons; one only a single layout places is created with a log line, and binding it at the other bind point
783 invalidates the list. Before
688 that it answers as the host runtime does (`compare_invalid_arguments`, "root signature:", RTX 5070 / 621.14): 784 that it answers as the host runtime does (`compare_invalid_arguments`, "root signature:", RTX 5070 / 621.14):
689 `S_FALSE` for a null output whatever the blob, then `E_INVALIDARG` for a node other than node 0 or a DXBC 785 `S_FALSE` for a null output whatever the blob, then `E_INVALIDARG` for a node other than node 0 or a DXBC
690 container whose size (the dword at +24) is not the size passed. 786 container whose size (the dword at +24) is not the size passed.
@@ -694,8 +790,13 @@ The compute path, end to end:
694 that set they are refused with a log. 790 that set they are refused with a log.
695- **Command list**: `Set{Compute,Graphics}RootSignature` (a different signature clears the arguments, as D3D12 791- **Command list**: `Set{Compute,Graphics}RootSignature` (a different signature clears the arguments, as D3D12
696 leaves them undefined; setting the bound one again keeps them, as D3D12 does), `SetPipelineState`, the 32-bit 792 leaves them undefined; setting the bound one again keeps them, as D3D12 does), `SetPipelineState`, the 32-bit
697 constant, root view and descriptor-table setters, `SetDescriptorHeaps` and `ClearState`. A wrong parameter type 793 constant, root view and descriptor-table setters, `SetDescriptorHeaps` and `ClearState`. A wrong parameter type,
698 or out-of-range constants makes `Close` return `E_INVALIDARG`. 794 out-of-range constants, or an invalid `SetDescriptorHeaps` call makes `Close` return `E_INVALIDARG`.
795 - `SetDescriptorHeaps` tracks the currently bound shader-visible `CBV_SRV_UAV` and `SAMPLER` heaps and their
796 arena GPU base VAs, holds references to them until `Reset` or list destruction, unbinds omitted types (clearing
797 both on `ClearState` and `Reset`), refuses `COPY` lists, > 2 heaps, null arrays/elements, non-shader-visible or
798 `RTV`/`DSV`/duplicate-type/foreign-device heaps, and enforces bundle matching against the parent list (`parent`'s
799 currently bound heap for each non-null heap the bundle specifies, `d3d12_set_descriptor_heaps`).
699 - The list holds a reference to every root signature and pipeline state it is given, until `Reset` or its own 800 - The list holds a reference to every root signature and pipeline state it is given, until `Reset` or its own
700 release. D3D12 lets an application release them right after setting them, so the root layout the setters read 801 release. D3D12 lets an application release them right after setting them, so the root layout the setters read
701 and the pipeline `ExecuteCommandLists` looks up must outlive that. Keeping them alive while the GPU runs the 802 and the pipeline `ExecuteCommandLists` looks up must outlive that. Keeping them alive while the GPU runs the
@@ -710,25 +811,79 @@ The compute path, end to end:
710 topology, stencil references and the blend factor are dynamic, and so are vertex strides when the pipeline has 811 topology, stencil references and the blend factor are dynamic, and so are vertex strides when the pipeline has
711 vertex bindings. A pipeline without them (a full-screen pass from `SV_VertexID`) does not declare the stride 812 vertex bindings. A pipeline without them (a full-screen pass from `SV_VertexID`) does not declare the stride
712 state, since nothing would set it (`VUID-vkCmdDraw-pStrides-04913`). 813 state, since nothing would set it (`VUID-vkCmdDraw-pStrides-04913`).
814 `d3d12_state_sweep_test` checks the mapping against the host on the same adapter: 482 full-screen draws over
815 every blend factor pair, blend operation, write mask, comparison function and stencil operation, with the stencil
816 plane read back, are byte-identical on an RTX 5080 and a Radeon iGPU.
713 - **Logic ops** come from `RenderTarget[0]`, as in D3D12, and apply to every target (Vulkan has one per 817 - **Logic ops** come from `RenderTarget[0]`, as in D3D12, and apply to every target (Vulkan has one per
714 pipeline; it skips float formats). **`DepthClipEnable = FALSE`** is depth clamping: D3D12 clamps output depth 818 pipeline; it skips float formats). **`DepthClipEnable = FALSE`** is depth clamping: D3D12 clamps output depth
715 to the viewport's range anyway. 819 to the viewport's range anyway.
716 - **Conservative rasterization (Tier 1):** the standalone device enables `VK_EXT_conservative_rasterization` 820 - **Conservative rasterization (Tier 1/2):** the standalone device enables `VK_EXT_conservative_rasterization`
717 when available; caller-owned devices must set `VulkanDeviceInfo::conservative_rasterization` only if they 821 when available; caller-owned devices must set `VulkanDeviceInfo::conservative_rasterization` only if they
718 enabled it. OPTIONS reports Tier 1 only with at least eight subpixel precision bits and a finite, nonnegative 822 enabled it. OPTIONS reports at least Tier 1 only with at least eight subpixel precision bits and a finite, nonnegative
719 primitive overestimation no greater than `0.5 - 1/512` pixels, leaving half a minimum grid step within the 823 primitive overestimation no greater than `0.5 - 1/512` pixels, leaving half a minimum grid step within the
720 Tier 1 uncertainty bound. `ConservativeRaster=ON` uses overestimate mode with zero extra overestimation, 824 Tier 1 uncertainty bound. `ConservativeRaster=ON` uses overestimate mode with zero extra overestimation,
721 including unbound-attachment variants. OFF keeps the ordinary pipeline. Missing support, unknown modes, 825 including unbound-attachment variants. OFF keeps the ordinary pipeline. Missing support, unknown modes,
722 wireframe and non-triangle PSOs are refused; conservative TIR (`ForcedSampleCount != 0`) remains `E_NOTIMPL`. 826 wireframe and non-triangle PSOs are refused; conservative TIR (`ForcedSampleCount != 0`) remains `E_NOTIMPL`.
723 Tier 2/3 and `SV_InnerCoverage` are not exposed. See [Microsoft's rules](https://learn.microsoft.com/en-us/windows/win32/direct3d12/conservative-rasterization) 827 Tier 2 additionally requires `degenerateTrianglesRasterized` and primitive overestimation plus half a
828 device subpixel step no greater than 1/256 pixel. Other eligible devices retain Tier 1. The standalone
829 device does not expose Tier 3: the Xbox `SV_InnerCoverage` input mapping has not been confirmed. See
830 [Microsoft's rules](https://learn.microsoft.com/en-us/windows/win32/direct3d12/conservative-rasterization)
724 and [Vulkan's properties](https://docs.vulkan.org/refpages/latest/refpages/source/VkPhysicalDeviceConservativeRasterizationPropertiesEXT.html). 831 and [Vulkan's properties](https://docs.vulkan.org/refpages/latest/refpages/source/VkPhysicalDeviceConservativeRasterizationPropertiesEXT.html).
832 `d3d12_conservative_tier2_test` checks the tighter geometric uncertainty bound, post-snap and exact
833 degenerates with distinct indices, provoking-vertex colour, constant depth, back-facing classification,
834 culling, indexed permutations, triangle strips, scissor and unbound-attachment variants. On RX 5700 XT
835 (Windows driver 32.0.21045.5002), 16 tight-bound scenes and 480 degenerate draws pass across Vulkan and native
836 AMD D3D12. The WARP comparison omits only its pixel-corner fixture: WARP drops that tiny triangle even though
837 Vulkan and native AMD cover it. `--warp-corner` retains the strict failing software-reference reproducer;
838 Vulkan always checks the corner. Variable `SV_Position.z` is not a provoking-vertex oracle: both native
839 references and Vulkan exhibit extrapolation for screen-space degenerates. This test checks constant depth
840 and separately varying colour, and does not claim a depth-buffer readback or variable-depth conformance.
725 `d3d12_conservative_raster_test` checks geometric required/forbidden coverage, subpixel/sliver and degenerate 841 `d3d12_conservative_raster_test` checks geometric required/forbidden coverage, subpixel/sliver and degenerate
726 triangles, culling, scissor, 1x/4x MSAA, variants, feature reporting and refusals. Uncertain edge pixels are 842 triangles, culling, scissor, 1x/4x MSAA, variants, feature reporting and refusals. Uncertain edge pixels are
727 allowed to differ. On RX 5700 XT (Windows 32.0.21045.5002), 48 scenario pairs pass on Vulkan and native AMD; 843 allowed to differ. On RX 5700 XT (Windows 32.0.21045.5002), 48 scenario pairs pass on Vulkan and native AMD;
728 24 single-sample pairs pass on WARP. WARP's 4x subpixel fixture covers outside the geometric bound; it remains 844 24 single-sample pairs pass on WARP. WARP's 4x subpixel fixture covers outside the geometric bound; it remains
729 reproducible with `--warp-msaa4`, separately from CTest's 1x software comparison. Vulkan's 4x oracle remains 845 reproducible with `--warp-msaa4`, separately from CTest's 1x software comparison. Vulkan's 4x oracle remains
730 strict. The GPU test needs the current graphics path's 144-byte push-constant support; CPU capability checks 846 strict. On RTX 3060 (Windows 11, NVIDIA 610.88), 48 pairs pass on Vulkan and native NVIDIA. The oracle judges
847 the layer alone. A native render that fails it is printed as "host not comparable", with its normal and
848 conservative pixel counts, and that scenario isn't compared with the host. For example, Windows 10's WARP
849 (`d3d10warp.dll` 10.0.19041, the host CTest selects with `LEONIDA_HOST_ADAPTER=warp`) misses pixel (4,4) of
850 scene 4 with conservative rasterization on: seen on an RTX 5060 Ti and an RTX 2060 machine, both of which pass
851 with their NVIDIA GPU as the host (TEST-907).
852 The GPU test needs the current graphics path's 144-byte push-constant support; CPU capability checks
731 do not need a GPU. No game-pass usage is claimed by these synthetic tests. 853 do not need a GPU. No game-pass usage is claimed by these synthetic tests.
854 `d3d12_conservative_tier3_reference` is a native D3D12 reference probe, not Tier 3 support in the Vulkan layer.
855 **Explicit InnerCoverage library contract (experimental):** a caller-owned device can set
856 `VulkanDeviceInfo::inner_coverage_abi` only for a shader library whose InnerCoverage input is already lowered
857 to the boolean SPIR-V `FullyCoveredEXT` built-in (false maps to uint 0, true to uint 1). Tier 3 then also
858 requires all Tier 2 properties and `fullyCoveredFragmentShaderInputVariable`. The default remains false,
859 including for the standalone device; this is not an inferred FSSM/VGPR layout or automatic game-shader support.
860 Graphics PSOs inspect the actual SPIR-V capability, even if index capability metadata is absent, and refuse
861 `FragmentFullyCoveredEXT` with `E_NOTIMPL` before shader-module creation unless the contract and device support
862 are present. A module using `PostDepthCoverage` additionally requires
863 `conservativeRasterizationPostDepthCoverage`. The tests use explicit synthetic GLSL; no new translator rule
864 or retail shader coverage is claimed.
865 `inner_coverage_oracle` checks false positives, missed interior values and missing invocations on the CPU.
866 `d3d12_inner_coverage_guards` checks that neither opt-in nor metadata omission can bypass missing support.
867 `d3d12_inner_coverage_native` checks 48 native D3D12 scenarios on the matching adapter: six triangles,
868 1x/4x MSAA, scissor and unbound-target variants. These pass on RX 5700 XT (Windows 32.0.21045.5002) with
869 Vulkan validation active. `d3d12_conservative_tier3` runs the same 48 scenario pairs on Vulkan and native D3D12
870 when Vulkan has the property and native D3D12 has Tier 3; it skips on this RX 5700 XT. The positive Vulkan
871 path still requires independent execution on a capable GPU. InnerCoverage with conservative rasterization
872 off is undefined in D3D12 and is not compared. Edge pixels within the uncertainty region are not required
873 to match byte-for-byte; both backends must independently satisfy the geometric guarantees.
874 To validate the explicit path, configure with Vulkan SDK/glslang available, build
875 `d3d12_conservative_tier3_test`, select an adapter with `LEONIDA_VK_DEVICE` if needed, and run
876 `ctest --test-dir runtime/build -C RelWithDebInfo -R "^(inner_coverage_oracle|d3d12_inner_coverage_guards|d3d12_inner_coverage_native|d3d12_conservative_tier3)$" -V`.
877 Check that the positive test prints 48 Vulkan/native paired scenarios rather than `Skipped`.
878 `d3d12_conservative_tier3_reference` remains a native D3D12 reference probe; it does not opt in to that Vulkan contract.
879 It reports the selected Vulkan device's `fullyCoveredFragmentShaderInputVariable`, matches that device to its
880 native D3D12 adapter by LUID, then checks the adapter's Tier 3 `SV_InnerCoverage` output on four synthetic
881 triangles. On Windows with Visual Studio 2022 and Windows SDK 10.0.26100 or newer, run
882 `.\scripts\run_conservative_tier3_reference.ps1` from the repository root; by default this uses Vulkan's default
883 adapter. Pass `-Device <name substring>` to select a specific one when multiple GPUs are present. It builds only
884 this test, needs no glslang, and fetches the pinned Vulkan headers only if none are installed. The verbose CTest
885 output reports the capability and result; it skips if the selected device lacks a matching native D3D12 adapter
886 or Tier 3.
732 - **Formats:** dynamic rendering takes the RTV and DSV formats. A draw that leaves a slot unbound for which the 887 - **Formats:** dynamic rendering takes the RTV and DSV formats. A draw that leaves a slot unbound for which the
733 PSO names a format (D3D12 allows it and discards those writes) uses a variant of the pipeline with that format 888 PSO names a format (D3D12 allows it and discards those writes) uses a variant of the pipeline with that format
734 undefined, built on first use and kept with the PSO. Bit i of the variant key is colour slot i, and bit 8 is 889 undefined, built on first use and kept with the PSO. Bit i of the variant key is colour slot i, and bit 8 is
@@ -742,6 +897,15 @@ The compute path, end to end:
742 entries), `shaderFloat64`, `shaderInt16`, `shaderClipDistance` and `shaderCullDistance` where the GPU has them. 897 entries), `shaderFloat64`, `shaderInt16`, `shaderClipDistance` and `shaderCullDistance` where the GPU has them.
743 Without one, `vkCreateShaderModule` reports the capability (`VUID-VkShaderModuleCreateInfo-pCode-08740`). The 898 Without one, `vkCreateShaderModule` reports the capability (`VUID-VkShaderModuleCreateInfo-pCode-08740`). The
744 index's `features` list is not read yet, so a shader that needs a feature the GPU lacks is not refused up front. 899 index's `features` list is not read yet, so a shader that needs a feature the GPU lacks is not refused up front.
900 - **Stores and atomics outside compute:** a pixel shader that stores to an image or does an image atomic declares
901 that storage image without `NonWritable` (of the 1,038 translated 1.0.2.1 modules that contain an image atomic,
902 counted as modules with an `OpImageTexelPointer` and split by the index's stage, 1,018 are pixel shaders and 20
903 compute),
904 which Vulkan allows only with `fragmentStoresAndAtomics` (`VUID-RuntimeSpirv-NonWritable-06340`); a vertex or
905 geometry shader needs `vertexPipelineStoresAndAtomics` (`-06341`). The standalone device enables both where the
906 GPU has them. A graphics PSO whose stage declares writable storage (read off the module's declarations,
907 `src/spirv_stores.h`) on a device without the feature is refused with `E_NOTIMPL` and a log naming the shader.
908 `d3d12_stores_atomics_test` checks both under the validation layer.
745 - **Geometry shaders:** `desc.GS` is the translator's Vulkan geometry stage (docs/design.md, "Geometry 909 - **Geometry shaders:** `desc.GS` is the translator's Vulkan geometry stage (docs/design.md, "Geometry
746 shaders": triangles in, a triangle strip out) between the VS and PS. It needs `geometryShader`, which the 910 shaders": triangles in, a triangle strip out) between the VS and PS. It needs `geometryShader`, which the
747 standalone device enables where the GPU has it and reports in `VulkanDeviceInfo::features`; without it such a 911 standalone device enables where the GPU has it and reports in `VulkanDeviceInfo::features`; without it such a
@@ -818,12 +982,39 @@ the game's present entry point (`PresentX`; the DXGI factory/swapchain and the p
818 wave32) needs no chain. Where the size cannot be required (stage not listed, feature off) but the device default is 982 wave32) needs no chain. Where the size cannot be required (stage not listed, feature off) but the device default is
819 the wanted one, the shader works as it is (`device_default`; nothing guarantees the default, so it is not logged 983 the wanted one, the shader works as it is (`device_default`; nothing guarantees the default, so it is not logged
820 as inexact); any other size is `unavailable` and logged. 984 as inexact); any other size is `unavailable` and logged.
821 - **Which stages can be required:** it is the driver's list, not a fixed rule. The AMD Windows driver reports 985 - **Which stages can be required:** it is the driver's list, not a fixed rule, and AMD's Windows driver gives
822 FRAGMENT | COMPUTE | TASK | MESH (measured on a Radeon 880M, 26.11.2, sizes 32..64), so wave64 and wave32 pixel 986 different lists for different GPUs, on the same 26.11.2 release too:
823 shaders run exact there; so does current Mesa RADV on GFX10+ (COMPUTE | FRAGMENT | task/mesh, Mesa main at 987 - Radeon 880M (RDNA3.5, gfx1150), 26.11.2: FRAGMENT | COMPUTE | TASK | MESH, sizes 32..64, so wave64 and wave32
824 152b9cde, `src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`; older Mesa reported compute only). 988 pixel shaders run exact there.
825 NVIDIA lists every stage but only size 32, so a native wave64 shader cannot get 64 there. Vertex and geometry 989 - RX 6800 (RDNA2 like the console; gfx1030), 26.11.2 (Windows driver 32.0.21045.29003), measured 2026-11-22:
826 stages are in neither list. 990 COMPUTE only, sizes 32..64, default 64 (`vulkaninfo`; the device log says `requirable in stages 0x20`). No
991 size can be requested for pixel or mesh shaders (`vk_harness` chains none for `VKH_SUBGROUP_SIZE`), and at the
992 default they run 64-wide: a GLSL probe pixel shader drawn by `vk_harness` counts 64 live invocations per
993 subgroup (`subgroupBallotBitCount`) on a full-screen draw (SPIR-V 1.5 and 1.6), and `ms_w64x_ballot` (both
994 halves of a wave64) passes natively. For the translated SPIR-V 1.5 modules, made without
995 `ALLOW_VARYING_SUBGROUP_SIZE`, the specification fixes `SubgroupSize` at that default ("Varying Subgroup
996 Size"); only the driver's default could change. So wave64 pixel and mesh shaders work at the default
997 (`device_default`; the layer has no mesh PSO yet), and a wave32 pixel shader is `unavailable`: two of its
998 waves share a subgroup. `ps_bitmask_perm` shows it: lanes 0-31 exact, while the
999 other 2,048 of 4,096 pixels read `v_mbcnt_lo` = 32 instead of their lane (the fixture's check judges lanes
1000 0-31 only). Of the 1,127 wave32 pixel shaders in the corpus, 1,010 contain a `v_readlane`/`v_writelane`/
1001 `v_readfirstlane`, 146 a `v_mbcnt`, 105 an `s_bcnt1`/`s_ff1` of a lane mask, and all 1,127 a branch on EXEC
1002 or VCC or an SCC vote on a mask, which the translator decides by a subgroup vote (117 have only those). 926
1003 also have `v_permlanex16` and row DPP and 826 quad ops, which stay inside a 32-lane half as translated
1004 (`tools/wave32_pixel_scan.py`; counts of candidates, not verdicts).
1005 - Ryzen 7 9800X3D iGPU (RDNA2, gfx1036), Windows driver 32.0.21045.5002: COMPUTE only, sizes 32..64; RX 9070 XT
1006 (RDNA4, gfx1201), Windows driver 32.0.31041.1004: FRAGMENT | COMPUTE | TASK | MESH, sizes 32..64
1007 (@AC-Storm-YT, `vulkaninfoSDK` from Vulkan SDK 1.4.363.1,
1008 [#313](https://github.com/ItsNotRexed/Leonida/issues/313#issuecomment-7086133354)). The same two lists on
1009 AMD 26.11.2 (Windows drivers 32.0.21045.29003 and 32.0.32029.2010), where `ps_bitmask_perm` also shows the
1010 live fragment width: the gfx1036 iGPU gets the RX 6800's split (2,048 of 4,096 pixels read lane 32), the
1011 RX 9070 XT is exact on all 4,096 (@AC-Storm-YT,
1012 [#3982](https://github.com/ItsNotRexed/Leonida/pull/3982#issuecomment-7088523396) and #4225).
1013
1014 Current Mesa RADV on GFX10+ lists COMPUTE | FRAGMENT | task/mesh (Mesa main at 152b9cde,
1015 `src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`; older Mesa reported compute only), so
1016 pixel shaders run exact there. NVIDIA lists every stage but only size 32, so a native wave64 shader cannot get 64
1017 there. Vertex and geometry stages are in neither list.
827 - **A size the device cannot give** is logged once per stage with the first shader's name (and again at 10, 100, 1018 - **A size the device cannot give** is logged once per stage with the first shader's name (and again at 10, 100,
828 1000 shaders of that stage): `[rt] d3d12: <name> (<stage>) is a 64-wide shader but this device cannot require that 1019 1000 shaders of that stage): `[rt] d3d12: <name> (<stage>) is a 64-wide shader but this device cannot require that
829 subgroup size ...`. For compute and mesh the fix is the build, `--wave64-emulate` (`make_game.py 1020 subgroup size ...`. For compute and mesh the fix is the build, `--wave64-emulate` (`make_game.py
@@ -835,7 +1026,7 @@ the game's present entry point (`PresentX`; the DXGI factory/swapchain and the p
835 1026
836Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and 1027Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and
837therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines, 1028therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines,
838multisampled pipelines, several viewports, primitive restart; subgroup size for mesh pipelines (the decision covers them, no mesh PSO exists to chain it into), and for wave64 vertex, geometry and, on a GPU that cannot require 64 for pixel shaders (NVIDIA), pixel shaders, which have no emulation (SHADER-10); 1029multisampled pipelines, several viewports, primitive restart; subgroup size for mesh pipelines (the decision covers them, no mesh PSO exists to chain it into), and for wave64 vertex, geometry and, on a GPU that cannot require 64 for pixel shaders (NVIDIA), pixel shaders, which have no emulation (SHADER-10); wave32 pixel shaders on a GPU that runs the fragment stage 64-wide and cannot require 32 for it (RDNA2 under AMD's Windows driver, "Subgroup size" above), where two waves share a subgroup;
839the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what either 1030the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what either
840calls), HDR and fullscreen; buffer and constant-buffer views (UAV clears read the descriptor bytes, so they do 1031calls), HDR and fullscreen; buffer and constant-buffer views (UAV clears read the descriptor bytes, so they do
841not wait on view creation), typeless volume RTVs, depth-stencil resolves to a destination offset other than 1032not wait on view creation), typeless volume RTVs, depth-stencil resolves to a destination offset other than
@@ -936,8 +1127,12 @@ and any validation error fails them.
936 the 43 rows: an exact half-level LOD, or a fractional ResourceMinLODClamp. LOD 1.49 reads level 1 on both. The 1127 the 43 rows: an exact half-level LOD, or a fractional ResourceMinLODClamp. LOD 1.49 reads level 1 on both. The
937 AMD driver does not follow it. Through the runtime's own path (`vk_sampler_test`, `vulkan_sampler(decode(S#))`), 1128 AMD driver does not follow it. Through the runtime's own path (`vk_sampler_test`, `vulkan_sampler(decode(S#))`),
938 an S# LOD_BIAS of +0.5 on `image_sample_lz` reads level 1, like the console, on the same gfx1036 and on an RX 7800 1129 an S# LOD_BIAS of +0.5 on `image_sample_lz` reads level 1, like the console, on the same gfx1036 and on an RX 7800
939 XT (both AMD 26.10.1). So on AMD hosts the S# case matches. Other hosts (NVIDIA, Intel, Mesa) are not measured 1130 XT (both AMD 26.10.1). So on AMD hosts the S# case matches. On other hosts the result splits: Mesa llvmpipe
940 here. 1131 (Mesa 23.2.1, LLVM 15.0.7) and an Apple M2 (macOS 26.4, MoltenVK 1.4.2) follow the spec's nearest rule — the
1132 same `vk_sampler_test` S# with LOD_BIAS +0.5 reads level 0 (on the M2 the same explicit `image_sample_lz` with
1133 bias 0 and -0.5 also reads level 0; llvmpipe switches to level 1 at 129/256, for LOD_BIAS and MIN_LOD alike),
1134 while NVIDIA reads level 1, like the console: an RTX 5070 (driver 610.88) switches at exactly 128/256. Intel
1135 is not measured here.
941 - **Layout.** gfx1036 lays a linear mip chain out smallest level first, each row padded to 256 bytes. Levels 6..0 1136 - **Layout.** gfx1036 lays a linear mip chain out smallest level first, each row padded to 256 bytes. Levels 6..0
942 of the 64-wide R32 chain start at dwords 0, 64, 192, 448, 960, 1984 and 4032. 1137 of the 64-wide R32 chain start at dwords 0, 64, 192, 448, 960, 1984 and 4032.
943 1138
@@ -1096,6 +1291,10 @@ and any validation error fails them.
1096 .asm header where the PSO required 64: 4096 of 4096 on the 880M. The control is asserted to differ only where the 1291 .asm header where the PSO required 64: 4096 of 4096 on the 880M. The control is asserted to differ only where the
1097 default pixel subgroup is not 64; the 880M runs pixel shaders 64-wide by default, so its control is exact too. On 1292 default pixel subgroup is not 64; the 880M runs pixel shaders 64-wide by default, so its control is exact too. On
1098 the RTX 5070 the shader gets no 64 (0 of 4096 exact, not judged). 1293 the RTX 5070 the shader gets no 64 (0 of 4096 exact, not judged).
1294 - **RX 6800 (RDNA2, AMD Windows driver 26.11.2, 2026-11-22):** the compute requests take effect (wave32 compute
1295 goes from 64-wide to 32-wide), but nothing can be requested for the fragment stage: the pixel probe runs at the
1296 64-wide default for the wave64, wave32 and emulated entries (outcomes `device_default`, `unavailable`, `emulated`), and
1297 `ps_w64x_readlane` is not judged; its control, at the 64-wide default, is 4096 of 4096 exact.
1099- `d3d12_descriptor_test`: descriptors through the proxy. 1298- `d3d12_descriptor_test`: descriptors through the proxy.
1100 - Copies, checked on the slots' bytes: one run, range lists of different shapes on each side, null size 1299 - Copies, checked on the slots' bytes: one run, range lists of different shapes on each side, null size
1101 arrays, and a destination longer than its source. 1300 arrays, and a destination longer than its source.
@@ -1143,6 +1342,38 @@ and any validation error fails them.
1143 refused with `E_INVALIDARG`: an untranslated program, bare and in a container; kind-6 entries that end past the 1342 refused with `E_INVALIDARG`: an untranslated program, bare and in a container; kind-6 entries that end past the
1144 payload, start inside the directory, wrap 32 bits, are too large or are empty; a container without `ACCC`; bytes 1343 payload, start inside the directory, wrap 32 bits, are too large or are empty; a container without `ACCC`; bytes
1145 without the prologue; and the program with four bytes appended. 1344 without the prologue; and the program with four bytes appended.
1345- `d3d12_bindless_churn_test`: the table churn of D3D-314 through D3D12 alone, on a direct and a compute queue with
1346 three frames in flight. Each of 96 frames makes 24 textures with SRVs in a ring of shader-visible heap slots and
1347 releases those of seven frames earlier (about 190 live keys, so the table grows), the direct queue uploads, the
1348 compute queue waits for it on the GPU, and each queue runs the `cs_set0_sample.comp` shader eight times on SRVs
1349 of the frame and the three before it. All 98,304 sampled texels per run are compared with what the CPU wrote.
1350 The two D3D12 queues get distinct `VkQueue`s where the device's family has two (`queue_count_wanted = 2`,
1351 `command_queues`; the test prints which it got and says so when the family has only one). Two queues on one
1352 `VkQueue` are ordered by submission, which hides a missing wait between them. It runs four times: as the layer is (0
1353 `vkDeviceWaitIdle` for the bindless set required, at least one generation made, a retired generation seen pending
1354 right after the submit that made it); with the compute queue never waiting on the direct queue's fence (it samples
1355 textures the CPU has seen finished, so only the grown table is new to it); and both again with
1356 `LEONIDA_BINDLESS_IDLE_WAIT=1` (the old wait, counted above 0). Times are printed, not asserted. The async runs
1357 are what the layer's wait on the uploading submission keeps correct: with that wait removed, the RTX 5070 run
1358 failed at frame 5 (compute read a zeroed table: the grown binding 2 with the upload not yet run), as @duudiis
1359 reported on #2740; the old-wait path shares that bug on `main` (the idle wait only covers work already submitted,
1360 not another queue's later submission that binds the new table). The Radeon 880M did not reproduce it in two
1361 runs. `d3d12_bindless_churn_validated` runs it under the validation layer.
1362 The table's growth is the only replacing flush this scenario produces (3 generations). The other kinds (a live
1363 key's index replaced, a relocation) and the failed-submit retry are checked at the Vulkan level by
1364 `vk_bindless_test` cases 3 to 6 (the set changes; `release_retired` frees only what its ticket allows). That test
1365 needs the translated `vs_ids`, `ps_tex` and `ps_imgatomic`; it was not in ctest before D3D-314 (only
1366 `scripts/run_gpu_tests.py` and `check.py` ran it), and is now, as `vk_bindless_ps_tex` and `vk_bindless_ps_imgatomic`.
1367 without the prologue; and the program with four bytes appended. It also covers the dispatch state:
1368 - one program in containers with three kind-0 entries picks its own entry for each, an unknown kind 0 is refused, and
1369 the bare program is refused as ambiguous;
1370 - slot 67 with all four pairs picks by kind 0 too (one entry's module is missing on purpose, so the pick shows as
1371 `E_FAIL`), and four inconsistent pairs are refused before they are read;
1372 - slot 67 with the description built the way the DLL builds it (`dll_slot67`: the reader's pair order over the
1373 container's own directory, kinds 0, 1 and 7 pointing into the payload, kind 6 copied into a 256-rounded buffer
1374 padded with `0xcc`) resolves each program to its own translation with its own state;
1375 - console slot 11 on a slot-67 and a slot-62 pipeline returns an object whose slot 3 points at the dword 0 and whose
1376 slot 4 gives 4 bytes; it releases to 0, and the pipeline's reference count is unchanged.
1146- `d3d12_set0_compute_test`: set 0 from the compute bind point, through the proxy and D3D12 alone. The index entry 1377- `d3d12_set0_compute_test`: set 0 from the compute bind point, through the proxy and D3D12 alone. The index entry
1147 of its shader lists set-0 bindings, so the PSO's layout holds the device's bindless set and replay binds it at 1378 of its shader lists set-0 bindings, so the PSO's layout holds the device's bindless set and replay binds it at
1148 each dispatch; nothing in the test binds it. Four dispatches of `test/glsl/cs_set0_sample.comp` (GLSL written to 1379 each dispatch; nothing in the test binds it. Four dispatches of `test/glsl/cs_set0_sample.comp` (GLSL written to
@@ -1189,7 +1420,8 @@ and any validation error fails them.
1189 that the whole image holds the clear colour at the swapchain's size (after the first 60 frames, after the 1420 that the whole image holds the clear colour at the swapchain's size (after the first 60 frames, after the
1190 resize and at the end). Last, it reads the colour on screen with GDI when the window is in front, no other 1421 resize and at the end). Last, it reads the colour on screen with GDI when the window is in front, no other
1191 window lies over its centre (an always-on-top one can, even over the foreground window) and GDI can read the 1422 window lies over its centre (an always-on-top one can, even over the foreground window) and GDI can read the
1192 screen. Under Wine's macOS driver it can't: `GetPixel` on the screen DC returns `CLR_INVALID` even 1423 screen. On a GPU that does not drive the window's monitor (the UHD 770 with the desktop on an RTX 4080 SUPER) the
1424 desktop never shows the swapchain, so the test prints the pixel, does not assert it and says why. Under Wine's macOS driver it can't: `GetPixel` on the screen DC returns `CLR_INVALID` even
1193 for a pixel GDI painted itself, and the window's own DC holds Wine's GDI surface (white), not the image 1425 for a pixel GDI painted itself, and the window's own DC holds Wine's GDI surface (white), not the image
1194 presented through the Metal layer. There the capture checks are what confirms the colour. 1426 presented through the Metal layer. There the capture checks are what confirms the colour.
1195 - The injected failures below make the runtime log `[rt] d3d12: present failed` three times (VkResult 1427 - The injected failures below make the runtime log `[rt] d3d12: present failed` three times (VkResult
@@ -1222,7 +1454,8 @@ host_address = heap_base + console_va
1222where `heap_base` is push-constant dwords 32–33 and `console_va` is an Xbox GPU virtual address the game writes 1454where `heap_base` is push-constant dwords 32–33 and `console_va` is an Xbox GPU virtual address the game writes
1223into a descriptor, a root argument, or a buffer. This applies to buffer, descriptor-table and shader-code 1455into a descriptor, a root argument, or a buffer. This applies to buffer, descriptor-table and shader-code
1224addresses. Image descriptors (T#) are hashed by the translator, not dereferenced, so an image's base can be a 1456addresses. Image descriptors (T#) are hashed by the translator, not dereferenced, so an image's base can be a
1225separate key range (below). Some shaders also force the high dword of a descriptor-table pointer to zero, so 1457separate key range (below). Most shaders also force the high dword of a descriptor-table pointer to zero (25,865
1458of the 26,503 in package 1.0.2.1, counted 2026-11-22; see "Descriptor-table high-dword truncation" below), so
1226**shader-visible descriptor heaps must live below 4 GB** in this address space. 1459**shader-visible descriptor heaps must live below 4 GB** in this address space.
1227 1460
1228The layer therefore owns the console VAs. It returns them from `ID3D12Resource::GetGPUVirtualAddress` and from 1461The layer therefore owns the console VAs. It returns them from `ID3D12Resource::GetGPUVirtualAddress` and from
@@ -1236,13 +1469,13 @@ The layer therefore owns the console VAs. It returns them from `ID3D12Resource::
1236| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture (1D, 2D or 3D) gets its own `VkDeviceMemory` and a null VA, as in D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures (D3D-191) and multisampled 2D placed textures (D3D-222) share that backing, answer `GetResourceAllocationInfo` and `GetResourceTiling`, and check heap/offset alignments. Reserved buffers can use heap tile mappings (section 4.2). | 1469| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture (1D, 2D or 3D) gets its own `VkDeviceMemory` and a null VA, as in D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures (D3D-191) and multisampled 2D placed textures (D3D-222) share that backing, answer `GetResourceAllocationInfo` and `GetResourceTiling`, and check heap/offset alignments. Reserved buffers can use heap tile mappings (section 4.2). |
1237| Descriptor heaps | Shader-visible CBV/SRV/UAV and sampler heaps are allocated in the low 4 GB of the arena. RTV/DSV heaps are host-side only. | 1470| Descriptor heaps | Shader-visible CBV/SRV/UAV and sampler heaps are allocated in the low 4 GB of the arena. RTV/DSV heaps are host-side only. |
1238| Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. | 1471| Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. |
1239| Upload/readback | `D3D12_HEAP_TYPE_UPLOAD`/`READBACK` resources are separate host-visible buffers outside the arena. Their console VAs are only used by copy APIs; if the game binds one as a vertex/index buffer or reads it in a shader, the layer biases the view/descriptor by `-heap_base` so the shader's addition lands on the host BDA (**Assumption**; **measured to fail for a V#**, see below). | 1472| Upload/readback | `D3D12_HEAP_TYPE_UPLOAD`/`READBACK` resources are separate host-visible buffers outside the arena. Their console VAs are only used by copy APIs; if the game binds one as a vertex/index buffer or reads it in a shader, the layer biases the view/descriptor by `-heap_base` so the shader's addition lands on the host BDA (**ASSUMPTION**; **measured to fail for a V#**, see below). |
1240 1473
1241Non-arena buffers (upload/readback) can still be addressed by the shader without putting them in the arena: pass 1474Non-arena buffers (upload/readback) can still be addressed by the shader without putting them in the arena: pass
1242`console_va = host_bda - heap_base` (mod 2^64) in root descriptors and vertex/index/indirect views, so the shader's 1475`console_va = host_bda - heap_base` (mod 2^64) in root descriptors and vertex/index/indirect views, so the shader's
1243`heap_base + console_va` equals the host BDA. For descriptors, patch the V# base field the same way when the layer 1476`heap_base + console_va` equals the host BDA. For descriptors, patch the V# base field the same way when the layer
1244copies or scans them. This relies on the game not using the raw VA for anything except shader addressing 1477copies or scans them. This relies on the game not using the raw VA for anything except shader addressing
1245(**Assumption**); if it does, the resource must move into the arena instead. 1478(**ASSUMPTION**); if it does, the resource must move into the arena instead.
1246 1479
1247**Measured (D3D-53, `d3d12_translated_draw_test`):** the bias works for 64-bit root arguments (`d3d12_compute_test`: a root 1480**Measured (D3D-53, `d3d12_translated_draw_test`):** the bias works for 64-bit root arguments (`d3d12_compute_test`: a root
1248CBV and a table slot that point at an upload buffer) but **not for a V#**. A V#'s base field is 48 bits 1481CBV and a table slot that point at an upload buffer) but **not for a V#**. A V#'s base field is 48 bits
@@ -1272,8 +1505,8 @@ Arena VAs (at most 4095 MiB, so 32-bit) pass. A VA biased from outside the arena
1272VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer 1505VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer
1273a console client can address is an arena range, whichever heap it comes from. 1506a console client can address is an arena range, whichever heap it comes from.
1274 1507
1275Why not give each buffer its own BDA and set `heap_base = 0`? Because many shaders truncate descriptor-table 1508Why not give each buffer its own BDA and set `heap_base = 0`? Because 25,865 of the 26,503 shaders (97.6%)
1276pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable. 1509truncate descriptor-table pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable.
1277 1510
1278Why one arena rather than several? Because the shader gets exactly one `heap_base` for buffer, descriptor-table and 1511Why one arena rather than several? Because the shader gets exactly one `heap_base` for buffer, descriptor-table and
1279code accesses. A draw can reference a descriptor table in one heap and a vertex buffer in another; both must 1512code accesses. A draw can reference a descriptor table in one heap and a vertex buffer in another; both must
@@ -1325,11 +1558,9 @@ and updating `heap_base` for all subsequent commands; do it at a frame boundary,
1325`VK_KHR_maintenance4`) and `maxMemoryAllocationSize` bound the arena; a large open-world buffer working set may not 1558`VK_KHR_maintenance4`) and `maxMemoryAllocationSize` bound the arena; a large open-world buffer working set may not
1326fit on smaller PC GPUs. This is a product requirement, not something the layer can hide. 1559fit on smaller PC GPUs. This is a product requirement, not something the layer can hide.
1327 1560
1328**Reserved resources.** `CreateReservedResource` plus tile mappings is a sparse resource. Vulkan sparse binding 1561**Reserved resources.** `CreateReservedResource` and the queue tile APIs use Vulkan sparse binding for buffers and
1329works on images and buffers, but the layer's arena model assumes all buffer memory is in one BDA range; a sparse 1562compatible single-mip RGBA8 2D textures (section 4.2). Other descriptions have fully allocated backing. Wider
1330buffer would need its bound memory at the console VA. For the first boot, reserve the full size as ordinary arena 1563texture coverage and the game's use of tile streaming remain open.
1331memory and log the tile calls; implement sparse binding only if the game uses it for streaming. Sparse images can
1332use their own VkDeviceMemory and are easier. **Open.**
1333 1564
1334### 3.4 Descriptor heaps and the bindless model 1565### 3.4 Descriptor heaps and the bindless model
1335 1566
@@ -1355,7 +1586,10 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all
1355 graphics stages (question 3 in the table below) is what would confirm it. Which SGPR holds which heap varies 1586 graphics stages (question 3 in the table below) is what would confirm it. Which SGPR holds which heap varies
1356 with the stage and the root signature, so placing the bases belongs to the root-signature mapping, not to a new 1587 with the stage and the root signature, so placing the bases belongs to the root-signature mapping, not to a new
1357 translator input. No stride is read at run time: static offsets of T# loads are multiples of 32 and of S# loads 1588 translator input. No stride is read at run time: static offsets of T# loads are multiples of 32 and of S# loads
1358 multiples of 16, so the stride is compiled into the code. 1589 multiples of 16, so the stride is compiled into the code. In the runtime shim, `CreateRootSignature` records the
1590 `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and `SAMPLER_HEAP_DIRECTLY_INDEXED` root-signature flags and `SetDescriptorHeaps`
1591 tracks the bound shader-visible heap GPU bases (`d3d12_set_descriptor_heaps`), while placing those bases into
1592 per-stage user SGPRs remains open on question 3.
13593. **Game-built descriptor memory.** The game writes raw T#/S# bytes into a heap itself, without calling 15933. **Game-built descriptor memory.** The game writes raw T#/S# bytes into a heap itself, without calling
1360 `CreateShaderResourceView`. The shaders then read those bytes exactly as in case 1. 1594 `CreateShaderResourceView`. The shaders then read those bytes exactly as in case 1.
1361 1595
@@ -1501,6 +1735,34 @@ Measured on the corpus (`python -I tools/user_sgpr_census.py <spirv/index.json>
1501 1735
1502Taken together this disagrees with the packing above (from s0, two dwords per table) and is consistent with a per-stage base (s8 VS/PS, s4 CS, s16 MS) and one dword per table pointer. It is a census of shader reads, not a confirmed mapping: it does not show which root parameter feeds which SGPR, and the GS behave differently. `--expect ps=8 vs=8 cs=4 ms=16` turns it into a check; `tests/test_user_sgpr_census.py` shows that the two packing models give different results. 1736Taken together this disagrees with the packing above (from s0, two dwords per table) and is consistent with a per-stage base (s8 VS/PS, s4 CS, s16 MS) and one dword per table pointer. It is a census of shader reads, not a confirmed mapping: it does not show which root parameter feeds which SGPR, and the GS behave differently. `--expect ps=8 vs=8 cs=4 ms=16` turns it into a check; `tests/test_user_sgpr_census.py` shows that the two packing models give different results.
1503 1737
1738**Console layout, measured for compute (D3D-448).** `rt::rootsig::pack_stage` lays the parameters out for one stage:
1739in root order from the stage base, each while it fits whole, a constant taking one dword per value, a root
1740CBV/SRV/UAV two (its 64-bit VA), a descriptor table **one** (the 32-bit VA of its first descriptor; the heaps live
1741below 4 GiB). A parameter that does not fit goes, with every later one, to the spill array behind `s[0:1]`
1742(section 7), which is not modelled, so such a signature is refused. How each part is known:
1743- **Compute, base s4: measured three ways.**
1744 - The console compiler's output (section 7).
1745 - The package's FidelityFX DLL, whose 29 compute containers carry their `RTS0` next to the console-compiled
1746 program (`tools/rootsig_census.py <fspx> --disasm <fspx>/disasm`, Xbox Series 1.0.2.1). Base s4 plus the
1747 signature's span in this layout equals the program's RSRC2 `USER_SGPR` count in 29 of 29: 27 signatures
1748 (table, table, four root CBVs) span 10 dwords and launch with 14 user SGPRs, 2 (table, table, one root CBV)
1749 span 4 and launch with 8. The `pack()` layout spans 12 and 6, two short of both.
1750 - The reads: `tools/root_sig_contract.py <fspx index.json> --rootsig <that shape> --model console` finds all 20
1751 translated programs compatible (tables read at s4/s5 as 32-bit pointers, each root CBV's VA copied whole as
1752 two dwords from s6). The `pack()` layout contradicts 7 of them, which read the second table at s5, the first
1753 table's high half in that layout.
1754- **Vertex/pixel/geometry s8 and mesh s16: a hypothesis.** It rests on the census above only; no signature
1755 confirms these bases, and visibility is not modelled (every parameter takes its place in every stage).
1756
1757The runtime uses the console layout for the **compute** bind point only. Graphics keeps `pack()`: every stage of a
1758pipeline reads `s0..s31` from one push-constant block at offset 0 (`tools/rdna2spirv.py`, `ShaderUserData` in
1759`runtime/src/vulkan_replay.h`), so a mesh shader (base s16) and a pixel shader (base s8) in one pipeline would need
1760the same root argument at two offsets. That needs per-stage user-data windows in the translator's push-constant
1761contract (D3D-448 follow-up). A root signature carries both layouts; one that only one of them can place is
1762created, and binding it at the other bind point invalidates the command list (`Close` returns `E_INVALIDARG`).
1763`s0..s3` of a compute dispatch are the driver's block; the layer leaves them zero (109 CS read `s1` as a constant,
176442 `s3`; their meaning is open).
1765
1504**Measured: a real signature beside the count it produced.** `tools/fspx_unpack.py` decodes `COMPUTE_PGM_RSRC2` of 1766**Measured: a real signature beside the count it produced.** `tools/fspx_unpack.py` decodes `COMPUTE_PGM_RSRC2` of
1505each of the 29 compute programs in `amd_fidelityfx_upscaler_xbox.dll`, and its `USER_SGPR` field is the count the 1767each of the 29 compute programs in `amd_fidelityfx_upscaler_xbox.dll`, and its `USER_SGPR` field is the count the
1506console launched the dispatch with. Every one of those 29 containers also carries an `RTS0`, which makes this the 1768console launched the dispatch with. Every one of those 29 containers also carries an `RTS0`, which makes this the
@@ -1542,6 +1804,33 @@ Spill policy: a signature needing more than 32 user SGPRs, or more than the 64-d
1542refused loudly (`pack` returns the offending parameter) instead of being truncated. The console spills through 1804refused loudly (`pack` returns the offending parameter) instead of being truncated. The console spills through
1543`__XB_GetRootSignatureSpillPointer`; until that layout is measured, refusing is the only correct behaviour. 1805`__XB_GetRootSignatureSpillPointer`; until that layout is measured, refusing is the only correct behaviour.
1544 1806
1807Measured (D3D-315): zero below-base spill-pointer candidates in the translated shaders.
1808`python -I tools/root_spill_census.py <spirv/index.json> --carve <dxbc/index.json> --expect-no-spill` exits 0 on
1809the 26,501 translated shaders (all but the 2 compute shaders refused for workgroup memory under wave64 emulation),
1810Xbox Series 1.0.2.1:
1811- **No root signatures in the containers.** 0 of the 26,503 carved containers have an `RTS0` part. The game
1812 builds its root signatures at run time, so the number that exceed 32 dwords is open until they are dumped from
1813 the executable.
1814- **No spill-pointer candidates.** No user-SGPR read used as an address (`ptr32_lo`, `ptr64_lo`, `ptr64_hi`) sits
1815 below the stage base (ps/vs/gs s8, cs s4, ms s16) in any stage. For compute that block holds the measured spill
1816 pointer `s[0:1]` (section 7); here `s0` and `s1` are never read as an address, only `s1` as a constant
1817 (109 CS, 551 PS, 12 VS).
1818- **Compute stays far below the budget.** The largest RSRC2 `USER_SGPR` count is 14 (31 of 2,687 shaders), so at
1819 most 10 of the 28 root dwords above s4 are used.
1820- **The highest reads are not spills.** PS reads reach s31 (8 shaders), s29 (7), s27 (1) and s25 (8); MS s29 (2)
1821 and s27 (8); VS s25 (2). Each of those top reads is a 32-bit constant after a gap, not an address.
1822
1823What this does not settle:
1824- **How many runtime-created signatures exceed the budget.** The containers carry none, so that count waits for
1825 signatures dumped from the executable.
1826- **Why a particular `pack()` refusal happens.** `pack()` counts two dwords per table from s0, which the census
1827 above disagrees with, so its 32-dword limit and the console's budget need not agree. Whether a given refusal is
1828 that model or a real spill is open until the signature and its shaders are compared.
1829- **A spill behind a pointer at or above the base.** It reads the same as a table pointer, so the census can't
1830 tell the two apart.
1831
1832The spill layout stays unimplemented: no shader in the translated set reads a candidate a spill could sit behind.
1833
1545Reconciliation: `tools/root_sig_contract.py` checks a candidate root signature against every shader's 1834Reconciliation: `tools/root_sig_contract.py` checks a candidate root signature against every shader's
1546`user_sgpr_reads` from `spirv/index.json` (const32 vs constant dwords, 64-bit VAs vs view/table pairs) and fails 1835`user_sgpr_reads` from `spirv/index.json` (const32 vs constant dwords, 64-bit VAs vs view/table pairs) and fails
1547the build on the first contradiction. Until the console mapping in §3.5 is confirmed by a PSO, this check — not 1836the build on the first contradiction. Until the console mapping in §3.5 is confirmed by a PSO, this check — not
@@ -1613,7 +1902,9 @@ Things that can invalidate this simple model, all **Open**:
1613 driver must spill the rest to memory, probably behind a pointer in the user data. The current shader contract has 1902 driver must spill the rest to memory, probably behind a pointer in the user data. The current shader contract has
1614 no representation for that. The likely answer is that this game keeps its root signatures small (bindless 1903 no representation for that. The likely answer is that this game keeps its root signatures small (bindless
1615 descriptors, a few constants), but it must be measured. If a large root signature appears, the spill layout has 1904 descriptors, a few constants), but it must be measured. If a large root signature appears, the spill layout has
1616 to be reverse-engineered from the shader's loads. 1905 to be reverse-engineered from the shader's loads. Measured on the shader side (D3D-315, spill policy above):
1906 zero below-base spill-pointer candidates in the translated shaders. The root signatures themselves, and how many
1907 exceed the budget, are still to be dumped from the executable.
1617- **Direct heap indexing.** The bound heap base and stride are not root parameters. Measured (D3D-329, section 1908- **Direct heap indexing.** The bound heap base and stride are not root parameters. Measured (D3D-329, section
1618 3.4): each heap's base reaches the shader as a 32-bit pointer in an entry SGPR, inside the user data for compute 1909 3.4): each heap's base reaches the shader as a 32-bit pointer in an entry SGPR, inside the user data for compute
1619 (and below `s32` for the graphics stages, whose user count is not measured yet), and the stride is compiled into 1910 (and below `s32` for the graphics stages, whose user count is not measured yet), and the stride is compiled into
@@ -1627,10 +1918,74 @@ Things that can invalidate this simple model, all **Open**:
1627 `CreateSampler2` encodes the same description (the five `D3D12_STATIC_BORDER_COLOR` values, two of them UINT, and 1918 `CreateSampler2` encodes the same description (the five `D3D12_STATIC_BORDER_COLOR` values, two of them UINT, and
1628 the 1.2 flags), and gets a sampler in set 0 and a key in the hash table without a heap slot. The entry outlives 1919 the 1.2 flags), and gets a sampler in set 0 and a key in the hash table without a heap slot. The entry outlives
1629 the root signature. `d3d12_descriptor_test` checks the key before and after and samples with it. 1920 the root signature. `d3d12_descriptor_test` checks the key before and after and samples with it.
1921 loads it by value works; a shader that expects a driver table needs that table's location. **Measured
1922 (SHADER-735): no sampling instruction in the corpus was found reading an S# from a fixed table** (0 of 366,628;
1923 0.66% stay undetermined under the conservative reading), so on this evidence the layer has none to emulate; the
1924 counts and their limits are under "Where the sampled S# comes from" below.
1630- **Descriptor-table high-dword truncation.** If a shader forces the high dword of a table pointer to zero, the 1925- **Descriptor-table high-dword truncation.** If a shader forces the high dword of a table pointer to zero, the
1631 table must be below 4 GB; the layer allocates all shader-visible heaps there. If a shader forces a resource VA's 1926 table must be below 4 GB; the layer allocates all shader-visible heaps there. If a shader forces a resource VA's
1632 high dword to zero, the resource must also be low; that would constrain the arena layout. The disassembly shows 1927 high dword to zero, the resource must also be low; that would constrain the arena layout. Measured on 2026-11-22
1633 which addresses are truncated; collect them per shader. 1928 over package 1.0.2.1 (`python -I tools/ptr_truncation_census.py <work>/shaders/disasm`, all 26,503 shaders, the
1929 `truncates_high` / `ptr32_lo` rule of `tools/shader_meta.py`): 25,865 shaders truncate at least one pointer
1930 (VS 2,038 of 2,236, PS 11,666 of 12,101, CS 2,684 of 2,689, GS 195 of 195, MS 9,282 of 9,282), 86,036 truncated
1931 pointers in all, at most 5 per shader. Every one is the base of a 4/8/16-dword descriptor load (`s_load_dwordx4/x8/x16`,
1932 a table pointer) from a user SGPR, and no 1–2 dword `s_load` base is truncated. No `global_*` in the corpus
1933 takes its base from SGPRs: its 10,548 `global_*` instructions (530 shaders) address through VGPR pairs, which the
1934 classifier does not follow. 25,669 shaders truncate every user-SGPR pointer they dereference, 196 only some (the
1935 195 GS, whose 64-bit s8 pointer has a high dword the classifier cannot resolve, and one CS), and the other 638
1936 dereference no user-SGPR pointer. Bases not rooted in a user SGPR (462 shader/access combinations) never have a constant-zero
1937 high dword. So what is measured to need the low 4 GB is the descriptor heaps; buffer addresses reach the shaders
1938 inside V#s (48-bit bases) or in VGPRs for `global_*`, and this count sees neither, so it does not show that
1939 buffers may sit above 4 GB.
1940
1941**Where the sampled S# comes from** (SHADER-735; counts only). `tools/sampler_source_census.py` follows the four
1942SGPRs of the sampler operand of every `image_sample*`, `image_gather4*` and `image_get_lod` back to where their
1943values are made: through constants, scalar loads, SGPRs spilled to a VGPR and read back, and joins, where it keeps
1944the sources of every path. Over the 1.0.2.1 corpus (26,503 listings, none skipped; the ones with embedded data
1945words are re-anchored as the translator does) 14,025 shaders sample, with 366,628 such instructions:
1946
1947| stage | sampling instructions | loaded through user data | literal | held in user SGPRs | other base | undetermined |
1948|---|---|---|---|---|---|---|
1949| CS | 120,816 | 63,141 | 57,674 | 0 | 0 | 1 |
1950| MS | 21,992 | 10,142 | 9,723 | 0 | 0 | 2,127 |
1951| PS | 221,157 | 115,109 | 106,048 | 0 | 0 | 0 |
1952| VS | 2,663 | 1,020 | 1,351 | 0 | 0 | 292 |
1953| all (the 195 GS do not sample) | 366,628 | 189,412 | 174,796 | 0 | 0 | 2,420 |
1954
1955- **Other base** is what a driver table would be: some dword of the S#, on some path, held in or loaded through a
1956 constant address, a system SGPR (at or above `USER_SGPR` in CS; `s32` and up in the graphics stages, and the
1957 NGG `s3` in MS and GS) or a code-relative address. It wins over every other class, the undetermined one
1958 included, and it is empty in every stage.
1959- **Loaded through user data**: an `s_load_dwordx4` or wider at an address that starts from a user SGPR, 179,602
1960 at a static offset (0x540 at most) and 9,810 at a run-time one. No constant is added to any of these pointers,
1961 so `constant table address + user index`, which is the same arithmetic as `user pointer + constant` and which
1962 the classes could not tell apart, does not occur either. All 189,412 are in shaders whose `SFI0` sets the
1963 sampler-heap bit: no shader without it loads an S# from memory. Whether one of these loads goes through a
1964 descriptor table or through the sampler heap base of section 3.4 the shader cannot say; both are a user SGPR.
1965- **Literal**: four immediates, 105,235 in shaders with the sampler-heap bit and 69,561 in shaders without it,
1966 which sample with nothing else. 28,659 of them, in 6,824 shaders, build one dword with `s_brev_b32`.
1967 `tools/shader_meta.py` does not fold that instruction, so `literal_samplers` in the index does not list those
1968 S#s yet and the layer cannot register them from it.
1969- **Undetermined** (0.66%, in 300 shaders): with every edge followed, some path brings something else into the S#
1970 registers. 2,355 read the S# back from a VGPR it was spilled to, and one path does not save it there (on the
1971 paths that do, it is a load through user data); in 64 the paths bring a literal and a load through user data;
1972 in 1 a path brings a value the dataflow does not follow. All of them go away with one kind of edge: the S# is
1973 made or saved inside a region the compiler jumps over with `s_cbranch_execz` when no lane is active, and the
1974 sample comes after the region. Without the taken edge of those branches (the region always runs, as it does
1975 whenever a lane is active) the same analysis gives all 2,420 a class: 2,419 loaded through user data, 1
1976 literal. The table keeps them apart because that second reading trusts that nothing samples on the skipping
1977 path; lane masks are not modelled.
1978
1979So, as far as the shaders can answer it, this corpus gives no evidence of a driver sampler table: no instruction
1980lands in the other-base class, and the 2,420 undetermined ones are not shown to be free of it by the conservative
1981reading, only by the one that assumes nothing samples on an exec-zero skip.
1982What the census does not show: it reads the shaders, not what the driver writes at the addresses they load from;
1983the graphics stages' user count is the translator's 32, not a measured one (question 3 in section 8.2); and it
1984cannot say which S# is a root signature's static sampler. The literals are the candidates, since a static sampler
1985is known when the shader is compiled and half of the sampling instructions build their S# from immediates, but
1986that is a hypothesis until the root signatures are matched against them. Reproduce with
1987`python -I tools/sampler_source_census.py <work>/shaders/dxbc/disasm --jobs 4 --expect-none other_base`, which
1988exits 1 if an instruction lands in that class.
1634 1989
1635**What the console's own D3D12 libraries show** (names only, read statically from a user's console system-file 1990**What the console's own D3D12 libraries show** (names only, read statically from a user's console system-file
1636dump; nothing from those files is in this repository): 1991dump; nothing from those files is in this repository):
@@ -1669,7 +2024,8 @@ rendering silently wrong.
1669fields into `spirv/index.json`: `user_sgpr_reads` (`const32`, `ptr64_lo`/`ptr64_hi`, `ptr32_lo`, `vsharp`, `tsharp`, 2024fields into `spirv/index.json`: `user_sgpr_reads` (`const32`, `ptr64_lo`/`ptr64_hi`, `ptr32_lo`, `vsharp`, `tsharp`,
1670`ssharp`), `descriptor_strides`, `uses_code_base`, `literal_samplers`, `input_signature` (ISG1 semantic name/index, 2025`ssharp`), `descriptor_strides`, `uses_code_base`, `literal_samplers`, `input_signature` (ISG1 semantic name/index,
1671register, masks, system value, component type), `fssm_sha256`, and `descriptor_access` (DXBC `SFI0` direct-indexing 2026register, masks, system value, component type), `fssm_sha256`, and `descriptor_access` (DXBC `SFI0` direct-indexing
1672bits 25/26 plus table-load and high-dword-truncation flags). 2027bits 25/26 plus table-load and high-dword-truncation flags). A missing or malformed ISG1 signature leaves the vertex shader
2028without recorded inputs. In that case the runtime accepts any input layout when filtering shader candidates.
1673 2029
1674### 3.6 Shader identity, PSOs and feature selection 2030### 3.6 Shader identity, PSOs and feature selection
1675 2031
@@ -1711,11 +2067,57 @@ Pipeline creation:
1711 shader, root signature content or state, a changed byte, a truncated blob or a pointer with size 0 give 2067 shader, root signature content or state, a changed byte, a truncated blob or a pointer with size 0 give
1712 `E_INVALIDARG`; a null pointer with a size is ignored; another adapter gives `D3D12_ERROR_ADAPTER_NOT_FOUND` and 2068 `E_INVALIDARG`; a null pointer with a size is ignored; another adapter gives `D3D12_ERROR_ADAPTER_NOT_FOUND` and
1713 another driver `D3D12_ERROR_DRIVER_VERSION_MISMATCH`. `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan 2069 another driver `D3D12_ERROR_DRIVER_VERSION_MISMATCH`. `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan
1714 cache. 2070 cache. Its arguments answer as the host's (`d3d12_pipeline_library_host_test`, 74 values from 46 calls that need no
2071 PSO, each run on the host in a process of its own, since a call it faults on leaves its runtime broken and the next
2072 one failing fast; RTX 3060, driver 610.88):
2073 - `CreatePipelineLibrary`: a foreign, truncated or corrupt blob, the other device's blob, or a null pointer with a
2074 size is `E_INVALIDARG`, and `*ppPipelineLibrary` is left as it was. One of the layer's own blobs from another
2075 format version is `D3D12_ERROR_DRIVER_VERSION_MISMATCH`, the documented code for a cache from another driver.
2076 A pointer with size 0 is an empty library; a longer blob than the header is accepted; a null output is
2077 `S_FALSE`.
2078 - The library is a device child, not a pageable object: `QueryInterface(ID3D12Pageable)` is `E_NOINTERFACE`.
2079 - `LoadComputePipeline`/`LoadGraphicsPipeline`/`LoadPipeline` with a null output are `E_INVALIDARG`, as is an
2080 unknown or empty name. `Serialize` with a buffer smaller than `GetSerializedSize()` is `E_INVALIDARG`. The
2081 serialized size and bytes are each device's own (the host's empty library is 900 bytes, the layer's 16).
2082 - Not compared: the calls the host runtime faults on (`Serialize(nullptr, n)`, `StorePipeline` with a null PSO,
2083 `Load*` with a null name or description); the layer answers `E_INVALIDARG` for each.
1715 2084
1716**Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. 2085**Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear.
1717The trace will enumerate them. 2086The trace will enumerate them.
1718 2087
2088**Implemented (D3D-29): pipeline state streams, mesh PSOs and `DispatchMesh`.**
2089- **Device:** `VK_EXT_mesh_shader` with `meshShader` is enabled where the GPU has it (`VulkanDeviceInfo::mesh_shader`).
2090 `taskShader` is not enabled, since the corpus has no amplification shaders. `D3D12_OPTIONS7` reports
2091 `MeshShaderTier` 1 only then; without the extension it reports `NOT_SUPPORTED` and mesh PSOs are `E_NOTIMPL`.
2092- **Streams:** `CreatePipelineState` parses the stream in the d3dx12.h layout: a subobject type, then its
2093 description at that description's alignment, each subobject pointer-aligned.
2094 - Every type up to `RASTERIZER2` is read.
2095 - Missing subobjects take the runtime's defaults: depth test on with `LESS`, back-face culling, no blending, sample
2096 mask `0xFFFFFFFF`, one sample.
2097 - The stream becomes the same descriptions `CreateGraphicsPipelineState` and `CreateComputePipelineState` take, so
2098 a VS stream builds the same PSO as the classic call.
2099 - `E_INVALIDARG`, as on the PC runtime: a type given twice, an unknown type, a truncated stream, MS with VS,
2100 tessellation or GS, CS with a graphics stage, or no stage at all.
2101 - `E_NOTIMPL` with a log, for what is not built yet: an AS, a depth-bounds test, separate front and back stencil
2102 masks, view instancing.
2103 - `RASTERIZER1`/`2`'s float depth bias is truncated to the integer the PSO path takes, with a log.
2104- **Mesh PSO:** the MS (`ms` index entry by FSSM hash) and PS on the mesh stage. It has no vertex input or input
2105 assembly; the input layout, topology type and strip cut are ignored, as D3D12 ignores them for mesh PSOs. Topology
2106 and strides are not dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065/07066). Creation
2107 is refused when the index's `max_vertices`/`max_primitives` or the workgroup size exceed the device's
2108 `VkPhysicalDeviceMeshShaderPropertiesEXT`.
2109- **`DispatchMesh`:** recorded as a `Draw` with `mesh` set; the thread-group counts go in `count`/`instances`/`first`.
2110 It takes the same state snapshot as `DrawInstanced`: render targets, root arguments, viewport, scissor, blend
2111 factor, stencil references. Replay issues `vkCmdDrawMeshTasksEXT`.
2112 - **Recording errors** (`Close` returns `E_INVALIDARG`): a grid above 65535 per count or 2^22 groups.
2113 - **Not recorded:** an empty grid.
2114 - **Execution error** (`ReplayResult::invalid_draw`): a mesh draw with a VS pipeline, or the reverse.
2115- **Tests:** `d3d12_mesh_test` checks the refusals and three draws pixel by pixel on an RX 9060 XT (RADV, under
2116 Wine), validation-clean.
2117 - **The three draws:** a 2×2×1 and a 1×1×2 mesh grid, plus a VS PSO from a stream.
2118 - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open
2119 question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly.
2120
1719## 4. Object model mapping 2121## 4. Object model mapping
1720 2122
1721| D3D12 / Xbox object | Vulkan / layer object | Notes | 2123| D3D12 / Xbox object | Vulkan / layer object | Notes |
@@ -1798,13 +2200,13 @@ The trace will enumerate them.
1798 and resolve bits also require the format's image-usage/sample-count query to succeed. D3D12's per-format 2200 and resolve bits also require the format's image-usage/sample-count query to succeed. D3D12's per-format
1799 rules then apply, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP): 2201 rules then apply, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP):
1800 - `MIP` wherever the image can have more than one level. 2202 - `MIP` wherever the image can have more than one level.
1801 - `SHADER_GATHER` with `SHADER_SAMPLE` (not `A8_UNORM`, whose swizzled view isn't verified for gathers). 2203 - `SHADER_GATHER` with `SHADER_SAMPLE`, including `A8_UNORM` where the 49-footprint WARP regression verified alpha selection.
1802 - `UAV_TYPED_LOAD` with every typed UAV. Typed UAV texture reads normally use the sampled binding 2204 - `UAV_TYPED_LOAD` with every typed UAV. Ordinary typed UAV texture reads use the sampled binding
1803 (`image_read_typed`); storage-only 1D arrays and loads that need storage visibility use storage-image reads. 2205 (`image_read_typed`), while coherent `glc` loads and storage-only 1D-array loads use storage-image reads.
1804 Typed buffer UAVs: the layer writes their V# (section 3.4, "Buffer UAVs"); `rdna2spirv.py` `FORMATS` 2206 Typed buffer UAVs: the layer writes their V# (section 3.4, "Buffer UAVs"); `rdna2spirv.py` `FORMATS`
1805 determines which buffer formats the translator can decode. 2207 still limits decoded buffer formats (including gaps in 8/16-bit and 10_11_11 formats).
1806 - The UAV atomic bits other than exchange for `R32_UINT` where Vulkan reports storage image atomics. 2208 - The UAV atomic bits other than exchange for `R32_UINT` where Vulkan supports storage image atomics.
1807 The translator and set 0 use the formatted `r32ui` views for 2D and 3D; `R32_SINT` gets no `r32ui` view. 2209 The translator and set 0 use the formatted `r32ui` views for 2D and 3D; `R32_SINT` has no `r32ui` view.
1808 - `MULTISAMPLE_RENDERTARGET` for depth formats, from the same usages `MULTISAMPLE_QUALITY_LEVELS` queries. 2210 - `MULTISAMPLE_RENDERTARGET` for depth formats, from the same usages `MULTISAMPLE_QUALITY_LEVELS` queries.
1809 - No integer resolve, no 1D block-compressed. Depth formats are 2D and cube only: no 3D, shader reads, UAVs, 2211 - No integer resolve, no 1D block-compressed. Depth formats are 2D and cube only: no 3D, shader reads, UAVs,
1810 buffer or vertex use, and no 1D, which native D3D12 allows but the layer's resource creation refuses. 2212 buffer or vertex use, and no 1D, which native D3D12 allows but the layer's resource creation refuses.
@@ -1845,11 +2247,15 @@ The trace will enumerate them.
1845- `GetAdapterLuid` (implemented): `VkPhysicalDeviceIDProperties::deviceLUID`, which on Windows is the DXGI 2247- `GetAdapterLuid` (implemented): `VkPhysicalDeviceIDProperties::deviceLUID`, which on Windows is the DXGI
1846 adapter's LUID; `d3d12_fence_timing_test` finds it with `IDXGIFactory4::EnumAdapterByLuid` (RTX 4090, driver 2248 adapter's LUID; `d3d12_fence_timing_test` finds it with `IDXGIFactory4::EnumAdapterByLuid` (RTX 4090, driver
1847 621.14). A driver that reports `deviceLUIDValid = VK_FALSE` gets a zero LUID, logged. 2249 621.14). A driver that reports `deviceLUIDValid = VK_FALSE` gets a zero LUID, logged.
1848- `GetCustomHeapProperties` (implemented): the D3D12 documentation's table for a NUMA adapter, matching the 2250- `GetCustomHeapProperties` (implemented): the D3D12 documentation's table for the architecture
1849 `UMA = FALSE` that `D3D12_FEATURE_ARCHITECTURE` reports: `DEFAULT` is `NOT_AVAILABLE`/`L1`, `UPLOAD` 2251 `D3D12_FEATURE_ARCHITECTURE` reports. On a discrete GPU (`UMA = FALSE`): `DEFAULT` is `NOT_AVAILABLE`/`L1`,
1850 `WRITE_COMBINE`/`L0`, `READBACK` `WRITE_BACK`/`L0`, `GPU_UPLOAD` `WRITE_COMBINE`/`L1`, all with type `CUSTOM` and 2252 `UPLOAD` `WRITE_COMBINE`/`L0`, `READBACK` `WRITE_BACK`/`L0`, `GPU_UPLOAD` `WRITE_COMBINE`/`L1`. On an integrated
1851 node masks 1. `CUSTOM`, unknown types and node masks above 1 get an all-zero answer, logged. The test compares 2253 GPU (`UMA = TRUE`, `CacheCoherentUMA = FALSE`) the same pages, all in `L0`, and a custom heap in `L1` is refused
1852 `DEFAULT`, `UPLOAD` and `READBACK` byte for byte with the host runtime's answer (RTX 4090: identical). 2254 with `E_INVALIDARG` (`CreateHeap`, `CreateCommittedResource`), as the host runtime does on
2255 a Radeon 780M (AMD 32.0.13030.13001) and on WARP. All answers have type `CUSTOM` and node masks 1. `CUSTOM`,
2256 unknown types and node masks above 1 get an all-zero answer, logged. The test compares `DEFAULT`, `UPLOAD` and
2257 `READBACK` byte for byte with the host runtime's answer when the host adapter has the layer's architecture (RTX
2258 4090: identical); `d3d12_heap_properties` compares the `L1` heaps with the layer's own adapter.
1853- Residency and power (D3D-33) are no-ops that still check their arguments (`d3d12_vulkan_device.cpp`, tested in 2259- Residency and power (D3D-33) are no-ops that still check their arguments (`d3d12_vulkan_device.cpp`, tested in
1854 `d3d12_vulkan_device_test`). Vulkan has no residency API: memory from `vkAllocateMemory` stays usable until 2260 `d3d12_vulkan_device_test`). Vulkan has no residency API: memory from `vkAllocateMemory` stays usable until
1855 `vkFreeMemory`, and paging under pressure is the kernel driver's job, so every pageable object is always resident. 2261 `vkFreeMemory`, and paging under pressure is the kernel driver's job, so every pageable object is always resident.
@@ -1888,7 +2294,8 @@ The trace will enumerate them.
1888 and its layout field is `0x101` (tiled) or `0x1` (row-major buffer). The PC proxy replaces the layout with a 2294 and its layout field is `0x101` (tiled) or `0x1` (row-major buffer). The PC proxy replaces the layout with a
1889 driver-chosen one; our layer must recognise slot 76 and `0x101` explicitly and must not pass `0x101` to the public 2295 driver-chosen one; our layer must recognise slot 76 and `0x101` explicitly and must not pass `0x101` to the public
1890 layout enum. The FidelityFX upscaler creates 10 default-heap resources through this slot, so it is not optional 2296 layout enum. The FidelityFX upscaler creates 10 default-heap resources through this slot, so it is not optional
1891 for middleware. The actual console tiled data layout and the detile path remain **Open**. 2297 for middleware. The console tiled data layout is GFX10 `SW_64KB_D` (Mesa addrlib `GFX10_SW_64K_D_RBPLUS_PATINFO`),
2298 and the detile and tile path is implemented in `resource_detile.h` and verified by `resource_detile_test` (D3D-316).
1892- `CreateCommittedResource`: allocate an aligned range in the arena for a buffer, or a separate `VkDeviceMemory` 2299- `CreateCommittedResource`: allocate an aligned range in the arena for a buffer, or a separate `VkDeviceMemory`
1893 for an image; record the initial state. Map `D3D12_HEAP_TYPE_DEFAULT` to device-local memory, `UPLOAD`/`READBACK` 2300 for an image; record the initial state. Map `D3D12_HEAP_TYPE_DEFAULT` to device-local memory, `UPLOAD`/`READBACK`
1894 to separate host-visible buffers. This remains the path for buffers and for any PC-style committed resource. 2301 to separate host-visible buffers. This remains the path for buffers and for any PC-style committed resource.
@@ -1902,7 +2309,8 @@ The trace will enumerate them.
1902 `compare_invalid_arguments` (`d3d12_vulkan_device_test`): invalid ones, their valid neighbours, and 2309 `compare_invalid_arguments` (`d3d12_vulkan_device_test`): invalid ones, their valid neighbours, and
1903 `ALLOW_RENDER_TARGET`/`ALLOW_DEPTH_STENCIL` on every format both devices create. Rules the host keeps that are easy 2310 `ALLOW_RENDER_TARGET`/`ALLOW_DEPTH_STENCIL` on every format both devices create. Rules the host keeps that are easy
1904 to get wrong: a committed resource takes no heap flag except `SHARED`, `ALLOW_DISPLAY` (textures only), 2311 to get wrong: a committed resource takes no heap flag except `SHARED`, `ALLOW_DISPLAY` (textures only),
1905 `HARDWARE_PROTECTED`, `CREATE_NOT_RESIDENT` and `CREATE_NOT_ZEROED`; a buffer refuses `ALLOW_SIMULTANEOUS_ACCESS`; 2312 `HARDWARE_PROTECTED`, `CREATE_NOT_RESIDENT`, `CREATE_NOT_ZEROED` and `ALLOW_SHADER_ATOMICS` (only with
2313 `ALLOW_UNORDERED_ACCESS`; measured on an RTX 4070 Laptop and WARP); a buffer refuses `ALLOW_SIMULTANEOUS_ACCESS`;
1906 MSAA takes quality 0 or one of the two standard patterns; a buffer may be `ALLOW_RENDER_TARGET` but not 2314 MSAA takes quality 0 or one of the two standard patterns; a buffer may be `ALLOW_RENDER_TARGET` but not
1907 `ALLOW_DEPTH_STENCIL`, and is aligned 0 or 64 KiB only; upload heaps start in any part of `GENERIC_READ` (or 2315 `ALLOW_DEPTH_STENCIL`, and is aligned 0 or 64 KiB only; upload heaps start in any part of `GENERIC_READ` (or
1908 `COMMON`), readback heaps in `COPY_DEST` or `COMMON`, neither with UAVs; a texture starts in exactly 2316 `COMMON`), readback heaps in `COPY_DEST` or `COMMON`, neither with UAVs; a texture starts in exactly
@@ -1959,7 +2367,7 @@ The trace will enumerate them.
1959 heap reads back 0. 2367 heap reads back 0.
1960 `CheckFeatureSupport` still reports `TiledResourcesTier` as not supported, so a game that checks it creates 2368 `CheckFeatureSupport` still reports `TiledResourcesTier` as not supported, so a game that checks it creates
1961 committed resources instead. Buffer mappings alone do not implement a full tiled-resources tier. 2369 committed resources instead. Buffer mappings alone do not implement a full tiled-resources tier.
1962 The Xbox tiled layout word `0x101` is accepted as `64KB_UNDEFINED_SWIZZLE` (**Assumption**: 2370 The Xbox tiled layout word `0x101` is accepted as `64KB_UNDEFINED_SWIZZLE` (**ASSUMPTION**:
1963 that the console uses it for reserved resources too). 2371 that the console uses it for reserved resources too).
1964 - `GetResourceTiling`: the standard 64 KiB tile shapes, standard and packed mips (a mip stays standard while it is 2372 - `GetResourceTiling`: the standard 64 KiB tile shapes, standard and packed mips (a mip stays standard while it is
1965 wider than half the tile or taller than the tile, depth not counting, as AMD's PC runtime does on RDNA2 and RDNA4 2373 wider than half the tile or taller than the tile, depth not counting, as AMD's PC runtime does on RDNA2 and RDNA4
@@ -2005,7 +2413,7 @@ The trace will enumerate them.
2005 is deeper than a tile it steps at each tile depth (8x8x32 R8 takes 1 tile, 8x8x33 takes 2, 8x8x256 takes 8), even 2413 is deeper than a tile it steps at each tile depth (8x8x32 R8 takes 1 tile, 8x8x33 takes 2, 8x8x256 takes 8), even
2006 where the bytes would fit in fewer (16x16x128 RGBA8: 8 tiles for 3 tiles of data). Those 32 are in the test too, 2414 where the bytes would fit in fewer (16x16x128 RGBA8: 8 tiles for 3 tiles of data). Those 32 are in the test too,
2007 79 layouts in all, identical on both GPUs. The console is RDNA2, so the layer follows this rule (D3D-65; 2415 79 layouts in all, identical on both GPUs. The console is RDNA2, so the layer follows this rule (D3D-65;
2008 **Assumption**: that the console's runtime splits like the PC's AMD driver). 2416 **ASSUMPTION**: that the console's runtime splits like the PC's AMD driver).
2009 - `UpdateTileMappings` and `CopyTileMappings` bind pages in reserved buffers to default heaps from D3D-16. 2417 - `UpdateTileMappings` and `CopyTileMappings` bind pages in reserved buffers to default heaps from D3D-16.
2010 Sequential, NULL, SKIP and single-tile reuse ranges are supported. Queue timeline waits order binding between 2418 Sequential, NULL, SKIP and single-tile reuse ranges are supported. Queue timeline waits order binding between
2011 ordinary submissions, and the previous heap allocation is retained until an in-flight unbind completes. 2419 ordinary submissions, and the previous heap allocation is retained until an in-flight unbind completes.
@@ -2013,13 +2421,23 @@ The trace will enumerate them.
2013 `d3d12_buffer_tiles_test` compares three full readbacks with native D3D12, including a fence-gated queue. 2421 `d3d12_buffer_tiles_test` compares three full readbacks with native D3D12, including a fence-gated queue.
2014 - Drivers that exclude the host-visible arena memory type from sparse buffers (including NVIDIA 621.01 on the 2422 - Drivers that exclude the host-visible arena memory type from sparse buffers (including NVIDIA 621.01 on the
2015 RTX 3090) use a dedicated device-local allocation per heap for its tiles. A heap with this dedicated backing 2423 RTX 3090) use a dedicated device-local allocation per heap for its tiles. A heap with this dedicated backing
2016 cannot mix placed buffers and sparse mappings. Sparse mapping and `CopyTiles` for reserved textures are open. 2424 cannot mix placed buffers and sparse mappings.
2425 - D3D-285 extends these mappings to single-sample `R8G8B8A8_UNORM` reserved 2D textures with one mip, one
2426 layer and no resource flags. The Vulkan image must support sparse aliases and zero reads from unmapped tiles,
2427 with 128 × 128 color blocks aligned to 64 KiB. Images requiring an opaque mip tail or separately bound metadata
2428 keep the fully allocated fallback. The image is transitioned while still unbound and kept in `GENERAL` so
2429 mapping an alias preserves contents. Image tiles use dedicated device-local heap memory and can alias tiles
2430 of compatible sparse images. Buffer and placed-resource aliases with texture tiles are outside this path.
2431 - `CopyTiles` transfers RGBA8 tiles in either direction. Partial edge blocks use the full 512-byte linear row
2432 pitch and transfer only in-bounds texels. Byte-unaligned offsets use transfer scratch.
2433 `d3d12_texture_tiles_test` compares initially unmapped tiles, column mappings, aliases, and a fence-delayed
2434 remap with native D3D12, including clipped edges and byte-unaligned offsets.
2017- `D3D12_RESOURCE_DESC::Layout`: the public `ROW_MAJOR` and `64KB_STANDARD_SWIZZLE` values plus the Xbox `0x101` 2435- `D3D12_RESOURCE_DESC::Layout`: the public `ROW_MAJOR` and `64KB_STANDARD_SWIZZLE` values plus the Xbox `0x101`
2018 tiled value from slot 76. Row-major textures need `VK_IMAGE_TILING_LINEAR` (not usable for RT/DS) or a staging 2436 tiled value from slot 76. Row-major textures need `VK_IMAGE_TILING_LINEAR` (not usable for RT/DS) or a staging
2019 copy; `64KB_STANDARD_SWIZZLE` and `0x101` have no direct Vulkan equivalent. If the game uploads console-tiled data, 2437 copy; `64KB_STANDARD_SWIZZLE` and `0x101` have no direct Vulkan equivalent. If the game uploads console-tiled data,
2020 the layer needs a detile step or a matching tiled image. **Open**; the ABI value is known, the data layout is not. 2438 the layer uses a detile step. `runtime/src/resource_detile.h` (`detile_surface_64k` / `tile_surface_64k`, `resource_detile_test`)
2021 `runtime/src/gfx10_tiling.h` provides single-level GFX10/RbPlus SW_4KB_S and SW_64KB_D tile/detile, 2439 and `runtime/src/gfx10_tiling.h` provide GFX10/RbPlus `SW_64KB_D` detiling. Which mode `0x101` uses, the mip tail and
2022 tested synthetically by `gfx10_tiling_test`. Which mode `0x101` uses, the mip tail and upload wiring remain **Open**. 2440 upload wiring remain **Open**.
2023- Formats: a `DXGI_FORMAT` → `VkFormat` table, including sRGB and typeless variants. Typeless resources get a 2441- Formats: a `DXGI_FORMAT` → `VkFormat` table, including sRGB and typeless variants. Typeless resources get a
2024 concrete image format plus `VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT` and a `VK_KHR_image_format_list` when views cast 2442 concrete image format plus `VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT` and a `VK_KHR_image_format_list` when views cast
2025 within the family; unsupported casts are logged and fall back to the resource format. `CreateCommittedResource3`'s 2443 within the family; unsupported casts are logged and fall back to the resource format. `CreateCommittedResource3`'s
@@ -2094,7 +2512,8 @@ The trace will enumerate them.
2094 the texel block size and its row length in texels (VUID-vkCmdCopyBufferToImage-dstImage-07975), while the 2512 the texel block size and its row length in texels (VUID-vkCmdCopyBufferToImage-dstImage-07975), while the
2095 capability lifts D3D12's two alignments and is not documented as keeping offsets and pitches texel multiples 2513 capability lifts D3D12's two alignments and is not documented as keeping offsets and pitches texel multiples
2096 (not tested here), so a footprint that is not texel-aligned would have to be repacked through scratch memory 2514 (not tested here), so a footprint that is not texel-aligned would have to be repacked through scratch memory
2097 the way a 96-bit one is (section 4.2). The replay already accepts any offset and pitch that are texel multiples 2515 the way a 96-bit one is (section 4.2). The replay already accepts any pitch that is a texel multiple and any
2516 offset that is one, except that a depth, stencil or 96-bit copy needs an offset that is a multiple of 4
2098 (`prepare_texture_copy` in `runtime/src/vulkan_replay.h`; anything else is `unsupported` there), so accepting 2517 (`prepare_texture_copy` in `runtime/src/vulkan_replay.h`; anything else is `unsupported` there), so accepting
2099 those needs only the record-time check changed; reporting the capability needs the repack as well. What the 2518 those needs only the record-time check changed; reporting the capability needs the repack as well. What the
2100 console's runtime reports is not measured, and no title code that depends on it has been seen. 2519 console's runtime reports is not measured, and no title code that depends on it has been seen.
@@ -2115,11 +2534,13 @@ The trace will enumerate them.
2115- `AtomicCopyBufferUINT` / `AtomicCopyBufferUINT64` (D3D-26) → one `vkCmdCopyBuffer` region of 4 or 8 bytes, after 2534- `AtomicCopyBufferUINT` / `AtomicCopyBufferUINT64` (D3D-26) → one `vkCmdCopyBuffer` region of 4 or 8 bytes, after
2116 a `ALL_COMMANDS`/`MEMORY_WRITE` → `TRANSFER`/`TRANSFER_READ|WRITE` barrier. That barrier covers every earlier 2535 a `ALL_COMMANDS`/`MEMORY_WRITE` → `TRANSFER`/`TRANSFER_READ|WRITE` barrier. That barrier covers every earlier
2117 write, those to the dependent resources among them, so the copy sees them all, as D3D12 requires. The dependent 2536 write, those to the dependent resources among them, so the copy sees them all, as D3D12 requires. The dependent
2118 ranges are checked against their buffers but add nothing a global barrier does not already cover. Recording 2537 ranges are checked against their buffers (`end == UINT64_MAX` resolves to the buffer's size) but add nothing a
2119 follows the debug layer's `ATOMICCOPYBUFFER_*` rules (IDs 1027-1040): offsets aligned to the copy size and at 2538 global barrier does not already cover. Recording matches live Windows 11 WARP and hardware D3D12 `Close`
2120 least one dependency. **Assumption:** Vulkan promises no atomicity for a transfer, and the layer relies on a 2539 validation: offsets aligned to and within the buffer for the copy size, zero dependencies allowed (with null
2121 naturally aligned 4- or 8-byte copy being a single write on the GPU. This matters only to a reader racing the 2540 arrays), buffer dependency ranges with `begin < end` and either `end == UINT64_MAX` or `end <= width`, and
2122 copy on another queue or on the host. 2541 texture dependency ranges `{0, UINT64_MAX}` on a valid subresource or `ALL_SUBRESOURCES`. **ASSUMPTION:** Vulkan
2542 promises no atomicity for a transfer, and the layer relies on a naturally aligned 4- or 8-byte copy being a
2543 single write on the GPU. This matters only to a reader racing the copy on another queue or on the host.
2123- Clears: a full-subresource clear maps to `vkCmdClearColorImage`/`vkCmdClearDepthStencilImage` (UAV buffers to 2544- Clears: a full-subresource clear maps to `vkCmdClearColorImage`/`vkCmdClearDepthStencilImage` (UAV buffers to
2124 `vkCmdFillBuffer`); a rect clear uses `vkCmdClearAttachments` inside the rendering scope. UAV image clears use 2545 `vkCmdFillBuffer`); a rect clear uses `vkCmdClearAttachments` inside the rendering scope. UAV image clears use
2125 `vkCmdClearColorImage` in `GENERAL`, and rectangles `vkCmdClearAttachments`. Buffer patterns of other sizes 2546 `vkCmdClearColorImage` in `GENERAL`, and rectangles `vkCmdClearAttachments`. Buffer patterns of other sizes
@@ -2130,8 +2551,11 @@ The trace will enumerate them.
2130 `VkClearColorValue::uint32` for both image and rectangle clears; copying float bits gives incorrect stored 2551 `VkClearColorValue::uint32` for both image and rectangle clears; copying float bits gives incorrect stored
2131 integers without a Vulkan validation error. **Measured:** Windows D3D12 on WARP and AMD RX 5700 XT clamps 2552 integers without a Vulkan validation error. **Measured:** Windows D3D12 on WARP and AMD RX 5700 XT clamps
2132 negatives/NaN to zero, positive overflow/infinity to the component maximum, and truncates fractions. 2553 negatives/NaN to zero, positive overflow/infinity to the component maximum, and truncates fractions.
2133 `d3d12_uint_clear_test` compares full and rectangular D3D12 readbacks with WARP over seven input sets on all 2554 `d3d12_clear_test` (renamed from `d3d12_uint_clear_test` in #525, D3D-45) compares full and rectangular D3D12
2134 three formats; `clear_color_test` checks both replay paths without a GPU, including unchanged float values. 2555 readbacks with WARP over eleven integer input sets on every UINT and SINT render-target format it lists, beside
2556 the UNORM/SNORM/FLOAT and depth/stencil cases. ctest runs only its `--rgb9e5` mode (`d3d12_rgb9e5_rtv`), so the
2557 WARP comparison is run by hand until #521's 0.5 tie rounding lands (`runtime/CMakeLists.txt`).
2558 `clear_color_test` checks both replay paths without a GPU, including unchanged float values.
2135 This does not add typed-view reinterpretation of typeless resources or new integer formats. 2559 This does not add typed-view reinterpretation of typeless resources or new integer formats.
2136- **RGBA8 typeless RTV clears:** explicit UNORM, SRGB, UINT, SINT and SNORM RTVs on a 2560- **RGBA8 typeless RTV clears:** explicit UNORM, SRGB, UINT, SINT and SNORM RTVs on a
2137 `R8G8B8A8_TYPELESS` 2D resource with sample count 1, selecting a mip and a contiguous array-layer range. 2561 `R8G8B8A8_TYPELESS` 2D resource with sample count 1, selecting a mip and a contiguous array-layer range.
@@ -2169,6 +2593,23 @@ The trace will enumerate them.
2169 `uint4(7, 300, 1000, 3)` or `float4(0.5, -2, 1.5, 0.25)` into R16G16B16A16_UINT/FLOAT/UNORM, R32_UINT/FLOAT, 2593 `uint4(7, 300, 1000, 3)` or `float4(0.5, -2, 1.5, 0.25)` into R16G16B16A16_UINT/FLOAT/UNORM, R32_UINT/FLOAT,
2170 R10G10B10A2_UINT/UNORM and R8G8B8A8_UINT views of the matching TYPELESS textures: 8 of 8 equal the host, with no 2594 R10G10B10A2_UINT/UNORM and R8G8B8A8_UINT views of the matching TYPELESS textures: 8 of 8 equal the host, with no
2171 validation error, before and after the clear fix. 2595 validation error, before and after the clear fix.
2596- **RTVs through a castable-format list in the other channel order:** an `R8G8B8A8` or `B8G8R8A8` texture (UNORM or
2597 SRGB, `B8G8R8X8` included) whose castable-format list names the RTV's format in the other channel order, across
2598 `B8G8R8X8` and `B8G8R8A8`, or a typed `B8G8R8A8` texture's listed SRGB format, gets an RTV in that format.
2599 `CreateRenderTargetView` checks the list as the application gave it (`lists_castable_format`), and
2600 `color_view_format` lets a castable image's clear cross between the RGBA8 and BGRA8 orders. WARP and AMD's D3D12
2601 driver (RX 9060 XT, 26.11.2) store clears and draws in the view's channel order and encoding: an `R8G8B8A8` texture
2602 cleared to (0.2, 0.4, 0.6, 0.25) through a `B8G8R8A8` RTV holds the bytes 153, 102, 51, 64. Before, the RTV was
2603 refused for an `R8G8B8A8` texture (its clear failed `Close` and its draws were dropped), and a typed `B8G8R8A8`
2604 texture's RTV kept the image's format whatever the view named, so its clears came out in BGRA order and without
2605 the sRGB encoding (its draws were right already, as they use the PSO's format). A format the list doesn't name
2606 is refused, on a typed `B8G8R8A8` or `B8G8R8X8` texture as on an `R8G8B8A8` one (the `B8G8R8A8` and
2607 `B8G8R8X8` ones kept the image's format before); a typed `B8G8R8A8` texture without a list still ignores the
2608 RTV's format, as before. `d3d12_clear_test` compares 8 such textures with WARP in full and rectangle clears
2609 within 1 (the X byte of an X8 view left out: WARP and AMD write different values there) and checks that an
2610 `R8G8B8A8`, a `B8G8R8A8` and a `B8G8R8X8` texture each take their own and their listed format and refuse 3
2611 formats their lists don't name, `d3d12_draw_test` draws through the same views, and `typeless_rtv_test` checks
2612 the replay's crossing and its refusals.
2172- **Typed RTV clears:** `ClearRenderTargetView` still takes `FLOAT[4]`. For every integer RTV format the device 2613- **Typed RTV clears:** `ClearRenderTargetView` still takes `FLOAT[4]`. For every integer RTV format the device
2173 exposes (`R8G8`, `R8G8B8A8`, `R16G16`, `R16G16B16A16`, `R32`, `R32G32` and `R32G32B32A32` in `_UINT` and `_SINT`, 2614 exposes (`R8G8`, `R8G8B8A8`, `R16G16`, `R16G16B16A16`, `R32`, `R32G32` and `R32G32B32A32` in `_UINT` and `_SINT`,
2174 plus `R10G10B10A2_UINT`; `R8`/`R16` `_UINT`/`_SINT` are handled in replay too) convert those values numerically 2615 plus `R10G10B10A2_UINT`; `R8`/`R16` `_UINT`/`_SINT` are handled in replay too) convert those values numerically
@@ -2272,37 +2713,115 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a
2272 (`CommandList` is a value; the application may `Reset` its list at once) and holds the operation. Everything the 2713 (`CommandList` is a value; the application may `Reset` its list at once) and holds the operation. Everything the
2273 queue is asked to do after it (batches, Signals, queue markers) goes behind it, so per-queue order is kept. 2714 queue is asked to do after it (batches, Signals, queue markers) goes behind it, so per-queue order is kept.
2274 The held operations are recorded and submitted, in order, on their own `VkQueue` as soon as the Signals they wait for 2715 The held operations are recorded and submitted, in order, on their own `VkQueue` as soon as the Signals they wait for
2275 have been submitted: by the thread that submits that Signal, after it has released its own queue's lock (or by the 2716 have been submitted: by the thread that submits that Signal (or makes the CPU `Signal`), after it has dropped its own
2276 thread of a CPU `Signal`). There is no worker thread and no caller ever waits for the GPU or for a Signal: the cost 2717 queue's state lock. There is no worker thread and no GPU wait is added, but the call that releases is not free: that
2277 moves to that thread and is what the held `ExecuteCommandLists` would have cost anyway. One thread releases at a time 2718 thread records the held batches (what the `ExecuteCommandLists` would have cost, including whatever `execute` does
2278 (the others leave a note and the running one makes another pass), a release that submits a Signal lets the next 2719 for the lists, such as the bindless upload's wait for the device until D3D-314 removes it) while it still holds the
2279 queue's front run in the same pass, so chains (C waits B, B waits A, in any submission order) and operations with 2720 mutex of the D3D12 queue whose `Signal` or `Wait` it is in, so other calls on that queue wait meanwhile; and
2280 several waits resolve in dependency order, and the layout tracker follows that order. A wait whose value has been 2721 `remove_fence`, queue destruction and presenter destruction wait for a release in progress. One thread releases at a
2281 reached by a submitted Signal never blocks again. The normal case (the Signal submitted first) is unchanged: no copy, 2722 time (the others leave a note and the running one makes another pass); a release that submits a Signal lets the
2282 no hold, the same `vkQueueSubmit`. Holding on the CPU also avoids a Wait and its Signal landing in the wrong order on 2723 next queue's front run in the same pass, so chains (C waits B, B waits A, in any submission order) and operations
2283 one `VkQueue`, which would not make forward progress on the GPU (Vulkan-Docs issue 1262). Edge cases: a queue 2724 with several waits resolve in dependency order, and the layout tracker follows that order. A wait whose value has
2284 destroyed with held operations reports them once (stderr: `queue destroyed with N held operation(s) never 2725 been reached by a submitted Signal never blocks again (vkd3d-proton's rule too). The normal case (the Signal
2285 submitted: waits for a fence value (V) that no Signal reached`) and goes on without waiting; a fence nobody signals 2726 submitted first) is unchanged: no copy, no hold, the same `vkQueueSubmit`. Holding on the CPU also avoids a Wait and
2286 holds back only the queues that wait for it (and those that wait for what they would have signaled), never the 2727 its Signal landing in the wrong order on one `VkQueue`, which would not make forward progress on the GPU
2287 others; a fence released while operations wait for it drops them and says so; a Signal value that is not above 2728 (Vulkan-Docs issue 1262): the test also runs with every D3D12 queue on one `VkQueue` and with two.
2288 the fence's (Vulkan timelines only increase) is still dropped with a note, as before. Failures of a held 2729 What a held operation keeps alive, as D3D12's queue does: the fences it waits on and signals, until its submission
2289 `ExecuteCommandLists` (what the call would have returned) are printed when it is released, not returned from the 2730 has completed on the GPU (a released fence stays until then, which also removes the destroy-while-pending
2290 call. Not covered: sparse `UpdateTileMappings` while a queue holds work still submits at once, and the resources a 2731 validation error the unheld path could hit); the pipeline states and root signatures of its lists (copied from the
2291 held batch names must stay alive until its fence signals (the layer does not pin them; the deferred-destruction 2732 recording before the application may `Reset` it, so releasing a PSO right after `ExecuteCommandLists` is fine).
2292 tickets only know submitted work, D3D-203). Facts from vkd3d-proton (LGPL, approach only, nothing copied): it keeps 2733 Resources are not kept: a resource released while a batch that names it is held fails that batch at release.
2293 a CPU-side virtual value and pending signals per fence and blocks the queue's submission thread until a signal that 2734 Order against other work: a held `Signal(F, v)` released after an unheld `Signal(F, w)` with `w >= v` leaves the
2294 satisfies a wait has been submitted, so Vulkan never sees a wait without a submitted signal; a satisfied wait stays 2735 Vulkan signal out (timelines only increase; waits for `v` already pass), decided under the submit lock so the
2295 satisfied. It also maps virtual fence values to physical timeline values so a D3D12 `Signal` of a lower value works; 2736 order of the checks is the order of the submissions, and the value counts as submitted only once the
2296 the layer does not yet (the value is dropped with a note). Resources are `VK_SHARING_MODE_EXCLUSIVE` and every 2737 `vkQueueSubmit` succeeded (a failed Signal releases nobody and its retry goes through); `Present` is queued behind
2297 D3D12 queue is in the graphics family, so no ownership transfer is needed; with dedicated compute/transfer families 2738 held work too (below). Fence keep-alives are released outside the queue lock, at the next `ExecuteCommandLists`,
2298 they would need `CONCURRENT` (vkd3d-proton does that, because D3D12 gives no information for transfers). 2739 `Signal`, `Wait` or marker once their submission has completed. Edge cases:
2299 Measured: `d3d12_queue_handover_test` runs 358 cases on the layer (371 on the RTX 5070 Laptop, which gives three 2740 a queue destroyed with held operations reports them once (stderr: `queue destroyed with N held operation(s) never
2300 queues per type) and 369 on the host runtime: three-stage chains (produce, relay, consume) over all 27 queue type 2741 submitted: waits for a fence value (V) that no Signal reached`) and goes on without waiting, and the CPU waits on
2301 assignments and all 6 submission orders (consumer first among them), two producers (texture from one queue, buffer 2742 the fences of its held Signals are completed, as a released fence completes them; queues that wait for those fences
2302 from another) with one consumer, a chain released by a CPU `Signal`, a CPU `Signal` before and after the `Wait`, 2743 stay held and are reported when they go; a fence nobody signals holds back only the queues that wait for it (and
2303 a never-signaled fence and a fence released while a batch waits; results compared byte for byte, sync validation 2744 for what they would have signaled), never the others; a Signal value that is not above the fence's is still
2304 clean. With holding disabled the same test fails 236 cases on the layer and validation reports 2745 dropped with a note at call time, as before (vkd3d-proton instead maps virtual fence values to physical timeline
2305 `VUID-vkCmdDraw-None-09600`. 2746 values; the layer does not yet). A held `ExecuteCommandLists` that fails when it is released does not return its
2747 result to a call that has returned: it is printed, `last_execute_result` and `VulkanQueue::take_held_failure`
2748 report it, the `Signal` behind it still signals (the work did not run; nothing waits forever, as for a failure that is
2749 not held), and its waits stay for the queue's next submission, as after a failed `vkQueueSubmit`. A queue does not
2750 hold `UpdateTileMappings` / `CopyTileMappings`: they still submit at once, before earlier held work, and take the
2751 queue's pending waits (documented limit). `VulkanQueue::idle` waits for submitted work only.
2752 `Present` (`VulkanPresenter`): when any queue holds work, a presented back buffer would be blitted as it was before
2753 that work, so the Present is queued instead (`QueueHolds::after_held`), returns success as a held
2754 `ExecuteCommandLists` does, and is submitted, in order with the presents queued before it, by the thread that
2755 releases the last operation held when it was called. It is not blocked on the calling thread because the Signal that
2756 releases the work may be one that thread makes after `Present` returns. Held work that is never released holds back
2757 the presents after it (device-wide, since the layer cannot tell which batch draws into which back buffer). A
2758 blank present reads nothing and is only ordered behind earlier queued presents. At most 8 presents queue up; the
2759 next one waits for held work to release (logged once; `set_abort` ends the wait), as a full frame-latency queue
2760 does. A queued present reports `last_present_tore()` false, which the Xbox PresentX path turns into the default
2761 vblank sync for the frame pacer. The presenter's state is guarded by one mutex (the counters are atomics, so
2762 reading them never waits for a present blocked on a swapchain image); `set_abort` has its own.
2763 Facts from vkd3d-proton (LGPL, approach only, nothing copied): it keeps a CPU-side virtual value and pending signals
2764 per fence and blocks the queue's submission thread until a signal that satisfies a wait has been submitted, so Vulkan
2765 never sees a wait without a submitted signal. Resources are `VK_SHARING_MODE_EXCLUSIVE` and every D3D12 queue is in
2766 the graphics family, so no ownership transfer is needed; with dedicated compute/transfer families they would need
2767 `CONCURRENT` (vkd3d-proton does that, because D3D12 gives no information for transfers).
2768 Every mode of the handover test ends with the same cases on the host runtime (the expected data is the CPU's
2769 pattern in all of them, so that run shows the cases are valid D3D12 and holds the layer's modes to one bar).
2770 The pipeline-state and root-signature pins are covered end to end by `d3d12_m4_compute_test`: the compute list is
2771 executed while held, its two PSOs and root signature are released and the list is Reset, the copy that releases
2772 it is submitted, and the output is compared with the CPU (it reads zeros without the pins).
2773 Measured: `d3d12_queue_handover_test` (three modes: the standalone device with a `VkQueue` per D3D12 queue, then the
2774 host runtime; `--two-queues`, a caller-owned device with two `VkQueue`s handed over; `--shared-queue`, one) runs
2775 592 cases on the layer on the Radeon 880M and the RTX 5070 (also with one shared `VkQueue`; 8 with two handed over) and 587 on the host runtime: pairs and three-stage chains (produce, relay, consume)
2776 over the queue type assignments that fit and all 6 submission orders (consumer first among them), two producers
2777 (texture from one queue, buffer from another) with one consumer, a chain released by a CPU `Signal`, a CPU
2778 `Signal` before and after the `Wait`, a never-signaled fence, a fence released while a batch waits, a held Signal
2779 of a fence the application released, a held Signal below an unheld one on a shared fence, teardown with a held
2780 Signal under a CPU wait, and 200 rounds with two threads signalling and releasing at once; results compared byte
2781 for byte, sync validation clean. With holding disabled the test fails 236 cases and validation reports
2782 `VUID-vkCmdDraw-None-09600`; with the monotonic check disabled it reports
2783 `VUID-VkSubmitInfo-pSignalSemaphores-03242`; `vk_presenter_sync_test` and `d3d12_m4_compute_test` (which
2784 submits the compute list first and releases its PSOs and root signature before the copy that feeds it) fail
2785 without the Present ordering and the pins.
2786- **More D3D12 queues than Vulkan queues** (`pick_queue_slot` in `src/queue_families.h`, `CreateCommandQueue`;
2787 test `d3d12_queue_share_test`). A GPU can expose fewer `VkQueue`s than a title creates D3D12 queues: the Intel
2788 UHD 770 on Windows and lavapipe have one family with `queueCount` 1, so the second D3D12 queue of any type was
2789 refused with `E_OUTOFMEMORY` ("no independent Vulkan queue available") and a title with a DIRECT and a COMPUTE
2790 queue stopped at boot (PingasMech, #4863). A new D3D12 queue takes an unused `VkQueue` of its own type's family,
2791 then of the graphics family, as before (D3D-97: one `VkQueue` per live D3D12 queue while there are enough, so
2792 nothing changes on a GPU with enough queues; an RTX 5080 gives 16 graphics, 8 compute and 2 transfer queues); when
2793 every one is in use it shares the one with the fewest D3D12 queues (its own family's first on a tie) and logs that
2794 once per type. D3D12 queues on one `VkQueue` stay separate objects: each keeps its own batches in order, its own
2795 progress timeline and its own held operations; the `VkQueue` runs their batches one after the other, in the order
2796 they reach it, so they lose concurrency, not correctness (as on one family, below). What would break is a GPU
2797 wait that no submitted signal satisfies landing on the shared `VkQueue` ahead of the signal it waits for, which
2798 never makes progress. The holding above already rules that out: a batch reaches `vkQueueSubmit` only once every
2799 fence value it waits for has a *submitted* Signal (earlier on the same `VkQueue`, or on another one) or has been
2800 set by the CPU. One case let the CPU half slip: a CPU `Signal` that has to wait behind a queue Signal the GPU has
2801 not reached yet (`VUID-VkSemaphoreSignalInfo-value-03259`, applied later by the fence wait thread) never told the
2802 held queues, so a queue waiting for that value was held for ever, on separate `VkQueue`s too. The wait thread now
2803 reports the value once it has set it, and releases what it satisfies; reporting it earlier, when the CPU called
2804 `Signal`, would send the waiting batch ahead of the queue Signal it depends on, which on a shared `VkQueue` never
2805 completes. `vkQueueSubmit`, `vkQueueBindSparse`, `vkQueuePresentKHR`, `vkQueueWaitIdle` and the queue labels
2806 need the `VkQueue` externally synchronised; every call the layer makes holds the device's one submit lock
2807 (`VulkanContext::submit_mutex`), which covers shared `VkQueue`s as it covers the staging queue the first DIRECT
2808 queue already shares. A per-`VkQueue` lock (#3841) must key on the `VkQueue` handle, not the D3D12 queue. Costs on
2809 a shared `VkQueue`: `GetClockCalibration` without calibrated timestamps and the destruction of a D3D12 queue wait
2810 for the other D3D12 queues' submitted work too, and queue debug labels (`BeginEvent`/`EndEvent`) of the D3D12
2811 queues interleave on it. Two test settings make the standalone device look like such a GPU, so the sharing path
2812 runs anywhere: `LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N` (at most N `VkQueue`s per family) and
2813 `LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1` (COMPUTE and COPY in the graphics family); both together are one family with
2814 one queue (`docs/testing.md`, "Choosing the GPU"). Only the test executables apply them: the game's device
2815 (`d3d12_xs`, `LEONIDA_D3D12=vulkan`) ignores them and says so, so a variable left in the environment cannot put
2816 every queue of the game on one `VkQueue` (`run_tiny_frame_queue_test_settings`). Measured on an RTX 5080 (Linux, driver 580.65.06, Wine 11)
2817 and on lavapipe, under the validation layer with synchronization validation: `d3d12_queue_share_test` passes
2818 with no setting, with one queue per family, with one queue in all and on lavapipe (36 queues, a buffer copied
2819 exactly through all of them consumer first and producer first, 9 deferred CPU Signal cases, 4 threads on 9 queues:
2820 2,000 iterations with all 9 on one `VkQueue` of the RTX 5080, 80,000 on lavapipe; a fence released right after
2821 the GPU passed the queue Signal its deferred CPU Signal waited behind, 900 times per mode, the held batch running
2822 every time), 0 validation messages; on main
2823 it fails at the 27th queue on the RTX 5080 and at the 2nd on lavapipe, and the first deferred case hangs. The layer
2824 half of `d3d12_queue_handover_test` runs its 371 cases exact in all four (on lavapipe main ran 0: one queue).
2306- `SetEventOnCompletion(value, hEvent)`: a small wait thread calls `vkWaitSemaphores` and `SetEvent`. Reuse one 2825- `SetEventOnCompletion(value, hEvent)`: a small wait thread calls `vkWaitSemaphores` and `SetEvent`. Reuse one
2307 thread with a condition variable; do not create a thread per fence. 2826 thread with a condition variable; do not create a thread per fence.
2308- `GetCompletedValue` is `vkGetSemaphoreCounterValue`; CPU `Signal` is `vkSignalSemaphore`. 2827- `GetCompletedValue` is `vkGetSemaphoreCounterValue`; CPU `Signal` is `vkSignalSemaphore`.
@@ -2401,8 +2920,16 @@ SDL2 `src/render/direct3d12/SDL_render_d3d12_xbox.cpp` (zlib).
2401 entries carry a `PlaneIndex`; display entries carry `PercentScanned`. 2920 entries carry a `PlaneIndex`; display entries carry `PercentScanned`.
240211. Xbox titles do not handle `DXGI_ERROR_DEVICE_REMOVED`/`RESET`. 292111. Xbox titles do not handle `DXGI_ERROR_DEVICE_REMOVED`/`RESET`.
2403 2922
2404*Not measured:* vtable slots of all `*X` methods, exact `D3D12XBOX_*` struct layouts and sizes, enum values, and 2923*Public corroboration (not measured here).* XCL, a GPL-2.0-only compatibility layer that runs retail Xbox Series
2405whether the token is exactly 64 bits in the ABI. The samples give argument counts and field names only. 2924titles, records `PresentX` at queue slot 30 for the older runtime layout (XDefiant, Minecraft, Fortnite) and 32 for
2925a newer one (Unicorn Overlord), and the four frame calls at device slots 78-81: `SetFrameIntervalX`,
2926`ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` (0-based, `QueryInterface` = 0). The Apache-2.0
2927ebiten Xbox binding has the same device order, declares `D3D12XBOX_PRESENT_PLANE_PARAMETERS` as a 0x48-byte x64
2928struct and `D3D12XBOX_PRESENT_PARAMETERS` as 0x20 bytes, and stores the token in 64 bits. So the plane and
2929present-parameter layouts and the token width in `runtime/shims/xbox_present.h` are no longer guesses; the enum
2930values and the `SuspendX`/`ResumeX` slots still are. XCL returns `S_FALSE` from a timed-out `WaitFrameEventX`
2931where this layer returns `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`. The full comparison is in
2932[d3d12_xs_surface.md §7.1](d3d12_xs_surface.md#71-public-sources-for-the-presentation-and-device-abi).
2406 2933
2407*Hypothesis (the game is not observed):* a GDKX title follows this pattern, so the DXGI swapchain shim (D3D-2) 2934*Hypothesis (the game is not observed):* a GDKX title follows this pattern, so the DXGI swapchain shim (D3D-2)
2408is probably **not** on its boot path. What is on it: `D3D12XboxCreateDevice`, `IDXGIDevice1`/`IDXGIAdapter`/ 2935is probably **not** on its boot path. What is on it: `D3D12XboxCreateDevice`, `IDXGIDevice1`/`IDXGIAdapter`/
@@ -2429,16 +2956,19 @@ Layer plan:
2429 2956
2430**What is implemented (the presentation core).** Everything in the plan above that does not need a slot exists as 2957**What is implemented (the presentation core).** Everything in the plan above that does not need a slot exists as
2431methods of `rt::d3d12::XboxPresentation` (`runtime/shims/xbox_present.h`), on top of the presenter of section 3.2 and 2958methods of `rt::d3d12::XboxPresentation` (`runtime/shims/xbox_present.h`), on top of the presenter of section 3.2 and
2432`leonida::FramePacer` (`runtime/src/frame_pacer.h`, no Vulkan, no Windows headers). The struct layouts, constant 2959`leonida::FramePacer` (`runtime/src/frame_pacer.h`, no Vulkan, no Windows headers). The plane and present-parameter
2433values, HRESULTs and the 64-bit token are **our own provisional definitions**: the samples give call shapes and field 2960layouts and the 64-bit token are confirmed on x64 by the public code cited above; the constant values and HRESULTs
2434names only, so the real slots, layouts and enum values are still unmeasured and the class is the surface the proxy 2961are **our own provisional definitions**, because the samples give call shapes and field names only and the enum
2435will forward to. The queue-side calls ignore which queue they came on (one `VkQueue` behind all of them). 2962values are still unmeasured. The class is the surface the proxy will forward to. The queue-side calls ignore which
2963queue they came on (one `VkQueue` behind all of them).
2436 2964
2437- *Frame pacing* (`FramePacer`, time from an injectable clock; real time is a steady timer, a host vblank source 2965- *Frame pacing* (`FramePacer`, time from an injectable clock; real time is a steady timer, a host vblank source
2438 can replace it). `SetFrameIntervalX` takes the interval as a period in microseconds and the latency, and starts 2966 can replace it). `SetFrameIntervalX` takes the interval as a period in microseconds and the latency, and starts
2439 the vblank grid. `ScheduleFrameEventX` arms the origin event, delayed by an offset inside the frame. 2967 the vblank grid. `ScheduleFrameEventX` arms the origin event, delayed by an offset inside the frame.
2440 `WaitFrameEventX` returns at the next origin with the next token (1, 2, 3, ...; 0 is the null token) and does not 2968 `WaitFrameEventX` returns at the next origin with the next token (1, 2, 3, ...; 0 is the null token) and does not
2441 return while `latency` presented frames are still waiting for their vblank. A wait that comes late returns at once 2969 return while `latency` presented frames are still waiting for their vblank. A frame presented before the origin event
2970 is armed is not paced (`PresentX` does not hold it for a vblank), so it is shown at once and never waits for a vblank:
2971 blank presents of a loading screen do not delay the first wait. A wait that comes late returns at once
2442 with the newest passed origin; the missed ones are skipped. A finite timeout gives 2972 with the newest passed origin; the missed ones are skipped. A finite timeout gives
2443 `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`; nothing registered, or suspended, gives `HRESULT_FROM_WIN32(ERROR_INVALID_STATE)`. 2973 `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`; nothing registered, or suspended, gives `HRESULT_FROM_WIN32(ERROR_INVALID_STATE)`.
2444 `GetFrameStatisticsX` keeps the last 64 frames and reports the event, present and display times (not render; 2974 `GetFrameStatisticsX` keeps the last 64 frames and reports the event, present and display times (not render;
@@ -2476,8 +3006,12 @@ will forward to. The queue-side calls ignore which queue they came on (one `VkQu
2476 (`composed_presents()` does not move; the test compares the bytes of a blit with the compose pass at 1:1 and they are 3006 (`composed_presents()` does not move; the test compares the bytes of a blit with the compose pass at 1:1 and they are
2477 equal). Anything else goes through `VulkanPresenter::present_planes`: a compute pass (`runtime/src/present_compose.comp`, 3007 equal). Anything else goes through `VulkanPresenter::present_planes`: a compute pass (`runtime/src/present_compose.comp`,
2478 SPIR-V embedded as `depth24_convert` is, built with `glslc --target-env=vulkan1.1 -O -mfmt=c`) writes an RGBA16F image of 3008 SPIR-V embedded as `depth24_convert` is, built with `glslc --target-env=vulkan1.1 -O -mfmt=c`) writes an RGBA16F image of
2479 the swapchain's size, and a `vkCmdBlitImage` (same size, nearest) puts it in the swapchain image, which keeps the 3009 the swapchain's size, and a `vkCmdBlitImage` (same size, nearest) puts it in the swapchain image, so the layer writes
2480 swapchain `TRANSFER_DST`-only and the capture path unchanged. The planes are read with `texelFetch` (no sampler, so any 3010 the swapchain only by transfer (no storage usage) and the capture path is unchanged. The swapchain also asks for
3011 `COLOR_ATTACHMENT`, which the layer never uses: overlays that hook the swapchain (Bandicam's
3012 `VK_LAYER_bandicam_helper`, measured) draw into its images through a framebuffer, and without it every frame raised
3013 `VUID-VkFramebufferCreateInfo-pAttachments-00877` and `VUID-VkImageViewCreateInfo-image-04441`. Surfaces always
3014 report it, and the DXGI swapchain (`dxgi_swapchain.h`) already requested it. The planes are read with `texelFetch` (no sampler, so any
2481 sampled float/UNORM/sRGB format works and filtering never reads outside the source rectangle); an sRGB-format source is 3015 sampled float/UNORM/sRGB format works and filtering never reads outside the source rectangle); an sRGB-format source is
2482 decoded by the texture unit and encoded again, so its bytes are read as stored. Plane 0: `pSrcViewRects[0]` (else the 3016 decoded by the texture unit and encoded again, so its bytes are read as stored. Plane 0: `pSrcViewRects[0]` (else the
2483 whole texture) scaled to `pDestPlacementBase` (fractions of the output; null is the whole output; outside it is black), 3017 whole texture) scaled to `pDestPlacementBase` (fractions of the output; null is the whole output; outside it is black),
@@ -2640,9 +3174,10 @@ will forward to. The queue-side calls ignore which queue they came on (one `VkQu
2640 second (GameDVR) output, resolving multisampled planes, a mutable-format swapchain (an sRGB/UNORM 3174 second (GameDVR) output, resolving multisampled planes, a mutable-format swapchain (an sRGB/UNORM
2641 alternation recreates the swapchain; `VK_KHR_swapchain_mutable_format` is not enabled on the device), a host-vblank clock (the timer drifts from the 3175 alternation recreates the swapchain; `VK_KHR_swapchain_mutable_format` is not enabled on the device), a host-vblank clock (the timer drifts from the
2642 display; with FIFO presents the swapchain holds the queue to the real refresh anyway), render statistics, 3176 display; with FIFO presents the swapchain holds the queue to the real refresh anyway), render statistics,
2643 `PercentScanned` of frames shown at a vblank (a scan position is never measured), and the vtable wiring. Slots to measure (all unknown): the device's `SetFrameIntervalX`, 3177 `PercentScanned` of frames shown at a vblank (a scan position is never measured), and the vtable wiring. The
2644 `ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` and the queue's `PresentX`, `SuspendX`, `ResumeX` 3178 public slots are the device's `SetFrameIntervalX`/`ScheduleFrameEventX`/`WaitFrameEventX`/`GetFrameStatisticsX`
2645 (the list is in the header). 3179 at 78-81 and `PresentX` at queue 30 (older runtime layout) or 32 (newer); `SuspendX`/`ResumeX` have no public
3180 slot. Nothing here is wired to those slots yet, and the game's own runtime is not observed.
2646- *Tests*: `frame_pacer_test` (fake clock: interval, offset, late waits, timeouts, latency blocking, tokens, 3181- *Tests*: `frame_pacer_test` (fake clock: interval, offset, late waits, timeouts, latency blocking, tokens,
2647 statistics, suspend/resume, a real 10 ms timer; no GPU) and `xbox_present_test` (the Vulkan device, reading the 3182 statistics, suspend/resume, a real 10 ms timer; no GPU) and `xbox_present_test` (the Vulkan device, reading the
2648 swapchain image back: blank, solid, two colours, source rectangles, RGBA/BGRA/sRGB sources, 2 planes, plane composition 3183 swapchain image back: blank, solid, two colours, source rectangles, RGBA/BGRA/sRGB sources, 2 planes, plane composition
@@ -2711,7 +3246,9 @@ Implemented (`QueryHeap` in `runtime/shims/d3d12_vulkan_device.cpp`, the query c
2711 one scratch chunk, alternating binary and ordinary resolves under a predicate, gated submissions, crossing 3246 one scratch chunk, alternating binary and ordinary resolves under a predicate, gated submissions, crossing
2712 statistics queries against three unsplit references word by word, and an ordinary query around a binary one, on 3247 statistics queries against three unsplit references word by word, and an ordinary query around a binary one, on
2713 a GPU; `replay_query_predication` pins the segment layouts, the helper dispatches inside an overlap and the 3248 a GPU; `replay_query_predication` pins the segment layouts, the helper dispatches inside an overlap and the
2714 binary sum-and-normalize without a GPU. 3249 binary sum-and-normalize without a GPU. On a device without `pipelineStatisticsQuery` (MoltenVK) the test
3250 leaves the statistics lists out; `vk_overlapping_occlusion_no_statistics` runs it that way (`--no-statistics`)
3251 on a device that has the feature, so that path is also run where no such device is at hand.
2715- **Helper dispatches during a pipeline-statistics query** (D3D-162). The helper dispatches above (binary 3252- **Helper dispatches during a pipeline-statistics query** (D3D-162). The helper dispatches above (binary
2716 normalisation, occlusion sums), statistics sums, `SetPredication` captures, predicated buffer copies and D24/RGB96 footprint 3253 normalisation, occlusion sums), statistics sums, `SetPredication` captures, predicated buffer copies and D24/RGB96 footprint
2717 conversions would count in the application's `CSInvocations` if they ran inside its query. Such a query is split. 3254 conversions would count in the application's `CSInvocations` if they ran inside its query. Such a query is split.
@@ -2727,6 +3264,25 @@ Implemented (`QueryHeap` in `runtime/shims/d3d12_vulkan_device.cpp`, the query c
2727 results still match and all 11 statistics counters are zero. Without a statistics pool (single-list `replay()` or 3264 results still match and all 11 statistics counters are zero. Without a statistics pool (single-list `replay()` or
2728 a queue without the summation helper), these three commands are refused before helper scratch allocation or 3265 a queue without the summation helper), these three commands are refused before helper scratch allocation or
2729 recording. The resolve fallback is unchanged: only resolves needing dispatches are refused there. 3266 recording. The resolve fallback is unchanged: only resolves needing dispatches are refused there.
3267- **Mesh draws during a pipeline-statistics query** (D3D-291). D3D12 allows `DispatchMesh` inside a statistics query
3268 and reads its input-assembly, vertex, geometry and tessellation fields as 0. Vulkan forbids `vkCmdDrawMeshTasksEXT`
3269 while a query with those counters is active (`VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076`), and the heap's
3270 pool has all eleven. So a statistics query that holds a mesh draw is split as above, and a split before a draw stays
3271 outside its rendering scope. A segment's first draw decides its pool: the submission's full pool, or a second pool
3272 with only clipping invocations and primitives, fragment and compute invocations. A later draw of the other kind ends
3273 the segment and begins one of its own kind; dispatches and segments without draws use the full pool, and
3274 `ExecuteIndirect` draws count as vertex draws. The sum copies a mesh segment's four counters into fields 5 to 8 of
3275 its record, and `statistics_sum.comp` adds them as `CInvocations`, `CPrimitives`, `PSInvocations` and
3276 `CSInvocations`, so the other fields get nothing from it. A query that holds only mesh draws is one mesh segment,
3277 resolved through the same sum. Without the compute helper there is no segment pool and such a list is refused
3278 (`unsupported`) rather than run unsplit; so is one on the single-list `replay()` (D3D-399), whose
3279 `create_segment_pool` gives no mesh pool. Overlapping statistics queries (D3D-252) split the same way inside their
3280 shared segments: a draw of the other kind than the open segment's opens a new one, so every query that segment
3281 belongs to sums both kinds. `replay_query_predication_test` (cases 15 and 16) checks the split points, the segment
3282 kinds and the resolve plan on the CPU. `d3d12_mesh_test` resolves a query around a vertex, two mesh and a vertex
3283 draw, one around a mesh draw and one around the two vertex draws: the vertex fields count only the two triangles,
3284 and the mixed query has more clipping and pixel-shader invocations than the vertex-only one. On the RX 9060 XT
3285 (RADV), the clipping counts add up exactly (2 + 10 = 12).
2730- **Timestamps.** `GetTimestampFrequency` is `1e9 / timestampPeriod` (1 GHz on the test GPU). Every D3D12 queue 3286- **Timestamps.** `GetTimestampFrequency` is `1e9 / timestampPeriod` (1 GHz on the test GPU). Every D3D12 queue
2731 shares one `VkQueue` for now (question 12), so they share one frequency. 3287 shares one `VkQueue` for now (question 12), so they share one frequency.
2732- **Timestamp resolves on MoltenVK.** On Apple GPUs, MoltenVK delays every `vkCmdWriteTimestamp` to the end of 3288- **Timestamp resolves on MoltenVK.** On Apple GPUs, MoltenVK delays every `vkCmdWriteTimestamp` to the end of
@@ -2876,8 +3432,6 @@ own names use the `XDXR` prefix for Xbox's raytracing path:
2876**The builder's own shaders are console FSSM, not Xbox DXIL.** Each of the 52 containers carries an LLVM 3432**The builder's own shaders are console FSSM, not Xbox DXIL.** Each of the 52 containers carries an LLVM
2877bitcode blob and an `XDAT`/`XBCH` record; the PC experiment below compiled the bitcode, but the console runtime 3433bitcode blob and an `XDAT`/`XBCH` record; the PC experiment below compiled the bitcode, but the console runtime
2878executes the `XBCH` record. Measured from that record: 52/52 unpack to `FSSM`, 51 translate and all 51 pass 3434executes the `XBCH` record. Measured from that record: 52/52 unpack to `FSSM`, 51 translate and all 51 pass
2879`spirv-val` with the same translator the game's 26,503 shaders use; the one left, `Box16Rehydration`, needs
2880`buffer_store_short` ([embedded_shaders.md](embedded_shaders.md)). The
2881`spirv-val` with the same translator the game's 26,503 shaders use; the one left (`Box16Rehydration`) needs 3435`spirv-val` with the same translator the game's 26,503 shaders use; the one left (`Box16Rehydration`) needs
2882`buffer_store_short` (#1864) ([embedded_shaders.md](embedded_shaders.md)). The 3436`buffer_store_short` (#1864) ([embedded_shaders.md](embedded_shaders.md)). The
2883raw 64-bit addresses are the corpus's existing raw-address path, not a separate lowering. Open: whether the game 3437raw 64-bit addresses are the corpus's existing raw-address path, not a separate lowering. Open: whether the game
@@ -2890,7 +3444,6 @@ Vulkan AS would be invisible to them. Two paths:
28901. If `XboxBvhBuilder` does the build with its own compute dispatches (the likely case, given it ships as a DLL 34441. If `XboxBvhBuilder` does the build with its own compute dispatches (the likely case, given it ships as a DLL
2891 with a device and command lists), the layer must translate and run its compute shaders. The console programs 3445 with a device and command lists), the layer must translate and run its compute shaders. The console programs
2892 are `FSSM` and 51 of the 52 already pass `spirv-val`; only `Box16Rehydration` still needs `buffer_store_short` (#1864). Buffers, 3446 are `FSSM` and 51 of the 52 already pass `spirv-val`; only `Box16Rehydration` still needs `buffer_store_short` (#1864). Buffers,
2893 are `FSSM` and 51 of the 52 already pass `spirv-val`; the one left still needs `buffer_store_short`. Buffers,
2894 UAVs, descriptors, barriers and indirect dispatch are necessary but not sufficient. The standard 3447 UAVs, descriptors, barriers and indirect dispatch are necessary but not sufficient. The standard
2895 `BuildRaytracingAccelerationStructure` calls may never reach our command list. 3448 `BuildRaytracingAccelerationStructure` calls may never reach our command list.
28962. If the game calls `ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure`, the layer must implement 34492. If the game calls `ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure`, the layer must implement
@@ -2903,6 +3456,16 @@ Vulkan AS would be invisible to them. Two paths:
2903 buffers then keep their console VAs, the addresses the records name each other by. `LEONIDA_RT_AS=khr` keeps 3456 buffers then keep their console VAs, the addresses the records name each other by. `LEONIDA_RT_AS=khr` keeps
2904 #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. Updates refit 3457 #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. Updates refit
2905 the source structure instead of rebuilding it, `CopyRaytracingAccelerationStructure` clones and compacts, and the 3458 the source structure instead of rebuilding it, `CopyRaytracingAccelerationStructure` clones and compacts, and the
3459 postbuild compacted and current sizes are written ([bvh.md](bvh.md) §7a). A bottom-level build with
3460 `MINIMIZE_MEMORY` gets BOX16 nodes (half boxes, about a fifth smaller; top-level builds stay BOX32), and one
3461 without `ALLOW_UPDATE` pairs sibling triangles that share an edge into TRI0/TRI1 leaves. Serialization and the Xbox
3462 #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. A top-level
3463 build with `D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS` is supported there: the console VAs in the pointer list are
3464 translated to Vulkan device addresses in a staged copy, without changing the guest's input. The list must be in
3465 CPU-writable memory (an UPLOAD or write-back CUSTOM heap; WRITE_COMBINE CUSTOM is CPU-writable too); GPU-written
3466 DEFAULT and READBACK lists are refused as `unsupported` before submission, since their mapped bytes can still hold
3467 an earlier frame's pointers when the CPU prepares the build. Completed staging buffers
3468 are reused, so a per-frame rebuild does not allocate memory each frame. Updates refit the source structure instead of rebuilding it, `CopyRaytracingAccelerationStructure` clones and compacts, and the
2906 postbuild compacted and current sizes are written ([bvh.md](bvh.md) §7a). Serialization and the Xbox 3469 postbuild compacted and current sizes are written ([bvh.md](bvh.md) §7a). Serialization and the Xbox
2907 batched/streaming builds are not implemented. The 3470 batched/streaming builds are not implemented. The
2908 reported `RaytracingTier` is unchanged (`NOT_SUPPORTED`). Checked by `runtime/test/d3d12_xdxr_rt_test.cpp` through 3471 reported `RaytracingTier` is unchanged (`NOT_SUPPORTED`). Checked by `runtime/test/d3d12_xdxr_rt_test.cpp` through
@@ -2920,6 +3483,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce
2920| Binning | The GDK topic index names Xbox binning modes (NDA content) | Should be a no-op if the game uses it only as an optimisation: it changes how a render pass uses on-chip memory, not the result. Log and ignore for the first boot; revisit for performance. **Open** whether the game relies on binning for correctness. | 3483| Binning | The GDK topic index names Xbox binning modes (NDA content) | Should be a no-op if the game uses it only as an optimisation: it changes how a render pass uses on-chip memory, not the result. Log and ignore for the first boot; revisit for performance. **Open** whether the game relies on binning for correctness. |
2921| DCC / texture compatibility | Public release note for `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` | Let Vulkan choose compression; fail if the game aliases/reads raw compressed data. | 3484| DCC / texture compatibility | Public release note for `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` | Let Vulkan choose compression; fail if the game aliases/reads raw compressed data. |
2922| PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | 3485| PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. |
3486| Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. |
2923| VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | 3487| VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. |
2924| Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | 3488| Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. |
2925| Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | 3489| Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. |
@@ -3030,14 +3594,11 @@ struct entry { // 10 uints = 40 bytes
3030| Entries (cap / load / bytes / mean probes) | Placement | `uniform_tsharp_hit` (us/1M, Glk/s) | `uniform_pair_ts` (us/1M, Glk/s) | `divergent_tsharp_hit` (us/1M, Glk/s) | `divergent_pair_ts` (us/1M, Glk/s) | `divergent_miss` (us/1M, Glk/s) | 3594| Entries (cap / load / bytes / mean probes) | Placement | `uniform_tsharp_hit` (us/1M, Glk/s) | `uniform_pair_ts` (us/1M, Glk/s) | `divergent_tsharp_hit` (us/1M, Glk/s) | `divergent_pair_ts` (us/1M, Glk/s) | `divergent_miss` (us/1M, Glk/s) |
3031|---|---|---|---|---|---|---| 3595|---|---|---|---|---|---|---|
3032| 1k (4,096 / 24.4% / 160 KiB / 1.316; 900 T#, 1k pair, 1,024 miss) | `device_local` | 3.322 (301.06) | 2.917 (342.84) | 24.008 (41.65) | 23.759 (42.09) | 96.175 (10.40) | 3596| 1k (4,096 / 24.4% / 160 KiB / 1.316; 900 T#, 1k pair, 1,024 miss) | `device_local` | 3.322 (301.06) | 2.917 (342.84) | 24.008 (41.65) | 23.759 (42.09) | 96.175 (10.40) |
3033| 1k | `host_visible` | 4.890 (204.48) | 3.583 (279.10) | 27.582 (36.26) | 26.426 (37.84) | 395.433 (2.53) | 3597| 1k | `host_device_local` `host_visible` | 3.317 (301.49) 4.890 (204.48) | 2.918 (342.73) 3.583 (279.10) | 23.973 (41.71) 27.582 (36.26) | 23.732 (42.14) 26.426 (37.84) | 96.148 (10.40) 395.433 (2.53) |
3034| 1k | `host_device_local` | 3.317 (301.49) | 2.918 (342.73) | 23.973 (41.71) | 23.732 (42.14) | 96.148 (10.40) |
3035| 10k (65,536 / 15.3% / 2.50 MiB / 1.310; 9k T#, 10k pair, 16,384 miss) | `device_local` | 12.842 (77.87) | 5.142 (194.49) | 38.202 (26.18) | 39.618 (25.24) | 206.654 (4.84) | 3598| 10k (65,536 / 15.3% / 2.50 MiB / 1.310; 9k T#, 10k pair, 16,384 miss) | `device_local` | 12.842 (77.87) | 5.142 (194.49) | 38.202 (26.18) | 39.618 (25.24) | 206.654 (4.84) |
3036| 10k | `host_visible` | 211.889 (4.72) | 16.257 (61.51) | 10261.465 (0.10) | 3334.286 (0.30) | 181717.455 (0.01) | 3599| 10k | `host_device_local` `host_visible` | 12.838 (77.89) 211.889 (4.72) | 5.166 (193.59) 16.257 (61.51) | 38.223 (26.16) 10261.465 (0.10) | 39.468 (25.34) 3334.286 (0.30) | 209.528 (4.77) 181717.455 (0.01) |
3037| 10k | `host_device_local` | 12.838 (77.89) | 5.166 (193.59) | 38.223 (26.16) | 39.468 (25.34) | 209.528 (4.77) |
3038| 100k (524,288 / 19.1% / 20.00 MiB / 1.416; 90k T#, 100k pair, 131,072 miss) | `device_local` | 6.007 (166.47) | 7.159 (139.69) | 71.939 (13.90) | 47.306 (21.14) | 483.346 (2.07) | 3600| 100k (524,288 / 19.1% / 20.00 MiB / 1.416; 90k T#, 100k pair, 131,072 miss) | `device_local` | 6.007 (166.47) | 7.159 (139.69) | 71.939 (13.90) | 47.306 (21.14) | 483.346 (2.07) |
3039| 100k | `host_visible` | 213.404 (4.69) | 183.383 (5.45) | 15149.069 (0.07) | 16289.665 (0.06) | 205561.481 (0.00) | 3601| 100k | `host_device_local` `host_visible` | 6.025 (165.97) 213.404 (4.69) | 7.161 (139.64) 183.383 (5.45) | 71.895 (13.91) 15149.069 (0.07) | 47.277 (21.15) 16289.665 (0.06) | 482.358 (2.07) 205561.481 (0.00) |
3040| 100k | `host_device_local` | 6.025 (165.97) | 7.161 (139.64) | 71.895 (13.91) | 47.277 (21.15) | 482.358 (2.07) |
3041 3602
3042Three consequences for the runtime and table layout (additional GPU measurements follow, including AMD RDNA3): 3603Three consequences for the runtime and table layout (additional GPU measurements follow, including AMD RDNA3):
3043 3604
@@ -3052,14 +3613,11 @@ Raw CSV rows (297, 9 processes): [D3D-56 RTX 5080 report](https://github.com/Its
3052| Entries (cap / load / bytes / mean probes) | Placement | `uniform_tsharp_hit` (us/1M, Glk/s) | `uniform_pair_ts` (us/1M, Glk/s) | `divergent_tsharp_hit` (us/1M, Glk/s) | `divergent_pair_ts` (us/1M, Glk/s) | `divergent_miss` (us/1M, Glk/s) | 3613| Entries (cap / load / bytes / mean probes) | Placement | `uniform_tsharp_hit` (us/1M, Glk/s) | `uniform_pair_ts` (us/1M, Glk/s) | `divergent_tsharp_hit` (us/1M, Glk/s) | `divergent_pair_ts` (us/1M, Glk/s) | `divergent_miss` (us/1M, Glk/s) |
3053|---|---|---|---|---|---|---| 3614|---|---|---|---|---|---|---|
3054| 1k (4,096 / 24.4% / 160 KiB / 1.316) | `device_local` | 6.220 (160.76) | 5.705 (175.27) | 15.285 (65.42) | 14.051 (71.17) | 50.461 (19.82) | 3615| 1k (4,096 / 24.4% / 160 KiB / 1.316) | `device_local` | 6.220 (160.76) | 5.705 (175.27) | 15.285 (65.42) | 14.051 (71.17) | 50.461 (19.82) |
3055| 1k | `host_visible` | 9.508 (105.17) | 5.783 (172.93) | 15.869 (63.02) | 13.465 (74.27) | 51.978 (19.24) | 3616| 1k | `host_device_local` `host_visible` | 8.783 (113.85) 9.508 (105.17) | 5.360 (186.58) 5.783 (172.93) | 15.380 (65.02) 15.869 (63.02) | 13.974 (71.56) 13.465 (74.27) | 49.765 (20.09) 51.978 (19.24) |
3056| 1k | `host_device_local` | 8.783 (113.85) | 5.360 (186.58) | 15.380 (65.02) | 13.974 (71.56) | 49.765 (20.09) |
3057| 10k (65,536 / 15.3% / 2.50 MiB / 1.310) | `device_local` | 5.152 (194.09) | 4.880 (204.90) | 27.998 (35.72) | 20.506 (48.77) | 146.217 (6.84) | 3617| 10k (65,536 / 15.3% / 2.50 MiB / 1.310) | `device_local` | 5.152 (194.09) | 4.880 (204.90) | 27.998 (35.72) | 20.506 (48.77) | 146.217 (6.84) |
3058| 10k | `host_visible` | 7.536 (132.69) | 6.236 (160.36) | 72.932 (13.71) | 54.183 (18.46) | 334.096 (2.99) | 3618| 10k | `host_device_local` `host_visible` | 5.066 (197.38) 7.536 (132.69) | 4.841 (206.57) 6.236 (160.36) | 28.322 (35.31) 72.932 (13.71) | 20.641 (48.45) 54.183 (18.46) | 144.532 (6.92) 334.096 (2.99) |
3059| 10k | `host_device_local` | 5.066 (197.38) | 4.841 (206.57) | 28.322 (35.31) | 20.641 (48.45) | 144.532 (6.92) |
3060| 100k (524,288 / 19.1% / 20.00 MiB / 1.416) | `device_local` | 7.618 (131.28) | 6.005 (166.54) | 53.558 (18.67) | 54.927 (18.21) | 290.279 (3.45) | 3619| 100k (524,288 / 19.1% / 20.00 MiB / 1.416) | `device_local` | 7.618 (131.28) | 6.005 (166.54) | 53.558 (18.67) | 54.927 (18.21) | 290.279 (3.45) |
3061| 100k | `host_visible` | 47.905 (20.87) | 29.887 (33.46) | 3492.770 (0.29) | 2240.356 (0.45) | 32108.853 (0.03) | 3620| 100k | `host_device_local` `host_visible` | 7.660 (130.54) 47.905 (20.87) | 6.040 (165.55) 29.887 (33.46) | 53.983 (18.52) 3492.770 (0.29) | 54.804 (18.25) 2240.356 (0.45) | 292.561 (3.42) 32108.853 (0.03) |
3062| 100k | `host_device_local` | 7.660 (130.54) | 6.040 (165.55) | 53.983 (18.52) | 54.804 (18.25) | 292.561 (3.42) |
3063 3621
3064On this GPU: 3622On this GPU:
3065 3623
@@ -3105,7 +3663,7 @@ contract, not a runtime bug:
3105 3663
3106- Only 155 shaders use code-embedded data, and a graphics pipeline has at least two stages (typically VS+PS, or 3664- Only 155 shaders use code-embedded data, and a graphics pipeline has at least two stages (typically VS+PS, or
3107 MS+PS). If only one stage in a pipeline uses it, the layer can set that stage's code base; the other stage never 3665 MS+PS). If only one stage in a pipeline uses it, the layer can set that stage's code base; the other stage never
3108 reads it. This probably covers the first boot. **Assumption.** 3666 reads it. This probably covers the first boot. **ASSUMPTION.**
3109- If both stages use it, the layer cannot satisfy both with the current contract. The clean fix is a translator 3667- If both stages use it, the layer cannot satisfy both with the current contract. The clean fix is a translator
3110 change: give each stage its own code-base slot (for example dwords 34–35 VS, 36–37 PS, 38–39 CS, 40–41 GS/MS, 3668 change: give each stage its own code-base slot (for example dwords 34–35 VS, 36–37 PS, 38–39 CS, 40–41 GS/MS,
3111 extending the block to 168 bytes) and have each compiled shader read its stage's slot. A 168-byte push-constant 3669 extending the block to 168 bytes) and have each compiled shader read its stage's slot. A 168-byte push-constant
@@ -3119,7 +3677,7 @@ Measured per stage (all 26,503, `tools/feature_scan.py`): `s_getpc_b64` is kept
3119VS, 93 PS, 266 MS and 263 CS (0 GS); the 147 VS/PS match the translator's own note. Both stages of a VS+PS or 3677VS, 93 PS, 266 MS and 263 CS (0 GS); the 147 VS/PS match the translator's own note. Both stages of a VS+PS or
3120MS+PS pipeline can therefore need a code base. 3678MS+PS pipeline can therefore need a code base.
3121 3679
3122**Measured:** across the GPU test fleet (Issue #166), desktop NVIDIA (Turing, Ampere, Ada, Blackwell: 256 bytes), desktop AMD (RDNA2: 256 bytes) and Apple Silicon (MoltenVK: 4096 bytes) all satisfy the 144-byte contract natively (`maxPushConstantsSize >= 144`). Intel Arc is not uniform: the earlier fleet entries report the 128-byte specification minimum (`maxPushConstantsSize == 128`) for Arc, but an Arc B580 (Battlemage) on Windows 11, driver 32.0.101.9175, reports 256 bytes (#166, @rtrexmass), so there D3D-14's fallback never engages. The 128 figure may be specific to another OS or driver (Mesa ANV on Linux is the guess; no Arc run on Linux that records the OS is cited here, and an ANV result would settle it). So does an integrated AMD RDNA2 GPU, a Radeon 680M on the Windows driver 22.40.84.06, so the minimum is not Intel-only. 128 bytes cannot fit the 16-byte tail (dwords 32–35: heap base and code base) inside push constants. The runtime detects `maxPushConstantsSize < 144` at device creation (`d3d12_vulkan_device.cpp`) and flags `push_constants_need_fallback` for the uniform-buffer fallback. 3680**Measured:** across the GPU test fleet (Issue #166), desktop NVIDIA (Turing, Ampere, Ada, Blackwell: 256 bytes), desktop AMD (RDNA2: 256 bytes) and Apple Silicon (MoltenVK: 4096 bytes) all satisfy the 144-byte contract natively (`maxPushConstantsSize >= 144`). Intel Arc is not uniform: the earlier fleet entries report the 128-byte specification minimum (`maxPushConstantsSize == 128`) for Arc, but an Arc B580 (Battlemage) on Windows 11, driver 32.0.101.9175, reports 256 bytes (#166, @rtrexmass), so there D3D-14's fallback never engages. The 128 figure may be specific to another OS or driver (Mesa ANV on Linux is the guess; no Arc run on Linux that records the OS is cited here, and an ANV result would settle it). So does an integrated AMD RDNA2 GPU, a Radeon 680M on the Windows driver 22.40.84.06, so the minimum is not Intel-only. That figure follows the driver as well: a Radeon 610M reports 128 on 24.10.16.14 and 256 on 26.11.2 (#166). 128 bytes cannot fit the 16-byte tail (dwords 32–35: heap base and code base) inside push constants. The runtime detects `maxPushConstantsSize < 144` at device creation (`d3d12_vulkan_device.cpp`) and flags `push_constants_need_fallback` for the uniform-buffer fallback.
3123**Open:** the exact count of such PSOs (the pairing is in the executable), and the minimum `maxPushConstantsSize` across target GPUs. If a GPU only 3681**Open:** the exact count of such PSOs (the pairing is in the executable), and the minimum `maxPushConstantsSize` across target GPUs. If a GPU only
3124supports 128 bytes, the current 144-byte contract already fails; the layer needs a fallback (uniform buffer for the 3682supports 128 bytes, the current 144-byte contract already fails; the layer needs a fallback (uniform buffer for the
3125tail) regardless. 3683tail) regardless.
@@ -3235,9 +3793,7 @@ folded into the table below with the measurement basis noted per row; nothing is
3235| Xbox root-signature descriptors carry flags `0x03000000`. The PC serializer rejects them with `E_INVALIDARG`; the proxy clears the high byte on a copy. The v1.0 `D3D12SerializeRootSignature` path keeps flags at +32, and `0x3000001` also fails on the PC runtime. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Narrows the root-signature reflection risk. Mask the high byte on a private copy; the meaning of the bits remains **Open**. See section 3.5. | 3793| Xbox root-signature descriptors carry flags `0x03000000`. The PC serializer rejects them with `E_INVALIDARG`; the proxy clears the high byte on a copy. The v1.0 `D3D12SerializeRootSignature` path keeps flags at +32, and `0x3000001` also fails on the PC runtime. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Narrows the root-signature reflection risk. Mask the high byte on a private copy; the meaning of the bits remains **Open**. See section 3.5. |
3236| The BVH builder's constructor creates 53 compute pipelines through device slot 62, called with a compute-PSO shape (a plain `D3D12_COMPUTE_PIPELINE_STATE_DESC`, two zero words, iid, out). On the PC interface the prior art forwards to, slot 62 is `CreateStateObject` (wrong arity), so the proxy overrides it. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Corrects the assumption that the whole device vtable is public order. Slot 62 must be compute-PSO creation for the builder, not a state object. Slots 1/15/18/19/27/38 did match the desktop order. | 3794| The BVH builder's constructor creates 53 compute pipelines through device slot 62, called with a compute-PSO shape (a plain `D3D12_COMPUTE_PIPELINE_STATE_DESC`, two zero words, iid, out). On the PC interface the prior art forwards to, slot 62 is `CreateStateObject` (wrong arity), so the proxy overrides it. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Corrects the assumption that the whole device vtable is public order. Slot 62 must be compute-PSO creation for the builder, not a state object. Slots 1/15/18/19/27/38 did match the desktop order. |
3237| A reusable `xbox_device_proxy.h` forwards every slot to a PC object, counts hits per slot and logs first calls with `XS_TRACE=1`; the observed device slots include 1, 14, 15, 16, 18, 19, 27, 38, 62 and 76. Their `xgr` stand-in covers 48 of 398 methods; Xodus (LGPL-2.1) covers 152 of 396 via IDL-generated stubs. | *Run* — [platform README](https://github.com/realdody/americas-recomp/blob/xbox-series/tools/xbox/platform/README.md), [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Confirms the trace-first approach and shows the long tail. We adopt the *method* (per-slot counters, first-call logging), not the code. | 3795| A reusable `xbox_device_proxy.h` forwards every slot to a PC object, counts hits per slot and logs first calls with `XS_TRACE=1`; the observed device slots include 1, 14, 15, 16, 18, 19, 27, 38, 62 and 76. Their `xgr` stand-in covers 48 of 398 methods; Xodus (LGPL-2.1) covers 152 of 396 via IDL-generated stubs. | *Run* — [platform README](https://github.com/realdody/americas-recomp/blob/xbox-series/tools/xbox/platform/README.md), [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Confirms the trace-first approach and shows the long tail. We adopt the *method* (per-slot counters, first-call logging), not the code. |
3238| The BVH builder's 53 compute shaders are Xbox DXIL with `@xbox.*` intrinsics; 44 of 53 fail the PC D3D12 shader compiler, 22 have been lowered to standard DXIL and accepted as pipelines, and 31 use raw 64-bit GPU addresses. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | A separate translation path from the FSSM RDNA2 corpus when measured on the **bitcode**. Measured later on the console `XBCH` record of the same containers: 52 programs, 42 pass `spirv-val` through the FSSM translator ([embedded_shaders.md](embedded_shaders.md)). | 3796| The BVH builder's 53 compute shaders are Xbox DXIL with `@xbox.*` intrinsics; 44 of 53 fail the PC D3D12 shader compiler, 22 have been lowered to standard DXIL and accepted as pipelines, and 31 use raw 64-bit GPU addresses. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | A separate translation path from the FSSM RDNA2 corpus when measured on the **bitcode**. See section 4.8 and the paragraph below. Measured later on the console `XBCH` record of the same containers: 52 programs, 51 pass `spirv-val` through the FSSM translator ([embedded_shaders.md](embedded_shaders.md)). 52 programs, 42 pass `spirv-val` through the FSSM translator ([embedded_shaders.md](embedded_shaders.md)). |
3239| The BVH builder's 53 compute shaders are Xbox DXIL with `@xbox.*` intrinsics; 44 of 53 fail the PC D3D12 shader compiler, 22 have been lowered to standard DXIL and accepted as pipelines, and 31 use raw 64-bit GPU addresses. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | A separate translation path from the FSSM RDNA2 corpus when measured on the **bitcode**. Measured later on the console `XBCH` record of the same containers: 52 programs, 51 pass `spirv-val` through the FSSM translator ([embedded_shaders.md](embedded_shaders.md)). |
3240| The BVH builder's 53 compute shaders are Xbox DXIL with `@xbox.*` intrinsics; 44 of 53 fail the PC D3D12 shader compiler, 22 have been lowered to standard DXIL and accepted as pipelines, and 31 use raw 64-bit GPU addresses. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | A separate translation path from the FSSM RDNA2 corpus. See section 4.8 and the paragraph below. |
3241| On the console's own shader compiler, compute user parameters go into user SGPRs `s4`… in root-signature order while each fits whole (root constant = 1 dword, root descriptor = 2, descriptor table = 1 dword holding the 32-bit address of its first descriptor); `s0`..`s3` are the driver's. From the first parameter that does not fit, it and all after it go into a packed array addressed by a 40-bit pointer in `s[0:1]` (constant 4 B, descriptor 8 B, no alignment). Thread-group ids follow the user SGPRs. | *Console-compiler output, sibling layer* | Narrows question 3 for the compute stage: the inline-from-`s4` model matches this repo's census (lowest CS pointer SGPR `s4`), and the spill target is named (the array at `s[0:1]`), not guessed. VS/PS/MS bases were not measured there; verify against the game's own signatures. | 3797| On the console's own shader compiler, compute user parameters go into user SGPRs `s4`… in root-signature order while each fits whole (root constant = 1 dword, root descriptor = 2, descriptor table = 1 dword holding the 32-bit address of its first descriptor); `s0`..`s3` are the driver's. From the first parameter that does not fit, it and all after it go into a packed array addressed by a 40-bit pointer in `s[0:1]` (constant 4 B, descriptor 8 B, no alignment). Thread-group ids follow the user SGPRs. | *Console-compiler output, sibling layer* | Narrows question 3 for the compute stage: the inline-from-`s4` model matches this repo's census (lowest CS pointer SGPR `s4`), and the spill target is named (the array at `s[0:1]`), not guessed. VS/PS/MS bases were not measured there; verify against the game's own signatures. |
3242| The command list's inline records: a `Dispatch` is `0x4002C400` followed by x, y, z (16 B); a 20-byte record `0x4003CC00` stands in for console slot 80; the pipeline record is a 28-byte copy of the PSO object's +0x10..+0x2B; a root parameter starts from the header word at list +0x344+4·i (the high half carries n−1 for a multi-constant write), then a descriptor is 12 B, one constant 8 B and n constants 4+4n B. | *Console-DLL run, sibling layer* | Supplies the record opcode for the "five-dword packet" this repo inferred at slot 80 and the header encoding for parameter groups; consistent with our own measurements of +0x18/+0x28/+0x30/+0x140/+0x344/+0x544. | 3798| The command list's inline records: a `Dispatch` is `0x4002C400` followed by x, y, z (16 B); a 20-byte record `0x4003CC00` stands in for console slot 80; the pipeline record is a 28-byte copy of the PSO object's +0x10..+0x2B; a root parameter starts from the header word at list +0x344+4·i (the high half carries n−1 for a multi-constant write), then a descriptor is 12 B, one constant 8 B and n constants 4+4n B. | *Console-DLL run, sibling layer* | Supplies the record opcode for the "five-dword packet" this repo inferred at slot 80 and the header encoding for parameter groups; consistent with our own measurements of +0x18/+0x28/+0x30/+0x140/+0x344/+0x544. |
3243| Mesh (NGG) inputs measured across the corpus: `s3[27:24]` = wave index in the group, `v5` = group·128 + thread, `s16`–`s24` = user data. | *Corpus measurement, sibling layer* | Confirms the `s16` mesh base of §3.5's census and the `v5` group numbering already used for the mesh stage. | 3799| Mesh (NGG) inputs measured across the corpus: `s3[27:24]` = wave index in the group, `v5` = group·128 + thread, `s16`–`s24` = user data. | *Corpus measurement, sibling layer* | Confirms the `s16` mesh base of §3.5's census and the `v5` group numbering already used for the mesh stage. |
@@ -3340,7 +3896,7 @@ nothing is copied from their trees.
3340|---|---|---| 3896|---|---|---|
3341| 1 | The device entry point is now named `D3D12XboxCreateDevice(adapter, params, riid, out)`. What do its 24-word params and flag bits mean? | Public documentation and the executable's call sites. Log the words and accept any flag bits; do not treat a wrong params layout as fatal until the fields are understood. | 3897| 1 | The device entry point is now named `D3D12XboxCreateDevice(adapter, params, riid, out)`. What do its 24-word params and flag bits mean? | Public documentation and the executable's call sites. Log the words and accept any flag bits; do not treat a wrong params layout as fatal until the fields are understood. |
3342| 2 | Which Xbox device/heap/queue/command-list slots differ? Prior art measured device slots 62 and 76 and descriptor-heap slots 9/10; slot 14 is the public `CreateDescriptorHeap`, with only the returned heap's start-handle return wrapped. **Partly measured** with the FSR DLL ([d3d12_command_objects.md §3.5a](d3d12_command_objects.md)): device slots 14, 15, 16, 18, 19, 27, 38, 62 and 76 at their expected shapes (24 in the code, not called), slot 67 a console-only pipeline call; command-list slots 14, 15, 25 and 26 at their PC positions, then shifted (+4 from `SetDescriptorHeaps` at 32, +2 at `ExecuteIndirect` at 61), with console-only methods at 85 and 141. The BVH builder's call sites add the rest of the +4 root group (37, 39, 43, 45) and console slots 71, 73, 80, 146 (the GCL7 `Barrier`) and 148 (an upload allocator whose pointer is also the GPU address) ([d3d12_command_objects.md §3.3, §3.3a](d3d12_command_objects.md)). A second, retail-title measurement adds console slots 83 (`CopyTextureRegion`), 84 (`CopyResource`), 26 (barriers), 127 (direct mesh dispatch — not the PC position, GCL6 slot 79), 59 (a second indirect/mesh dispatch path) and 96 (an async-compute budget call) (section 7). Presentation, queue and fence slots remain unknown. | Trace every `QueryInterface` and every method slot with per-slot hit counters. A wrong slot shows as an immediate crash or wrong argument; compare against the SDK vtable. | 3898| 2 | Which Xbox device/heap/queue/command-list slots differ? Prior art measured device slots 62 and 76 and descriptor-heap slots 9/10; slot 14 is the public `CreateDescriptorHeap`, with only the returned heap's start-handle return wrapped. **Partly measured** with the FSR DLL ([d3d12_command_objects.md §3.5a](d3d12_command_objects.md)): device slots 14, 15, 16, 18, 19, 27, 38, 62 and 76 at their expected shapes (24 in the code, not called), slot 67 a console-only pipeline call; command-list slots 14, 15, 25 and 26 at their PC positions, then shifted (+4 from `SetDescriptorHeaps` at 32, +2 at `ExecuteIndirect` at 61), with console-only methods at 85 and 141. The BVH builder's call sites add the rest of the +4 root group (37, 39, 43, 45) and console slots 71, 73, 80, 146 (the GCL7 `Barrier`) and 148 (an upload allocator whose pointer is also the GPU address) ([d3d12_command_objects.md §3.3, §3.3a](d3d12_command_objects.md)). A second, retail-title measurement adds console slots 83 (`CopyTextureRegion`), 84 (`CopyResource`), 26 (barriers), 127 (direct mesh dispatch — not the PC position, GCL6 slot 79), 59 (a second indirect/mesh dispatch path) and 96 (an async-compute budget call) (section 7). Presentation, queue and fence slots remain unknown. | Trace every `QueryInterface` and every method slot with per-slot hit counters. A wrong slot shows as an immediate crash or wrong argument; compare against the SDK vtable. |
3343| 3 | How does the console map a root signature to `s0..s31` (order, per-stage visibility, spills above 32 dwords, static samplers, direct-heap base)? | **Compute partly measured** by a sibling project's console-compiler output (section 7): parameters inline in user SGPRs from `s4` in root order while each fits whole; the first that does not fit, and all after it, go into a packed array addressed by a 40-bit pointer at `s[0:1]`; thread-group ids follow the user SGPRs. That matches this repo's CS census (lowest CS pointer SGPR `s4`). VS/PS/MS bases and static samplers remain open. Dump the game's root-signature blobs with the host deserializer; mask the `0x03000000` flag byte on a copy first; match against the per-shader user-SGPR read sets. If a signature exceeds 32 dwords, reverse the spill pointer from the shader. | 3899| 3 | How does the console map a root signature to `s0..s31` (order, per-stage visibility, spills above 32 dwords, static samplers, direct-heap base)? | **Compute partly measured** by a sibling project's console-compiler output (section 7): parameters inline in user SGPRs from `s4` in root order while each fits whole; the first that does not fit, and all after it, go into a packed array addressed by a 40-bit pointer at `s[0:1]`; thread-group ids follow the user SGPRs. That matches this repo's CS census (lowest CS pointer SGPR `s4`). VS/PS/MS bases remain open. Static samplers: no sampling instruction was found reading one from a driver table (SHADER-735, section 3.5; 0.66% undetermined); which S# is a static sampler remains open. Dump the game's root-signature blobs with the host deserializer; mask the `0x03000000` flag byte on a copy first; match against the per-shader user-SGPR read sets. If a signature exceeds 32 dwords, reverse the spill pointer from the shader. |
3344| 4 | Are Xbox descriptor bytes GFX10 T#/S#, and what are the heap increments? Does the game use `Create*View` or build descriptors itself? | Dump a shader-visible heap after the first `CreateShaderResourceView` and after the first draw; compare the bytes the shader loads with the T# parser. The start-handle return ABI is known (RAX); the increment values still need measuring. | 3900| 4 | Are Xbox descriptor bytes GFX10 T#/S#, and what are the heap increments? Does the game use `Create*View` or build descriptors itself? | Dump a shader-visible heap after the first `CreateShaderResourceView` and after the first draw; compare the bytes the shader loads with the T# parser. The start-handle return ABI is known (RAX); the increment values still need measuring. |
3345| 5 | What is the buffer/descriptor/code VA range, and what arena capacity is needed? | Log every `GetGPUVirtualAddress` and every descriptor base; track the high-water mark. Choose a capacity; grow at a frame boundary if needed. | 3901| 5 | What is the buffer/descriptor/code VA range, and what arena capacity is needed? | Log every `GetGPUVirtualAddress` and every descriptor base; track the high-water mark. Choose a capacity; grow at a frame boundary if needed. |
3346| 6 | Which swapchain/present path is used: DXGI, `PresentX`, or both? | **Partly answered from public samples (§4.5):** GDKX samples use `PresentX` + frame events and no DXGI swapchain (DXGI only for `IDXGIDevice1`→adapter→output). Hypothesis for the game, not observed: same. Still open: vtable slots, `D3D12XBOX_*` layouts, and whether the game also creates a swapchain. Check imports and the first present call. Implement the `PresentX` + frame-event presenter first; keep DXGI swapchain as fallback. | 3902| 6 | Which swapchain/present path is used: DXGI, `PresentX`, or both? | **Partly answered from public samples (§4.5):** GDKX samples use `PresentX` + frame events and no DXGI swapchain (DXGI only for `IDXGIDevice1`→adapter→output). Hypothesis for the game, not observed: same. Still open: vtable slots, `D3D12XBOX_*` layouts, and whether the game also creates a swapchain. Check imports and the first present call. Implement the `PresentX` + frame-event presenter first; keep DXGI swapchain as fallback. |
@@ -3348,7 +3904,7 @@ nothing is copied from their trees.
3348| 8 | What are the layouts of `D3D12XBOX_XDXR_STREAM_DESC`, the batched build desc, and the offline statistics desc? | **Measured** from `XboxBvhBuilder.dll`'s reads ([xdxr.md](xdxr.md)): `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) with every field's offset, and the stream records' offsets, types and defaults. Still open: the record names, and the offline statistics layout, which the DLL never writes (it rejects that postbuild type). | 3904| 8 | What are the layouts of `D3D12XBOX_XDXR_STREAM_DESC`, the batched build desc, and the offline statistics desc? | **Measured** from `XboxBvhBuilder.dll`'s reads ([xdxr.md](xdxr.md)): `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) with every field's offset, and the stream records' offsets, types and defaults. Still open: the record names, and the offline statistics layout, which the DLL never writes (it rejects that postbuild type). |
3349| 9 | Xbox texture creation is device slot 76 with layout `0x101` (tiled) or `0x1` (row-major). What is the tiled data layout, and does the game upload console-tiled or DCC data? | Trace slot 76, `CopyTextureRegion` and the resource descs. If the game uploads console-tiled data, add a detile step or a matching layout. | 3905| 9 | Xbox texture creation is device slot 76 with layout `0x101` (tiled) or `0x1` (row-major). What is the tiled data layout, and does the game upload console-tiled or DCC data? | Trace slot 76, `CopyTextureRegion` and the resource descs. If the game uploads console-tiled data, add a detile step or a matching layout. |
3350| 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. | 3906| 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. |
3351| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (discrete desktop GPU: non-UMA), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. | 3907| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (a discrete GPU: non-UMA; an integrated GPU, `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`: UMA, not cache-coherent, as the host runtime answers on a Radeon 780M), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. |
3352| 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | 3908| 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. |
3353| 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), desktop AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively. A Radeon 680M on the Windows driver 22.40.84.06 and the earlier Intel Arc entries expose only the core minimum 128 B (`maxPushConstantsSize == 128`), but an Arc B580 on Windows 11 (driver 32.0.101.9175) reports 256 B (#166), so the 128 B figure for Arc depends on the OS or driver; an Arc result on Linux (Mesa ANV) would settle which side it is. `d3d12_vulkan_device_test` accepts either answer and checks that the fallback flag matches it. Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | 3909| 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), desktop AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively. A Radeon 680M on the Windows driver 22.40.84.06 and the earlier Intel Arc entries expose only the core minimum 128 B (`maxPushConstantsSize == 128`), but an Arc B580 on Windows 11 (driver 32.0.101.9175) reports 256 B (#166), so the 128 B figure for Arc depends on the OS or driver; an Arc result on Linux (Mesa ANV) would settle which side it is. `d3d12_vulkan_device_test` accepts either answer and checks that the fallback flag matches it. Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. |
3354| 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | 3910| 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. |
@@ -3357,8 +3913,7 @@ nothing is copied from their trees.
3357| 17 | Do upload/readback resources ever reach shaders (as vertex/index buffers or descriptors), and does the `-heap_base` bias work for them? | Trace `CreateCommittedResource` heap types and every VB/IB/descriptor that points at an upload resource; test the bias with a synthetic draw. | 3913| 17 | Do upload/readback resources ever reach shaders (as vertex/index buffers or descriptors), and does the `-heap_base` bias work for them? | Trace `CreateCommittedResource` heap types and every VB/IB/descriptor that points at an upload resource; test the bias with a synthetic draw. |
3358| 18 | Does the game alias buffers/images in a heap, or use reserved/tiled resources? | Trace `CreatePlacedResource` ranges, aliasing barriers, `CreateReservedResource` and tile mappings. If yes, implement shared memory per heap range or fall back to linear allocations with a clear log. Shaders: 30 declare `TILED_RESOURCES` in SFI0 (`tools/feature_scan.py`), so reserved/tiled resources are likely used. Placed resources are D3D-16 and reserved resources D3D-20 (#313). | 3914| 18 | Does the game alias buffers/images in a heap, or use reserved/tiled resources? | Trace `CreatePlacedResource` ranges, aliasing barriers, `CreateReservedResource` and tile mappings. If yes, implement shared memory per heap range or fall back to linear allocations with a clear log. Shaders: 30 declare `TILED_RESOURCES` in SFI0 (`tools/feature_scan.py`), so reserved/tiled resources are likely used. Placed resources are D3D-16 and reserved resources D3D-20 (#313). |
3359| 19 | What do the `0x03000000` root-signature flag bits mean? | Masking them on a copy works around the PC serializer; the semantics remain unknown. **Origin measured** (section "Root-signature flag quirk"): in the package only `XboxBvhBuilder.dll` sets them, in its 52 compiled `RTS0` parts and unconditionally at `0xc30e` before serialising; the FSR DLL's 29 `RTS0` parts carry 0. Compare against the public flag enum and observe the game's behaviour with and without the mask; check whether the executable's root signatures carry them. | 3915| 19 | What do the `0x03000000` root-signature flag bits mean? | Masking them on a copy works around the PC serializer; the semantics remain unknown. **Origin measured** (section "Root-signature flag quirk"): in the package only `XboxBvhBuilder.dll` sets them, in its 52 compiled `RTS0` parts and unconditionally at `0xc30e` before serialising; the FSR DLL's 29 `RTS0` parts carry 0. Compare against the public flag enum and observe the game's behaviour with and without the mask; check whether the executable's root signatures carry them. |
3360| 20 | Which of the BVH builder's 52 `FSSM` programs does the game actually use, and do the translated programs match a reference? | Dump the slot-62 compute PSOs on the first RT frame and map each to its container by the `ILDN` name; 42/52 pass `spirv-val` today and the four missing rules are named in [embedded_shaders.md](embedded_shaders.md); compare against the builder's CPU validation (`CpuValidateResultX`) or a captured reference. | 3916| 20 | Which of the BVH builder's 52 `FSSM` programs does the game actually use, and do the translated programs match a reference? | Dump the slot-62 compute PSOs on the first RT frame and map each to its container by the `ILDN` name; 51/52 pass `spirv-val` today and the one missing rule is named in [embedded_shaders.md](embedded_shaders.md); compare against the builder's CPU validation (`CpuValidateResultX`) or a captured reference. 42/52 pass `spirv-val` today and the four missing rules are named in [embedded_shaders.md](embedded_shaders.md); compare against the builder's CPU validation (`CpuValidateResultX`) or a captured reference. |
3361| 20 | Which of the BVH builder's 52 `FSSM` programs does the game actually use, and do the translated programs match a reference? | Dump the slot-62 compute PSOs on the first RT frame and map each to its container by the `ILDN` name; 51/52 pass `spirv-val` today and the one missing rule is named in [embedded_shaders.md](embedded_shaders.md); compare against the builder's CPU validation (`CpuValidateResultX`) or a captured reference. |
3362| 21 | Which `Metadata` values and blob format does the console's PIX use for `SetMarker`/`BeginEvent`? The layer reads 0 and 1 as strings and labels 2 (the PC PIX3 blob) `PIX event` (section 4.10). | Log the `Metadata` values the game passes; if it is 2, decode the console blob from the executable's PIX calls rather than assuming the PC WinPixEventRuntime layout. | 3917| 21 | Which `Metadata` values and blob format does the console's PIX use for `SetMarker`/`BeginEvent`? The layer reads 0 and 1 as strings and labels 2 (the PC PIX3 blob) `PIX event` (section 4.10). | Log the `Metadata` values the game passes; if it is 2, decode the console blob from the executable's PIX calls rather than assuming the PC WinPixEventRuntime layout. |
3363| 22 | Does the game ask `CheckFeatureSupport(D3D12_OPTIONS5)` for `RaytracingTier` and switch ray tracing off when it reads `NOT_SUPPORTED`? The layer answers `NOT_SUPPORTED` because full DXR (`CreateStateObject`, `DispatchRays`) is not implemented, even though the XDXR acceleration-structure path the game's own traversal shaders use is ([bvh.md](bvh.md) §7a). On the console, ray tracing is always present, so the game may never ask. | The first-boot trace (`--trace-d3d12`) logs every `CheckFeatureSupport` call and its answer. If the game asks and gates its RT on the tier, decide with the maintainer whether to report `TIER_1_0`/`1_1` for this game while `DispatchRays` stays unimplemented; until then, keep the conservative answer. | 3918| 22 | Does the game ask `CheckFeatureSupport(D3D12_OPTIONS5)` for `RaytracingTier` and switch ray tracing off when it reads `NOT_SUPPORTED`? The layer answers `NOT_SUPPORTED` because full DXR (`CreateStateObject`, `DispatchRays`) is not implemented, even though the XDXR acceleration-structure path the game's own traversal shaders use is ([bvh.md](bvh.md) §7a). On the console, ray tracing is always present, so the game may never ask. | The first-boot trace (`--trace-d3d12`) logs every `CheckFeatureSupport` call and its answer. If the game asks and gates its RT on the tier, decide with the maintainer whether to report `TIER_1_0`/`1_1` for this game while `DispatchRays` stays unimplemented; until then, keep the conservative answer. |
3364 3919
@@ -3386,7 +3941,6 @@ nothing is copied from their trees.
3386 unknown. If the game assumes console tiling or compression metadata, the layer needs a detile/repack step. 3941 unknown. If the game assumes console tiling or compression metadata, the layer needs a detile/repack step.
3387- **BVH builder shaders.** The container's DXIL bitcode is Xbox DXIL that PC drivers reject; its console `XBCH` 3942- **BVH builder shaders.** The container's DXIL bitcode is Xbox DXIL that PC drivers reject; its console `XBCH`
3388 record is `FSSM`, and 51 of the 52 programs already pass `spirv-val` through the same translator as the game 3943 record is `FSSM`, and 51 of the 52 programs already pass `spirv-val` through the same translator as the game
3389 ([embedded_shaders.md](embedded_shaders.md)). The one left needs `buffer_store_short`. Translation is not execution:
3390 ([embedded_shaders.md](embedded_shaders.md)). The one left needs `buffer_store_short` (#1864). Translation is not execution: 3944 ([embedded_shaders.md](embedded_shaders.md)). The one left needs `buffer_store_short` (#1864). Translation is not execution:
3391 there is no GPU reference for any of the 52 yet. 3945 there is no GPU reference for any of the 52 yet.
3392- **Ray tracing.** The game's RT work includes 64 compute shaders that traverse AMD-format BVH nodes, and it ships 3946- **Ray tracing.** The game's RT work includes 64 compute shaders that traverse AMD-format BVH nodes, and it ships
@@ -3531,6 +4085,15 @@ on a PC device behind the Xbox-ABI proxy). Measured:
3531 `XBCH` record, which decompresses to `FSSM`; 51 of the 52 programs translate and pass `spirv-val` today 4085 `XBCH` record, which decompresses to `FSSM`; 51 of the 52 programs translate and pass `spirv-val` today
3532 ([embedded_shaders.md](embedded_shaders.md)). Translating that record is the path that avoids a DXIL lowering 4086 ([embedded_shaders.md](embedded_shaders.md)). Translating that record is the path that avoids a DXIL lowering
3533 front end (section 7.2, M6); the bitcode is a second representation. 4087 front end (section 7.2, M6); the bitcode is a second representation.
4088- **On the Vulkan device (D3D-557).** With `LEONIDA_BVH_DEVICE=vulkan` the constructor runs on the Vulkan-backed
4089 device, where slot 62 needs the translated module of each container's `FSSM` program. `make_game.py` translates
4090 the DLL's programs into `<shaders>/bvh/` and the shader library reads that index
4091 ([embedded_shaders.md](embedded_shaders.md) section 7). Measured on 1.0.2.1: before that step creation #1 failed
4092 (`E_FAIL` with no library, `E_INVALIDARG` with the game's corpus loaded). With it, on an RTX 3070 (NVIDIA 610.74)
4093 and on a Ryzen 7 9700X's integrated Radeon (AMD 32.0.21042.62), both with the `--wave64-emulate` translation, 49 of
4094 the first 50 creations return `S_OK` and the constructor throws `E_INVALIDARG` at #50, `Box16Rehydration`, the one
4095 program the translator has no rule for yet (#1864). With that rule applied locally all 53 are created and the
4096 constructor and destructor return. Nothing has been dispatched.
3534 4097
3535### A.3 `amd_fidelityfx_upscaler_xbox.dll` 4098### A.3 `amd_fidelityfx_upscaler_xbox.dll`
3536 4099
@@ -3606,11 +4169,12 @@ on a PC device behind the Xbox-ABI proxy). Measured:
3606 messages, not the PC method at that index; the proxy routes it to `CreateComputePipelineState`. The dispatch stops where the PC runtime 4169 messages, not the PC method at that index; the proxy routes it to `CreateComputePipelineState`. The dispatch stops where the PC runtime
3607 refuses the DLL's compute code at slot 62: the DLL's shaders carry an `ACCC` part instead of DXIL, an `FSPX` 4170 refuses the DLL's compute code at slot 62: the DLL's shaders carry an `ACCC` part instead of DXIL, an `FSPX`
3608 payload with an RDNA2 program ([fspx.md](fspx.md)). The Vulkan device takes both forms at 4171 payload with an RDNA2 program ([fspx.md](fspx.md)). The Vulkan device takes both forms at
3609 `CreateComputePipelineState`: the `ACCC` container slot 62 gets, and the bare kind-6 program the proxy forwards 4172 `CreateComputePipelineState`: the `ACCC` container slot 62 gets, and the `FSPX` payload the proxy builds from the
3610 from the slot-67 description (`+0x28`, size at `+0x30`). It finds the translated module by `fspx_code_sha256`, the 4173 slot-67 description's four pairs. It finds the translated module by `fspx_code_sha256` and `fspx_state_sha256` in
3611 SHA-256 of the kind-6 bytes, in `<shaders>/fspx/index.json`, which `make_game.py` writes ([fspx.md](fspx.md), 4174 `<shaders>/fspx/index.json`, which `make_game.py` writes ([fspx.md](fspx.md), "Build and run-time lookup";
3612 "Build and run-time lookup"; `d3d12_fspx_compute_test`). Not done: the console-only pipeline slot 11 the DLL 4175 `d3d12_fspx_compute_test`). The pipeline answers the console slot 11 the DLL calls afterwards with 0, so no
3613 calls afterwards. 4176 compute scratch buffer is made ([d3d12_command_objects.md](d3d12_command_objects.md) §3.5a). Not run here: the
4177 DLL's own dispatch on this device (`fsr_dispatch_test` needs MSVC structured exception handling).
3614 - Its `throw 1` reaches the caller. Before #965 the throw carried an image base of 0, because `_CxxThrowException` 4178 - Its `throw 1` reaches the caller. Before #965 the throw carried an image base of 0, because `_CxxThrowException`
3615 did not know manually mapped images; with #965 it carries the DLL's base, and the DLL still does not catch it on 4179 did not know manually mapped images; with #965 it carries the DLL's base, and the DLL still does not catch it on
3616 that path (measured with `fsr_dispatch_test` and `LEONIDA_FSR_NO_STANDIN=1`). 4180 that path (measured with `fsr_dispatch_test` and `LEONIDA_FSR_NO_STANDIN=1`).
diff --git a/docs/d3d12_xs_surface.md b/docs/d3d12_xs_surface.md
index aed604416..4e4b018d4 100644
--- a/docs/d3d12_xs_surface.md
+++ b/docs/d3d12_xs_surface.md
@@ -64,7 +64,7 @@ and the individual stubs in
64| 1 | `D3D12ZeroMemoryX` | console | absent | console fast-zero; `memset` is equivalent | 64| 1 | `D3D12ZeroMemoryX` | console | absent | console fast-zero; `memset` is equivalent |
65| 2 | `PixGetPixieEntryPoints` | console (PIX) | absent | no PIX path | 65| 2 | `PixGetPixieEntryPoints` | console (PIX) | absent | no PIX path |
66| 3 | `D3D10CreateBlob` | console (D3D10) | absent | local `ID3D10Blob`; no D3D10 dependency needed | 66| 3 | `D3D10CreateBlob` | console (D3D10) | absent | local `ID3D10Blob`; no D3D10 dependency needed |
67| 4 | `D3D12ConfigureVirtualMemoryX` | console | absent | VM policy; PC/Vulkan owns it | 67| 4 | `D3D12ConfigureVirtualMemoryX` | console | present (returns `S_OK`) | VM policy; PC/Vulkan owns it. Measured: one pointer argument (a zeroed 32-byte block, dword +4 set to a count); the title only tests the result for failure |
68| 5 | `D3D12CreateDevice` | standard | **absent** | Leonida exports only the Xbox entry point; see §2.3 | 68| 5 | `D3D12CreateDevice` | standard | **absent** | Leonida exports only the Xbox entry point; see §2.3 |
69| 6 | `D3D12CreateRootSignatureDeserializer` | standard | present | forwarded | 69| 6 | `D3D12CreateRootSignatureDeserializer` | standard | present | forwarded |
70| 7 | `D3D12CreateVersionedRootSignatureDeserializer` | standard | absent | forward if imported | 70| 7 | `D3D12CreateVersionedRootSignatureDeserializer` | standard | absent | forward if imported |
@@ -522,7 +522,8 @@ collected in [d3d12_vulkan.md §4.5](d3d12_vulkan.md):
522 token), `GetFrameStatisticsX` (4). Back buffers are committed resources with `ALLOW_DISPLAY`; DXGI is used 522 token), `GetFrameStatisticsX` (4). Back buffers are committed resources with `ALLOW_DISPLAY`; DXGI is used
523 only for `IDXGIDevice1`→`GetAdapter`→`EnumOutputs`. No DXGI swapchain. 523 only for `IDXGIDevice1`→`GetAdapter`→`EnumOutputs`. No DXGI swapchain.
524 524
525Vtable slots, struct layouts and enum values are still **unmeasured**. 525Vtable slots and struct layouts are **not** unmeasured any more: public, licensed code and Microsoft's public
526reference give most of them. Enum values are still mostly **unmeasured**.
526 527
527§8.2 question 6 ("DXGI, `PresentX`, or both") is **partly answered**: public GDKX code presents through 528§8.2 question 6 ("DXGI, `PresentX`, or both") is **partly answered**: public GDKX code presents through
528`PresentX` and frame events only. That the game does the same is a **hypothesis**; the game is not observed. 529`PresentX` and frame events only. That the game does the same is a **hypothesis**; the game is not observed.
@@ -535,6 +536,83 @@ Leonida's loader will report them as unimplemented; a Vulkan present-array imple
535need a swapchain registry, which does not exist yet. SCARAB's no-op behavior is not acceptable for 536need a swapchain registry, which does not exist yet. SCARAB's no-op behavior is not acceptable for
536Leonida because it would silently present nothing. 537Leonida because it would silently present nothing.
537 538
539### 7.1 Public sources for the presentation and device ABI
540
541Microsoft's public GDK graphics reference does not document the console interfaces. The
542[graphics index](https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference.txt) lists 528 pages,
5438 of them under `d3d12_xs` (six enums, `D3D10CreateBlob`, `DXGI_ADAPTER_DESC2`); the `ID3D12CommandQueue`
544page lists the PC methods only, and there is no `PresentX`, `SetFrameIntervalX` or `D3D12XboxCreateDevice`
545page, while the `D3D12_ROOT_SIGNATURE_FLAGS` pages return 404. The slots and layouts below therefore come from public code
546that is not Microsoft documentation: XCL and the Microsoft samples measure other titles' runtimes, ebiten and
547Mesa are public code compiled against the GDK headers, and docs.xbox.com is Microsoft's reference.
548
549| Item | Public source and value | Verdict on this repository's provisional value |
550|---|---|---|
551| Queue `PresentX` slot | `ivall/xcl` (GPL-2.0-only; facts only) dispatches `PresentX(planeCount, planes, params)` at queue slot **30** in the older runtime layout (XDefiant, Minecraft, Fortnite) and slot **32** in a newer one (Unicorn Overlord), with the same SDK version but two methods inserted before `Signal` ([`present.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/present.rs), [`real.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/real.rs), [`HANDOFF.md`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/HANDOFF.md)). | **Confirms a slot, not one number.** The version moves it; trace the game's runtime, do not hard-code either value. |
552| Queue `SuspendX` / `ResumeX` slots | No public slot in XCL or the samples. The signatures are `SuspendX(UINT flags)` and `ResumeX()` from the Apache-2.0 ebiten C++ binding ([`api_microsoftgdk_windows.go`](https://github.com/hajimehoshi/ebiten/blob/d438df689b19544c82543ad522b36be86a5a60b7/internal/graphicsdriver/directx/api_microsoftgdk_windows.go)); the samples call `SuspendX(0)` and `ResumeX()`. | **Leaves provisional.** |
553| `D3D12XBOX_PRESENT_PLANE_PARAMETERS` | 0x48 bytes on x64: `Token` u64 @0x00, `ResourceCount` u32 @0x08, `ppResources` @0x10, `pSrcViewRects` @0x18, `pDestPlacementBase` @0x20 (four floats), `ColorSpace` int32 @0x28, `ScaleFilter` int32 @0x2C, `ExtendedDescCount` u32 @0x30, `pExtendedDescs` @0x38, `Flags` u32 @0x40. ebiten's Go mirror of the GDK struct ([`d3d12_windows.go`](https://github.com/hajimehoshi/ebiten/blob/d438df689b19544c82543ad522b36be86a5a60b7/internal/graphicsdriver/directx/d3d12_windows.go)); XCL independently reads token @0, count @8 and resource list @0x10 ([`present.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/present.rs)). | **Confirms** the field order, types and size in `xbox_present_types.h` and `xbox_present.h`. `ScaleFilter` and `Flags` values stay ours. |
554| `D3D12XBOX_PRESENT_PARAMETERS` | 0x20 bytes on x64: `ImmediateThresholdPercent` float @0x00, `ViewCount` u32 @0x04, `ExtendedDescCount` u32 @0x08, `pExtendedDescs` @0x10, `Flags` u32 @0x18. Mesa's MIT Xbox WGL backend sets `Flags = D3D12XBOX_PRESENT_FLAG_IMMEDIATE` for an immediate present ([`d3d12_wgl_framebuffer_xbox.cpp`](https://github.com/openbsd/xenocara/blob/f3893fcf57cec33c2bd4275edd8ca6d865e3adf2/lib/mesa/src/gallium/winsys/d3d12/wgl/d3d12_wgl_framebuffer_xbox.cpp)); ebiten has the field order. The flag's numeric value is not public. | **Corrects** "at least this field": the repository's one-float struct is the first 4 bytes of a 0x20-byte object. Safe as a pointer prefix; never size a copy by it. |
555| Device frame calls | Slots **78** `SetFrameIntervalX`, **79** `ScheduleFrameEventX`, **80** `WaitFrameEventX`, **81** `GetFrameStatisticsX` (0-based, `QueryInterface` = 0). XCL's [`frame.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/frame.rs) numbers the calls and documents the arguments; ebiten's `ID3D12Device` vtable has `SetFrameIntervalX`/`ScheduleFrameEventX`/`WaitFrameEventX` at 78/79/80 and leaves 81 unnamed ([`d3d12_windows.go`](https://github.com/hajimehoshi/ebiten/blob/d438df689b19544c82543ad522b36be86a5a60b7/internal/graphicsdriver/directx/d3d12_windows.go)). | **Confirms** all four slots, two independent public sources. |
556| `D3D12XBOX_FRAME_STATISTICS` | The MIT FramePacing sample names `Type`, `Interval`, `Event`, `Render`/`Present`/`Display` with `PlaneIndex`, and `Display.PercentScanned`; it treats `S_FALSE` or a count below the request as "not available yet" ([`FramePacing.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Samples/Graphics/FramePacing/FramePacing.cpp)). XCL's implementation writes `Type` at +0, origin at +0x10 and flip at +0x18, so its record is at least 0x20 bytes ([`frame.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/frame.rs)). | **Partly confirms** the field meanings and the two timestamp offsets; the full record layout and the union members stay unmeasured. |
557| Token and timeout | `D3D12XBOX_FRAME_PIPELINE_TOKEN` is a 64-bit integer with 0 as `..._NULL` (ebiten). Microsoft's Game Streaming page says `WaitFrameEventX` returns the token at frame start and `PresentX` sends it with the frame to the client ([Learn](https://learn.microsoft.com/en-us/gaming/gdk/docs/features/common/game-streaming/game-streaming-latency-compensation-deep-dive)). XCL's implementation issues 48-bit nonzero tokens (mask `0xFFFF_FFFF_FFFF`), i.e. it leaves the top 16 bits unused, returns `S_FALSE` on a finite timeout, writes the token on timeout only with flag 2, and returns `E_INVALIDARG` for an unscheduled event; `ScheduleFrameEventX` returns `S_FALSE` or `0x10000000` when it starts the clock. | **Confirms** the 64-bit storage and the `0` null. **Contradicts** this layer's `HRESULT_FROM_WIN32(WAIT_TIMEOUT)` on timeout (XCL: `S_FALSE`) and `ERROR_INVALID_STATE` for an unscheduled event (XCL: `E_INVALIDARG`); both are recorded here, not changed in this PR. The 48-bit range is XCL's implementation choice, not a documented mask. |
558| `D3D12XBOX_CREATE_DEVICE_PARAMETERS` | Public field names and (for ebiten's version) x64 offsets: `Version` @0, `ProcessDebugFlags` @4, `GraphicsCommandQueueRingSizeBytes` @8, `pOffchipTessellationBuffer` @0x10, `GraphicsScratchMemorySizeBytes` @0x18, `ComputeScratchMemorySizeBytes` @0x1C, `DisableGeometryShaderAllocations` @0x20, `DisableTessellationShaderAllocations` @0x24, `DisableDXR` @0x28, `DisableAutomaticDPBBBreakBatchEvents` @0x2C, `pDXRStackBuffer` @0x30, `DXRStackBufferOverrideSizeBytes` @0x38, `CreateDeviceFlags` @0x3C, `AutoHDRPaperWhiteLevelNits` @0x40, `DisableAutomaticCommandSegmentChaining` @0x44 ([`d3d12_windows.go`](https://github.com/hajimehoshi/ebiten/blob/d438df689b19544c82543ad522b36be86a5a60b7/internal/graphicsdriver/directx/d3d12_windows.go)). The MIT samples add `AmplificationShaderIndirectArgsBufferSize` and `AmplificationShaderPayloadBufferSize` by name ([`SimpleDeviceAndSwapChain.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Samples/IntroGraphics/SimpleDeviceAndSwapChain/SimpleDeviceAndSwapChain.cpp)). | **Partly confirms.** Seventeen named fields cover the first 18 words (word 3 is the x64 alignment pad at 0x0C); the samples name two more fields without a public layout. A 24-word (96-byte) block still has at least four words with no public name or meaning. |
559| Root-signature flags `0x03000000` | Not documented: the [graphics index](https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference.txt) has no `D3D12_ROOT_SIGNATURE_FLAGS` entry, and both URL forms under `docs.xbox.com/reference/graphics/` (`d3d12` and `d3d12_xs`) return 404. | **Leaves provisional.** Keep masking the byte on a copy; no public bit meaning. |
560| `CheckFeatureSupport(D3D12_OPTIONS)` with 0x40 bytes | Microsoft publishes the 15-field PC structure, 0x3C bytes, with no extra member ([`D3D12_FEATURE_DATA_D3D12_OPTIONS`](https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_feature_data_d3d12_options_public.md)); its `CheckFeatureSupport` page says a size mismatch is `E_INVALIDARG` ([`CheckFeatureSupport`](https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_checkfeaturesupport_public.md)). XCL measured XDefiant asking 0x40 and retries with 0x3C, zeroing the tail ([`HANDOFF.md`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/HANDOFF.md), [`real.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/real.rs)). | **Confirms the 0x40 request size; leaves the extra 4 bytes unknown.** The measurement fixes the size, not the field. No public source names them; `MaxGPUVirtualAddressBitsPerProcess` is a member of the separate `D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT`, not a published member of `D3D12_OPTIONS`. The repository's accept-and-zero-tail behaviour matches the observed failure and is safe. |
561
562The call shapes are the samples' (and XCL's) shapes: `SetFrameIntervalX(output, interval_us, period, flags)`,
563`ScheduleFrameEventX(type, offset_us, ancillary, flags)`,
564`WaitFrameEventX(type, timeout_ms, ancillary, flags, &token)`,
565`GetFrameStatisticsX(token, type_mask, &count, stats)`, and `PresentX(plane_count, planes, params)`. Type 0 is
566the frame origin (the samples use only it); XCL also uses 1 and 2 for later points in the frame. The
567`D3D12XBOX_SCHEDULE_FRAME_OBJECT_LIST` / `D3D12XBOX_WAIT_FRAME_OBJECT_LIST` ancillary block is
568`{ u32 count; HANDLE* objects @0x08; i32* signaled @0x10 }` per XCL.
569
570The meanings the public samples give the create-device words: `Version` is the SDK version (`D3D12_SDK_VERSION`
571in `SimpleDeviceAndSwapChain`), `GraphicsCommandQueueRingSizeBytes` is the command-queue ring,
572`GraphicsScratchMemorySizeBytes` and `ComputeScratchMemorySizeBytes` are shader scratch memory,
573`D3D12XBOX_DEFAULT_SIZE_BYTES` asks for the runtime's default, the `Disable*` BOOLs save title memory when the
574stage is unused, and `CreateDeviceFlags` is `D3D12XBOX_CREATE_DEVICE_FLAG_NONE` in the sample. XCL logs word 0
575as the SDK version. ebiten also gives the `D3D12XBOX_PROCESS_DEBUG_FLAG_*` values (`DEBUG` 1, `INSTRUMENTED`
5760x00100000, `NULL_GPU` 0x00400000, `ENABLE_COMMON_STATE_PROMOTION` 0x01000000, `ENHANCED_VALIDATION`
5770x02000000); these are process debug flags, not `CreateDeviceFlags` bits. The `0x03000000` root-signature bit
578is separate and has no public meaning.
579
580The provisional layouts in the split `xbox_present_types.h` on the PresentX-capture branch (not yet on main) are
581the same as `xbox_present.h`: the plane struct agrees byte for byte with the 0x48 layout above, the
582present-parameter struct is the 4-byte prefix of the 0x20 console object, and `uint64_t Token` is the confirmed
583width. Its colour-space values are the documented DXGI numbers; `ScaleFilter` and the plane flags are still ours.
584The 60/30/120 Hz periods (`16667`/`33333`/`8333` us) are the public ones; this layer does not carry 24/40/50 Hz.
585
586Still unknown after this search: the queue slots of `SuspendX`/`ResumeX`; which of the two queue layouts the
587game's runtime uses; the values of `ScaleFilter` and the plane flags; the full `D3D12XBOX_FRAME_STATISTICS`
588layout (the samples name `Type`, `Interval`, `Event`, `Render`/`Present`/`Display.PlaneIndex` and
589`Display.PercentScanned`, but no public byte layout); the four extra `D3D12_OPTIONS` bytes; the last words of
590the create-device block; the `0x03000000` meaning; and the console's behaviour for a null, repeated or
591out-of-order token.
592
593### 7.2 What the public samples give Bink, XAudio2 and FidelityFX
594
595- **FidelityFX.** The MIT `Kits/AMDTK` GDK backend includes `<xmem.h>`, calls
596 `XMemGetWorkingSetStatistics(XMEM_WORKING_SET_TITLE, ...)` for its memory report, and on Scarlett creates
597 resources with `CreateCommittedResourceX` and a `D3D12XBOX_RESOURCE_DESC` carrying DCC options
598 ([`ffx_gdk.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Kits/AMDTK/fidelityfx/src/backends/gdk/ffx_gdk.cpp)).
599 Its frame-interpolation swapchain calls the title's `PresentX` callback with `framePipelineTokenOriginal`
600 and `framePipelineTokenToSubmit`; the FSR3 sample can pass `D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL` for the
601 real frame ([`ffx_gdk.h`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Kits/AMDTK/fidelityfx/include/FidelityFX/host/backends/gdk/ffx_gdk.h),
602 [`DeviceResources.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Samples/Graphics/AMDFidelityFX_FSR3FrameInterpolation/DeviceResources.cpp)).
603 This matches the three `xmem` imports of the shipped `amd_fidelityfx_upscaler_xbox.dll`; only the
604 allocation/capability part transfers, because that DLL is an upscaler and the public sample is the
605 frame-interpolation swapchain.
606- **XAudio2.** `SimplePlaySound` calls `XAudio2Create(&pXAudio2, 0)` in `InitializeXAudio`, after the device
607 resources are made, and sets `XAUDIO2_DEBUG_CONFIGURATION` only in debug. XMA2 playback needs the compressed
608 audio in APU memory: `ApuAlloc(&m_xmaMemory, nullptr, bytes, SHAPE_XMA_INPUT_BUFFER_ALIGNMENT)`, filled with
609 `memcpy`, and freed with `ApuFree`
610 ([`SimplePlaySound.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Samples/Audio/SimplePlaySound/SimplePlaySound.cpp)).
611 That is the console-specific part a title using XMA reaches; the sample does not show a slot or an ABI addition
612 beyond it.
613- **Bink.** No Bink use exists in the public GDK samples (the tree has none), so there is nothing to borrow;
614 the repository's existing `Bink2Scarlett.dll` path stands.
615
538## 8. Memory, heaps, compression and tiling 616## 8. Memory, heaps, compression and tiling
539 617
540SCARAB's `memory-adapter` is also a seam only: every flag is declared with value 0 and the header 618SCARAB's `memory-adapter` is also a seam only: every flag is declared with value 0 and the header
@@ -562,9 +640,12 @@ None of these has a numeric value in SCARAB, and none has a layout. The tiling/D
562therefore **described, not answered**: the names tell Leonida what to look for in the game's 640therefore **described, not answered**: the names tell Leonida what to look for in the game's
563resource descriptions, and the copy/state names tell it which compression transitions the game 641resource descriptions, and the copy/state names tell it which compression transitions the game
564may perform, but the actual swizzle and DCC metadata format still has to come from Leonida's own 642may perform, but the actual swizzle and DCC metadata format still has to come from Leonida's own
565`tools/amd_swizzle.py` / `tools/tile_probe.py` work or from the console `xg_xs.dll` functions 643`tools/amd_swizzle.py` (the mode's equation, read from the public AMD header and evaluated to
566`XGComputeOptimalSwizzleMode`, `XGEncodeDCC`, `XGDecodeDCC` (SCARAB names them; it does not call 644detile with), `tools/tile_probe.py` (the block-endpoint feature and smoothness score measured on
567them). 645a blob) and `tools/swizzle_search.py` (the brute-force search over every bit ordering with the
646right x/y split inside a tile, scored with `tile_probe`), or from the console `xg_xs.dll`
647functions `XGComputeOptimalSwizzleMode`, `XGEncodeDCC`, `XGDecodeDCC` (SCARAB names them; it does
648not call them).
568 649
569Two names are worth adding to the trace filter because they affect correctness, not just 650Two names are worth adding to the trace filter because they affect correctness, not just
570performance: `D3D12CONS_RESOURCE_STATE_PRESERVE_*` (a barrier that preserves compressed data) and 651performance: `D3D12CONS_RESOURCE_STATE_PRESERVE_*` (a barrier that preserves compressed data) and
@@ -577,19 +658,19 @@ Mapping to [d3d12_vulkan.md §8.2](d3d12_vulkan.md). "Answered" means a fact Leo
577against; "described" means names or constraints but no layout; "still unknown" means no usable 658against; "described" means names or constraints but no layout; "still unknown" means no usable
578evidence. 659evidence.
579 660
580| Leonida unknown | Status after SCARAB | What is actually new | 661| Leonida unknown | Status after SCARAB (and §7.1) | What is actually new |
581|---|---|---| 662|---|---|---|
582| #1 device entry point and 24-word params | **described** | The separate console device export exists at ordinal 13 and is named `D3D12ConsCreateDevice` internally / `D3D12XboxCreateDevice` publicly; the params struct is named `D3D12CONS_CREATE_DEVICE_PARAMETERS`. Layout and field meanings are still unknown. | 663| #1 device entry point and 24-word params | **described** | The separate console device export exists at ordinal 13 and is named `D3D12ConsCreateDevice` internally / `D3D12XboxCreateDevice` publicly; the params struct is named `D3D12CONS_CREATE_DEVICE_PARAMETERS`. Public sources name 17 fields and their x64 offsets, plus two more field names; a 24-word block still has at least four words unaccounted (§7.1). |
583| #2 device/heap/queue/command-list slots | **still unknown** | SCARAB has no console slot map. Its appended-after-GCL6 model conflicts with the SDK's GCL8/GCL9 methods (§5.1). Do not use it as a slot source. | 664| #2 device/heap/queue/command-list slots | **partly measured** | SCARAB has no console slot map. Its appended-after-GCL6 model conflicts with the SDK's GCL8/GCL9 methods (§5.1). Public §7.1 gives the presentation slots (device 78-81, queue 30/32); the heap and command-list slot map is still unknown. Do not use SCARAB as a slot source. |
584| #3 root signature → `s0..s31` | **still unknown** | Only flag names (`D3D12CONS_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI`, `_RAYTRACING`); no mapping. Leonida's own register-based/spill facts already go further. | 665| #3 root signature → `s0..s31` | **still unknown** | Only flag names (`D3D12CONS_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI`, `_RAYTRACING`); no mapping. Leonida's own register-based/spill facts already go further. |
585| #4 descriptor bytes and increments | **still unknown** | No measured increment. `D3D12CONS_DESCRIPTOR_HEAP_TYPE_SAMPLER_UNBOUNDED` is a new name, not a size. | 666| #4 descriptor bytes and increments | **still unknown** | No measured increment. `D3D12CONS_DESCRIPTOR_HEAP_TYPE_SAMPLER_UNBOUNDED` is a new name, not a size. |
586| #5 VA range / arena capacity | **still unknown** | — | 667| #5 VA range / arena capacity | **still unknown** | — |
587| #6 DXGI vs `PresentX` | **described** | `PresentX` is a queue method; ≤2 planes, ≤8 views, four flag names. Public samples give the call sequence and argument counts (no DXGI swapchain; frame events + `PresentX`), see §7. No slot or layout; game itself not observed. | 668| #6 DXGI vs `PresentX` | **partly answered** | `PresentX` is a queue method; public code gives its queue slot (30 in the older runtime layout, 32 in the newer) and the x64 plane/present layouts (§7.1). Public samples give the call sequence and argument counts (no DXGI swapchain; frame events + `PresentX`), see §7. The game itself is not observed. |
588| #7 standard AS vs BVH builder | **still unknown** | New names: `D3D12ConsRehydrateRaytracingAccelerationStructure`, `D3D12CONS_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_DEHYDRATE`, `DispatchRaysX`, `DispatchRaysDimensionsX`. No layouts. | 669| #7 standard AS vs BVH builder | **still unknown** | New names: `D3D12ConsRehydrateRaytracingAccelerationStructure`, `D3D12CONS_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_DEHYDRATE`, `DispatchRaysX`, `DispatchRaysDimensionsX`. No layouts. |
589| #8 XDXR struct layouts | **still unknown** | Nothing from SCARAB. Measured since from `XboxBvhBuilder.dll` itself, see [xdxr.md](xdxr.md). | 670| #8 XDXR struct layouts | **still unknown** | Nothing from SCARAB. Measured since from `XboxBvhBuilder.dll` itself, see [xdxr.md](xdxr.md). |
590| #9 tiled data layout / DCC | **described** | Flag, copy and state names; no values, no swizzle. | 671| #9 tiled data layout / DCC | **described** | Flag, copy and state names; no values, no swizzle. |
591| #10 binning/DCC/VRS/WMMA usage | **described** | `D3D12CONS_PIPELINE_STATE_FLAG_DISABLE_AUTO_DPBB`, `_DISABLE_RB_PLUS`, `RSSetShadingRateX`; usage still unknown. | 672| #10 binning/DCC/VRS/WMMA usage | **described** | `D3D12CONS_PIPELINE_STATE_FLAG_DISABLE_AUTO_DPBB`, `_DISABLE_RB_PLUS`, `RSSetShadingRateX`; usage still unknown. |
592| #11 `CheckFeatureSupport` answers | **still unknown** | — | 673| #11 `CheckFeatureSupport` answers | **partly measured** | A console title asks `D3D12_OPTIONS` with 0x40 bytes where the PC struct is 0x3C (XCL/XDefiant); the extra 4 bytes are unnamed. The layer answers the PC fields and zeroes the tail (§7.1). |
593| #12 async compute / copy queues | **described** | `CreateCommandQueueX` creates a shader-based queue, which the UMD says only supports `D3D12_COMMAND_LIST_TYPE_COMPUTE`; `SuspendX`/`ResumeX` exist. No params. | 674| #12 async compute / copy queues | **described** | `CreateCommandQueueX` creates a shader-based queue, which the UMD says only supports `D3D12_COMMAND_LIST_TYPE_COMPUTE`; `SuspendX`/`ResumeX` exist. No params. |
594| #18 heap aliasing / reserved | **still unknown** | — | 675| #18 heap aliasing / reserved | **still unknown** | — |
595| console IIDs | **10 exported; 4 not exported** | The DMA list IID is proven and the other nine console GUIDs are reported. SCARAB's provenance reports that the four command-list IIDs are not runtime exports, so they have no ordinal; this package has no D3D12 DLL to read. They stay unresolved until a title trace or another artifact supplies them. | 676| console IIDs | **10 exported; 4 not exported** | The DMA list IID is proven and the other nine console GUIDs are reported. SCARAB's provenance reports that the four command-list IIDs are not runtime exports, so they have no ordinal; this package has no D3D12 DLL to read. They stay unresolved until a title trace or another artifact supplies them. |
@@ -638,9 +719,7 @@ These are stated plainly because a future reader will otherwise trust the wrong
6389. **The Wine results are not reproducible here.** "All 7 DLLs load", "the whole console graphics 7199. **The Wine results are not reproducible here.** "All 7 DLLs load", "the whole console graphics
639 stack runs on Linux", and the DMA round-trip are **Reported**. This page did not open 720 stack runs on Linux", and the DMA round-trip are **Reported**. This page did not open
640 `d3d12_xs.dll` and did not run Wine. Nothing in this doc depends on them. 721 `d3d12_xs.dll` and did not run Wine. Nothing in this doc depends on them.
64110. **`docs/dll-surface.md` is stale.** It says the console `d3d12_xs.dll` is "not obtainable" 72210. **The package's D3D12 DLL exports do not contain the four command-list IIDs with 1.0.2.1.**
642 (line 83), while `d3d12_xs-findings.md` documents the acquired binary. Use the findings doc.
64311. **The package's D3D12 DLL exports do not contain the four command-list IIDs with 1.0.2.1.**
644 The package has 16 DLLs and no D3D12 runtime DLL, and `gameos.xvd` is encrypted; SCARAB's 723 The package has 16 DLLs and no D3D12 runtime DLL, and `gameos.xvd` is encrypted; SCARAB's
645 provenance says the runtime does not export these four IIDs. There is no export ordinal to 724 provenance says the runtime does not export these four IIDs. There is no export ordinal to
646 read in this package or in the vendor DLL. A `QueryInterface` trace from the running title is 725 read in this package or in the vendor DLL. A `QueryInterface` trace from the running title is
@@ -663,6 +742,10 @@ code**. It records interface names, ordinal numbers and 16-byte GUIDs, which are
663the source file and line cited. The 28 standard GUIDs are also facts from the Windows SDK; the 10 742the source file and line cited. The 28 standard GUIDs are also facts from the Windows SDK; the 10
664console GUIDs are reported from the vendor runtime and are attributed to SCARAB. 743console GUIDs are reported from the vendor runtime and are attributed to SCARAB.
665 744
745The public sources in §7.1 are used as facts only: XCL is GPL-2.0-only (no code copied), ebiten is Apache-2.0,
746the Mesa WGL file is MIT, and the Microsoft samples are MIT. Only names, numbers, field offsets and slot indices
747are taken from them; no code or prose is copied.
748
666If any code is later adapted from SCARAB, it must carry the SCARAB copyright and 749If any code is later adapted from SCARAB, it must carry the SCARAB copyright and
667`GPL-3.0-only` notice, and the file must say exactly which SCARAB file it came from. The checker 750`GPL-3.0-only` notice, and the file must say exactly which SCARAB file it came from. The checker
668in `tools/d3d12_xs_surface.py` is original code written for this repository; it reads only the 751in `tools/d3d12_xs_surface.py` is original code written for this repository; it reads only the
diff --git a/docs/design.md b/docs/design.md
index 6b04965c9..395bda055 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -37,7 +37,6 @@ tools/ Python analysis tools (no game data inside)
37 pe_inspect.py PE headers, sections, entropy, imports sorted by where they resolve, .pdata, TLS 37 pe_inspect.py PE headers, sections, entropy, imports sorted by where they resolve, .pdata, TLS
38 rpf_probe.py RPF header survey of a game folder 38 rpf_probe.py RPF header survey of a game folder
39 manifest.py SHA-256 manifest of a game folder (create), plus a verify subcommand 39 manifest.py SHA-256 manifest of a game folder (create), plus a verify subcommand
40 manifest.py SHA-256 manifest of a game folder, plus a --verify mode
41 inline_scan.py inline command-list writes in an image, and whether each checks the cursor limit first 40 inline_scan.py inline command-list writes in an image, and whether each checks the cursor limit first
42scripts/ 41scripts/
43 first_look.ps1 run once the exe arrives: the full report set for it 42 first_look.ps1 run once the exe arrives: the full report set for it
@@ -149,9 +148,11 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b
149 148
150``` 149```
151dotnet build tools\rpf9dump\rpf9dump.csproj -c Release -o <work>\tools\rpf9dump 150dotnet build tools\rpf9dump\rpf9dump.csproj -c Release -o <work>\tools\rpf9dump
152rpf9dump models|textures <archive.rpf> <work>\assets 151rpf9dump models <archive.rpf> <work>\assets
152rpf9dump textures <archive.rpf> <work>\assets
153rpf9dump ttpf <pool.ttpf> <work>\assets\ttpf 153rpf9dump ttpf <pool.ttpf> <work>\assets\ttpf
154rpf9dump audio <audio.rpf> <work>\assets 154rpf9dump audio <audio.rpf> <work>\assets
155rpf9dump xma <audio.rpf> <work>\assets
155python -I make_game.py --stages assets # everything, in order; skips what is done 156python -I make_game.py --stages assets # everything, in order; skips what is done
156``` 157```
157 158
@@ -159,9 +160,10 @@ Full-scan indexes are also saved to `%LOCALAPPDATA%\RpfPreview\Indexes`, so the
159 160
160## Other prepared pieces 161## Other prepared pieces
161 162
162- `tools\shader_profile.py` writes the instruction profile to `<work>\shaders\profile.json`. An earlier corpus 163- `python -I tools\shader_profile.py <work>\shaders\dxbc\disasm` writes the instruction profile to
163 run reported 551 distinct mnemonics, with 204 accounting for 99% of instructions. Those counts predate the 164 `<work>\shaders\dxbc\profile.json` by default. Use `--out` to choose a different file. An earlier corpus run
164 filter for assembler directives and comments. 165 reported 551 distinct mnemonics, with 204 accounting for 99% of instructions. Those counts predate the filter
166 for assembler directives and comments.
165- `tools\shader_ir.py`: parses every disassembled instruction into opcode, typed operands (s/v registers and 167- `tools\shader_ir.py`: parses every disassembled instruction into opcode, typed operands (s/v registers and
166 ranges, NSA register lists, constants, literals, export targets, interpolation attributes), modifiers and 168 ranges, NSA register lists, constants, literals, export targets, interpolation attributes), modifiers and
167 encoding bytes. On 1,000 shaders, 12 of 2.2M operands were left untyped before the last fix. This is the front end 169 encoding bytes. On 1,000 shaders, 12 of 2.2M operands were left untyped before the last fix. This is the front end
@@ -186,8 +188,9 @@ Full-scan indexes are also saved to `%LOCALAPPDATA%\RpfPreview\Indexes`, so the
186 188
187## Shader translation (RDNA → SPIR-V) 189## Shader translation (RDNA → SPIR-V)
188 190
189`tools\rdna2spirv.py` (needs `spirv-as`/`spirv-val` on PATH: Vulkan SDK, or `spirv-tools` in WSL) translates parsed RDNA 191`tools\rdna2spirv.py` (needs `spirv-val` on PATH — Vulkan SDK, or `spirv-tools` in WSL — and `spirv-as` too
190code to SPIR-V assembly, assembles it with `spirv-as`, and validates it with `spirv-val` (Vulkan 1.2). It runs one 192unless `--assembler python` assembles in process with `tools\spirv_asm.py`) translates parsed RDNA code to
193SPIR-V assembly, assembles it (`spirv-as` by default), and validates it with `spirv-val` (Vulkan 1.2). It runs one
191lane per invocation and keeps VGPRs and SGPRs as uint arrays with exact bit patterns. Version 0 treated EXEC as 194lane per invocation and keeps VGPRs and SGPRs as uint arrays with exact bit patterns. Version 0 treated EXEC as
192all-ones and covered only branch-free vertex and pixel shaders with no memory loads: common float and integer ALU 195all-ones and covered only branch-free vertex and pixel shaders with no memory loads: common float and integer ALU
193ops and exports to `gl_Position`, params and MRTs. Unsupported instructions are reported by name, never guessed. 196ops and exports to `gl_Position`, params and MRTs. Unsupported instructions are reported by name, never guessed.
@@ -202,11 +205,22 @@ could overflow to inf), and pixel interpolation (`v_interp_p1/p2/mov` become fra
202location). MODE writes (`s_setreg`) model the f16/f64 rounding field, FP_ROUND[3:2], the only MODE field the 205location). MODE writes (`s_setreg`) model the f16/f64 rounding field, FP_ROUND[3:2], the only MODE field the
203corpus writes; other MODE writes are refused (see Known approximations). 206corpus writes; other MODE writes are refused (see Known approximations).
204 207
208`--opt` is off by default and runs a basic-block peephole pass, `tools/spirv_opt.py`, over the emitted
209module before it is assembled: register store-to-load forwarding, `OpAccessChain` CSE, dead-store
210elimination, `OpSelect`/`OpCopyObject` folding and DCE. Only Function-scope variables that do not escape
211are tracked, and a variable with any dynamic index is excluded from whole-function dead-slot elimination.
212
213Measured on five hand-written pixel fixtures from `tests/semantic/fixtures/disasm`, with every result still
214passing `spirv-val --target-env vulkan1.2`: `ps_ops` 76→33 instructions and 7,876→4,516 bytes, `ps_flat`
21560→22 and 4,560→1,676, `ps_sdwa` 61→19 and 5,720→2,192, `ps_vcc_x2` 63→26 and 5,260→2,552, and
216`ps_fnan_med3` 76→26 and 8,060→4,264.
217
205### GPU tests (RTX 4060 Ti) 218### GPU tests (RTX 4060 Ti)
206 219
207`runtime\test\vk_harness.cpp` (build: `runtime\build\test\build_harness.cmd`, MSVC + the Vulkan 1.4 headers from 220`runtime\test\vk_harness.cpp` (CMake target `vk_harness`, built by `scripts\build_runtime.ps1` or
208Hookshot's CPM cache, loading `vulkan-1.dll` at runtime) draws one triangle with a given VS + FS into an RGBA32F 221`cmake --build runtime\build --target vk_harness`; see "Build the test programs" in `docs/testing.md`. It loads
209target and dumps the floats. Test shaders are in `<work>\gputest`. 222`vulkan-1.dll` at runtime.) draws one triangle with a given VS + FS into an RGBA32F target and dumps the floats.
223Test shaders are in `<work>\gputest`.
210 224
211- **`VS_Passthrough` (translated) is bit-exact.** All 64×64 pixels are written, and `param0.xy` = (u, 1 − v) with max 225- **`VS_Passthrough` (translated) is bit-exact.** All 64×64 pixels are written, and `param0.xy` = (u, 1 − v) with max
212 error **0**, with zw = (0, 1) as exported. This covers the VertexIndex input, integer/float ALU, inline constants, 226 error **0**, with zw = (0, 1) as exported. This covers the VertexIndex input, integer/float ALU, inline constants,
@@ -248,43 +262,49 @@ How the generated SPIR-V expects the runtime to work:
248| Piece | Contract | 262| Piece | Contract |
249|---|---| 263|---|---|
250| Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | 264| Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. |
251| Execution model | One invocation = one lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). | 265| Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. |
252| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | 266| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. |
253| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases). Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. A pixel lane that was inactive at the last `exp ... vm` it executed is discarded, and on a path without one, a lane inactive at the end (EXEC is kept at the export only where a path can write it afterwards). **The `vm` rule is from the RDNA2 ISA reference guide (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used), not measured on hardware**; checked on the CPU by `tests/semantic/test_export_valid_mask.py`. VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), **not yet GPU-verified**. Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately.; also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately. | 267| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. |
254| `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1`, `orn2`, `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | 268| `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. |
255| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound sits at 16. Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. | 269| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). |
256| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | 270| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. |
257| Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | 271| Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. |
258| Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). Both checks for clean listings and re-anchoring use the parsed operand count to apply this exception only to unused sources. A used source encoded as 0 reads `s0` and is never treated as inline zero. `tests/semantic/test_printed_encoding.py` checks used `SRC1`/`SRC2` and an unused field with synthetic listings. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. | 272| Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). Both checks for clean listings and re-anchoring use the parsed operand count to apply this exception only to unused sources. A used source encoded as 0 reads `s0` and is never treated as inline zero. `tests/semantic/test_printed_encoding.py` checks used `SRC1`/`SRC2` and an unused field with synthetic listings. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. A reachable instruction that falls through into words llvm-mc skipped (it printed no instruction there) is rejected too, as `fall-through into undecodable words`: until SHADER-813 the reachable path ended there without a word, so everything after the gap (exports, stores) was dropped from a module that still passed `spirv-val`. No VS/PS of the corpus has such a gap on a reachable path; in the FidelityFX FSPX programs it is the `v_dot4_i32_i8 ... op_sel` words LLVM 23 cannot decode (`docs/fspx.md`), so those programs are now refused instead of translated without their stores, until those words are decoded (#2038, #2323). `tests/test_rdna2spirv_decode.py` (`test_fall_through_into_undecodable_words_is_refused`). |
259| Printed encodings | A listing is LLVM's text for what it decoded, not the bytes it read, so the translator checks the two against each other: the re-anchoring above for listings with undecodable words, and, for every other listing whose header names its code range and whose blob sits next to it (`fssm/`, or `fspx/` for FSPX), each instruction's printed encoding against the bytes at its offset, with the same exceptions (`same_encoding`). A difference is `Unsupported`, naming the instruction, its offset and both byte strings, instead of a translation of the field as 0. The case that prompted it: llvm-mc's gfx1013 decoder (LLVM 21.1.8) drops the VOP3 `op_sel` bits (word 0, bits 14:11) of a 16-bit VOPC compare: `0a 08 a9 d4 01 05 02 00` disassembles as `v_cmp_lt_u16_e64 s10, v1, v2` and re-encodes with the bits cleared (its assembler rejects `op_sel` on VOPC for gfx1013 and gfx1030 alike). Counted over the 1.0.2.1 corpus: the 25,030 clean listings hold 30,335,381 instructions, and none differs from its bytes beyond those exceptions (754); the 166 16-bit VOPC compares (154 shaders, all `f16`) have `op_sel` clear. Hand-written listings, `run_gpu_tests.py`'s `code 0x0..0x0 (synthetic)` listings and a blob that doesn't hold the listing's code range (the tests' header-only FSSM) are not checked. `tests/semantic/test_printed_encoding.py` (a dropped VOPC `op_sel`, a later instruction, the SRC2 exception, and the unchecked cases). | 273| VOP3 opcode 0x140 | LLVM disassembly of the synthetic words in `tests/test_rdna2_decode.py` gives `v_mad_legacy_f32` on gfx1010 through gfx1013 and `v_fma_legacy_f32` on gfx1030. The direct decoder defaults to gfx1013, matching the disassembler CLI. Checked by the unit test `test_vop3_legacy_mad_fma_target` in `tests/test_rdna2_decode.py`, which decodes the same words directly and runs the Python disassembler backend for gfx1013 and gfx1030. |
274| Printed encodings | A listing is LLVM's text for what it decoded, not the bytes it read, so the translator checks the two against each other: the re-anchoring above for listings with undecodable words, and, for every other listing whose header names its code range and whose blob sits next to it (`fssm/`, or `fspx/` for FSPX), each instruction's printed encoding against the bytes at its offset, with the same exceptions (`same_encoding`). A difference is `Unsupported`, naming the instruction, its offset and both byte strings, instead of a translation of the field as 0. The case that prompted it: llvm-mc's gfx1013 decoder (LLVM 21.1.8) drops the VOP3 `op_sel` bits (word 0, bits 14:11) of a 16-bit VOPC compare: `0a 08 a9 d4 01 05 02 00` disassembles as `v_cmp_lt_u16_e64 s10, v1, v2` and re-encodes with the bits cleared (its assembler rejects `op_sel` on VOPC for gfx1013 and gfx1030 alike). Counted over the 1.0.2.1 corpus: the 25,030 clean listings hold 30,335,381 instructions, and none differs from its bytes beyond those exceptions (754); the 166 16-bit VOPC compares (154 shaders, all `f16`) have `op_sel` clear. Hand-written listings, `run_gpu_tests.py`'s `code 0x0..0x0 (synthetic)` listings and a blob that doesn't hold the listing's code range (the tests' header-only FSSM) are not checked. `tests/semantic/test_printed_encoding.py` (a dropped VOPC `op_sel`, a later instruction, the SRC2 exception, and the unchecked cases). One difference is repaired instead of refused: a `v_fma_mix*` literal that llvm-mc prints cut to its low 16 bits (and re-encodes with a zero high half). llvm-mc 23.1.5 prints some of these literals in full as `lit(V)` (an f32 source, or a low half that is an inline constant; LLVM 21 printed the inline constant and dropped the literal word) and still re-encodes only the low half: `tools/shader_ir.py` reads `lit(V)` as V, and the same repair applies (5,733 such operands in the pipeline library, [shader_library.md](shader_library.md)). When the 8 instruction bytes match (`same_encoding` with all three sources counted as used, so a live `s0` can't pass as an inline 0) and the printed literal is the stored one's low half, every source the bytes encode as the literal (SRC field `0xff`) takes the stored 32 bits, so a source with `op_sel_hi` and `op_sel` set reads the high half instead of +0.0. Seen in one program of the FidelityFX DLL's `FSPX` code ([fspx.md](fspx.md)): src0 the low half, src2 the high half; the game's clean listings have no such difference (the count above). That the hardware gives op_sel's high half of the literal to that source is not measured; it is what Mesa's ACO compiler relies on (public: `optimize_constants()` in `src/amd/compiler/aco_optimizer.cpp`, Mesa `main` at `bb986060`, packs two constants as the two f16 halves of one literal, read through `v_fma_mix`'s `op_sel_hi` with the second source extracting the high half), and what the console compiler emitted here. `tools/fma_mix_literal_probe.py --oracle hw` measures it on an AMD GPU (the instruction's exact bytes through `tools/hw_oracle`; not run on one yet). `tests/semantic/test_fma_mix_literal.py` (the value through the interpreter, the re-anchoring path, an inline constant with the literal's printed value left alone, and the refused cases, a live source printed as inline 0 among them). |
260| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). | 275| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). |
261| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** \|\| M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected). **Not GPU-verified.** | 276| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 \|\| M > DATA) ? DATA : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** \|\| M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** |
262| Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88). Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** | 277| `global_atomic_csub`, `buffer_atomic_csub` (GFX10.3) | `tmp = M; M = (DATA > tmp) ? 0 : tmp - DATA`, unsigned: a subtract clamped at 0 that never wraps; with `glc` the old M comes back. Measured on gfx1036 by @Vonsek (#3193): 162/162 (memory, data) pairs over both forms. Same `OpAtomicCompareExchange` loop as `inc`/`dec` (`Gen.atomic_inc_dec_cas`), so exact under contention; operands, inactive lanes, buffer bounds and `glc` as `inc`/`dec`. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_atomic_csub.py` (a 9×9 value grid, no `glc`, buffer bounds, 32 lanes on one dword against 32 sequential subtracts, seeded values). The translation is not GPU-verified. |
263| 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** | 278| Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88) and, with the same eight words, on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel), so the `vdst` preservation, the sign/zero extension, the ushort load across a dword and the element-size end check are GPU-checked on AMD too. `tools/hw_oracle` was not used for this; the Vulkan path above is what the translator runs. Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** Measured on an AMD Radeon RX 7900 XTX (`gfx1100`, driver 26.10.1) by running the instructions as a raw compute kernel (`tools/hw_oracle`, wave32, seeded synthetic bytes): the four loads zero-/sign-extend at byte offsets 0..7, the ushort at byte offset 3 merges byte 0 of the next dword, and with `NUM_RECORDS` = 8 the end check uses the element size (a ubyte at 7 reads where one at 8 returns 0, a ushort at 6 reads 0x5eee where one at 7 returns 0, an sshort at 7 returns 0 where an sbyte at 7 reads). `buffer_load_format_x` with `FORMAT` code 5 and `tbuffer_load_format_x format:[BUF_FMT_8_UINT]` return that byte zero-extended with the same 1-byte end check (at `NUM_RECORDS` 8, offset 7 reads 0x5e and 8 returns 0), and a V# whose `DST_SEL`s are 1/2/3/4 returns the integer 1 in all four components, not the fetched byte. The inactive-lane clause rests on the NVIDIA run. **Not GPU-verified.** |
279| 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. **Not GPU-verified.** |
264| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). | 280| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). |
265| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). | 281| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). |
266| 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | 282| 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). |
267| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | 283| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. |
268| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | 284| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. |
269| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | 285| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm, and, since 2026-11-22, the other GFX10 buffer codes 1–77 (every USCALED/SSCALED, 10_11_11 and 11_11_10 FLOAT, the 10_10_10_2 and 2_10_10_10 families, 8_8_8_8 and 16_16_16_16 SINT and SCALED; see *Typed buffer formats*). Others (code 0 and 78 up) give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). |
270| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by `tests/test_desc_cache.py` (`test_lookup_result_is_broadcast_before_use`). | 286| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). |
271| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# runs only that format's decode: `Gen.decode_any_format` is a binary search over the codes in `FORMATS` (`OpSelectionMerge` with `DontFlatten`, plain conditional branches), and a code outside the table gives zeros. The element size is selected from the format alone, and the per-lane byte offset is added once. Confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. Regression test: `tests/semantic/test_format_decode_branch.py`. | 287| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# runs only that format's decode: `Gen.decode_any_format` is a binary search over the codes in `FORMATS` (`OpSelectionMerge` with `DontFlatten`, plain conditional branches), and a code outside the table gives zeros. The element size is selected from the format alone, and the per-lane byte offset is added once. Confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. Regression test: `tests/semantic/test_format_decode_branch.py`. |
272| 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | 288| 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) |
273| `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | 289| `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. |
274| Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). | 290| Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). |
275| Depth-compare samples with implicit LOD (`image_sample_c`, `image_sample_c_b`, and the `_o` forms) | In a pixel shader `image_sample_c` is `OpImageSampleDrefImplicitLod` and `image_sample_c_b` adds `Bias` (the LOD comes from the quad derivatives; the sampler is the comparison sampler `image_sample_c_lz` already uses, and the result is one value, f32 bits or with `d16` an f16 in the low half). The address order after the optional texel-offset dword is **bias, z-compare, coordinates** (GFX10 MIMG: offset, bias, zcompare, derivatives, coordinates, LOD, clamp): `image_sample_c_b` read the compare first until this change, the one place that order was wrong, which `ps_sample_c_b` catches (a bias of 1.0 read as the reference compares false everywhere). Outside the pixel stage there are no derivatives: `image_sample_c` samples LOD 0 (like `image_sample`), `image_sample_c_b` is `Unsupported`. `_o` takes the offset as the other `_o` forms do (`Offset`, or with `--texel-offset-fallback` the coordinate shift and a `Grad` sample of the unshifted coordinate's derivatives, scaled by `2^bias` for `_c_b`). Refused still: `_cl`, `_c_d`, `_c_cd` and the gradient forms of the compare samples; `image_sample_c_l` is #2685. GPU tests: `ps_sample_c`, `ps_sample_c_b` (`vk_texture_test dref_c`, `dref_c_b`: the D32 8x8 depth texture of `ps_sample_c_lz`, all 4096 pixels exact for the f32 result and the d16 one); semantic: `tests/semantic/test_sample_c.py` and the forms in `tests/test_texel_offsets.py`. `vk_texture_test` now takes the GPU `LEONIDA_VK_DEVICE` names, as the other harnesses do (it ignored it before). | 291| Depth-compare samples with implicit LOD (`image_sample_c`, `image_sample_c_b`, and the `_o` forms) | In a pixel shader `image_sample_c` is `OpImageSampleDrefImplicitLod` and `image_sample_c_b` adds `Bias` (the LOD comes from the quad derivatives; the sampler is the comparison sampler `image_sample_c_lz` already uses, and the result is one value, f32 bits or with `d16` an f16 in the low half). The address order after the optional texel-offset dword is **bias, z-compare, coordinates** (GFX10 MIMG: offset, bias, zcompare, derivatives, coordinates, LOD, clamp): `image_sample_c_b` read the compare first until this change, the one place that order was wrong, which `ps_sample_c_b` catches (a bias of 1.0 read as the reference compares false everywhere). Outside the pixel stage there are no derivatives: `image_sample_c` samples LOD 0 (like `image_sample`), `image_sample_c_b` is `Unsupported`. `_o` takes the offset as the other `_o` forms do (`Offset`, or with `--texel-offset-fallback` the coordinate shift and a `Grad` sample of the unshifted coordinate's derivatives, scaled by `2^bias` for `_c_b`). Refused still: `_cl`, `_c_d`, `_c_cd` and the gradient forms of the compare samples; `image_sample_c_l` is #2685. GPU tests: `ps_sample_c`, `ps_sample_c_b` (`vk_texture_test dref_c`, `dref_c_b`: the D32 8x8 depth texture of `ps_sample_c_lz`, all 4096 pixels exact for the f32 result and the d16 one); semantic: `tests/semantic/test_sample_c.py` and the forms in `tests/test_texel_offsets.py`. `vk_texture_test` now takes the GPU `LEONIDA_VK_DEVICE` names, as the other harnesses do (it ignored it before). |
276| Min-LOD clamp forms (`image_sample_cl`, `_b_cl`, `_c_cl`, `_c_b_cl`, and the `_o` forms) | The clamp is the component after the coordinates (address order: offset, bias, z-compare, coordinates, clamp), and becomes the `MinLod` image operand of the implicit-LOD sample (`OpImageSampleImplicitLod` / `OpImageSampleDrefImplicitLod`, with `Bias` and `Offset` before it in mask order), the same as the `image_sample_d_cl` that already existed; the module declares `MinLod` (`shaderResourceMinLod`, the harnesses skip a device without it). Outside the pixel stage there are no derivatives and the LOD is 0, so the clamp raises it: explicit `Lod = max(0, clamp)` and no `MinLod`. Under `a16` the clamp is packed with the coordinates (its own f16, with a pad after it in the last VGPR), as for `_d_cl`. With `--texel-offset-fallback` the Grad sample takes `Grad\|MinLod`. A clamp on a form that has no `_cl` instruction (`_l`, `_lz`, `_c_lz`) stays `Unsupported`. GPU tests: `ps_texture_cl` and `ps_texture_b_cl` on `vk_texture_test --two-mip` (coordinates / 4 so the unclamped LOD is -1; clamp 0.0 left of x = 32 reads mip 0 red, 1.0 from there on reads mip 1 cyan; dropping the MinLod operand turns the right half red); semantic: `tests/semantic/test_sample_cl.py` and the `_cl_o` forms in `tests/test_texel_offsets.py`. The compare forms (`_c_cl`, `_c_b_cl`) have no GPU test: the depth fixture has one mip level. Not translated: `_c_d`, `_c_cd`, `_d_cl` with compare, the g16 forms. | 292| Min-LOD clamp forms (`image_sample_cl`, `_b_cl`, `_c_cl`, `_c_b_cl`, and the `_o` forms) | The clamp is the component after the coordinates (address order: offset, bias, z-compare, coordinates, clamp), and becomes the `MinLod` image operand of the implicit-LOD sample (`OpImageSampleImplicitLod` / `OpImageSampleDrefImplicitLod`, with `Bias` and `Offset` before it in mask order), the same as the `image_sample_d_cl` that already existed; the module declares `MinLod` (`shaderResourceMinLod`, the harnesses skip a device without it). Outside the pixel stage there are no derivatives and the LOD is 0, so the clamp raises it: explicit `Lod = max(0, clamp)` and no `MinLod`. Under `a16` the clamp is packed with the coordinates (its own f16, with a pad after it in the last VGPR), as for `_d_cl`. With `--texel-offset-fallback` the Grad sample takes `Grad\|MinLod`. A clamp on a form that has no `_cl` instruction (`_l`, `_lz`, `_c_lz`) stays `Unsupported`. GPU tests: `ps_texture_cl` and `ps_texture_b_cl` on `vk_texture_test --two-mip` (coordinates / 4 so the unclamped LOD is -1; clamp 0.0 left of x = 32 reads mip 0 red, 1.0 from there on reads mip 1 cyan; dropping the MinLod operand turns the right half red); semantic: `tests/semantic/test_sample_cl.py` and the `_cl_o` forms in `tests/test_texel_offsets.py`. The compare forms (`_c_cl`, `_c_b_cl`) have no GPU test: the depth fixture has one mip level. Not translated: `_c_d`, `_c_cd`, `_d_cl` with compare, the g16 forms. |
293| Flat and scratch store operands | Register analysis reads the full address and data VGPR ranges and defines neither. A store after a block terminator can still appear in the listing scanned for PS live-ins. The CPU branch regression in `tests/semantic/test_store_liveins.py` checks both exported barycentric weights. LLVM gfx1013 confirms operand order. Reachable flat and scratch stores still raise `Unsupported`. |
277| Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). Reads of components the element doesn't declare (e.g. `.w` of an `xyz` position, 3 VS) are allowed: the fetch returns the format defaults (0, 0, 1), and Vulkan fills a `vec4` input from a narrower format the same way. Inputs are declared as `vec4`. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** | 294| Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). Reads of components the element doesn't declare (e.g. `.w` of an `xyz` position, 3 VS) are allowed: the fetch returns the format defaults (0, 0, 1), and Vulkan fills a `vec4` input from a narrower format the same way. Inputs are declared as `vec4`. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** |
278| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | 295| `v_swap_b32` and pixel inputs | The swap reads and writes both VGPRs (AMD RDNA2 ISA, VOP1). A barycentric coordinate in the first operand is therefore a live input, and a coordinate or copy in the second operand is overwritten. When the swap changes an interpolation weight, the other incoming weight is still available to the pair. Checked by `tests/semantic/test_interp_computed_ij.py`: `test_swap_reads_both_incoming_barycentrics`, `test_swap_overwrites_interpolation_weight_in_second_operand` and `test_swapped_copies_swap_the_weights` run synthetic fragment exports through the SPIR-V interpreter. |
296| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Counted over all 12,101 PS listings of 1.0.2.1 (names starting with `.` included; `rdna2spirv.read_before_write_vgprs`, with `v_interp`'s I/J operands left out as the translator does, against the ISG1 read masks from `input_signature_full`; an earlier sample gave 2,531 of 3,000): in 12,098 the VGPRs they read before writing inside the system-input range (v2 up to the last hardware input) equal exactly the position components their input signature reads, then front face when its read mask is non-zero. The 1,639 PS that declare `SV_IsFrontFace` with read mask 0 never read that slot; the translator still places it, last of the inputs this layout models, so no other modelled input moves. The other 3 read fewer position components than their read mask says. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: of the 345 PS that read front face, 130 read pos.xy + front face and 141 pos.x/y/w + front face. That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. `ps_persp_bary.asm` (the same code drawn by `vs_persp.asm`, clip w = 1, 2, 4) checks them, and the interpolated attributes, against perspective-correct CPU weights; the affine weights differ by at least 0.006 on every covered pixel (all 1158 judged), so `NoPerspective` interpolation fails it. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. 373 PS have one (and 85 more whose raw listing holds embedded data words). In each of the 373 a branch instruction comes earlier in listing order than the first such read; in 364 the register is written later in listing order, which suggests a loop-carried value (inferred from listing order, not measured on the control flow), in 9 never after the read. All register arrays start at zero, so translated shaders are deterministic. |
279| Partial pixel color exports | Each MRT retains channels from earlier exports when the current `exp` disables them. Uncompressed exports enable individual RGBA channels and compressed exports enable the RG and BA pairs. Partial MRT outputs start at zero so a channel the shader never writes keeps its existing translator default. The CPU test in `tests/semantic/test_export_valid_mask.py` checks the eight RGBA words from two interleaved targets in `partial_color_exports.asm`. [AMD RDNA 2 ISA, sections 11.1 and 11.2.1](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | 297| Partial pixel color exports | Each MRT retains channels from earlier exports when the current `exp` disables them. Uncompressed exports enable individual RGBA channels and compressed exports enable the RG and BA pairs. Partial MRT outputs start at zero so a channel the shader never writes keeps its existing translator default. The CPU test in `tests/semantic/test_export_valid_mask.py` checks the eight RGBA words from two interleaved targets in `partial_color_exports.asm`. [AMD RDNA 2 ISA, sections 11.1 and 11.2.1](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
280| Inputs and outputs | VS: **legacy (non-NGG) hardware VS, measured** over all 2,236 (`scripts/vs_input_survey.py`): no `exp prim`, no `s_sendmsg` (so no `GS_ALLOC_REQ`) and no `v_mbcnt` in any of them, and every one exports `pos0` and `param`. The input VGPRs are Mesa's GFX10 legacy-VS layout (`radv_shader_args.c`, `declare_vs_input_vgprs`, not `is_ngg`): `v0` = vertex id, `v1` unused, `v2` = primitive id, `v3` = instance id. On entry no VS reads `v1` or `v2`; 788 start with the fetch call (see *Vertex fetch*) and read the fetched attributes from `v4` up, and of the other 1,448, 1,052 read `v0` only, 386 `v0` and `v3`, and 10 neither (NGG would have put the VS inputs at `v5`/`v8`, after five GS VGPRs). **Both ids are zero-based on the hardware**: `v0` excludes the draw's base vertex and `v3` its first instance (Mesa `ac_nir_lower_intrinsics_to_args.c`: `vertex_id` is `load_vertex_id_zero_base`, `instance_id` is `load_instance_id`; the bases come in the `base_vertex` / `start_instance` SGPRs). Vulkan's `VertexIndex` / `InstanceIndex` include `firstVertex`/`vertexOffset` / `firstInstance`, so the translator seeds `v0 = VertexIndex - BaseVertex` and `v3 = InstanceIndex - BaseInstance` (`DrawParameters`, device feature `shaderDrawParameters`, in every VS's `features`). GPU-checked with `runtime/test/shaders/vs_base_ids.asm` (`VKH_DRAW=16,7`): `0x101` on every pixel, where `VertexIndex`/`InstanceIndex` alone gave `0x7111`. `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. | 298| Inputs and outputs | VS: **legacy (non-NGG) hardware VS, measured** over all 2,236 (`scripts/vs_input_survey.py`): no `exp prim`, no `s_sendmsg` (so no `GS_ALLOC_REQ`) and no `v_mbcnt` in any of them, and every one exports `pos0` and `param`. The input VGPRs are Mesa's GFX10 legacy-VS layout (`radv_shader_args.c`, `declare_vs_input_vgprs`, not `is_ngg`): `v0` = vertex id, `v1` unused, `v2` = primitive id, `v3` = instance id. On entry no VS reads `v1` or `v2`; 788 start with the fetch call (see *Vertex fetch*) and read the fetched attributes from `v4` up, and of the other 1,448, 1,052 read `v0` only, 386 `v0` and `v3`, and 10 neither (NGG would have put the VS inputs at `v5`/`v8`, after five GS VGPRs). **Both ids are zero-based on the hardware**: `v0` excludes the draw's base vertex and `v3` its first instance (Mesa `ac_nir_lower_intrinsics_to_args.c`: `vertex_id` is `load_vertex_id_zero_base`, `instance_id` is `load_instance_id`; the bases come in the `base_vertex` / `start_instance` SGPRs). Vulkan's `VertexIndex` / `InstanceIndex` include `firstVertex`/`vertexOffset` / `firstInstance`, so the translator seeds `v0 = VertexIndex - BaseVertex` and `v3 = InstanceIndex - BaseInstance` (`DrawParameters`, device feature `shaderDrawParameters`, in every VS's `features`). GPU-checked with `runtime/test/shaders/vs_base_ids.asm` (`VKH_DRAW=16,7`): `0x101` on every pixel, where `VertexIndex`/`InstanceIndex` alone gave `0x7111`. `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N. `exp mrtK` → the location of the K-th declared `SV_Target` (**Pixel colour exports**): colour exports are packed, so a shader that declares `SV_Target0` and `SV_Target2` exports `mrt0` and `mrt1`, and `mrt1` is render target 2. Counted over the 1.0.2.1 corpus (SHADER-210): of 10,500 pixel shaders with `SV_Target` outputs (OSG1 system value 64, register = semantic index in all 29,290), the 221 that declare non-consecutive targets all export `mrt0`..`mrt(k-1)`, never `mrtN` at register N. Without an OSG1 (hand-written listings, `run_gpu_tests.py` fixtures) `mrtK` is location K. An export past the declared targets is `Unsupported`. `tests/semantic/test_sparse_sv_target.py`. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` only when x is on in an uncompressed export; the 16-bit `compr` form holds stencil and sample mask, never Z (Mesa `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`), and an export without Z must not declare `DepthReplacing`. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. |
299| VS input layout, per PAL hardware stage | `scripts/vs_layout_census.py` joins every tag-0x0D payload's PAL stage record (`tools/pal_stages.py`) with its code markers over all 26,698 payloads of the 26,503 1.0.2.1 containers: the 2,236 stage-4 (VS) payloads are **all** legacy non-NGG — no `exp prim`, no `s_sendmsg`, no `v_mbcnt`, and every one exports `pos0` and `param` — so the Mesa GFX10 legacy-VS layout of *Inputs and outputs* holds for every VS the corpus translates, and `v0` = `VertexIndex` (zero-based, `DrawParameters`) is confirmed rather than NGG. The NGG markers belong to the 9,282 stage-7 payloads (every one has `exp prim`, `s_sendmsg MSG_GS_ALLOC_REQ` and `v_mbcnt`), the 195 stage-3 payloads are the geometry shaders (`s_sendmsg` + `v_mbcnt`, no position export), and the 195 stage-2 payloads are the ES variants of the next row; the PS (12,101) and CS (2,689) payloads carry `v_mbcnt` (332 and 266) and, in ten PS, an `s_sendmsg`, but no `exp prim`. |
300| VS as ES (two-payload VS containers) | 195 `$VS_VoxelizeGeneric_*` containers carry **two** tag-0x0D payloads: besides the legacy VS above, a stage-2 (`es`) payload — the vertex shader compiled for the export-shader stage of a legacy geometry-shader pipeline. It has **no `exp`** (the vertex outputs go to LDS with `ds_write*` for the GS to read), takes its lane id from `v_mbcnt`, and on entry its read-before-write VGPRs are `v5`, `v9`, `v10`, `v11`, `v13` and `v14` (never `v0`/`v3`); none of the 195 starts with the fetch call. `fssm_unpack.py` defaults to the **last** payload, so the corpus translates the VS variant; the ES variant is untranslated, and which payload a GS-bound pipeline selects is open (`docs/fssm_crosscheck.md` §6). |
281| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. | 301| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. |
282| 16-bit SDWA result with `dst_sel:DWORD` | A 16-bit op in SDWA form (`v_add/sub/subrev/mul/min/max_f16_sdwa`, the f16 unary ops, `v_cvt_u16_f16`, `v_cvt_i16_f16`, `v_cvt_f16_u16`, `v_cvt_f16_i16`) with `dst_sel:DWORD` writes the whole VGPR: the 16-bit result zero-extended, **whatever `dst_unused` says**. The keep-the-high-half rule of the row above is for the non-SDWA forms only; with `dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE` the high half is kept as usual. **Until 2026-11-22 the translator kept the high half for `dst_sel:DWORD`** (`Gen.insn` marked an SDWA destination only for a `dst_sel` other than DWORD). Measured natively on an AMD Radeon iGPU (gfx1036, RDNA2, Windows driver 26.10.1) with `python -I tools/sdwa_diff.py --oracle hw` (#2113) and with the program of `runtime/test/shaders/ps_sdwa_dword_hi.asm` through `tools/hw_oracle`: destinations 0xdeadbeef give 0x00004000 (`v_add_f16`, PRESERVE), 0x00000003 (`v_cvt_u16_f16`, PAD), 0x00004700 (`v_cvt_f16_u16`, PRESERVE), 0x0000c000 (`v_mul_f16`, SEXT); the same ops with `dst_sel:WORD_0 UNUSED_PRESERVE` give 0xdead4000, 0xdead0003, 0xdead4700, 0xdeadc000. GPU-checked through Vulkan with `ps_sdwa_dword_hi.asm` on an RTX 5080 (driver 616.92) and the same Radeon iGPU (4096/4096 pixels each); CPU-checked in `tests/semantic/test_value_semantics.py`. | 302| 16-bit SDWA result with `dst_sel:DWORD` | A 16-bit op in SDWA form (`v_add/sub/subrev/mul/min/max_f16_sdwa`, the f16 unary ops, `v_cvt_u16_f16`, `v_cvt_i16_f16`, `v_cvt_f16_u16`, `v_cvt_f16_i16`) with `dst_sel:DWORD` writes the whole VGPR: the 16-bit result zero-extended, **whatever `dst_unused` says**. The keep-the-high-half rule of the row above is for the non-SDWA forms only; with `dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE` the high half is kept as usual. **Until 2026-11-22 the translator kept the high half for `dst_sel:DWORD`** (`Gen.insn` marked an SDWA destination only for a `dst_sel` other than DWORD). Measured natively on an AMD Radeon iGPU (gfx1036, RDNA2, Windows driver 26.10.1) with `python -I tools/sdwa_diff.py --oracle hw` (#2113) and with the program of `runtime/test/shaders/ps_sdwa_dword_hi.asm` through `tools/hw_oracle`: destinations 0xdeadbeef give 0x00004000 (`v_add_f16`, PRESERVE), 0x00000003 (`v_cvt_u16_f16`, PAD), 0x00004700 (`v_cvt_f16_u16`, PRESERVE), 0x0000c000 (`v_mul_f16`, SEXT); the same ops with `dst_sel:WORD_0 UNUSED_PRESERVE` give 0xdead4000, 0xdead0003, 0xdead4700, 0xdeadc000. GPU-checked through Vulkan with `ps_sdwa_dword_hi.asm` on an RTX 5080 (driver 616.92) and the same Radeon iGPU (4096/4096 pixels each); CPU-checked in `tests/semantic/test_value_semantics.py`. |
283| f16 inline constants | An inline float constant (`0.5`, `1.0`, `2.0`, `4.0`, their negatives, `0.15915494`) in an operand of a 16-bit float op is the **f16 value in the low half with a zero high half**, not f32 bits (the translator used to unpack the f32 pattern, whose low half is 0, so `v_add_f16 d, 1.0, v` added 0.0). Measured on an AMD RX 6800 (gfx1030) raw kernel, wave32 and wave64: `v_add/mul/max_f16`, `v_sub_f16_e64`, `v_fma_f16`, `v_fmac_f16`, `v_rcp_f16`, `v_med3_f16`, `v_cmp_lt_f16`, `v_cvt_f32_f16` (`0.5` gives `0x3f000000`), `v_cos_f16`, `v_pk_add_f16`/`v_pk_mul_f16` (the high result half sees 0.0), `v_pack_b32_f16`; `0.15915494` is `0x3118`; the high half `op_sel` selects from a constant reads +0.0 (`v_med3_f16`, `v_fma_f16`, `v_pack_b32_f16`, `v_pk_add_f16` with swapped halves). GPU tests `ps_f16_const`, `ps_f16_const2` and `ps_f16_pack` (Vulkan: AMD Radeon RX 6800, Windows, driver 26.11.2; all three fail without the fix). Constants in `v_fma_mix_f32`/`v_fma_mixlo/mixhi_f16` operands follow the same rule per operand (measured on an RDNA2 iGPU, gfx1036, SHADER-135): f32 bits where `op_sel_hi` makes the operand f32, the f16 constant with a zero high half where it makes it f16, so `op_sel` with `op_sel_hi` reads +0.0; an integer constant is its 32-bit integer. The translator gives the same words for the float constants in every `op_sel`/`op_sel_hi` combination and for the integer constants as f16 halves, but not for `1` and `64` as f32 operands: their bits are f32 denormals, which gfx1036 flushes to a zero of their sign (`denorm_mode_32 = 0`, the MODE the translator assumes for the game) and the translator keeps (difference 4 in docs/shader_validation.md, "f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2"). | 303| f16 inline constants | An inline float constant (`0.5`, `1.0`, `2.0`, `4.0`, their negatives, `0.15915494`) in an operand of a 16-bit float op is the **f16 value in the low half with a zero high half**, not f32 bits (the translator used to unpack the f32 pattern, whose low half is 0, so `v_add_f16 d, 1.0, v` added 0.0). Measured on an AMD RX 6800 (gfx1030) raw kernel, wave32 and wave64: `v_add/mul/max_f16`, `v_sub_f16_e64`, `v_fma_f16`, `v_fmac_f16`, `v_rcp_f16`, `v_med3_f16`, `v_cmp_lt_f16`, `v_cvt_f32_f16` (`0.5` gives `0x3f000000`), `v_cos_f16`, `v_pk_add_f16`/`v_pk_mul_f16` (the high result half sees 0.0), `v_pack_b32_f16`; `0.15915494` is `0x3118`; the high half `op_sel` selects from a constant reads +0.0 (`v_med3_f16`, `v_fma_f16`, `v_pack_b32_f16`, `v_pk_add_f16` with swapped halves). GPU tests `ps_f16_const`, `ps_f16_const2` and `ps_f16_pack` (Vulkan: AMD Radeon RX 6800, Windows, driver 26.11.2; all three fail without the fix). Constants in `v_fma_mix_f32`/`v_fma_mixlo/mixhi_f16` operands follow the same rule per operand (measured on an RDNA2 iGPU, gfx1036, SHADER-135): f32 bits where `op_sel_hi` makes the operand f32, the f16 constant with a zero high half where it makes it f16, so `op_sel` with `op_sel_hi` reads +0.0; an integer constant is its 32-bit integer. The translator gives the same words for the float constants in every `op_sel`/`op_sel_hi` combination and for the integer constants as f16 halves, but not for `1` and `64` as f32 operands: their bits are f32 denormals, which gfx1036 flushes to a zero of their sign (`denorm_mode_32 = 0`, the MODE the translator assumes for the game) and the translator keeps (difference 4 in docs/shader_validation.md, "f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2"). |
284| `v_fmamk_f16`, `v_fmaak_f16` | VOP2 with a literal K: `fmamk` computes `D = S0 * K + S1` (printed `vdst, src0, K, vsrc1`), `fmaak` computes `D = S0 * S1 + K` (printed `vdst, src0, vsrc1, K`). In print order both are `a[1] * a[2] + a[3]`, as for `v_fmamk/fmaak_f32`. K is the f16 in the literal's low 16 bits; a float literal is converted to f16 (`src_h`). One rounding to f16, as `v_fmac_f16` (SHADER-55). The GFX10 f16 VOP2 write puts the result in the low half and keeps the high half. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_fmamk_fmaak_f16.py`, against `v_fma_f16` with K in a VGPR (value grids, a float literal, the operand order, seeded values). **Not GPU-verified.** | 304| `v_fmamk_f16`, `v_fmaak_f16` | VOP2 with a literal K: `fmamk` computes `D = S0 * K + S1` (printed `vdst, src0, K, vsrc1`), `fmaak` computes `D = S0 * S1 + K` (printed `vdst, src0, vsrc1, K`). In print order both are `a[1] * a[2] + a[3]`, as for `v_fmamk/fmaak_f32`. K is the f16 in the literal's low 16 bits; a float literal is converted to f16 (`src_h`). One rounding to f16, as `v_fmac_f16` (SHADER-55). The GFX10 f16 VOP2 write puts the result in the low half and keeps the high half. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_fmamk_fmaak_f16.py`, against `v_fma_f16` with K in a VGPR (value grids, a float literal, the operand order, seeded values). **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 17 cases: the print order, the one-rounding rule and the kept high half hold (`1*2+3`, `1.5*2+0.5`, both orders, `(1+2^-10)*3` rounding the exact 3.0029296875 to the tie's even `0x4202`, `65504*2` overflowing to `+inf`); f16 VALU keeps denormals, unlike the LDS float adder, so `0x0001*1+0x0001` gives `0x0002`; an sNaN is quieted with its payload kept (`0x7c01` gives `0x7e01`) and `inf + -inf` gives the negative default `0xfe00`. **Not GPU-verified.** |
285| SDWA select on an f16 inline constant | In an `_sdwa` 16-bit float op, an inline float constant is first the f16 value over a zero high half (row above) and `src0_sel`/`src1_sel` then narrows those 32 bits like a register's, zero-extended, before neg/abs and the op: `1.0` under `WORD_1` reads +0.0, `2.0` under `BYTE_1` reads the f16 denormal `0x0040`. An SGPR source, and an integer op reading the f32 bits of a float constant (`v_cvt_f16_u16_sdwa d, 1.0 src0_sel:WORD_1` converts 0x3f80), are narrowed the same way. **Until 2026-11-22 the translator used the whole f16 constant** (`v_add_f16_sdwa d, 1.0, v src0_sel:WORD_1` with v = 0.5 gave 1.5). Measured on an AMD Radeon iGPU (gfx1036, Ryzen 9 9950X3D, driver 26.10.1) with `tools/hw_oracle` (raw HIP kernel, wave32): the four words of `runtime/test/shaders/ps_sdwa_f16_const.asm`; found with `python -I tools/sdwa_diff.py --oracle hw` (#2113). GPU test `ps_sdwa_f16_const`, 4096/4096 pixels on an NVIDIA GeForce RTX 5080 (driver 616.92) and the same Radeon iGPU through Vulkan; both fail without the fix. Also executed by `tests/semantic/test_value_semantics.py`. | 305| SDWA select on an f16 inline constant | In an `_sdwa` 16-bit float op, an inline float constant is first the f16 value over a zero high half (row above) and `src0_sel`/`src1_sel` then narrows those 32 bits like a register's, zero-extended, before neg/abs and the op: `1.0` under `WORD_1` reads +0.0, `2.0` under `BYTE_1` reads the f16 denormal `0x0040`. An SGPR source, and an integer op reading the f32 bits of a float constant (`v_cvt_f16_u16_sdwa d, 1.0 src0_sel:WORD_1` converts 0x3f80), are narrowed the same way. **Until 2026-11-22 the translator used the whole f16 constant** (`v_add_f16_sdwa d, 1.0, v src0_sel:WORD_1` with v = 0.5 gave 1.5). Measured on an AMD Radeon iGPU (gfx1036, Ryzen 9 9950X3D, driver 26.10.1) with `tools/hw_oracle` (raw HIP kernel, wave32): the four words of `runtime/test/shaders/ps_sdwa_f16_const.asm`; found with `python -I tools/sdwa_diff.py --oracle hw` (#2113). GPU test `ps_sdwa_f16_const`, 4096/4096 pixels on an NVIDIA GeForce RTX 5080 (driver 616.92) and the same Radeon iGPU through Vulkan; both fail without the fix. Also executed by `tests/semantic/test_value_semantics.py`. |
286| `v_pack_b32_f16` input `neg` | A VOP3 `neg` on an operand of this instruction flips the sign bit of **the 16-bit half that operand contributes**, not of the whole 32-bit source, and only that half: measured on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels, `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`. The translator moved the bits unchanged and refused every modifier; it now XORs `0x8000` into the selected half. `abs` is still refused, because its rule on this instruction is unmeasured (SHADER-260), and the mode-1 quieting of a signalling-NaN half is not modelled while SHADER-190 is open; under mode 0, where the bits move unchanged, the translation is exact. Checked on the CPU by `tests/test_values.py` and `tests/semantic/test_vop3_const_mods.py`; the gfx1036 measurement above is @Sanonymous01's, not repeated here. | 306| `v_pack_b32_f16` input `neg` | A VOP3 `neg` on an operand of this instruction flips the sign bit of **the 16-bit half that operand contributes**, not of the whole 32-bit source, and only that half: measured on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels, `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`. The translator moved the bits unchanged and refused every modifier; it now XORs `0x8000` into the selected half. `abs` is still refused, because its rule on this instruction is unmeasured (SHADER-260), and the mode-1 quieting of a signalling-NaN half is not modelled while SHADER-190 is open; under mode 0, where the bits move unchanged, the translation is exact. Checked on the CPU by `tests/test_values.py` and `tests/semantic/test_vop3_const_mods.py`; the gfx1036 measurement above is @Sanonymous01's, not repeated here. |
287| Packed 16-bit integer ops (`v_pk_add/sub_u16/i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16/i16`, `v_pk_max/min_u16/i16`) | VOP3P: result half 0 takes each source's half from `op_sel[i]`, result half 1 from `op_sel_hi[i]` (defaults `[0,..]` and `[1,..]`), as for `v_pk_lshlrev_b16`. Each half is computed on its own and wraps to 16 bits. `clamp` (add, sub, mad) saturates the half to its type's range; the exact value fits in 32 bits. `neg_lo`/`neg_hi` are float-only and raise `Unsupported`, as does `clamp` on the other ops. A constant operand is treated as a 32-bit dword `C`: `op_sel[i] == 0` selects bits `[15:0]`, `op_sel[i] == 1` selects bits `[31:16]`. Positive inline constants zero-extend (`5` → `0x00000005`), negative inline constants sign-extend (`-1` → `0xFFFFFFFF`, `-16` → `0xFFFFFFF0`), and 32-bit literals retain their full dword (`0x12345678`). Lowered via `OpBitField*Extract` at `16 * sl[i]`. Until 2026-11-22 reading the high half of a constant raised `Unsupported`. A constant operand reads as its low 16 bits. Its high half under `op_sel`/`op_sel_hi` is **not measured** for integer ops (for f16 constants it reads +0.0, see the row above), so a constant whose high half would be read raises `Unsupported` instead of guessing; the compiler's usual form, `op_sel_hi:[1,0]` with the constant second, reads only the low half. Until 2026-11-22 all eleven ops raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, inline and literal constants, rejected forms). **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`, and independently on `gfx1036` desktop APU, Windows 11, driver `32.0.21045.29003`, across 380 raw compute kernels covering all 11 ops, constants under `op_sel`/`op_sel_hi`, `clamp`, and wave32/wave64 parity with 0 wave diffs and 0 mismatches): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and constant `op_sel`/`op_sel_hi`) match bit-for-bit. **Not GPU-verified.** **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and `op_sel`/`op_sel_hi`) match bit-for-bit. | 307| Packed 16-bit integer ops (`v_pk_add/sub_u16/i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16/i16`, `v_pk_max/min_u16/i16`) | VOP3P: result half 0 takes each source's half from `op_sel[i]`, result half 1 from `op_sel_hi[i]` (defaults `[0,..]` and `[1,..]`), as for `v_pk_lshlrev_b16`. Each half is computed on its own and wraps to 16 bits. `clamp` (add, sub, mad) saturates the half to its type's range (the exact value fits in 32 bits), whereas on `v_pk_mul_lo_u16` and `v_pk_max/min_u16/i16` VOP3P `clamp` is a hardware no-op (`v_pk_mul_lo_u16 clamp` wraps modulo 2^16 rather than saturating to `0xFFFF`, and `max`/`min` results are unchanged; until 2026-11-23 `clamp` on those five ops raised `Unsupported`). `neg_lo`/`neg_hi` are float-only and unsupported modifiers (such as `mul:*`/`div:*`) raise `Unsupported`. `clamp` (add, sub, mad) saturates the half to its type's range; the exact value fits in 32 bits. `neg_lo`/`neg_hi` are float-only and raise `Unsupported`, as does `clamp` on the other ops. A constant operand is treated as a 32-bit dword `C`: `op_sel[i] == 0` selects bits `[15:0]`, `op_sel[i] == 1` selects bits `[31:16]`. Positive inline constants zero-extend (`5` → `0x00000005`), negative inline constants sign-extend (`-1` → `0xFFFFFFFF`, `-16` → `0xFFFFFFF0`), and 32-bit literals retain their full dword (`0x12345678`). Lowered via `OpBitField*Extract` at `16 * sl[i]` (the packed 16-bit *shifts* read their halves with a shift and a mask instead, like every other high-half reader: see the 16-bit high-half reads row). Lowered via `OpBitField*Extract` at `16 * sl[i]`. Until 2026-11-22 reading the high half of a constant raised `Unsupported`. A constant operand reads as its low 16 bits. Its high half under `op_sel`/`op_sel_hi` is **not measured** for integer ops (for f16 constants it reads +0.0, see the row above), so a constant whose high half would be read raises `Unsupported` instead of guessing; the compiler's usual form, `op_sel_hi:[1,0]` with the constant second, reads only the low half. Until 2026-11-22 all eleven ops raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, inline and literal constants, rejected forms) and `tests/semantic/test_pk_int16_clamp.py` (all 26 probe cases plain vs `clamp`, SPIR-V non-saturation assertion, inactive `EXEC` preservation, `spirv-val` Vulkan 1.2 validation, rejected modifiers), plus `tests/test_pk_int16_clamp_probe.py`. **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`, and independently on `gfx1036` desktop APU, Windows 11, driver `32.0.21045.29003`, across 380 raw compute kernels covering all 11 ops, constants under `op_sel`/`op_sel_hi`, `clamp`, and wave32/wave64 parity with 0 wave diffs and 0 mismatches, and via `tools/pk_int16_clamp_probe.py --hw-arch gfx1036` across 624 wave32 & wave64 evaluations with `mismatches=0, wave_diffs=0, target_clamp_diffs=0, control_clamp_diffs=34`, plus a 96-word wave32 Vulkan compute check under `VK_LAYER_KHRONOS_validation` passing with 0 mismatches on `AMD Radeon RX 9070 XT` driver `26.11.2` and `AMD Radeon(TM) Graphics` driver `26.11.2`): all eleven ops (wrap, `clamp` saturation on add/sub/mad, `clamp` no-op on `mul_lo`/`max`/`min`, and constant `op_sel`/`op_sel_hi`) match bit-for-bit. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, inline and literal constants, rejected forms). **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`, and independently on `gfx1036` desktop APU, Windows 11, driver `32.0.21045.29003`, across 380 raw compute kernels covering all 11 ops, constants under `op_sel`/`op_sel_hi`, `clamp`, and wave32/wave64 parity with 0 wave diffs and 0 mismatches): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and constant `op_sel`/`op_sel_hi`) match bit-for-bit. **Not GPU-verified.** **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and `op_sel`/`op_sel_hi`) match bit-for-bit. **`v_pk_mul_lo_u16` low 16 bits (found with `pk16_diff --oracle hw,vk`, GPU test `cs_pk_mul_lo_const`):** each half is `((x << 16) * y) >> 16`, not `(x * y) & 0xffff`: with a constant half of 0 in the other half of the result the AMD Windows driver (Radeon iGPU gfx1036, 26.10.1) dropped the mask (`0x1234 * 0xaaaa` gave `0x0c229e88`, hardware `0x00009e88`); the RTX 5080 was right either way. Words measured on the same gfx1036 in `runtime/test/shaders/cs_pk_mul_lo_const.asm`. |
288| `v_sin_f32`, `v_cos_f32`, `v_sin_f16`, `v_cos_f16` | The operand is an angle in turns (the ISA says valid over +-256; the measurement below finds no such limit on gfx1030). `turn_angle` reduces it in turns first, `x - RoundEven(x)` (exact in binary32, in [-0.5, 0.5]), then scales by `2*pi` and calls `Sin`/`Cos`, so the angle stays in [-pi, pi], the only range where GLSL guarantees them (2^-11 absolute). Scaling first rounded the fractional turn away (about 1.2e-4 rad near 255 turns, #594); the first fix (#1283) reduced with `Fract`, which rounds `1 - \| x \| ` for a negative x and lost `-2^-26` (it returned +0; absolute errors up to ~1.7e-7 at -0.1 turns), so the reduction is `RoundEven`-centred. `RoundEven` rather than `Round` so +-0.5 turn reduce symmetrically. inf and NaN still give NaN, and a zero operand is passed through unreduced so `sin(-0)` stays -0. CPU-checked by `tests/semantic/test_alu_sincos.py` against `sin`/`cos(2*pi*x)` in double (large angles, tiny arguments, whole turns of either sign, +-0, inf/NaN, modifiers, f16) and `tests/semantic/test_valu_sin_cos_turns.py` (#1283). GPU test `cs_w32_sincos` (large angles within 1e-3, since the driver `Sin` is only good to 2^-11) is a regression guard, not proof the old form failed on a given driver. Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) by @shelbykb2 (#616): whole and half turns of either sign give +0 (only `sin(-0)` is -0, so no sign needs copying onto a zero result, as here); there is no +-256 limit on that card (any finite x reduces exactly: `sin(300.25)` = 1, `sin(2^24)` = +0); the f16 forms reduce the same way as the f32 ones; +-inf gives a NaN and a NaN passes through, quieted with IEEE mode on. Re-measured natively on gfx1036 (RDNA2, SHADER-134) for f32 and f16 over every quarter turn from 0.25 to 2^24 of either sign and around +-256: the same rules. At an odd half turn `sin`, and at an odd quarter turn `cos`, is exactly +0 (either sign of x), where `Sin`/`Cos` of the rounded 2*pi give about -+8.7e-8 (f32) or a +-1-ulp f16 denormal; since 2026-11-22 the translator selects +0 there (`Gen.trig_exact_zero`), checked against 500 measured words by `tests/semantic/test_alu_sincos_turns_hw.py`. Known differences from this translation: for Known differences from this translation: at half turns `Sin` of the rounded pi gives about -+8.7e-8 where the hardware returns exactly 0, likewise `cos` at quarter turns; for \| x \| <= 2^-12 the hardware multiplies by `0x40c90fd5`, not the rounded 2*pi; the inf/NaN words are whatever the host driver returns. Not checked on gfx1013. | 308| `v_sin_f32`, `v_cos_f32`, `v_sin_f16`, `v_cos_f16` | The operand is an angle in turns (the ISA says valid over +-256; the measurement below finds no such limit on gfx1030). `turn_angle` reduces it in turns first, `x - RoundEven(x)` (exact in binary32, in [-0.5, 0.5]), then scales by `2*pi` and calls `Sin`/`Cos`, so the angle stays in [-pi, pi], the only range where GLSL guarantees them (2^-11 absolute). Scaling first rounded the fractional turn away (about 1.2e-4 rad near 255 turns, #594); the first fix (#1283) reduced with `Fract`, which rounds `1 - \| x \| ` for a negative x and lost `-2^-26` (it returned +0; absolute errors up to ~1.7e-7 at -0.1 turns), so the reduction is `RoundEven`-centred. `RoundEven` rather than `Round` so +-0.5 turn reduce symmetrically. inf and NaN still give NaN, and a zero operand is passed through unreduced so `sin(-0)` stays -0. CPU-checked by `tests/semantic/test_alu_sincos.py` against `sin`/`cos(2*pi*x)` in double (large angles, tiny arguments, whole turns of either sign, +-0, inf/NaN, modifiers, f16) and `tests/semantic/test_valu_sin_cos_turns.py` (#1283). GPU test `cs_w32_sincos` (large angles within 1e-3, since the driver `Sin` is only good to 2^-11) is a regression guard, not proof the old form failed on a given driver. Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) by @shelbykb2 (#616): whole and half turns of either sign give +0 (only `sin(-0)` is -0, so no sign needs copying onto a zero result, as here); there is no +-256 limit on that card (any finite x reduces exactly: `sin(300.25)` = 1, `sin(2^24)` = +0); the f16 forms reduce the same way as the f32 ones; +-inf gives a NaN and a NaN passes through, quieted with IEEE mode on. Re-measured natively on gfx1036 (RDNA2, SHADER-134) for f32 and f16 over every quarter turn from 0.25 to 2^24 of either sign and around +-256: the same rules. At an odd half turn `sin`, and at an odd quarter turn `cos`, is exactly +0 (either sign of x), where `Sin`/`Cos` of the rounded 2*pi give about -+8.7e-8 (f32) or a +-1-ulp f16 denormal; since 2026-11-22 the translator selects +0 there (`Gen.trig_exact_zero`), checked against 500 measured words by `tests/semantic/test_alu_sincos_turns_hw.py`. Known differences from this translation: for Known differences from this translation: at half turns `Sin` of the rounded pi gives about -+8.7e-8 where the hardware returns exactly 0, likewise `cos` at quarter turns; for \| x \| <= 2^-12 the hardware multiplies by `0x40c90fd5`, not the rounded 2*pi; the inf/NaN words are whatever the host driver returns. Not checked on gfx1013. |
289| `v_pack_b32_f16` source modifiers | A VOP3 `abs` or `neg` on an operand of this instruction acts on **the 16-bit half that operand contributes**, not on the whole 32-bit source, and only on that half: `abs` clears bit 15 and `neg` flips it, `abs` first, both as plain bit moves — the operand is not converted to a float. Until 2026-11-22 any such operand was rejected as `Unsupported`. **`neg` is measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels: `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`, so the sign move does not depend on the mode. **`neg`, `abs`, and `neg_abs` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64, 0 mismatches): **`abs` and `- **`neg`, `abs`, and `- **`abs` rests on the ISA's definition of ABS on a float operand as the sign clear, applied before `neg`; no hardware run of this instruction with `abs` exists yet**, and `abs` on a NaN half is therefore unmeasured too. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. \| x src \| ` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64): ` (neg+abs) are measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21045.29003) with 1,088 raw kernels across wave32 and wave64 (0 mismatches): `abs` clears bit 15 (`& 0x7FFF`), `neg` flips it (`^ 0x8000`), and `neg_abs` sets bit 15 across all normal numbers, zeros, infinities, subnormals, quiet NaNs, and signaling NaNs, in either half and with `op_sel`. Under IEEE mode 0, signaling NaN payloads are preserved untouched (`0x7c01` gives `0xfc01` under `neg` and `0x7c01` under `abs`); under IEEE mode 1, a signaling-NaN half is quieted (bit 9 set: `0x7c01` gives `0xfe01` under `neg` and `0x7e01` under `abs`). ` are hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels): On `gfx1035`, `abs` clears bit 15 and applies before `neg` on `-1.0`, `-0.0`, `-qNaN` (`0xfe05` → `0x7e05`), and `-sNaN` (`0xfc01` → `0x7c01` under `ieee=0`), with and without `op_sel`. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. | 309| `v_pack_b32_f16` source modifiers | A VOP3 `abs` or `neg` on an operand of this instruction acts on **the 16-bit half that operand contributes**, not on the whole 32-bit source, and only on that half: `abs` clears bit 15 and `neg` flips it, `abs` first, both as plain bit moves — the operand is not converted to a float. Until 2026-11-22 any such operand was rejected as `Unsupported`. **`neg` is measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels: `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`, so the sign move does not depend on the mode. **`neg`, `abs`, and `neg_abs` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64, 0 mismatches): **`abs` and `- **`neg`, `abs`, and `- **`abs` rests on the ISA's definition of ABS on a float operand as the sign clear, applied before `neg`; no hardware run of this instruction with `abs` exists yet**, and `abs` on a NaN half is therefore unmeasured too. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. \| x src \| ` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64): ` (neg+abs) are measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21045.29003) with 1,088 raw kernels across wave32 and wave64 (0 mismatches): `abs` clears bit 15 (`& 0x7FFF`), `neg` flips it (`^ 0x8000`), and `neg_abs` sets bit 15 across all normal numbers, zeros, infinities, subnormals, quiet NaNs, and signaling NaNs, in either half and with `op_sel`. Under IEEE mode 0, signaling NaN payloads are preserved untouched (`0x7c01` gives `0xfc01` under `neg` and `0x7c01` under `abs`); under IEEE mode 1, a signaling-NaN half is quieted (bit 9 set: `0x7c01` gives `0xfe01` under `neg` and `0x7e01` under `abs`). ` are hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels): On `gfx1035`, `abs` clears bit 15 and applies before `neg` on `-1.0`, `-0.0`, `-qNaN` (`0xfe05` → `0x7e05`), and `-sNaN` (`0xfc01` → `0x7c01` under `ieee=0`), with and without `op_sel`. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. |
290| Packed integer dot products (`v_dot2_i32_i16`, `v_dot2_u32_u16`, `v_dot4_u32_u8`, `v_dot8_i32_i4`, `v_dot8_u32_u4`, plus VOP2 accumulating `v_dot2c_i32_i16`, `v_dot2c_u32_u16`, `v_dot4c_u32_u8`, `v_dot8c_i32_i4`, `v_dot8c_u32_u4`), `v_dot2_f32_f16` / `v_dot2c_f32_f16`, and `v_pk_fmac_f16` | RDNA2 ISA: `v_dot2_i32_i16`/`u16` (2×16-bit), `v_dot4_u32_u8` (4×8-bit unsigned), and `v_dot8_i32_i4`/`u4` (8×4-bit) — and their VOP2 accumulating `v_dot*c_*` forms (reading old `vdst` as `acc`) — extract each element with `OpBitFieldSExtract`/`OpBitFieldUExtract`, sum the elementwise products with `S2` (or old `vdst`) wrapping at 32 bits, and saturate to `[INT32_MIN, INT32_MAX]` / `[0, UINT32_MAX]` under `clamp` (signed carry tracking handles the `v_dot2_i32_i16` `(-32768)^2 + (-32768)^2 + acc` overflow/cancellation edge). For VOP3P `v_dot*_*`, the hardware default `op_sel:[0,0,0]` and `op_sel_hi:[1,1,1]` is accepted and any other `op_sel`/`op_sel_hi`, `neg_lo`/`neg_hi`, DPP/SDWA, or source `neg`/`abs` raises `Unsupported`; for VOP2 `v_dot*c_*`, only optional `clamp` and VGPR `vdst` are accepted. `v_dot2_f32_f16` (VOP3P) and `v_dot2c_f32_f16` (VOP2) compute `a0*b0 + a1*b1 + acc` in f32 (`f16_in` per half, `flush_f32` on `acc`, optional `clamp`, and for `v_dot2_f32_f16` `op_sel`/`op_sel_hi`/`neg_lo`/`neg_hi` on the inputs and `neg_lo[2]` on `acc`). All 6 new `v_dot*c_*` ops mark `vdst` as read-before-write in `read_before_write_vgprs` and `reg_reads_writes`. (`v_dot4_i32_i8` and `v_dot4c_i32_i8` are covered separately in the Signed-byte dot products row, #1754.) `v_pk_fmac_f16` (VOP2) unpacks `src0`, `vsrc1` and `vdst` as `f16x2` (`Gen.src_h`, so inline float constants apply in the low half with `+0.0` high), computes `fma(src0[k], vsrc1[k], vdst[k])` per half with single f16 rounding (`Gen.fma_f16_odd`, SHADER-55), and packs with `Gen.f16_pack2`; any modifier outside `_dpp` or non-VGPR `vdst` raises `Unsupported`, and `v_pk_fmac_f16` marks `vdst` as read before write in `read_before_write_vgprs` and `reg_reads_writes`. **Hardware-confirmed on RDNA2** for the 5 VOP3P integer forms and `v_pk_fmac_f16`: on `gfx1036` (Ryzen 9 7950X3D iGPU, `tools/hw_oracle`, @aslan2142), all 60 integer dot-product sets and all 22 `v_pk_fmac_f16` default-MODE words match; independently confirmed on `gfx1035` (Radeon 680M, @Youssefrah16) across 18 cases × wave32/wave64 (36/36 bit-exact), pinned by `tests/semantic/test_alu_dot_pk_fmac.py`. The 5 VOP2 `v_dot*c_*` integer forms and `v_dot2_f32_f16` / `v_dot2c_f32_f16` are CPU-checked by `tests/semantic/test_alu_dot_complete.py` and not yet hardware-measured on RDNA2. Non-default f16 MODEs (denormal flush, RTZ) are not modelled on `v_pk_fmac_f16` while the translator has no MODE input. | 310| Packed integer dot products (`v_dot2_i32_i16`, `v_dot2_u32_u16`, `v_dot4_u32_u8`, `v_dot8_i32_i4`, `v_dot8_u32_u4`, plus VOP2 accumulating `v_dot2c_i32_i16`, `v_dot2c_u32_u16`, `v_dot4c_u32_u8`, `v_dot8c_i32_i4`, `v_dot8c_u32_u4`), `v_dot2_f32_f16` / `v_dot2c_f32_f16`, and `v_pk_fmac_f16` | RDNA2 ISA: `v_dot2_i32_i16`/`u16` (2×16-bit), `v_dot4_u32_u8` (4×8-bit unsigned), and `v_dot8_i32_i4`/`u4` (8×4-bit) — and their VOP2 accumulating `v_dot*c_*` forms (reading old `vdst` as `acc`) — extract each element with `OpBitFieldSExtract`/`OpBitFieldUExtract`, sum the elementwise products with `S2` (or old `vdst`) wrapping at 32 bits, and saturate to `[INT32_MIN, INT32_MAX]` / `[0, UINT32_MAX]` under `clamp` (signed carry tracking handles the `v_dot2_i32_i16` `(-32768)^2 + (-32768)^2 + acc` overflow/cancellation edge). For VOP3P `v_dot*_*`, the hardware default `op_sel:[0,0,0]` and `op_sel_hi:[1,1,1]` is accepted and any other `op_sel`/`op_sel_hi`, `neg_lo`/`neg_hi`, DPP/SDWA, or source `neg`/`abs` raises `Unsupported`; for VOP2 `v_dot*c_*`, only optional `clamp` and VGPR `vdst` are accepted. `v_dot2_f32_f16` (VOP3P) and `v_dot2c_f32_f16` (VOP2) compute `a0*b0 + a1*b1 + acc` in f32 (`f16_in` per half, `flush_f32` on `acc`, optional `clamp`, and for `v_dot2_f32_f16` `op_sel`/`op_sel_hi`/`neg_lo`/`neg_hi` on the inputs and `neg_lo[2]` on `acc`). All 6 new `v_dot*c_*` ops mark `vdst` as read-before-write in `read_before_write_vgprs` and `reg_reads_writes`. (`v_dot4_i32_i8` and `v_dot4c_i32_i8` are covered separately in the Signed-byte dot products row, #1754.) `v_pk_fmac_f16` (VOP2) unpacks `src0`, `vsrc1` and `vdst` as `f16x2` (`Gen.src_h`, so inline float constants apply in the low half with `+0.0` high), computes `fma(src0[k], vsrc1[k], vdst[k])` per half with single f16 rounding (`Gen.fma_f16_odd`, SHADER-55), and packs with `Gen.f16_pack2`; any modifier outside `_dpp` or non-VGPR `vdst` raises `Unsupported`, and `v_pk_fmac_f16` marks `vdst` as read before write in `read_before_write_vgprs` and `reg_reads_writes`. **Hardware-confirmed on RDNA2** for the 5 VOP3P integer forms and `v_pk_fmac_f16`: on `gfx1036` (Ryzen 9 7950X3D iGPU, `tools/hw_oracle`, @aslan2142), all 60 integer dot-product sets and all 22 `v_pk_fmac_f16` default-MODE words match; independently confirmed on `gfx1035` (Radeon 680M, @Youssefrah16) across 18 cases × wave32/wave64 (36/36 bit-exact), pinned by `tests/semantic/test_alu_dot_pk_fmac.py`. The 5 VOP2 `v_dot*c_*` integer forms and `v_dot2_f32_f16` / `v_dot2c_f32_f16` are CPU-checked by `tests/semantic/test_alu_dot_complete.py` and not yet hardware-measured on RDNA2. Non-default f16 MODEs (denormal flush, RTZ) are not modelled on `v_pk_fmac_f16` while the translator has no MODE input. |
@@ -294,164 +314,183 @@ How the generated SPIR-V expects the runtime to work:
294| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | 314| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). |
295| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10-10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class for those 2D views, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); other loads in the corpus keep the sampled path and need no storage feature (SHADER-151). The D3D-78 row below describes the storage-only and tagged atomic readback exceptions. `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) or on a dimension without storage views (cube) is `Unsupported`. Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | 315| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10-10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class for those 2D views, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); other loads in the corpus keep the sampled path and need no storage feature (SHADER-151). The D3D-78 row below describes the storage-only and tagged atomic readback exceptions. `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) or on a dimension without storage views (cube) is `Unsupported`. Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. |
296| 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. | 316| 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. |
297| 2D `image_sample_l` | The T# FORMAT selects the sampled image type, and every type uses the LOD following the two coordinates. Vulkan requires the sampled type and signedness to match the view. The CPU test in `tests/test_image_load_typed.py` checks the R32 UINT, SINT and FLOAT descriptor branches, the float fallback on a lookup miss and the LOD register with full-width and D16 results. [Vulkan sampling validation](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-input-validation) | 317| 2D `image_sample_l` | The T# FORMAT selects the sampled image type, and every type uses the LOD following the two coordinates. Vulkan requires the sampled type and signedness to match the view. The unit test `test_2d_lod_samples_use_matching_typed_views` in `tests/test_image_load_typed.py` checks the R32 UINT, SINT and FLOAT descriptor branches, the float fallback on a lookup miss and the LOD register with full-width and D16 results. [Vulkan sampling validation](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-input-validation) |
298| Implicit 2D pixel-shader integer samples | For `image_sample`, take the UV derivatives before branching on the T# format, then sample the matching float, UINT or SINT view with those gradients. In `ps_sample_implicit_sint` a 128×128 signed texture minifies onto 64×64 pixels. Clamping the sampler to level 0 returned four color quadrants; allowing level 1 returned cyan. All four signed D16 channels matched at every pixel on RTX 5080 and gfx1036. | 318| Implicit 2D pixel-shader integer samples | For `image_sample`, take the UV derivatives before branching on the T# format, then sample the matching float, UINT or SINT view with those gradients. In `ps_sample_implicit_sint` a 128×128 signed texture minifies onto 64×64 pixels, and `ps_sample_implicit_uint` samples the same image through the unsigned view. Clamping the sampler to level 0 returned four color quadrants; allowing level 1 returned cyan. All four signed D16 channels matched at every pixel on RTX 5080 and gfx1036; both fixtures are 4096/4096 pixels exact on an Intel UHD Graphics 630 (CFL GT2), Mesa 25.2.8. |
299| Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. The operand is always a run-time value: the translator extracts the fields from the register, also when the shader loaded the dword from an immediate, so every `_o` sample needs the extension. `image_gather4_lz_o` / `_l_o` read x and y the same way; a gather `Offset` needs `shaderImageGatherExtended`, not maintenance8. **GPU-tested** with `runtime/test/shaders/ps_texoff.asm` on `vk_texture_test` (in `check.py` and `scripts/run_gpu_tests.py`; SKIP on a device without the extension), on an AMD Radeon RX 6800, Windows driver 26.11.2, maintenance8 enabled: an 8×8 texture whose texels are all different, a point sampler that clamps to the edge, 2D targets, mip 0. `image_sample_lz_o` with an offset computed per pixel (all 64 pairs of x, y in −4..3, none clamped), `image_sample_l_o` with (−3, +2) and `image_sample_lz_o` with (+16, −32) from immediates, and `image_gather4_lz_o` of red and of green with the per-pixel offset gave, on all 4096 pixels, the texels worked out by hand from this rule (derivation in the `.asm` header). Run with a sabotaged translator, the test fails when the sample offset is dropped, has x and y swapped, takes y from bit 6, or uses 4-bit or 5-bit fields, and when the gather offset is dropped, has x and y swapped or takes y from bit 6; 4-bit and 5-bit gather fields pass, because the gather offsets stay in −4..3. What it shows is that the translated SPIR-V implements this rule on Vulkan; it does not measure the field layout on the hardware. **It cannot see the sign extension on this driver**: with the fields read unsigned the same texels come back: `Offset` 60..63 sampled as −4..−1 and +32 as −32 (the device reports texel offset limits −64..63, gather −32..31). The sign extension and the gather field width are therefore pinned by the structural test `tests/test_texel_offsets.py` (signed, bit 8k, 6 bits, for `_lz_o`, `_l_o`, `_o`, 3D and gather) and are not GPU-tested through Vulkan. **The x field is measured on hardware:** `image_sample_lz_o` run as a raw compute kernel on the same RX 6800 (gfx1030, wave32 and wave64), on a 64×1 `R32_FLOAT` image whose texel i holds i, with a point sampler that clamps to the last texel: from texel 40, offset dword `0x20` reads texel 8 and `0x3c` reads texel 36 (unsigned would clamp both to 63); from texel 10, `0x1f` reads 41 and `0x20` clamps to 0; `0x40`, `0x80` and `0xc0` read the centre texel (bits 6–7 are ignored); and a non-zero y field, z field or top byte leaves x alone. All 36 rows fit x = sign-extended bits [5:0]. **The y and z fields are measured too** (SHADER-337): `tools/texoff_probe.py --oracle hw` on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010), wave32 and wave64, samples a linear `R32_SFLOAT` texture whose texel holds its index (2D 64×64 for y, 3D 64×1×64 for z) with `image_sample_lz_o` and a point sampler that clamps to the last texel. From row 40, y = `0x20` reads row 8 and `0x3c` row 36, `0x21` row 9 (unsigned would clamp all three to 63); from row 10, `0x1f` reads 41 and `0x20` clamps to 0 (unsigned: 42); `0xc0` (bits 14–15 set, field 0) reads row 40 and `0x7f` row 39, so those bits are ignored; x −2 with y −4 in one dword reads both. The z field at bits [21:16] gives the same 7 results on the 3D image. All 15 rows fit each field = sign-extended 6 bits, the bits above it ignored, which is the translator's rule; `tests/test_texoff_probe.py` checks that every row with a negative field tells the signed reading from the unsigned one. The (+16, −32) sample is outside Vulkan's guaranteed −8..7 and is judged only where the device limits cover it. **`image_sample_o`, `image_sample_b_o` and `image_gather4_l_o` are GPU-tested** with `runtime/test/shaders/ps_texoff_forms.asm` (the same texture, sampler and per-pixel offset as `ps_texoff`, all 64 offset pairs in −4..3; in `check.py` and `scripts/run_gpu_tests.py`): 4096/4096 pixels exact on an NVIDIA GeForce RTX 4090 (driver 621.24) and on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, driver 32.0.21045.16010), both with maintenance8 enabled. Not GPU-tested: `_c_lz_o`, the z field (3D), 1D, 2D-array and cube targets (offset next to an array layer), wrap or mirror addressing, linear filtering, mips other than 0, other vendors' drivers, and a device without maintenance8 (the test skips there; the translator has no fallback for it). **Without maintenance8 (`--texel-offset-fallback`, NVIDIA Pascal for one):** an `image_sample*_o` gets no `Offset`; the offset is folded into the coordinate instead, as coordinate + offset ÷ the size of the sampled level. The level is 0 for `_lz` / `_c_lz`, the given LOD for `_l`, and `OpImageQueryLod`'s for implicit samples (plus the bias for `_b`), floored and clamped to the image's levels. A texel offset applies before wrapping and clamping, and an integer offset commutes with both, so the shift is exact for every address mode at that level. The one case that differs is a trilinear blend of two levels, where the coarser level moves by offset ÷ 2 of its texels. Implicit samples become `Grad` samples with the derivatives of the unshifted coordinate (× 2^bias for `_b`), so the LOD and anisotropy are those of the original sample even when the offset varies per pixel. Gathers keep their `Offset` (`shaderImageGatherExtended`). Only 4 of the 12,101 PS need it, all through `image_sample_o`. **GPU-tested** on an NVIDIA GeForce GTX 1060 6GB (no maintenance8; driver 560.94, Windows 10) with `LEONIDA_TEXOFF_FALLBACK=1`: `ps_texoff` and `ps_texoff_implicit` (the per-pixel sample as `image_sample_o`) are 4096/4096 pixels exact, with the +16/−32 sample judged too, since a coordinate shift has no device offset limit. Checked in `tests/test_texel_offsets.py`, including `spirv-val` without `--allow-offset-texture-operand`. | 319| Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. The operand is always a run-time value: the translator extracts the fields from the register, also when the shader loaded the dword from an immediate, so every `_o` sample needs the extension. `image_gather4_lz_o` / `_l_o` read x and y the same way; a gather `Offset` needs `shaderImageGatherExtended`, not maintenance8. **GPU-tested** with `runtime/test/shaders/ps_texoff.asm` on `vk_texture_test` (in `check.py` and `scripts/run_gpu_tests.py`; SKIP on a device without the extension), on an AMD Radeon RX 6800, Windows driver 26.11.2, maintenance8 enabled: an 8×8 texture whose texels are all different, a point sampler that clamps to the edge, 2D targets, mip 0. `image_sample_lz_o` with an offset computed per pixel (all 64 pairs of x, y in −4..3, none clamped), `image_sample_l_o` with (−3, +2) and `image_sample_lz_o` with (+16, −32) from immediates, and `image_gather4_lz_o` of red and of green with the per-pixel offset gave, on all 4096 pixels, the texels worked out by hand from this rule (derivation in the `.asm` header). Run with a sabotaged translator, the test fails when the sample offset is dropped, has x and y swapped, takes y from bit 6, or uses 4-bit or 5-bit fields, and when the gather offset is dropped, has x and y swapped or takes y from bit 6; 4-bit and 5-bit gather fields pass, because the gather offsets stay in −4..3. What it shows is that the translated SPIR-V implements this rule on Vulkan; it does not measure the field layout on the hardware. **It cannot see the sign extension on this driver**: with the fields read unsigned the same texels come back: `Offset` 60..63 sampled as −4..−1 and +32 as −32 (the device reports texel offset limits −64..63, gather −32..31). The sign extension and the gather field width are therefore pinned by the structural test `tests/test_texel_offsets.py` (signed, bit 8k, 6 bits, for `_lz_o`, `_l_o`, `_o`, 3D and gather) and are not GPU-tested through Vulkan. **The x field is measured on hardware:** `image_sample_lz_o` run as a raw compute kernel on the same RX 6800 (gfx1030, wave32 and wave64), on a 64×1 `R32_FLOAT` image whose texel i holds i, with a point sampler that clamps to the last texel: from texel 40, offset dword `0x20` reads texel 8 and `0x3c` reads texel 36 (unsigned would clamp both to 63); from texel 10, `0x1f` reads 41 and `0x20` clamps to 0; `0x40`, `0x80` and `0xc0` read the centre texel (bits 6–7 are ignored); and a non-zero y field, z field or top byte leaves x alone. All 36 rows fit x = sign-extended bits [5:0]. **The y and z fields are measured too** (SHADER-337): `tools/texoff_probe.py --oracle hw` on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010), wave32 and wave64, samples a linear `R32_SFLOAT` texture whose texel holds its index (2D 64×64 for y, 3D 64×1×64 for z) with `image_sample_lz_o` and a point sampler that clamps to the last texel. From row 40, y = `0x20` reads row 8 and `0x3c` row 36, `0x21` row 9 (unsigned would clamp all three to 63); from row 10, `0x1f` reads 41 and `0x20` clamps to 0 (unsigned: 42); `0xc0` (bits 14–15 set, field 0) reads row 40 and `0x7f` row 39, so those bits are ignored; x −2 with y −4 in one dword reads both. The z field at bits [21:16] gives the same 7 results on the 3D image. All 15 rows fit each field = sign-extended 6 bits, the bits above it ignored, which is the translator's rule; `tests/test_texoff_probe.py` checks that every row with a negative field tells the signed reading from the unsigned one. The (+16, −32) sample is outside Vulkan's guaranteed −8..7 and is judged only where the device limits cover it. **`image_sample_o`, `image_sample_b_o` and `image_gather4_l_o` are GPU-tested** with `runtime/test/shaders/ps_texoff_forms.asm` (the same texture, sampler and per-pixel offset as `ps_texoff`, all 64 offset pairs in −4..3; in `check.py` and `scripts/run_gpu_tests.py`): 4096/4096 pixels exact on an NVIDIA GeForce RTX 4090 (driver 621.24) and on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, driver 32.0.21045.16010), both with maintenance8 enabled. Not GPU-tested: `_c_lz_o`, the z field (3D), 1D, 2D-array and cube targets (offset next to an array layer), wrap or mirror addressing, linear filtering, mips other than 0, other vendors' drivers, and a device without maintenance8 (the test skips there; the translator has no fallback for it). **Without maintenance8 (`--texel-offset-fallback`, NVIDIA Pascal for one):** an `image_sample*_o` gets no `Offset`; the offset is folded into the coordinate instead, as coordinate + offset ÷ the size of the sampled level. The level is 0 for `_lz` / `_c_lz`, the given LOD for `_l`, and `OpImageQueryLod`'s for implicit samples (plus the bias for `_b`), rounded the way the S#'s `MIP_FILTER` (word 2 [27:26], literal or read at run time) picks a level, and clamped to the image's levels: floored for linear, nearest with a tie rounding up for point (floor(LOD + 0.5), computed as floor + (fraction ≥ 0.5) so binary32 rounding of the sum can't move it; Vulkan allows either tie rule, and RTX 5070 GPUs (drivers 616.56, 621.01) sample LOD 0.5 and 0x3f000001 at mip 1, as `tools/image_query_probe.py` records RDNA2 doing) and for the value 3, and 0 for none, whose LOD the runtime holds in [0, 0.25] (SHADER-699: a point-mip sample at LOD 0.75 reads mip 1, so flooring shifted it by mip-0 texels; checked in `tests/test_texel_offsets.py` by evaluating the emitted level chain). A texel offset applies before wrapping and clamping, and an integer offset commutes with both, so the shift is exact for every address mode at that level. The one case that differs is a trilinear blend of two levels, where the coarser level moves by offset ÷ 2 of its texels. Implicit samples become `Grad` samples with the derivatives of the unshifted coordinate (× 2^bias for `_b`), so the LOD and anisotropy are those of the original sample even when the offset varies per pixel. Gathers keep their `Offset` (`shaderImageGatherExtended`). Only 4 of the 12,101 PS need it, all through `image_sample_o`. **GPU-tested** on an NVIDIA GeForce GTX 1060 6GB (no maintenance8; driver 560.94, Windows 10) with `LEONIDA_TEXOFF_FALLBACK=1`: `ps_texoff` and `ps_texoff_implicit` (the per-pixel sample as `image_sample_o`) are 4096/4096 pixels exact, with the +16/−32 sample judged too, since a coordinate shift has no device offset limit. Checked in `tests/test_texel_offsets.py`, including `spirv-val` without `--allow-offset-texture-operand`. |
300| A16 sample offsets | For the supported `image_sample*_o` forms, the first address VGPR retains the signed texel-offset fields. The following coordinates and any trailing LOD use packed binary16 halves, low half first. LLVM counts extra operands as whole words before packing coordinates and LOD ([getAddrSizeMIMGOp](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342)). On RTX 5080 and Radeon Graphics, `ps_texoff.asm` checked 64 distinct offsets applied to packed U/V at texel (3,5) against the expected texel for each of 4096 pixels. Swapping the halves or dropping the offset changed 4032 pixels per GPU. | 320| A16 sample offsets | For the supported `image_sample*_o` forms, the first address VGPR retains the signed texel-offset fields. The following coordinates and any trailing LOD use packed binary16 halves, low half first. LLVM counts extra operands as whole words before packing coordinates and LOD ([getAddrSizeMIMGOp](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342)). On RTX 5080 and Radeon Graphics, `ps_texoff.asm` checked 64 distinct offsets applied to packed U/V at texel (3,5) against the expected texel for each of 4096 pixels. Swapping the halves or dropping the offset changed 4032 pixels per GPU. |
301| A16 gather offsets | On GFX10, `image_gather4_lz_o` and `image_gather4_l_o` take the packed signed texel offset in a full VGPR before the packed binary16 coordinates and optional LOD. LLVM [counts the extra operand before packing coordinate words](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342). The synthetic `gather_offset_a16.asm` checks an offset of (−1,+1) with distinct U and V and a nonzero mip. | 321| `s_memtime`, `s_memrealtime` | Behind `--shader-clock khr` (default `off`: both stay `Unsupported`, as before). `s_memtime` is the per-CU shader clock: `OpReadClockKHR` with Subgroup scope; `s_memrealtime` is the constant-rate REFCLK counter: Device scope. The 64-bit result goes to the destination SGPR pair, low word first; other destinations are `Unsupported`. Each module declares `ShaderClockKHR` + `SPV_KHR_shader_clock` and lists `shaderSubgroupClock` and/or `shaderDeviceClock` in the index `features`, only for the scopes it reads. The runtime enables `VK_KHR_shader_clock` with whichever feature the GPU has (`VulkanDeviceInfo::shader_subgroup_clock` / `shader_device_clock`, checked by `d3d12_vulkan_device_test`); the shader library does not read `features`, which is why the rule is opt-in: a module with a scope the device lacks fails `vkCreateShaderModule`. Values are not comparable with a console GPU's (different clock and frequency), so time differences work and fixed-frequency assumptions don't. CPU-checked by `tests/semantic/test_smem_clock.py` (scopes, capability/extension, features, spirv-val, off by default). GPU: a PS reading both clocks creates its pipeline (`vk_pipeline_check`) on an RTX 6000 Ada (Linux) and an RX 9060 XT (RADV, #2817). The values themselves are not measured. |
322| A16 gather offsets | On GFX10, `image_gather4_lz_o` and `image_gather4_l_o` take the packed signed texel offset in a full VGPR before the packed binary16 coordinates and optional LOD. LLVM [counts the extra operand before packing coordinate words](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342). The synthetic `gather_offset_a16.asm` checks an offset of (−1,+1) with distinct U and V and a nonzero mip. Checked by the unit test `test_a16_offset_gathers_preserve_offset_and_unpack_uv_lod` in `tests/test_image_load_typed.py`, which translates that fixture and its `gather4_lz_o` variant and follows the offset fields and the packed U, V and LOD halves back to their source VGPRs. |
302| Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti (and an RTX 2060 SUPER), and `runtime/test/vk_harness.cpp` enables them when available, as does the runtime's `create_vulkan_device_standalone`, each with its extension (`VulkanDeviceInfo::fragment_shader_barycentric`, `fragment_shader_interlock`, `maintenance8`; checked by `d3d12_vulkan_device_test`). All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. (It is guarded by the header macro `VK_KHR_MAINTENANCE_8_EXTENSION_NAME`, so older Vulkan headers build without it. `vk_texture_test` enables it too, and `shaderImageGatherExtended`.) A device without `fragmentShaderBarycentric` (NVIDIA Pascal) runs the raw-barycentric PS with `--bary-fallback` (below). Shaders translated with `--fma khr` need `VK_KHR_shader_fma` and its `shaderFmaFloat32` feature (`VkPhysicalDeviceShaderFmaFeaturesKHR`): `create_vulkan_device_standalone`, `runtime/test/vk_test_device.h` and the `vk_*` test programs enable it when the device offers it (`VulkanDeviceInfo::shader_fma`), and a test program refuses (exit 77) a module with `OpCapability FMAKHR` on a device without it. | 323| Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti (and an RTX 2060 SUPER), and `runtime/test/vk_harness.cpp` enables them when available, as does the runtime's `create_vulkan_device_standalone`, each with its extension (`VulkanDeviceInfo::fragment_shader_barycentric`, `fragment_shader_interlock`, `maintenance8`; checked by `d3d12_vulkan_device_test`). All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. (It is guarded by the header macro `VK_KHR_MAINTENANCE_8_EXTENSION_NAME`, so older Vulkan headers build without it. `vk_texture_test` enables it too, and `shaderImageGatherExtended`.) A device without `fragmentShaderBarycentric` (NVIDIA Pascal) runs the raw-barycentric PS with `--bary-fallback` (below). Shaders translated with `--fma khr` need `VK_KHR_shader_fma` and its `shaderFmaFloat32` feature (`VkPhysicalDeviceShaderFmaFeaturesKHR`): `create_vulkan_device_standalone`, `runtime/test/vk_test_device.h` and the `vk_*` test programs enable it when the device offers it (`VulkanDeviceInfo::shader_fma`), and a test program refuses (exit 77) a module with `OpCapability FMAKHR` on a device without it. |
303| Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | 324| Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS, but it left out the 769 listings whose names start with `.` (616 of them mesh shaders; Python's `glob` skips such names). Over all 26,503, the translator's own marker test (`WAVE64_RE`, or a 64-bit op on EXEC/VCC) on the code `translate()` keeps finds 21,554 wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 867 CS and 195 GS. With the 2,287 above that is exactly the flag's 23,841, and none contradicts it; read raw, 104 more wave32 listings (80 CS, 24 PS) seem to carry a marker, all from embedded data words decoded as instructions. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. |
304| Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. | 325| Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. |
305| Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | 326| Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one), and on by itself in `make_game.py` on Intel's Windows Vulkan driver (`VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS` with mesh shaders, `runtime_gpu_mesh_draws_crash`): there `vkCmdDrawMeshTasksEXT` crashes (0xC0000409 in `igvk64.dll`) for a mesh shader with a live push-constant load at byte 32 or later, which every corpus mesh shader has, while `--mesh-compute` is exact (BUILD-2202, Arc A770, driver 32.0.101.9175; no fixed version known; `--native-mesh` keeps native mesh shaders). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. |
306| Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | 327| Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks, and rejecting (`Unsupported`) an `OpEmitVertex` in a loop header before its `OpLoopMerge`, which the split would move; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. |
307| Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | 328| Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. |
308| Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's Windows driver on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py`; all 185 hand-written GPU test shaders pass `spirv-val` with the flag (109 of them read the tail) with set-0 bindings unchanged. The GPU harnesses and the D3D12 layer that bind the block are the follow-ups. | 329| Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's older Windows drivers on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24; a 610M on 26.11.2 reports 256) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py`; all 185 hand-written GPU test shaders pass `spirv-val` with the flag (109 of them read the tail) with set-0 bindings unchanged. The GPU harnesses and the D3D12 layer that bind the block are the follow-ups. |
309| `v_add_nc_i16`, `v_sub_nc_i16` | GFX10 VOP3-only signed 16-bit add and subtract. Without `clamp` they are bit-identical to `v_add_nc_u16`/`v_sub_nc_u16` (the low 16 bits wrap) and take the same path: `op_sel:[s0,s1,dst]` picks each source's half and the destination half, and the other half of D is kept. With `clamp`, the exact sum or difference of the sign-extended halves saturates to [-32768, 32767] (`SClamp`), where the u16 forms saturate to [0, 0xFFFF]. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel` including the destination half, and equality with the u16 forms without `clamp`). **Not GPU-verified.** Measured on native gfx1100: `clamp` saturates the exact sign-extended sum to [-32768, 32767] and the other half of D is kept. | 330| `v_mad_u32_u16` / `v_mad_i32_i16` op_sel on S2 and D, and clamp | D = S0.half · S1.half + S2, the halves zero- (u16) or sign-extended (i16), op_sel bit 0 / 1 reading the high half of S0 / S1. The other bits and `clamp` were refused (`Unsupported: op_sel/clamp`) until their results were measured on RDNA2 (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1, raw kernels through `tools/hw_oracle`, wave32 and wave64 alike; EGEN-HW-MAD-U32-U16, 44 words): **op_sel bit 2 adds S2[31:16] zero-extended, in the i16 op too** (`v_mad_i32_i16 d, 3, 3, 0xffff8000 op_sel:[0,0,1,0]` gives `0x00010008`, not 8); an inline float constant there is its f32 pattern (`1.0` adds `0x3f80`); **op_sel bit 3 writes the result shifted left by 16** (low half 0, the old D not kept); **`clamp` saturates the 32-bit sum** to [0, 0xffffffff] (u16) or [0x80000000, 0x7fffffff] (i16), before that shift (the 16-bit product itself never overflows). GPU-checked with `runtime/test/shaders/ps_valu16_mad_sel.asm` (4096/4096 on NVIDIA GeForce RTX 5080, driver 616.92, and the gfx1036 iGPU); CPU-checked by `tests/semantic/test_alu_mad_32_16.py` (40 seeded cases against a Python reference) and `tests/semantic/test_value_semantics.py`. |
310| Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). | 331| `v_add_nc_i16`, `v_sub_nc_i16` | GFX10 VOP3-only signed 16-bit add and subtract. Without `clamp` they are bit-identical to `v_add_nc_u16`/`v_sub_nc_u16` (the low 16 bits wrap) and take the same path: `op_sel:[s0,s1,dst]` picks each source's half and the destination half, and the other half of D is kept. With `clamp`, the exact sum or difference of the sign-extended halves saturates to [-32768, 32767] (`SClamp`), where the u16 forms saturate to [0, 0xFFFF]. RDNA2 (GFX10.3) dropped reversed 16-bit integer subtraction (`v_subrev_nc_u16` / `v_subrev_nc_i16` do not exist on hardware; `v_subrev_f16` is the only 16-bit reverse subtract opcode). Checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel`, literals, SGPR sources, and untouched half preservation) and **Hardware-verified on AMD RDNA2** (`gfx1036`, wave32 and wave64 via `tools/int_hw_probe.py`, `valu_add_nc_clamp/v_add_sub_nc_i16_clamp`): signed saturation to [-32768, 32767], `op_sel` source selection, and untouched destination half preservation match hardware bit-for-bit. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel` including the destination half, and equality with the u16 forms without `clamp`). **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one-thread raw kernels: 112 of 112 directed cases (both ops; 0x7FFF+1, 0x8000+1, 0x8000+0xFFFF, 0x7FFF+0x7FFF, 0x8000+0x8000 and others, each with and without `clamp` and with `op_sel` `[0,0,0]`, `[1,0,1]`, `[0,1,0]` and `[1,1,1]`, the destination preset to 0xA5A5A5A5). For example `v_add_nc_i16(0x7FFF, 1)` gives 0x8000 wrapped and 0x7FFF with `clamp`, `v_sub_nc_i16(0x8000, 1) clamp` gives 0x8000, and the destination half `op_sel` doesn't pick keeps its 0xA5A5. `tools/pk16_diff.py --oracle translator,hw --ops v_add_nc_i16,v_sub_nc_i16 --programs 3000 --seed 1`: 3000 of 3000 programs agree with the hardware and the translator. **Not GPU-verified.** Measured on native gfx1100: `clamp` saturates the exact sign-extended sum to [-32768, 32767] and the other half of D is kept. |
332| Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). It computes `floor(LOD) + (LOD - floor(LOD) >= 0.5)`, which is exact in binary32, not `Floor(LOD + 0.5)`: that sum rounds `0x3effffff` up to 1.0, and on an RTX 5070 (621.24) the gather then read mip 1 where native `image_sample_l` at the same LOD reads mip 0. |
311| `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches, and the high product word and SCC retention confirmed across edge values. | 333| `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches, and the high product word and SCC retention confirmed across edge values. |
312| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). | 334| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). |
313| Chained scalar constant folding (PERF) | Multi-step constant calculations on SGPRs (`s_mov_b32`, `s_lshl_b32`, `s_lshr_b32`, `s_mul_i32`, `s_add_u32`, `s_sub_u32`, `s_lshl1..4_add_u32`, `s_bfe_u32/i32`, `s_min/max_u32/i32`, `s_andn2/orn2/nand/nor/xnor_b32`, `s_abs_i32`, `s_absdiff_i32`, `s_sext_i32_i8/i16`, `s_pack_*_b32_b16`, `s_bfm_b32`) fold completely at translation time and record folded literal values in `self.sgpr_imm`, allowing downstream instructions within the basic block to propagate constants. `s_buffer_load` offset expressions computed via constant SALU fold statically into 64-bit addresses, and in-bounds reads eliminate runtime bounds check branches and Phi nodes. `s_bfe` with constant control words emits static offset/width operands directly. Checked by `tests/semantic/test_salu_chained_const_prop.py` and `tests/semantic/test_scalar_alu_and_smem_folding.py`. | 335| Chained scalar constant folding (PERF) | Multi-step constant calculations on SGPRs (`s_mov_b32`, `s_lshl_b32`, `s_lshr_b32`, `s_mul_i32`, `s_add_u32`, `s_sub_u32`, `s_lshl1..4_add_u32`, `s_bfe_u32/i32`, `s_min/max_u32/i32`, `s_andn2/orn2/nand/nor/xnor_b32`, `s_abs_i32`, `s_absdiff_i32`, `s_sext_i32_i8/i16`, `s_pack_*_b32_b16`, `s_bfm_b32`) fold completely at translation time and record folded literal values in `self.sgpr_imm`, allowing downstream instructions within the basic block to propagate constants. `s_buffer_load` offset expressions computed via constant SALU fold statically into 64-bit addresses, and in-bounds reads eliminate runtime bounds check branches and Phi nodes. `s_bfe` with constant control words emits static offset/width operands directly. Checked by `tests/semantic/test_salu_chained_const_prop.py` and `tests/semantic/test_scalar_alu_and_smem_folding.py`. |
314| Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. The `s_sub_u32 K; s_subb_u32 0` form is the backward jump (a loop back-edge), as is `s_add_u32 -K; s_addc_u32 -1`. K is a byte distance, so the fold needs the instructions' `; encoding:` bytes; a listing without them is `Unsupported` ("without encoding"), not a crash. GPU-checked by `ps_far_branch.asm` (two forward jumps, a `sub`/`subb` loop, an `add`/`addc -1` loop and a conditional one run twice, K and the expected words derived by hand; RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_far_branch.py`. | 336| Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. The `s_sub_u32 K; s_subb_u32 0` form is the backward jump (a loop back-edge), as is `s_add_u32 -K; s_addc_u32 -1`. K is a byte distance, so the fold needs the instructions' `; encoding:` bytes; a listing without them is `Unsupported` ("without encoding"), not a crash. GPU-checked by `ps_far_branch.asm` (two forward jumps, a `sub`/`subb` loop, an `add`/`addc -1` loop and a conditional one run twice, K and the expected words derived by hand; RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_far_branch.py`. |
315| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | 337| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). |
316| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint/sint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. A store with fewer components than its format writes the whole element, with 0 for the components it doesn't give (`_xy` into 32_32_32_32 leaves z = w = 0, `_xyz` into 16_16_16_16 leaves w = 0); into a one-channel format only x is written. Measured natively on a Radeon 680M (gfx1035, RDNA2), and GPU-checked by `cs_fmt_xy_xyz.asm` for 32_32_32_32, 16_16_16_16, 8_8_8_8 UNORM and UINT and 32 (TEST-185). Unsigned integer stores saturate to the destination channel width. On native gfx1036, RGBA8_UINT, RG16_UINT and RGBA16_UINT clipped overflowing inputs to 255 or 65535, with RGBA32_UINT as a full-width control. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero; native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. `tbuffer_store_format_*` is not translated. 8- and 16-bit SINT stores clamp the signed 32-bit value to [-2^(w-1), 2^(w-1) - 1] (300 stores 127 into 8_SINT, -129 stores -128), and the 8/16-bit UINT formats 5, 11 and 18 saturate like the others; measured natively on gfx1036 for x, xy, xyzw and d16_xyzw stores (a d16 half is read as a signed 16-bit integer for SINT, so 0xff80 stores -128) with the runtime's selectors (X001, XY01, XYZW) and checked by `tests/semantic/test_buffer_format_narrow_int.py` (until 2026-11-22 those formats stored nothing). `tbuffer_store_format_*` and its `_d16_*` forms take the instruction's format instead of the V#'s, as the tbuffer loads do: only that format is encoded, and its element size decides the bounds check (an 8_UNORM byte is stored where the V#'s 16-byte element would not fit; a 16-byte element is dropped where the V#'s 4-byte one would fit). A V# whose FORMAT is 0 (INVALID) still disables the store. No `format:` modifier is GFX10's default, BUF_FMT_8_UNORM; a format FORMATS has no encoder for stays `Unsupported`. Measured natively on a Radeon 680M (gfx1035, wave32 = wave64) and GPU-checked by `cs_tbuffer_store.asm` (13 stores: f32, f16, 8_8_8_8 UINT and UNORM, 2_10_10_10, d16, the default format, more and fewer components than the format has, both bounds cases, a V# with FORMAT 0; exact on an RTX 3050 and the 680M); CPU-checked by `tests/semantic/test_tbuffer_store.py`. | 338| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint/sint 8/16, and the formats of the *Typed buffer formats* row). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. A store with fewer components than its format writes the whole element, with 0 for the components it doesn't give (`_xy` into 32_32_32_32 leaves z = w = 0, `_xyz` into 16_16_16_16 leaves w = 0); into a one-channel format only x is written. Measured natively on a Radeon 680M (gfx1035, RDNA2), and GPU-checked by `cs_fmt_xy_xyz.asm` for 32_32_32_32, 16_16_16_16, 8_8_8_8 UNORM and UINT and 32 (TEST-185). Unsigned integer stores saturate to the destination channel width. On native gfx1036, RGBA8_UINT, RG16_UINT and RGBA16_UINT clipped overflowing inputs to 255 or 65535, with RGBA32_UINT as a full-width control. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero; native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. `tbuffer_store_format_*` is not translated. 8- and 16-bit SINT stores clamp the signed 32-bit value to [-2^(w-1), 2^(w-1) - 1] (300 stores 127 into 8_SINT, -129 stores -128), and the 8/16-bit UINT formats 5, 11 and 18 saturate like the others; measured natively on gfx1036 for x, xy, xyzw and d16_xyzw stores (a d16 half is read as a signed 16-bit integer for SINT, so 0xff80 stores -128) with the runtime's selectors (X001, XY01, XYZW) and checked by `tests/semantic/test_buffer_format_narrow_int.py` (until 2026-11-22 those formats stored nothing). `tbuffer_store_format_*` and its `_d16_*` forms take the instruction's format instead of the V#'s, as the tbuffer loads do: only that format is encoded, and its element size decides the bounds check (an 8_UNORM byte is stored where the V#'s 16-byte element would not fit; a 16-byte element is dropped where the V#'s 4-byte one would fit). A V# whose FORMAT is 0 (INVALID) still disables the store. No `format:` modifier is GFX10's default, BUF_FMT_8_UNORM; a format FORMATS has no encoder for stays `Unsupported`. Measured natively on a Radeon 680M (gfx1035, wave32 = wave64) and GPU-checked by `cs_tbuffer_store.asm` (13 stores: f32, f16, 8_8_8_8 UINT and UNORM, 2_10_10_10, d16, the default format, more and fewer components than the format has, both bounds cases, a V# with FORMAT 0; exact on an RTX 3050 and the 680M); CPU-checked by `tests/semantic/test_tbuffer_store.py`. |
339| Typed buffer formats | `Gen.FORMATS` holds all 77 GFX10 codes a V# or MTBUF can carry (a buffer's `FORMAT` is 7 bits; codes from 128 are image-only, and there are no 5_6_5, 1_5_5_5, 5_5_5_1 or 4_4_4_4 buffer formats): the 8/16-bit UINT, SINT, USCALED and SSCALED families (USCALED/SSCALED: the integer converted to float, not divided), 10_11_11 and 11_11_10 in all seven numeric formats (the FLOAT ones are unsigned floats: 5 exponent bits, bias 15, 6 or 5 mantissa bits, no sign; the first number is the top field, so 36 has x in bits 10:0 and a 10-bit z on top), and the 10_10_10_2 (44–49) and 2_10_10_10 (50–55) families. Codes outside the table decode to 0 and store nothing. **Stores**: UINT and SINT saturate; UNORM and SNORM round the exact product once (`Gen.encode_norm_bits`: 0.3 · 65535 stores 19661; nearest even, but a half rounds away from zero in a 2-bit SNORM field); a SCALED store converts as the matching NORM format; float stores (16_FLOAT and the small floats) **round toward zero, saturate to the largest finite value (65504), keep a NaN a NaN and give 0 for a negative number in an unsigned float** (`Gen.ufloat_encode_bits`); **a two-component format stored through a V# takes channel y as its second component when DST_SEL_Y is Y and DST_SEL_Z a constant (the runtime's X,Y,0,1), channel w otherwise (identity XYZW: `_xy` writes (x, 0))**, and `tbuffer_store_format_*` takes (x, y) whatever the V# says. The typed-store encode is emitted once per module (`Gen.format_encode_call`: one encode function and one element-size function, each store site a call, like the shared decode), because inlined every site carried every format. **How confirmed**: `tools/buffer_format_fuzz.py --oracle hw` runs raw `buffer_load_format_xyzw` / `buffer_store_format_xyzw` / `_xy` / `tbuffer_*_format_*` kernels and compares every result word with a CPU model (a distinct value in every register). **Radeon 880M (gfx1150, RDNA3.5; GFX11 numbers its formats differently, so formats are mapped by name)**: 1,390,400 elements over the 63 formats GFX11 has, 0 mismatches. **Real RDNA2, gfx1036, by @AwkGrep256 on the Linux DRM backend ([#2022](https://github.com/ItsNotRexed/Leonida/pull/2022))**: the same totals, 1,330,469 validated and 26,523 elements of the (x, w) routing, 0 mismatches, and 199,144 elements of the 14 codes GFX11 lacks (10_11_11 and 11_11_10 non-FLOAT, 10_10_10_2 USCALED/SSCALED), 0 mismatches. Per-format counts in [buffer_formats.md](buffer_formats.md); `--negative-control` catches a wrong V# format on all but one or two elements. The translated SPIR-V is held to the same model by `tests/semantic/test_buffer_formats_all.py` (every added format, loads through the V# and tbuffer, stores, every older format's store, hand-worked values) and by the GPU test `cs_fmt_all.asm` (32 loads and 20 stores, on an AMD Radeon 880M and an NVIDIA RTX 5070); `cs_store`, `cs_fmt_*`, `cs_oob_*` and `cs_tbuffer_store` pass on both too. Three older stores used to differ from the hardware (f16 format stores rounded to nearest and overflowed to infinity, NORM stores rounded an f32 product twice, a two-component V# store always took (x, y)) and follow it now. **Unmeasured**: the console's gfx1013, d16 forms of the new kinds and of the (x, w) routing, `_xyz` into a two-component format, selector sets that reorder channels. |
317| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | 340| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). |
318| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`, `s_incperflevel`, `s_decperflevel`, `s_wakeup`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). `s_incperflevel` and `s_decperflevel` increment or decrement a performance counter (RDNA2 ISA SOPP, SIMM16[3:0]) and `s_wakeup` pings the other waves of the threadgroup out of an `s_sleep`, which is itself a no-op here; none writes a register, memory, SCC, VCC or EXEC, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | 341| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`, `s_incperflevel`, `s_decperflevel`, `s_wakeup`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). `s_incperflevel` and `s_decperflevel` increment or decrement a performance counter (RDNA2 ISA SOPP, SIMM16[3:0]) and `s_wakeup` pings the other waves of the threadgroup out of an `s_sleep`, which is itself a no-op here; none writes a register, memory, SCC, VCC or EXEC, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). |
319| Buffer format store rounding and 2-component `DST_SEL` (SHADER-364) | UNORM/SNORM stores (`Gen.encode_norm_bits`) round the exact product `clamp(x) * scale` once in 64-bit integer arithmetic with ties away from zero, instead of double-rounding through `OpFMul` + `RoundEven` (`UNORM16(0.3)` stores 19661, not 19660; `SNORM2(±0.5)` stores ±1). MUBUF `buffer_store_format_*` (and `_d16_*`) into 2-component formats infer `COMP_SWAP` from V# `DST_SEL_X/Y/Z`: `use_y = (sy >= 4) and (sz < 4)`, `rev = (sx != 4) and (sy >= 4 or sz >= 4)` (`XY01` → `(x, y)`, `YX01` → `(y, x)`, `XYZW` → `(x, w)` so `_xy` writes `(x, 0)`, `YXZW`/`ZYXW` → `(w, x)`); MTBUF `tbuffer_store_format_*` ignores `DST_SEL` and always stores `(x, y)`. Measured natively on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64) with `tools/buffer_store_probe.py`: 0 mismatches across 5 UNORM/SNORM formats (2,474 inputs × MUBUF/MTBUF × wave32/64 = 9,896 runs) + SNORM2 ties, all 12 2-component formats (`XY01` vs `XYZW`), and all 216 `(sx, sy, sz)` triples on `32_32_UINT`. Checked on CPU + `spirv-val` by `tests/semantic/test_buffer_store_rdna2.py` and `tests/test_buffer_store_probe.py`. | 342| Buffer format store rounding and 2-component `DST_SEL` (SHADER-364) | UNORM/SNORM stores (`Gen.encode_norm_bits`) round the exact product `clamp(x) * scale` once in 64-bit integer arithmetic with ties away from zero, instead of double-rounding through `OpFMul` + `RoundEven` (`UNORM16(0.3)` stores 19661, not 19660; `SNORM2(±0.5)` stores ±1). MUBUF `buffer_store_format_*` (and `_d16_*`) into 2-component formats infer `COMP_SWAP` from V# `DST_SEL_X/Y/Z`: `use_y = (sy >= 4) and (sz < 4)`, `rev = (sx != 4) and (sy >= 4 or sz >= 4)` (`XY01` → `(x, y)`, `YX01` → `(y, x)`, `XYZW` → `(x, w)` so `_xy` writes `(x, 0)`, `YXZW`/`ZYXW` → `(w, x)`); MTBUF `tbuffer_store_format_*` ignores `DST_SEL` and always stores `(x, y)`. Measured natively on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64) with `tools/buffer_store_probe.py`: 0 mismatches across 5 UNORM/SNORM formats (2,474 inputs × MUBUF/MTBUF × wave32/64 = 9,896 runs) + SNORM2 ties, all 12 2-component formats (`XY01` vs `XYZW`), and all 216 `(sx, sy, sz)` triples on `32_32_UINT`. Checked on CPU + `spirv-val` by `tests/semantic/test_buffer_store_rdna2.py` and `tests/test_buffer_store_probe.py`. |
343| `_d16_hi_` typed buffer forms (SHADER-755) | Only the single-component forms are instructions. `buffer_load_format_d16_hi_x` and `buffer_store_format_d16_hi_x` are the `_x` forms of the d16 load and store with their one component in bits 31:16 instead of 15:0; #1885 (SHADER-320) adds them. The multi-component spellings (`buffer_load_format_d16_hi_xy`, `_xyz`, `_xyzw`, and `buffer_store_format_d16_hi_*`) name no RDNA instruction and stay `Unsupported`: AMD's machine-readable [RDNA1 and RDNA2 ISA XML](isa_coverage.md) lists `BUFFER_LOAD_FORMAT_D16_HI_X` and `BUFFER_STORE_FORMAT_D16_HI_X` (MUBUF opcodes 0x026 and 0x027) as the only format D16 high-half instructions, and the packed widths `BUFFER_*_FORMAT_D16_X` to `_XYZW` (0x080-0x087) have no high-half counterpart; LLVM's gfx10 to gfx12 MUBUF tables define the same two, and the console's gfx1013 decodes through the gfx10 table, so no listing can carry one (the 25,735-shader corpus has none, reported in #4084). CPU-checked by `tests/semantic/test_buffer_format_d16_hi_absent.py`: every multi-component spelling raises `Unsupported`, and the packed forms translate as a control. |
320| `s_lshl1..4_add_u32` | D = (S0 << N) + S1. SCC = the sum taken in 64 bits is ≥ 2³², so a bit shifted out of S0 sets it as well as a carry out of the add (RDNA ISA pseudocode: `tmp = (64'U(S0) << N) + 64'U(S1)`). Checked on the CPU by `tests/semantic/test_salu_lshl_add.py`. **Hardware-verified** on the same gfx1100 part through `tools/hw_oracle`: `s_lshl1_add_u32(0x80000000, 0)` = 0 with SCC = 1 (the bit shifted out of S0 sets it, with no carry out of the add), `s_lshl2_add_u32(5, 3)` = 0x17 with SCC = 0, `s_lshl4_add_u32(1, 0)` = 0x10. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches across shift amounts 1–4, confirming that bits shifted out of S0 set SCC as well as sum overflow. | 344| `s_lshl1..4_add_u32` | D = (S0 << N) + S1. SCC = the sum taken in 64 bits is ≥ 2³², so a bit shifted out of S0 sets it as well as a carry out of the add (RDNA ISA pseudocode: `tmp = (64'U(S0) << N) + 64'U(S1)`). Checked on the CPU by `tests/semantic/test_salu_lshl_add.py`. **Hardware-verified** on the same gfx1100 part through `tools/hw_oracle`: `s_lshl1_add_u32(0x80000000, 0)` = 0 with SCC = 1 (the bit shifted out of S0 sets it, with no carry out of the add), `s_lshl2_add_u32(5, 3)` = 0x17 with SCC = 0, `s_lshl4_add_u32(1, 0)` = 0x10. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches across shift amounts 1–4, confirming that bits shifted out of S0 set SCC as well as sum overflow. |
321| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at the mip the "Gather sampler LOD" row chooses, in gather order. `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip `Floor(clamp(LOD, S# MIN_LOD, MAX_LOD) + 0.5)` (ties up, as native) in gather order. With `d16` those four taps round to binary16 and pack low half first into two consecutive VGPRs. The packed words and the first untouched VGPR were checked with `ps_gather_wrap.asm` on RTX 5080 and Radeon Graphics. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. The modulo is `OpSRem` plus the period when the remainder is negative, not `OpSMod`. On a Ryzen 5 7600's iGPU (RDNA2) with AMD's Windows driver 24.10.24, `OpSMod` of a negative coordinate came out with the dividend's sign: the three `ps_gather_wrap` cases whose wrap or mirror coordinate is negative (1, 2 and 6) fetched outside the image and read zeros, while the same module passed on an RTX 4070 SUPER. With `OpSRem` and the fix-up, all 4096 pixels are exact on both. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. A literal S# with a border mode (4-7: half-border, border colour) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4-7 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Modes 6 (clamp border) and 7 (mirror once border) give a tap whose coordinate, before the clamp, is outside [0, n-1] on either axis the S# border colour's channel instead of the fetched texel: BORDER_COLOR_TYPE = word 3 [31:30] (Mesa `gfx10-rsrc.json` `SQ_IMG_SAMP_WORD3`, `SQ_TEX_BORDER_COLOR_*` in `gfx6.json`), 0 transparent black, 1 opaque black (alpha 1), 2 opaque white; 1 for an integer format, as Vulkan's `INT_OPAQUE_*`. Type 3 (a colour from the border-colour table, `BORDER_COLOR_PTR`) is `Unsupported` on a literal S# and transparent black at run time (SHADER-348: since #1567 made the game's S# words literals, 16 of the corpus's mode-6 gathers failed as `Unsupported`; before that they ran as clamp-to-edge). A literal S# with a half-border mode (4, 5) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4 and 5 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two, and a table border colour (BORDER_COLOR_TYPE 3) on a run-time S#, which gives transparent black, are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070; the border modes with `runtime/test/shaders/ps_gather_border.asm` (two literal and two run-time S#s, opaque white and transparent black, modes 6 and 7) on NVIDIA RTX 4070 SUPER (driver 621.01), with `tests/test_translate.py`'s `test_gather4_l_*border*`. `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | 345| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at the mip the "Gather sampler LOD" row chooses, in gather order. `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip `Floor(clamp(LOD, S# MIN_LOD, MAX_LOD) + 0.5)` (ties up, as native) in gather order. With `d16` those four taps round to binary16 and pack low half first into two consecutive VGPRs. The packed words and the first untouched VGPR were checked with `ps_gather_wrap.asm` on RTX 5080 and Radeon Graphics. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. The modulo is `OpSRem` plus the period when the remainder is negative, not `OpSMod`. On a Ryzen 5 7600's iGPU (RDNA2) with AMD's Windows driver 24.10.24, `OpSMod` of a negative coordinate came out with the dividend's sign: the three `ps_gather_wrap` cases whose wrap or mirror coordinate is negative (1, 2 and 6) fetched outside the image and read zeros, while the same module passed on an RTX 4070 SUPER. With `OpSRem` and the fix-up, all 4096 pixels are exact on both. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. Modes 6 (clamp border) and 7 (mirror once border) give a tap whose coordinate, before the clamp, is outside [0, n-1] on either axis the S# border colour's channel instead of the fetched texel: BORDER_COLOR_TYPE = word 3 [31:30] (Mesa `gfx10-rsrc.json` `SQ_IMG_SAMP_WORD3`, `SQ_TEX_BORDER_COLOR_*` in `gfx6.json`), 0 transparent black, 1 opaque black (alpha 1), 2 opaque white; 1 for an integer format, as Vulkan's `INT_OPAQUE_*`. Type 3 (a colour from the border-colour table, `BORDER_COLOR_PTR`) is `Unsupported` on a literal S# and transparent black at run time (SHADER-348: since #1567 made the game's S# words literals, 16 of the corpus's mode-6 gathers failed as `Unsupported`; before that they ran as clamp-to-edge). A literal S# with a half-border mode (4, 5) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4 and 5 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two, and a table border colour (BORDER_COLOR_TYPE 3) on a run-time S#, which gives transparent black, are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070; the border modes with `runtime/test/shaders/ps_gather_border.asm` (two literal and two run-time S#s, opaque white and transparent black, modes 6 and 7) on NVIDIA RTX 4070 SUPER (driver 621.01), with `tests/test_translate.py`'s `test_gather4_l_*border*`. `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). |
322| `v_mad_u64_u32`, `v_mad_i64_i32` | {sdst, D} = S0 × S1 + S2 as a 65-bit result (RDNA ISA pseudocode), the product unsigned or signed. sdst (a lane mask) gets bit 64 for active lanes and 0 for lanes off in EXEC (`EXEC[lane] ? bit64 : 0`, matching `v_cmp_*` and `*_co_*`): the carry out for u64, and for i64 the sign of the exact sum (bit 64 of a 65-bit two's-complement value), not a signed-overflow flag. `tools/lane_masks.py` tracks sdst as a lane mask (until 2026-11-22 it only matched `*_co_*`, so `s_bcnt1`/`s_ff1`/`v_mbcnt` on sdst read each lane's own mask word as plain data). `clamp` is rejected. Checked on the CPU by `tests/test_lane_masks.py`, `tests/semantic/test_alu_mad64.py` (including 64-lane `s_bcnt1_i32_b64`/`s_ff1_i32_b64` ballot tests), and `tests/semantic/test_carry_exec_mask.py` (EXEC masking on inactive lanes). **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): unsigned carry, signed positive overflow `(-2³¹)² + INT64_MAX` giving `sdst = 0`, negative sum giving `sdst = 1`, and inactive EXEC lane leaving D untouched with `sdst = 0` all match bit-for-bit. | 346| `v_mad_u64_u32`, `v_mad_i64_i32` | {sdst, D} = S0 × S1 + S2 as a 65-bit result (RDNA ISA pseudocode), the product unsigned or signed. sdst (a lane mask) gets bit 64 for active lanes and 0 for lanes off in EXEC (`EXEC[lane] ? bit64 : 0`, matching `v_cmp_*` and `*_co_*`): the carry out for u64, and for i64 the sign of the exact sum (bit 64 of a 65-bit two's-complement value), not a signed-overflow flag. `tools/lane_masks.py` tracks sdst as a lane mask (until 2026-11-22 it only matched `*_co_*`, so `s_bcnt1`/`s_ff1`/`v_mbcnt` on sdst read each lane's own mask word as plain data). `clamp` is rejected. Checked on the CPU by `tests/test_lane_masks.py`, `tests/semantic/test_alu_mad64.py` (including 64-lane `s_bcnt1_i32_b64`/`s_ff1_i32_b64` ballot tests), and `tests/semantic/test_carry_exec_mask.py` (EXEC masking on inactive lanes). **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): unsigned carry, signed positive overflow `(-2³¹)² + INT64_MAX` giving `sdst = 0`, negative sum giving `sdst = 1`, and inactive EXEC lane leaving D untouched with `sdst = 0` all match bit-for-bit. |
323| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, misses = `0xFFFFFFFF`, sorted when descriptor bit 63 (box_sort_enable) is set. **The box test is the native one, measured on RDNA2** (SHADER-650; RX 6900 XT, gfx1030, `tools/hw_oracle` raw kernels, 338 cases: BOX32 and BOX16, four rays including negative directions, NaN in every position, empty boxes, planes on the origin, and every tie order of four children; the translator now matches all 338 bit for bit, `main` before it 43): per axis, the near plane is min and the far plane max when the inverse direction (taken as given, not clamped) is ≥ 0, swapped otherwise; t = (plane − origin) × inverse direction, so `0 × inf` is NaN. tnear = max of the three near t, tfar = min of the three far t, **each skipping NaN**; all three near or all three far NaN is a miss. Hit when max(tnear, 0) ≤ tfar and tnear < extent (the extent boundary itself was not measured). So a lone NaN bound leaves its own plane open (a box with min.x = NaN is hit wherever x ≤ max.x), an empty box (min > max on any axis, ±inf or ±65504 included) is a miss without a separate check, and a plane exactly on the origin along a zero-direction axis is open. The sort key is max(tnear, 0), so boxes around the origin tie at 0, ordered by the network (0,2) (1,3) (0,1) (2,3) (1,2) with a strict `<` swap (all 88 measured tie orders). `tests/semantic/test_image_bvh_box_hw.py` holds measured words. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a). These two references agree; no game BVH is decoded yet to count over. The triangle rule has not been run natively yet; the box rule above has (`tools/hw_oracle` on an AMD RDNA2 card runs the instruction itself). `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (measured on gfx1030: the 32-bit form with a non-zero base and the 64-bit form with base 0 and the full address gave the same words in 71 cases). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact; its box with a NaN min.x is entered at t = 0 and sorts first (`0x68 0x48 0x40 0xffffffff`), as native gfx1030 returns for that scene. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. | 347| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. **The box test is the native one, measured on RDNA2** (SHADER-650; RX 6900 XT, gfx1030, `tools/hw_oracle` raw kernels, 338 cases: BOX32 and BOX16, four rays including negative directions, NaN in every position, empty boxes, planes on the origin, and every tie order of four children; the translator now matches all 338 bit for bit, `main` before it 43): per axis, the near plane is min and the far plane max when the inverse direction (taken as given, not clamped) is ≥ 0, swapped otherwise; t = (plane − origin) × inverse direction, so `0 × inf` is NaN. tnear = max of the three near t, tfar = min of the three far t, **each skipping NaN**; all three near or all three far NaN is a miss. BOX32 and BOX16, four rays including negative directions, NaN in every position, empty boxes, planes on the origin, and every tie order of four children; the translator now matches all 338 bit for bit, `main` before it 43, and all 811 rounding cases below): per axis, the near plane is min and the far plane max when the inverse direction (taken as given, not clamped) is ≥ 0, swapped otherwise; t = (plane − origin) × inverse direction, so `0 × inf` is NaN. **Both the subtraction and the multiply round toward zero** (811 more cases, 800 randomized slabs at origins 2^18 to 2^27 away plus 11 ties: round-to-nearest predicts 769 of them, round-toward-zero all 811; among the ties, a box with min.x = 1 > max.x = 0 at origin.x = −2^25 is a hit on hardware because both planes round to the same t). The translator emulates this exactly: the subtraction's error comes from TwoSum, the product's error sign from a Dekker split of the two mantissas scaled to [1, 2), and a result rounded away from zero steps one ulp back; a finite overflow gives ±FLT_MAX. tnear = max of the three near t, tfar = min of the three far t, **each skipping NaN**; all three near or all three far NaN is a miss. Hit when max(tnear, 0) ≤ tfar and tnear < extent (the extent boundary itself was not measured). So a lone NaN bound leaves its own plane open (a box with min.x = NaN is hit wherever x ≤ max.x), an empty box (min > max on any axis, ±inf or ±65504 included) is a miss without a separate check, and a plane exactly on the origin along a zero-direction axis is open. The sort key is max(tnear, 0), so boxes around the origin tie at 0, ordered by the network (0,2) (1,3) (0,1) (2,3) (1,2) with a strict `<` swap (all 88 measured tie orders). `tests/semantic/test_image_bvh_box_hw.py` holds measured words. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2 and 3 = vertex 0, bits [7:4] ignored; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a), and the hardware agrees. **The triangle step is the native one, measured on RDNA2** (AMD Radeon RX 6800, gfx1030, AMD Windows driver 26.11.2, Windows 11, 2026-11-22; the `tools/hw_oracle` kernels `tools/bvh_tri_probe.py` builds, hand-built nodes and rays: 14 kernels, 308 single-lane cases and 7 cases on 64 lanes, 1,204 results, each in both forms; the 32-bit form with the descriptor base at the node and the 64-bit form with base 0, wave32 and wave64, NSA and contiguous operands all gave the same words). A NaN anywhere in t max, the origin, the direction or the inverse direction, or an infinite origin, returns (+inf, 1.0, +0, +0). Otherwise the watertight test runs with its shear taken from the direction (kz = the axis of the largest \|d\|, ties x, y, z; kx and ky swapped when d[kz] < 0; Sz = 1/d[kz]): **the supplied inverse direction is not used**. With the edge functions U, V, W, det = U + V + W, T = t·det and k = \|d[kz]\|³, a hit returns (k·T, k·det, k·b_i, k·b_j) and a miss (copysign(inf, k·det), k·det, k·b_i, k·b_j): numerators over the denominator k·det, and a miss keeps the plane's barycentric numerators. det = 0 is a miss with word 0 = +inf. The hit needs t ≥ 0 (t = 0 hits); there is no test against t max. Every zero word is +0 and every NaN word 0xFFC00000, so a NaN det gives word 0 = −inf. An edge function of 0 is inside when its edge passes RDNA2's tie rule, which is not RADV's: the edge from P to Q (U: B→C, V: C→A, W: A→B), with (tx, ty) = Q′ − P′ in the sheared frame with the d[kz] < 0 swap of kx and ky undone, passes when ty = 0 ? sign(det)·tx > 0 : sign(d[kz])·sign(det)·ty > 0, and every zero edge must pass. Every shared edge and shared vertex gave exactly one hit. How this rule was found: the first fit (ty = 0 ? tx < 0 : sign(det)·ty > 0, on the 49 tie rows of the first measurement, all z dominant) was confounded, because every one of those rows had det < 0 with d[kz] > 0 or det > 0 with d[kz] < 0, and it was wrong in the cells it never saw. A second measurement (2026-11-23, same part and driver; 8 more kernels, 256 rows: ties with x, y and z dominant, both windings, both signs of d[kz], every edge direction class in each of those cells, tilted triangles with oblique rays, equal \|d\| components) fitted none of the eight rules registered before it ran. The rule above was then read off its x/y rows (post hoc), and it predicted the z-dominant bridge kernel `tri_t8` before that ran: 32 of 32 cases, 10 of them rows where it and the first fit disagree. The translator computes these words without a division, with the shear multiplied through by \|d[kz]\| (a shear divided by d[kz] gives the same words on every measured row but d.z = +inf, and divides by zero at d = 0; this form gives d = 0 → (+inf, 0, 0, 0) and d.z = +inf → (−inf, NaN, −inf, −inf) as measured, a fit after the runs), and fixes zero signs and NaN bits with integer selects, so every measured input is defined SPIR-V. `tests/semantic/test_image_bvh_tri_hw.py` asserts all 308 rows and 84 lane results of the first measurement and the 256 rows of the second bit for bit (the translator before it: 129 of the first 308; the first fit: 210 of the 256); `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. **A consumer that divides by word 1** (t = w0/w1, weights w2/w1 and w3/w1) gets t and the weights on a hit (k cancels; word 1 keeps det's sign); +inf for t on a miss of either winding, with the plane's weights; t = +inf/+0 = +inf and weights 0/0 on a zero-area triangle; t = NaN with a NaN or inf vertex, so a `t < t max` test fails as on a miss; t = +inf with a NaN in the ray or an infinite origin. It must compare t with t max itself. The translator's earlier normalised words (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|; a miss (inf, 1, 0, 0)) gave such a consumer the same t on every row and the same weights on every hit except on 14 shared-edge rows (RADV's tie rule), 3 rows whose inverse direction is not 1/d, 3 rows with a NaN in the ray (it reported a hit or other words), the v0.x = −inf and d.z = +inf rows, and 14 rows that were undefined SPIR-V there (zero area, a NaN or inf vertex, a NaN, inf or zero ray). **Not measured:** gfx1013 (the console); node types 6 and 7; the box extent boundary; descriptor words other than w2 = 0xFFFFFFFF, w3 = 0x81000000 (return mode 0 included); the dominant axis on equal \|d\| components except where a measured tie row tells the axes apart: x for \|dx\| = \|dy\| > \|dz\| (only with dx, dy > 0), x for \|dx\| = \|dz\| > \|dy\| (not with dx > 0 > dz), y for \|dy\| = \|dz\| > \|dx\| (only with dy, dz of the same sign) and x with all three equal (in the four of the eight sign patterns that ran), which is the translator's `>=` order (a non-tie row gives the same words whatever the choice, and every sign pattern could show it with the right tie); rounding-sensitive inputs (every input is dyadic, so the divided versus multiplied-through shear and fused versus separate rounding are not told apart); d = 0 and infinite d beyond one row each; the remap's high nibble on TRI1–TRI3. These two references agree; one real pack BLAS is now matched, rehydrated and traversed (§7b), though the rule has not been counted over the whole corpus. The triangle rule has not been measured on the native instruction yet: `tools/hw_oracle` can run it on RDNA2, and box32 nodes were measured that way (gfx1036, address = base × 256 + (node & ~7) × 8 in both instruction widths, §7b), so the triangle counterpart is a possible follow-up rather than an impossibility. These two references agree; no game BVH is decoded yet to count over. The triangle rule has not been run natively yet; the box rule above has (`tools/hw_oracle` on an AMD RDNA2 card runs the instruction itself). `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter, including the descriptor-base case. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3). The descriptor's dword0 is the base in 256-byte units: the game passes `ptr >> 8` there, and the `\| 0x30` its shader ORs is only the temporary address it uses to load `rootNodePtr`, not the descriptor base. Measured at base 0 and at base 0x1000 (structure at VA 0x1000, dword0 `0x10`): the GPU returns the CPU walker's children in the same order at both, so the `<< 8` is correct and a nonzero base needs no masking. `tests/semantic/test_image_bvh_tri.py` runs the nonzero base (`0x10` → `0x1000`). Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (measured on gfx1030: the 32-bit form with a non-zero base and the 64-bit form with base 0 and the full address gave the same words in 71 cases). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact; its box with a NaN min.x is entered at t = 0 and sorts first (`0x68 0x48 0x40 0xffffffff`), as native gfx1030 returns for that scene. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. Corpus counts (`tools/image_bvh_census.py`, static, [bvh.md](bvh.md) §7): 716 sites, 638 32-bit and 78 64-bit; the descriptor has box_sort_en 1, big_page 1, size all ones and type 8 at every site; on every path from the call, 397 sites take `v_rcp_f32` of word 1, multiply word 0 (335 also words 2 and 3) by it and read `sext(w1[31:16])`, all 716 read the words as integers (397 through shifts and `v_and_or_b32`/`v_lshl_or_b32`/`v_or3_b32`, 319 through `v_cmp_eq_u32` only), and none reads a word undivided as a float; 633 sites also have reads on some paths only, which the census leaves unclassified. |
324| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS (tier C of the *Wave64 graphics* row; tiers A and B are exact); compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | 348| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS (tier C of the *Wave64 graphics* row; tiers A and B are exact); compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). |
325| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` with the p0 select is declared `Flat` (a location a p10/p20 mov reads is `PerVertexKHR`, next row). A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. | 349| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` with the p0 select is declared `Flat` (a location a p10/p20 mov reads is `PerVertexKHR`, next row). A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. On the CPU, `test_v_interp_mov_emits_flat_decoration` and `test_attribute_read_both_flat_and_interpolated_is_not_flat` in `tests/semantic/test_interp_mov_flat.py` check the Flat decoration of a p0-only location and that a location also read with p1/p2 is not decorated Flat. |
326| v_interp operand guards (SHADER-177) | The single-lane model reads the attribute's own value for `v_interp_p1/p2`, which is only right when the VGPR source really holds the barycentric coordinate that op interpolates with — **p1 reads I = v0 and p2 reads J = v1, per op** — and `v_interp_mov_f32` p0 is the provoking vertex (p10/p20 are the deltas of the vertex-delta row above). A p1/p2 (f32 and f16 forms) whose source is not its own coordinate — v0 for p1, v1 for p2, each either the hardware register or a plain `v_mov_b32` copy rooted at it (the copy's single write in the whole shader, defined before the use, copy chains followed, and its source v0/v1 itself unwritten up to the copy: a copy of an already-overwritten v0/v1 carries a computed value — zeroing the source before copying renders (0,0) on hardware — while a write after the copy is fine, the copy saved the value) — is **Unsupported**, naming the register and the role, so a swapped p1(v1)/p2(v0) pair, a both-v0 pair, or a copy of an overwritten source is refused rather than silently mistranslated; `v_interp_mov_f32` with p10/p20 was **Unsupported** until the vertex-delta row above; any other select still is, naming it. `v_interp_mov_f32` with p10/p20 is **Unsupported**, naming the select. A **direct** v0/v1 read stays accepted even when the shader overwrites v0/v1 first (evaluate-at-offset/snapped barycentrics; up to 213 PS, #1218): modelling that computed value is the separate provenance follow-up. Zero corpus cost: over the 26,503-shader corpus every f32 I/J source is v0/v1 (117,001 / 116,997) except one PS whose four `v_interp_p2_f32` read J through `v_mov_b32 v14, v1` (its v1 unwritten up to the copy; the later overwrites are the saved-copy case), which the copy rule keeps translating (bit-identical .spv), every f16 source is v0/v1 (58,950 / 58,950), and all 6,926 `v_interp_mov_f32` use p0. Confirmed by `tests/semantic/test_interp_guards.py` (refusals name the operand and its role, including swapped and both-v0 pairs, a wrong-root copy, and a copy of an overwritten source; the copy, copy-chain, matching-role and saved-from-later-zero cases translate and compute; a second write or a dpp copy no longer qualifies; a mutation check that the guard consults the copy analysis) and by re-translating a 200-shader corpus slice plus that PS before and after: translated/valid counts and every .spv unchanged. | 350| v_interp operand guards (SHADER-177) | The single-lane model reads the attribute's own value for `v_interp_p1/p2`, which is only right when the VGPR source really holds the barycentric coordinate that op interpolates with — **p1 reads I = v0 and p2 reads J = v1, per op** — and `v_interp_mov_f32` p0 is the provoking vertex (p10/p20 are the deltas of the vertex-delta row above). A p1/p2 (f32 and f16 forms) whose source is not its own coordinate — v0 for p1, v1 for p2, each either the hardware register or a plain `v_mov_b32` copy rooted at it (the copy's single write in the whole shader, defined before the use, copy chains followed, and its source v0/v1 itself unwritten up to the copy: a copy of an already-overwritten v0/v1 carries a computed value — zeroing the source before copying renders (0,0) on hardware — while a write after the copy is fine, the copy saved the value) — is **Unsupported**, naming the register and the role, so a swapped p1(v1)/p2(v0) pair, a both-v0 pair, or a copy of an overwritten source is refused rather than silently mistranslated; `v_interp_mov_f32` with p10/p20 was **Unsupported** until the vertex-delta row above; any other select still is, naming it. `v_interp_mov_f32` with p10/p20 is **Unsupported**, naming the select. A **direct** v0/v1 read stays accepted even when the shader overwrites v0/v1 first (evaluate-at-offset/snapped barycentrics; up to 213 PS, #1218): modelling that computed value is the separate provenance follow-up. Zero corpus cost: over the 26,503-shader corpus every f32 I/J source is v0/v1 (117,001 / 116,997) except one PS whose four `v_interp_p2_f32` read J through `v_mov_b32 v14, v1` (its v1 unwritten up to the copy; the later overwrites are the saved-copy case), which the copy rule keeps translating (bit-identical .spv), every f16 source is v0/v1 (58,950 / 58,950), and all 6,926 `v_interp_mov_f32` use p0. Confirmed by `tests/semantic/test_interp_guards.py` (refusals name the operand and its role, including swapped and both-v0 pairs, a wrong-root copy, and a copy of an overwritten source; the copy, copy-chain, matching-role and saved-from-later-zero cases translate and compute; a second write or a dpp copy no longer qualifies; a mutation check that the guard consults the copy analysis) and by re-translating a 200-shader corpus slice plus that PS before and after: translated/valid counts and every .spv unchanged. |
327| Pixel-shader interpolants | When a sidecar `fssm/<name>.fssm` holds a pixel-input table (`tools/fssm_header.py`: 8-byte records from 0x138 while the first byte is 6; table position = `v_interp attr` number), every position 0..count−1 is declared as a fragment input at that Location, including positions the code never reads (the table overcounts the code's distinct `v_interp` attrs in 775 of 12,101 PS: 300 by one, 475 by two or more; only the 10 records starting with kind 7 undercount). A 32-bit `v_interp` read (`p1/p2/mov`) of a 16-bit-flagged position (flag bit 4; **measured natively on RDNA2**, AMD Radeon 680M `gfx1035` in wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430: the VINTRP unit reads the same LDS parameter-cache dwords at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}` with no hidden 16-bit unpacking, so `v_interp_mov_f32` returns the raw 32-bit parameter word and `v_interp_p1_f32`/`v_interp_p2_f32` interpolate those 32-bit words as binary32), and reads past the table still declare an input (the value is undefined on hardware). 11,199 such inputs corpus-wide, matching the `*_f16` interpolation opcodes in 99.7%) sees the value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, back to f32) via a single `OpQuantizeToF16` (a `PackHalf2x16`/`UnpackHalf2x16` round-trip is folded to a no-op by at least one Vulkan driver, RTX 5080); reads through the `*_f16` opcodes already narrow and are unchanged (on a location an f16 op also reads, the f32 read is of the per-vertex raw word, "16-bit interpolation"; on gfx1036 a 32-bit `p1/p2_f32` read of a packed channel takes the raw LDS words as f32 bits, one fma each (SHADER-430, `tools/interp_hw_probe.py`); what P10/P20 words the SPI stores for such a channel is unverified), and reads past the table still declare an input (the value is undefined on hardware). Without a sidecar, or with an empty table, the output is byte-identical to the code-driven path. Confirmed by synthetic fixtures plus mini-interpreter agreement (`tests/test_rdna2spirv_pixelinput.py`: an f32 read of a flagged slot with input 1.1 yields the f16-rounded 1.099609375; unflagged and table-less controls yield exact 1.1) and `tests/test_vinterp_hw_probe.py`. The `index.json` entry records `ps_interpolants` (count) and `ps_fp16_interpolants` (flagged positions). | 351| Pixel-shader interpolants | When a sidecar `fssm/<name>.fssm` holds a pixel-input table (`tools/fssm_header.py`: 8-byte records from 0x138 while the first byte is 6; table position = `v_interp attr` number), every position 0..count−1 is declared as a fragment input at that Location, including positions the code never reads (the table overcounts the code's distinct `v_interp` attrs in 775 of 12,101 PS: 300 by one, 475 by two or more; only the 10 records starting with kind 7 undercount). A 32-bit `v_interp` read (`p1/p2/mov`) of a 16-bit-flagged position (flag bit 4; **measured natively on RDNA2**, AMD Radeon 680M `gfx1035` in wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430: the VINTRP unit reads the same LDS parameter-cache dwords at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}` with no hidden 16-bit unpacking, so `v_interp_mov_f32` returns the raw 32-bit parameter word and `v_interp_p1_f32`/`v_interp_p2_f32` interpolate those 32-bit words as binary32), and reads past the table still declare an input (the value is undefined on hardware). 11,199 such inputs corpus-wide, matching the `*_f16` interpolation opcodes in 99.7%) sees the value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, back to f32) via a single `OpQuantizeToF16` (a `PackHalf2x16`/`UnpackHalf2x16` round-trip is folded to a no-op by at least one Vulkan driver, RTX 5080); reads through the `*_f16` opcodes already narrow and are unchanged (on a location an f16 op also reads, the f32 read is of the per-vertex raw word, "16-bit interpolation"; on gfx1036 a 32-bit `p1/p2_f32` read of a packed channel takes the raw LDS words as f32 bits, one fma each (SHADER-430, `tools/interp_hw_probe.py`); what P10/P20 words the SPI stores for such a channel is unverified), and reads past the table still declare an input (the value is undefined on hardware). Without a sidecar, or with an empty table, the output is byte-identical to the code-driven path. Confirmed by synthetic fixtures plus mini-interpreter agreement (`tests/test_rdna2spirv_pixelinput.py`: an f32 read of a flagged slot with input 1.1 yields the f16-rounded 1.099609375; unflagged and table-less controls yield exact 1.1) and `tests/test_vinterp_hw_probe.py`. The `index.json` entry records `ps_interpolants` (count) and `ps_fp16_interpolants` (flagged positions). |
328| PS interpolation modes (SHADER-181) | Every interpolated pixel input in this build is **perspective-correct at the pixel center**, and every other input is flat, so the single v0/v1 pair the code reads is `PERSP_CENTER`. The translator models exactly these two: Flat for `v_interp_mov_f32`, plain (perspective, center) inputs and `BaryCoordKHR` for `v_interp_p1/p2` and the f16 forms. Two records describe each input, and they state **different facts**: PSV0 (DXBC) stores the interpolation **mode**; the FSSM input record's flags byte (byte 7) stores the **read method** — bit 0 (0x01) marks `v_interp_mov_f32` (4,600 records), bit 1 (0x02) 32-bit `v_interp_p1/p2` (51,191; values 0 and 3 never occur), bit 3 (0x08) a Float16-typed parameter (11,619), bit 4 (0x10) the `*_f16` opcodes (11,199; 24 f16-read records lack it). The flag/usage cross-table over all 55,791 records has no contradiction: every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 positions), every bit-1 position only by `v_interp_p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). **The mode is in PSV0, not the FSSM**: `tools/ps_interp_modes.py` decodes it from the PSV0 signature elements (`DXIL::InterpolationMode`, "must match D3D_INTERPOLATION_MODE": 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, 5 LinearNoperspectiveCentroid, 6 LinearSample, 7 LinearNoperspectiveSample; the 16-byte elements carry row, cols, semantic kind, component type and the mode — layout in the Pixel-shader inputs section) and maps the modes onto the `SPI_PS_INPUT_ENA` barycentric-pair bits (Mesa `gfx103.json` register type SPI_PS_INPUT_ENA: PERSP_SAMPLE/CENTER/CENTROID = bits 0/1/2, LINEAR_SAMPLE/CENTER/CENTROID = bits 4/5/6; the same type serves `SPI_PS_INPUT_ADDR`). **No FSSM word stores ENA/ADDR**: every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the signature-reconstructed ENA and only constant coincidences matched, and the register addresses (0x286CC/0x286D0, or 0xA1B3/0xA1B4 as context-register indices) appear in no PS blob, so the v2.. position layout of "PS system inputs" (one enabled pair) is the only ENA witness. The #2735 packed-component census matched PSV0, FSSM and disassembly for all 12,101 indexed PS. Of 101,024 declared input rows, 77,245 have a nonzero read mask. Census (12,101 PS; 101,024 declared / 77,245 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 4,529 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. 101,024 declared / 76,215 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 3,652 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. ISG1 has no mode field, and the DXIL part carries no bitcode. SV_Position is mode 4 (11,295 rows) or mode 5 (27), both noperspective by the D3D rule. With packed-component read masks, the classifier assigns 10,260 shaders to the perspective-centre pair and 1,841 to no pair. None classify as linear-centre. Hardware delivery of SV_Position was not measured by this census. Front face is a system input (1,984 rows, 345 read, at most one per shader). It assigns none to a linear pair. This count measures input classification; it does not directly measure how the hardware delivers SV_Position; front face is a system input (1,984 rows, 345 read, at most one per shader). SV_Position is mode 4 (11,295 rows) or mode 5 (27) — noperspective by the D3D rule — and is delivered through the system VGPRs in every shader except **4**, which interpolate it through the parameter cache with the *linear* pair (`FragCoord` stays at the pixel center, which only differs at partly covered MSAA pixels); front face is a system input (1,984 rows, 345 read, at most one per shader). The code reads **one** barycentric pair per shader: v0/v1 in 10,259, none in 1,841, and one shader reads J from v14 (a copy of v1), so the perspective-centre assumption holds for every interpolated generic input. **Mode and read method disagree in thousands of rows** — the residual surface for modelling is: those 4 linear-pair position shaders, Constant rows read via `p1/p2` or `*_f16` (2,190 records at the matching table position; flat semantics in hardware, not modelled), and Linear rows read only by `v_interp_mov_f32` (3,197; already declared `Flat`). The translator's table check (`check_read_methods`, the row below) compares each read's opcode against the record's read-method bits (`fssm_header.read_methods`) — since the bits restate the read method, it rejects 0 of 12,101 PS: a consistency check between the two encodings of the read, not a mode check (a centroid/sample/noperspective input would still read `v_interp_p1/p2` and pass; that every interpolated input is perspective-centre is the PSV0 census result above, so keying a refusal on genuinely unmodelled modes means decoding PSV0, not reading these bits). Counted with `tools/ps_interp_modes.py` (stdlib; PSV0, FSSM and disassembly in one pass; #1301 removed the earlier #1246 census tool in favour of it) on the 1.0.2.1 corpus; tests `tests/test_ps_interp_modes.py`, `tests/test_fssm_header.py` and `tests/test_rdna2spirv_pixelinput.py` (synthetic). No GPU test: no shader needs centroid or sample interpolation. **Not covered:** bit 3 (0x08) is set in 11,619 records (all 11,199 16-bit ones, 396 flat, 24 linear). The 213 PS that overwrite v0/v1 before a `v_interp` (SHADER-178) compute their own barycentrics in code; PSV0 gives them no other mode. | 352| PS interpolation modes (SHADER-181) | Every interpolated generic pixel input in this build is **perspective-correct at the pixel center**, and every other input is flat, so the single v0/v1 pair the code reads is `PERSP_CENTER`. The translator models exactly these two: Flat for `v_interp_mov_f32`, plain (perspective, center) inputs and `BaryCoordKHR` for `v_interp_p1/p2` and the f16 forms. Two records describe each input, and they state **different facts**: PSV0 (DXBC) stores the interpolation **mode**; the FSSM input record's flags byte (byte 7) stores the **read method** — bit 0 (0x01) marks `v_interp_mov_f32` (4,600 records), bit 1 (0x02) 32-bit `v_interp_p1/p2` (51,191; values 0 and 3 never occur), bit 3 (0x08) a Float16-typed parameter (11,619), bit 4 (0x10) the `*_f16` opcodes (11,199; 24 f16-read records lack it). The flag/usage cross-table over all 55,791 records has no contradiction: every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 positions), every bit-1 position only by `v_interp_p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). **The mode is in PSV0, not the FSSM**: `tools/ps_interp_modes.py` decodes it from the PSV0 signature elements (`DXIL::InterpolationMode`, "must match D3D_INTERPOLATION_MODE": 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, 5 LinearNoperspectiveCentroid, 6 LinearSample, 7 LinearNoperspectiveSample; the 16-byte elements carry row, cols, semantic kind, component type and the mode — layout in the Pixel-shader inputs section) and maps the modes onto the `SPI_PS_INPUT_ENA` barycentric-pair bits (Mesa `gfx103.json` register type SPI_PS_INPUT_ENA: PERSP_SAMPLE/CENTER/CENTROID = bits 0/1/2, LINEAR_SAMPLE/CENTER/CENTROID = bits 4/5/6; the same type serves `SPI_PS_INPUT_ADDR`). **No FSSM word stores ENA/ADDR**: every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the signature-reconstructed ENA and only constant coincidences matched, and the register addresses (0x286CC/0x286D0, or 0xA1B3/0xA1B4 as context-register indices) appear in no PS blob, so the v2.. position layout of "PS system inputs" (one enabled pair) is the only ENA witness. The #2735 packed-component census matched PSV0, FSSM and disassembly for all 12,101 indexed PS. Of 101,024 declared input rows, 77,245 have a nonzero read mask. Census (12,101 PS; 101,024 declared / 77,245 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 4,529 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. 101,024 declared / 76,215 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 3,652 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. ISG1 has no mode field, and the DXIL part carries no bitcode. SV_Position is mode 4 (11,295 rows) or mode 5 (27), both noperspective by the D3D rule. With packed-component read masks, the classifier assigns 10,260 shaders to the perspective-centre pair and 1,841 to no pair. None classify as linear-centre. Hardware delivery of SV_Position is outside the scope of the census. Front face is a system input (1,984 rows, 345 read, at most one per shader). It assigns none to a linear pair. This count measures input classification; it does not directly measure how the hardware delivers SV_Position; front face is a system input (1,984 rows, 345 read, at most one per shader). SV_Position is mode 4 (11,295 rows) or mode 5 (27) — noperspective by the D3D rule — and is delivered through the system VGPRs in every shader except **4**, which interpolate it through the parameter cache with the *linear* pair (`FragCoord` stays at the pixel center, which only differs at partly covered MSAA pixels); front face is a system input (1,984 rows, 345 read, at most one per shader). The code reads **at most one** barycentric pair per shader: v0/v1 in 10,259, none in 1,841, and one shader reads J from v14 (a copy of v1), so the perspective-centre assumption holds for every interpolated generic input. **Mode and read method disagree in thousands of rows** — the residual surface for modelling is: those 4 linear-pair position shaders, Constant rows read via `p1/p2` or `*_f16` (2,190 records at the matching table position; flat semantics in hardware, not modelled), and Linear rows read only by `v_interp_mov_f32` (3,197; already declared `Flat`). The translator's table check (`check_read_methods`, the row below) compares each read's opcode against the record's read-method bits (`fssm_header.read_methods`) — since the bits restate the read method, it rejects 0 of 12,101 PS: a consistency check between the two encodings of the read, not a mode check (a centroid/sample/noperspective input would still read `v_interp_p1/p2` and pass; that every interpolated generic input is perspective-centre is the PSV0 census result above, so keying a refusal on genuinely unmodelled modes means decoding PSV0, not reading these bits). Counted with `tools/ps_interp_modes.py` (stdlib; PSV0, FSSM and disassembly in one pass; #1301 removed the earlier #1246 census tool in favour of it) on the 1.0.2.1 corpus; tests `tests/test_ps_interp_modes.py`, `tests/test_fssm_header.py` and `tests/test_rdna2spirv_pixelinput.py` (synthetic). No GPU test: no shader needs centroid or sample interpolation. **Not covered:** bit 3 (0x08) is set in 11,619 records (all 11,199 16-bit ones, 396 flat, 24 linear). The 213 PS that overwrite v0/v1 before a `v_interp` (SHADER-178) compute their own barycentrics in code; PSV0 gives them no other mode. |
329| `v_interp_mov_f32` p10 / p20 | The VINTRP mov returns one of the three values the hardware keeps per attribute for the p1/p2 pair, {P10, P20, P0}[S] (RDNA2 ISA, VINTRP; P = P0 + i·P10 + j·P20). p0 stays the provoking vertex (`Flat`, exact bits). p10 and p20 read the location `PerVertexKHR` (the per-vertex path the `*_f16` interps use, so the PS needs `fragmentShaderBarycentric`) and return P1 − P0 and P2 − P0 as one f32 `OpFSub` of the producer's words, vertices ordered as in the f16 row (BaryCoordKHR .y/.z weight vertices 1/2). Refused (`Unsupported`) under `--bary-fallback` and `--f16-interp-fallback` (no per-vertex inputs) and on a 16-bit-flagged interpolant (FSSM table), where whether the hardware forms the delta in f16 is unmeasured. Until 2026-11-22 both selects were refused; all 6,926 `v_interp_mov_f32` in the corpus use p0, so the corpus translation is unchanged. Confirmed on the CPU by `tests/semantic/test_interp_mov_delta.py` (distinct per-vertex words give the deltas, and P0 + i·P10 + j·P20 from the three movs matches the p1/p2 pair bit for bit). **Unverified:** a GPU run, and AMD's rounding of P10/P20 for denormal or NaN words. | 353| `v_interp_mov_f32` p10 / p20 | The VINTRP mov returns one of the three values the hardware keeps per attribute for the p1/p2 pair, {P10, P20, P0}[S] (RDNA2 ISA, VINTRP; P = P0 + i·P10 + j·P20). p0 stays the provoking vertex (`Flat`, exact bits). p10 and p20 read the location `PerVertexKHR` (the per-vertex path the `*_f16` interps use, so the PS needs `fragmentShaderBarycentric`) and return P1 − P0 and P2 − P0 as one f32 `OpFSub` of the producer's words, vertices ordered as in the f16 row (BaryCoordKHR .y/.z weight vertices 1/2). Refused (`Unsupported`) under `--bary-fallback` and `--f16-interp-fallback` (no per-vertex inputs) and on a 16-bit-flagged interpolant (FSSM table), where whether the hardware forms the delta in f16 is unmeasured. Until 2026-11-22 both selects were refused; all 6,926 `v_interp_mov_f32` in the corpus use p0, so the corpus translation is unchanged. Confirmed on the CPU by `tests/semantic/test_interp_mov_delta.py` (distinct per-vertex words give the deltas, and P0 + i·P10 + j·P20 from the three movs matches the p1/p2 pair bit for bit). **Unverified:** a GPU run, and AMD's rounding of P10/P20 for denormal or NaN words. |
330| PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | 354| PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. |
331| Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | 355| Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and the SPIR-V interpreter check both reads at two points of one triangle, and both fallback modes raise Unsupported (`test_p0_and_interpolated_read_of_one_f32_location` in `tests/semantic/test_interp_mov_flat.py`). [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
332| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | 356| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). |
333| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. | 357| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). |
334| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. There is no f64 fused multiply-add in the translator yet (`v_add_f64` only). | 358| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does (RTX 4090, driver 621.24, Windows 11: `runtime/test/shaders/cs_div_fmas_f64.asm`, `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) gives the split 0 instead of 2^-60, while the f32 `cs_fma_fused` fuses 8/8). `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). |
335| `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | 359| `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). |
336| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | 360| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. |
337| MoltenVK fast-math (SHADER-234, NaN compares) | MoltenVK compiles every shader's MSL with Metal's fast-math on by default (`MVK_CONFIG_FAST_MATH_ENABLED`, default 1), and with it Metal folds an f32 compare of a NaN with itself as if the NaN were an ordinary number: `v_cmpx_eq_f32` and `v_cmpx_le_f32` on (NaN, NaN) give true where the ISA, AMD and NVIDIA give false (`ps_vcmpx_forms`, #1374: word 1 `0xf05e8e16`, want `0xf05e8a12`, bits 2 and 10; found by @zneel and @DomasUrbonas). The translation is not involved: the compare is `OpFOrdEqual` / `OpFOrdLessThanEqual`, and the MSL MoltenVK generates (`MVK_CONFIG_SHADER_DUMP_DIR`) is byte-identical with fast-math on and off, so it is Metal's compile option. `MVK_CONFIG_FAST_MATH_ENABLED=2` (on demand) does not help, because translated modules don't declare an execution mode that asks for IEEE behaviour; 0 does. The test tools (`runtime/test/vulkan_loader.h`, which every Vulkan test program uses to load MoltenVK) set `MVK_CONFIG_FAST_MATH_ENABLED=0` before MoltenVK reads its configuration, unless the variable is already set, so a user's own value still wins; the variable also reaches MoltenVK through the Vulkan loader. A runtime that loads MoltenVK on a Mac must do the same. Fast-math off does **not** remove the `[[clang::optnone]]` `spvFAdd`/`spvFSub`/`spvFMul` helpers SPIRV-Cross emits for `NoContraction` (11 calls in `ps_ops`'s MSL either way: their cost is the other part of SHADER-234), and it does not fix the row above (SHADER-182): `valu_fuzz.py --family f16 --seed 1` gives the same `v_mul_f16` +0 mismatch with fast-math on and off. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_vcmpx_forms` fails on all 4,096 pixels with fast-math on and matches all 4,096 with it off, natively and with wave64 emulation; no other `run_gpu_tests.py` result and none of the 25 `ctest` tests changes. | 361| MoltenVK fast-math (SHADER-234, NaN compares) | MoltenVK compiles every shader's MSL with Metal's fast-math on by default (`MVK_CONFIG_FAST_MATH_ENABLED`, default 1), and with it Metal folds an f32 compare of a NaN with itself as if the NaN were an ordinary number: `v_cmpx_eq_f32` and `v_cmpx_le_f32` on (NaN, NaN) give true where the ISA, AMD and NVIDIA give false (`ps_vcmpx_forms`, #1374: word 1 `0xf05e8e16`, want `0xf05e8a12`, bits 2 and 10; found by @zneel and @DomasUrbonas). The translation is not involved: the compare is `OpFOrdEqual` / `OpFOrdLessThanEqual`, and the MSL MoltenVK generates (`MVK_CONFIG_SHADER_DUMP_DIR`) is byte-identical with fast-math on and off, so it is Metal's compile option. `MVK_CONFIG_FAST_MATH_ENABLED=2` (on demand) does not help, because translated modules don't declare an execution mode that asks for IEEE behaviour; 0 does. The test tools (`runtime/test/vulkan_loader.h`, which every Vulkan test program uses to load MoltenVK) set `MVK_CONFIG_FAST_MATH_ENABLED=0` before MoltenVK reads its configuration, unless the variable is already set, so a user's own value still wins; the variable also reaches MoltenVK through the Vulkan loader. A runtime that loads MoltenVK on a Mac must do the same. Fast-math off does **not** remove the `[[clang::optnone]]` `spvFAdd`/`spvFSub`/`spvFMul` helpers SPIRV-Cross emits for `NoContraction` (11 calls in `ps_ops`'s MSL either way: their cost is the other part of SHADER-234), and it does not fix the row above (SHADER-182): `valu_fuzz.py --family f16 --seed 1` gives the same `v_mul_f16` +0 mismatch with fast-math on and off. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_vcmpx_forms` fails on all 4,096 pixels with fast-math on and matches all 4,096 with it off, natively and with wave64 emulation; no other `run_gpu_tests.py` result and none of the 25 `ctest` tests changes. |
362| `v_cmp(x)_lg_f32/f16` on MoltenVK (ordered not-equal) | LG is less-or-greater, false when either source is a NaN. The translator emits it as the `OpLogicalOr` of `OpFOrdLessThan` and `OpFOrdGreaterThan`, not as `OpFOrdNotEqual`. MoltenVK's SPIRV-Cross writes `OpFOrdNotEqual` as a plain `!=`, the same text it gives `OpFUnordNotEqual`, and Metal's `!=` is true on a NaN. That happens with fast-math off too, so it is not the row above: `ps_vcmp_f32_nan`'s SPIR-V has 8 `OpFOrdNotEqual` and 8 `OpFUnordNotEqual`, and the MSL MoltenVK dumps (`MVK_CONFIG_SHADER_DUMP_DIR`) has 16 identical `as_type<float>(a) != as_type<float>(b)`. Confirmed on an Apple M4 (MoltenVK 1.4.2, fast-math off, MoltenVK logs "MathMode Safe"). `ps_vcmp_f32_nan`, `ps_vcmp_f16`, `ps_vcmp_f16_e64`, `ps_vcmpx_f16` and `ps_vcmpx_f16_e64` failed only in the LG bits of their NaN pairs (f16 word 1 `0x4ce9bda2`, want `0x4ce9b1a2`; f32 `0x377c`, want `0x376c`). With this form all five pass, and no other `run_gpu_tests.py` result changes. f64 LG compares integer words and is not affected. `v_cmp(x)_lg_f32/f16` is in 13,795 of the 25,734 listings. The form is pinned on the CPU by `tests/semantic/test_vcmp_f32_predicates.py` (`test_lg_is_ordered_without_ord_not_equal`). |
338| Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). | 363| Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). |
339| f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for \|x\| > 1 is bit-exact, and for \|x\| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). `v_exp_f16`/`v_log_f16` give the same counts on gfx1036 (RDNA2, AMD Windows driver; SHADER-135). **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. | 364| f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for \|x\| > 1 is bit-exact, and for \|x\| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). `v_exp_f16`/`v_log_f16` give the same counts on gfx1036 (RDNA2, AMD Windows driver; SHADER-135). Since 2026-11-22 the translator selects those hardware words for `v_rcp_f16`, `v_rsq_f16` and `v_sqrt_f16` itself (the operand is replaced by 1.0 for the f32 `OpFDiv`/`InverseSqrt`/`Sqrt`, which SPIR-V leaves undefined at 0 or below 0) and `0xfe00` is the negative quiet NaN; checked bit for bit through the interpreter by `tests/semantic/test_valu_rcp_f16.py`, `test_valu_rsq_f16.py` and `test_valu_sqrt_f16.py` against exactly rounded references. The undefined cases of `v_exp_f16`/`v_log_f16`/`v_sin_f16`/`v_cos_f16` are still left to the driver. **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. |
340| f64 literal sources | For `v_cvt_f32_f64` and either source of `v_add_f64`, a literal dword supplies bits 63:32 and bits 31:0 are zero. Inline integers are sign-extended and inline floats use their binary64 value. For example, gfx1030 `llvm-mc` encodes 1.5 as the literal word `0x3ff80000`. The synthetic `tests/semantic/fixtures/f64_literals.asm` checks both source words in the translated SPIR-V, including the distinction between the printed literal `0x1` and inline `1`. [LLVM AMDGPU operand conversions](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#integer-literals) | 365| f64 literal sources | For `v_cvt_f32_f64` and either source of `v_add_f64`, a literal dword supplies bits 63:32 and bits 31:0 are zero. For `v_cvt_f32_f64`, `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64`, `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` and either source of `v_add_f64`, a literal dword supplies bits 63:32 and bits 31:0 are zero. Inline integers are sign-extended and inline floats use their binary64 value. For example, gfx1030 `llvm-mc` encodes 1.5 as the literal word `0x3ff80000`. The synthetic `tests/semantic/fixtures/f64_literals.asm` checks both source words in the translated SPIR-V, including the distinction between the printed literal `0x1` and inline `1`. [LLVM AMDGPU operand conversions](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#integer-literals) In the synthetic `unary_f64_literals.asm`, LLVM gfx1030 encodes the five unary literal sources in trailing dwords. The regression checks the emitted high and low operand words for reciprocal, reciprocal square root and square root. It executes the integer-only frexp paths: for 6.0 the mantissa words are (0, 0x3fe80000) and the exponent is 3. The full fixture passes Vulkan 1.2 validation; the semantic interpreter cannot execute its Float64 instructions. |
341| `v_cvt_f32_f64` output modifiers | Convert to f32, apply `mul:2`, `mul:4`, or `div:2` if present, then apply `clamp` to [0, 1] if requested. [LLVM GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/main/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s#L3044-L3054) confirm the modifier encodings. `tests/test_f64_conversion.py` checks the resulting SPIR-V data flow. | 366| `v_cvt_f32_f64` output modifiers | Convert to f32, apply `mul:2`, `mul:4`, or `div:2` if present, then apply `clamp` to [0, 1] if requested. [LLVM GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/main/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s#L3044-L3054) confirm the modifier encodings. `tests/test_f64_conversion.py` checks the resulting SPIR-V data flow. |
367| 32-bit integers to binary64 | `v_cvt_f64_i32` sign-extends the input value and `v_cvt_f64_u32` treats it as unsigned. Every 32-bit integer is exactly representable in binary64. The low word goes in the first destination VGPR. **The output scaling is gated by `MODE`, measured by @fiestorra**: on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 6 inputs x 5 modifier forms x 5 MODEs, wave32 and wave64 identical) `mul:2`/`mul:4`/`div:2` scale the binary64 result only under `IEEE=0` with `denorm_mode_16_64=0`; under `denorm_mode_16_64=3`, which is what the translator assumes, and under `IEEE=1` they are ignored, while `clamp` applies in every MODE — so only `clamp` reaches `dst_f64` for these two ops, as `v_ldexp_f64` already does. For input `0x80000001`, SPIRV-Tools constant folding reproduced both words of each result in the synthetic `ps_int32_to_f64.s` fixture. [AMD RDNA 2 ISA, VOP1 conversions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
342| `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile<VOP_F64_F64_F64>>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). | 368| `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile<VOP_F64_F64_F64>>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). |
343| `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64` | Double-precision reciprocal (`OpFDiv %double 1.0 x`), inverse square root (`GLSL.std.450 InverseSqrt`), and square root (`GLSL.std.450 Sqrt`), requiring `Float64` (`shaderFloat64`). VOP3 input modifiers (`abs`, `neg`) apply to the double operand, and output modifiers (`mul:2`, `mul:4`, `div:2`, then `clamp` to [0, 1]) apply via `clamp_mods_f64` (LLVM `VOP1Inst` / `VOP_F64_F64` in `VOP1Instructions.td`, `HasClamp` and `HasOMod` via `VOPProfile`). Special-value edge cases (`±0`, negative inputs, NaN) follow the driver's SPIR-V `OpFDiv`/`InverseSqrt`/`Sqrt` rules, as for the f32 forms. Checked by `tests/test_f64_transcendentals.py` (SPIR-V data flow and `spirv-val`). | 369| `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64` | Double-precision reciprocal (`OpFDiv %double 1.0 x`), inverse square root (`GLSL.std.450 InverseSqrt`), and square root (`GLSL.std.450 Sqrt`), requiring `Float64` (`shaderFloat64`). VOP3 input modifiers (`abs`, `neg`) apply to the double operand, and output modifiers (`mul:2`, `mul:4`, `div:2`, then `clamp` to [0, 1]) apply via `clamp_mods_f64` (LLVM `VOP1Inst` / `VOP_F64_F64` in `VOP1Instructions.td`, `HasClamp` and `HasOMod` via `VOPProfile`). Special-value edge cases (`±0`, negative inputs, NaN) follow the driver's SPIR-V `OpFDiv`/`InverseSqrt`/`Sqrt` rules, as for the f32 forms. Checked by `tests/test_f64_transcendentals.py` (SPIR-V data flow and `spirv-val`). **Measured on RDNA2** (gfx1036 iGPU, Windows driver 31.0.24002.92, `tools/hw_oracle` raw kernels, MODE with IEEE on and f64 denormals kept): `v_sqrt_f64` is not the correctly rounded root. `sqrt(4.0)` stored `0x4000000004000000` (2.0000000298), `sqrt(9.0)` `0x4008000004000000`, `sqrt(0.25)` `0x3fe0000004000000` and `sqrt(2.0)` `0x3ff6a09e64000000`. Against the correctly rounded roots, the first three are exactly +2^26 ulps off, and `sqrt(2.0)` is −41,892,813 ulps (about −2^25.3) from `0x3ff6a09e667f3bcd` (1.4142135624), so only about 26 of the 53 significand bits are right. `GLSL.std.450 Sqrt` is the more accurate lowering, and a difference from the instruction on RDNA2 hardware is not a translator bug. `v_rcp_f64` and `v_rsq_f64` returned exact values, but only powers of two were tried, so their accuracy is unmeasured. None of the three occurs in the 26,503 game listings ([measurement](https://github.com/ItsNotRexed/Leonida/issues/4084#issuecomment-7088412190), @fiestorra). |
344| `v_trunc_f64`, `v_ceil_f64`, `v_rndne_f64`, `v_floor_f64` | Round binary64 toward zero, positive infinity, nearest-even, or negative infinity respectively; the result stays binary64. The translator maps these to GLSL.std.450 `Trunc`, `Ceil`, `RoundEven`, and `Floor` with `shaderFloat64` (no intermediate f32). Register pairs are low word first, literal dwords fill bits 63:32 with a zero low word, and inactive lanes keep both destination words. VOP3 applies source modifiers before rounding and the existing f64 scale/clamp path afterwards. Sources: AMD [RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §6.2.1 and §12.8 (VOP1 opcodes 23–26), and LLVM's [GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/1a7ece827ab3543387ee1adf1eb4c8878905b577/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s). Value and SPIR-V checks: `tests/semantic/test_f64_round.py`. Hardware-confirmed natively on RDNA2 (`gfx1036` iGPU, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case) by @timelery: exact IEEE-754 rounding that keeps signed zeros and binary64 subnormals (`ceil(+sub)` = +1.0, `ceil(-sub)` = -0.0, `floor(+sub)` = +0.0, `floor(-sub)` = -1.0, `trunc(±sub)` = ±0.0, `rndne(±0.5)` = ±0.0, `rndne(±1.5)` = ±2.0, `rndne(±2.5)` = ±2.0, ±inf stays ±inf, and ±qNaN/±sNaN pass through unchanged under IEEE=0), where `sub` is the smallest binary64 subnormal; the hex literal dword populates bits 63:32 with a zero low word (`v_floor_f64 v[4:5], 0x3ff80000` -> `0x3ff0000000000000`); and the VOP3 output modifiers behave as for `v_add_f64`/`v_sqrt_f64`: applied on hardware under `denorm16_64=0` and ignored under `denorm16_64=3` (IEEE=0), while the translator applies them through `clamp_mods_f64` as those rows do. | 370| `v_trunc_f64`, `v_ceil_f64`, `v_rndne_f64`, `v_floor_f64` | Round binary64 toward zero, positive infinity, nearest-even, or negative infinity respectively; the result stays binary64. The translator maps these to GLSL.std.450 `Trunc`, `Ceil`, `RoundEven`, and `Floor` with `shaderFloat64` (no intermediate f32). Register pairs are low word first, literal dwords fill bits 63:32 with a zero low word, and inactive lanes keep both destination words. VOP3 applies source modifiers before rounding and the existing f64 scale/clamp path afterwards. Sources: AMD [RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §6.2.1 and §12.8 (VOP1 opcodes 23–26), and LLVM's [GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/1a7ece827ab3543387ee1adf1eb4c8878905b577/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s). Value and SPIR-V checks: `tests/semantic/test_f64_round.py`. Hardware-confirmed natively on RDNA2 (`gfx1036` iGPU, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case) by @timelery: exact IEEE-754 rounding that keeps signed zeros and binary64 subnormals (`ceil(+sub)` = +1.0, `ceil(-sub)` = -0.0, `floor(+sub)` = +0.0, `floor(-sub)` = -1.0, `trunc(±sub)` = ±0.0, `rndne(±0.5)` = ±0.0, `rndne(±1.5)` = ±2.0, `rndne(±2.5)` = ±2.0, ±inf stays ±inf, and ±qNaN/±sNaN pass through unchanged under IEEE=0), where `sub` is the smallest binary64 subnormal; the hex literal dword populates bits 63:32 with a zero low word (`v_floor_f64 v[4:5], 0x3ff80000` -> `0x3ff0000000000000`); and the VOP3 output modifiers behave as for `v_add_f64`/`v_sqrt_f64`: applied on hardware under `denorm16_64=0` and ignored under `denorm16_64=3` (IEEE=0), while the translator applies them through `clamp_mods_f64` as those rows do. |
345| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). VOP3 `abs` and `neg` on `src0` are applied as raw sign-bit moves on the 32-bit integer bits (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`) rather than `FAbs`/`OpFNegate`, so signalling NaNs stay signalling (class bit 0) and subnormals are never flushed. **Hardware-measured natively on RDNA2 (`gfx1036`)** via `tools/hw_oracle` (Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM): 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, ` `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). \| v \| `, `- \| v \| `) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, `\|v\|`, `-\|v\|`) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). Corpus count (26,503 shaders): `v_cmp_class_f32` appears 37,026 times in 7,101 shaders (0 with VOP3 `abs`/`neg` on `src0`). Checked on CPU + `spirv-val` by `tests/semantic/test_cmp_class_f32_mods.py` and `tests/semantic/test_valu_f32_class_rndne.py`; `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive (GPU-checked on RTX 4070 SUPER driver 616.92 and AMD RX 9070 XT RADV Mesa 26.2.6, plus direct Vulkan compute verification of modified sNaNs on RX 9070 XT and Radeon 610M `gfx1036`). | 371| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). VOP3 `abs` and `neg` on `src0` are applied as raw sign-bit moves on the 32-bit integer bits (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`) rather than `FAbs`/`OpFNegate`, so signalling NaNs stay signalling (class bit 0) and subnormals are never flushed. **Hardware-measured natively on RDNA2 (`gfx1036`)** via `tools/hw_oracle` (Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM): 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, ` `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). \| v \| `, `- \| v \| `) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, `\|v\|`, `-\|v\|`) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). Corpus count (26,503 shaders): `v_cmp_class_f32` appears 37,026 times in 7,101 shaders (0 with VOP3 `abs`/`neg` on `src0`). Checked on CPU + `spirv-val` by `tests/semantic/test_cmp_class_f32_mods.py` and `tests/semantic/test_valu_f32_class_rndne.py`; `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive (GPU-checked on RTX 4070 SUPER driver 616.92 and AMD RX 9070 XT RADV Mesa 26.2.6, plus direct Vulkan compute verification of modified sNaNs on RX 9070 XT and Radeon 610M `gfx1036`). |
346| Float controls (NaN, ±inf, −0) (SHADER-99) | RDNA2 float ops return NaN, ±inf and −0 as computed, and Vulkan lets the driver assume none of them occur unless the module says otherwise. Every module therefore declares `OpExecutionMode %main SignedZeroInfNanPreserve 32` (capability `SignedZeroInfNanPreserve`, core since SPIR-V 1.4). Its index entry lists `"float_controls": ["shaderSignedZeroInfNanPreserveFloat32"]`, the device property it needs; `vk_pipeline_check` skips the shader where that property is false, and `--no-float-controls` leaves the mode out. Measured on AMD Radeon RX 9070 XT (driver 26.11.2). Without the mode, `runtime/test/shaders/cs_signed_zero_nan.asm` gets 0 in out[4..7]: the `x != x` NaN checks fold to false and a NaN `v_cvt_f16_f32` is lost. The f16 fuzzer (`tools/valu_fuzz.py --family f16`) also saw `v_pk_mul_f16` −0 products come back +0, and, with integer f16 narrowing (#575), NaN results that were never stored. With the mode, the test and those programs match. Other drivers, from testers in #664: RADV (RX 7800 XT) folds the f16 NaN check (out[6]) without the mode; NVIDIA and Intel Arc keep all three either way. Apple GPUs (MoltenVK) report the property, and the mode fixes their NaN checks, but −0 products (out[0], out[2], out[3]) still come back +0 with or without it (#1203, SHADER-182). `check.py` and `scripts/run_gpu_tests.py` don't judge those three words on an Apple device. Mesa's llvmpipe, where the CI runs these tests, returns 0 for the `0 × inf` NaN check (out[5]) with or without the mode, while its other NaN checks give 1 (#664), so out[5] isn't judged there (`UNJUDGED_WORDS` in `check.py`). f64 (`SignedZeroInfNanPreserve 64`) isn't declared yet. | 372| Float controls (NaN, ±inf, −0) (SHADER-99) | RDNA2 float ops return NaN, ±inf and −0 as computed, and Vulkan lets the driver assume none of them occur unless the module says otherwise. Every module therefore declares `OpExecutionMode %main SignedZeroInfNanPreserve 32` (capability `SignedZeroInfNanPreserve`, core since SPIR-V 1.4). Its index entry lists `"float_controls": ["shaderSignedZeroInfNanPreserveFloat32"]`, the device property it needs; `vk_pipeline_check` skips the shader where that property is false, and `--no-float-controls` leaves the mode out. Measured on AMD Radeon RX 9070 XT (driver 26.11.2). Without the mode, `runtime/test/shaders/cs_signed_zero_nan.asm` gets 0 in out[4..7]: the `x != x` NaN checks fold to false and a NaN `v_cvt_f16_f32` is lost. The f16 fuzzer (`tools/valu_fuzz.py --family f16`) also saw `v_pk_mul_f16` −0 products come back +0, and, with integer f16 narrowing (#575), NaN results that were never stored. With the mode, the test and those programs match. Other drivers, from testers in #664: RADV (RX 7800 XT) folds the f16 NaN check (out[6]) without the mode; NVIDIA and Intel Arc keep all three either way. Apple GPUs (MoltenVK) report the property, and the mode fixes their NaN checks, but −0 products (out[0], out[2], out[3]) still come back +0 with or without it (#1203, SHADER-182). `check.py` and `scripts/run_gpu_tests.py` don't judge those three words on an Apple device. Mesa's llvmpipe, where the CI runs these tests, returns 0 for the `0 × inf` NaN check (out[5]) with or without the mode, while its other NaN checks give 1 (#664), so out[5] isn't judged there (`UNJUDGED_WORDS` in `check.py`). f64 has its own row below (SHADER-597); its `SignedZeroInfNanPreserve 64` isn't declared yet. |
347| Float controls (f16 denormals) (SHADER-526) | RDNA2 keeps f16 denormals, so every module also declares `OpExecutionMode %main DenormPreserve 16` (capability `DenormPreserve`, core since SPIR-V 1.4 like `SignedZeroInfNanPreserve`, so no extension at `--target-env vulkan1.2`). The translator models f16 arithmetic in f32 with integer narrowing (`Gen.f16_bits`), so an f16 denormal is an ordinary f32 value in the module and no f32 denormal is involved: the 16-bit mode is what governs the f16→f32 conversion the driver emits for an f16 source. NVIDIA flushed that conversion without it: in `runtime/test/shaders/ps_sdwa_f16_const.asm` the y lane (`src0_sel:BYTE_1` of `2.0` is the denormal 0x0040 = 2^−18, × 1024.0 = 2^−8 = 0x1c00) read 0x0000, 4096/4096 pixels wrong, while x, z and w matched; with the mode the test is 4096/4096 exact (RTX 4070 SUPER, driver 610.88, Windows 11, validation layers on). The same lane read 0x0000 on an RTX 3090 (driver 610.88, found by @Rainmaker33). Assembling the same module with only the two `DenormPreserve` lines removed reads 0x0000 again, so it is the mode the driver honours, not a change in the translated code. Not every NVIDIA build flushes it: on `main` without the mode an RTX 4060 Ti (621.24), an RTX 5070 Ti (620.73.04, Linux) and an RTX 5080 (616.92) pass the test. The index entry lists `"shaderDenormPreserveFloat16"` after `"shaderSignedZeroInfNanPreserveFloat32"`; `vk_pipeline_check` skips the shader where the device reports that property false, and `--no-float-controls` leaves both modes out. Where the property is false the module has no f16 denormal guarantee, so an f16 denormal read can come back +0 exactly as in that lane above (NVIDIA's default without the mode); that is a value difference in the shader, and the GPU test's y lane is then expected to fail. The AMD Radeon iGPU (RDNA2, driver 24.10.24, Vulkan 1.3.280) reports `shaderDenormPreserveFloat16` true with `denormBehaviorIndependence` `32_BIT_ONLY`, and `vk_pipeline_check` builds the module and its pipeline there (`ps_sdwa_f16_const`: 1 module ok, 1 pipeline ok, wave32 and wave64); the GPU test itself skips on that device, which has 128 push-constant bytes where the test needs 144. `tests/semantic/test_f16_denorm_preserve.py` pins the mode, the index property and the four words. | 373| Float controls (f16 denormals) (SHADER-526) | RDNA2 keeps f16 denormals, so every module also declares `OpExecutionMode %main DenormPreserve 16` (capability `DenormPreserve`, core since SPIR-V 1.4 like `SignedZeroInfNanPreserve`, so no extension at `--target-env vulkan1.2`). The translator models f16 arithmetic in f32 with integer narrowing (`Gen.f16_bits`), so an f16 denormal is an ordinary f32 value in the module and no f32 denormal is involved: the 16-bit mode is what governs the f16→f32 conversion the driver emits for an f16 source. NVIDIA flushed that conversion without it: in `runtime/test/shaders/ps_sdwa_f16_const.asm` the y lane (`src0_sel:BYTE_1` of `2.0` is the denormal 0x0040 = 2^−18, × 1024.0 = 2^−8 = 0x1c00) read 0x0000, 4096/4096 pixels wrong, while x, z and w matched; with the mode the test is 4096/4096 exact (RTX 4070 SUPER, driver 610.88, Windows 11, validation layers on). The same lane read 0x0000 on an RTX 3090 (driver 610.88, found by @Rainmaker33). Assembling the same module with only the two `DenormPreserve` lines removed reads 0x0000 again, so it is the mode the driver honours, not a change in the translated code. Not every NVIDIA build flushes it: on `main` without the mode an RTX 4060 Ti (621.24), an RTX 5070 Ti (620.73.04, Linux) and an RTX 5080 (616.92) pass the test. The index entry lists `"shaderDenormPreserveFloat16"` after `"shaderSignedZeroInfNanPreserveFloat32"`; `vk_pipeline_check` skips the shader where the device reports that property false, and `--no-float-controls` leaves both modes out. Where the property is false the module has no f16 denormal guarantee, so an f16 denormal read can come back +0 exactly as in that lane above (NVIDIA's default without the mode); that is a value difference in the shader, and the GPU test's y lane is then expected to fail. The AMD Radeon iGPU (RDNA2, driver 24.10.24, Vulkan 1.3.280) reports `shaderDenormPreserveFloat16` true with `denormBehaviorIndependence` `32_BIT_ONLY`, and `vk_pipeline_check` builds the module and its pipeline there (`ps_sdwa_f16_const`: 1 module ok, 1 pipeline ok, wave32 and wave64); the GPU test itself skips on that device, which has 128 push-constant bytes where the test needs 144. `tests/semantic/test_f16_denorm_preserve.py` pins the mode, the index property and the four words. |
348| `v_mul_legacy_f32` default-mode f32 denormal flushing | Under the inferred game `MODE` (`IEEE=0`, `denorm_mode_32=0`), the DX9 legacy multiplication reads f32 denormal operands as signed zeros, then its zero-operand override produces **+0** even when an operand was negative or the other is infinity/NaN. A nonzero subnormal product flushes to a zero retaining its sign, *before* VOP3 `mul:2`/`mul:4`/`div:2`; with IEEE off an output multiplier converts a resulting -0 to +0 on native RDNA2. The translated result is flushed after the modifier. This uses software f32 bit tests (`Gen.flush_f32`) rather than driver-specific denormal controls. Native gfx1031 (39,101 programs) and gfx1036 (38,858 programs) measured the MODE and DX9 mul rule (see the output-modifier rows below); the previous translator allowed f32 denormal operands and products through raw `OpFMul`. Synthetic regression: `tests/semantic/test_valu_mul_legacy_denorm.py`, `ps_mul_legacy_denorm.asm` and `ps_mul_legacy_denorm_mods.asm` (CPU, spirv-val and Vulkan GPU). This models the inferred game mode, not all possible dynamically changed MODE configurations. | 374| `v_mul_legacy_f32` default-mode f32 denormal flushing | Under the inferred game `MODE` (`IEEE=0`, `denorm_mode_32=0`), the DX9 legacy multiplication reads f32 denormal operands as signed zeros, then its zero-operand override produces **+0** even when an operand was negative or the other is infinity/NaN. A nonzero subnormal product flushes to a zero retaining its sign, *before* VOP3 `mul:2`/`mul:4`/`div:2`; with IEEE off an output multiplier converts a resulting -0 to +0 on native RDNA2. The translated result is flushed after the modifier. This uses software f32 bit tests (`Gen.flush_f32`) rather than driver-specific denormal controls. Native gfx1031 (39,101 programs) and gfx1036 (38,858 programs) measured the MODE and DX9 mul rule (see the output-modifier rows below); the previous translator allowed f32 denormal operands and products through raw `OpFMul`. Synthetic regression: `tests/semantic/test_valu_mul_legacy_denorm.py`, `ps_mul_legacy_denorm.asm` and `ps_mul_legacy_denorm_mods.asm` (CPU, spirv-val and Vulkan GPU). This models the inferred game mode, not all possible dynamically changed MODE configurations. |
375| Float controls for f64 (SHADER-597) | A module that declares `Float64` (the translator's native f64 ops) also declares `OpExecutionMode %main SignedZeroInfNanPreserve 64`, since Vulkan does not guarantee −0, NaN or ±inf for 64-bit float ops without it (e.g. `v_add_f64` of −0 and −0 = −0). Same capability as the 32-bit mode, no extension; modules without `Float64` don't get it. The index entry then lists `"float_controls": ["shaderSignedZeroInfNanPreserveFloat32", "shaderSignedZeroInfNanPreserveFloat64", "shaderDenormPreserveFloat16"]`, `vk_pipeline_check` skips the shader where any of them is false, and `--no-float-controls` leaves all three modes out. Found by @Jolymmiles (issue #3047). `tests/test_f64_float_controls.py` checks the module and the index entry; **not yet GPU-verified** (`ps_f64_mods.asm` and the f64 fixtures need a run on a device with `shaderFloat64`). |
349| Multiply-add with a literal | `v_fmamk_f32`/`v_madmk_f32` are D = S0 × K + S1 and `v_fmaak_f32`/`v_madak_f32` are D = S0 × S1 + K, K being the 32-bit literal. LLVM prints them `vdst, src0, K, vsrc1` and `vdst, src0, vsrc1, K`, so in print order all four are a[1] × a[2] + a[3] (fused for fmamk/fmaak). **Until 2026-11-21 fmamk and madmk computed S0 × S1 + K.** Source: RDNA2 ISA (V_FMAMK_F32, V_MADMK_F32) and the operand fields of the llvm-mc encoding. Checked by `tests/semantic` and GPU-checked with `runtime/test/shaders/ps_fma_literal.asm` on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact, and 4096/4096 differ with the old translator. | 376| Multiply-add with a literal | `v_fmamk_f32`/`v_madmk_f32` are D = S0 × K + S1 and `v_fmaak_f32`/`v_madak_f32` are D = S0 × S1 + K, K being the 32-bit literal. LLVM prints them `vdst, src0, K, vsrc1` and `vdst, src0, vsrc1, K`, so in print order all four are a[1] × a[2] + a[3] (fused for fmamk/fmaak). **Until 2026-11-21 fmamk and madmk computed S0 × S1 + K.** Source: RDNA2 ISA (V_FMAMK_F32, V_MADMK_F32) and the operand fields of the llvm-mc encoding. Checked by `tests/semantic` and GPU-checked with `runtime/test/shaders/ps_fma_literal.asm` on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact, and 4096/4096 differ with the old translator. |
350| Multiply-add and output modifiers | `v_mac_f32` is the VOP2 form of `v_mad_f32`, **not** of `v_fma_f32`: the product is rounded before the add (`OpFMul` + `OpFAdd`, both `NoContraction`). It used to emit `Fma`, one ULP off on some inputs. Source: LLVM `SIInstrInfo.cpp` `getNewFMAInst` (`V_MAC_F32` -> `V_MAD_F32_e64`, `V_FMAC_F32` -> `V_FMA_F32_e64`). VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` now apply to `v_cvt_f32_i32`/`u32`/`ubyte0..3`, `v_cvt_f32_f16` and `v_rcp_iflag_f32` (they were dropped). Source: LLVM `VOPProfileI2F` (`Ins64 = $src0, $clamp, $omod`) and the float-source profiles. Found by `tools/f32_fuzz.py` (FUZZ-3: an exact-arithmetic model against the translated SPIR-V; 0 mismatches over 10,000 seeded programs after the fix) and pinned by `runtime/test/shaders/ps_f32_mods.asm` (`tests/semantic/test_f32_valu.py`); **GPU-checked** (TEST-298): `ps_f32_mods` gives the expected four words (`0xc0256a01 0x3f800000 0x41e00000 0x3fc00000`, so the `v_mac_f32` product is not fused and the `clamp`, `mul:4` and `div:2` on `v_cvt_f32_ubyte1`/`u32`/`f16` and `v_rcp_iflag_f32` apply) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 615.78.08); `mul:2` on the conversions is not in that fixture. **not yet GPU-verified**. Still open: on some inputs the ISA defines a result but the emitted SPIR-V is undefined: `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative. `v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp` (see "Float-to-byte pack"). `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative (`v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp`, see "Float-to-byte pack"). | 377| Multiply-add and output modifiers | `v_mac_f32` is the VOP2 form of `v_mad_f32`, **not** of `v_fma_f32`: the product is rounded before the add (`OpFMul` + `OpFAdd`, both `NoContraction`). It used to emit `Fma`, one ULP off on some inputs. Source: LLVM `SIInstrInfo.cpp` `getNewFMAInst` (`V_MAC_F32` -> `V_MAD_F32_e64`, `V_FMAC_F32` -> `V_FMA_F32_e64`). VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` now apply to `v_cvt_f32_i32`/`u32`/`ubyte0..3`, `v_cvt_f32_f16` and `v_rcp_iflag_f32` (they were dropped). Source: LLVM `VOPProfileI2F` (`Ins64 = $src0, $clamp, $omod`) and the float-source profiles. Found by `tools/f32_fuzz.py` (FUZZ-3: an exact-arithmetic model against the translated SPIR-V; 0 mismatches over 10,000 seeded programs after the fix) and pinned by `runtime/test/shaders/ps_f32_mods.asm` (`tests/semantic/test_f32_valu.py`); **GPU-checked** (TEST-298): `ps_f32_mods` gives the expected four words (`0xc0256a01 0x3f800000 0x41e00000 0x3fc00000`, so the `v_mac_f32` product is not fused and the `clamp`, `mul:4` and `div:2` on `v_cvt_f32_ubyte1`/`u32`/`f16` and `v_rcp_iflag_f32` apply) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 615.78.08); `mul:2` on the conversions is not in that fixture. **not yet GPU-verified**. Still open: on some inputs the ISA defines a result but the emitted SPIR-V is undefined: `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative. `v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp` (see "Float-to-byte pack"). `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative (`v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp`, see "Float-to-byte pack"). |
351| Output modifiers on hardware (gfx1150, RDNA2) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). **RDNA2 does the same, rule for rule** (SHADER-353): on an RX 6700 XT (gfx1031, a discrete RDNA2 part, not the console's gfx1013; AMD Windows driver 26.11.2), seeds 1 to 6, 39,101 programs, 0 mismatch and 66 omod -0 → +0 deviations. Per MODE, counting only the programs where the omod changes the result: with IEEE off and f32 denormals flushed (the game's mode) it is applied every time (2,680, and the 66 -0 results become +0); with denormals kept it is ignored by the ALU ops (1,811) and applied by `v_rcp/rcp_iflag/rsq/sqrt/exp/log_f32` and the four cube ops (869, -0 → +0 only there); with IEEE on it is ignored (2,650) and a -0 result stays -0. Earlier, gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D) gave seeds 1 to 6, 38,858 programs, 0 mismatch and 56 such deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | 378| Output modifiers on hardware (gfx1150, RDNA2) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). **RDNA2 does the same, rule for rule** (SHADER-353): on an RX 6700 XT (gfx1031, a discrete RDNA2 part, not the console's gfx1013; AMD Windows driver 26.11.2), seeds 1 to 6, 39,101 programs, 0 mismatch and 66 omod -0 → +0 deviations. Per MODE, counting only the programs where the omod changes the result: with IEEE off and f32 denormals flushed (the game's mode) it is applied every time (2,680, and the 66 -0 results become +0); with denormals kept it is ignored by the ALU ops (1,811) and applied by `v_rcp/rcp_iflag/rsq/sqrt/exp/log_f32` and the four cube ops (869, -0 → +0 only there); with IEEE on it is ignored (2,650) and a -0 result stays -0. Earlier, gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D) gave seeds 1 to 6, 38,858 programs, 0 mismatch and 56 such deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). |
352| Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. Measured natively on gfx1036 (RDNA2) in the MODE inferred for the game (IEEE 0, f32 denormals flushed): `v_floor_f32`, `v_ceil_f32` and `v_fract_f32` read a denormal operand as a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0), fract(±inf) is exactly `0xffc00000`, and a NaN operand comes back unchanged, a signalling one too. The translator flushes the operand and selects those words itself (`Gen.round_f32_flushed`) instead of leaving them to the driver's f32 denormal handling, which Vulkan does not fix; until 2026-11-22 a driver that keeps denormals gave -1.0, +1.0 and 0x3f7fffff there. `v_cvt_flr_i32_f32` likewise returns 0 for a negative denormal (the translator gave -1). Checked against 119 measured words by `tests/semantic/test_alu_floor_ceil_fract_hw.py`. For `v_fract_f16`, either infinity gives the gfx1036 word `0xfe00`, or +0 with the DX10 clamp. The translator selects these results explicitly. The hand-written `ps_fract_f16_infinity.asm` fixture checks both signs, the preserved destination bits and a color channel computed from the result sign in the CPU interpreter (`tests/semantic/test_fract_f16_infinity.py`). A source `neg` on a signalling NaN operand still quiets it in the translator. Not changed: f16 fract(±inf) is `0xfe00` on the hardware and a quiet positive NaN in the translator, and `neg` on a signalling NaN operand quiets it in the translator. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `NMin(NMax(z, NMin(x, y)), NMax(x, y))` (until 2026-11-22 this used `FClamp(z, lo, hi)`, which was GLSL.std.450 undefined whenever `z` was NaN or both `x` and `y` were NaN), and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead; all 1-, 2-, and 3-NaN operand positions for both `v_med3_f32` and `v_med3_f16` were hardware-verified on RDNA2 (`gfx1035`, wave32 & wave64). `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (the `clamp` bit, LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged. Not modelled: signalling NaNs under IEEE mode; NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the payload when all operands are NaN in the f16 or three-source forms (`NMin` and `NMax` only promise a NaN). The binary `v_min_f32` and `v_max_f32` forms explicitly select the first operand when the second is NaN, preserving the first quiet NaN's sign and payload when both are quiet NaNs, as measured on the RX 6800. The CPU test `tests/semantic/test_minmax_f32_payload.py` checks both operand orders using finite color exports. Also, without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the NaN payload when both operands are NaN (`NMin` only promises a NaN); and without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. | 379| Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. Measured natively on gfx1036 (RDNA2) in the MODE inferred for the game (IEEE 0, f32 denormals flushed): `v_floor_f32`, `v_ceil_f32` and `v_fract_f32` read a denormal operand as a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0), fract(±inf) is exactly `0xffc00000`, and a NaN operand comes back unchanged, a signalling one too. The translator flushes the operand and selects those words itself (`Gen.round_f32_flushed`) instead of leaving them to the driver's f32 denormal handling, which Vulkan does not fix; until 2026-11-22 a driver that keeps denormals gave -1.0, +1.0 and 0x3f7fffff there. `v_cvt_flr_i32_f32` likewise returns 0 for a negative denormal (the translator gave -1). Checked against 119 measured words by `tests/semantic/test_alu_floor_ceil_fract_hw.py`. For `v_fract_f16`, either infinity gives the gfx1036 word `0xfe00`, or +0 with the DX10 clamp. The translator selects these results explicitly. The hand-written `ps_fract_f16_infinity.asm` fixture checks both signs, the preserved destination bits and a color channel computed from the result sign in the CPU interpreter (`tests/semantic/test_fract_f16_infinity.py`). A source `neg` on a signalling NaN operand still quiets it in the translator. Not changed: f16 fract(±inf) is `0xfe00` on the hardware and a quiet positive NaN in the translator, and `neg` on a signalling NaN operand quiets it in the translator. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `NMin(NMax(z, NMin(x, y)), NMax(x, y))` (until 2026-11-22 this used `FClamp(z, lo, hi)`, which was GLSL.std.450 undefined whenever `z` was NaN or both `x` and `y` were NaN), and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead; all 1-, 2-, and 3-NaN operand positions for both `v_med3_f32` and `v_med3_f16` were hardware-verified on RDNA2 (`gfx1035`, wave32 & wave64). `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (the `clamp` bit, LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged. Not modelled: signalling NaNs under IEEE mode; NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`). All-NaN float min/max/med3 ops (`v_min/max/min3/max3/med3_f32` via `Gen.nminmax_f32`, `v_min/max/min3/max3/med3_f16` via `Gen.f16_in_bits`/`Gen.all_f16_nan_cond`, and per-half `v_pk_min/max_f16` when `clamp` is unset) explicitly preserve `src0`'s NaN bits (including sign, payload, and signalling bit under `IEEE = 0`, matching the RX 6800 and `gfx1036` hardware rules). The CPU tests `tests/semantic/test_minmax_f32_payload.py` and `tests/semantic/test_alu_min3_max3_med3_16_hw.py` check operand-order payload and signalling NaN preservation. Also, without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the NaN payload when both operands are NaN (`NMin` only promises a NaN); and without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. |
353| `ds_swizzle_b32` | An active destination reads the selected source lane's VGPR. If EXEC disables that source, the read returns zero; a disabled destination keeps its prior value. The [hardware measurements](shader_validation.md#hardware-oracle-for-the-lds-programs---oracle-hw) confirm the disabled-source result on gfx1036 and gfx1150. In the seven-invocation CPU fixture, lane 6 selects lane 7, which is absent. The translator returns zero in that case; the corresponding result on hardware is unverified. The fixture exercises `QUAD_PERM` and `SWAP` in `test_ds_permute.py`. | 380| `ds_swizzle_b32` | An active destination reads the selected source lane's VGPR. If EXEC disables that source, the read returns zero; a disabled destination keeps its prior value. The [hardware measurements](shader_validation.md#hardware-oracle-for-the-lds-programs---oracle-hw) confirm the disabled-source result on gfx1036 and gfx1150. In the seven-invocation CPU fixture, lane 6 selects lane 7, which is absent. The translator returns zero in that case; the corresponding result on hardware is unverified. The fixture exercises `QUAD_PERM` and `SWAP` in `test_ds_permute.py`. A numeric `offset:N` below 0xC000 is decoded like its symbolic `swizzle(...)` form since #4177; 0xC000–0xFFFF is refused (`Unsupported`), which RDNA2 treats as a separate mode (measured on gfx1036 for all 16,384 offsets). **No game shader is affected either way** (SHADER-811): over the 1.0.2.1 package's 26,503 DXBC listings and the FidelityFX DLL's 29 FSPX programs, llvm-mc prints all 105,529 `ds_swizzle_b32` (in 6,296 DXBC programs; the FSPX programs have none) in a symbolic form, with 17 distinct offsets: 101,913 in 0x8000–0xBFFF (`QUAD_PERM`), 3,616 below 0x8000 (the bitmask mode: `BROADCAST`, `SWAP`, `BITMASK_PERM`) and none at or above 0xC000. Counted from each instruction's printed encoding (offset = bits 15:0 of the first dword) in every listing, the 1,473 with embedded data words included (only decoded instructions count), and matched by a count of the printed offset classes on a second copy (#4566). |
354| Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. RDNA2 does the same: gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D; RDNA2, but not the console's gfx1013), seeds 1 to 6, 38,858 programs, 0 mismatch and 56 omod -0 → +0 deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | 381| Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. RDNA2 does the same: gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D; RDNA2, but not the console's gfx1013), seeds 1 to 6, 38,858 programs, 0 mismatch and 56 omod -0 → +0 deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). |
355| Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). Wave size comes from the sidecar `fssm/<name>.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (FSPX programs or synthetic listings). Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | 382| Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). In wave32 code (a header or FSPX dispatch state that says so) `s_bfm_b64` is 64-bit data instead: the translator writes `((1 << (S0 & 63)) - 1) << (S1 & 63)` to the pair, `tools/lane_masks.py` leaves it data, and it doesn't count against an FSPX program's wave32 state. The pipeline library's wave32 compute programs build an S# in place with it (`s_bfm_b64 s[88:89], 2, 54`, then `s_mov_b64` of words 2-3; 958 programs, [shader_library.md](shader_library.md)). Only constant operands are translated there; none other is seen. `tests/semantic/test_wave32_bfm64_data.py`. Wave size comes from the sidecar `fssm/<name>.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (synthetic listings). **An FSPX program** (the FidelityFX DLL's, no FSSM blob) takes its wave size from its dispatch state instead: kind 0 word 4 bit 20, set = wave32 (`fspx/<name>.json` `wave32`). Only a strict marker (`WAVE64_RE` against wave32, `WAVE32_RE` against wave64) contradicts it and raises `Unsupported`; a `_b64` op on `vcc` or `exec` does not, since these programs move `vcc` as an ordinary SGPR pair. Without that field the heuristic stays. Confirmed on the 29 programs of 1.0.2.1: strict markers never contradict the bit, the `RSRC1` VGPR granule fits it in all 21 programs that decode cleanly, and `PSV0` lane counts agree with it in all 5 that state one ([fspx.md](fspx.md), "Kind 0: dispatch state"). Translated with the bit, the 4 programs the heuristic got wrong change size, and the other 22 translated modules are byte-identical. CPU-checked by `tests/semantic/test_fspx_wave_size.py`, including a `v_readlane_b32` whose result differs between the two sizes; `vk_pipeline_check` builds all 26 modules. Not GPU-checked on these programs' own data. Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. |
356| Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. | 383| Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. |
357| First active lane in a vertex shader (`v_readfirstlane_b32`, MoltenVK) | A native `v_readfirstlane_b32` is a ballot of the EXEC lanes, its lowest set bit, and a shuffle from that lane (lane 0 when no lane is on). **In a vertex shader the lowest bit is taken with `FindILsb` over the ballot's four words** (the lowest non-zero word wins), not with `OpGroupNonUniformBallotFindLSB`. The two give the same lane, because a ballot has no bit at or above the subgroup size. Other stages keep `BallotFindLSB`; the `--wave64-emulate` form already used `FindILsb` on its two mask words. Why: MoltenVK lowers `BallotFindLSB`, like the `SubgroupSize` built-in, to Metal's `threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for input declaration in a vertex function"), so every VS with a readfirstlane failed to compile there. **Confirmed on an Apple M4 (MoltenVK 1.4.2):** hand-written VS with `subgroupBallotFindLSB` or `gl_SubgroupSize` fail, and ballot, shuffle, broadcast-first, elect, votes, and ballot + `findLSB` + shuffle (32- and 64-lane forms) create. Corpus (1.0.2.1, translated from `4eb6155d`): 572 of the 2,236 VS contain `v_readfirstlane_b32`, and exactly those 572 modules change; all 2,236 stay `spirv-val`-valid. VS pipelines on the M4 go from 667 to 672 of 2,236 on main (the rest fail on the subgroup lane built-in, #1784), and from 1,662 to 2,233 with #1784's vertex-subgroup workaround (its flag is not on main) (the 571 `threads_per_simdgroup` failures are gone). `tests/semantic/test_vs_readfirstlane.py` runs it on the wave interpreter with the first EXEC lane in word 0 and word 1. | 384| First active lane in a vertex shader (`v_readfirstlane_b32`, MoltenVK) | A native `v_readfirstlane_b32` is a ballot of the EXEC lanes, its lowest set bit, and a shuffle from that lane (lane 0 when no lane is on). **In a vertex shader the lowest bit is taken with `FindILsb` over the ballot's four words** (the lowest non-zero word wins), not with `OpGroupNonUniformBallotFindLSB`. The two give the same lane, because a ballot has no bit at or above the subgroup size. Other stages keep `BallotFindLSB`; the `--wave64-emulate` form already used `FindILsb` on its two mask words. Why: MoltenVK lowers `BallotFindLSB`, like the `SubgroupSize` built-in, to Metal's `threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for input declaration in a vertex function"), so every VS with a readfirstlane failed to compile there. **Confirmed on an Apple M4 (MoltenVK 1.4.2):** hand-written VS with `subgroupBallotFindLSB` or `gl_SubgroupSize` fail, and ballot, shuffle, broadcast-first, elect, votes, and ballot + `findLSB` + shuffle (32- and 64-lane forms) create. Corpus (1.0.2.1, translated from `4eb6155d`): 572 of the 2,236 VS contain `v_readfirstlane_b32`, and exactly those 572 modules change; all 2,236 stay `spirv-val`-valid. VS pipelines on the M4 go from 667 to 672 of 2,236 on main (the rest fail on the subgroup lane built-in, #1784), and from 1,662 to 2,233 with #1784's vertex-subgroup workaround (its flag is not on main) (the 571 `threads_per_simdgroup` failures are gone). `tests/semantic/test_vs_readfirstlane.py` runs it on the wave interpreter with the first EXEC lane in word 0 and word 1. |
358| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. Under `--wave64-emulate`, `tools/wave64_emulate_opt.py` runs three exact CFG/dataflow passes to eliminate redundant scheduler rounds and global `OpSwitch` blow-up (#884): (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, no live-out scalars, and for each memory domain (`mem`/`lds`) either read-only accesses or an acyclic single write/atomic behind `if (%active)` (issuing any uniform `x_memory_order` split/barrier before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), and (3) structured emulation (`plan_structured_emulation`, `control_flow = "emulated wave64 structured"`) removes the global round-loop `OpSwitch` on multi-superblock reducible CFGs without non-uniform 32-bit half-mask SCC: single-wave workgroups (`<= 64` threads) run 100% inline structured SPIR-V with direct workgroup barriers (`0` `OpSwitch`, `0` `x_spill`, strictly monotone GEN/KILL 4-bit `dirty_in` memory ordering across blocks and loop back-edges), while multi-wave workgroups (`> 64` threads, without divergent `s_barrier`) emit post-dominating spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, `EXEC`-widening, and read-only loops) inline and isolate any remaining wave-divergent barrier regions into local mini-schedulers (or a tail scheduler at early `s_endpgm`). Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (40/64/128/256-thread workgroup interpreter with strict uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, single-store WAR/RAW ordering, single-wave `inline_all` loop-carried WAR, monotone `dirty_in` regression after `x_round`, multi-wave `structured_hybrid` + local `mini_scheduler`, divergent `s_barrier` fallback, `cs_w64x_saveexec_b64.s` fixture, and negative controls; **not yet GPU-verified** for the structured emulation pass). (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), and (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no memory/LDS writes, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, and no live-out scalars behind `if (%active)` (issuing any uniform `x_memory_order` split before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), keeping all 64 lanes of each wave in the same scheduler round. Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (64-thread and 128-thread workgroup interpreter with uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, internal loop, `cs_w64x_saveexec_b64.s` fixture, RAW memory/scalar-load ordering, and negative controls for live-out scalars, stores, cross-lane ops, and EXEC-widening). `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | 385| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. Under `--wave64-emulate`, `tools/wave64_emulate_opt.py` runs three exact CFG/dataflow passes to eliminate redundant scheduler rounds and global `OpSwitch` blow-up (#884): (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, no live-out scalars, and for each memory domain (`mem`/`lds`) either read-only accesses or an acyclic single write/atomic behind `if (%active)` (issuing any uniform `x_memory_order` split/barrier before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), and (3) structured emulation (`plan_structured_emulation`, `control_flow = "emulated wave64 structured"`) removes the global round-loop `OpSwitch` on multi-superblock reducible CFGs without non-uniform 32-bit half-mask SCC: single-wave workgroups (`<= 64` threads) run 100% inline structured SPIR-V with direct workgroup barriers (`0` `OpSwitch`, `0` `x_spill`, strictly monotone GEN/KILL 4-bit `dirty_in` memory ordering across blocks and loop back-edges), while multi-wave workgroups (`> 64` threads, without divergent `s_barrier`) emit post-dominating spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, `EXEC`-widening, and read-only loops) inline and isolate any remaining wave-divergent barrier regions into local mini-schedulers (or a tail scheduler at early `s_endpgm`). Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (40/64/128/256-thread workgroup interpreter with strict uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, single-store WAR/RAW ordering, single-wave `inline_all` loop-carried WAR, monotone `dirty_in` regression after `x_round`, multi-wave `structured_hybrid` + local `mini_scheduler`, divergent `s_barrier` fallback, `cs_w64x_saveexec_b64.s` fixture, and negative controls; **not yet GPU-verified** for the structured emulation pass). (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), and (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no memory/LDS writes, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, and no live-out scalars behind `if (%active)` (issuing any uniform `x_memory_order` split before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), keeping all 64 lanes of each wave in the same scheduler round. Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (64-thread and 128-thread workgroup interpreter with uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, internal loop, `cs_w64x_saveexec_b64.s` fixture, RAW memory/scalar-load ordering, and negative controls for live-out scalars, stores, cross-lane ops, and EXEC-widening). `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). |
359| Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | 386| Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. |
360| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one). The raw pair a PS reads ("PS system inputs": 321 PS) comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module then needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. The stage before the PS writes (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices: `tools/bary_fallback_gs.py` writes that pass-through geometry shader from the index (Position and the PS's input locations copied unchanged). Default (perspective) interpolation of those weights is the perspective-correct barycentric, the value `BaryCoordKHR` has, so `.y`/`.z` stay AMD's i/j; shaders that don't read the pair translate to the same module either way. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal, no barycentric extension; driver 560.94, Windows 10) with `LEONIDA_BARY_FALLBACK=1`: `ps_bary` 4096/4096 pixels exact, and `ps_uniform_branch` and `ps_scc_mask32` pass, through `run_gpu_tests.py` and `build.py` + `check.py`, with zero Khronos validation messages. Checked in `tests/semantic/test_bary_fallback.py`. For a known VS/PS pair, `python -I tools/bary_fallback_gs.py DIR --pair VS PS` builds `PS.bary_gs.clipN.spv`. It copies the producer’s `ClipDistance[N]` at each emitted vertex, using the VS index field `clip_distance_count`. On RTX 5080 and Radeon integrated graphics, two independently shifted clip planes yielded 512, 1024, 2048 or 4096 covered pixels, matching the native barycentric path. For a cull-only VS the pair writes `PS.bary_gs.cullN.spv` from `cull_distance_count`. A two-plane synthetic draw on the same GPUs covered 0 pixels when every vertex was negative for either plane and all 4096 when each plane had a nonnegative vertex. The helper rejects mixed clip/cull arrays. The runtime building that GS per pipeline is the follow-up (it needs the graphics pipelines of #291). | 387| Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. |
388| Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** |
389| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. |
361| Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | 390| Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. |
362| Full-corpus pipeline build | `vk_pipeline_check <spirv dir> pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | 391| Full-corpus pipeline build | `vk_pipeline_check <spirv dir> pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. |
392| `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). |
363| Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | 393| Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. |
364| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. This was checked against what all 2,689 CS read before writing: 2,281 match exactly, and the rest overshoot only through loop-carried registers in the straight-line check. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | 394| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. |
365| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). | 395| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). |
366| Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | 396| Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. |
367| Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | 397| Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. |
368| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | 398| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. |
399| LDS access order within a wave (`Volatile`) | RDNA2 runs a wave in lockstep with an in-order LDS queue, so a `ds_read` issued after a `ds_write` sees every lane's write with no `s_barrier` between them (`cs_w64x_lds_raw`), and a `ds_write` issued after a `ds_read` does not change what that read returned (`cs_w64x_lds_war`). Translated, a lane is an invocation, and the Vulkan memory model orders nothing between invocations without a barrier or an atomic, so a driver's compiler may move an invocation's load ahead of its own earlier store to another address, or merge two loads of one address. Results consistent with these optimizations were observed with AMD's Windows driver 24.30.46 (LLPC, Vulkan 1.3.302) on a Radeon 880M (RDNA3.5, native 64-wide compute subgroups): on `main` `561b65a8` both tests failed on every run with uninitialized Workgroup memory in all eight words, and in `cs_w64x_lds_war` the second read returned the same words as the first. Rule: every plain LDS `OpLoad` and `OpStore` (`lds_load`, `lds_store` and the two ADDTID forms) carries the `Volatile` memory operand, which prevents elimination, duplication or combination of the access ([SPIR-V memory operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Memory_Access)). This rule applies to plain accesses only. On that GPU and driver `Volatile` on the store alone or on the load alone made `cs_w64x_lds_raw` return its expected words (hand-edited SPIR-V, 3 of 3 runs each, against 0 of 4 unmodified), and with the rule both tests pass: `run_gpu_tests.py` goes from 210 to 212 of 232 passed with none failing (20 skipped), native and with `LEONIDA_W64_EMULATE=1`. An RTX 5070 Laptop (NVIDIA 621.01) gives the same results before and after (183 of 232 native, 214 emulated; `ms_wave_info_s3` fails both times). The operand changes 17 of the 238 test shaders and nothing but those loads and stores. A [full Xbox 1.0.2.1 corpus comparison](https://github.com/ItsNotRexed/Leonida/pull/6714#issuecomment-7107280378) translated and validated all 26,503 shaders at both 561b65a8 and 58deee34. Only the added operands differed in the 484 compute and 5 mesh modules that changed. The RAW and WAR results establish a workaround on the tested driver. Portable ordering between invocations requires synchronization appropriate to the accesses (see #2345). Under `--wave64-emulate` the halves meet at the round barriers as before; the operand is emitted there too. CPU-checked by `tests/semantic/test_lds_volatile.py` (every plain access form on the wave32, wave64 and emulated paths, and no other access is Volatile). |
369| `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`; GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11), and measured on native gfx1100 through `tools/hw_oracle` (hit, miss and hit-to-zero), where GFX11 spells it `ds_cmpstore_b32` with the store value before the compare value. **Not GPU-verified.** GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11). | 400| `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`; GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11), and measured on native gfx1100 through `tools/hw_oracle` (hit, miss and hit-to-zero), where GFX11 spells it `ds_cmpstore_b32` with the store value before the compare value. **Not GPU-verified.** GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11). |
401| `ds_cmpst_f32`/`_rtn_f32`, `global_atomic_fcmpswap`, `buffer_atomic_fcmpswap` | `tmp = M; M = (tmp == CMP as binary32) ? DATA : tmp`, and the returning forms give `tmp` (RDNA2 ISA). The compare is a float compare (`OpFOrdEqual`): −0 matches +0, and a NaN never matches, not even the same bits. `OpAtomicCompareExchange` compares bits, so this is a loop (`Gen.float_cmpswap_loop`): read M, pick DATA or M by the float compare, and swap that in if M still holds what was read. Exact under contention. Operands: `ds_cmpst_f32` takes CMP then DATA, as `ds_cmpst_b32`; the global and buffer forms take `vdata` as {DATA, CMP}, as `cmpswap`. Inactive lanes, bounds and `glc` are as for their integer siblings. **Not measured:** subnormal inputs; the interpreter compares them exactly. `_x2` forms stay `Unsupported`; the image form is #2653's. Until 2026-11-22 all four raised `Unsupported`. CPU-checked by `tests/semantic/test_float_cmpswap.py` (±0, NaN, ∞, a subnormal, no `glc`, buffer bounds, 32 lanes on one dword). **Not GPU-verified.** |
370| LDS ADDTID (`ds_read_addtid_b32`, `ds_write_addtid_b32`) | The LDS forms address one dword at `M0[15:0] + offset + 4 * lane`, where `offset` is an unsigned 16-bit byte offset and `lane` is the invocation index within the RDNA wave. The Workgroup array supplies LDS_BASE. The compute/mesh path uses the ordinary LDS addressing and EXEC guard. The GDS form raises `Unsupported`. Source: RDNA2 ISA §10.4 and §12.13 (opcodes 176/177), LLVM GFX1030 assembly syntax. `tests/semantic/test_lds_addtid.py` compares the two forms with ordinary LDS reads/writes over two waves, including partial EXEC and emulated wave64. | 402| LDS ADDTID (`ds_read_addtid_b32`, `ds_write_addtid_b32`) | The LDS forms address one dword at `M0[15:0] + offset + 4 * lane`, where `offset` is an unsigned 16-bit byte offset and `lane` is the invocation index within the RDNA wave. The Workgroup array supplies LDS_BASE. The compute/mesh path uses the ordinary LDS addressing and EXEC guard. The GDS form raises `Unsupported`. Source: RDNA2 ISA §10.4 and §12.13 (opcodes 176/177), LLVM GFX1030 assembly syntax. `tests/semantic/test_lds_addtid.py` compares the two forms with ordinary LDS reads/writes over two waves, including partial EXEC and emulated wave64. |
371| `ds_add_f32`, `ds_add_rtn_f32` | `M = M + DATA` as binary32 on the LDS dword (RDNA2 ISA, `DS_ADD_F32`); the `_rtn_` form returns the old M. No core SPIR-V atomic adds floats on Workgroup memory, so it is an `OpAtomicCompareExchange` loop with an `OpFAdd` (round to nearest even, `NoContraction`). That is exact under contention: every update is one successful exchange of the value it read. **Not measured:** how the LDS adder treats denormals and NaN payloads; the result is `OpFAdd`'s IEEE sum. The f32 min/max forms are #2495's. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_add_f32.py` (a value grid, the non-returning form, `offset:`, ties to even, -0 + +0, overflow to ±inf, seeded values, against a once-rounded double sum). **Not GPU-verified.** | 403| `ds_add_f32`, `ds_add_rtn_f32` | Atomic binary32 add on LDS (`Workgroup` memory); `ds_add_rtn_f32` returns the exact pre-addition 32-bit value in `vdst`, while `ds_add_f32` discards it. Lowered to a core SPIR-V structured `OpAtomicCompareExchange` (`Workgroup` scope `2`, relaxed `None`/`None` equal and unequal semantics) CAS loop over `%v_lds` (`%uint` storage, `OpBitcast` <-> `%float` + `OpFAdd`, bitwise `OpIEqual` exit check so `NaN` terminates in 1 iteration without looping, returning loop-header `%cur` for `ds_add_rtn_f32` with no `VK_EXT_shader_atomic_float` dependency). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): confirmed normal binary32 sums (`1.5 + 2.25 -> 3.75`), signed zero rules (`+0.0 + +0.0 -> +0.0`, `-0.0 + -0.0 -> -0.0`, `+0.0 + -0.0 -> +0.0`), infinities/NaNs (`+Inf + 1.0 -> +Inf`, `+Inf + -Inf -> 0xffc00000` qNaN, quiet NaN payload `0x7fc12345` preserved), exact old-value return on `_rtn_` vs unchanged `vdst` on non-return, `offset:` variants (4, 16, 64, 256, 1020), unaligned byte addressing (unaligned non-4-byte-multiple byte addresses dropped by hardware), `EXEC` inactive-lane masking (0x55555555 leaves LDS untouched by inactive lanes), and wave32/wave64 multi-lane same-address contention (32 and 64 lanes concurrently adding 1.0f yield exact sums 32.0 / 64.0 and return unique permutation chains with zero lost updates). Subnormal note: native `gfx1036` flushed FP32 subnormal inputs/outputs to zero (FTZ/DAZ) in the LDS adder, whereas core SPIR-V `OpFAdd` leaves FP32 denorm flushing to the host Vulkan driver / `DenormFlushToZero` mode. CPU-checked by `tests/semantic/test_lds_add_f32.py`. `M = M + DATA` as binary32 on the LDS dword (RDNA2 ISA, `DS_ADD_F32`); the `_rtn_` form returns the old M. No core SPIR-V atomic adds floats on Workgroup memory, so it is an `OpAtomicCompareExchange` loop with an `OpFAdd` (round to nearest even, `NoContraction`). That is exact under contention: every update is one successful exchange of the value it read. **Not measured:** how the LDS adder treats denormals and NaN payloads; the result is `OpFAdd`'s IEEE sum. The f32 min/max forms are #2495's. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_add_f32.py` (a value grid, the non-returning form, `offset:`, ties to even, -0 + +0, overflow to ±inf, seeded values, against a once-rounded double sum). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 49 cases: the LDS adder **flushes denormal inputs and denormal results to zero** (`0x00800001 + -0x00800000` gives `+0`, not `0x00000001`; `0x007fffff + 0x00800000` gives `0x00800000`, not the tie's `0x00ffffff`; `0x00000001 + 0x00000001` gives `+0`), while the `OpFAdd` the translator emits keeps them, so denormal operands and results are a known divergence. A NaN is quieted with its payload and sign kept (sNaN `0x7f800001` becomes `0x7fc00001`) and when both operands are NaN the DATA operand wins whatever the payloads (`0x7fc00007 + 0x7fc00000` gives `0x7fc00000`); `inf + -inf` gives `0xffc00000`. The f32 min/max forms are #2495's. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_add_f32.py` (a value grid, the non-returning form, `offset:`, ties to even, -0 + +0, overflow to ±inf, seeded values, against a once-rounded double sum). Normal sums match that model on the same run: ties to even (`1.0 + 2^-24` stays `1.0`, `1.0 + 3*2^-25` goes up), `-0 + -0` is `-0`, `+0 + -0` is `+0`, overflow to `±inf`, and the `_rtn_` form returns the raw pre-op dword, denormal or not. |
372| `ds_mskor_b32`, `ds_mskor_rtn_b32` | `tmp = M[A]; M[A] = (tmp & ~DATA) \| DATA2`; the `_rtn_` form returns `tmp` (RDNA2 ISA, DS). Emitted as an atomic AND with `~DATA`, whose result is `tmp`, then an atomic OR with `DATA2`, so the returned value is exact. DATA2 bits outside DATA are ORed in too, as the formula says; it isn't a masked insert. **Approximation:** the memory ends as the single op leaves it unless another lane's op on the same dword lands between the two atomics. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_mskor.py` (a value grid, the non-returning form, DATA2 outside DATA, `offset:`, seeded values). Measured on native gfx1100, including DATA2 bits outside DATA being ORed in, so it is not a masked insert. **Not GPU-verified.** | 404| `ds_mskor_b32`, `ds_mskor_rtn_b32` | `tmp = M[A]; M[A] = (tmp & ~DATA) \| DATA2`; the `_rtn_` form returns `tmp` (RDNA2 ISA, DS). Emitted as an atomic AND with `~DATA`, whose result is `tmp`, then an atomic OR with `DATA2`, so the returned value is exact. DATA2 bits outside DATA are ORed in too, as the formula says; it isn't a masked insert. **Approximation:** the memory ends as the single op leaves it unless another lane's op on the same dword lands between the two atomics. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_mskor.py` (a value grid, the non-returning form, DATA2 outside DATA, `offset:`, seeded values). Measured on native gfx1100, including DATA2 bits outside DATA being ORed in, so it is not a masked insert. **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`: 20 of 20 one-thread cases (five M/DATA/DATA2 triples including DATA2 bits outside DATA, both forms, `offset:` 0 and 12) leave `(M & ~DATA) \| DATA2` and return M. **The approximation, measured:** 32 lanes on one dword (M = 0xABCD12FF, DATA = 0xFF, DATA2 = 1 << (lane & 7)) run one lane at a time in lane order on the hardware: each lane returns the word the lane before it left (lane 0 0xABCD12FF, lane 1 0xABCD1201, lane 2 0xABCD1202, …) and the dword ends 0xABCD1280. The two-atomic emission does every AND before every OR, so it would end 0xABCD12FF and return 0xABCD1200 to lanes 1..31 (expected, not run through the translator). **Not GPU-verified.** |
373| `ds_{inc,dec,rsub}_u32`, `ds_{min,max}_f32` (and `_rtn_`) | 32-bit LDS atomics lowered inside `Gen.lds_op` via a Workgroup-scope `OpAtomicCompareExchange` CAS loop (no shader float atomic extension needed): `ds_inc_u32` gives `(M >= DATA) ? 0 : M + 1` (unsigned), `ds_dec_u32` gives `(M == 0 \|\| M > DATA) ? DATA : M - 1` (unsigned), `ds_rsub_u32` gives `DATA - M` (wrapping), and `ds_{min,max}_f32` use GLSL.std.450 `NMin`/`NMax` (NaN returns the non-NaN operand, `-0.0 < +0.0`, matching `global_atomic_fmin`/`fmax`). The `_rtn_` forms return the pre-op word in `vdst`; inactive lanes skip the op and preserve `vdst`. Source: AMD RDNA2 ISA DS encoding. CPU-checked by `tests/semantic/test_lds_atomics_cas.py` (edge value grids, NaN/±0/±inf, `offset:`, `vdst` aliasing, inactive lanes, sequential wraparound, Workgroup CAS loop structure, outside-compute and bad-operand rejections). Measured on native gfx1100 (single thread, 28 cases): `ds_inc_u32` gives `M + 1` until `M >= DATA` and 0 from there, `ds_dec_u32` gives `M - 1` or `DATA` when `M == 0` or `M > DATA`, `ds_rsub_u32` wraps, the `_rtn_` forms return the pre-op word, and `ds_{min,max}_f32` take the non-NaN operand and rank `-0.0` below `+0.0`. **Not GPU-verified.** | 405| `ds_{inc,dec,rsub}_u32`, `ds_{min,max}_f32` (and `_rtn_`) | 32-bit LDS atomics lowered inside `Gen.lds_op` via a Workgroup-scope `OpAtomicCompareExchange` CAS loop (no shader float atomic extension needed): `ds_inc_u32` gives `(M >= DATA) ? 0 : M + 1` (unsigned), `ds_dec_u32` gives `(M == 0 \|\| M > DATA) ? DATA : M - 1` (unsigned), `ds_rsub_u32` gives `DATA - M` (wrapping), and `ds_{min,max}_f32` use GLSL.std.450 `NMin`/`NMax` (NaN returns the non-NaN operand, `-0.0 < +0.0`, matching `global_atomic_fmin`/`fmax`). The `_rtn_` forms return the pre-op word in `vdst`; inactive lanes skip the op and preserve `vdst`. Source: AMD RDNA2 ISA DS encoding. CPU-checked by `tests/semantic/test_lds_atomics_cas.py` (edge value grids, NaN/±0/±inf, `offset:`, `vdst` aliasing, inactive lanes, sequential wraparound, Workgroup CAS loop structure, outside-compute and bad-operand rejections). Measured on native gfx1100 (single thread, 28 cases): `ds_inc_u32` gives `M + 1` until `M >= DATA` and 0 from there, `ds_dec_u32` gives `M - 1` or `DATA` when `M == 0` or `M > DATA`, `ds_rsub_u32` wraps, the `_rtn_` forms return the pre-op word, and `ds_{min,max}_f32` take the non-NaN operand and rank `-0.0` below `+0.0`. **Not GPU-verified.** |
374| `ds_wrxchg2_rtn_b32`, `ds_wrxchg2st64_rtn_b32` | Two atomic exchanges, addressed as `ds_write2_b32` addresses its dwords: `vaddr + offset0 * 4` and `vaddr + offset1 * 4` (times 64 for st64). `M[A0] = data0` and `M[A1] = data1`, and `vdst` (a VGPR pair) gets the two old words. Both exchanges run before either result is written, so `vdst` may alias the address or data VGPRs. When both offsets name one dword, the second exchange returns `data0`. Each exchange is atomic on its own, not the pair together, as on hardware (two DS operations). Until 2026-11-22 both ops raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg2.py` (offsets, st64 = 256-byte steps, the same dword twice, aliasing, a single-VGPR `vdst` rejected). Measured on native gfx1100: with `vaddr` 16 the offsets 0/4 read `vaddr + 0` and `vaddr + 16`, the `_st64_` form's offsets 1/2 read `vaddr + 256` and `vaddr + 512` (64 dwords per step), `vdst` takes the two old words, and with both offsets on one dword the second exchange returns `data0`; `vdst` may alias the address or the data pair, which still lands both data words in LDS and leaves the old words in `vdst`. **Not GPU-verified.** | 406| `ds_wrxchg2_rtn_b32`, `ds_wrxchg2st64_rtn_b32` | Two atomic exchanges, addressed as `ds_write2_b32` addresses its dwords: `vaddr + offset0 * 4` and `vaddr + offset1 * 4` (times 64 for st64). `M[A0] = data0` and `M[A1] = data1`, and `vdst` (a VGPR pair) gets the two old words. Both exchanges run before either result is written, so `vdst` may alias the address or data VGPRs. When both offsets name one dword, the second exchange returns `data0`. Each exchange is atomic on its own, not the pair together, as on hardware (two DS operations). Until 2026-11-22 both ops raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg2.py` (offsets, st64 = 256-byte steps, the same dword twice, aliasing, a single-VGPR `vdst` rejected). Measured on native gfx1100: with `vaddr` 16 the offsets 0/4 read `vaddr + 0` and `vaddr + 16`, the `_st64_` form's offsets 1/2 read `vaddr + 256` and `vaddr + 512` (64 dwords per step), `vdst` takes the two old words, and with both offsets on one dword the second exchange returns `data0`; `vdst` may alias the address or the data pair, which still lands both data words in LDS and leaves the old words in `vdst`. **Not GPU-verified.** |
375| `ds_wrxchg_rtn_b64`, `ds_wrxchg2_rtn_b64`, `ds_wrxchg2st64_rtn_b64` | 64-bit LDS exchanges (two dwords, low first): `M[A] = DATA`, and `vdst` gets the old 64 bits. `wrxchg_rtn_b64` has one element at `vaddr + offset`. The `2` forms have two, at `vaddr + offset0/offset1 * 8` (times 64 for st64), as `ds_write2_b64` addresses them, and `vdst` is four VGPRs. Each dword is its own 32-bit `OpAtomicExchange`, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **Approximation:** two lanes exchanging into one element at once can tear it, leaving one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), which a 64-bit exchange never does; and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Until 2026-11-22 these three raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg_b64.py` (values, `offset:`, `vdst` aliasing the data, both 2 forms, st64 = 512-byte steps, bad operands rejected). Measured on native gfx1100: `M[vaddr]` takes the data pair and `vdst` gets the old pair, the `2` form's offsets 0/2 read `vaddr + 0` and `vaddr + 16` with four old dwords in `vdst`, and the `_st64_` form's offsets 1/2 read `vaddr + 512` and `vaddr + 1024` (64 pairs per step). **Not GPU-verified.** | 407| `ds_wrxchg_rtn_b64`, `ds_wrxchg2_rtn_b64`, `ds_wrxchg2st64_rtn_b64` | 64-bit LDS exchanges (two dwords, low first): `M[A] = DATA`, and `vdst` gets the old 64 bits. `wrxchg_rtn_b64` has one element at `vaddr + offset`. The `2` forms have two, at `vaddr + offset0/offset1 * 8` (times 64 for st64), as `ds_write2_b64` addresses them, and `vdst` is four VGPRs. Each dword is its own 32-bit `OpAtomicExchange`, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **Approximation:** two lanes exchanging into one element at once can tear it, leaving one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), which a 64-bit exchange never does; and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Until 2026-11-22 these three raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg_b64.py` (values, `offset:`, `vdst` aliasing the data, both 2 forms, st64 = 512-byte steps, bad operands rejected). Measured on native gfx1100: `M[vaddr]` takes the data pair and `vdst` gets the old pair, the `2` form's offsets 0/2 read `vaddr + 0` and `vaddr + 16` with four old dwords in `vdst`, and the `_st64_` form's offsets 1/2 read `vaddr + 512` and `vaddr + 1024` (64 pairs per step). **Not GPU-verified.** |
376| `ds_and_b64`, `ds_or_b64`, `ds_xor_b64` (and `_rtn_`) | `M = M op DATA` on the 64-bit LDS element at `vaddr + offset` (two dwords, low first); the `_rtn_` form returns the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so it is emitted as one 32-bit `OpAtomicAnd/Or/Xor` per dword. That leaves exactly the memory a 64-bit atomic would, without Int64 atomics on Workgroup memory (optional in Vulkan). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done; the memory result is exact. The other 64-bit LDS atomics (`add/sub/min/max_u64`, `wrxchg_b64`, `cmpst_b64`) carry between dwords or need the pair to move together, and still raise `Unsupported`. Until 2026-11-22 these three were rejected as well. CPU-checked by `tests/semantic/test_lds_bitwise_b64.py` (all six forms, offsets, `vdst` aliasing the data, seeded values). **Not GPU-verified.** Measured on native gfx1100 for all six forms, both dwords of each pair, with the returning forms giving the old pair. | 408| `ds_and_b64`, `ds_or_b64`, `ds_xor_b64` (and `_rtn_`) | `M = M op DATA` on the 64-bit LDS element at `vaddr + offset` (two dwords, low first); the `_rtn_` form returns the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so it is emitted as one 32-bit `OpAtomicAnd/Or/Xor` per dword. That leaves exactly the memory a 64-bit atomic would, without Int64 atomics on Workgroup memory (optional in Vulkan). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done; the memory result is exact. The other 64-bit LDS atomics (`add/sub/min/max_u64`, `wrxchg_b64`, `cmpst_b64`) carry between dwords or need the pair to move together, and still raise `Unsupported`. Until 2026-11-22 these three were rejected as well. CPU-checked by `tests/semantic/test_lds_bitwise_b64.py` (all six forms, offsets, `vdst` aliasing the data, seeded values). **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`: 39 of 39 one-thread cases (all six forms on three 64-bit M/DATA pairs, `offset:` 0 and 24, and `vdst` aliasing the data pair for each `_rtn_` op) leave M op DATA in both dwords and return the old pair. 32 lanes `ds_xor_rtn_b64` with (1 << lane) in both dwords on one element ran in lane order: lane i returned (2^i − 1) in both words, so the hardware never shows a half-done pair, unlike the two-read emission under contention. **Not GPU-verified.** Measured on native gfx1100 for all six forms, both dwords of each pair, with the returning forms giving the old pair. |
377| `ds_bpermute_b32` subgroup convergence | Native wave32 and wave64 apply bitwise masks to the shuffle result and the destination write so both the ballot and shuffle execute before lane predication. If the ballot has no source lane, the shuffle reads the calling lane before the result is masked to zero. MoltenVK 1.4.2 lowered the scalar selects to nested Metal ternaries, placing the subgroup operations in divergent control flow. The `cs_bpermute32` inactive-source case returned 64 on an Apple M1 Max, and all eight fixture words match with bitwise masking. | 409| `ds_bpermute_b32` subgroup convergence | Native wave32 and wave64 apply bitwise masks to the shuffle result and the destination write so both the ballot and shuffle execute before lane predication. If the ballot has no source lane, the shuffle reads the calling lane before the result is masked to zero. MoltenVK 1.4.2 lowered the scalar selects to nested Metal ternaries, placing the subgroup operations in divergent control flow. The `cs_bpermute32` inactive-source case returned 64 on an Apple M1 Max, and all eight fixture words match with bitwise masking. |
378| LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable); GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (unit 8 and the 512-byte st64 forms, plus vdst/vaddr overlap, on an RTX 3070, driver 621.01, Windows 11). | 410| LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable); GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (unit 8 and the 512-byte st64 forms, plus vdst/vaddr overlap, on an RTX 3070, driver 621.01, Windows 11; the same eight words also on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel)). |
379| Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. | 411| Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. |
380| Typed image stores | `image_store` (2D, 2D array, 3D) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. | 412| Typed image stores | `image_store` (2D, 2D array, 3D) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. |
381| Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D<min16uint>` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. | 413| Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D<min16uint>` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. |
382| Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | 414| Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
383| 1D and 3D texture UAVs (D3D-78) | Storage bindings are 17–19 for 1D and 26–28 for 1D arrays (SPIR-V `1D`, arrayed), leaving multisample SRV bindings 20–25 unchanged. 1D arrays are storage-only: `image_load` and `image_store` use `(x, layer)` relative to the view. Ordinary 1D and 3D loads use sampled aliases; `image_load ... glc` in either dimension, or any `image_load` on a 1D array, reads the Unknown-format storage view. A layer-created 3D UAV sets reserved bit 31 of T# word 4; word 7 tagged with `0xd7800000` (mask `0xff800000`) holds `WSize - 1` in bits [21:11] and `FirstWSlice` in bits [10:0], including for whole-mip UAVs. Vulkan rebases/checks Z for storage operations. The typed sampled aliases below use the tag to rebase Z and return zero outside the range or for nonzero UAV LOD; an untagged SRV keeps its original coordinates and LOD. For non-`glc` `image_load` on a tagged R32_UINT T# whose SGPR group also feeds volume atomics in the shader, the read uses their formatted storage view (binding 7) so it can observe the atomic result in the same dispatch. Other sampled loads retain the visibility rule below. 3D atomics run only in active lanes with a resolved R32_UINT UAV; `glc` returns the old value and inactive lanes keep their destination. `cs_texture_uav.asm` and `d3d12_texture_uav_test` check coherent and sampled reads, dynamic `image_load_mip`, an untouched base mip, and active/inactive add and compare-and-swap with `glc` on an RTX 4090. | 415| 1D and 3D texture UAVs (D3D-78) | Storage bindings are 17–19 for 1D and 26–28 for 1D arrays (SPIR-V `1D`, arrayed), leaving multisample SRV bindings 20–25 unchanged. 1D arrays are storage-only: `image_load` and `image_store` use `(x, layer)` relative to the view. Ordinary 1D and 3D loads use sampled aliases; `image_load ... glc` in either dimension, or any `image_load` on a 1D array, reads the Unknown-format storage view. A layer-created 3D UAV sets reserved bit 31 of T# word 4; word 7 tagged with `0xd7800000` (mask `0xff800000`) holds `WSize - 1` in bits [21:11] and `FirstWSlice` in bits [10:0], including for whole-mip UAVs. Vulkan rebases/checks Z for storage operations. The typed sampled aliases below use the tag to rebase Z and return zero outside the range or for nonzero UAV LOD; an untagged SRV keeps its original coordinates and LOD. For non-`glc` `image_load` on a tagged R32_UINT T# whose SGPR group also feeds volume atomics in the shader, the read uses their formatted storage view (binding 7) so it can observe the atomic result in the same dispatch. Other sampled loads retain the visibility rule below. 3D atomics run only in active lanes with a resolved R32_UINT UAV; `glc` returns the old value and inactive lanes keep their destination. `cs_texture_uav.asm` and `d3d12_texture_uav_test` check coherent and sampled reads, dynamic `image_load_mip`, an untouched base mip, and active/inactive add and compare-and-swap with `glc` on an RTX 4090. |
384| Packed RGB9E5 UAV backing (#1287 and D3D-78) | Emulated RGB9E5 still encodes the logical shared-exponent FORMAT in the T#. A sampled view reads E5B9G9R9; a raw storage view uses R32_UINT, with any selected W range applied only to that storage view. On 1D-family and 3D UAVs, bit 22 of the synthetic word 7 marks this backing (tag mask `0xff800000`, lower 22 W bits unchanged). The translator does not implement re-packing for generic `image_store` or unpacking for formatless storage loads: these operations respectively suppress writes or take the fallback, not a view of the wrong numeric type. R32_UINT atomics require a logical R32_UINT volume UAV. The packed bit does not affect slicing or untagged SRVs; `d3d12_r9g9b9e5_uav_test` checks raw stores and sampled readback with the real set 0. | 416| Packed RGB9E5 UAV backing (#1287 and D3D-78) | Emulated RGB9E5 still encodes the logical shared-exponent FORMAT in the T#. A sampled view reads E5B9G9R9; a raw storage view uses R32_UINT, with any selected W range applied only to that storage view. On 1D-family and 3D UAVs, bit 22 of the synthetic word 7 marks this backing (tag mask `0xff800000`, lower 22 W bits unchanged). The translator does not implement re-packing for generic `image_store` or unpacking for formatless storage loads: these operations respectively suppress writes or take the fallback, not a view of the wrong numeric type. R32_UINT atomics require a logical R32_UINT volume UAV. The packed bit does not affect slicing or untagged SRVs; `d3d12_r9g9b9e5_uav_test` checks raw stores and sampled readback with the real set 0. |
385| 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The synthetic translator tests check the four address registers and the RGBA32 format selection. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) Only a tagged 3D UAV constrains the view-relative LOD to zero and rebases Z; an untagged 3D SRV keeps its explicit LOD and coordinates. The `cs_imgload_mip` GPU fixture separately checks both D16 halves and full-width reads against distinct 2D mips. | 417| 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The unit test `test_volume_mip_fetch_uses_xyz_level_and_descriptor_type` in `tests/test_image_load_typed.py` checks the four address registers and the RGBA32 format selection on the translated module. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) |
386| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. \| AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. | 418| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. \| AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. On the CPU, the unit tests `test_explicit_lod_gather_fetches_four_taps_from_each_typed_view` and `test_2d_gather_picks_the_sampled_type_and_selected_component` in `tests/test_image_load_typed.py` check the typed views at binding 0, the selected component, the shared mip footprint and the d16 packing. |
419| Dynamic sampled descriptor indices | Set 0 bindings 0 (2D), 3 (2D array and cube), 5 (1D) and 6 (3D), including their integer sampled aliases, use runtime T# hash results for sampling, gather, texel fetch and image queries. Binding 1 uses runtime S# hash results for sampling, gather and LOD queries. Explicit-LOD gather emulation takes its sampler state directly from S# words and uses sampled-image fetches. Literal descriptor words and the zero-on-miss fallback still go through the runtime lookup. Emit `SampledImageArrayDynamicIndexing` and record `shaderSampledImageArrayDynamicIndexing` in the shader index whenever such an array is indexed. A storage-only shader can declare sampled arrays without indexing them. The hash table is one storage buffer containing an array of words. T# and S# operands are scalar across an RDNA2 wave (AMD RDNA 2 ISA, MIMG fields SRSRC/SSAMP). The Vulkan contract requires the resulting index to be dynamically uniform in the subgroup or invocation group, and in the invocation group when the effective subgroup size is one. If wave and Vulkan execution mappings break that uniformity, the affected accesses need separate non-uniform indexing support. Confirmed by the synthetic `sampled_dynamic_index.asm` regression (`test_sample_with_literal_sampler_still_indexes_both_arrays_dynamically` and `test_fetch_and_query_paths` in `tests/semantic/test_sampled_dynamic_index.py`), `spirv-val`, and the declaration-only GPU positive control in [#2806](https://github.com/ItsNotRexed/Leonida/pull/2806#issuecomment-7083836498). [Vulkan VUID 10128](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-SampledImageArrayDynamicIndexing-10128) and [runtime VUIDs 10135 and 10142](https://docs.vulkan.org/refpages/latest/refpages/source/RuntimeSpirv.html#VUID-RuntimeSpirv-SampledImageArrayNonUniformIndexing-10135). |
387| Half-precision coordinates for LOD queries | For `image_get_lod a16` on 2D and 2D-array images, the low and high halves of the first address VGPR supply U and V. The array layer is excluded from `OpImageQueryLod`; the selected clamped and raw LOD outputs are f32. `tests/semantic/fixtures/get_lod_a16.asm` assembles for gfx1030 and checks the query operands and output components through `tests/test_image_load_typed.py`. [AMD RDNA2 ISA, MIMG](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) | 420| Half-precision coordinates for LOD queries | For `image_get_lod a16` on 2D and 2D-array images, the low and high halves of the first address VGPR supply U and V. The array layer is excluded from `OpImageQueryLod`; the selected clamped and raw LOD outputs are f32. `tests/semantic/fixtures/get_lod_a16.asm` assembles for gfx1030 and checks the query operands and output components through `tests/test_image_load_typed.py`. [AMD RDNA2 ISA, MIMG](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) |
388| Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off leaves memory alone: cmpswap is skipped, the others run with the operand that changes nothing. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (1) and the level count in VGPRs 0..3 (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). The translator still differs in the first three: it writes 1 for the 2D depth word and the full layer count for a 2D array, and `OpImageQuerySizeLod` past the last level is undefined. `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: resinfo's depth word on hardware (1 is what the T#'s DEPTH field says for a 2D image), the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. | 421| Dynamic storage image descriptor indices | The runtime T# hash result indexes the r32ui arrays (bindings 4 and 7) used by `OpImageTexelPointer` for image atomics and the typed storage arrays (bindings 8 through 19) used by `OpImageWrite` for stores and `OpImageRead` for coherent loads. Literal T# words still go through the hash table. Emit `StorageImageArrayDynamicIndexing` and record `shaderStorageImageArrayDynamicIndexing` in the shader index when a storage array is accessed this way. Plain typed loads use sampled aliases and follow the sampled indexing rule. The same Vulkan dynamic-uniformity contract applies to storage indices. Confirmed by [Vulkan VUID 10130](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-StorageImageArrayDynamicIndexing-10130), the synthetic `storage_dynamic_index.asm` regression (`test_literal_storage_descriptor_and_mixed_sampled_load`, `test_storage_aliases_in_every_dimension` and `test_atomic_texel_pointers_use_storage_indices` in `tests/semantic/test_sampled_dynamic_index.py`) and `spirv-val`. |
422| Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off skips the access entirely (`OpAccessChain`, `OpImageTexelPointer`, `OpAtomic*`, and any `glc` write-back sit inside `if (active)`), leaving memory and `vdata` untouched. Two-VGPR `dmask:0x3` forms of the nine standard ops currently still operate on the low 32-bit dword as before; true 64-bit image atomics remain separate follow-up work. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (1) and the level count in VGPRs 0..3 (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). The translator still differs in the first three: it writes 1 for the 2D depth word and the full layer count for a 2D array, and `OpImageQuerySizeLod` past the last level is undefined. `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: resinfo's depth word on hardware (1 is what the T#'s DEPTH field says for a 2D image), the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. |
423| `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | The six remaining 32-bit MIMG image atomics on 2D (binding 4) and 3D (binding 7) `r32ui` storage images (including `a16` packed coordinates and optional `glc` return), guarded by `active_b` so inactive lanes skip memory access and preserve `vdata`. `image_atomic_swap` emits `OpAtomicExchange`; `inc`/`dec`/`fmin`/`fmax`/`fcmpswap` emit `OpAtomicLoad` (valid on `OpImageTexelPointer` `Image` pointers) followed by a Device-scope `OpAtomicCompareExchange` CAS loop (`inc`: `(M >= D) ? 0 : M + 1`; `dec`: `(M == 0 \|\| M > D) ? D : M - 1`; `fmin`/`fmax`: GLSL.std.450 `NMin`/`NMax`, no float-atomic extension required; `fcmpswap`: integer IEEE-754 binary32 ordered equality on raw 32-bit words — equal iff neither is NaN and `(cur == cmp) \|\| (both ±0.0)`, preserving subnormals even on Vulkan drivers reporting `shaderDenormPreserveFloat32 = false`, exiting without writing on mismatch or NaN; native RDNA2 subnormal behavior under denormal flush is unmeasured). Source: AMD RDNA2 ISA MIMG `IMAGE_ATOMIC_*`. CPU-checked structurally (including `spirv_mini_interp.check_structure` CFG validation) by `tests/semantic/test_image_atomics_32.py` (all 6 ops on 2D and 3D images, `a16`, `glc` and non-`glc`, no `AtomicFloat` capability, rejected widths/coords/dims). **Not GPU-verified on RDNA2.** |
389| Hand-written short assembler forms | `llvm-mc` accepts `v_add_co_ci_u32 vD, src0, src1` (also `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with the carry out and in left to VCC, and a modifier list shorter than the operands (`op_sel_hi:[0,0]`, `neg_lo:[1,0]` on a three-source op), whose missing entries are 0; it prints them as `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo` and `[0,0,0]`. The GPU runner assembles through `llvm-mc -show-encoding`, so it sees the printed form; `tests/semantic/regen_fixtures.py` copies the `.asm` text as written, so the translator takes the source spelling too (it used to raise `IndexError` for these: the carry forms, `v_pk_fma_f16`, `v_fma_mix_*`). A probe of 42,000 operand and modifier variations of 302 ALU mnemonics, in the source spelling and as `llvm-mc` prints them, found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_short_asm_forms.py`. | 424| Hand-written short assembler forms | `llvm-mc` accepts `v_add_co_ci_u32 vD, src0, src1` (also `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with the carry out and in left to VCC, and a modifier list shorter than the operands (`op_sel_hi:[0,0]`, `neg_lo:[1,0]` on a three-source op), whose missing entries are 0; it prints them as `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo` and `[0,0,0]`. The GPU runner assembles through `llvm-mc -show-encoding`, so it sees the printed form; `tests/semantic/regen_fixtures.py` copies the `.asm` text as written, so the translator takes the source spelling too (it used to raise `IndexError` for these: the carry forms, `v_pk_fma_f16`, `v_fma_mix_*`). A probe of 42,000 operand and modifier variations of 302 ALU mnemonics, in the source spelling and as `llvm-mc` prints them, found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_short_asm_forms.py`. |
390| SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. A byte or word destination with PRESERVE reads its incoming VGPR on first use. The synthetic `sdwa_bary_input.asm` checks this with two raw fragment weights, following the [LLVM SDWA destination rules](https://llvm.org/docs/AMDGPUModifierSyntax.html#dst-unused). VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. **Measured natively on RDNA2** (gfx1036 iGPU, `tools/hw_oracle`, the game's MODE): all 172 distinct SDWA forms of the 26,503 listings (79,307 instructions: opcode, operand kinds, sels, `sext`, neg/abs, `dst_unused`, omod), 12 operand words per source, 21,204 cases. 18,885 give the translator's word. The rest are: a 16-bit result with `dst_sel:DWORD`, where the hardware zeroes the high half and the translator keeps it (1,888, #2187); a NaN result, where the hardware keeps the input's sign and payload (826 counting those also in the first group, as in the f16 transcendentals row); `div:2` on -0, which gives +0 (1, as in the output-modifier rows); and 160 cases whose translation is undefined in SPIR-V (`FClamp`/`FDiv`/`Sqrt` on NaN, zero or negative operands). `tests/semantic/test_alu_sdwa_hw.py` replays 624 of the matching words, up to four per form. | 425| SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. A byte or word destination with PRESERVE reads its incoming VGPR on first use. The synthetic `sdwa_bary_input.asm` checks this with two raw fragment weights, following the [LLVM SDWA destination rules](https://llvm.org/docs/AMDGPUModifierSyntax.html#dst-unused). VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. **Measured natively on RDNA2** (gfx1036 iGPU, `tools/hw_oracle`, the game's MODE): all 172 distinct SDWA forms of the 26,503 listings (79,307 instructions: opcode, operand kinds, sels, `sext`, neg/abs, `dst_unused`, omod), 12 operand words per source, 21,204 cases. 18,885 give the translator's word. The rest are: a 16-bit result with `dst_sel:DWORD`, where the hardware zeroes the high half and the translator keeps it (1,888, #2187); a NaN result, where the hardware keeps the input's sign and payload (826, of which 556 also fall in the first group, so the groups add up to 21,204; as in the f16 transcendentals row); `div:2` on -0, which gives +0 (1, as in the output-modifier rows); and 160 cases whose translation is undefined in SPIR-V (`FClamp`/`FDiv`/`Sqrt` on NaN, zero or negative operands). `tests/semantic/test_alu_sdwa_hw.py` replays 624 of the matching words, up to four per form. |
391| VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). | 426| VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). |
392| Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. When S2 is a literal or a currently known SGPR constant, the translator emits fixed byte extracts/inserts (including sign replication), folds the zero and 0xff bytes, and uses the selected source directly for a whole-word identity. `tests/semantic/test_perm_known_selector.py` checks the resulting words and that selector dispatch only remains for a clobbered SGPR. | 427| Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. When S2 is a literal or a currently known SGPR constant, the translator emits fixed byte extracts/inserts (including sign replication), folds the zero and 0xff bytes, and uses the selected source directly for a whole-word identity. `tests/semantic/test_perm_known_selector.py` checks the resulting words and that selector dispatch only remains for a clobbered SGPR. |
393| `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | The six remaining 32-bit MIMG image atomics on 2D (binding 4) and 3D (binding 7) `r32ui` storage images (including `a16` packed coordinates and optional `glc` return), guarded by `active_b` so inactive lanes skip memory access and preserve `vdata`. `image_atomic_swap` emits `OpAtomicExchange`; `inc`/`dec`/`fmin`/`fmax`/`fcmpswap` emit `OpAtomicLoad` (valid on `OpImageTexelPointer` `Image` pointers) followed by a Device-scope `OpAtomicCompareExchange` CAS loop (`inc`: `(M >= D) ? 0 : M + 1`; `dec`: `(M == 0 \|\| M > D) ? D : M - 1`; `fmin`/`fmax`: GLSL.std.450 `NMin`/`NMax`, no float-atomic extension required; `fcmpswap`: integer IEEE-754 binary32 ordered equality on raw 32-bit words — equal iff neither is NaN and `(cur == cmp) \|\| (both ±0.0)`, preserving subnormals even on Vulkan drivers reporting `shaderDenormPreserveFloat32 = false`, exiting without writing on mismatch or NaN; native RDNA2 subnormal behavior under denormal flush is unmeasured). Source: AMD RDNA2 ISA MIMG `IMAGE_ATOMIC_*`. CPU-checked structurally (including `spirv_mini_interp.check_structure` CFG validation) by `tests/semantic/test_image_atomics_32.py` (all 6 ops on 2D and 3D images, `a16`, `glc` and non-`glc`, no `AtomicFloat` capability, rejected widths/coords/dims). **Not GPU-verified on RDNA2.** |
394| Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ \| S0 − S1\ \| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. | 428| Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ \| S0 − S1\ \| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. |
395| Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `test_alu_qsad.py` and `test_alu_mqsad_u32.py`. | 429| Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `tests/semantic/test_alu_qsad.py` (`test_null_pixel_source_and_null_accumulator`) and `tests/semantic/test_alu_mqsad_u32.py` (`test_null_pixel_source`). |
396| `v_mqsad_u32_u8` | Four masked byte-SADs with full 32-bit accumulators: D[k] = S2[k] + `v_msad_u8` of the 32-bit window S0[8k+31:8k] of the 64-bit S0 against S1, wrapping at 32 bits (S2 and D are four VGPRs). Every source is read before the first write; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mqsad_u32.py`. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across 64-bit sliding window and masked byte values against the 32-bit accumulators: bit-exact with the ISA reference. **Not GPU-verified.** | 430| `v_mqsad_u32_u8` | Four masked byte-SADs with full 32-bit accumulators: D[k] = S2[k] + `v_msad_u8` of the 32-bit window S0[8k+31:8k] of the 64-bit S0 against S1, wrapping at 32 bits (S2 and D are four VGPRs). Every source is read before the first write; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mqsad_u32.py`. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across 64-bit sliding window and masked byte values against the 32-bit accumulators: bit-exact with the ISA reference. |
397| `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py (500 programs, --oracle translator,hw): 500 pass, 0 mismatches against the reference; confirmed s_flbit_i32 gives 0xFFFFFFFF for 0 and -1. | 431| `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py (500 programs, --oracle translator,hw): 500 pass, 0 mismatches against the reference; confirmed s_flbit_i32 gives 0xFFFFFFFF for 0 and -1. |
398| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The translator uses the per-byte identity `x + y = 2*(x & y) + (x ^ y)`. It clears each byte's low bit before shifting, then adds the rounding bit only to an odd sum. Each result fits in one byte, so the packed additions do not carry across bytes. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. The synthetic `tests/semantic/fixtures/lerp_packed_bytes.asm` gives exact words across a 64x64 draw on an RTX 3070 (NVIDIA 591.86). Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across byte edge values and rounding bit variations: 0 mismatches against the ISA reference. | 432| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The translator uses the per-byte identity `x + y = 2*(x & y) + (x ^ y)`. It clears each byte's low bit before shifting, then adds the rounding bit only to an odd sum. Each result fits in one byte, so the packed additions do not carry across bytes. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. The synthetic `tests/semantic/fixtures/lerp_packed_bytes.asm` gives exact words across a 64x64 draw on an RTX 3070 (NVIDIA 591.86). Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across byte edge values and rounding bit variations: 0 mismatches against the ISA reference. |
399| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination stays `Unsupported`, #210). `s_cmov_b64`: D[63:0] = SCC ? S0[63:0] : D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask (EXEC, VCC or a mask SGPR) stays `Unsupported` (#210) — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask. D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask stays `Unsupported` (#210). D[63:0], SCC read and not written, on plain 64-bit data pairs (SGPR pair, immediate or `null`); any dword that is or has been a lane mask (EXEC, VCC or a mask SGPR) makes the pair `Unsupported` — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask (#210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU `SOPInstructions.td` (`S_CMOV_B64 : RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU [SOPInstructions.td](https://github.com/llvm/llvm-project/blob/2bfedf3338162e2c841a73cd7cd9e98d00add608/llvm/lib/Target/AMDGPU/SOPInstructions.td) (`S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`). CPU-checked by `tests/semantic/test_salu_cmov.py`, `tests/semantic/test_salu_cmov_b64.py` and `test_salu_pack.py`; no corpus count; **not GPU-verified, no corpus count**; the translated shaders were run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: **no corpus count**; Hardware: on native `gfx1036` (Ryzen 9 9950X3D iGPU, Windows 11, driver 26.10.1) `tools/int_hw_probe.py --oracle both --wave both` matches the translator in wave32 and wave64 for all five `salu_cmov_pack` cases and for the 14 `s_cmov_b64` cases (`--group salu_cmov_b64`: GPU-checked for `s_cmov_b32` (`cs_w32_salu64.asm`, SCC = 1 selects S0) and `s_pack_lh_b32_b16` (`cs_w32_int_ext.asm`) on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92); `s_cmovk_i32`, `s_cmov_b64` and the other `s_pack_*` forms have no GPU test on main; the translated shaders were also run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept), and on native gfx1036 (AMD Radeon Graphics, Windows 11, driver 26.10.1) through `tools/hw_oracle`: all five `salu_cmov_pack` cases and the 14 `s_cmov_b64` cases match the translator in wave32 and wave64 (SCC 0 and 1; an SGPR pair, the inline constants -1/-16/64, the literal 0x89abcdef, `null` and the destination itself; SCC = 1 takes S0, 0 keeps D, SCC is never written), `s_cmov_b32` matches under SCC=0 and SCC=1, and `s_pack_ll/lh/hh_b32_b16` is bit-exact on 500 random programs with 0 mismatches (`--oracle translator,hw`). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Also **measured on RDNA2 gfx1036** (Radeon iGPU of a Ryzen 9 9950X3D, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher, rocm-sdk-core clang): `tools/int_hw_probe.py --oracle both --wave both` gives the same words as the translator for all five `salu_cmov_pack` cases in wave32 and wave64, and the 14 `s_cmov_b64` cases of the `salu_cmov_b64` group (`python -I tools/int_hw_probe.py --oracle both --wave both --group salu_cmov_b64`; SCC 0 and 1; source an SGPR pair, the inline constants -1, -16 and 64, the literal 0x89abcdef, `null`, and the destination itself; SCC preset and read back after): SCC preset and read back after) match the translator in wave32 and wave64: SCC = 1 takes S0 (a literal zero-extended, an inline constant sign-extended, `null` gives 0), SCC = 0 keeps D, SCC is never written. Also on `gfx1035` via `int_hw_probe` (SHADER-137, SCC kept), and on `gfx1036` and an RTX 5080 through the fixtures `cs_w32_salu64.asm` (`s_cmov_b32`) and `cs_w32_int_ext.asm` (`s_pack_lh_b32_b16`). `tools/hw_oracle` + `tools/salu_diff.py` verify `s_cmov_b32` under SCC 0/1 and `s_pack_ll/lh/hh_b32_b16` bit-exact on 500 random programs with 0 mismatches. Reviewers ran `s_cmov*` on an RTX 5090, an RTX 4050 and a Radeon 740M (#613) and `s_pack_*` on an RTX 5090 (#449). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py: s_cmov_b32 verified under SCC=0 and SCC=1 (preserving destination and updating respectively); s_pack_ll/lh/hh_b32_b16 verified bit-exact on 500 random programs with 0 mismatches (--oracle translator,hw). **Not measured on RDNA2.** | 433| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination stays `Unsupported`, #210). `s_cmov_b64`: D[63:0] = SCC ? S0[63:0] : D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask (EXEC, VCC or a mask SGPR) stays `Unsupported` (#210) — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask. D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask stays `Unsupported` (#210). D[63:0], SCC read and not written, on plain 64-bit data pairs (SGPR pair, immediate or `null`); any dword that is or has been a lane mask (EXEC, VCC or a mask SGPR) makes the pair `Unsupported` — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask (#210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU `SOPInstructions.td` (`S_CMOV_B64 : RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU [SOPInstructions.td](https://github.com/llvm/llvm-project/blob/2bfedf3338162e2c841a73cd7cd9e98d00add608/llvm/lib/Target/AMDGPU/SOPInstructions.td) (`S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`). CPU-checked by `tests/semantic/test_salu_cmov.py`, `tests/semantic/test_salu_cmov_b64.py` and `test_salu_pack.py`; no corpus count; **not GPU-verified, no corpus count**; the translated shaders were run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: **no corpus count**; Hardware: on native `gfx1036` (Ryzen 9 9950X3D iGPU, Windows 11, driver 26.10.1) `tools/int_hw_probe.py --oracle both --wave both` matches the translator in wave32 and wave64 for all five `salu_cmov_pack` cases and for the 14 `s_cmov_b64` cases (`--group salu_cmov_b64`: GPU-checked for `s_cmov_b32` (`cs_w32_salu64.asm`, SCC = 1 selects S0) and `s_pack_lh_b32_b16` (`cs_w32_int_ext.asm`) on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92); `s_cmovk_i32`, `s_cmov_b64` and the other `s_pack_*` forms have no GPU test on main; the translated shaders were also run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept), and on native gfx1036 (AMD Radeon Graphics, Windows 11, driver 26.10.1) through `tools/hw_oracle`: all five `salu_cmov_pack` cases and the 14 `s_cmov_b64` cases match the translator in wave32 and wave64 (SCC 0 and 1; an SGPR pair, the inline constants -1/-16/64, the literal 0x89abcdef, `null` and the destination itself; SCC = 1 takes S0, 0 keeps D, SCC is never written), `s_cmov_b32` matches under SCC=0 and SCC=1, and `s_pack_ll/lh/hh_b32_b16` is bit-exact on 500 random programs with 0 mismatches (`--oracle translator,hw`). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Also **measured on RDNA2 gfx1036** (Radeon iGPU of a Ryzen 9 9950X3D, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher, rocm-sdk-core clang): `tools/int_hw_probe.py --oracle both --wave both` gives the same words as the translator for all five `salu_cmov_pack` cases in wave32 and wave64, and the 14 `s_cmov_b64` cases of the `salu_cmov_b64` group (`python -I tools/int_hw_probe.py --oracle both --wave both --group salu_cmov_b64`; SCC 0 and 1; source an SGPR pair, the inline constants -1, -16 and 64, the literal 0x89abcdef, `null`, and the destination itself; SCC preset and read back after): SCC preset and read back after) match the translator in wave32 and wave64: SCC = 1 takes S0 (a literal zero-extended, an inline constant sign-extended, `null` gives 0), SCC = 0 keeps D, SCC is never written. Also on `gfx1035` via `int_hw_probe` (SHADER-137, SCC kept), and on `gfx1036` and an RTX 5080 through the fixtures `cs_w32_salu64.asm` (`s_cmov_b32`) and `cs_w32_int_ext.asm` (`s_pack_lh_b32_b16`). `tools/hw_oracle` + `tools/salu_diff.py` verify `s_cmov_b32` under SCC 0/1 and `s_pack_ll/lh/hh_b32_b16` bit-exact on 500 random programs with 0 mismatches. Reviewers ran `s_cmov*` on an RTX 5090, an RTX 4050 and a Radeon 740M (#613) and `s_pack_*` on an RTX 5090 (#449). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py: s_cmov_b32 verified under SCC=0 and SCC=1 (preserving destination and updating respectively); s_pack_ll/lh/hh_b32_b16 verified bit-exact on 500 random programs with 0 mismatches (--oracle translator,hw). **Not measured on RDNA2.** |
400| `v_bfi_b32` | `(S0 & S1) \| (~S0 & S2)` (RDNA2 ISA, VOP3 opcode 330). A literal or known same-block SGPR mask of zero or all ones selects S2 or S1 directly. A contiguous mask uses `OpBitFieldInsert` with S1 shifted down by the field offset, since RDNA2 reads the bits in place. For sparse constant masks the translator precomputes the complement. Runtime masks use the full bitwise expression. Checked by the hand-written `bfi_known_mask.asm` and `tests/semantic/test_bfi_known_mask.py`. | 434| `v_bfi_b32` | `(S0 & S1) \| (~S0 & S2)` (RDNA2 ISA, VOP3 opcode 330). A literal or known same-block SGPR mask of zero or all ones selects S2 or S1 directly. A contiguous mask uses `OpBitFieldInsert` with S1 shifted down by the field offset, since RDNA2 reads the bits in place. For sparse constant masks the translator precomputes the complement. Runtime masks use the full bitwise expression. Checked by the hand-written `bfi_known_mask.asm` and `tests/semantic/test_bfi_known_mask.py`. |
435| `v_bfm_b32` | The low five bits of S0 give the width and those of S1 give the offset. The result is the low 32 bits of `((1 << width) - 1) << offset` (RDNA2 ISA §12.12, VOP3 opcode 867). Literal and same-block SGPR constants are folded in the translator, including zero width and shifts that discard the high bits. Runtime operands keep their low-five-bit masks. Checked by `tests/semantic/test_bfm_known_operands.py` and `test_alu_int_misc.py`. |
401| `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | 436| `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. |
402| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Not GPU-verified.** **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | 437| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
403| `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by `tests/test_int_hw_probe.py` (`ValuBfeMeasuredOnRdna2`). | 438| `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by the unit test `ValuBfeMeasuredOnRdna2.test_translator_gives_the_gfx1036_words` in `tests/test_int_hw_probe.py`. |
404| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | 439| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** |
405| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| 440| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \|
406| Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). | 441| Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). |
407| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | 442| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). |
408| Vector integer additions (`v_mul_hi_u32_u24`/`v_mul_hi_i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`) | `v_mul_hi_*24`: the high 32 bits of the 48-bit product of the low 24 bits, zero-extended (u24) or sign-extended from bit 23 (i24); the high halves of `v_mul_u32_u24` / `v_mul_i32_i24`. `v_lshrrev_b64` / `v_ashrrev_i64`: the pair (or a 64-bit constant) shifted right by S0 & 63, logically or arithmetically, through the `v_lshlrev_b64` code. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8`: D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31:8k] against S1) & 0xFFFF; the m form skips bytes where S1's byte is 0; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mul_hi_24.py`, `test_alu_shift_b64.py`, `test_alu_qsad.py`; run on NVIDIA by reviewers (`v_mul_hi_*24`: RTX 5090 and RTX 5070 in #440; `v_qsad`/`v_mqsad`: 24 cases bit-exact on an RTX 3060 in #623). **Not measured on RDNA2.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137), and on native `gfx1036` (AMD Radeon Graphics) with 0 mismatches across signed/unsigned products, shifts, and sliding windows. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | 443| Vector integer additions (`v_mul_hi_u32_u24`/`v_mul_hi_i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`) | `v_mul_hi_*24`: the high 32 bits of the 48-bit product of the low 24 bits, zero-extended (u24) or sign-extended from bit 23 (i24); the high halves of `v_mul_u32_u24` / `v_mul_i32_i24`. `v_lshrrev_b64` / `v_ashrrev_i64`: the pair (or a 64-bit constant) shifted right by S0 & 63, logically or arithmetically, through the `v_lshlrev_b64` code. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8`: D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31:8k] against S1) & 0xFFFF; the m form skips bytes where S1's byte is 0; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mul_hi_24.py`, `test_alu_shift_b64.py`, `test_alu_qsad.py`; run on NVIDIA by reviewers (`v_mul_hi_*24`: RTX 5090 and RTX 5070 in #440; `v_qsad`/`v_mqsad`: 24 cases bit-exact on an RTX 3060 in #623). **Not measured on RDNA2.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137), and on native `gfx1036` (AMD Radeon Graphics) with 0 mismatches across signed/unsigned products, shifts, and sliding windows. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). |
409| 64-bit constant vector compares | For `i64`, `u64` and `f64`, V_CMP writes the predicate to VCC or the named scalar mask, with inactive lane bits cleared. V_CMPX ANDs the predicate into EXEC and preserves VCC. Both predicates ignore the source values, including NaNs. The 12 instructions in `tests/semantic/fixtures/vopc_constant_64.asm` assemble for gfx1030 and are CPU-checked with active and inactive lanes in `test_vopc_const_ordered.py`. [AMD RDNA 2 ISA, VOPC](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | 444| 64-bit constant vector compares | For `i64`, `u64` and `f64`, V_CMP writes the predicate to VCC or the named scalar mask, with inactive lane bits cleared. V_CMPX ANDs the predicate into EXEC and preserves VCC. Both predicates ignore the source values, including NaNs. The 12 instructions in `tests/semantic/fixtures/vopc_constant_64.asm` assemble for gfx1030 and are CPU-checked with active and inactive lanes in `test_vopc_const_ordered.py`. Measured on native gfx1100 (Radeon RX 7900 XTX, driver 26.10.1) as raw compute kernels: with EXEC preset to 0x55555555, `v_cmp_t_i64`, `v_cmp_t_u64` and `v_cmp_tru_f64` write 0x55555555 into the destination mask and the `v_cmp_f_*` forms write 0, so the inactive lane bits are cleared, while the other mask keeps its preset words (`s[10:11]` stays 0xdeadbeef/0xfeedface, VCC stays 0x0f0f0f0f/0xf0f0f0f0); `v_cmpx_t_*` leaves EXEC at 0x55555555 and `v_cmpx_f_*` clears it to 0, with VCC untouched in both; an operand holding a quiet NaN changes nothing. In wave32 only the low 32-bit mask register is written — `s11` and `vcc_hi` keep their previous words for a constant and a real `v_cmp_eq_i64` alike — where the wave64 pair `s[10:11]` receives 0xffffffff in both halves. [AMD RDNA 2 ISA, VOPC](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
410| Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. All 16 f16 predicates (`v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16`, e32 and e64) are GPU-checked on quiet and signalling NaN, +-0, +-inf, denormals and junk high halves by `ps_vcmp_f16.asm` and `ps_vcmp_f16_e64.asm` (RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_vcmp_f16.py`. The 16 `v_cmpx_*_f16` forms (e32 and e64) are GPU-checked the same way by `ps_vcmpx_f16.asm` and `ps_vcmpx_f16_e64.asm` (EXEC result on every case, VCC kept, EXEC only narrowed; RTX 5080 and Radeon gfx1036), CPU side `tests/semantic/test_vcmpx_f16.py`. | 445| Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. All 16 f16 predicates (`v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16`, e32 and e64) are GPU-checked on quiet and signalling NaN, +-0, +-inf, denormals and junk high halves by `ps_vcmp_f16.asm` and `ps_vcmp_f16_e64.asm` (RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_vcmp_f16.py`. The 16 `v_cmpx_*_f16` forms (e32 and e64) are GPU-checked the same way by `ps_vcmpx_f16.asm` and `ps_vcmpx_f16_e64.asm` (EXEC result on every case, VCC kept, EXEC only narrowed; RTX 5080 and Radeon gfx1036), CPU side `tests/semantic/test_vcmpx_f16.py`. |
411| Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \ \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). | 446| Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. The SPIR-V register array has 256 entries. An effective index outside this array reads VGPR0 or drops the write, following RDNA2 ISA §3.6.1. A smaller per-wave hardware allocation is not available to this check. The boundary is checked by `tests/semantic/test_relative_vgpr_bounds.py`. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \ \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). |
412| `v_swaprel_b32` | GFX10 VOP1 opcode 104: swap `VGPR[D + M0[25:16]]` and `VGPR[S0 + M0[9:0]]`, the two M0 fields `v_movrelsd_2_b32` uses; the other M0 bits are ignored (RDNA2 ISA opcode description). Both registers are read before either is written. When both name one register it keeps its value. Inactive lanes keep both registers (`OpSelect` on `active`). As for `v_movrel*`, the hardware's range check against the VGPR allocation is not modelled. A non-VGPR operand raises `Unsupported`. Until 2026-11-22 the op raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_swaprel.py` (both fields, ignored M0 bits, a self-swap, a register-file model). **Not GPU-verified.** **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_swaprel`): M0[25:16] & M0[9:0] offsets, ignored upper M0 bits (`0xfc01fc02`), self-swap, and inactive EXEC lanes all match bit-for-bit. | 447| `v_swaprel_b32` | GFX10 VOP1 opcode 104: swap `VGPR[D + M0[25:16]]` and `VGPR[S0 + M0[9:0]]`, the two M0 fields `v_movrelsd_2_b32` uses; the other M0 bits are ignored (RDNA2 ISA opcode description). Both registers are read before either is written. When both name one register it keeps its value. Inactive lanes keep both registers (`OpSelect` on `active`). As for `v_movrel*`, the bounds check uses the 256 entries in the SPIR-V array. Both operands are destinations, so either invalid index suppresses the whole swap (RDNA2 ISA §3.6.1). As for `v_movrel*`, the hardware's range check against the VGPR allocation is not modelled. A non-VGPR operand raises `Unsupported`. Until 2026-11-22 the op raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_swaprel.py` (both fields, ignored M0 bits, a self-swap, a register-file model). **Not GPU-verified.** **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_swaprel`): M0[25:16] & M0[9:0] offsets, ignored upper M0 bits (`0xfc01fc02`), self-swap, and inactive EXEC lanes all match bit-for-bit. |
413| Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. An SGPR that `lane_masks.py` marks as a lane mask (a saved EXEC, a `v_cmp` result) holds only this lane's bit, so the whole wave's mask word is collected for each such SGPR (as for `s_bcnt1`) and read instead when the index lands on it; D then holds the mask as data (SHADER-284, CPU-checked by `tests/semantic/test_salu_movrels_lane_mask.py`, wave32 and wave64). **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept; lane-mask SGPR collection is CPU-checked only). **Not GPU-verified.** | 448| Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. An SGPR that `lane_masks.py` marks as a lane mask (a saved EXEC, a `v_cmp` result) holds only this lane's bit, so the whole wave's mask word is collected for each such SGPR (as for `s_bcnt1`) and read instead when the index lands on it; D then holds the mask as data (SHADER-284, CPU-checked by `tests/semantic/test_salu_movrels_lane_mask.py`, wave32 and wave64). **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept; lane-mask SGPR collection is CPU-checked only). **Not GPU-verified.** |
414| d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer ops (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`: to nearest even, except the typed-buffer float conversions, which round toward zero (below). AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). Packed MUBUF and MTBUF loads clamp unsigned 32-bit channels to 65535 before writing each half. On native gfx1036, values 65534 and 65535 survived, while 65536, 65537 and 0xffffffff all produced 0xffff, across all four load widths in wave32 and wave64. Packed `buffer_load_format_d16_x` and `_xyz` write only the low 16 bits of the final VGPR. Its upper half survives even when the load is out of bounds. Native gfx1036 wave32 and wave64 confirmed this with RGBA8_UINT and RGBA8_UNORM, two destination seeds, and both even-component loads as full-write controls. Full pairs are packed by `pack_f16_pair_int` and an odd final buffer component is narrowed with `f16_bits` for float/normalized formats. These memory conversions do not use `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). **Typed buffer floats are narrowed toward zero (SHADER-358).** Measured natively on gfx1036 (RDNA2, wave32 and wave64, `tools/hw_oracle`): `buffer_store_format_*` into `16_FLOAT`/`16_16_FLOAT`/`16_16_16_16_FLOAT` and `buffer_load_format_d16_*` from `32_FLOAT`/`32_32_FLOAT`/`32_32_32_32_FLOAT` round an f32 toward zero, give ±65504 for a finite value past the f16 range (65520 stores 0x7bff, not infinity), flush an f32 denormal to a signed zero, keep infinities, and keep a NaN's sign and top 10 payload bits without quieting it (1 if those are 0: 0x7fa00000 gives 0x7d00, 0x7f800001 gives 0x7c01); gfx1150 does the same for the stores (#1548). The translator does that with `Gen.mem_f16`; until 2026-11-22 it rounded these to nearest even and overflowed to infinity. UNORM/SNORM d16 loads keep the rounding above (nearest even of the exact quotient, re-measured on gfx1036 for every 8-bit value and a 16-bit sample). Checked by `tests/semantic/test_buffer_f16_narrowing_hw.py` (45 measured values in four forms). Image d16 results are still inferred to round to nearest even (SHADER-308). #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. For typed buffer loads the rounding is measured (BUILD-161, `tools/d16_format_probe.py`). On an RX 6700 (gfx1031, AMD Windows driver 32.0.21045.29003), every UNORM8, SNORM8, UNORM10, UNORM16 and SNORM16 value was loaded through `buffer_load_format_d16_x` and `tbuffer_load_format_d16_x`, in wave32 and wave64. The hardware rounds the exact quotient once, straight to f16, to nearest even, with f16 denormals kept (65,536 of 65,536 UNORM16 and SNORM16 values). It does not round to f32 first: that double rounding is 1 ulp high on exactly four values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009). Over every width from 1 to 16 bits, only two f32 quotients land on an f16 halfway point: 0x3f7ff000 (16379/16383, 32759/32767, 65519/65535) and 0x3f7fb000 (65455/65535). `Gen.d16_norm_f16` takes the f16 below for those two, for normalized formats only; a 32_FLOAT 0x3f7ff000 is a real tie and still rounds to even. `buffer_load_format_x` without d16 returned the correctly rounded f32 quotient for all of them, the decode `norm_bits` builds. A 16_FLOAT d16 load returned its own bits for all 65,536 encodings. MUBUF and MTBUF agreed everywhere. For d16 image results, round to nearest even is still inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). | 449| `v_div_fixup_f16`, `v_div_fixup_f64` | Final IEEE-754 special-case fixup for division (VOP3, `S0` quotient, `S1` denominator, `S2` numerator) under the game's `MODE` (`ieee=0, denorm16_64=3, dx10_clamp=1`): `sign_out = sign(S1) ^ sign(S2)`; `NaN(S2)` → quieted `S2`; `NaN(S1)` → quieted `S1`; `NaN(S2)` → `S2` unchanged (sNaN not quieted under `IEEE=0`); `NaN(S1)` → `S1` unchanged; `(0/0)` or `(±inf/±inf)` → canonical negative qNaN (`0xFE00` for f16, `0xFFF80000_00000000` for f64); `(x/±inf)`, `(±0/y)`, or guaranteed exponent underflow (`exp(S2) - exp(S1) <= -25` for f16, `<= -1075` for f64) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or guaranteed exponent overflow (`exp(S2) - exp(S1) >= 16` for f16, `>= 1024` for f64) → `±inf` with `sign_out`; otherwise `copysign(S0, sign_out)` (including `NaN(S0)` keeping its payload with `sign_out`). `(x/±inf)` or `(±0/y)` (plus `exp(S2) - exp(S1) <= -1076` on f64 only; f16 has no exponent-difference cutoff) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or `NaN(S0)` → `±inf` with `sign_out` (no exponent-difference overflow cutoff on either f16 or f64); otherwise `copysign(S0, sign_out)`. Computed bit-exactly on integer words (no `OpCapability Float64` for plain `v_div_fixup_f64`); VOP3 input modifiers (`abs`/`neg`, plus `op_sel:[s0,s1,s2,dst]` on f16 with the unwritten half preserved) and `clamp`, which applies in every MODE. `mul:2`/`mul:4`/`div:2` are ignored by hardware here: measured by @fiestorra on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 4 inputs x 5 modifier forms x 5 MODEs for each of the two ops, wave32 and wave64 identical), the f16 and the binary64 result scale only under `IEEE=0` with `denorm_mode_16_64=0`; under `denorm_mode_16_64=3` the scaling is dropped while `clamp` still saturates, which is the `MODE` this row assumes, so only `clamp` is applied and `Float64` is enabled on f64 only when `clamp` is requested. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_DIV_FIXUP_F16`, `V_DIV_FIXUP_F64`). **Not measured on RDNA2 hardware** (translated GPU output checked on RTX 5070 by @duudiis). **Hardware-measured on RDNA2** (`gfx1036`, Windows driver `32.0.21042.62`, `tools/hw_oracle`, `ieee=0, denorm16_64=3, dx10_clamp=1`, wave32, by @timelery): `NaN(S0)` → `±inf`, f16 has no exponent-difference underflow/overflow check, f64 has underflow cutoff `e2 - e1 <= -1076` with no overflow check, and sNaN passes through unchanged under `IEEE=0`. Checked bit-for-bit on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_div_fixup.py`; not run on the shader corpus. |
415| `v_div_fixup_f16`, `v_div_fixup_f64` | Final IEEE-754 special-case fixup for division (VOP3, `S0` quotient, `S1` denominator, `S2` numerator) under the game's `MODE` (`ieee=0, denorm16_64=3, dx10_clamp=1`): `sign_out = sign(S1) ^ sign(S2)`; `NaN(S2)` → quieted `S2`; `NaN(S1)` → quieted `S1`; `NaN(S2)` → `S2` unchanged (sNaN not quieted under `IEEE=0`); `NaN(S1)` → `S1` unchanged; `(0/0)` or `(±inf/±inf)` → canonical negative qNaN (`0xFE00` for f16, `0xFFF80000_00000000` for f64); `(x/±inf)`, `(±0/y)`, or guaranteed exponent underflow (`exp(S2) - exp(S1) <= -25` for f16, `<= -1075` for f64) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or guaranteed exponent overflow (`exp(S2) - exp(S1) >= 16` for f16, `>= 1024` for f64) → `±inf` with `sign_out`; otherwise `copysign(S0, sign_out)` (including `NaN(S0)` keeping its payload with `sign_out`). `(x/±inf)` or `(±0/y)` (plus `exp(S2) - exp(S1) <= -1076` on f64 only; f16 has no exponent-difference cutoff) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or `NaN(S0)` → `±inf` with `sign_out` (no exponent-difference overflow cutoff on either f16 or f64); otherwise `copysign(S0, sign_out)`. Computed bit-exactly on integer words (no `OpCapability Float64` for plain `v_div_fixup_f64`); VOP3 input modifiers (`abs`/`neg`, plus `op_sel:[s0,s1,s2,dst]` on f16 with the unwritten half preserved) and output modifiers (`mul:2`/`mul:4`/`div:2`/`clamp`, enabling `Float64` on f64) apply. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_DIV_FIXUP_F16`, `V_DIV_FIXUP_F64`). **Not measured on RDNA2 hardware** (translated GPU output checked on RTX 5070 by @duudiis). **Hardware-measured on RDNA2** (`gfx1036`, Windows driver `32.0.21042.62`, `tools/hw_oracle`, `ieee=0, denorm16_64=3, dx10_clamp=1`, wave32, by @timelery): `NaN(S0)` → `±inf`, f16 has no exponent-difference underflow/overflow check, f64 has underflow cutoff `e2 - e1 <= -1076` with no overflow check, and sNaN passes through unchanged under `IEEE=0`. Checked bit-for-bit on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_div_fixup.py`; not run on the shader corpus. |
416| Image instruction without a VGPR data operand | `llvm-mc` accepts `off`, an SGPR or a constant where an `image_*` instruction names the VGPR range of its result or data (`image_sample off, v[1:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D`); no compiler emits it (the texels would have nowhere to go). The translator raises `Unsupported` (`<op> destination` for `image_op` and `image_get_lod`, `<op> data` for the `image_misc` group: `image_load_mip`, `image_get_resinfo`, `image_store`, the atomics) instead of the `KeyError` it gave when it wrote the result. A probe of about 60,000 DS, MUBUF, MTBUF, MIMG, SMEM and FLAT/GLOBAL/SCRATCH operand and modifier variations (glc, slc, dlc, lds, tfe, d16, a16, unorm, dmask, dim, offset, idxen, offen, addr64, format; as written and as `llvm-mc` prints them; pixel and compute stages) found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_mem_crash_forms.py`. | 450| Image instruction without a VGPR data operand | `llvm-mc` accepts `off`, an SGPR or a constant where an `image_*` instruction names the VGPR range of its result or data (`image_sample off, v[1:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D`); no compiler emits it (the texels would have nowhere to go). The translator raises `Unsupported` (`<op> destination` for `image_op` and `image_get_lod`, `<op> data` for the `image_misc` group: `image_load_mip`, `image_get_resinfo`, `image_store`, the atomics) instead of the `KeyError` it gave when it wrote the result. A probe of about 60,000 DS, MUBUF, MTBUF, MIMG, SMEM and FLAT/GLOBAL/SCRATCH operand and modifier variations (glc, slc, dlc, lds, tfe, d16, a16, unorm, dmask, dim, offset, idxen, offen, addr64, format; as written and as `llvm-mc` prints them; pixel and compute stages) found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_mem_crash_forms.py`. |
451| 16-bit float widening in typed buffer loads | A half NaN in a `buffer_load_format_*` / `tbuffer_load_format_*` load of formats 13 (`16_FLOAT`), 29 (`16_16_FLOAT`) or 71 (`16_16_16_16_FLOAT`) widens to f32 as `sign \| 0x7F800000 \| (payload << 13)`: the sign is kept, the 10-bit payload moves into the f32 mantissa unchanged, and the quiet bit is not forced, so an sNaN stays signalling. Measured natively on RDNA2 (gfx1036, wave32 and wave64, `_x`/`_xy`/`_xyzw`, MUBUF and MTBUF, `tools/f16_widen_probe.py`): 0x7ddb → 0x7fbb6000, 0x7fe6 → 0x7ffcc000, 0x7fbb → 0x7ff76000, 0xffb2 → 0xfff64000, 0x7fcb → 0x7ff96000, 0xff96 → 0xfff2c000, 0x7c01 → 0x7f802000, 0xfc01 → 0xff802000, and the controls 0x3c00 → 0x3f800000, 0xc000 → 0xc0000000. `v_cvt_f32_f16` (what a driver lowers `UnpackHalf2x16` to) differs on an sNaN, which it quiets with the payload kept (0x7ddb → 0x7ffb6000), and `UnpackHalf2x16`'s NaN result is undefined; the mini interpreter canonicalised it to 0x7fc00000. Until 2026-11-23 `Gen.decode_format` used `UnpackHalf2x16` for every half and so lost NaN payloads on all three formats; it now keeps `UnpackHalf2x16` for the non-NaN halves (an exact widening) and builds the NaN word from the bits with integer ops. `tools/mem_diff.py`'s reference was right only on Python 3.14 (its `struct` `'<e'` keeps the payload from 3.14 and canonicalises before); it now uses the same bit-level `f16_to_f32`, so the fuzzer is version independent. Checked by `tests/semantic/test_buffer_f16_widen_hw.py` (the ten measured words, MUBUF and MTBUF, 13/29/71, absent MTBUF channels) and `tools/mem_diff.py --self-test`; 10,500 generated `mem_diff` programs across seeds 1, 2, 3, 7, 11, 21, 22 and 23 match. |
417| Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | 452| Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. |
418| `v_cvt_f16_u16`, `v_cvt_f16_i16`, `v_cvt_u16_f16`, `v_cvt_i16_f16` | Conversions of the low 16-bit half (`op_sel:[src,dst]` picks the high half of the source / of the destination in the VOP3 form where supported; GFX10 does not accept `op_sel` on these opcodes); the other half of the destination is kept, like the other 16-bit-result ops (see *16-bit results*). `v_cvt_f16_u16` / `v_cvt_f16_i16` convert the unsigned / sign-extended half and narrow with the usual f16 rounding (65520 and above give +infinity for the unsigned form). `v_cvt_u16_f16` / `v_cvt_i16_f16` truncate toward zero, saturate to [0, 65535] / [-32768, 32767] (an f16 infinity too) and give 0 for NaN, as the 32-bit conversions do (*Float-to-int saturation*). `clamp` and the output multipliers are rejected as `Unsupported` rather than guessed. Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode. Checked on the CPU by `tests/semantic/test_alu_cvt_16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all four `_e64` forms keep the high half of the destination, `v_cvt_u16/i16_f16` give 0 for ±qNaN and saturate ±inf, and `v_cvt_f16_u16(65520)` gives +inf (`0x7c00`). Not run on the shader corpus. | 453| `v_cvt_f16_u16`, `v_cvt_f16_i16`, `v_cvt_u16_f16`, `v_cvt_i16_f16` | Conversions of the low 16-bit half (`op_sel:[src,dst]` picks the high half of the source / of the destination in the VOP3 form where supported; GFX10 does not accept `op_sel` on these opcodes); the other half of the destination is kept, like the other 16-bit-result ops (see *16-bit results*). `v_cvt_f16_u16` / `v_cvt_f16_i16` convert the unsigned / sign-extended half and narrow with the usual f16 rounding (65520 and above give +infinity for the unsigned form). `v_cvt_u16_f16` / `v_cvt_i16_f16` truncate toward zero, saturate to [0, 65535] / [-32768, 32767] (an f16 infinity too) and give 0 for NaN, as the 32-bit conversions do (*Float-to-int saturation*). `clamp` and the output multipliers are rejected as `Unsupported` rather than guessed. Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode. Checked on the CPU by `tests/semantic/test_alu_cvt_16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all four `_e64` forms keep the high half of the destination, `v_cvt_u16/i16_f16` give 0 for ±qNaN and saturate ±inf, and `v_cvt_f16_u16(65520)` gives +inf (`0x7c00`). Not run on the shader corpus. |
419| `v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16` | Normalized f16-to-16-bit integer conversions: `round_even(clamp(S0, -1, 1) * 32767)` (`i16`, snorm16) and `round_even(clamp(S0, 0, 1) * 65535)` (`u16`, unorm16), with NaN giving `0`, source `neg`/`abs` and SDWA `WORD_1` supported, and the unwritten half of the destination preserved (matching `v_cvt_i16_f16`/`v_cvt_u16_f16`; GFX10/LLVM does not accept VOP3 `op_sel` on these opcodes). For `\|cl\| >= 0.25`, `cl * (scale + 1)` is an exact even integer in f32, so `cl * (scale + 1) - RoundEven(cl)` rounds the exact product once without binary32 double-rounding ties near `±0.5`. VOP3 `clamp`, `mul:2`, `mul:4`, `div:2` (and combinations) and SDWA `clamp` are hardware no-ops on these integer-destination conversions and are accepted without changing output semantics; unsupported modifiers or invalid form/modifier pairs (e.g., `mul:8`, `_sdwa mul:*`, `_e32`/`_dpp` output modifiers) still raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_CVT_NORM_I16_F16`, `V_CVT_NORM_U16_F16`). **Hardware-verified on RDNA2** (AMD Radeon RDNA2 iGPU `gfx1036`, Windows 11, driver `32.0.21043.5001`, wave32 and wave64 via `tools/hw_oracle`, @Pierre-Kookis): 655,360 / 655,360 exact words across all 65,536 f16 inputs in five forms (`_e32`, `_e32 ieee=1`, `_e64 -v1`, `_e64 \|v1\|`, `_sdwa WORD_1`), including NaN → 0, ±inf clamps, denormals, single-rounding ties near ±0.5, and the untouched destination half; **output modifiers additionally verified natively on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 and wave64 via `tools/cvt_norm_mods_probe.py --hw-arch gfx1036`): exhaustive 65,536/65,536 f16 sweeps across VOP3 `plain`, `clamp`, `mul:2`, `mul:4`, `div:2`, `clamp mul:2`, `clamp div:2`, plus `MODE.FP_ROUND=RTZ` (`0xCC`), `IEEE=1` (`0x2C0`), `_e64` high-half preservation, and `_sdwa clamp` (`WORD_0`/`WORD_1`, `UNUSED_PRESERVE`/`UNUSED_SEXT`/`UNUSED_PAD`) all match with 0 mismatches and 0 wave diffs (`1,050,708` total word evaluations across the four probe ops). **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 20 `v_cvt_norm_*` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py` and `tests/semantic/test_cvt_norm_mods.py`; not run on the shader corpus. | 454| `v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16` | Normalized f16-to-16-bit integer conversions: `round_even(clamp(S0, -1, 1) * 32767)` (`i16`, snorm16) and `round_even(clamp(S0, 0, 1) * 65535)` (`u16`, unorm16), with NaN giving `0`, source `neg`/`abs` and SDWA `WORD_1` supported, and the unwritten half of the destination preserved (matching `v_cvt_i16_f16`/`v_cvt_u16_f16`; GFX10/LLVM does not accept VOP3 `op_sel` on these opcodes). For `\|cl\| >= 0.25`, `cl * (scale + 1)` is an exact even integer in f32, so `cl * (scale + 1) - RoundEven(cl)` rounds the exact product once without binary32 double-rounding ties near `±0.5`. `clamp` and output multipliers (`mul:*`/`div:*`) are rejected as `Unsupported`. VOP3 `clamp`, `mul:2`, `mul:4`, `div:2` (and combinations) and SDWA `clamp` are hardware no-ops on these integer-destination conversions and are accepted without changing output semantics; unsupported modifiers or invalid form/modifier pairs (e.g., `mul:8`, `_sdwa mul:*`, `_e32`/`_dpp` output modifiers) still raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_CVT_NORM_I16_F16`, `V_CVT_NORM_U16_F16`). **Hardware-verified on RDNA2** (AMD Radeon RDNA2 iGPU `gfx1036`, Windows 11, driver `32.0.21043.5001`, wave32 and wave64 via `tools/hw_oracle`, @Pierre-Kookis): 655,360 / 655,360 exact words across all 65,536 f16 inputs in five forms (`_e32`, `_e32 ieee=1`, `_e64 -v1`, `_e64 \|v1\|`, `_sdwa WORD_1`), including NaN → 0, ±inf clamps, denormals, single-rounding ties near ±0.5, and the untouched destination half; Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py`. **Hardware-verified on RDNA2** (AMD Radeon gfx1036, wave32 and wave64, `tools/int_hw_probe.py --oracle both --group valu_cvt_norm_f16`): the same 34 inputs through both ops with the unwritten half kept and with `neg`/`abs`, bit-identical to the translator; the RDNA2 assembler takes no `op_sel` on these two opcodes, so only the VOP3P-style `pknorm` forms have an `op_sel` check. Not run on the shader corpus. **output modifiers additionally verified natively on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 and wave64 via `tools/cvt_norm_mods_probe.py --hw-arch gfx1036`): exhaustive 65,536/65,536 f16 sweeps across VOP3 `plain`, `clamp`, `mul:2`, `mul:4`, `div:2`, `clamp mul:2`, `clamp div:2`, plus `MODE.FP_ROUND=RTZ` (`0xCC`), `IEEE=1` (`0x2C0`), `_e64` high-half preservation, and `_sdwa clamp` (`WORD_0`/`WORD_1`, `UNUSED_PRESERVE`/`UNUSED_SEXT`/`UNUSED_PAD`) all match with 0 mismatches and 0 wave diffs (`1,050,708` total word evaluations across the four probe ops). **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 20 `v_cvt_norm_*` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py` and `tests/semantic/test_cvt_norm_mods.py`; not run on the shader corpus. |
420| `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Measured natively** on an RDNA2 iGPU (gfx1036, `tools/hw_oracle`): under the MODE inferred for the game (IEEE 0, f32 denormals flushed) the hardware gives the translator's word for all 30 special inputs of each frexp op and 741 ldexp cases (denormal inputs, results in and below the denormal range, every exponent clamp edge, NaN payloads). With f32 denormals kept the hardware normalizes denormal inputs and returns denormal ldexp results, and with IEEE 1 it quiets signalling NaNs; neither is modelled, since the game runs with both off. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. | 455| `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Measured natively** on an RDNA2 iGPU (gfx1036, `tools/hw_oracle`): under the MODE inferred for the game (IEEE 0, f32 denormals flushed) the hardware gives the translator's word for all 30 special inputs of each frexp op and 741 ldexp cases (denormal inputs, results in and below the denormal range, every exponent clamp edge, NaN payloads). With f32 denormals kept the hardware normalizes denormal inputs and returns denormal ldexp results, and with IEEE 1 it quiets signalling NaNs; neither is modelled, since the game runs with both off. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. |
421| `v_mad_u16`, `v_mad_i16` | `D = S0 * S1 + S2` on the low 16-bit halves (VOP3 only). The product and sum are formed in 32 bits, so nothing overflows, and the low 16 bits are the result. `op_sel` bits 0..2 read the high half of a source and bit 3 writes the high half of the destination; like the other opsel-capable 16-bit VOP3 ops the other half of the destination is kept (see *16-bit results*). `clamp` saturates the full-width result to [0, 65535] (`v_mad_u16`) or [-32768, 32767] (`v_mad_i16`). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode and Mesa ACO's `can_use_opsel`. Checked on the CPU by `tests/semantic/test_alu_mad_u16_i16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): full-width `clamp`, `op_sel` and the untouched destination half match bit-for-bit. Not run on the shader corpus. | 456| `v_mad_u16`, `v_mad_i16` | `D = S0 * S1 + S2` on the low 16-bit halves (VOP3 only). The product and sum are formed in 32 bits, so nothing overflows, and the low 16 bits are the result. `op_sel` bits 0..2 read the high half of a source and bit 3 writes the high half of the destination; like the other opsel-capable 16-bit VOP3 ops the other half of the destination is kept (see *16-bit results*). `clamp` saturates the full-width result to [0, 65535] (`v_mad_u16`) or [-32768, 32767] (`v_mad_i16`). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode and Mesa ACO's `can_use_opsel`. Checked on the CPU by `tests/semantic/test_alu_mad_u16_i16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): full-width `clamp`, `op_sel` and the untouched destination half match bit-for-bit. Not run on the shader corpus. |
422| `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | The binary16 versions of `v_frexp_mant_f32`, `v_frexp_exp_i32_f32` and `v_ldexp_f32`, computed on the f16 word of the low half with no float arithmetic (`op_sel` picks the high half of a source; the last `op_sel` bit sends the result to the high half of the destination; the other half of the destination is kept). A normal input has a biased exponent of 1..30. `v_frexp_mant_f16` returns the input with its exponent set to 14 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i16_f16` returns the biased exponent minus 14 as a 16-bit integer, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. Zero gives a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. f16 denormals are kept, as in the MODE inferred for the game (`denorm_mode_16_64` = 3): a denormal input is normalized (`v_frexp_mant_f16(0x0001)` = 0.5 with exponent -23, `0x03ff` gives `0x3bfe` and -14). `v_ldexp_f16` is S0 × 2^S1 with S1 the low 16 bits of the source read as a signed integer: S1 is clamped to [-64, 64] and added to the exponent field; a new field above 30 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. S1 is clamped to [-64, 64]; a result above the f16 range gives ±infinity, and one below the smallest normal is a denormal rounded to nearest even (1.0 × 2^-15 = `0x0200`, 1.5 × 2^-24 = `0x0002`, 1.0 × 2^-25 = 0, 65504 × 2^-30 rounds up to `0x0400`); zero, infinities and NaNs ignore S1. Source neg/abs apply to the float operand. `clamp` and the output multipliers are rejected as unsupported rather than guessed. VOP3 `clamp` clamps the FP16 result of `v_frexp_mant_f16` and `v_ldexp_f16` to [0.0, 1.0] (negative values and NaNs clamp to +0.0, values > 1.0 and +Inf clamp to 1.0, [0.0, 1.0] kept; hardware-verified on gfx1036 with 302 kernels across wave32 and wave64). Output multipliers and clamp on `v_frexp_exp_i16_f16` raise `Unsupported`. Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling, the NaN payload, and whether `v_frexp_exp_i16_f16` keeps the high half of its destination (it is modelled like the other 16-bit ops here, which keep it) are the translator's choice. **Measured natively** on an RDNA2 iGPU (gfx1036, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`) under IEEE 0, DX10_CLAMP 1, f32 denormals flushed and f16 denormals kept: the translated rule gives the hardware's word for every one of the 65,536 f16 inputs of both frexp ops and of `v_ldexp_f16` under 16 exponents (1,048,576 cases), and the high half of the destination is kept by all three. Until 2026-11-22 the translator read f16 denormals as zero and flushed denormal ldexp results, which the hardware does only with `denorm_mode_16_64` = 0. Not modelled (the game runs with IEEE 0): with IEEE 1 a signalling NaN is quieted (`0x7c01` gives `0x7e01`). Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp_f16.py`, which holds measured words (including VOP3 clamp); not run on the shader corpus. | 457| `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | The binary16 versions of `v_frexp_mant_f32`, `v_frexp_exp_i32_f32` and `v_ldexp_f32`, computed on the f16 word of the low half with no float arithmetic (`op_sel` picks the high half of a source; the last `op_sel` bit sends the result to the high half of the destination; the other half of the destination is kept). A normal input has a biased exponent of 1..30. `v_frexp_mant_f16` returns the input with its exponent set to 14 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i16_f16` returns the biased exponent minus 14 as a 16-bit integer, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. Zero gives a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. f16 denormals are kept, as in the MODE inferred for the game (`denorm_mode_16_64` = 3): a denormal input is normalized (`v_frexp_mant_f16(0x0001)` = 0.5 with exponent -23, `0x03ff` gives `0x3bfe` and -14). `v_ldexp_f16` is S0 × 2^S1 with S1 the low 16 bits of the source read as a signed integer: S1 is clamped to [-64, 64] and added to the exponent field; a new field above 30 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. S1 is clamped to [-64, 64]; a result above the f16 range gives ±infinity, and one below the smallest normal is a denormal rounded to nearest even (1.0 × 2^-15 = `0x0200`, 1.5 × 2^-24 = `0x0002`, 1.0 × 2^-25 = 0, 65504 × 2^-30 rounds up to `0x0400`); zero, infinities and NaNs ignore S1. Source neg/abs apply to the float operand. Under the game's console MODE (`0x1c0`: `IEEE=0`, `DX10_CLAMP=1`, `denorm_mode_16_64=3`) and under `IEEE=1` (`0x3c0`), VOP3 `mul:2`, `mul:4`, and `div:2` are hardware no-ops on `v_frexp_mant_f16` and `v_ldexp_f16` (since `denorm_mode_16_64=3` disables `omod` on f16 results), while `clamp` clamps to [0.0, 1.0] (negative values and NaNs clamp to +0.0, values > 1.0 and +Inf clamp to 1.0, [0.0, 1.0] kept) both alone and combined with `mul:*`/`div:*`; on `v_frexp_exp_i16_f16` (16-bit integer result), `clamp` and `mul:2`/`mul:4`/`div:2` are all hardware no-ops under every MODE (`0x1c0`, `0x100`, `0x3c0`). Under the `denorm_mode_16_64=0, IEEE=0` (`0x100`) control, `mul:2`/`mul:4`/`div:2` scale `v_frexp_mant_f16` and `v_ldexp_f16` (not modelled because the game runs with `denorm_mode_16_64=3`). Unknown or unmodelled modifiers raise `Unsupported`. Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling, the NaN payload, and whether `v_frexp_exp_i16_f16` keeps the high half of its destination (it is modelled like the other 16-bit ops here, which keep it) are the translator's choice. **Measured natively** on an RDNA2 iGPU (gfx1036, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`) under IEEE 0, DX10_CLAMP 1, f32 denormals flushed and f16 denormals kept: the translated rule gives the hardware's word for every one of the 65,536 f16 inputs of both frexp ops and of `v_ldexp_f16` under 16 exponents (1,048,576 cases), and the high half of the destination is kept by all three. Until 2026-11-22 the translator read f16 denormals as zero and flushed denormal ldexp results, which the hardware does only with `denorm_mode_16_64` = 0. Not modelled (the game runs with IEEE 0): with IEEE 1 a signalling NaN is quieted (`0x7c01` gives `0x7e01`). VOP3 output modifiers (`clamp`, `mul:2`, `mul:4`, `div:2`, `clamp` + `mul:*`/`div:*`, and source `abs`/`neg`) were additionally measured natively on an RDNA2 iGPU (`AMD Radeon(TM) Graphics`, `gfx1036`, Windows driver `32.0.21045.29003`, wave32 & wave64 via `tools/frexp_ldexp_f16_mods_probe.py`): 3,466 / 3,466 exact words (3,360 console-MODE grid words, 22 source-modifier words, and 84 `0x100`/`0x3c0` control words, 0 wave diffs, 0 omod diffs). Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_ldexp_f16.py`, `tests/semantic/test_frexp_ldexp_f16_mods.py`, and `tests/test_frexp_ldexp_f16_mods_probe.py`; not run on the shader corpus. |
423| `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` | Binary64 versions of `v_frexp_mant_f32` and `v_frexp_exp_i32_f32`, computed bit-exactly on the `(lo, hi)` dword pair without requiring `OpCapability Float64` or `Int64` unless VOP3 output modifiers are used. A normal input has biased exponent `1..2046` (bits `[62:52]`): `v_frexp_mant_f64` sets the biased exponent to `1022` (`0x3FE00000`, mantissa in `[0.5, 1)` with sign and low mantissa bits kept), and `v_frexp_exp_i32_f64` returns `e - 1022` as a 32-bit signed integer so `mantissa × 2^exponent == input`. Under the default f16/f64 denormal mode (`denorm_mode_16_64` = 3, matching `v_frexp_mant_f16`/`v_frexp_exp_i16_f16`), non-zero subnormals (`e == 0`, 52-bit fraction `≠ 0`) are normalized into `[0.5, 1)` with sign preserved and exponent `msb − 1073` (`-1073..-1022`; e.g. `0x0000000000000001` → `0x3FE0000000000000` / `-1073`, `0x000FFFFFFFFFFFFF` → `0x3FEFFFFFFFFFFFFE` / `-1022`). Zero and denormals give signed zero and exponent `0`; infinities and NaNs pass through unchanged with exponent `0`. VOP3 source `abs`/`neg` flip/clear bit 31 of `hi`; VOP3 output modifiers (`mul:2`/`mul:4`/`div:2`, then `clamp`) apply to `v_frexp_mant_f64` via `clamp_mods_f64` (`OpCapability Float64`) and are rejected on `v_frexp_exp_i32_f64`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_FREXP_MANT_F64`, `V_FREXP_EXP_I32_F64`) and LLVM `VOP1Instructions.td`. **Measured natively** on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case): under `IEEE=0, denorm_mode_16_64=3, DX10_CLAMP=1` all 71 cases (all 52 single-bit subnormal positions `0..51`, lo/hi boundary-crossing multi-bit subnormals, negative subnormals, `±0`, normals, `±inf`, `qNaN`, `sNaN`, plus VOP3 `abs`/`neg`/`clamp`) matched bit-for-bit. Until 2026-11-22 the translator flushed binary64 subnormals to `±0` / exponent `0`, which the hardware does only under `denorm_mode_16_64=0`. Not modelled (the game runs with `IEEE=0, denorm_mode_16_64=3`): `IEEE=1` quieting signalling NaNs (`0x7FF0000000000001` → `0x7FF8000000000001`), `denorm_mode_16_64=0` flushing subnormals, and `denorm_mode_16_64=3` ignoring `omod`. **Not measured on hardware** (denormal input handling and NaN payload follow the f32 rule). Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_f64.py`; not run on the shader corpus. | 458| `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` | Binary64 versions of `v_frexp_mant_f32` and `v_frexp_exp_i32_f32`, computed bit-exactly on the `(lo, hi)` dword pair without requiring `OpCapability Float64` or `Int64` unless VOP3 output modifiers are used. A normal input has biased exponent `1..2046` (bits `[62:52]`): `v_frexp_mant_f64` sets the biased exponent to `1022` (`0x3FE00000`, mantissa in `[0.5, 1)` with sign and low mantissa bits kept), and `v_frexp_exp_i32_f64` returns `e - 1022` as a 32-bit signed integer so `mantissa × 2^exponent == input`. Under the default f16/f64 denormal mode (`denorm_mode_16_64` = 3, matching `v_frexp_mant_f16`/`v_frexp_exp_i16_f16`), non-zero subnormals (`e == 0`, 52-bit fraction `≠ 0`) are normalized into `[0.5, 1)` with sign preserved and exponent `msb − 1073` (`-1073..-1022`; e.g. `0x0000000000000001` → `0x3FE0000000000000` / `-1073`, `0x000FFFFFFFFFFFFF` → `0x3FEFFFFFFFFFFFFE` / `-1022`). Zero and denormals give signed zero and exponent `0`; infinities and NaNs pass through unchanged with exponent `0`. VOP3 source `abs`/`neg` flip/clear bit 31 of `hi`; VOP3 output modifiers are gated by the `MODE`, measured for this row by @fiestorra on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 7 mantissa inputs x 5 modifier forms x 5 MODEs, wave32 and wave64 identical): `clamp` applies to `v_frexp_mant_f64` in every MODE via `clamp_mods_f64` (`OpCapability Float64`), while `mul:2`/`mul:4`/`div:2` scale the mantissa only under `IEEE=0` with `denorm_mode_16_64=0` and are ignored under `IEEE=1` and under `denorm_mode_16_64=3`, the mode this row assumes, so only `clamp` needs `Float64` here. All output modifiers are rejected on `v_frexp_exp_i32_f64`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_FREXP_MANT_F64`, `V_FREXP_EXP_I32_F64`) and LLVM `VOP1Instructions.td`. **Measured natively** on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case): under `IEEE=0, denorm_mode_16_64=3, DX10_CLAMP=1` all 71 cases (all 52 single-bit subnormal positions `0..51`, lo/hi boundary-crossing multi-bit subnormals, negative subnormals, `±0`, normals, `±inf`, `qNaN`, `sNaN`, plus VOP3 `abs`/`neg`/`clamp`) matched bit-for-bit. Until 2026-11-22 the translator flushed binary64 subnormals to `±0` / exponent `0`, which the hardware does only under `denorm_mode_16_64=0`. Not modelled (the game runs with `IEEE=0, denorm_mode_16_64=3`): `IEEE=1` quieting signalling NaNs (`0x7FF0000000000001` → `0x7FF8000000000001`), `denorm_mode_16_64=0` flushing subnormals, and `denorm_mode_16_64=3` ignoring `omod`. **Not measured on hardware** beyond that gate: it was measured by @fiestorra with `tools/f64_omod_probe.py` (see the modifiers sentence above), while the pass-through of NaN payloads under `IEEE=0` is part of the 71 cases above and denormal-input handling follows the f32 rule. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_f64.py`; not run on the shader corpus. |
424| `v_min3_f16`, `v_max3_f16`, `v_min3_i16`, `v_min3_u16`, `v_max3_i16`, `v_max3_u16`, `v_med3_i16`, `v_med3_u16` | Three-operand 16-bit min/max/median (VOP3 only). `op_sel` bits 0..2 read the high half of S0..S2, bit 3 writes the high half of D, and the unwritten half of D is kept (see *16-bit results*). `v_min3_f16` and `v_max3_f16` read each selected f16 half through `Gen.f16_in` (`neg`/`abs` apply to the selected half), fold with `NMin`/`NMax` (so a NaN operand yields the other operand and −0 orders below +0, matching `v_min3_f32`/`v_max3_f32` and `v_med3_f16`), then apply VOP3 `omod`/`clamp` and `Gen.f16_out`. The 16-bit integer ops zero-extend (`u16`) or sign-extend (`i16`) the selected 16-bit halves, evaluate `UMin`/`UMax`/`UClamp` or `SMin`/`SMax`/`SClamp`, and write the low 16 bits into the selected half of D; `clamp` is supported on integer min3/max3/med3 as an identity no-op on the 16-bit container (hardware-verified on gfx1036 across wave32 and wave64); non-VGPR `op_sel` destinations raise `Unsupported`. `clamp` and non-VGPR `op_sel` destinations raise `Unsupported`. Until 2026-11-22 all eight raised `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) VOP3 opcodes `0x351`–`0x356`, `0x359`–`0x35A`, and Mesa ACO's `can_use_opsel`. **Hardware-verified on RDNA2** (gfx1036 iGPU, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`, IEEE 0 with f16 denormals kept): 6,092 cases (every triple of ±0, a denormal, 1.0, -1.0, 2.0, ±inf, a quiet and a signalling NaN for each f16 op; every triple of 8 edge values for the i16/u16 ops; `op_sel` on each source and the destination; a 0xabcd high half on every source) give the translator's word, the kept destination half included, except one: with all three operands NaN the hardware returns src0's NaN bits unchanged (`0x7c01` stays a signalling NaN under IEEE 0), the translator a quiet NaN, as for the 32-bit ops (*Float min/max/med3 with NaN*). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words, and `ALL_NAN_SRC0_SIGNALLING` there holds the 8 all-NaN min3/max3 rows with a signalling src0 (an `expectedFailure` until the translator keeps src0's bits). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words. **Not GPU-verified.** CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`. CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`; also **hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_min3_max3_med3_16`): all eight ops (`op_sel`, untouched destination half, NaN, −0/+0 ordering, and `v_max3_f16` `clamp`) match bit-for-bit. | 459| `v_ldexp_f64` | Binary64 load-exponent (`D.f64 = S0.f64 × 2^(S1.i32)`), lowered bit-exactly on the `(lo, hi)` dword pair using only 32-bit integer ops (no `OpCapability Float64` or `OpCapability Int64`, even with `clamp`). `±0`, `±inf`, and both quiet and signalling NaNs (under `IEEE = 0`) pass through bit-for-bit unchanged after `S0` `abs`/`neg`. Subnormal inputs (`denorm_mode_16_64 = 3`) are normalized via `FindUMsb` before adding `clamp(S1, -4096, 4096)` to the exponent field; overflow (`e2 >= 2047`) gives `±inf`, and subnormal outputs (`e2 <= 0`) shift the 53-bit significand right by `sh = 1 - e2` (`1..53`) and round to nearest even (carry into bit 52 yields `±min_norm`; `sh >= 54` flushes to `±0`). VOP3 `clamp` applies bit-exactly in integer ops (`DX10_CLAMP = 1`: `NaN`, `-0.0`, `<0` → `+0.0`; `>1.0` including `+inf` → `1.0`). VOP3 `omod` (`mul:2`/`mul:4`/`div:2`) is rejected as `Unsupported` because hardware ignores it under `denorm_mode_16_64 = 3` and applies it under `denorm_mode_16_64 = 0`. For immediate `S0` operands, inline integers `-16..64` sign-extend across 64 bits while 32-bit literals occupy `[63:32]` with `[31:0] = 0`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_LDEXP_F64`). **Measured natively** on an RDNA2 iGPU (`gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle` under game MODE `IEEE=0`, `DX10_CLAMP=1`, `denorm32=0`, `denorm16_64=3`): 870 / 870 cases bit-exact across all 52 subnormal input bit positions, all 54 subnormal right-shift boundaries and exact half-ULP ties, carry into `min_norm`, `±0`/`±inf`/qNaN/sNaN, `abs`/`neg`/`clamp`, immediate/literal `S0`, and seeded random inputs (not modelled: `IEEE=1` quiets signalling NaNs). Checked on the CPU and assembled by `tests/semantic/test_alu_ldexp_f64.py`; not run on the shader corpus. |
460| `v_min3_f16`, `v_max3_f16`, `v_min3_i16`, `v_min3_u16`, `v_max3_i16`, `v_max3_u16`, `v_med3_i16`, `v_med3_u16` | Three-operand 16-bit min/max/median (VOP3 only). `op_sel` bits 0..2 read the high half of S0..S2, bit 3 writes the high half of D, and the unwritten half of D is kept (see *16-bit results*). `v_min3_f16` and `v_max3_f16` read each selected f16 half through `Gen.f16_in` (`neg`/`abs` apply to the selected half), fold with `NMin`/`NMax` (so a NaN operand yields the other operand and −0 orders below +0, matching `v_min3_f32`/`v_max3_f32` and `v_med3_f16`), then apply VOP3 `omod`/`clamp` and `Gen.f16_out`. The 16-bit integer ops zero-extend (`u16`) or sign-extend (`i16`) the selected 16-bit halves, evaluate `UMin`/`UMax`/`UClamp` or `SMin`/`SMax`/`SClamp`, and write the low 16 bits into the selected half of D; `clamp` is supported on integer min3/max3/med3 as an identity no-op on the 16-bit container (hardware-verified on gfx1036 across wave32 and wave64); non-VGPR `op_sel` destinations raise `Unsupported`. `clamp` and non-VGPR `op_sel` destinations raise `Unsupported`. Until 2026-11-22 all eight raised `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) VOP3 opcodes `0x351`–`0x356`, `0x359`–`0x35A`, and Mesa ACO's `can_use_opsel`. **Hardware-verified on RDNA2** (gfx1036 iGPU, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`, IEEE 0 with f16 denormals kept): 6,092 cases (every triple of ±0, a denormal, 1.0, -1.0, 2.0, ±inf, a quiet and a signalling NaN for each f16 op; every triple of 8 edge values for the i16/u16 ops; `op_sel` on each source and the destination; a 0xabcd high half on every source) match the translator's word, including keeping the destination half and returning `src0`'s NaN bits unchanged (`0x7c01` stays signalling under IEEE 0) when all three operands are NaN (`ALL_NAN_SRC0_SIGNALLING` in `tests/semantic/test_alu_min3_max3_med3_16_hw.py`, alongside 540 sampled measured words). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words. **Not GPU-verified.** CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`. CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`; also **hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_min3_max3_med3_16`): all eight ops (`op_sel`, untouched destination half, NaN, −0/+0 ordering, and `v_max3_f16` `clamp`) match bit-for-bit. |
425| `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. `sat_i32(floor(S0))` and exact `sat_i32(floor(S0 + 0.5))` (computed via `f = Floor(x); (x - f >= 0.5) ? f + 1 : f`, with no binary32 rounding of `S0 + 0.5`: `0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`). Out-of-range values (±2³¹ and beyond, ±inf) and NaNs all saturate by the sign bit of the operand (`+NaN` → `0x7FFFFFFF`, `-NaN` → `0x80000000`, unlike `v_cvt_i32_f32` which returns `0` for NaN); the sign is read from `x` before `Floor` so driver NaN canonicalization cannot flip it. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. **Until 2026-11-22 the translator rounded `S0 + 0.5` in binary32 and returned `0` for NaN.** Hardware-verified natively on RDNA2 (AMD Radeon 680M `gfx1035`: 82/82 wave32 and 82/82 wave64 via `tools/hw_oracle`, plus `gfx1036` confirmation in #1746) and CPU-checked by `tests/semantic/test_alu_cvt_flr_rpi.py`. | 461| `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. `sat_i32(floor(S0))` and exact `sat_i32(floor(S0 + 0.5))` (computed via `f = Floor(x); (x - f >= 0.5) ? f + 1 : f`, with no binary32 rounding of `S0 + 0.5`: `0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`). Out-of-range values (±2³¹ and beyond, ±inf) and NaNs all saturate by the sign bit of the operand (`+NaN` → `0x7FFFFFFF`, `-NaN` → `0x80000000`, unlike `v_cvt_i32_f32` which returns `0` for NaN); the sign is read from `x` before `Floor` so driver NaN canonicalization cannot flip it. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. **Until 2026-11-22 the translator rounded `S0 + 0.5` in binary32 and returned `0` for NaN.** Hardware-verified natively on RDNA2 (AMD Radeon 680M `gfx1035`: 82/82 wave32 and 82/82 wave64 via `tools/hw_oracle`, plus `gfx1036` confirmation in #1746) and CPU-checked by `tests/semantic/test_alu_cvt_flr_rpi.py`. |
426| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does: **measured** on an RDNA2 iGPU (gfx1036, SHADER-339), 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept (`tools/pknorm_probe.py --oracle hw`). **The rounding differs:** the hardware rounds the exact product x · 32767 (or 65535) once, while the translator rounds the f32 `OpFMul` product and then `RoundEven`, so it is one off where the f32 product lands exactly on k + 0.5 (28 of 28 such near-tie inputs, both directions; `docs/shader_validation.md`, "`v_cvt_pknorm_*` NaN and rounding on RDNA2"). On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Not fixed here. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. VOP3 `clamp` is a hardware no-op on RDNA2 and is accepted without changing the result; other modifiers (`mul:*`/`div:*`, `op_sel:*`) raise `Unsupported`. `clamp` raises `Unsupported`. Until 2026-11-22 both ops were rejected. CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg). **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; additionally, `tools/cvt_norm_mods_probe.py --hw-arch gfx1036` verified `plain` vs VOP3 `clamp` across 40 edge/near-tie/NaN/±inf/subnormal pairs + 3 source-modifier cases across 6 `HW_REG_MODE` configurations and wave32/wave64 on `gfx1036` driver `32.0.21045.29003`: 2,064/2,064 words exact with 0 clamp diffs and 0 wave diffs). CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg, `clamp`), `tests/semantic/test_cvt_norm_mods.py`, and `tests/test_pknorm_probe.py`. **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 8 `v_cvt_pknorm_*` plain & `clamp` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. **Not checked through Vulkan on a GPU.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): ±qNaN → 0, ±inf saturation, and round-to-nearest-even ties at ±0.5 match bit-for-bit (the near-tie rounding above is a separate case). **Not GPU-verified.** | 462| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does: **measured** on an RDNA2 iGPU (gfx1036, SHADER-339), 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept (`tools/pknorm_probe.py --oracle hw`). **The rounding differs:** the hardware rounds the exact product x · 32767 (or 65535) once, while the translator rounds the f32 `OpFMul` product and then `RoundEven`, so it is one off where the f32 product lands exactly on k + 0.5 (28 of 28 such near-tie inputs, both directions; `docs/shader_validation.md`, "`v_cvt_pknorm_*` NaN and rounding on RDNA2"). On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Not fixed here. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. VOP3 `clamp` is a hardware no-op on RDNA2 and is accepted without changing the result; other modifiers (`mul:*`/`div:*`, `op_sel:*`) raise `Unsupported`. `clamp` raises `Unsupported`. Until 2026-11-22 both ops were rejected. CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg). **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; additionally, `tools/cvt_norm_mods_probe.py --hw-arch gfx1036` verified `plain` vs VOP3 `clamp` across 40 edge/near-tie/NaN/±inf/subnormal pairs + 3 source-modifier cases across 6 `HW_REG_MODE` configurations and wave32/wave64 on `gfx1036` driver `32.0.21045.29003`: 2,064/2,064 words exact with 0 clamp diffs and 0 wave diffs). CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg, `clamp`), `tests/semantic/test_cvt_norm_mods.py`, and `tests/test_pknorm_probe.py`. **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 8 `v_cvt_pknorm_*` plain & `clamp` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. **Not checked through Vulkan on a GPU.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): ±qNaN → 0, ±inf saturation, and round-to-nearest-even ties at ±0.5 match bit-for-bit (the near-tie rounding above is a separate case). **Not GPU-verified.** |
427| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). It depends on the driver: `ps_sdwa_f16_const` failed this way on `main` with NVIDIA 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99 (RTX 5090, Linux) and 580.173 (RTX 3060 Ti, Linux), and passed with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop) (#3220). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). | 463| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). It depends on the driver: `ps_sdwa_f16_const` failed this way on `main` with NVIDIA 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99 (RTX 5090, Linux) and 580.173 (RTX 3060 Ti, Linux), and passed with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop) (#3220). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). |
428| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` | VOP3 packed normalized conversion from two f16 sources (`D[15:0]` from `S0.f16`, `D[31:16]` from `S1.f16`): each selected f16 half (`op_sel[0..1]`, with `neg`/`abs` source modifiers and inline f16 constants via `Gen.f16_in`) is clamped to `[-1, 1]` (`i16`) or `[0, 1]` (`u16`), scaled by `32767` or `65535`, and rounded once to nearest even (`NaN → 0`). Uses `cl * (scale + 1) - RoundEven(cl)` for `\|cl\| >= 0.25` to avoid binary32 double-rounding at near-tie f16 inputs (e.g. `0x3801` = `0.5 + 2^-11`). Output modifiers (`clamp`, `mul:*`, `div:*`), `op_sel` destination bit, and VOP3P modifiers raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOP3 `v_cvt_pknorm_i16_f16` / `v_cvt_pknorm_u16_f16`) and LLVM AMDGPU `VOP3Instructions.td`. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py`; **not GPU-verified** and not run on the shader corpus. | 464| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` | VOP3 packed normalized conversion from two f16 sources (`D[15:0]` from `S0.f16`, `D[31:16]` from `S1.f16`): each selected f16 half (`op_sel[0..1]`, with `neg`/`abs` source modifiers and inline f16 constants via `Gen.f16_in`) is clamped to `[-1, 1]` (`i16`) or `[0, 1]` (`u16`), scaled by `32767` or `65535`, and rounded once to nearest even (`+inf → 32767`/`65535`, `-inf → -32767`/`0`, `NaN → 0`, `±0` and f16 denormals `→ 0`). Uses `cl * (scale + 1) - RoundEven(cl)` for `\|cl\| >= 0.25` to avoid binary32 double-rounding at near-tie f16 inputs (e.g. `0x3801` = `0.5 + 2^-11`). **Measured natively on RDNA2** (`AMD Radeon(TM) Graphics`, `gfx1036`, wave32 & wave64 via `tools/cvt_pknorm_f16_probe.py`): across all 65,536 binary16 inputs in `plain`, `clamp`, `op_sel:[0,0,1]`, and `op_sel:[0,0,1] clamp` (1,048,576 half evaluations) plus 33 targeted edge cases (264 words), VOP3 `clamp` is a **hardware no-op**, destination `op_sel[2] = 1` (`op_sel:[s0,s1,1]`) shifts the 32-bit packed result left by 16 bits (`D[31:16] = norm16(S0.f16)`, `D[15:0] = 0x0000`, overwriting prior `vdst` and dropping `S1`), and raw reserved VOP3 `omod` bits `[60:59]` (`1..3`) are ignored by silicon (rejected by `llvm-mc` on `gfx1036`). The translator accepts `clamp` (no-op) and `op_sel[2] = 1` (`OpShiftLeftLogical` by 16), while `mul:*`/`div:*`, VOP3P modifiers (`op_sel_hi:*`, `neg_lo:*`, `neg_hi:*`), `_dpp`/`_sdwa`, duplicate `op_sel:`, and malformed `op_sel` lists raise `Unsupported`. Output modifiers (`clamp`, `mul:*`, `div:*`), `op_sel` destination bit, and VOP3P modifiers raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOP3 `v_cvt_pknorm_i16_f16` / `v_cvt_pknorm_u16_f16`) and LLVM AMDGPU `VOP3Instructions.td`. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py` and `tests/semantic/test_cvt_pknorm_f16_mods.py`, by unit tests `tests/test_cvt_pknorm_f16_probe.py`, and through Vulkan (`vk_compute_test` with `VK_LAYER_KHRONOS_validation`, 116/116 exact words, 0 clamp diffs, 0 validation errors) on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`); not run on the shader corpus. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py`; **Hardware-verified on RDNA2** (AMD Radeon gfx1036, wave32 and wave64, `tools/int_hw_probe.py --oracle both --group valu_cvt_norm_f16`): 33 programs of four conversions each over +-0, +-1, 1 +- 1ulp, +-0.5 and the f16 neighbours of the 0.5 and 0.25 ties, an f16 denormal, +-65504, +-inf and quiet and signalling NaNs, with `op_sel:[1,0]`/`[0,1]` and `neg`/`abs`, all bit-identical to the translator. Not run on the shader corpus. **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 38 cases against the same exact-rational model, all matching: the halves pack in the documented order (`0.3333 \| 0.5+2^-11` and `1.5 \| -0.5` are asymmetric), each result is one round-to-nearest-even of the exact `cl * 32767` or `cl * 65535` (`0x3801` gives `32799` for `u16`), out-of-range values and infinities saturate the same way (`+inf` gives `32767`/`65535`, `-inf` gives `-32767`/`0`, so an infinity clamps to `±1`), and `NaN` (quiet or signalling), `-0` and a denormal f16 input all give `0`. Not measured: the `op_sel` destination bit and the `neg`/`abs` source modifiers, and not run on the shader corpus. |
429| `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions in `test_scalar_noop_waitcnt.py` check both modes in one shader. | 465| `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions check both modes in one shader (`test_round_mode_switches_half_precision_color_rounding` in `tests/semantic/test_scalar_noop_waitcnt.py`). |
430| f16 narrowing size | `Gen.f16_bits` leaves out or shares steps where that can't change the result. In nearest-even mode there is no separate infinity select: infinity is already at or above the overflow threshold (65520), which gives 0x7C00. For `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_pk_add_f16` without omod (`exact_tiny`), the range below 2^-14 is neither rounded nor tested for underflow: a sum of two f16 values is a multiple of 2^-24, so there it is already an f16 value, and clamp keeps that true. With an omod the rounding stays, since `div:2` can create a tie. No range has an underflow test: below 2^-25 the shift is 25, which moves the mantissa (plus the rounding bias) out to 0. The subnormal range rounds like the normal one, by adding half - 1 + the kept low bit before the shift. When the program writes MODE, `Gen.f16_res` makes one pass: toward zero selects a bias of 0, the 65536 overflow threshold and 0x7BFF, and keeps the infinity select. Confirmed by running the emitted integer sequences before and after on all 2^32 f32 inputs (both roundings) and on all 2^32 f16 operand pairs (both roundings, with and without clamp): no difference. Regression test: `tests/semantic/test_f16_sum_narrowing.py`. | 466| f16 narrowing size | `Gen.f16_bits` leaves out or shares steps where that can't change the result. In nearest-even mode there is no separate infinity select: infinity is already at or above the overflow threshold (65520), which gives 0x7C00. For `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_pk_add_f16` without omod (`exact_tiny`), the range below 2^-14 is neither rounded nor tested for underflow: a sum of two f16 values is a multiple of 2^-24, so there it is already an f16 value, and clamp keeps that true. With an omod the rounding stays, since `div:2` can create a tie. No range has an underflow test: below 2^-25 the shift is 25, which moves the mantissa (plus the rounding bias) out to 0. The subnormal range rounds like the normal one, by adding half - 1 + the kept low bit before the shift. When the program writes MODE, `Gen.f16_res` makes one pass: toward zero selects a bias of 0, the 65536 overflow threshold and 0x7BFF, and keeps the infinity select. Confirmed by running the emitted integer sequences before and after on all 2^32 f32 inputs (both roundings) and on all 2^32 f16 operand pairs (both roundings, with and without clamp): no difference. Regression test: `tests/semantic/test_f16_sum_narrowing.py`. |
431| `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | 467| `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. |
432| 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator narrows the f32 sum) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Still unverified:** what the SPI writes into LDS for a packed channel in a real draw (P10/P20 as f32 differences of the raw words, or per-half f16 differences under `FP16_INTERP_MODE`), which needs a pixel-shader harness; also f16 inf/NaN halves and `p1lv_f16`. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | 468| 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator narrows the f32 sum) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Still unverified:** what the SPI writes into LDS for a packed channel in a real draw (P10/P20 as f32 differences of the raw words, or per-half f16 differences under `FP16_INTERP_MODE`), which needs a pixel-shader harness; also f16 inf/NaN halves and `p1lv_f16`. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. |
433| 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 29 − 2N and high halves at 30 − 2N, below MoltenVK's 31 locations (124 components); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(29 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. **Unverified:** devices with fewer than 124 vertex output components. **Unverified:** devices with fewer than 31 output locations. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2· **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 124 vertex output components. Not combined with `--bary-fallback`'s geometry shader. \| F \| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Not combined with `--bary-fallback`'s geometry shader. | 469| 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Not combined with `--bary-fallback`'s geometry shader. |
434| `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | 470| `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. |
471| `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. |
435| `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. | 472| `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. |
436| 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Measured (TEST-650) with `tools/vcmp16_opsel_probe.py --oracle hw`, which writes `v_cmp_{lt,eq,gt}_{f16,u16,i16}_e64` as raw words with OPSEL set by hand in word 0 [12:11]: llvm-mc rejects `op_sel` on these compares and drops the bits when disassembling, so no listing carries it. On an RDNA2 iGPU (gfx1036), with the Windows HIP launcher (AMD 26.10.1) and independently with the Linux DRM launcher (#3329), all 50 rows read the low halves in wave32 and wave64, including the 20 where the selected halves would answer differently (f16 with and without `neg`, u16, sign-extended i16). The same hand-set bits on `v_add_nc_u16_e64` do select the high halves, so the encoding is right. The translator still honours `op_sel` here (from the ISA text and Mesa ACO `can_use_opsel`), which only a hand-encoded word can reach: #3487, which made it read the low halves as TEST-650 measured, was reverted because the constant, literal and SGPR-high-half checks below (row 403, measured natively) expect `op_sel` to select; the two measurements disagree and are open. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. **Measured natively on RDNA2** (gfx1036, AMD Ryzen 7000 iGPU, driver 26.11.2) across wave32 and wave64: `v_cmp` writes 0 for inactive lanes in `sdst` (`s4` in wave32, `s[4:5]` in wave64); `v_cmpx` kills inactive lanes in EXEC; inline float constants (`1.0`, `-2.0`, `0.5`, `4.0`) read f16 in low half with `op_sel=0` and +0.0 with `op_sel=1`; inline integer constants (`1`, `-1`) read low half with `op_sel=0` and high half with `op_sel=1` (`0` for `1`, `0xFFFF` for `-1`); 32-bit literals read `[15:0]` (`op_sel=0`) and `[31:16]` (`op_sel=1`, including signed negative high halves in `i16`); SGPR high halves as src0 and src1 with modifiers (`neg`, `abs`); and f16 ordered vs unordered relations on `qNaN`/`sNaN`. Probed natively with zero divergences by `tools/probe_gfx1036_vcmp16.py`, and checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations, spirv-val compliance, wave32/wave64 EXEC updates and inactive-lane 0 writes in `sdst`). Not measured: `v_cmpx`, `abs`, RDNA1. **not GPU-verified**. | 473| 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Measured (TEST-650) with `tools/vcmp16_opsel_probe.py --oracle hw`, which writes `v_cmp_{lt,eq,gt}_{f16,u16,i16}_e64` as raw words with OPSEL set by hand in word 0 [12:11]: llvm-mc rejects `op_sel` on these compares and drops the bits when disassembling, so no listing carries it. On an RDNA2 iGPU (gfx1036), with the Windows HIP launcher (AMD 26.10.1) and independently with the Linux DRM launcher (#3329), all 50 rows read the low halves in wave32 and wave64, including the 20 where the selected halves would answer differently (f16 with and without `neg`, u16, sign-extended i16). The same hand-set bits on `v_add_nc_u16_e64` do select the high halves, so the encoding is right. The translator still honours `op_sel` here (from the ISA text and Mesa ACO `can_use_opsel`), which only a hand-encoded word can reach: #3487, which made it read the low halves as TEST-650 measured, was reverted because the constant, literal and SGPR-high-half checks below (row 403, measured natively) expect `op_sel` to select; the two measurements disagree and are open. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. **Measured natively on RDNA2** (gfx1036, AMD Ryzen 7000 iGPU, driver 26.11.2) across wave32 and wave64: `v_cmp` writes 0 for inactive lanes in `sdst` (`s4` in wave32, `s[4:5]` in wave64); `v_cmpx` kills inactive lanes in EXEC; inline float constants (`1.0`, `-2.0`, `0.5`, `4.0`) read f16 in low half with `op_sel=0` and +0.0 with `op_sel=1`; inline integer constants (`1`, `-1`) read low half with `op_sel=0` and high half with `op_sel=1` (`0` for `1`, `0xFFFF` for `-1`); 32-bit literals read `[15:0]` (`op_sel=0`) and `[31:16]` (`op_sel=1`, including signed negative high halves in `i16`); SGPR high halves as src0 and src1 with modifiers (`neg`, `abs`); and f16 ordered vs unordered relations on `qNaN`/`sNaN`. Probed natively with zero divergences by `tools/probe_gfx1036_vcmp16.py`, and checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations, spirv-val compliance, wave32/wave64 EXEC updates and inactive-lane 0 writes in `sdst`). Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); Not measured: `v_cmpx`, `abs`, RDNA1. **not GPU-verified**. |
437| `v_cmp_class_f16`, `v_cmpx_class_f16`, `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 floating-point class tests against the 10-bit class mask (`0: sNaN, 1: qNaN, 2: -inf, 3: -normal, 4: -denormal, 5: -0, 6: +0, 7: +denormal, 8: +normal, 9: +inf`), writing VCC/SGPR or narrowing EXEC (`v_cmpx`). Computed bit-exactly on integer words (so `sNaN` is never quieted by float ops and `v_cmp(x)_class_f64` does not require `OpCapability Float64`): `f16` reads the selected half (`op_sel[0]`, inline f16 constants via `src_h`) and applies `abs`/`neg` on bits `[15:0]`; `f64` reads the `(lo, hi)` pair (32-bit literals placed in the upper word with `lo = 0` per RDNA2 ISA) and applies `abs`/`neg` on `hi`. Output modifiers (`clamp`, `mul:*`, `div:*`) and unsupported `op_sel` bits raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOPC `V_CMP_CLASS_F16/F64`, `V_CMPX_CLASS_F16/F64`). Checked bit-for-bit across all 10 classes on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cmp_class_f16_f64.py`; **not GPU-verified** and not run on the shader corpus. | 474| `v_cmp_class_f16`, `v_cmpx_class_f16`, `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 floating-point class tests against the 10-bit class mask (`0: sNaN, 1: qNaN, 2: -inf, 3: -normal, 4: -denormal, 5: -0, 6: +0, 7: +denormal, 8: +normal, 9: +inf`), writing VCC/SGPR or narrowing EXEC (`v_cmpx`). Computed bit-exactly on integer words (so `sNaN` is never quieted by float ops and `v_cmp(x)_class_f64` does not require `OpCapability Float64`): `f16` reads both the value operand (`op_sel[0]`) and the class mask operand via `src_h` (so float inline constants like `0.5`, `1.0`, `-2.0`, `0.15915494` take their 16-bit binary16 value over a zero high half before SDWA selection, matching `tools/sdwa_diff.py --oracle hw` on RDNA2 `gfx1036`; until 2026-11-23 `cmp_class` read the mask with `src_u`, turning inline float constants into 32-bit binary32 bits and failing `sdwa_diff --ops v_cmp_class_f16` 12/500) and applies `abs`/`neg` on bits `[15:0]`; `f16` reads the selected half (`op_sel[0]`, inline f16 constants via `src_h`) and applies `abs`/`neg` on bits `[15:0]`; `f64` reads the `(lo, hi)` pair (32-bit literals placed in the upper word with `lo = 0` per RDNA2 ISA) and applies `abs`/`neg` on `hi`. Output modifiers (`clamp`, `mul:*`, `div:*`) and unsupported `op_sel` bits raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOPC `V_CMP_CLASS_F16/F64`, `V_CMPX_CLASS_F16/F64`). Checked bit-for-bit across all 10 classes on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cmp_class_f16_f64.py`, and across 500 SDWA programs (`v_cmp_class_f16`, 0 mismatches) via `tools/sdwa_diff.py`; **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 85 cases, all matching the operand's own bits: the ten classes on ten `f16` words (`0x7c01` sNaN, `0x7e00` qNaN, `0xfc00` -inf, `0xbc00` -normal, `0x8001` -denormal, `0x8000` -0, `0x0000` +0, `0x0001` +denormal, `0x3c00` +normal, `0x7c00` +inf) and on ten `f64` pairs, each against its own class bit, all ten bits, no bits and the nine other bits (80), plus both `v_cmpx` forms on the launched lane (5). Not measured: `abs`/`neg`/`op_sel`, an inactive lane's `vdst`/`EXEC` under `v_cmpx`, wave64, and the shader corpus. |
438| Float-to-byte pack | `v_cvt_pk_u8_f32` rounds to nearest even (the default MODE round mode; the hardware follows the MODE register's f32 round mode, which the translator ignores, see #358), clamps to [0, 255], and gives 0 for NaN and negative values, then inserts the byte at `src1[1:0]` of `src2` and keeps the other three. NaN is replaced by +0 before `FClamp`, which is undefined for a NaN operand. **Measured natively** on RDNA2 (gfx1036, the Ryzen 7 9800X3D iGPU, AMD driver 25.10, the instruction run through inline assembly): all 256 inputs k + 0.5 round to even, 0.5 gives 0, 0x3f000001 gives 1, +inf and 300.0 give 255, -inf, -1.0, ±0, denormals and quiet, signalling and negative NaNs give 0 (#358). `cs_cvt_pk_u8.asm` holds eight of these words, checked by `check.py`/`run_gpu_tests.py` and bit-for-bit by `tests/semantic/test_cvt_pk_u8.py`. | 475| Float-to-byte pack | `v_cvt_pk_u8_f32` rounds to nearest even (the default MODE round mode; the hardware follows the MODE register's f32 round mode, which the translator ignores, see #358), clamps to [0, 255], and gives 0 for NaN and negative values, then inserts the byte at `src1[1:0]` of `src2` and keeps the other three. NaN is replaced by +0 before `FClamp`, which is undefined for a NaN operand. **Measured natively** on RDNA2 (gfx1036, the Ryzen 7 9800X3D iGPU, AMD driver 25.10, the instruction run through inline assembly): all 256 inputs k + 0.5 round to even, 0.5 gives 0, 0x3f000001 gives 1, +inf and 300.0 give 255, -inf, -1.0, ±0, denormals and quiet, signalling and negative NaNs give 0 (#358). `cs_cvt_pk_u8.asm` holds eight of these words, checked by `check.py`/`run_gpu_tests.py` and bit-for-bit by `tests/semantic/test_cvt_pk_u8.py`. |
439| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (see the f16 rounding row). `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); the translator does that in both modes through `Gen.fma_mix_odd`; the ALU ones follow a MODE toward-zero write (below; `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); toward zero the translator does that already, while in nearest-even mode it still narrows an f32 `Fma`, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036, finding 7079901079; an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| a x*y \| >= < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each, see the f16 transcendentals row; independently confirmed by an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, as `Gen.fma_mix_odd` produces (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"). In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). \| b \| `, `FastTwoSum`: `bb = r - a`, `e = b - bb`) and steps back one ulp when the rounding error shows it rounded away from zero; finite overflow gives the largest finite value (unordered `TwoSum` `r - x` can overflow to `±inf` and yield `NaN` error for opposite-sign finite operands with ` \| x \| < \| y \| ` near `±DBL_MAX`, e.g. `0x7fdd9bb47daa1333 + 0xffefffffffffffff` found by `@Jolymmiles`; GPU-checked with `runtime/test/shaders/ps_f64_round.asm` on NVIDIA GeForce RTX 5060 Ti, 4096/4096 pixels exact). The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| x*y \| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | 476| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (see the f16 rounding row). `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); the translator does that in both modes through `Gen.fma_mix_odd`; the ALU ones follow a MODE toward-zero write (below; `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); toward zero the translator does that already, while in nearest-even mode it still narrows an f32 `Fma`, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036, finding 7079901079; an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| a x*y \| >= < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each, see the f16 transcendentals row; independently confirmed by an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, as `Gen.fma_mix_odd` produces (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"). In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). \| b \| `, `FastTwoSum`: `bb = r - a`, `e = b - bb`) and steps back one ulp when the rounding error shows it rounded away from zero; finite overflow gives the largest finite value (unordered `TwoSum` `r - x` can overflow to `±inf` and yield `NaN` error for opposite-sign finite operands with ` \| x \| < \| y \| ` near `±DBL_MAX`, e.g. `0x7fdd9bb47daa1333 + 0xffefffffffffffff` found by `@Jolymmiles`; GPU-checked with `runtime/test/shaders/ps_f64_round.asm` on NVIDIA GeForce RTX 5060 Ti, 4096/4096 pixels exact). The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| x*y \| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). |
440| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits ` \| x \| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and (via `Gen.flush_f32_mods`) both before and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). **Measured natively on RDNA1** (`AMD Radeon RX 5600 XT`, `gfx1010`, Windows driver `32.0.21045.29003`, `tools/mad_denorm_probe.py --oracle hw`, SHADER-340): 48 of 48 cases match in wave32 and wave64 across `game` (`IEEE=0`, `denorm32=0`), `dx10_clamp=0` and `denorm32=3` (`v_mul_f32(FLT_MIN, 0.5)` confirms `denorm32=3` keeps subnormals on the GPU while the mad/mac ops still flush them), and all 40 non-`omod` cases match under `IEEE=1` (where hardware ignores `mul:2`/`mul:4`/`div:2` as for other f32 VALU ops). Before SHADER-340 the translator ran `flush_f32` only after `clamp_mods`, which gave `FLT_MIN` (`0x00800000`) instead of `+0` (`0x00000000`) on `(1.5*2^-126 - 2^-126) mul:2` (and `0x01000000` on `mul:4`), whereas hardware flushes the sum before `omod` (`+0`) as well as after (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, pre- and post-`omod` cases, NaN/inf/zero pass-through, and a sabotaged pass-through that fails) and `tests/test_mad_denorm_probe.py`. **not GPU-verified** — a native measurement still needs an RDNA1 part (gfx1010-gfx1013): no RDNA2 part has these opcodes, and on gfx103x the encodings of `v_mad_legacy_f32` (VOP3 0x140) and `v_mac_legacy_f32` (VOP2 0x06) are the fused `v_fma_legacy_f32` / `v_fmac_legacy_f32`, so a raw-encoding run on the gfx1036 oracle would measure a different instruction (see the GFX10.1/GFX10.3 opcode row). **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | 477| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits ` \| x \| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and (via `Gen.flush_f32_mods`) both before and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). **Measured natively on RDNA1** (`AMD Radeon RX 5600 XT`, `gfx1010`, Windows driver `32.0.21045.29003`, `tools/mad_denorm_probe.py --oracle hw`, SHADER-340): 48 of 48 cases match in wave32 and wave64 across `game` (`IEEE=0`, `denorm32=0`), `dx10_clamp=0` and `denorm32=3` (`v_mul_f32(FLT_MIN, 0.5)` confirms `denorm32=3` keeps subnormals on the GPU while the mad/mac ops still flush them), and all 40 non-`omod` cases match under `IEEE=1` (where hardware ignores `mul:2`/`mul:4`/`div:2` as for other f32 VALU ops). Before SHADER-340 the translator ran `flush_f32` only after `clamp_mods`, which gave `FLT_MIN` (`0x00800000`) instead of `+0` (`0x00000000`) on `(1.5*2^-126 - 2^-126) mul:2` (and `0x01000000` on `mul:4`), whereas hardware flushes the sum before `omod` (`+0`) as well as after (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, pre- and post-`omod` cases, NaN/inf/zero pass-through, and a sabotaged pass-through that fails) and `tests/test_mad_denorm_probe.py`. **not GPU-verified** — a native measurement still needs an RDNA1 part (gfx1010-gfx1013): no RDNA2 part has these opcodes, and on gfx103x the encodings of `v_mad_legacy_f32` (VOP3 0x140) and `v_mac_legacy_f32` (VOP2 0x06) are the fused `v_fma_legacy_f32` / `v_fmac_legacy_f32`, so a raw-encoding run on the gfx1036 oracle would measure a different instruction (see the GFX10.1/GFX10.3 opcode row). **not GPU-verified** — a native measurement still needs an RDNA1 part (gfx1010-gfx1013): no RDNA2 part has these opcodes, and on gfx103x the encodings of `v_mad_legacy_f32` (VOP3 0x140) and `v_mac_legacy_f32` (VOP2 0x06) are the fused `v_fma_legacy_f32` / `v_fmac_legacy_f32`, so a raw-encoding run on the gfx1036 oracle would measure a different instruction (see the GFX10.1/GFX10.3 opcode row). The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. |
441| 16-bit high-half reads (`Gen.u16_half` / `Gen.i16_half`, #1506) | Reading the high 16 bits of a 32-bit word emits `OpShiftRightLogical %uint u 16` (`u16_half`) or `OpShiftRightArithmetic %int (as_int(u)) 16` (`i16_half`) alone, without a trailing `OpBitwiseAnd ... 0xFFFF` or `OpBitFieldSExtract ... 0 16` (used for the low half only). On 32-bit inputs `>> 16` already zero- or sign-extends bits 31..16, and AMD's Windows LLPC compiler (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24 on Ryzen 5 7600 iGPU) miscompiles both `(u >> 16) & 0xFFFF` and `OpBitFieldSExtract (u >> 16) 0 16` after two partial-half writes to `u` by dropping the `>> 16` when the result feeds `OpIAdd`, `OpIMul`, or `OpShiftLeftLogical` (e.g. `(0x41b1 << 1) & 0xFFFF` became `0x0000` instead of `0x8362` in `cs_f16fuzz_s2_163_w64`, `s_bitreplicate`'s `((0x41b1 << 8) \| 0x41b1) & 0x00ff00ff` became `0xb10000` instead of `0x4100b1`, and `SExtract(0x91b1138b >> 16, 0, 16) + 1` became `0x91b10001` instead of `0xffff91b2`). Applies across all 16-bit half readers (`v_*_b16`/`u16`/`i16`, `v_mad_{u,i}16`, `v_min3/max3/med3_{u,i}16`, `v_cvt_f16_{u,i}16`, `v_pack_b32_f16`, `v_frexp_*_f16`, `v_ldexp_f16`, `s_bitreplicate_b64_b32`, and `buffer_store_format_d16_*`). Checked by `tests/test_u16_high_half.py` and `tools/valu_fuzz.py --family f16 --seed 2 --programs 200 --wave both` on AMD Ryzen 5 7600 iGPU (driver 24.10.24: 400/400 native, up from 399/400; 200/200 wave64 emulated on both AMD and NVIDIA). | 478| 16-bit high-half reads (`Gen.u16_half` / `Gen.i16_half`, #1506) | Reading the high 16 bits of a 32-bit word emits `OpShiftRightLogical %uint u 16` (`u16_half`) or `OpShiftRightArithmetic %int (as_int(u)) 16` (`i16_half`) alone, without a trailing `OpBitwiseAnd ... 0xFFFF` or `OpBitFieldSExtract ... 0 16` (used for the low half only). On 32-bit inputs `>> 16` already zero- or sign-extends bits 31..16, and AMD's Windows LLPC compiler (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24 on Ryzen 5 7600 iGPU) miscompiles both `(u >> 16) & 0xFFFF` and `OpBitFieldSExtract (u >> 16) 0 16` after two partial-half writes to `u` by dropping the `>> 16` when the result feeds `OpIAdd`, `OpIMul`, or `OpShiftLeftLogical` (e.g. `(0x41b1 << 1) & 0xFFFF` became `0x0000` instead of `0x8362` in `cs_f16fuzz_s2_163_w64`, `s_bitreplicate`'s `((0x41b1 << 8) \| 0x41b1) & 0x00ff00ff` became `0xb10000` instead of `0x4100b1`, and `SExtract(0x91b1138b >> 16, 0, 16) + 1` became `0x91b10001` instead of `0xffff91b2`). Applies across all 16-bit half readers (`v_*_b16`/`u16`/`i16`, `v_mad_{u,i}16`, `v_min3/max3/med3_{u,i}16`, `v_cvt_f16_{u,i}16`, `v_pack_b32_f16`, `v_frexp_*_f16`, `v_ldexp_f16`, `s_bitreplicate_b64_b32`, and `buffer_store_format_d16_*`). Checked by the unit tests in `tests/test_u16_high_half.py` and `tools/valu_fuzz.py --family f16 --seed 2 --programs 200 --wave both` on AMD Ryzen 5 7600 iGPU (driver 24.10.24: 400/400 native, up from 399/400; 200/200 wave64 emulated on both AMD and NVIDIA). **The packed 16-bit shifts follow the same rule** (`v_pk_lshlrev_b16`, `v_pk_lshrrev_b16`, `v_pk_ashrrev_i16`, since 2026-11-23): the shift amount comes from `OpShiftRightLogical %uint s0 16` then `& 15`, and the value from `OpShiftRight{Logical,Arithmetic} %uint s1 16`, where the code used `OpBitField{S,U}Extract … 16 16`. A field extract at offset 16 is what an AMD Windows driver 25.10.36 on a gfx1036 iGPU reads with the offset taken mod 16, so both result halves got the **low** half of the source: 5 of 2,000 `tools/valu_fuzz.py --family f16 --programs 2000 --seed 1 --wave 32` programs, all in wave32 and none in native wave64 (@Darkz0rz, reported in the coordination issue as SHADER-777). The same 2,000 programs match 2000/2000 on a second gfx1036 (Radeon iGPU of a Ryzen 7 7800X3D, driver 31.0.24002.92), where the field-extract form was already correct, and its SPIR-V does contain the offset-16 extracts, so the change is a lowering that survives both drivers, not a value change: `OpBitField{S,U}Extract(x, 16, 16)` equals `x >> 16` with the matching right shift and `OpBitFieldUExtract(x, 16, 4)` equals `(x >> 16) & 15`, checked for 200,010 inputs including 0, 1, 0xFFFF, 0x10000, 0x80000000, 0xFFFFFFFF, 0x7FFFFFFF and 0x8000. Counted over the 26,503 listings: 1 `v_pk_lshlrev_b16` in 1 compute listing (`op_sel_hi:[0,1]`) and 1 `v_pk_lshrrev_b16` in 1 other (`op_sel:[1,0] op_sel_hi:[0,0]`), no `v_pk_ashrrev_i16` and no `_sdwa` form; those two modules are the only ones whose output changes. Values are checked by the unit tests in `tests/test_pk16_diff.py` and the `ps_ops4` / `ps_ops6` fixtures. |
442| `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | 479| `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. |
443| `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Measured on native gfx1100 (single thread, 116 cases): all 16 predicates return IEEE-754 results (`eq` on `NaN` is 0 while `neq`/`nlt`/`nge`/`ngt` are 1, `lg` is 0 for `NaN` with `o`/`u` splitting on it, `eq(+0.0, -0.0)` is 1, `inf` compares equal to itself) and `v_cmpx_*_f64` narrows `EXEC` instead of writing `VCC`. | 480| `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Measured on native gfx1100 (single thread, 116 cases): all 16 predicates return IEEE-754 results (`eq` on `NaN` is 0 while `neq`/`nlt`/`nge`/`ngt` are 1, `lg` is 0 for `NaN` with `o`/`u` splitting on it, `eq(+0.0, -0.0)` is 1, `inf` compares equal to itself) and `v_cmpx_*_f64` narrows `EXEC` instead of writing `VCC`. |
444| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | 481| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. |
445| `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. A bitwise op or an exchange leaves the same memory done one dword at a time, so each dword is its own 32-bit `OpAtomic*` and no Int64 atomics are needed. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. Each dword is its own 32-bit `OpAtomic*`, so no Int64 atomics are needed; a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** | 482| `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. A bitwise op or an exchange leaves the same memory done one dword at a time, so each dword is its own 32-bit `OpAtomic*` and no Int64 atomics are needed. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. Each dword is its own 32-bit `OpAtomic*`, so no Int64 atomics are needed; a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** |
446| Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census <spirv>/index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. | 483| Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise; GPU-checked at required 64 and 32 lanes by `ps_w64_a_bpermute`, `ps_w64_a_permlane` (`v_permlane16` and `v_permlanex16`) and `ps_w64_a_swizzle` in `w64_graphics.py`, TEST-433), loops closed by `execnz` with no scalar state carried. `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. A `vccz`/`vccnz` on a wave-uniform compare is no lane vote and is tier A too: a `v_cmp` made while EXEC is the launch mask from untainted immediates, scalars that are no lane mask and VGPRs written from them (optionally ANDed with EXEC, the LLVM form `s_and_b64 vcc, exec, s[..]`) gives every launch lane or none, so each half votes as the wave does and both sides may have code and scalars of their own (if/else, a uniform loop back edge; the mask itself read as data, e.g. exported, is still tier C `cross-lane`), while the same compare under a narrowed EXEC (a half with no active lane votes no and keeps its own scalars) or on a tainted value (`v_readfirstlane` of a varying VGPR, a lane count, an AND with a lane mask) stays tier C; confirmed on the wave interpreter (`UniformVote` in `tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32, equal for the accepted forms with s4 = 9 and s4 = 1, different for each near miss) and by `ps_w64_a_uniform_vote`, which gives its derived words on an NVIDIA GeForce RTX 5080 (Linux, driver 580.65.06, 32 only). **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census <spirv>/index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c` with `--wave64-emulate`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (Earlier censuses counted 11,405 shaders, from when the wave size came from code markers: TEST-319 had A 1,919, B 17, C 9,469 with all 195 GS in C; its re-run with the GS ring rule below and #1982 had A 2,117, B 17, C 9,271 with all 195 GS in A.) The lane-id bpermute rule moves no corpus shader. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. **ADD_TID_ENABLE** (SHADER-833, finding by @shdann in #4571): an access with no `idxen` through a V# whose word3 is a literal (`s_mov_b32` earlier in the block, the notion `rdna2spirv` uses for `sgpr_imm`) with bit 23 set takes the wave lane as its index (`idxen` ignores the bit, see *Swizzled buffer addressing*), so its `buffer_load*`/`tbuffer_load*` result and its `buffer_store*`/`tbuffer_store*`/`buffer_atomic*` address carry the raw lane id: tier C `lane-id`. A literal with the bit clear, and every access with `idxen`, are unchanged. **Assumption**: through a run-time V# (loaded from memory or user data) tiers A and B take ADD_TID_ENABLE as 0 for an access without `idxen`; the code cannot say otherwise. The literal is tracked with the same folds `rdna2spirv` applies to `sgpr_imm` (mirrored in `Analysis.literal_sgpr`: `s_mov_b32/b64`, `s_movk_i32`, `s_pack_*`, `s_bfm_b32`, `s_not_b32`, `s_and/lshl/lshr_b32`, `s_mul_i32`; other folded ops count as run-time). The corpus census was not re-measured with this rule: its tier counts above are from before it and may change. Follow-up, needs the game: count the bound V#s with word3 bit 23 set at run time, and re-run `--census`. |
447| GFX10.1 (console gfx1013) / GFX10.3 (gfx1030, gfx1036 oracle) opcode differences | Found by disassembling every opcode of every GFX10 encoding (SOP1/SOP2/SOPK/SOPC/SOPP, SMEM, VOP1/VOP2/VOPC/VOP3/VOP3P, DS, FLAT/GLOBAL/SCRATCH, MUBUF/MTBUF, MIMG) with LLVM 21 `llvm-mc` for `-mcpu=gfx1013` and for `gfx1030`/`gfx1036` (the two gfx103x lists are identical). Every other opcode slot decodes to the same mnemonic on both, so the hardware-oracle rows measured on gfx1036 are about the same instructions the console runs (the microarchitectures still differ, which no opcode table shows). **On gfx1013 only:** `v_mac_f32`/`v_mad_f32` (VOP2 0x1f, VOP3 0x11f/0x141) and `v_mac_legacy_f32`/`v_mad_legacy_f32` (VOP2 0x06, VOP3 0x106/0x140), translated (rows above; not measurable on gfx103x, where 0x06/0x106/0x140 are the fused `v_fmac_legacy_f32`/`v_fma_legacy_f32`); `v_mul_lo_i32` (VOP3 0x16b; `Unsupported` until #3504 translates it); `s_get_waveid_in_workgroup` (SMEM 0x2a), translated in compute and mesh shaders; scalar stores (`s_store_dword*`, `s_buffer_store_dword*`), scalar atomics (`s_atomic_*`, `s_buffer_atomic_*`, 32- and 64-bit), scalar scratch (`s_scratch_load/store_dword*`), `s_dcache_wb`, `s_dcache_discard(_x2)` and the 31 LDS `ds_*_src2_*` forms, all `Unsupported`. **On gfx103x only:** `v_dot2c_f32_f16`, `v_dot4c_i32_i8`, the VOP3P `v_dot2_f32_f16`, `v_dot2_i32_i16`/`u32_u16`, `v_dot4_i32_i8`/`u32_u8`, `v_dot8_i32_i4`/`u32_u4`, `v_fmac_legacy_f32`/`v_fma_legacy_f32`, `global_load/store_dword_addtid`, `global_atomic_csub`, `buffer_atomic_csub`. The console's code can't contain these; the translator handles the integer dot products (rows above, measured on gfx1036) and refuses the rest, so a listing disassembled for the wrong target (VOP2 0x06 printed as `v_fmac_legacy_f32`) fails loudly instead of being translated as a fused multiply-add. Not covered by the sweep: opcodes whose operand template did not decode on either target, and behaviour that differs without an opcode change. | 484| GFX10.1 (console gfx1013) / GFX10.3 (gfx1030, gfx1036 oracle) opcode differences | Found by disassembling every opcode of every GFX10 encoding (SOP1/SOP2/SOPK/SOPC/SOPP, SMEM, VOP1/VOP2/VOPC/VOP3/VOP3P, DS, FLAT/GLOBAL/SCRATCH, MUBUF/MTBUF, MIMG) with LLVM 21 `llvm-mc` for `-mcpu=gfx1013` and for `gfx1030`/`gfx1036` (the two gfx103x lists are identical). Every other opcode slot decodes to the same mnemonic on both, so the hardware-oracle rows measured on gfx1036 are about the same instructions the console runs (the microarchitectures still differ, which no opcode table shows). **On gfx1013 only:** `v_mac_f32`/`v_mad_f32` (VOP2 0x1f, VOP3 0x11f/0x141) and `v_mac_legacy_f32`/`v_mad_legacy_f32` (VOP2 0x06, VOP3 0x106/0x140), translated (rows above; not measurable on gfx103x, where 0x06/0x106/0x140 are the fused `v_fmac_legacy_f32`/`v_fma_legacy_f32`); `v_mul_lo_i32` (VOP3 0x16b; `Unsupported` until #3504 translates it); `s_get_waveid_in_workgroup` (SMEM 0x2a), translated in compute and mesh shaders; scalar stores (`s_store_dword*`, `s_buffer_store_dword*`), scalar atomics (`s_atomic_*`, `s_buffer_atomic_*`, 32- and 64-bit), scalar scratch (`s_scratch_load/store_dword*`), `s_dcache_wb`, `s_dcache_discard(_x2)` and the 31 LDS `ds_*_src2_*` forms, all `Unsupported`. **On gfx103x only:** `v_dot2c_f32_f16`, `v_dot4c_i32_i8`, the VOP3P `v_dot2_f32_f16`, `v_dot2_i32_i16`/`u32_u16`, `v_dot4_i32_i8`/`u32_u8`, `v_dot8_i32_i4`/`u32_u4`, `v_fmac_legacy_f32`/`v_fma_legacy_f32`, `global_load/store_dword_addtid`, `global_atomic_csub`, `buffer_atomic_csub`. The console's code can't contain these; the translator handles the integer dot products (rows above, measured on gfx1036) and refuses the rest, so a listing disassembled for the wrong target (VOP2 0x06 printed as `v_fmac_legacy_f32`) fails loudly instead of being translated as a fused multiply-add. Not covered by the sweep: opcodes whose operand template did not decode on either target, and behaviour that differs without an opcode change. |
448| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **RDNA1 (gfx1011, Navi 12) follows the same RDNA2/GFX11 column**: `tools/buffer_bounds_probe.py` ran 12 one-lane 4-byte `buffer_load_dword` cases at wave32 and wave64 through `tools/hw_oracle` (24 groups, 0 wave32/64 differences); all matched the measured column and 8 disagreed with Mesa's GFX10 column (SHADER-341, results in `docs/buffer_bounds.md`). **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | 485| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **RDNA1 (gfx1011, Navi 12) follows the same RDNA2/GFX11 column**: `tools/buffer_bounds_probe.py` ran 12 one-lane 4-byte `buffer_load_dword` cases at wave32 and wave64 through `tools/hw_oracle` (24 groups, 0 wave32/64 differences); all matched the measured column and 8 disagreed with Mesa's GFX10 column (SHADER-341, results in `docs/buffer_bounds.md`). **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. |
486| 8/16-bit MUBUF d16 loads and stores | (The plain `buffer_load_{u,s}byte`/`{u,s}short` are `Gen.buffer_load_sub`'s; `tests/semantic/test_buffer_sub_dword.py` checks them too.) The `_d16` loads (`buffer_load_{u,s}byte_d16[_hi]`, `buffer_load_short_d16[_hi]`) write one 16-bit half of `vdata` (`_hi` the high one; a byte zero- or sign-extended to 16 bits) and keep the other. `buffer_store_byte`/`short` write the low 8/16 bits of `vdata` (the `_d16_hi` forms its high half). The address is `buffer_address`'s, and the bounds check covers the access's own size, 1 or 2 bytes, as for a typed element of that size (`elem="fmt"`, format 1 or 7). Out of range, a load gives 0 (in the half it writes, for d16; **not measured** for d16) and a store writes nothing. Each byte is its own access, so a 16-bit one that crosses a dword is exact; in a swizzled buffer the next dword is `step` bytes on. A store merges each byte into its dword with atomic and/or, as buffer byte format stores do. Inactive lanes neither load nor store, and the first-read analysis counts a d16 load's `vdata` as read. Until 2026-11-22 these ten raised `Unsupported`. CPU-checked by `tests/semantic/test_buffer_sub_dword.py` (every op at byte offsets 0 to 7, the edge of `num_records`, an inactive lane, rejected forms). GPU fixture `cs_w32_buffer_sub16` (the six d16 loads with their kept half and the sign extension, the two `_d16_hi` stores taking bits 23:16 / 31:16), passes on llvmpipe (Mesa 26.0.8) and on an NVIDIA RTX 5090 (595.99.02, @tylerstraub on #1864), all eight words; GPU fixture `cs_w32_buffer_store_sub` for the plain `buffer_store_byte`/`buffer_store_short` (Box16Rehydration's blocker, @YaBulochka on #1864), including a short at byte 3 that writes its high byte into the next dword, passes on llvmpipe with LLVM 21 and 23, and on an Apple M4 (MoltenVK 1.4.2) once the second dword of a 16-bit load is indexed from the first one's pointer instead of a second pointer converted from the same address, which Apple's compiler read as 0 (@sovljanskii on #1864). |
449| Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | 487| Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. |
488| `v_permlane16_b32` / `v_permlanex16_b32` with the source lane off in EXEC (SHADER-74) | The VOP3 modifier `op_sel:[FI, BOUND_CTRL]` decides what a lane gets when the lane it reads is off in EXEC. **FI=1** (`op_sel` bit 0, encoding 0x0800): the source lane's value, as before. **FI=0** (the default): the destination lane is not written and keeps its old value when BOUND_CTRL=0, and gets 0 when BOUND_CTRL=1 (`op_sel` bit 1, 0x1000). A source lane that is on gives its value whatever FI / BOUND_CTRL are, and a lane that is itself off is never written (normal EXEC rule). The translator shuffles the active bit with the same selector as the value (also in `--wave64-emulate`, where it is a second exchange). On a native subgroup the two shuffles are combined with bitwise masks, not a scalar select: absent source lanes are redirected to the calling lane first (as `ds_lane_read`), the value and the activity bit are fetched through the redirected index, and `ok` masks the shuffled value over the old one (over zero with BOUND_CTRL=1) and the destination write is masked too, so the ballot and both shuffles run before lane predication — MoltenVK 1.4.2 and MoltenVK main at SPIRV-Cross aa217aeb lowered the scalar select to a short-circuiting Metal ternary and the FI=0 lanes read the source lane's value instead, which `cs_w32_permlane_fi` caught on an Apple M1 Max (#5895); `v_permlanex16_b32` pairs the rows 0↔1 and 2↔3 of a wave64 as before. Until SHADER-74 every case returned the source value (right only for FI=1). Source of the bit mapping: LLVM `llvm.amdgcn.permlane16/permlanex16 <old> <src0> <src1> <src2> <fi> <bound_control>` (IntrinsicsAMDGPU.td) is selected in `VOP3Instructions.td` (`PermlanePat`) with `fi` as the `src0` op_sel bit and `bound_control` as the `src1` one, and the CodeGen tests `llvm.amdgcn.permlane.ll` print `op_sel:[1,0]` for FI and `op_sel:[0,1]` for BOUND_CTRL; `llvm-mc -mcpu=gfx1013` encodes `op_sel:[1,0]` as 0x0800 and `op_sel:[0,1]` as 0x1000 in the second byte pair of the first word (0xD777 / 0xD778). Behaviour: hardware measurement on RDNA2 (Ryzen 7950X3D iGPU, raw kernel, wave64 and wave32 consistent; the same on RDNA3.5) by aslan2142 in [#374](https://github.com/ItsNotRexed/Leonida/issues/374#issuecomment-7071597516). Pinned by `runtime/test/shaders/cs_w32_permlane_fi.asm` (EXEC 0x55555555, every active lane's source is off; out[0..7] = 1000 0 4 1 1000 0 52 49) in `check.py` and `scripts/run_gpu_tests.py`, and on the CPU by `tests/semantic/test_permlane_fi.py`. |
450| Null mask source | The scalar register `null` supplies zero when read as a lane mask. The wave64 fixture in `tests/semantic/fixtures/null_mask_source.asm` checks a high-bit test, a zero-bit count, a first-set-bit search and a masked vector write after `s_and_saveexec_b64`. LLVM 21.1.8 assembles each instruction for gfx1030. [LLVM GFX10 null operand](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#null) | 489| Null mask source | The scalar register `null` supplies zero when read as a lane mask. The wave64 fixture in `tests/semantic/fixtures/null_mask_source.asm` checks a high-bit test, a zero-bit count, a first-set-bit search and a masked vector write after `s_and_saveexec_b64`. LLVM 21.1.8 assembles each instruction for gfx1030. [LLVM GFX10 null operand](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#null) |
451| Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, `s_bfm_b64` bitfields, `_b64` copies of immediates into `vcc`, and `_b64` bitwise/select ops combining a lane mask or `vcc` destination with immediates; 32-bit mask + non-0/-1 immediate into an SGPR stays plain data, #1792). Split wave64 SGPR pairs whose two dwords hold separately written half-masks or a half-mask paired with a 0/-1 `EITHER` constant (`include_either=True`) are recognized by `holds_lane_mask` and read `s[r]` for lanes 0–31 and `s[r+1]` for lanes 32–63 in `mask_src`, and `--wave64-emulate`'s `x_mcache` keys `wave_mask` on every dword of an SGPR operand so rewriting `s[r+1]` invalidates a cached 64-bit exchange. `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, `s_bitcmp0/1_b32/b64`, and `v_mbcnt_lo/hi_u32_b32` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops (including `v_mbcnt_lo/hi_u32_b32` on `vcc_hi`/`vcc_lo`/`exec_lo` via `mask_half`) and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py`, `tests/semantic/test_scalar_alu_shifts.py`, `tests/semantic/test_loop_ballot_barrier.py`, and `tests/test_lane_masks.py` (split SGPR pairs, dual-dword `x_mcache`, `_b64` mask+imm, and `v_mbcnt` half selection CPU-checked, not yet GPU-verified). GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | 490| Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, `s_bfm_b64` bitfields, `_b64` copies of immediates into `vcc`, and `_b64` bitwise/select ops combining a lane mask or `vcc` destination with immediates; 32-bit mask + non-0/-1 immediate into an SGPR stays plain data, #1792). Split wave64 SGPR pairs whose two dwords hold separately written half-masks or a half-mask paired with a 0/-1 `EITHER` constant (`include_either=True`) are recognized by `holds_lane_mask` and read `s[r]` for lanes 0–31 and `s[r+1]` for lanes 32–63 in `mask_src`, and `--wave64-emulate`'s `x_mcache` keys `wave_mask` on every dword of an SGPR operand so rewriting `s[r+1]` invalidates a cached 64-bit exchange. `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, `s_bitcmp0/1_b32/b64`, and `v_mbcnt_lo/hi_u32_b32` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops (including `v_mbcnt_lo/hi_u32_b32` on `vcc_hi`/`vcc_lo`/`exec_lo` via `mask_half`) and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py`, `tests/semantic/test_scalar_alu_shifts.py`, `tests/semantic/test_loop_ballot_barrier.py`, and `tests/test_lane_masks.py` (split SGPR pairs, dual-dword `x_mcache`, `_b64` mask+imm, and `v_mbcnt` half selection CPU-checked, not yet GPU-verified). GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. |
452| 64-bit mask equality (SHADER-551) | `s_cmp_eq_u64` / `s_cmp_lg_u64` compare both exact 32-bit words and set a uniform SCC. Canonical full-wave masks (`exec`, mask-valued `vcc`, or a wave64 `MASK_LO`/`MASK_HI` SGPR pair) compared with another full mask or zero may use a whole-wave equality vote. Other SGPR pairs materialize each mask half separately and retain scalar data and constant words, including split, swapped, duplicated, mixed mask/data and wave32 pairs. Comparing with all ones also materializes words, so unlaunched lanes remain zero bits in partial waves. CPU-checked by `tests/semantic/test_scmp_u64_mask_pairs.py` with full and partial wave64, wave32, and wave64-emulation cases; independent synthetic Vulkan readback is reported in [PR #3007](https://github.com/ItsNotRexed/Leonida/pull/3007). No native RDNA2 instruction oracle was run for this rule. | 491| 64-bit mask equality (SHADER-551) | `s_cmp_eq_u64` / `s_cmp_lg_u64` compare both exact 32-bit words and set a uniform SCC. Canonical full-wave masks (`exec`, mask-valued `vcc`, or a wave64 `MASK_LO`/`MASK_HI` SGPR pair) compared with another full mask or zero may use a whole-wave equality vote. Other SGPR pairs materialize each mask half separately and retain scalar data and constant words, including split, swapped, duplicated, mixed mask/data and wave32 pairs. Comparing with all ones also materializes words, so unlaunched lanes remain zero bits in partial waves. CPU-checked by `tests/semantic/test_scmp_u64_mask_pairs.py` with full and partial wave64, wave32, and wave64-emulation cases; independent synthetic Vulkan readback is reported in [PR #3007](https://github.com/ItsNotRexed/Leonida/pull/3007). No native RDNA2 instruction oracle was run for this rule. |
453| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `\|...\|`, `-\|...\|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-\|1.0\|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `\|0x...\|` / `-\|0x...\|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). | 492| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `\|...\|`, `-\|...\|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-\|1.0\|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `\|0x...\|` / `-\|0x...\|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). |
454| `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 binary64 numeric class test against the 10-bit mask (`0` sNaN, `1` qNaN, `2` `-inf`, `3` `-normal`, `4` `-subnormal`, `5` `-0`, `6` `+0`, `7` `+subnormal`, `8` `+normal`, `9` `+inf`), lowered in `Gen.cmp_class_f64` using pure 32-bit `%uint` bit extraction on `(lo, hi)` with no `Float64` capability required. Supports VGPR/SGPR pairs, float inline constants (`fimm`), sign-extended inline integers (`-16..64`), 32-bit literals placed in bits `[63:32]` (as on RDNA2), and VOP3 `abs`/`neg` sign-bit modifiers on `src0` (`abs` clears bit 63, `neg` flips bit 63 without quieting sNaN). Inactive lanes produce 0 for `v_cmp_class_f64` and stay inactive for `v_cmpx_class_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 `V_CMP_CLASS_F64` / `V_CMPX_CLASS_F64`. CPU-checked by `tests/semantic/test_cmp_class_f64.py` (all 10 classes with low- and high-word payload bits, mask combinations and high-bit ignores, SGPR pairs, `fimm`/inline/literal constants, `abs`/`neg`/`-\|x\|`, `v_cmpx_class_f64` EXEC narrowing, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** | 493| `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 binary64 numeric class test against the 10-bit mask (`0` sNaN, `1` qNaN, `2` `-inf`, `3` `-normal`, `4` `-subnormal`, `5` `-0`, `6` `+0`, `7` `+subnormal`, `8` `+normal`, `9` `+inf`), lowered in `Gen.cmp_class_f64` using pure 32-bit `%uint` bit extraction on `(lo, hi)` with no `Float64` capability required. Supports VGPR/SGPR pairs, float inline constants (`fimm`), sign-extended inline integers (`-16..64`), 32-bit literals placed in bits `[63:32]` (as on RDNA2), and VOP3 `abs`/`neg` sign-bit modifiers on `src0` (`abs` clears bit 63, `neg` flips bit 63 without quieting sNaN). Inactive lanes produce 0 for `v_cmp_class_f64` and stay inactive for `v_cmpx_class_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 `V_CMP_CLASS_F64` / `V_CMPX_CLASS_F64`. CPU-checked by `tests/semantic/test_cmp_class_f64.py` (all 10 classes with low- and high-word payload bits, mask combinations and high-bit ignores, SGPR pairs, `fimm`/inline/literal constants, `abs`/`neg`/`-\|x\|`, `v_cmpx_class_f64` EXEC narrowing, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) through `tools/hw_oracle`: the ten classes as `f64` pairs (`0x7ff0000000000001` sNaN, `0x7ff8000000000000` qNaN, `0xfff0000000000000` -inf, `0xbff0000000000000` -normal, `0x8000000000000001` -denormal, `-0`, `+0`, `0x0000000000000001` +denormal, `0x3ff0000000000000` +normal, `0x7ff0000000000000` +inf) against their own bit, all ten bits, no bits and the nine other bits (40), and `v_cmpx_class_f64` on the launched lane true and false (2), all matching the same CPU model. Not measured: `abs`/`neg`, inactive lanes and wave64. **Not GPU-verified.** |
455| Mesh/compute input registers (historical measurement) | An early read-before-write analysis over all compute and mesh shaders found **compute** v0 (880), v0–v1 (614), v0–v2 (50), consistent with AMD's local thread ID x/y/z in v0/v1/v2, and scalar inputs centred on a pointer at s[4:5] and s6/s7. **Mesh:** every one of 2,969 reads exactly **v5**, plus s3 (always arithmetic), s[16:17] and s19–s23. The early pass also read FSSM 0x13C as the group width and compared the first SGPR multiply against it (82 match, 151 don't, 1,447 no simple multiply) and wrongly concluded that 0x13C was not the group width; the matching register varied by shader (s6/s10/s7/s9…). PSV0 gave the real thread-group sizes (32×1×1 for 1,253, 8×8×1 for 416, …). **Superseded:** 0x13C/0x140/0x144 are the thread-group size, `COMPUTE_PGM_RSRC2` at 0x138 gives the per-shader user-SGPR count and enabled workgroup IDs, and mesh takes NumThreads, limits and topology from PSV0 with `v5 = linearGroupIndex * NumThreads + LocalInvocationIndex`. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). | 494| Mesh/compute input registers (historical measurement) | An early read-before-write analysis over all compute and mesh shaders found **compute** v0 (880), v0–v1 (614), v0–v2 (50), consistent with AMD's local thread ID x/y/z in v0/v1/v2, and scalar inputs centred on a pointer at s[4:5] and s6/s7. **Mesh:** every one of 2,969 reads exactly **v5**, plus s3 (always arithmetic), s[16:17] and s19–s23. The early pass also read FSSM 0x13C as the group width and compared the first SGPR multiply against it (82 match, 151 don't, 1,447 no simple multiply) and wrongly concluded that 0x13C was not the group width; the matching register varied by shader (s6/s10/s7/s9…). PSV0 gave the real thread-group sizes (32×1×1 for 1,253, 8×8×1 for 416, …). **Superseded:** 0x13C/0x140/0x144 are the thread-group size, `COMPUTE_PGM_RSRC2` at 0x138 gives the per-shader user-SGPR count and enabled workgroup IDs, and mesh takes NumThreads, limits and topology from PSV0 with `v5 = linearGroupIndex * NumThreads + LocalInvocationIndex`. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). |
456| Formerly untranslated | Mesh (9,282), geometry (195) and compute (2,689) now translate; `s_swappc_b64` is replaced by Vulkan vertex inputs (see *Vertex fetch*) and the `tbuffer_load_format_*` forms use the instruction's format. Packed `tbuffer_load_format_d16_{x,xy,xyz,xyzw}` load two 16-bit components per VGPR, with the same final partial write as MUBUF. Native gfx1036 wave32/64 confirmed all four widths for RGBA8_UINT and RGBA8_UNORM with a conflicting 32_UINT V# format. Both packed and ordinary MTBUF loads ignore the V# channel selectors and use identity for the instruction format, zero-filling missing channels. Native gfx1036 measurements compared multiple V# permutations with MUBUF as a control. An INVALID V# format (0) suppresses the MTBUF fetch even at a valid address inside its bounds. Native gfx1036 wave32/64 returned zero components at all four widths and preserved the untouched half of an odd D16 destination, as specified for unbound resources in the [RDNA2 ISA, §8.1.4](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). A translated vertex fetch on RTX 5080 and Radeon Graphics also followed a change to the instruction format between two draws with identical vertex records and V#. Fixed UNORM and SNORM loads share the exact integer quotient for each magnitude width across instructions and channels (checked against rationally rounded binary32 values on RTX 5080 and Radeon Graphics). The gfx1013 disassembler omits `format:` for the [GFX10 MTBUF default](https://llvm.org/docs/AMDGPUModifierSyntax.html#ufmt), `BUF_FMT_8_UNORM` (code 1). A few rare ops are still reported by name rather than guessed. | 495| Formerly untranslated | Mesh (9,282), geometry (195) and compute (2,689) now translate; `s_swappc_b64` is replaced by Vulkan vertex inputs (see *Vertex fetch*) and the `tbuffer_load_format_*` forms use the instruction's format. Packed `tbuffer_load_format_d16_{x,xy,xyz,xyzw}` load two 16-bit components per VGPR, with the same final partial write as MUBUF. Native gfx1036 wave32/64 confirmed all four widths for RGBA8_UINT and RGBA8_UNORM with a conflicting 32_UINT V# format. Both packed and ordinary MTBUF loads ignore the V# channel selectors and use identity for the instruction format, zero-filling missing channels. Native gfx1036 measurements compared multiple V# permutations with MUBUF as a control. An INVALID V# format (0) suppresses the MTBUF fetch even at a valid address inside its bounds. Native gfx1036 wave32/64 returned zero components at all four widths and preserved the untouched half of an odd D16 destination, as specified for unbound resources in the [RDNA2 ISA, §8.1.4](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). A translated vertex fetch on RTX 5080 and Radeon Graphics also followed a change to the instruction format between two draws with identical vertex records and V#. Fixed UNORM and SNORM loads share the exact integer quotient for each magnitude width across instructions and channels (checked against rationally rounded binary32 values on RTX 5080 and Radeon Graphics). The gfx1013 disassembler omits `format:` for the [GFX10 MTBUF default](https://llvm.org/docs/AMDGPUModifierSyntax.html#ufmt), `BUF_FMT_8_UNORM` (code 1). A few rare ops are still reported by name rather than guessed. |
457| `v_cubema_f32` signed zero | Whenever the selected major axis is ±0.0, `v_cubema_f32` returns `+0.0` (`0x00000000`), never `-0.0` (`0x80000000`), while preserving NaNs and signed non-zero major-axis values (`2.0 * m`). Emitted as `OpFOrdEqual %bool m %f0` selecting `%f0` over `OpFMul m 2.0`, so `-0.0` maps to `+0.0`, NaN compares false and propagates, and non-zero finite/infinite values double with sign preserved. Until 2026-11-22 both `tools/rdna2spirv.py` and `tools/f32_fuzz.py` multiplied `m` by `2.0` directly and returned `-0.0` when `z = -0.0` on `(±0.0, ±0.0, -0.0)` (or when `-0.0` was selected alongside NaN axes). **Measured natively on RDNA2** (`gfx1036`, AMD Radeon(TM) Graphics, Windows driver `32.0.21042.62`, wave32 & wave64, all four MODE combinations `flush`/`keep`/`no_dx10`/`ieee` via `tools/hw_oracle/`): all 8 `(±0.0, ±0.0, ±0.0)` triples, `-v` source negation of `+0.0`, `mul:2`, negative denormals, and `(-0.0, qNaN, qNaN)` returned `0x00000000`, while `(-qNaN, 1.0, 1.0)` returned `0xffc00000` and `(-1.0, qNaN, qNaN)` returned `0xc0000000`. Checked by `tests/semantic/test_valu_cube.py` (`test_signed_zero_triples_and_nan_cubema`), `tests/test_f32_fuzz.py` (`test_cube_major_axis`), and `tools/f32_fuzz.py --oracle hw --ops v_cubema_f32,v_cubeid_f32,v_cubesc_f32,v_cubetc_f32`. | 496| `v_cubema_f32` signed zero | Whenever the selected major axis is ±0.0, `v_cubema_f32` returns `+0.0` (`0x00000000`), never `-0.0` (`0x80000000`), while preserving NaNs and signed non-zero major-axis values (`2.0 * m`). Emitted as `OpFOrdEqual %bool m %f0` selecting `%f0` over `OpFMul m 2.0`, so `-0.0` maps to `+0.0`, NaN compares false and propagates, and non-zero finite/infinite values double with sign preserved. Until 2026-11-22 both `tools/rdna2spirv.py` and `tools/f32_fuzz.py` multiplied `m` by `2.0` directly and returned `-0.0` when `z = -0.0` on `(±0.0, ±0.0, -0.0)` (or when `-0.0` was selected alongside NaN axes). **Measured natively on RDNA2** (`gfx1036`, AMD Radeon(TM) Graphics, Windows driver `32.0.21042.62`, wave32 & wave64, all four MODE combinations `flush`/`keep`/`no_dx10`/`ieee` via `tools/hw_oracle/`): all 8 `(±0.0, ±0.0, ±0.0)` triples, `-v` source negation of `+0.0`, `mul:2`, negative denormals, and `(-0.0, qNaN, qNaN)` returned `0x00000000`, while `(-qNaN, 1.0, 1.0)` returned `0xffc00000` and `(-1.0, qNaN, qNaN)` returned `0xc0000000`. Checked by `tests/semantic/test_valu_cube.py` (`test_signed_zero_triples_and_nan_cubema`), `tests/test_f32_fuzz.py` (`test_cube_major_axis`), and `tools/f32_fuzz.py --oracle hw --ops v_cubema_f32,v_cubeid_f32,v_cubesc_f32,v_cubetc_f32`. |
@@ -538,6 +577,25 @@ closing `s_endpgm`, then `s_code_end` padding. The data is not code, so the tool
538(`data_block_start`) and no longer reports those words as invalid. Over a 26,503-blob build, 1,473 blobs had such a 577(`data_block_start`) and no longer reports those words as invalid. Over a 26,503-blob build, 1,473 blobs had such a
539block (N from 0 up to several hundred); with the block excluded all 1,473 decode with no invalid word, and none of 578block (N from 0 up to several hundred); with the block excluded all 1,473 decode with no invalid word, and none of
540the other 25,030 blobs matches the pattern. 579the other 25,030 blobs matches the pattern.
580## PAL stage descriptors
581
582The FSSM header starts a table of 0x88-byte hardware-stage records at offset 0x100. A record's first qword is
583`0x000000C0_0002_AAHH`: `HH` (byte 0) is the PAL hardware stage and `AA` (byte 1) the API stage. Record k
584starts at `0x100 + 0x88*k`; the table ends at the first zero or non-tag qword. On the 26,503-blob corpus
58526,308 blobs carry one record and 195 (all GS) carry two, the second at 0x188 being the same shader's VS
586copy. API ids: 0 VS (2,236), 1 PS (12,101), 2 GS (195), 3 CS (2,689), 6 MS (9,282), each equal to the carve
587index's stage. Hardware ids: 2 ES (the first tag-0x0D payload of the 195 two-payload VS containers), 3 GS
588(195), 4 VS (2,431, the 195 GS copies included), 5 PS (12,101), 6 CS (2,689) and 7 (9,282, every mesh
589shader: the NGG/primitive path). Unused record fields are zero in 25,643 records; 1,055 records (860 blobs,
590the 195 GS pairs included) carry paired `0xDEADBEEFDEADBEEF` qwords, a lone 32-bit `0xDEADBEEF` never
591occurs, and those 860 are the blobs whose 0x120/0x12C/0x130 directory words are `0xDEADBEEF`. The hardware
592ids 0/1 and the API ids 4/5 are not in the corpus; the rest of a record is not decoded.
593`tools/pal_stages.py` prints the records of an FSSM or a container (every tag-0x0D payload);
594`tests/test_pal_stages.py` covers the layout with synthetic blobs.
595`scripts/vs_layout_census.py` checks these hardware ids against the code of every payload: every stage-7
596payload carries the NGG markers (`exp prim`, `s_sendmsg MSG_GS_ALLOC_REQ`, `v_mbcnt`), every stage-4 payload
597is a legacy non-NGG VS, and the stage-2 ES payloads have no `exp` (they write the vertex outputs to LDS for
598the geometry stage) — see *VS input layout, per PAL hardware stage* and *VS as ES* above.
541 599
542## Pixel-shader inputs 600## Pixel-shader inputs
543 601
diff --git a/docs/dev-tools.md b/docs/dev-tools.md
new file mode 100644
index 000000000..d36091ec3
--- /dev/null
+++ b/docs/dev-tools.md
@@ -0,0 +1,93 @@
1# Development tools
2
3From the Leonida checkout root, use Python 3 to list the development tools:
4
5```powershell
6python -I scripts/dev.py --help
7python -I scripts/dev.py discover
8python -I scripts/dev.py discover --json
9```
10
11From another directory, pass the path to `scripts/dev.py`, quoting it if needed.
12The inventory always describes the checkout containing that script.
13
14`boot-trace` points to the analyzer for startup JSONL and D3D12 stderr logs.
15`guest-scene` points to the headless synthetic guest runner. Run a listed help
16command from the checkout root to see the producer's options. The text
17inventory displays commands for PowerShell on Windows and POSIX shells
18on other platforms. The inventory
19checks for each producer script and lists its prerequisites without checking
20those prerequisites or running the producer. Live attach, pause, step, input,
21and screenshots are unavailable through this entry point.
22
23## JSON output
24
25`discover --json` writes one object to stdout:
26
27- `schema_version` identifies the format. The current version is `1`.
28- `tools` lists entries by `id`. Each `path` uses forward slashes and is
29 relative to the checkout root. `present` indicates whether the script is
30 a file. `help_argv` is a list of arguments for a command run from the checkout
31 root. Its first argument is the Python executable running discovery. It
32 is `null` when the script is missing. `requirements` lists prerequisites
33 for using the producer.
34- `live_controls` contains an `available` boolean and a `reason`.
35
36Exit code `0` indicates that the inventory was emitted, including when a
37producer script is missing. Invalid CLI arguments exit with code `2`.
38
39## Analyze a boot trace
40
41Use the existing analyzer through the development CLI:
42
43```powershell
44python -I scripts/dev.py boot-trace --help
45python -I scripts/dev.py boot-trace "logs/startup trace.jsonl"
46python -I scripts/dev.py boot-trace "logs/startup trace.jsonl" --d3d12 "logs/d3d12 stderr.log" --json
47```
48
49Pass a startup JSONL from `gta6rt --trace`, a D3D12 stderr log from
50`gta6rt --trace-d3d12`, or both. Relative input paths are interpreted from
51the directory where you run the CLI. From outside the checkout, give the
52path to `scripts/dev.py` and keep the trace paths relative to your directory.
53
54The analyzer supplies the help, output, diagnostics and exit status. If one
55input fails but the other can be read, `--json` can still emit a partial
56summary on stdout with a diagnostic on stderr and exit code `2`. If neither
57input can be analyzed, there is no JSON summary. The summary describes the
58recorded events, and the exit status reports the analysis result.
59
60You can also run `python -I tools/boot_trace.py` with the same arguments.
61
62## Run a synthetic guest scene
63
64Use the existing headless runner with a loader and guest built on Windows
65with Vulkan, static SDL3 and `LEONIDA_GUEST_SCENE=ON`. Supply the synthetic
66M1.5 shader fixture root containing `spirv/`. See the
67[runtime instructions](../runtime/README.md#a-600-frame-headless-guest-scene)
68for the build, fixture and Wine setup.
69
70```powershell
71python -I scripts/dev.py guest-scene --help
72python -I scripts/dev.py guest-scene --loader "build/gta6rt.exe" --guest "build/tiny_guest_draw.exe" --shaders "m15 shaders" --out "scene run" --negative-controls
73```
74
75Pass `--out PATH` or `--out=PATH` with a new or empty directory. Relative
76paths are interpreted from the directory where you run the CLI, including
77when you invoke `scripts/dev.py` by its full path from another directory.
78
79The CLI forwards the runner's exit code and diagnostics. Exit code `0`
80means the scene checks passed. Exit code `1` can indicate a scene check
81failure or a failure before the runner can write a report, such as an
82output directory it cannot create. Exit code `2` indicates a usage or
83prerequisite error.
84
85When the runner writes `report.json`, it prints the path. Open that file
86for the scene result and per-run details. For example, if the full run
87starts and the loader exits with an error, `runs.full.returncode` records
88the loader's exit code while the CLI returns the runner's exit code.
89The output directory also holds any logs, frame records and PPM images
90the runner produced. If the runner rejects an occupied directory, any
91report already there belongs to an earlier run.
92
93You can also invoke `python -I scripts/run_guest_scene.py` directly.
diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md
index 24f0b9971..ed3a254d7 100644
--- a/docs/embedded_shaders.md
+++ b/docs/embedded_shaders.md
@@ -7,8 +7,9 @@ hold counts, offsets, chunk names and module identifiers.
7 7
8## 1. Why they matter 8## 1. Why they matter
9 9
10`make_game.py`'s `shaders` stage carves `shaders.rpf` only (`make_game.py`:655). Two DLLs in the same package 10`tools/shader_carve.py` carves `shaders.rpf` only. Two DLLs in the same package carry compute programs of their
11carry compute programs of their own: 11own, and `make_game.py`'s `shaders` stage translates both sets after the game's shaders (section 7 for the
12builder, [fspx.md](fspx.md) for FidelityFX):
12 13
13* `XboxBvhBuilder.dll`, Microsoft's XDXR acceleration-structure builder. Its constructor creates compute PSOs 14* `XboxBvhBuilder.dll`, Microsoft's XDXR acceleration-structure builder. Its constructor creates compute PSOs
14 through device slot 62, and the builder is on the critical path for ray tracing. 15 through device slot 62, and the builder is on the critical path for ray tracing.
@@ -25,18 +26,34 @@ python -I tools/pe_shader_containers.py <dll> --json <work>/containers.json --ex
25 26
26## 2. Inventory 27## 2. Inventory
27 28
28The 16 DLLs and the package's root files were scanned. All the containers are in two DLLs: 29The 16 DLLs and the package's root files were scanned first (`XboxBvhBuilder.dll` and `amd_fidelityfx_upscaler_xbox.dll`); `game_scarlett_master.exe` (RT-5) adds 10 more console containers:
29 30
30| image | containers | bytes | min / median / max | chunks | 31| image | containers | bytes | min / median / max | chunks |
31|---|---:|---:|---:|---| 32|---|---:|---:|---:|---|
32| `XboxBvhBuilder.dll` | 52 | 674,404 | 4,072 / 7,454 / 74,508 | `SFI0 ISG1 OSG1 PSV0 RTS0 STAT ILDN HASH DXIL` | 33| `XboxBvhBuilder.dll` | 52 | 674,404 | 4,072 / 7,454 / 74,508 | `SFI0 ISG1 OSG1 PSV0 RTS0 STAT ILDN HASH DXIL` |
33| `amd_fidelityfx_upscaler_xbox.dll` | 29 | 289,656 | 1,764 / 5,176 / 42,616 | `SFI0 ISG1 OSG1 PSV0 RTS0 HASH ACCC` | 34| `amd_fidelityfx_upscaler_xbox.dll` | 29 | 289,656 | 1,764 / 5,176 / 42,616 | `SFI0 ISG1 OSG1 PSV0 RTS0 HASH ACCC` |
34| other 14 DLLs | 0 | 0 | — | — | 35| other 14 DLLs | 0 | 0 | — | — |
36| `game_scarlett_master.exe` | 10 | 9,520 | 924 / 936 / 992 | `SFI0 ISG1 OSG1 PSV0 HASH DXIL PRIV` |
35 37
36The 29 `ACCC` containers hold `FSPX` payloads ([fspx.md](fspx.md)); the 52 `DXIL` containers are the subject of 38The 29 `ACCC` containers hold `FSPX` payloads ([fspx.md](fspx.md)); the 52 `DXIL` containers are the subject of
37this note. The FSR DLL has one rejected `DXBC` hit: the bytes are an immediate in its own magic check, and the 39this note. The FSR DLL has one rejected `DXBC` hit: the bytes are an immediate in its own magic check, and the
38validator rejects it (the scan reports both counts). 40validator rejects it (the scan reports both counts).
39 41
42### Retail executable (`game_scarlett_master.exe`, RT-5)
43
44Scanning the retail executable (120,181,760 bytes, SHA-256 `e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993`)
45with `tools/pe_shader_containers.py` finds **10** valid DXBC containers (9,520 bytes total, file offsets
46`0x688cd3c`..`0x688fdf6`, sizes 924–992 bytes) and 1 rejected `DXBC` hit:
47
48* **Stages (`PSV0`):** **1** vertex shader (`0x688cd3c`, 992 bytes) and **9** pixel shaders (924–980 bytes). Unlike the
49 DLL containers above, none carries `ILDN`, `STAT`, `RTS0`, or LLVM bitcode (`has_bitcode = false`). All 10 carry
50 console-only `XBCH` (`XDAT` tag `0x0d`, 307–368 bytes) and `NOBC` (tag `0x07`, 28 bytes), plus a 12-byte `PRIV` chunk.
51* **Translation and GPU check:** `tools/pe_shader_containers.py --extract` previously hardcoded `"stage": "cs"` in
52 `index.json`, causing `rdna2spirv.py` to reject all 10 with `CS group size`. With `stage` read from `PSV0`, all 10
53 unpack via `tools/fssm_unpack.py` (10/10 `FSSM`, 1,245–4,176 bytes), disassemble cleanly via `tools/shader_disasm.py --backend python`
54 (10/10 clean), translate via `tools/rdna2spirv.py` (10/10 translated, all wave64 tier A), and pass `vk_pipeline_check`
55 on an NVIDIA GeForce RTX 5060 Laptop GPU (driver `617.14`, Windows 11): **10/10 modules and 10/10 pipelines OK** (1 VS, 9 PS, 0 failed, 0 skipped).
56
40**Every one of the 52 containers carries two representations of its program:** 57**Every one of the 52 containers carries two representations of its program:**
41 58
42* an LLVM bitcode blob in the `DXIL` chunk (`BC C0 DE`, 1,820 to 70,276 bytes), and 59* an LLVM bitcode blob in the `DXIL` chunk (`BC C0 DE`, 1,820 to 70,276 bytes), and
@@ -66,14 +83,20 @@ All spans fit inside their enclosing parts, and all 104 `STAT` and outer `DXIL`
66The bitcode is what a PC D3D12 compiler consumes; the runtime path is the `XBCH` record. The constructor passes 83The bitcode is what a PC D3D12 compiler consumes; the runtime path is the `XBCH` record. The constructor passes
67the **whole container** to the compute-PSO call: at `0x180021330` it loads `DAT_180025700` with size `0x1134` 84the **whole container** to the compute-PSO call: at `0x180021330` it loads `DAT_180025700` with size `0x1134`
68(4,404 bytes, the size of container 0, `CopyAndCompactBVH`) and calls `FUN_18000c470`, whose vtable call at 85(4,404 bytes, the size of container 0, `CopyAndCompactBVH`) and calls `FUN_18000c470`, whose vtable call at
69`+0x1f0` (slot 62) receives that pointer, its size and two zero words. `FUN_18001d400` adds two more PSOs, 86`+0x1f0` (slot 62) receives that pointer, its size and two zero words. `FUN_18001d400` creates the
70`XDXR PostBuildInfoQuery` (0x14a4 bytes) and `XDXR GetBVHCompactedSize`. `bvh_builder_test` measures **53** PSO 87`XDXR GetBVHCompactedSize` PSO (0x14a4 bytes; measured below). `bvh_builder_test` measures **53** PSO
71creations during construction over the **52** containers ([d3d12_vulkan.md](d3d12_vulkan.md) A.2), so one 88creations during construction over the **52** containers ([d3d12_vulkan.md](d3d12_vulkan.md) A.2), so one
72container is created twice. It is **`GetBVHCompactedSize`** (5,284 bytes = 0x14a4): creations **#47 and #53** pass 89container is created twice. It is **`GetBVHCompactedSize`** (5,284 bytes = 0x14a4): creations **#47 and #53** pass
73byte-identical containers (RT-182, `LEONIDA_BVH_RECORD62=1`, which now prints each creation's module from its `ILDN` 90byte-identical containers (RT-182, `LEONIDA_BVH_RECORD62=1`, which now prints each creation's module from its `ILDN`
74part and says when a container repeats). 0x14a4 is also the size this section gives for `XDXR PostBuildInfoQuery`, 91part and says when a container repeats). The test now also prints each creation's call site and the name the builder
75which fits `FUN_18001d400`'s two XDXR PSOs being this one container created twice, once under each name; the test 92gives the returned PSO (RT-266, WARP, default constructor flag): the builder names every one of the 53 PSOs with
76does not see the PSO names, so that last step is a hypothesis. The creation order, by module (it is not the table 93`SetName`, `XDXR <module>` (for example `XDXR InitPartitionedHeaders`; some modules are shortened, as
94`XDXR CopyAndCompact`, or numbered, as `XDXR CalculateMortonCodes 0`/`1`). **#47 and #53 both get `XDXR
95GetBVHCompactedSize`**, from the same call site in `FUN_18001d400` (return address `+0x1d503`, called through
96`FUN_18000c470` at `+0xc4e4`); `FUN_18001d400` is called twice, once from `FUN_18000d850` (#47) and once from
97`FUN_180021330` directly (#53). So the repeat is one PSO created twice under one name, not one container under two
98names, and no creation is named `XDXR PostBuildInfoQuery` in this run (default flag, WARP; the flag-true
99constructor was not run). The creation order, by module (it is not the table
77order of section 3; `CopyAndCompactBVH` is #52, not the first): 100order of section 3; `CopyAndCompactBVH` is #52, not the first):
78 101
79| creations | modules, in the order of the `CreateComputePipelineState` calls | 102| creations | modules, in the order of the `CreateComputePipelineState` calls |
@@ -82,12 +105,12 @@ order of section 3; `CopyAndCompactBVH` is #52, not the first):
82| #14-#29 | `BitonicPreSortCS`, `BitonicOuterSortCS`, `BitonicInnerSortCS`, `BitonicPreSort64CS`, `BitonicOuterSort64CS`, `BitonicInnerSort64CS`, `RadixReset`, `RadixCount`, `PrefixSum64`, `PrefixSum128`, `PrefixSum256`, `PrefixSum512`, `PrefixSum1024`, `PrefixSum2048`, `PrefixSum4096`, `RadixAlloc` | 105| #14-#29 | `BitonicPreSortCS`, `BitonicOuterSortCS`, `BitonicInnerSortCS`, `BitonicPreSort64CS`, `BitonicOuterSort64CS`, `BitonicInnerSort64CS`, `RadixReset`, `RadixCount`, `PrefixSum64`, `PrefixSum128`, `PrefixSum256`, `PrefixSum512`, `PrefixSum1024`, `PrefixSum2048`, `PrefixSum4096`, `RadixAlloc` |
83| #30-#46 | `RearrangeTriangles`, `RearrangeBVHs`, `LoadInstances`, `SplitInstances`, `LoadTriangles`, `LoadProceduralGeometry`, `ReloadTriangles`, `ReloadProcedurals`, `PT_ConstructBVH4`, `ConstructBVH4`, `RefitBVH4`, `BuildBVHSplits`, `BuildBVHSplits64`, `FindTreelets`, `ResetKDOP`, `BuildKDOP`, `BuildApexPointMap` | 106| #30-#46 | `RearrangeTriangles`, `RearrangeBVHs`, `LoadInstances`, `SplitInstances`, `LoadTriangles`, `LoadProceduralGeometry`, `ReloadTriangles`, `ReloadProcedurals`, `PT_ConstructBVH4`, `ConstructBVH4`, `RefitBVH4`, `BuildBVHSplits`, `BuildBVHSplits64`, `FindTreelets`, `ResetKDOP`, `BuildKDOP`, `BuildApexPointMap` |
84| #47-#53 | `GetBVHCompactedSize`, `DecompressHeader`, `LeafRehydration`, `Box16Rehydration`, `Box32Rehydration`, `CopyAndCompactBVH`, `GetBVHCompactedSize` (again) | 107| #47-#53 | `GetBVHCompactedSize`, `DecompressHeader`, `LeafRehydration`, `Box16Rehydration`, `Box32Rehydration`, `CopyAndCompactBVH`, `GetBVHCompactedSize` (again) |
85container is created twice: **`GetBVHCompactedSize`** (RT-182). With `LEONIDA_BVH_RECORD62=1` the test prints each 108
86creation's container with its `ILDN` module name and the first bytes of its digest: creations 1 to 51 are 51 109The test also prints each creation's container with its `ILDN` module name and the first bytes of its digest
87distinct containers, `GetBVHCompactedSize` (5,284 bytes, 0x14a4) among them at 47; creation 52 is 110(RT-182): creations 1 to 51 are 51 distinct containers, `GetBVHCompactedSize` (5,284 bytes, 0x14a4) among them at 47;
88`CopyAndCompactBVH` (4,404 bytes, 0x1134); creation 53 is `GetBVHCompactedSize` again, with the same digest and 111creation 52 is `CopyAndCompactBVH` (4,404 bytes, 0x1134); creation 53 is `GetBVHCompactedSize` again, with the
89size. So the 0x14a4-byte container `FUN_18001d400` passes for `XDXR PostBuildInfoQuery` is the 112same digest and size. So the 0x14a4-byte container `FUN_18001d400` passes is the `GetBVHCompactedSize` module, and
90`GetBVHCompactedSize` module, and the PSO for it is created twice. Measured on 1.0.2.1 with an RTX 5080 (driver 113the PSO for it is created twice (under one name, `XDXR GetBVHCompactedSize`, per the SetName record above). Measured on 1.0.2.1 with an RTX 5080 (driver
91621.01): all 53 creations return `S_OK`. 114621.01): all 53 creations return `S_OK`.
92 115
93## 3. The 52 modules 116## 3. The 52 modules
@@ -147,17 +170,6 @@ The single remaining untranslated program stops at one rule:
147|---|---| 170|---|---|
148| `Box16Rehydration` | `buffer_store_short` (#1864) | 171| `Box16Rehydration` | `buffer_store_short` (#1864) |
149 172
150| module(s) | blocker then | now |
151|---|---|---|
152| `BuildKDOP`, `LoadInstances`, `ReloadProcedurals`, `LoadProceduralGeometry`, `LoadTriangles` | `global_atomic_fmax` | translate |
153| `PT_LoadInstances` | `global_atomic_fmin` | translates |
154| `Box32Rehydration`, `ReloadTriangles` | `buffer_load_ushort` | translate |
155| `LeafRehydration` | `tbuffer_load_format_x GFX10_FORMAT_8_UINT` | translates |
156| `Box16Rehydration` | `buffer_load_ushort` | stops at `buffer_store_short` (#1864) |
157
158The disassembly count is unchanged: the same 42 programs have no invalid word, and 10 have invalid words in the
159code. All 10 of those translate; `Box16Rehydration` is one of the 42 clean ones.
160
161Reproduction, after `--extract` above: 173Reproduction, after `--extract` above:
162 174
163```sh 175```sh
@@ -166,6 +178,8 @@ python -I tools/shader_disasm.py <work>/embedded/dxbc/fssm --out <work>/embedded
166python -I tools/rdna2spirv.py <work>/embedded/dxbc/disasm --out <work>/embedded/spirv 178python -I tools/rdna2spirv.py <work>/embedded/dxbc/disasm --out <work>/embedded/spirv
167``` 179```
168 180
181`make_game.py` runs the same four tools as a build step (section 7).
182
169## 5. What this changes 183## 5. What this changes
170 184
171* **The RT builder does not need a DXIL path for the console code.** Its programs are RDNA2 `FSSM`, and 51 of 185* **The RT builder does not need a DXIL path for the console code.** Its programs are RDNA2 `FSSM`, and 51 of
@@ -201,7 +215,8 @@ python -I tools/rdna2spirv.py <work>/embedded/dxbc/disasm --out <work>/embedded/
201 * the wave64 bitonic sorts (`BitonicPreSort64CS`, `BitonicInnerSort64CS`) declare 32,780 bytes of workgroup memory 215 * the wave64 bitonic sorts (`BitonicPreSort64CS`, `BitonicInnerSort64CS`) declare 32,780 bytes of workgroup memory
202 with the translator's default cap, 12 over the 32 KiB AMD's Windows driver allows 216 with the translator's default cap, 12 over the 32 KiB AMD's Windows driver allows
203 (`VUID-RuntimeSpirv-Workgroup-06530`). Their highest LDS offset is 8192, and `--max-shared-memory 32768` shrinks 217 (`VUID-RuntimeSpirv-Workgroup-06530`). Their highest LDS offset is 8192, and `--max-shared-memory 32768` shrinks
204 the array to what they use; 218 the array to what they use. That was before SHADER-579 moved the barrier-round counts into the LDS array: today
219 both declare 32,768 bytes with the default cap, and section 7 has what the cap still changes;
205 * with every table word 0 instead, the descriptors point at the table itself, and `RadixCount` then writes into the 220 * with every table word 0 instead, the descriptors point at the table itself, and `RadixCount` then writes into the
206 table that other waves are reading, so its output differs between runs. That is the test input, not the 221 table that other waves are reading, so its output differs between runs. That is the test input, not the
207 translator; the tool's default avoids it. 222 translator; the tool's default avoids it.
@@ -225,3 +240,156 @@ container only when the chunk table is sorted, 4-byte aligned, entirely inside t
225chunk ends exactly at that total; that is what rejects the FSR DLL's `DXBC` immediate. The synthetic tests in 240chunk ends exactly at that total; that is what rejects the FSR DLL's `DXBC` immediate. The synthetic tests in
226`tests/test_pe_shader_containers.py` build containers by hand (no game data) and cover the accepted layout, a 241`tests/test_pe_shader_containers.py` build containers by hand (no game data) and cover the accepted layout, a
227bare magic, a truncated chunk, an `ACCC`/`FSPX` container, the `ILDN` name and the extraction index. 242bare magic, a truncated chunk, an `ACCC`/`FSPX` container, the `ILDN` name and the extraction index.
243
244## 7. Build step and run-time lookup
245
246**Build (D3D-557).** `make_game.py`'s `shaders` stage, after the game's own shaders and the FidelityFX step, runs
247`bvh_shaders()` on the package's `XboxBvhBuilder.dll`. It is the recipe of section 4, with the extraction index
248passed along so that each tool reads only what the one before it wrote:
249
250```sh
251python -I tools/pe_shader_containers.py <game>/XboxBvhBuilder.dll --extract <work>/shaders/bvh
252python -I tools/fssm_unpack.py <work>/shaders/bvh --carve-index <work>/shaders/bvh/index.json
253python -I tools/shader_disasm.py <work>/shaders/bvh/fssm --unpack-index <work>/shaders/bvh/fssm_index.json --out <work>/shaders/bvh/disasm --mcpu gfx1013
254python -I tools/rdna2spirv.py <work>/shaders/bvh/disasm --out <work>/shaders/spirv/bvh --no-asm --max-shared-memory 32768
255```
256
257The last line also gets `--wave64-emulate` and the fallback flags of the build, like the game's shaders.
258
259* **The key is the game shaders' key.** The programs are `FSSM` (section 4), so each index entry gets
260 `fssm_sha256`, the SHA-256 of the blob `fssm_unpack.py` inflates from the container's `XBCH` record. That is what
261 the runtime computes from the container the DLL passes to slot 62, as it does for a shader of `shaders.rpf`. No
262 second key or name table was added. The 52 blobs are 52 different programs, and none of them is in a translated
263 1.0.2.1 corpus of `shaders.rpf` (0 of 52 hashes among its 26,501 index entries), so the two indexes do not meet;
264 if a program were in both, both entries would be candidates, the game's first.
265* **One folder, redone as a whole.** The step is reused only when both indexes, every module the translation index
266 names and a matching `bvh_build.json` (written last) are there. It runs again when the DLL, one of the three
267 tools before the translator, the translator, `llvm-mc`, the wave64 mode, the flags or the memory cap change, and
268 it never makes the game's shaders translate again. Before it runs, it removes the containers, blobs, listings and modules of the run before:
269 `pe_shader_containers.py` never overwrites a container, so a second extraction into the same folder would write
270 `<module>_NN.dxbc` beside the first and those would be translated as more programs. A package without the DLL
271 skips the step.
272* **A program without a rule is reported, not skipped.** There is no skip list. After the translation the step
273 compares the extraction index with the translation index and logs the counts and the name of every program the
274 runtime cannot find (no entry with an `fssm_sha256`, which includes an entry whose metadata failed). It logs them
275 on every run, also when the step is reused. Today that is one line: 51 of 52, `Box16Rehydration`
276 (`buffer_store_short`, #1864). The other 51 are published. When no program translates the step fails and keeps
277 no index.
278* **`--max-shared-memory 32768`.** The constructor creates a pipeline for every program and throws at the first
279 failure, and the runtime refuses a module over the device's `maxComputeSharedMemorySize` (`E_NOTIMPL`,
280 [design.md](design.md), "Workgroup memory limit"). 32,768 is what the AMD Windows and Intel drivers report.
281 Measured on `main` `3faac557`, by `lds_bytes` and by comparing the modules byte for byte:
282
283 | translation | default cap (65,536) | `--max-shared-memory 32768` |
284 |---|---|---|
285 | native | largest 32,768 B (`BitonicPreSort64CS`, `BitonicInnerSort64CS`, `RadixAlloc`), none over | all 51 modules identical |
286 | `--wave64-emulate` | `RadixAlloc` 37,084 B, the others at most 32,768 B | `RadixAlloc` 22,236 B, the other 50 modules identical |
287
288 So the cap changes one module, and only in an emulated build; the same 51 programs translate with and without
289 it. Without it that build stops on a 32,768-byte device at creation #29: measured on the Radeon below with the
290 emulated modules made at the default cap, `RadixAlloc` is refused (`declares 37084 bytes of workgroup memory`,
291 `0x80004001`) after 28 creations.
292
293**Run time.** `ShaderLibrary::load(dir)` (`runtime/src/shader_library.h`) reads `<dir>/index.json`, then
294`<dir>/fspx/index.json` and `<dir>/bvh/index.json` when they are there. The builder's entries are named
295`bvh/<name>`, the path of their module below `<dir>`, and go into the table of the game's shaders, so
296`create_compute` finds them through the lookup it already had (`compute_program()` gives an `FSSM` program, looked up
297by `(cs, fssm_sha256)`). A missing or unreadable `bvh/index.json` leaves the other indexes loaded, and the main
298index is still required. `bvh_size()` counts the entries, which `shader_library_corpus_test` leaves out of the
299entries a carved container must reach, like the FSPX ones.
300
301**Measured: `LEONIDA_BVH_DEVICE=vulkan bvh_builder_test`** (package 1.0.2.1, `LEONIDA_BVH_RECORD62=1`,
302`LEONIDA_SHADERS` on a folder holding this step's output and an empty main index, since only this step was run).
303Before the step, on `main` `3faac557`, creation #1 failed on both GPUs: `0x80004005` with no library, `0x80070057`
304with a translated corpus of 26,521 entries, none of them the builder's.
305
306| GPU | translation | result |
307|---|---|---|
308| RTX 3070, NVIDIA 610.74 (subgroups 32..32, limit 49,152) | `--wave64-emulate` | 49 of 50 creations `S_OK`; #50 `Box16Rehydration` has no module, `E_INVALIDARG`, and the constructor throws `0x80070057` |
309| same | native | the same 49 of 50; the runtime warns that this device cannot require 64-wide subgroups |
310| Radeon integrated (Ryzen 7 9700X), AMD 32.0.21042.62 (subgroups 32..64, limit 32,768) | `--wave64-emulate` | 49 of 50 `S_OK`, stops at #50 the same way |
311| same | native | 49 of 50 `S_OK`, stops at #50 the same way. That is the translator of `main` `561b65a8`; with the one of `3faac557`, 48 creations returned `S_OK` and #49 `LeafRehydration` did not come back from the driver's pipeline compile in 16 minutes (below) |
312
313The rows above were measured before #1864 (`buffer_store_short`) was on `main`. With it (`main` `8575d36e`) the
314step translates 52 of 52, and on the Radeon with the emulated modules all 53 creations return `S_OK` and
315`bvh_builder_test` passes on the Vulkan device; the RTX 3070 and the native modules were not run again.
316
317Before that, with #1864's translator change applied to a local copy of the tools (not part of this step), 52 of 52 translate
318and pass `spirv-val`, and with the emulated modules all 53 creations return `S_OK` on both GPUs: the constructor
319and the destructor return and the test passes. So with the emulated modules the one thing between this step and a
320constructed builder on the Vulkan device is `buffer_store_short`. The PC-device run of the test (WARP) is
321unchanged: 53 of 53.
322
323**`LeafRehydration` on the AMD driver (SHADER-995).** The step was first measured with the translator of `main`
324`3faac557`. `vk_pipeline_check` then created the same pipelines without the D3D12 layer: all 51 on the RTX 3070
325(native and emulated) and on the Radeon (emulated), and on the Radeon with the native modules 50 of 51, while
326`LeafRehydration`, a 1.66 MB wave64 module, was still compiling when the check was stopped after 15 minutes. Its
327emulated module was created in 12 s on that driver, and its native module in 11 s on the RTX 3070.
328
329The stop was that driver's compile time for the control-flow form of one module, not the lookup, native wave64 or
330the module's size. The translator of `3faac557` emitted a structured tree deeper than 16 in the dispatch-loop form
331(SHADER-299: one loop around an `OpSwitch` with a case per basic block), and this program's tree nests 18 deep
332(`ReloadTriangles`' 17; found by lowering `--max-structured-depth` until the form changes). Since SHADER-427 the
333bound is 64, so with `main` `561b65a8` all 51 native modules are structured (47) or barrier rounds (4), the native
334row of the table above is that translation, and `vk_pipeline_check` creates all 51 native pipelines on the Radeon
335(18.4 s on one thread, `LoadInstances` 8.6 s the slowest; the 51 emulated ones 26.9 s, `LeafRehydration` 11.6 s the
336slowest). No build option is involved, and the step needed no change. @Jadiac5 measured the same translation on an
337RX 9070 XT (RDNA4, AMD 32.0.32029.2010): 51 of 51 native and 51 of 51 emulated, the slowest module in 19 to 35 s
338([their comment](https://github.com/ItsNotRexed/Leonida/pull/5680#issuecomment-7101091229)). Those are the
339structured modules too, so the dispatch-loop module below has only been tried on the gfx1036 and the RTX 3070.
340
341Measured on the Radeon (gfx1036, AMD 32.0.21042.62) with `vk_pipeline_check --jobs 1`, one module in the driver at
342a time beside the one long run. That driver keeps compiled shaders on disk and gives back a module it has seen in
3430.2 s, so every time is the first compile of a module, or of a copy with another generator word in its header:
344
345| `LeafRehydration` module | size | shape | pipeline creation |
346|---|---|---|---|
347| dispatch loop, translator of `3faac557` | 1,658,968 B | 1,532 blocks: one loop around an `OpSwitch` with 581 cases | created after 2,039.5 s (34 minutes): 2,014 s of CPU time, one busy thread, the process at 1.2 GB after 5 minutes and 1.7 GB after 21. Slow, not hung |
348| the same module, pipeline requiring 32-wide subgroups, or no size | | | not within 150 s either way |
349| dispatch loop, current translator (`--dispatch-loop` or `--max-structured-depth 16`, the same bytes) | 1,192,148 B | 2,954 blocks, the same loop and switch | XXnot created within 10 minutes; the run was stopped there |
350| structured, the default now | 1,238,360 B | 4,108 blocks, 1,763 selections, no loop, no switch | 2.9 s (3.6 s and 3.2 s for two more copies) |
351| `--wave64-emulate`, translator of `3faac557` | 1,703,748 B | emulated wave64 structured | 12.6 s |
352| `--wave64-emulate`, current translator | 1,358,436 B | emulated wave64 structured | 12.4 s |
353
354What the time depends on, tried on the current translator's dispatch-loop module with a limit of 45 to 150 s per
355compile:
356
357* **Not the subgroup operations or the subgroup size.** All three native forms hold the same 590
358 `OpGroupNonUniformAny` and no other subgroup operation. A copy with each of them replaced by an `OpLogicalOr` (a
359 compile-time probe, not an equivalent module) did not finish in 120 s, and neither did the first module with
360 32-wide or no required subgroup size.
361* **Not the size of the switch by itself.** The other programs compile in the dispatch-loop form on that driver,
362 2.5 to 5 times slower than structured: `LoadInstances` (628 cases, 5.35 MB) in 40.3 s against 8.6 s,
363 `ReloadTriangles` (311) 3.6 s against 0.7 s, `ConstructBVH4` (206) 2.2 s against 0.6 s, `PT_ConstructBVH4` (186)
364 1.9 s, `LoadTriangles` (185) 2.1 s, `SplitInstances` (153, 1.53 MB) 4.0 s against 1.2 s, `RefitBVH4` (125) 1.3 s,
365 `FindTreelets` (89) 0.9 s, and the wave64 `Box32Rehydration` (47) 0.5 s and `RadixAlloc` (17) 0.4 s.
366* **It is how much of this program the loop reaches.** With only the first K of the 581 cases left in the
367 `OpSwitch` (the other blocks unreachable; a probe again): K = 64 0.8 s, 128 1.5 s, 256 3.6 s, 272 5.4 s, 280
368 23.1 s, 284 24.5 s, 286 43.5 s, 287 42.9 s, and 288, 320, 384 and 512 not within 60 to 90 s. So past case 272 a
369 few more blocks multiply the time. That looks like growth with the paths through the program rather than with
370 its size, which these numbers suggest and do not show.
371* **Nothing done to the module from outside changed that.** `spirv-opt -O` (1,350,016 B) and the local SSA
372 rewrite with dead-code elimination (`--ssa-rewrite` after the two local eliminations and before
373 `--eliminate-dead-code-aggressive`, 1,120,512 B) validate and did not finish in 120 s;
374 `--eliminate-dead-branches --merge-blocks --cfg-cleanup` returns the module unchanged. Marking every load and
375 store of the dispatch variables `%pc` and `%done` `Volatile`, which keeps the module equivalent, did not finish in
376 150 s either (whether that driver honours the flag was not checked). `-Os`, `--merge-return` and
377 `--scalar-replacement` were not run.
378
379So the AMD compiler's time on this module comes from the dispatch-loop form of this one program: of the eleven
380tried it is the only one that is both large and without a loop of its own (its structured module has no
381`OpLoopMerge`), which is an observation, not an explanation, and which of the driver's passes takes the time was
382not looked into. The default translation does not emit that form for any of these 51 programs, so the step keeps
383what `wave64_settings` chooses for this driver (native, #857) and makes no exception for the builder. A module can
384still come out in the dispatch-loop form elsewhere (a graph `cfg_structure` cannot make reducible, a tree deeper
385than the bound, `--dispatch-loop`); [testing.md](testing.md), "Known problems", has the row for that.
386
387Still open: nothing has dispatched one of these pipelines through the D3D12 layer, so this shows that the
388constructor's pipelines are created, not that a build produces the right tree (section 5).
389
390`tests/test_bvh_shaders_stage.py` runs the step on a synthetic DLL (hand-built containers around a made-up `FSSM`
391blob, no game data): the key the extracted layout gives the translator, the tools and arguments, reuse and each
392reason to run again, a second run that leaves no duplicate containers, the report of an untranslated program on
393every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` index (found by the
394container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test`
395creates a pipeline through slot 62 whose only translation is in `<shaders>/bvh/index.json`.
diff --git a/docs/first_light.md b/docs/first_light.md
index 654665c6c..9eaff8f37 100644
--- a/docs/first_light.md
+++ b/docs/first_light.md
@@ -1,9 +1,9 @@
1# First light: a game model's UVs drawn with translated game shaders 1# Drawing model UVs and textures with First Light
2 2
3**Status: measured** on the 1.0.2.1 package and an NVIDIA RTX 2060 SUPER (driver 620.73.04, Vulkan 1.4.357, 3**Status: measured** on the 1.0.2.1 package and an NVIDIA RTX 2060 SUPER (driver 620.73.04, Vulkan 1.4.357,
4CachyOS). The fixture draws a model from the package with a vertex and pixel shader chosen to display its UVs. The image 4CachyOS). The untextured fixture draws a model from the package with a shader pair chosen to display its UVs.
5stays in the user's work folder; this note records the counts and the recipe, not the model, the shaders or a 5With `--dds`, the default pixel shader samples the supplied texture at those UVs. Section 6 gives the textured
6screenshot. 6draw recipe. The image stays in the user's work folder.
7 7
8## 1. What was drawn 8## 1. What was drawn
9 9
@@ -14,7 +14,7 @@ those counts and has SHA-256
14assembles it, `tools/first_light.py`, centres and fits X/Y to NDC and flattens Z (the chosen VS applies no 14assembles it, `tools/first_light.py`, centres and fits X/Y to NDC and flattens Z (the chosen VS applies no
15matrix), so the draw is an orthographic projection of the model's own geometry. 15matrix), so the draw is an orthographic projection of the model's own geometry.
16 16
17The shaders are two ordinary containers from `shaders.rpf`, carved and translated by the repository's own tools: 17The untextured fixture uses two containers from `shaders.rpf`, carved and translated by the repository's tools.
18 18
19| stage | FSSM SHA-256 | what it does | 19| stage | FSSM SHA-256 | what it does |
20|---|---|---| 20|---|---|---|
@@ -25,7 +25,7 @@ The model's authored shader assignment can be checked separately. In the model e
25above, `MeshShaders[0]` selects material slot 0, the only slot. Looking up its `Materials[0].Shader` in the 25above, `MeshShaders[0]` selects material slot 0, the only slot. Looking up its `Materials[0].Shader` in the
26native shader database yields one effect with one technique and four compute-only passes. The VS and PS 26native shader database yields one effect with one technique and four compute-only passes. The VS and PS
27in the table are the fixture's chosen pair. The model's use during gameplay remains unverified. 27in the table are the fixture's chosen pair. The model's use during gameplay remains unverified.
28See the [effect lookup](https://github.com/ItsNotRexed/Leonida/pull/3036) and the 28See the [effect lookup tool](../tools/sgd5_effects.py) and the
29[Windows reproduction of the UV draw](https://github.com/ItsNotRexed/Leonida/pull/2893#issuecomment-7084947193). 29[Windows reproduction of the UV draw](https://github.com/ItsNotRexed/Leonida/pull/2893#issuecomment-7084947193).
30 30
31Both disassemble with no invalid word, translate, and pass `spirv-val`; `tools/shader_link_check.py check` reports 31Both disassemble with no invalid word, translate, and pass `spirv-val`; `tools/shader_link_check.py check` reports
@@ -69,8 +69,10 @@ python -I tools/first_light.py --check --out ~/leonida-work/first_light/out
69``` 69```
70 70
71`--check` on an existing folder re-runs the harness through the same fresh path and `check_image` as the test; a 71`--check` on an existing folder re-runs the harness through the same fresh path and `check_image` as the test; a
72harness that exits 0 without writing, an all-opaque image and a swapped-U/V image all exit 1. The test has seven 72harness that exits 0 without writing, an all-opaque image and a swapped-U/V image all exit 1. The test has
73cases: the two package-gated draw/manifest checks, the `--check` command and four oracle fixtures. 73twenty-five cases: the two package-gated draw/manifest checks, the `--check` command, four oracle fixtures, the
74mesh depth fit, a preview with non-finite readback channels, the stage files of two shaders with the same name, two
75OBJ parsing checks, seven checks of the textured path (section 6) and six CPU checks of `--camera` (section 7).
74 76
75`first_light.py` carves `shaders.rpf` if the work folder does not have it, translates only the chosen pair, converts 77`first_light.py` carves `shaders.rpf` if the work folder does not have it, translates only the chosen pair, converts
76the OBJ to the harness's mesh file (`u32 vertex_count, u32 index_count`, `(x,y,z,u,v) f32` vertices, `u32` 78the OBJ to the harness's mesh file (`u32 vertex_count, u32 index_count`, `(x,y,z,u,v) f32` vertices, `u32`
@@ -82,6 +84,9 @@ Each run stages its pair in `<work>/first_light/dxbc` and translates it into `<w
82are removed at the start of a run, so they hold that run's two shaders and nothing an earlier run selected; do not 84are removed at the start of a run, so they hold that run's two shaders and nothing an earlier run selected; do not
83keep files there. The output folder (`first_light/out` or `--out`) and `<work>/shaders` are not emptied. If either 85keep files there. The output folder (`first_light/out` or `--out`) and `<work>/shaders` are not emptied. If either
84folder is a symlink or a junction, or a file in it cannot be removed, the run stops and names it. 86folder is a symlink or a junction, or a file in it cannot be removed, the run stops and names it.
87With `--keep-z` or `--no-fit`, a triangle can cross the near or far clip plane. For the
88passthrough VS, the CPU predicts a UV only where the interpolated depth is between 0 and 1,
89inclusive. If several triangles cover a probe there, the last one drawn supplies its UV.
85 90
86## 4. The harness mode 91## 4. The harness mode
87 92
@@ -135,9 +140,10 @@ The CPU oracle (`check_image`) samples the decoded `R8G8B8A8_UNORM` texture bili
135`centre_uv` and each `uv_probes` entry and requires the GPU readback to match within `0.02` (rejecting the 140`centre_uv` and each `uv_probes` entry and requires the GPU readback to match within `0.02` (rejecting the
136magenta unbound-texture fallback and wrong-colour probes). Verified on Windows 11 with an NVIDIA GeForce RTX 3060 141magenta unbound-texture fallback and wrong-colour probes). Verified on Windows 11 with an NVIDIA GeForce RTX 3060
137(driver 621.24, Vulkan 1.4.357): **12,804/16,384 (0.781)** covered. Without `LEONIDA_FIRST_LIGHT_DIR`, 142(driver 621.24, Vulkan 1.4.357): **12,804/16,384 (0.781)** covered. Without `LEONIDA_FIRST_LIGHT_DIR`,
138`python -I tests/test_first_light.py -v` runs **14 tests: 11 passed, 3 skipped** (the 3 package-gated 143`python -I tests/test_first_light.py -v` runs **46 tests: 42 passed, 4 skipped** (the 3 package-gated
139`FirstLightTests` require `LEONIDA_FIRST_LIGHT_DIR`; the 4 `OracleTests` and 7 `TexturedOracleTests` run without a 144`FirstLightTests` require `LEONIDA_FIRST_LIGHT_DIR`, and `test_harness_rejects_wrapped_tsharp_va_overflow` needs a
140package). With `LEONIDA_FIRST_LIGHT_DIR` set against a local package run, all **14/14** tests pass. 145built `vk_harness`; the 4 `OracleTests` and the other 11 `TexturedOracleTests` run without a package). With
146`LEONIDA_FIRST_LIGHT_DIR` set against a local package run (and `vk_harness` built) none of the 46 is skipped.
141 147
142```sh 148```sh
143python -I tools/first_light.py --game "<package>" --work ~/leonida-work \ 149python -I tools/first_light.py --game "<package>" --work ~/leonida-work \
@@ -146,10 +152,64 @@ python -I tools/first_light.py --game "<package>" --work ~/leonida-work \
146LEONIDA_FIRST_LIGHT_DIR=~/leonida-work/first_light/out python -I tests/test_first_light.py -v 152LEONIDA_FIRST_LIGHT_DIR=~/leonida-work/first_light/out python -I tests/test_first_light.py -v
147``` 153```
148 154
149## 7. Limits and next 155## 7. A camera (TEST-523)
150 156
151* The chosen VS applies no matrix; the tool's fit is an orthographic stand-in for the game's view/projection. A 157`first_light.py --camera` draws the same model in perspective with a game VS that applies a world matrix and a
152 real camera needs a VS that reads its constants, which is the next model/shader pair. 158view-projection matrix of its own, read from two constant buffers. The PS is the one from section 1:
159
160| stage | FSSM SHA-256 | what it does |
161|---|---|---|
162| VS | `e909a9e5a0096e00bc2b621ae3bdc96ac904f3047aed3917835774cbccb09716` | POSITION × world × view-projection to clip space (computed w); TEXCOORD to a varying |
163| PS | `ed4147a5f7514947c2eb8d79255bd80f72761ac1ba2205dd811d3e050cf1b495` | as in section 1 |
164
165The VS's scalar loads give its constant layout. The 32-bit address of a descriptor table is in s9 (the high half is
1660). The V# at table + 0x20 points at the world rows: X, Y, Z and translation, one float4 each at 0x00–0x30, of
167which the VS reads xyz. The V# at table + 0x60 points at a constant buffer whose view-projection rows sit at
1680x160–0x19f. Both matrices multiply a row vector: `world = [x y z 1] W`, `clip = [world 1] VP`. The view-projection
169block is common in the game: on 1.0.2.1, all 9 translated VS modules with exactly POSITION and TEXCOORD inputs and
170a clip w that is not the constant 1.0 read 16 dwords at 0x160 of a constant buffer, as do 123 of the 254 VS
171modules with a POSITION input and a computed w, and 1,266 of all 2,236 VS modules. That it is the view-projection
172everywhere is a hypothesis; for this VS the arithmetic shows it.
173
174The mesh keeps the model's own coordinates. The tool builds a world matrix that centres the model and scales its
175bounding sphere to radius 1. The camera sits 3 radii away, `--yaw` degrees around Z (the game's up axis) from −Y
176and `--pitch` degrees above the XY plane, with a vertical `--fov` (defaults 30, 25 and 50). The projection is
177Vulkan's, with the near and far planes just outside the sphere, so depth clips no vertex. The tool writes the two
178matrices, the two V#s (raw buffers, stride 0, sized to what the VS reads) and the table into `vk_harness`'s heap
179(`VKH_HEAP`) and the table address into s9 (`VKH_SGPRS`). The manifest's `camera` block keeps both, so `--check`
180and the test draw with the same constants. The prediction projects the same vertices with the same float32
181matrices on the CPU and interpolates UV perspective-correctly, dividing each screen-space weight by its vertex's
182clip w. The output goes to `<work>/first_light/camera`, leaving the orthographic folder for section 5.
183
184On an Apple M4 (macOS, MoltenVK 1.4.2), with the section 1 model and the default camera at 128×128:
185
186* The draw covers **6,851 of 16,384 pixels (0.418)**.
187* The centre pixel matches the predicted UV `(0.8100, 0.3096)`, and so do the four U ≠ V probes, within the
188 oracle's 2e-3. The corner keeps the clear value.
189* On a full 32×32 grid of pixel centres, the predicted coverage agrees on all 1,024. The UV agrees within 2e-3 on
190 all 428 covered ones, with the worst at 5.05e-4.
191* The same draw without the constants covers nothing and is rejected. With the camera turned 2° in yaw, the
192 centre pixel is off and the check is rejected too.
193* The pair passes `spirv-val`, and `shader_link_check.py check` reports it compatible.
194
195The model's triangles are small, so perspective-correct and affine UV differ by at most 1e-4 at the probes. The
196image therefore does not tell the two apart; `CameraTests` in `tests/test_first_light.py` checks the
197perspective-correct weights on one large triangle instead. Those CPU tests also read the constants back the way
198the VS's loads do (table, V#, num_records, rows) and compare the result with the matrices the prediction uses.
199
200```sh
201python -I tools/first_light.py --game "<package>" --work ~/leonida-work \
202 --obj ~/leonida-work/assets/data/models/<model>.obj --camera --run # coverage window 0.2-0.99
203LEONIDA_FIRST_LIGHT_DIR=~/leonida-work/first_light/camera python -I tests/test_first_light.py -v
204```
205
206## 8. Limits and next
207
208* The camera draw (section 7) runs in `vk_harness` only. Through the D3D12 layer, s9 and the table it points at
209 have to come from root arguments, which `d3d12_first_light_test` does not set up yet.
210* `--camera` and `--dds` don't combine: the camera VS's table and the textured PS's T# both take s9 of the shared
211 push constants and heap VA 0x100, so `first_light.py` refuses the pair. A textured perspective draw needs a
212 second constant layout.
153* One model and one draw. The `levels.rpf` windows have world props with POSITION/NORMAL/COLOUR/UV layouts that 213* One model and one draw. The `levels.rpf` windows have world props with POSITION/NORMAL/COLOUR/UV layouts that
154 match the `sga_dr_*`/`Rage_Transform*` families by signature; pairing one of those is the natural next image. 214 match the `sga_dr_*`/`Rage_Transform*` families by signature; pairing one of those is the natural next image.
155* The game still cannot boot: the executable is not in the package (RT-5), so no call site selects these programs. 215* The game still cannot boot: the executable is not in the package (RT-5), so no call site selects these programs.
diff --git a/docs/fspx.md b/docs/fspx.md
index 9736133a1..7550a2cc8 100644
--- a/docs/fspx.md
+++ b/docs/fspx.md
@@ -55,6 +55,30 @@ The size at `+0x30` is kind 6's own size, not the rounded allocation: the DLL ro
55`0x56d5`). So 55`0x56d5`). So
56the bytes at `+0x28` with that size are exactly kind 6, and their SHA-256 is the key below. 56the bytes at `+0x28` with that size are exactly kind 6, and their SHA-256 is the key below.
57 57
58**How the table was pinned** (read from the DLL's code with `objdump`; checked by running the DLL's reader on all 29
59payloads):
60- **The reader (`0x1a20`).** It zeroes four (pointer, size) pairs, then stores kind 0 in pair 0, kind 1 in pair 1,
61 kind 6 in pair 2 and kind 7 in pair 3 (`0x1bcb` to `0x1bfb`). Each pointer points into the payload itself.
62- **The container branch (`0x5510` to `0x55ea`).** For a `DXBC` container the pipeline function runs the same loop
63 inline over the `ACCC` part and fills the same four places. Unlike the reader, it does not zero the kind-1 and
64 kind-7 places first; all 29 payloads have both kinds.
65- **The copy into the description (`0x567d` to `0x56d5`).** Pair 0 goes to `+0x08`, pair 1 to `+0x18`, the kind-6
66 copy to `+0x28` with pair 2's size at `+0x30`, and pair 3 to `+0x38`.
67- **Code and state come from one payload.** Kind 0 and kind 6 of one call therefore always belong to the same
68 program, so the run-time lookup by code key and state key (below) has the pairing the build gives it.
69- **Run.** A harness mapped the DLL without running it and called its reader on each of the 29 payloads. It built the
70 description that way and called slot 67 on the Vulkan device with the 26 programs translated on `main` at
71 `aa2988cc`:
72 - all 26 resolve to their own entry with their own state, and the other 3 are refused with `E_INVALIDARG`;
73 - the same on llvmpipe, the Ryzen 9 7950X3D's integrated GPU and the RX 7900 XTX (Mesa 26.3.1, under Wine).
74
75`d3d12_fspx_compute_test` builds its slot-67 descriptions the same way, from a container's own directory.
76
77**What happens when a program is not translated.** The DLL creates its pipelines one after another as a dispatch
78needs them. When one of them has no translation, slot 67 fails, and so does the slot-62 fallback with the same
79container. The DLL then records the null pipeline and faults at `0x65ff`, as on a PC device. The proxy logs every
80failed slot-67 call with its number (`slot 67 call N failed`), because only the first call of a slot is announced.
81
58The DLL's own messages name that call `DeserializeComputePipelineStateX` and the path "ACO". When the call fails, 82The DLL's own messages name that call `DeserializeComputePipelineStateX` and the path "ACO". When the call fails,
59the message says it falls back to "NewBE", and the DLL sets the environment variable `FFX_FSR4_XBOX_ACO_ACTIVE` to 83the message says it falls back to "NewBE", and the DLL sets the environment variable `FFX_FSR4_XBOX_ACO_ACTIVE` to
60`0`. Its next pipeline call is slot 62 (measured in #864), so "NewBE" is inferred to be that path, the one a PC 84`0`. Its next pipeline call is slot 62 (measured in #864), so "NewBE" is inferred to be that path, the one a PC
@@ -69,12 +93,35 @@ Seven u32 words.
69| 0, 1 | Unknown | The same two values in all 29. | 93| 0, 1 | Unknown | The same two values in all 29. |
70| 2 | 0 | All 29. | 94| 2 | 0 | All 29. |
71| 3 | `NumThreadsX` (bits 15..0), `NumThreadsY` (31..16) | Measured: equal to the container's `PSV0` thread-group size in all 29. | 95| 3 | `NumThreadsX` (bits 15..0), `NumThreadsY` (31..16) | Measured: equal to the container's `PSV0` thread-group size in all 29. |
72| 4 | `NumThreadsZ` (15..0); bit 20 set = wave32 | Z measured against `PSV0` in all 29. Wave size inferred: bit 20 is clear in exactly the programs whose code has a wave64 marker (`rdna2spirv`'s `WAVE64_RE`) in 28 of 29; the 29th has no marker either way. | 96| 4 | `NumThreadsZ` (15..0); bit 20 set = wave32 | Z measured against `PSV0` in all 29. Wave size: bit 20 is set in 24 programs and clear in 5, and nothing measured contradicts it (below the table). The translator takes it as the wave size. |
73| 5 | `COMPUTE_PGM_RSRC1` | Inferred. `FLOAT_MODE` 0xC0, `DX10_CLAMP` and `MEM_ORDERED` in all 29. With a VGPR granule of 8 for wave32 and 4 for wave64, the highest VGPR the code uses is inside the allocation in all 21 programs that decode with no invalid word, at its last register in several. | 97| 5 | `COMPUTE_PGM_RSRC1` | Inferred. `FLOAT_MODE` 0xC0, `DX10_CLAMP` and `MEM_ORDERED` in all 29. With a VGPR granule of 8 for wave32 and 4 for wave64, the highest VGPR the code uses is inside the allocation in all 21 programs that decode with no invalid word, at its last register in several. |
74| 6 | `COMPUTE_PGM_RSRC2` | Inferred. `LDS_SIZE` covers the largest `ds_*` offset in all 29. `USER_SGPR` plus the enabled `TGID` SGPRs cover the SGPRs the code reads before writing them in 20 of those 21 (8 or 14 user SGPRs here). In the 21st, a wave64 program, the only SGPRs past them are the carry-out destination of a `v_add_co_ci_u32_e64`, which the check counted as a read. | 98| 6 | `COMPUTE_PGM_RSRC2` | Inferred. `LDS_SIZE` covers the largest `ds_*` offset in all 29. `USER_SGPR` plus the enabled `TGID` SGPRs cover the SGPRs the code reads before writing them in 20 of those 21 (8 or 14 user SGPRs here). In the 21st, a wave64 program, the only SGPRs past them are the carry-out destination of a `v_add_co_ci_u32_e64`, which the check counted as a read. |
75 99
76`rdna2spirv.py` reads words 3, 4 (low half) and 6 from `fspx/<name>.json` where it reads the FSSM header for a game 100`rdna2spirv.py` reads words 3, 4 and 6 from `fspx/<name>.json` where it reads the FSSM header for a game compute
77compute shader. 101shader: the thread-group size, `RSRC2`, and the wave size from word 4 bit 20 (the `wave32` field).
102
103**Word 4 bit 20 is the wave size.** Over the 29 programs of 1.0.2.1 (`tests/semantic/test_fspx_wave_size.py` has
104the rule):
105
106- **Strict markers (measured).** A strict wave64 marker (`rdna2spirv`'s `WAVE64_RE`: `exec_hi`, `v_mbcnt_hi`,
107 `*_saveexec_b64` and the 64-bit lane-mask SOP ops) is in 4 of the 5 programs with the bit clear and in none of the
108 24 with it set. A wave32 marker (`*_saveexec_b32`, `*_wrexec_b32`) is in 4 programs with the bit set and in none
109 with it clear.
110- **VGPR granule (measured).** In the 21 programs that decode with no invalid word, the highest VGPR is inside the
111 `RSRC1` allocation with the granule the bit gives (8 for wave32, 4 for wave64) in all 21. All 18 of those with the
112 bit set use a VGPR past what the wave64 granule would allocate. The 3 with the bit clear would fit either granule.
113- **`PSV0` (measured).** Its expected wave lane counts are stated in 5 programs and agree with the bit in all 5 (64 in
114 3 programs with it clear, 32 in 2 with it set); the other 24 leave them open (0 and the maximum).
115- **Thread groups (measured; the reading is a hypothesis).** The programs with the bit clear have 64 or 256 threads
116 per group; 17 with it set have 32, which as one wave64 would leave half its lanes idle.
117- **`_b64` ops on `vcc` are not markers (measured counts; the reading is a hypothesis).** The three wave32 programs
118 the old heuristic called wave64 write `vcc` from an SGPR pair with `s_mov_b64` (2 to 5 times each) and otherwise use
119 `vcc_lo` and `vcc_hi`, including `vcc_lo` as the lane mask of `v_cmp`/`v_cndmask`: `vcc` held as an ordinary pair.
120- **The one program with no evidence beyond the bit.** It has the bit clear and no marker either way, and its highest
121 VGPR is the last register of the wave64 allocation, so the bit alone decides.
122
123A strict marker against the bit makes the translation refuse the program, as a contradicting FSSM header does. A
124program whose kind 0 is too short for word 4 keeps the code heuristic.
78 125
79## Kind 6: the program 126## Kind 6: the program
80 127
@@ -83,7 +130,11 @@ compute shader.
83 literals. 130 literals.
84 - They carry the container's shader hash. Measured: the low halves of words 0 and 3 and the literals in words 2 and 131 - They carry the container's shader hash. Measured: the low halves of words 0 and 3 and the literals in words 2 and
85 5 equal the 16 bytes after kind 7's `0x43` word, which are the digest in the container's `HASH` part, in all 29. 132 5 equal the 16 bytes after kind 7's `0x43` word, which are the digest in the container's `HASH` part, in all 29.
86 - `llvm-mc` rejects them. Their effect on the GPU was not checked; that they are no-ops is inferred. 133 - `llvm-mc` rejects them. Measured on RDNA2 hardware (`gfx1031`, AMD Radeon RX 6700 XT, driver 26.11.2, through
134 `tools/fspx_prologue_probe.py` / `tools/hw_oracle`): in wave32 and wave64 across 5 synthetic 36-byte prologues
135 (50 positive checks and 8 negative controls), executing the raw words leaves VGPRs (`v0`, `v1`, `v8`..`v15`),
136 SGPRs (`s[0:1]`, `s4`..`s15`), `M0`, `VCC`, `EXEC` (including inactive lanes across 64 threads) and `SCC` (both 0
137 and 1) unchanged, and execution resumes cleanly at `+36` bytes. So they are hardware no-ops on RDNA2.
87 - `tools/fspx_unpack.py` disassembles from the end of the prologue. 138 - `tools/fspx_unpack.py` disassembles from the end of the prologue.
88- **Target.** The programs use `v_dot4_i32_i8` (1,458 times) and `v_dot4c_i32_i8` (25,813 times), which fits the 139- **Target.** The programs use `v_dot4_i32_i8` (1,458 times) and `v_dot4c_i32_i8` (25,813 times), which fits the
89 provider's name (`FSR4_Int8`). `llvm-mc` (LLVM 23.1.5) decodes them for `gfx1011`, `gfx1012`, `gfx1030`, `gfx1031`, 140 provider's name (`FSR4_Int8`). `llvm-mc` (LLVM 23.1.5) decodes them for `gfx1011`, `gfx1012`, `gfx1030`, `gfx1031`,
@@ -155,22 +206,43 @@ clamped total), so a malformed directory, or one without kind 0 or kind 6, gives
155pipeline's code base, which a translated shader reads its embedded constants through, is the kind-6 bytes: the 206pipeline's code base, which a translated shader reads its embedded constants through, is the kind-6 bytes: the
156translator's code offsets are into `fspx/<name>.code`. 207translator's code offsets are into `fspx/<name>.code`.
157 208
158The proxy maps slot 67's description onto `CreateComputePipelineState` with `CS` = the kind-6 pointer and size 209**Slot 67.** The proxy maps slot 67's description onto `CreateComputePipelineState` (#1714). When kind 0 is in the
159(#1714), which is the bare-program row above. Not done here: the console-only pipeline slot 11 the DLL calls after 210description, which the DLL always passes (its reader refuses a payload without one), the proxy builds one FSPX
160either path ([d3d12_command_objects.md](d3d12_command_objects.md) §3.5a), and using 211payload from the four pointer and size pairs (`leonida::fspx_payload_from_parts`) and passes that as `CS`, the
161kind 0 at run time beyond what the translated module already carries (its thread-group size and `RSRC2`). 212bare-payload row above. Two programs with the same code and different dispatch state therefore stay apart at slot 67
213too. Each pair is checked before it is read: a pointer without a size or a size without a pointer, a size over
21416 MiB, or a missing kind 6 refuses the call with `E_INVALIDARG`. Only a description without kind 0 still passes the
215kind-6 bytes alone (the bare-program row).
216
217**Slot 11.** After either path the DLL calls the pipeline's console slot 11. The Vulkan device's pipeline answers
218with a blob holding the dword 0, so the DLL creates no compute scratch buffer; why 0 is justified is in
219[d3d12_command_objects.md](d3d12_command_objects.md) §3.5a.
220
221Not done here: using kind 0 at run time beyond what the translated module already carries (its thread-group size
222and `RSRC2`).
162 223
163## Translation status 224## Translation status
164 225
226With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs (`main` at `aa2988cc` with the
227`v_fma_mix*` literal repair in [design.md](design.md), "Printed encodings"):
228**Wave size.** On `main` at `aa2988cc`, `make_game.py`'s FSPX step translates 26 of the 29, and each now gets the
229wave size of its dispatch state. Before, the code heuristic gave 4 of the 26 the other size: one wave64 program
230was translated as wave32, and three wave32 programs as wave64, because they write `vcc` with `s_mov_b64`. The
231translated and `spirv-val`-valid count is the same (26) either way. The breakdown below was measured when 17 translated.
232
165With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs: 233With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs:
166 234
167- **17 translate and pass `spirv-val`.** 13 of them are the 16 programs that use no dot4 instruction, minus 3 that 235- **27 translate and pass `spirv-val`**, 11 of the 13 programs that use dot4 among them (design.md, "Signed-byte
168 stop at `v_pk_add_u16`, `image_atomic_add` (2D) and `v_pk_fmac_f16`. The other 4 use dot4 (design.md, "Signed-byte 236 dot products"). Without the repair, 26: the `v_fma_mix_f32` it is for is refused.
169 dot products"). 237- **The other 2** (both use dot4) stop at a reachable `v_dot4_i32_i8` VOP3P word with `op_sel` 2 that `llvm-mc` does
170- **9 more programs that use dot4 do not translate yet.** The first thing each stops at: 238 not decode (the VOP3P words above).
171 - 6 at an `s_buffer_load_dwordx8` or `_dwordx16` whose destination range ends in `vcc_lo, vcc_hi`; 239
172 - 2 at a reachable word `llvm-mc` does not decode (the VOP3P words above); 240These counts predate SHADER-813. A program whose reachable code falls through into those undecodable VOP3P words used
173 - 1 at an `src_scc` operand. 241to translate with the path cut at the gap, so its later stores were missing from a module that passed `spirv-val`;
242it is now refused (`fall-through into undecodable words`): programs 04, 05, 06, 09, 12 and 15 of package 1.0.2.1
243(found by @aslan2142). Recount by @CuteBooty with LLVM 23.1.5 (gfx1030 listings, `spirv-val --target-env vulkan1.2`):
24426 of 29 translated and passed before the change, **20 of 29** after it; the 20 kept give byte-identical SPIR-V, and
2458 of the 9 refused stop at a fall-through into undecodable words.
174 246
175## Unknown 247## Unknown
176 248
diff --git a/docs/fssm_crosscheck.md b/docs/fssm_crosscheck.md
index e78d87336..7b85df1ea 100644
--- a/docs/fssm_crosscheck.md
+++ b/docs/fssm_crosscheck.md
@@ -108,6 +108,9 @@ Leonida's rule is `u32[0xC0] + 0x28` to the last `s_endpgm` (also `docs/design.m
108The 1.0.2.1 scan tested 88 aligned little-endian words in each of the 26,503 indexed FSSM blobs as possible 108The 1.0.2.1 scan tested 88 aligned little-endian words in each of the 26,503 indexed FSSM blobs as possible
109packed `PGM_RSRC1` registers carrying `FLOAT_MODE`, `DX10_CLAMP` and `IEEE`. It covered 78 word starts at 109packed `PGM_RSRC1` registers carrying `FLOAT_MODE`, `DX10_CLAMP` and `IEEE`. It covered 78 word starts at
110FSSM offsets `0x00` through `0x134` and 10 at `code_off + 0x00` through `code_off + 0x24`, inclusive. 110FSSM offsets `0x00` through `0x134` and 10 at `code_off + 0x00` through `code_off + 0x24`, inclusive.
111Local Python scripts walked the exported DXBC `index.json`, opened the matching `fssm/<stem>.fssm` for each row,
112and read each candidate with `struct.unpack_from("<I", ...)`. For the standalone check, the scripts intersected
113the sets of header offsets containing `0xC0` across all rows.
111 114
112The VGPR allocation field provides an independent check on that interpretation. Of 2,689 compute shaders, 1,675 115The VGPR allocation field provides an independent check on that interpretation. Of 2,689 compute shaders, 1,675
113had zero reported invalid words and at least one explicit VGPR in the instruction listing. For each of these, 116had zero reported invalid words and at least one explicit VGPR in the instruction listing. For each of these,
@@ -119,6 +122,34 @@ Of the 88 positions, 63 gave too little capacity for at least one qualifying com
119exceeded the minimum whole-granule allocation in all 1,675. Over-allocation is possible, and the mode fields could 122exceeded the minimum whole-granule allocation in all 1,675. Over-allocation is possible, and the mode fields could
120be stored separately or supplied by pipeline state. The initial float mode remains unresolved. 123be stored separately or supplied by pipeline state. The initial float mode remains unresolved.
121 124
125#### Standalone FLOAT_MODE candidate at +0x104
126
127@465d6a0eac proposed that FSSM stores the eight mode bits in their own word. Across all 26,503 indexed
1281.0.2.1 headers, `+0x104` is the only aligned word below `+0x138` that always equals `0x000000C0`.
129Reading it as packed RSRC1 gives too few VGPRs in 1,578 of the 1,675 qualifying compute shaders.
130A standalone mode field makes no VGPR allocation prediction. The contributor also reports the same value in
13152 BVH-builder DLL shaders, outside this replay.
132
133The adjacent words provide two cross-checks. The low byte at `+0x100` matches the stage in every row
134(GS 3, VS 4, PS 5, CS 6, MS 7). The VS word is `0x00020004`; the GS word is `0x00020203`.
135Only the 2,236 VS have zero in bits 15:8 and match the full `0x000200NN` pattern.
136The corresponding byte is 1 for PS, 3 for CS and 6 for MS. The word at `+0x108` is always zero. For every one of the 2,689 CS,
137rounding the byte count at `+0x10C` up to 512-byte blocks predicts the independently decoded
138`COMPUTE_PGM_RSRC2.LDS_SIZE` at `+0x138[23:15]`, including all 485 nonzero allocations. Five MS also
139have a nonzero count. This varying LDS measurement locates stage state near the candidate.
140
141Under the AMD FLOAT_MODE layout, `0xC0` selects round-to-nearest for both precision groups, flushes f32
142denormals on input and output, and preserves f16/f64 denormals on both. All 29 [FSPX programs](fspx.md)
143have the same mode byte in an inferred packed RSRC1 whose VGPR allocation varies. That supports a plausible
144compiler default across formats. The 102,365 reported f32 output modifiers agree with f32 flushing.
145The absence of f16 output modifiers leaves f16 preservation open, and explicit rounding updates give no
146initial value. IEEE and DX10_CLAMP lie outside the proposed byte.
147
148A fixed header-layout value also fits the census: `0xC0` is the offset of the established `code_off` field.
149Whether `+0x104` refers to that field is itself unverified. A loader read mapping `+0x104` to the mode bits,
150or an FSSM with the same layout and an independently known different mode correctly predicted there, would
151distinguish the readings. SHADER-190 remains open.
152
122## 3. ISA, RDNA2 classification and the "XBSC" notes 153## 3. ISA, RDNA2 classification and the "XBSC" notes
123 154
124| Claim | SCARAB source | Leonida behaviour / measurement | Verdict | 155| Claim | SCARAB source | Leonida behaviour / measurement | Verdict |
@@ -195,7 +226,15 @@ PR description.
195 measured on the Leonida corpus; the shared FSSM v0x101/DXBC shape makes the same layout 226 measured on the Leonida corpus; the shared FSSM v0x101/DXBC shape makes the same layout
196 likely, but it is not directly verified against SCARAB's title. 227 likely, but it is not directly verified against SCARAB's title.
197- Which of the two `$VS_*` XBCH payloads the game's pipeline actually uses is not 228- Which of the two `$VS_*` XBCH payloads the game's pipeline actually uses is not
198 established. The 24-byte descriptor is the same in both, so it does not disambiguate. 229 established against pipeline bytes. The 24-byte descriptor is the same in both, so
230 it does not disambiguate, but the PAL stage descriptors do name two different
231 hardware stages for them (`tools/pal_stages.py`): the first payload is stage 2
232 (`es`) and the last stage 4 (`vs`), and `scripts/vs_layout_census.py` confirms the
233 code matches those stages — the ES payload has no `exp` (it writes the vertex
234 outputs to LDS for the geometry stage), takes its lane id from `v_mbcnt` and reads
235 `v5`, `v9`-`v11` and `v13`-`v14` on entry, while the VS payload is the legacy non-NGG VS of
236 `docs/design.md`. `fssm_unpack.py` defaults to the last payload, so the translated
237 one is the VS variant; which payload a GS-bound pipeline selects is still open.
199- The meaning of the 24-byte descriptor (two 12-byte records with a `0xD580` tag) is not 238- The meaning of the 24-byte descriptor (two 12-byte records with a `0xD580` tag) is not
200 established. It is a fixed header, not code. 239 established. It is a fixed header, not code.
201- The vendor disassembler's `asic(CI)` label is unexplained; it does not override the 240- The vendor disassembler's `asic(CI)` label is unexplained; it does not override the
@@ -209,7 +248,7 @@ PR description.
209 248
210``` 249```
211python -I tests/test_fssm_crosscheck.py 250python -I tests/test_fssm_crosscheck.py
212# 4 tests, 1 expected failure (the duplicate-XBCH loss) 251# 6 tests, all pass (the duplicate-XBCH payloads are pinned; no expected failure)
213``` 252```
214 253
215The test uses synthetic `FSSM` and `DXBC` bytes only. No game data is read or written. 254The test uses synthetic `FSSM` and `DXBC` bytes only. No game data is read or written.
diff --git a/docs/gamedata.md b/docs/gamedata.md
index 5aa880df4..586db6a4e 100644
--- a/docs/gamedata.md
+++ b/docs/gamedata.md
@@ -29,6 +29,8 @@ python -I tools/gamedata_index.py <work>\carve\common --csv common.csv --json co
29 29
30The CSV/JSON contain offsets, sizes, the coarse type and the XML root element. They contain no element values 30The CSV/JSON contain offsets, sizes, the coarse type and the XML root element. They contain no element values
31or entry names, but they are still local work products and must not be committed or attached to an issue. 31or entry names, but they are still local work products and must not be committed or attached to an issue.
32`--csv` and `--json` refuse a path that would replace the carve's `index.json` or one of its
33`<offset>.bin`/`.bk2` streams, so a report cannot be written over a carved input.
32 34
33### Coverage 35### Coverage
34 36
@@ -54,7 +56,7 @@ their content.
54## Type split 56## Type split
55 57
56Stream-level split, using the requested classes. `other` is 2 `MHIU` payloads (38 streams), 1 `PAMH` and 1 58Stream-level split, using the requested classes. `other` is 2 `MHIU` payloads (38 streams), 1 `PAMH` and 1
57`SPS1Z`; there are no `RBF0`, `PSIN` or Bink 2 streams in this archive. 59`SPS1`; there are no `RBF0`, `PSIN` or Bink 2 streams in this archive.
58 60
59| Type | Streams | Stored B | Inflated B | Logical payloads | 61| Type | Streams | Stored B | Inflated B | Logical payloads |
60|---|---:|---:|---:|---:| 62|---|---:|---:|---:|---:|
@@ -63,7 +65,7 @@ Stream-level split, using the requested classes. `other` is 2 `MHIU` payloads (3
63| `PSIN` | 0 | 0 | 0 | 0 | 65| `PSIN` | 0 | 0 | 0 | 0 |
64| text / INI-like | 4 | 30,162 | 142,036 | 3 | 66| text / INI-like | 4 | 30,162 | 142,036 | 3 |
65| binary | 66 | 1,396,087 | 4,312,136 | 2 | 67| binary | 66 | 1,396,087 | 4,312,136 | 2 |
66| other (`MHIU`/`PAMH`/`SPS1Z`) | 40 | 456,483 | 2,492,026 | 4 | 68| other (`MHIU`/`PAMH`/`SPS1`) | 40 | 456,483 | 2,492,026 | 4 |
67| **total** | **954** | **5,647,255** | **50,231,123** | **276** | 69| **total** | **954** | **5,647,255** | **50,231,123** | **276** |
68 70
69By inflated bytes: 86.2% XML, 8.6% binary, 5.0% `other`, 0.3% text. XML is only 66.7% of stored bytes, 71By inflated bytes: 86.2% XML, 8.6% binary, 5.0% `other`, 0.3% text. XML is only 66.7% of stored bytes,
@@ -72,7 +74,7 @@ root element. Non-XML grouping follows the 64 KiB block rule; none of the nine n
72that is an exact multiple of 64 KiB, so their counts are unambiguous too. 74that is an exact multiple of 64 KiB, so their counts are unambiguous too.
73 75
74The four non-XML structured payloads are the only readable binary metadata here: two `MHIU` blobs (about 76The four non-XML structured payloads are the only readable binary metadata here: two `MHIU` blobs (about
751.19 MB and 1.21 MB inflated), one `PAMH` blob (48.6 KB) and one `SPS1Z` shader-parameter table (43.8 KB). 771.19 MB and 1.21 MB inflated), one `PAMH` blob (48.6 KB) and one `SPS1` shader-preset table (43,791 B).
76The two large opaque blobs (1.04 MB and 3.27 MB) have no recognised header and are left as binary. No model, 78The two large opaque blobs (1.04 MB and 3.27 MB) have no recognised header and are left as binary. No model,
77texture or audio signature is present in `common.rpf`; the two opaque blobs are not identified. 79texture or audio signature is present in `common.rpf`; the two opaque blobs are not identified.
78 80
@@ -140,7 +142,7 @@ the payload end happened to fit the byte count, but it is not the format.
140| magic | 0x00 | 4 bytes | `PAMH` (little-endian `HMAP`) | 142| magic | 0x00 | 4 bytes | `PAMH` (little-endian `HMAP`) |
141| version | 0x04 | 2 x `u8` | 1.2 in `common.rpf`; overwritten in the `levels.rpf` tiles | 143| version | 0x04 | 2 x `u8` | 1.2 in `common.rpf`; overwritten in the `levels.rpf` tiles |
142| pad | 0x06 | `u16` | 0 in `common.rpf`; text in the tiles | 144| pad | 0x06 | `u16` | 0 in `common.rpf`; text in the tiles |
143| flag word | 0x08 | `u32` | `0x1BBC8CED` in `common.rpf`; padding in the tiles | 145| word at the GTA V `compressed` offset | 0x08 | `u32` | `0x1BBC8CED` in `common.rpf`. Level tiles contain label bytes with bit 0 set. |
144| width, height | 0x0C | 2 x `u16` | 144, 164 in `common.rpf`; 64, 64 in every tile | 146| width, height | 0x0C | 2 x `u16` | 144, 164 in `common.rpf`; 64, 64 in every tile |
145| six bounds | 0x10 | 6 x `f32` | `(-13312, -9728, -302)` to `(5120, 11264, 404)` | 147| six bounds | 0x10 | 6 x `f32` | `(-13312, -9728, -302)` to `(5120, 11264, 404)` |
146| data size | 0x28 | `u32` | 48,544 in `common.rpf`; 8,704 in a tile | 148| data size | 0x28 | `u32` | 48,544 in `common.rpf`; 8,704 in a tile |
@@ -167,13 +169,16 @@ same rules: a 44-byte header, 64 x 64 cells, 64 full-width row records with
167- Max values span 0..255 and min values 0..254. `min <= max` in all but 62 169- Max values span 0..255 and min values 0..254. `min <= max` in all but 62
168 cells, all in the tile at `(-5120, 2048)`, where the encoder wrote a min 170 cells, all in the tile at `(-5120, 2048)`, where the encoder wrote a min
169 above its max. 171 above its max.
170- Bytes 0x05..0x0B are leftover text, not a version minor and a flag. 0x04 172- Use the tile's minimum XY corner to recover its column and row. Subtract the
171 stays 1, 0x05.. hold the tile name `n_m` (column + 1, row + 1), and the 173 grid minimum and divide each axis by 512. The 1,476 distinct coordinate pairs
172 remaining bytes keep the tail of the string `height`, right-aligned at 0x0B. 174 produce only 954 distinct seven-byte labels at 0x05..0x0B.
173 The 28 distinct 0x08..0x0B words are all text; none is zero and none changes 175- To reproduce the label, right-align `height` in those seven bytes, then write
174 the arrays. 176 the one-based `column_row` and its NUL at 0x05. This predicts 819 headers
175- The census groups by grid size, not by the 0x04 version bytes, because 177 exactly. Setting bit 0 at **0x08** in that prediction matches all seven bytes
176 0x05 is the first digit of the name. Nothing depends on the 0x08 word. 178 on **1,476/1,476** tiles. In 81 tiles the bit occupies the expected NUL.
179 Every stored 0x08 word is odd. The bit's runtime meaning is unknown.
180- The census groups by grid size. Byte 0x04 stays 1, 0x05 holds the first
181 digit of the column, and the 0x08 word takes 28 distinct values.
177 182
178```powershell 183```powershell
179python -I tools/gamedata_maps.py <work>\carve\levels --json levels.json 184python -I tools/gamedata_maps.py <work>\carve\levels --json levels.json
@@ -204,10 +209,9 @@ python -I tools/gamedata_maps.py <work>\carve\common --json maps.json
204 209
205### Checksum and unknown fields 210### Checksum and unknown fields
206 211
207- `PAMH` 0x08 is GTA V's `compressed` word only in the `common.rpf` payload, 212- The `common.rpf` `PAMH` payload holds `0x1BBC8CED` at GTA V's `compressed`
208 where it holds `0x1BBC8CED`. In the 1,476 `levels.rpf` tiles bytes 0x04..0x0B 213 offset, 0x08. The level tiles overlap this word with the coordinate label
209 are leftover text (tile name plus `height`), so 0x08 is padding there. The 214 described above. The common value is not CRC32, Adler32, FNV-1a, joaat32 or a hashlib
210 `0x1BBC8CED` value is not CRC32, Adler32, FNV-1a, joaat32 or a hashlib
211 digest of the max/min arrays; it is reported as a flag word, not a proven 215 digest of the max/min arrays; it is reported as a flag word, not a proven
212 checksum. 216 checksum.
213- `MHIU` 0x28 is a `u8` default height, not a 32-bit word (ASSET-48). Its 217- `MHIU` 0x28 is a `u8` default height, not a 32-bit word (ASSET-48). Its
@@ -224,6 +228,36 @@ python -I tools/gamedata_maps.py <work>\carve\common --json maps.json
224 sum of the grid. They are most likely uninitialised struct padding after the 228 sum of the grid. They are most likely uninitialised struct padding after the
225 `u8` and are reported as `pad_29`; with N = 2 this is a hypothesis. 229 `u8` and are reported as `pad_29`; with N = 2 this is a hypothesis.
226 230
231## `SPS1` shader-preset table
232
233The single `SPS1` payload in `common.rpf` (`0x650000`, `43,791` B inflated, 1 stream) is the material shader-preset
234lookup table (`tools/gamedata_sps1.py`), not an `"SPS1Z"` five-byte magic:
235
236| Offset | Type | Meaning | Measured in 1.0.2.1 `common.rpf` |
237|---|---|---|---|
238| `0x00` | `char[4]` | Magic | `"SPS1"` |
239| `0x04` | `u32` | `entry_count` | `858` (`0x0000035A`; its low byte `0x5A == 'Z'` caused the old `"SPS1Z"` reading) |
240| `0x08` | `entry[858]` | `{u8 preset_len, char preset[], u8 effect_len, char effect[], u8 render_bucket}` | `43,783` B consuming the entire payload to EOF (`0` extra bytes) |
241
242Measured over all **858** records and cross-checked against `shaders.rpf`'s two `SGD5` databases:
243
244- **Presets:** all `858` carry a unique case-insensitive `.sps` path (`8`..`51` bytes), split into `846` root
245 names and `12` one-folder paths with zero basename stem collisions.
246- **100% `SGD5` target resolution:** all **858 of 858** records (`539 of 539` distinct target effects, `4`..`47`
247 bytes) match an effect in `shaders.rpf` `SGD5` Database 0 (`0x10E39`, `910` effects; `0` in Database 1).
248- **Aliases:** `532` presets have `preset_stem == effect` and `326` alias a preset name onto a shared effect; only
249 `589` preset stems match an `SGD5` effect name directly (`269` preset stems are defined only in `SPS1`).
250- **Default render buckets (`0..7`):** `0` (`401`), `1` (`161`), `2` (`101`), `3` (`162`), `4` (`1`), `5` (`1`),
251 `6` (`30`), `7` (`1`). `63` target effects span multiple buckets across their presets (`58` in `{0, 3}`, `2` in
252 `{0, 1, 3}`, `1` in `{1, 3}`, `1` in `{0, 1, 2, 3, 6, 7}`, and `1` in `{4, 5}` — the single bucket-`4` and bucket-`5`
253 presets both point to effect hash `0xFC34F08B`, matching [`models.md`](models.md#shader-render-buckets)).
254
255```powershell
256python -I tools/gamedata_sps1.py <work>\carve\common --shaders shaders.rpf --json sps1.json
257```
258
259Only counts, bucket distributions and `--preset-hash` hashes are written; preset and effect names stay local.
260
227## Grid atlases 261## Grid atlases
228 262
229Four `GridAtlasInfo` documents describe world-space texture grids streamed by position. All four have the 263Four `GridAtlasInfo` documents describe world-space texture grids streamed by position. All four have the
@@ -251,11 +285,107 @@ corner, 1.0%; as the top-left corner with y growing downwards, 82.5%. The `level
251same picture: 99.83%, 1.0% and 83.0%. The centre 285same picture: 99.83%, 1.0% and 83.0%. The centre
252reading also gives a minimum x of exactly -13,312, the `PAMH` heightmap's minimum x above. 286reading also gives a minimum x of exactly -13,312, the `PAMH` heightmap's minimum x above.
253 287
254Tile names: none of the four `tileTextureNamePrefix` values starts an archive entry name or a texture-dictionary 288Tile names: the tile textures do exist, but none is named after the tile. Every tile carries only the grid's
255item name in the local catalog (118,925 named items, 119,090 item hashes). Neither the global nor the sector 289`tileTextureNameSuffix` as its texture name, one tile per texture dictionary, and the dictionary names are not in
256fallback names match an item name or its joaat hash, and ten `prefix + x + y + suffix` spellings over all 290the data. That is why `tileTextureNamePrefix` spellings and the fallback names matched no archive entry or item name
2572,112 tiles match nothing in three atlases and one hash in the fourth. The tile textures are therefore either 291in the earlier catalog search. `tools/world_grid_atlas.py` (below) finds them in the texture manifests of
258outside the scanned archives or named another way; this is unresolved. 292`make_game.py --stages assets`.
293
294### What the four grids hold
295
296All four are water data. Every count below is in the tool's printed summary or is the named `--json` field;
297`levels` and `textures` are `levels.rpf` and `textures.rpf`.
298
299| Grid (`clientSystemName`) | Tile texture | Tile dictionaries | Fallback (pixels per tile) | Placed |
300|---|---|---:|---|---:|
301| `WaterSystemHeightMap` | `watersystemheightmap`, 512 x 512 `R16_UNORM` | 738 in `levels` | 1024 x 2112 `R16_UNORM` (32) | 737 |
302| `shorelinegrid1` | `shore_wave_placement_set1`, 256 x 256 `B8G8R8A8_UNORM` | 268 in `levels` | 1024 x 2112 `BC7_UNORM` (32) | 262 |
303| `waterfogatlas` | `waterfog`, 128 x 128 `BC6H_UF16` | 1,313 in `textures` | 512 x 1056 `BC6H_UF16` (16) | 592 |
304| `waterfogatlas2` | `waterfog2`, 128 x 128 `BC6H_UF16` | the same 1,313 | 512 x 1056 `BC6H_UF16` (16) | 592 |
305
306- Each `globalFallbackTextureName` is a mosaic of the whole 32 x 66 grid. Fallback image row 0 is the grid's north
307 edge (largest y, see the fit below), and cell = row * 32 + column.
308- The two fog grids share their dictionaries: each of the 1,313 holds one `waterfog` and one `waterfog2`.
309- `shared_minigame000` holds the `mapswap_tblux` sector-override fallback of all four grids (`sector_fallbacks`)
310 and a few more tiles (`tiles_in_other_archives`: 10 water height, 2 shoreline, 1 fog pair). They are counted
311 and printed, not placed.
312- The water-height fallback has 1,134 constant cells of 2,112; its most common value, 20,480, covers 55.74% of the
313 pixels, and the values run from 20,470 to 49,247.
314
315### Placing the tiles
316
317A tile's cell is recovered by comparing it with its grid's fallback mosaic, then checked against archive order.
318
319- Water height and fog (`method: content`): each tile is point-sampled to the fallback's pixels per tile and
320 compared with every cell by mean absolute difference; the two fog textures of a dictionary are matched together.
321 An anchor is a tile with detail (standard deviation above 0.5) whose runner-up distance is at least twice the
322 best and 0.5 above it. 737 of 738 water-height tiles are anchors; the one flat tile stays unplaced. For fog,
323 617 dictionaries have detail in either texture and 561 are anchors.
324- Shoreline (`method: mask`): the fallback's most common colour, `(0, 128, 0, 128)`, is background. Tiles and cells
325 are compared by intersection over union of their feature masks (pixels more than 32 from the background), 264
326 fallback cells have features and 6 tiles have none. The tiles, in archive order, are aligned to cells in text
327 order (next point) by a dynamic programme that maximises the summed overlap. A tile is placed when it overlaps
328 the cell it is aligned to: 262 are (median overlap 0.83, `overlap_median`), and the 6 unplaced ones are the 6
329 without features. 208 tiles match one cell clearly without the order (best overlap more than 0.2 above the
330 runner-up); these are the shoreline anchors, and the alignment moves none of them
331 (`anchors_moved_by_alignment` 0).
332- **Archive order:** the tile dictionaries are stored in the order of their cells sorted as text of the decimal
333 cell index (`sorted(cells, key=str)`). Ascending steps of the anchors in archive order (`anchor_order`):
334
335| Order of the cells | Water height | Fog | Shoreline |
336|---|---:|---:|---:|
337| text of the cell index | 736 / 736 | 560 / 560 | 207 / 207 |
338| cell index as a number | 735 / 736 | 559 / 560 | 206 / 207 |
339| text of `row_column` | 709 / 736 | 540 / 560 | 189 / 207 |
340| text of `column_row` | 700 / 736 | 526 / 560 | 173 / 207 |
341
342Number order differs from text order only where the cell index changes its digit count. The one break of
343number order in each grid is there: in the `--json` placements the three-digit cells (from 912 in water height)
344are stored after the last four-digit cells, where text order puts them. The dictionary names most likely
345contain the decimal cell index; with one deciding step per grid this is a strong hint, not a read name.
346- Between two anchors, tiles are placed by archive order when their number equals the free cells between them
347 (`placed_by_order`): 31 fog tiles, none for water height. 721 fog dictionaries stay unplaced; 677 of them have
348 no detail in either texture (`unplaced_without_detail`), which content cannot place.
349- Cross-check (`in_water_height_cells`, `anchors_in_water_height_cells`, `placed_by_order_in_water_height_cells`):
350 all 262 placed shoreline tiles and all 561 fog anchors lie in a cell that also has a water-height tile; of the
351 31 fog tiles placed by order, 16 do.
352
353### Water-height values and `zInflation`
354
355The water-height values follow the ground. Over the fallback pixels above 36,000, a least-squares fit against the
356`MHIU` terrain heights (`water_fit`) gives:
357
358| `MHIU` payload | Units per metre | Value at 0 m | r (north up) | r (south up) |
359|---|---:|---:|---:|---:|
360| `0x144000` | 40.81 | 32,947 | 0.9457 | -0.2193 |
361| `0x16E000` | 40.97 | 32,815 | 0.9935 | -0.2187 |
362
363Reading row 0 as the south edge destroys the fit, which is why row 0 is north. Under the better fit, the
364fallback's 20,470 to 49,247 is -301.3 to 401.1 m (`water_metres`), close to the `PAMH` Z box of -302 to 404 m. The
365fit is consistent with a `R16_UNORM` value spread over -800 to 800 m (65,536 / 1,600 = 40.96 units per metre, 0 m
366at 32,768). Under that reading the dominant 20,480 is -300 m, at the floor of the `PAMH` Z box (-302 m) and below
367all ground in `MHIU` (-50 m), which would make it a "no water" value. Both readings are hypotheses: the scale comes from a fit, not from a field.
368
369`zInflation` was not observed at runtime. All four documents have origin z = 0 and `zInflation` 1,000, so if the
370runtime turns each 2D tile into a box from origin z - 1,000 to origin z + 1,000 for its stream test, that box
371covers every height the world data describes. The tool reports (`z_check`) that all 3 heightmap Z ranges in
372`common.rpf` (`PAMH` -302 to 404 m, both `MHIU` -50 to 500 m) lie inside -1,000 to 1,000, and the water heights
373above fall inside it as well. This is a consistency check of that reading, not a measurement of the runtime:
374nothing here shows whether the box is used for the stream test, the camera, or something else.
375
376```powershell
377python -I tools/rpf9_carve.py <game>\common.rpf <work>\carve\common
378python -I tools/world_grid_atlas.py <work> --carve <work>\carve\common --json <scratch>\grid_atlas.json
379python -I tests/test_world_grid_atlas.py
380```
381
382The tool imports numpy and Pillow (Pillow decodes `BC6H`); its placement, ordering and fitting logic is plain
383Python, and the tests of that part run on the standard library alone. The forward check in the tests builds four
384synthetic grids with tiles at known cells, stored in text order, and requires every tile with content to come back
385at its cell; stored in number order instead, the text-order check reports breaks. The `--json` file holds the cell
386of every placed tile, derived from your own copy of the game: keep it local.
387
388### `TextureGridInfo`
259 389
260In the 1.0.2.1 exports, one content change set lists four grid metadata registrations and three candidate 390In the 1.0.2.1 exports, one content change set lists four grid metadata registrations and three candidate
261archive paths as siblings. The list gives no per-grid archive assignment. The two fog grids share a tile 391archive paths as siblings. The list gives no per-grid archive assignment. The two fog grids share a tile
@@ -273,8 +403,9 @@ radius and the same 1,000 `zInflation`, around a different origin. Tested the sa
273placements fall inside with `origin` as the centre, 0.01% as the minimum corner and 11.8% as the top-left 403placements fall inside with `origin` as the centre, 0.01% as the minimum corner and 11.8% as the top-left
274corner, so the centre convention holds for both document types. 404corner, so the centre convention holds for both document types.
275 405
276Not measured here (hypothesis): what the four grids hold (their names suggest per-tile map data for separate 406The tool looks up both fallback names of this document (`texture_grids`): `fallen_snow_cov_fallback_low` is in
277client systems), and how `zInflation` widens a tile's streaming box vertically. 407`textures.rpf` and `fallen_snow_cov_fallback_high` is in none of the exported manifests. The document has no tile
408name field, so the tool does not look for its tiles, and what this grid holds is not measured.
278 409
279## XML documents 410## XML documents
280 411
@@ -367,9 +498,77 @@ Two consequences for a loader. The stored matrices do not include `Scale`, so th
367built from `Position`, `Rotation` and `Scale` rather than read from `TransformMtx`. Profile indices are 498built from `Position`, `Rotation` and `Scale` rather than read from `TransformMtx`. Profile indices are
368positions in `ProfileList`, so its order must be kept. 499positions in `ProfileList`, so its order must be kept.
369 500
501**Package-wide census (ASSET-308, `tools/fog_volumes.py`).** Scanning all `0x7a` resources (assembled via
502`world_census.assemble`, up to 64 MiB and multi-stream, without a 256 KiB per-stream cutoff) in `packs.rpf`,
503`levels.rpf`, `data.rpf`, and `story000.rpf`, plus bounded zlib-stream scans across the remaining package
504archives (`common.rpf`, `anim.rpf`, `navmeshes.rpf`, `textures.rpf`, `script.rpf`, `story000_script.rpf`,
505`core_restofworld.rpf`, `core_restofworld001.rpf`, `story000_restofworld.rpf`, `shared_minigame000.rpf`,
506`core_bvh4.rpf`, `shared_minigame000_bvh4.rpf`, `appdata0.rpf`, `core_licenses_data.rpf`) for XML, RBF0, and
507`0x7a` schemas matching `CScatteringTransmittance__FogVolumeListData` (`0x03073767`) or
508`CScatteringTransmittance__FogVolume` (`0x81907918`) finds:
509
510- **`levels.rpf`** (`188,449` complete `0x7a`, `0` incomplete), **`data.rpf`** (`15,768` complete `0x7a`, `0`
511 incomplete — matching `docs/world.md` and `docs/page_directory.md` — plus `1,263` `RBF0`), **`story000.rpf`**
512 (`48,084` complete `0x7a`, `0` incomplete, plus `1` `RBF0`), and all other archives except `common.rpf` and
513 `packs.rpf`: **0** `FogVolumeListData` / `FogVolume` resources.
514- **`common.rpf`**: remains the only archive with the XML `FogVolumeProfileList` (`0x236000`, 43 profiles) and
515 world-coordinate `CScatteringTransmittance__FogVolumeListData` (`0x64c000`, 14 volumes).
516- **`packs.rpf`** (`4,678` complete `0x7a` resources assembled, `0` incomplete): **231 complete `0x7a`
517 resources** (`0x8ae9010..0xc120010`) containing **770 stored** `CScatteringTransmittance__FogVolume`
518 (`0x81907918`, 512 bytes, 45 members) records and **384 distinct serialized records**:
519 - **230 smaller resources** (`{1: 80, 2: 146, 3: 3, 4: 1}`, median `2`) carrying **385** stored records (`384`
520 distinct).
521 - **1 larger resource** carrying **385** stored records (`384` distinct) that match the 385 records from the 230
522 smaller resources byte-for-byte (including multiplicities).
523
524| Check (`packs.rpf` 0x7a, 770 stored / 384 distinct across 231 resources) | Result (stored occurrences) |
525|---|---|
526| `Position` | `(0, 0, 0)` in all 770 (local-space attachments) |
527| `PositionOffset` | non-zero in 766 of 770: X `-2.46..2.46`, Y `-9.20..20.62`, Z `-6.50..6.66` m |
528| `Scale` | X `0.43..6.00`, Y `0.13..28.00`, Z `0.13..2.63` m |
529| `Rotation` / `Shear` | non-zero in 82 / 388 of 770 |
530| `RotationMtx` and `TransformMtx` | identity in all 770 (even where `Rotation` or `Shear` is non-zero) |
531| `IsBox` (`+0x000`, `ty=0x01`) | `1` in 730, `0` in 40 |
532| `BlendMode` / `IntExtMode` | `1` in all 770 / `1` in 760, `0` in 10 |
533| `ProfileIndex` / `SecondaryProfileIndex` | `{0: 2, 10: 4, 12: 764}` (all in `0..42`) / `0` in all 770; `ProfileInterpolation` is 0 in all 770 |
534| `Type` / `SortKey` | `{0: 768, 2: 2}` / `{0: 768, 10: 2}` |
535
536This resolves the earlier hypothesis: across all 188,449 complete `0x7a` resources in `levels.rpf`, none carries
537`FogVolumeListData` or `FogVolume`. Instead, `packs.rpf` holds 231 resources totalling 770 stored local-space
538records (384 distinct serialized 512-byte records: 385 in 230 per-asset resources duplicated by 385 in one larger
539resource; `Position = 0`, non-zero `PositionOffset` and `Shear`, `IntExtMode = 1` in 760/770), and
540`RotationMtx`/`TransformMtx` stay identity there too — confirming a loader must compose the volume transform from
541`Position`, `PositionOffset`, `Rotation`, `Shear`, and `Scale`. Runtime placement identity, resource-relative
542reference targets, and what `IntExtMode` and `BlendMode` select at runtime remain untested.
370Not measured here (hypothesis): with half the volumes at the origin, two profiles in use and no interpolation, 543Not measured here (hypothesis): with half the volumes at the origin, two profiles in use and no interpolation,
371this list looks like a sample or default set; the placed fog of the map is probably elsewhere (map resources 544this list looks like a sample or default set; the placed fog of the map is probably elsewhere (map resources
372or another archive). What `IntExtMode` (interior/exterior) and `BlendMode` select is also untested. 545or another archive).
546
547**`IntExtMode` and `BlendMode` against placement and interiors (ASSET-312).** Measured on the same 14 volumes
548(`common.rpf`, `CScatteringTransmittance__FogVolumeListData` at `0x64c000`) and on the interior positions of
549`GameShape__Data__LocationNameLoopkup` (`InteriorNames`, 2,280 `Pos`; see [world.md](world.md)), both read with
550`tools/gamedata_reader.py <carve> --root <root> --out <dir>`. That document gives interior points, not bounds; no
551document in `common.rpf` stores interior extents (the `CMloArchetypeDef` bounds in `levels.rpf` are in interior
552space and need the placing instance). So containment cannot be tested: what is measured is only the distance
553from a volume centre (`Position` + `PositionOffset`) to the nearest interior point, and a point nearby would not
554show that a volume is inside an interior.
555
556| Field value | Volumes | `Position` | Nearest interior point | Within 100 m of one |
557|---|---|---|---|---|
558| `BlendMode` 0 | 7 | world coordinates, none at the origin | 117.48 to 230.16 m | 0 |
559| `BlendMode` 1 | 7 | exactly (0, 0, 0) in all 7, offset only | unknown (parent transform not known) | unknown |
560| `IntExtMode` 0 | 14 | both groups above | as above | 0 of the 7 world-placed |
561
562- `BlendMode` splits the list exactly by placement: 0 on the 7 world-placed volumes, 1 on the 7 at the origin.
563 The world position of those 7 is unknown: their offsets are local to a parent this document does not name.
564 #3873 reports `BlendMode` 1 on the 385 local-space records of `packs.rpf`; that counts record occurrences in
565 one representation of the pack block, so it agrees with the split without being independent placement
566 evidence. Hypothesis: 1 marks a volume attached to (and blended with) a parent transform; what it does in the
567 renderer is not measured.
568- `IntExtMode` cannot be correlated here: it is 0 in all 14, and none of the 7 world-placed centres is near an
569 interior point. The 2 volumes that use a profile with `IntExtMode` 1 (`ProfileIndex` 10) are origin volumes
570 with `IntExtMode` 0, so the volume field does not copy the profile's. Whether 1 means interior stays a
571 hypothesis; deciding it needs world-placed volumes with `IntExtMode` 1 and placed interior bounds.
373 572
374## Schema style 573## Schema style
375 574
@@ -434,8 +633,7 @@ Measured over the 630 clouds:
434- **`CoverageMinMax` is a distance range, not a fraction**: min <= max in all 630, values 0 to 30,000, medians 200 633- **`CoverageMinMax` is a distance range, not a fraction**: min <= max in all 630, values 0 to 30,000, medians 200
435 (min) and 2,000 (max), so it reads as an inner/outer radius in world units. 634 (min) and 2,000 (max), so it reads as an inner/outer radius in world units.
436- `StrikeChance` and `BurstChance` are within 0..1 in all 630. `Rain` and `Fog` are within -1..1 (median 0), 635- `StrikeChance` and `BurstChance` are within 0..1 in all 630. `Rain` and `Fog` are within -1..1 (median 0),
437 `Density` within -100..100 (median 0.5) and `FogHeight` within -100..300: signed values, so these act as 636 `Density` within -100..100 (median 0.5) and `FogHeight` within -100..300.
438 offsets or overrides with a sign, not plain amounts.
439 637
440The cloud renderer's settings sit in one `STS_Config` document with 44 top-level sections: four cloud layers 638The cloud renderer's settings sit in one `STS_Config` document with 44 top-level sections: four cloud layers
441(`Nimbus`, `Cumulus`, `Stratus`, `Alto`) that share one set of 13 fields (noise weights and blends, erosion, 639(`Nimbus`, `Cumulus`, `Stratus`, `Alto`) that share one set of 13 fields (noise weights and blends, erosion,
@@ -444,12 +642,33 @@ noise displacement); six media (`GlobalFog`, `LocalFog`, `Rain`, `Clouds`, `Clou
444share another set of 9; and 34 single-value or vector settings. Of the five cloud flags above, `Cumulus` and 642share another set of 9; and 34 single-value or vector settings. Of the five cloud flags above, `Cumulus` and
445`Stratus` match a layer name, `Nimbus0`/`Nimbus1` would both fall on the one `Nimbus` layer, and 643`Stratus` match a layer name, `Nimbus0`/`Nimbus1` would both fall on the one `Nimbus` layer, and
446`CirroStratus` has no layer of its own (`CloudsCirrus` is a medium, not a layer). The weather data's 644`CirroStratus` has no layer of its own (`CloudsCirrus` is a medium, not a layer). The weather data's
447`CloudType` is fractional (14 distinct values from 0.01 to 0.67 over the 25 weathers), so it is a blend 645`CloudType` has 14 distinct fractional values from 0.01 to 0.67 over the 25 weathers.
448position rather than an index into these layers. 646
449 647### Custom-cloud map draw (ASSET-337)
450Not measured here (hypothesis): how a cloud's radius range blends with the weather's `CloudType` and cloud maps, 648
451what a negative `Rain`/`Fog`/`Density` means (subtracting from the weather, or "unset"), and what the two 649One atmospheric technique in the 1.0.2.1 shader dictionary lists a cloud-map compute pass, a custom-cloud
452`Nimbus` flags distinguish. 650vertex/pixel draw and a cloud-density compute pass in consecutive entries, in that order. The density
651program has two distinct resource rows whose compiled and authored name hashes match `CloudMapA` and
652`CloudMapB`. Across the resource and constant-buffer member rows of all 932 effects and 26,503 programs,
653neither hash column has an exact match for `Rain`, `Fog`, `Density`, `CoverageMinMax` or `CloudType`.
654
655The draw reads three consecutive words from a cloud record. They hold a half-precision coefficient and a
65616-bit selector, two half-precision radii, and a half-precision center pair. For distance `d` from that
657center in map coordinates and `outer > inner`, the pixel contribution before render-target blending is
658`coefficient * clamp((outer - d) / (outer - inner), 0, 1)`. Selectors 0 through 3 route it to R, G, B
659or A of the first target. Selector 4 writes it to both R and G of the second target.
660
661A Vulkan replay used the translated draw with synthetic records and blending disabled. Switching only the
662coefficient from +0.75 to -0.75 reversed all 1,804 nonzero pixels exactly. A coefficient of -1 also produced
663a negative contribution. Equal positive radii gave a hard edge at the sampled distances, all strictly inside
664or outside the radius. Across fifteen 64×64 readbacks, the largest absolute error against the expected
665pixel values was below 0.00048.
666
667The missing link is the producer that converts an XML cloud into these draw records. The world-to-map conversion
668for `CoverageMinMax`, the fields that supply the coefficient and selector (including the two `Nimbus` flags),
669and any handling of negative `Rain`, `Fog` or `Density` before the draw remain open. The replay also leaves
670the live target formats, overlap blending, and the relationship between the weather's `CloudType` and the
671two maps unmeasured.
453 672
454## XML catalog 673## XML catalog
455 674
@@ -542,8 +761,8 @@ How the pieces link, checked by name (case-insensitive) over the archive:
542 and 14 `To` values are weather type names, and 13 pairs have both. 761 and 14 `To` values are weather type names, and 13 pairs have both.
543- The two `WeatherCycles` names occur in other `common.rpf` documents (2 and 1 documents), not as weather types. 762- The two `WeatherCycles` names occur in other `common.rpf` documents (2 and 1 documents), not as weather types.
544 763
545Not measured here (hypothesis): what the `Mod*` axes do at runtime (they read as weather-app forecast 764Measured further in [weather.md](weather.md): the `Mod*` axes against the numeric fields, the exact-case
546attributes), how `TimeMult` scales a cycle, and what the `Honor*` values gate. 765vocabulary mismatches, `TimeMult`, and the `Honor*` values.
547 766
548## `OceanSimPresets` 767## `OceanSimPresets`
549 768
@@ -554,20 +773,40 @@ Its element tree (counts per path; no values or names):
554|---|---:|---| 773|---|---:|---|
555| `Presets/Item` | 10 | one preset per sea region | 774| `Presets/Item` | 10 | one preset per sea region |
556| `Presets/Item/Name`, `Id` | 10 each | region label and id | 775| `Presets/Item/Name`, `Id` | 10 each | region label and id |
557| `Presets/Item/Location` | 10 | `x`, `y` attributes in world units: x -7,995 to 3,183, y -4,572 to 8,645 | 776| `Presets/Item/Location` | 10 | `x`, `y`, `z` attributes in world units. The 10 elevations are distinct. Horizontal extents are x -7,995 to 3,183 and y -4,572 to 8,645. |
558| `Presets/Item/Direction` | 10 | wave direction | 777| `Presets/Item/Direction` | 10 | wave direction |
559| `Presets/Item/Octaves/Item` | 30 | exactly 3 per preset | 778| `Presets/Item/Octaves/Item` | 30 | exactly 3 per preset |
560| `Presets/Item/Octaves/Item/ControlPoints` | 30 | 4 `(x, y)` pairs each, both in 0..1 | 779| `Presets/Item/Octaves/Item/ControlPoints` | 30 | 4 `(x, y)` pairs each, both in 0..1 |
561| `WavefrontShapeA`, `B`, `G`, `R` `/Item/ControlPoints` | 1 each | one curve each | 780| `WavefrontShapeA`, `B`, `G`, `R` `/Item/ControlPoints` | 1 each | one curve each |
562 781
563So the ocean is a small set of regional presets placed by world position, each with three wave octaves whose 782The presets supply three octave curves per world position. A separate timecycle input,
564amplitude is a 4-point curve over a 0..1 input. The input is the sea state: the timecycle keyframe documents 783`water_ocean_beaufort_scale`, occurs 676 times across 26 keyframe documents and ranges from 0 to 10.
565carry a `water_ocean_beaufort_scale` variable (26 documents, 676 values, 0 to 10), the Beaufort number per 784
566weather and time of day. 785The authored curves and locations provide two controls for a runtime capture.
567 786
568Not measured here (hypothesis): which preset applies at a position (nearest `Location` is the obvious reading), 787- Hold position fixed at an authored site and compare the octave amplitudes at Beaufort 10. All 30 curves
569how the Beaufort number maps onto the 0..1 curve input (Beaufort / 12 is one choice), and what the four 788 have strictly increasing x and endpoints at x = 0 and x = 1. Under piecewise-linear interpolation, 19
570`WavefrontShape` curves drive. 789 differ by more than 0.000001 between inputs 1 and 5/6, the predictions for division by 10 and by 12.
790 The other 11 are unsuitable as controls at that weather setting. The interpolation is an assumption of this test.
791- Hold the normalized input at 1. In the horizontal (XY) plane, 11 of the 45 pairs of sites have a midpoint
792 closer to the pair than to any third site. At 49% and 51% along each of those 11 segments, the nearest site switches. In every
793 case at least one octave's endpoint amplitudes differ by more than 0.000001 across the pair. A hard
794 nearest-site rule predicts a step there. Samples approaching the midpoint from both sides can distinguish
795 that prediction from a continuous blend.
796- To test whether elevation enters the selection, hold XY at one of those midpoints. Evaluate the 3D distance
797 first at one site's elevation and then at the other's. The unique nearest site switches for all 11 pairs.
798 A selector using only XY sees identical inputs for both measurements.
799
800The ocean simulation technique has six compute programs. Four declare the same nine constant-buffer members
801in the same order and at the same byte offsets. In all four, the pipeline reflection binds one constant buffer
802at `b5, space1`. The other two declare zero members and zero constant buffers. To reproduce the program
803selection, run `python -I tools/sgd5_effects.py <shaders.rpf> --effect OceanWaveSim --technique oceanWaveSim`.
804Compare the member keys and offsets in each program's counted trailer against the other passes, then check
805the constant-buffer register in its `PSV0` reflection.
806
807Which preset applies at a position, how Beaufort maps to the curve input, and what the four `WavefrontShape`
808curves drive remain open. The reflected member keys give a concrete target for tracing the writer or comparing
809dispatch inputs with position and weather varied independently.
571 810
572## Timecycle documents 811## Timecycle documents
573 812
@@ -620,9 +859,84 @@ Modifiers come in two shapes:
62049 documents, so a submodifier is a by-name reference to another modifier, with its own blend attributes. 85949 documents, so a submodifier is a by-name reference to another modifier, with its own blend attributes.
621The one unresolved item points outside this archive or at a document lost to the unread region. 860The one unresolved item points outside this archive or at a document lost to the unread region.
622 861
862**Sample hours come from data.** One `time_data` document (root attributes `version` and `mode`) has exactly 13
863`sample` elements, each with `name`, `hour`, `uw_tc_mod` and `interpolation_type`, plus one `region`. The 13
864hours are integers from 0 to 22 in strictly increasing order, with gaps of 1 hour (7 times), 2 (twice), 3 (once)
865and 4 (twice); `interpolation_type` is `EASE_LINEAR_IN` on 9 samples and `EASE_QUARTIC_INOUT` on 4, and all 13
866`uw_tc_mod` values are the same name, which resolves to one of the 4,592 modifier names. The `region` name equals one of the two keyframe
867region names. So unlike GTA V, where the 13 sample times are compiled in, this build stores them in `time_data`;
868their count matches the 13 values of every keyframe variable. The `interpolation_type` labels are stored metadata:
869how the runtime selects the interval between two samples, and whether it applies the label, is not verified.
870
871The `hour` attributes of the 13 `sample` elements, in document order, are **0, 4, 5, 6, 7, 9, 12, 16, 18, 19, 20,
87221, 22**. They come from the one `time_data` payload of the `common.rpf` carve, at archive offset 1,773,568
873(`0x1b1000`): a single zlib stream, 268 B stored and 1,370 B inflated. The samples at hours 4, 20, 21 and 22
874carry the `EASE_QUARTIC_INOUT` label. That value *i* of a keyframe variable belongs to sample *i* is a
875hypothesis: it rests on the equal count and the document order, not on the executable. To export the sample
876records as JSON from a carve (the CLI prints summary counts; the JSON is game data and stays local):
877
878```
879python -I tools/gamedata_reader.py <work>/carve/common --root time_data --out <scratch>
880```
881
882Not measured here (hypothesis): how the two regions are chosen at runtime, what the two plain-modifier numbers
883are (GTA V reads them as a value pair blended by strength), and how `controlValue` maps onto game state.
884
885**The two plain-modifier numbers.** Measured over the 29,727 two-number variables of the plain modifiers
886(1,051 variable names, 3,257 modifiers with at least one such variable):
887
888- The second number is `0` in 26,186 pairs (88 %) and `1` in 3,104; only 437 take another value. In 2,300 of
889 the 3,257 modifiers it is `0` on every variable, in 21 it repeats the first number on every variable, and
890 936 mix. Per variable name, 624 names never have a non-zero second number (8,410 pairs), 83 always do
891 (1,289 pairs) and the other 344 vary from one modifier to the next.
892- The pair is not an ordered range: the first number is larger in 20,833 pairs, smaller in 4,604 and equal in
893 4,290.
894- Where the second number is non-zero (3,541 pairs) it does not follow the first: Pearson correlation 0.009,
895 and the first is `0` in 570 of them.
896- Against the keyframe documents (25,732 pairs with a second number of `0` whose name is also a keyframe
897 variable): `0` lies outside every value that variable takes in the 27 keyframe documents in 17,041 pairs,
898 but the first number is outside that range too in 15,183 of the same pairs. Plain-modifier values are not
899 bounded by the keyframe ranges, so this comparison does not tell what either number means.
900
901So `0` is the most frequent stored value of the second number. What it means, and how the runtime blends the
902two numbers by strength, is not settled by these counts.
903
623Not measured here (hypothesis): the hour of each of the 13 samples (GTA V's are fixed in code), how the two 904Not measured here (hypothesis): the hour of each of the 13 samples (GTA V's are fixed in code), how the two
624regions are chosen at runtime, what the two plain-modifier numbers are (GTA V reads them as a value pair 905regions are chosen at runtime, what the two plain-modifier numbers mean and how the runtime blends them (see
625blended by strength), and how `controlValue` maps onto game state. 906above), and how `controlValue` maps onto game state.
907**Plain-modifier number pairs `(a, b)`** (`tools/timecycle_pairs.py`, measured over all **29,727** two-number
908elements in the 4,291 plain modifiers across all 49 `timecycle_modifier_data` documents):
909
910| Measure | First number (`a`) | Second number (`b`) |
911|---|---:|---:|
912| Range (`min .. max`, median) | `-31,869.0 .. 400,000.0` (`0.789439`) | `-3.0 .. 5,000.0` (`0.0`) |
913| Distinct values (rounded to 6 dp) | 4,566 | 71 |
914| `< 0` | 2,972 (10.0%) | 7 (0.02%) |
915| `== 0` | 3,590 (12.1%) | 26,186 (88.1%) |
916| `(0, 1)` | 10,230 (34.4%) | 88 (0.30%) |
917| `== 1` | 6,973 (23.5%) | 3,104 (10.4%) |
918| `> 1` | 5,962 (20.1%) | 342 (1.15%) |
919
920Three patterns establish what the pair stores (matching RAGE's two-float `tcModData` slot):
921
9221. **`a` carries the variable's value; `b` is zero (`0.0`) on 88.1% of entries.** Across the 1,051 distinct plain
923 variables, 624 always have `b == 0.0`, 75 always have `b == 1.0`, and 343 appear with both `b == 0.0` and
924 `b == 1.0` (272 of them mixed within a single document, and 579 modifiers mix `0` and `1` across their own
925 variables) with the same physical range in `a`. A loader that applied `lerp(base, a, strength * b)` uniformly
926 would discard 88.1% of all modifier entries.
9272. **Fractional `b` in `(0, 1)` is a shared per-colour blend weight.** Only 18 variables ever take `b` outside
928 `{0, 1}`; 15 of them stay in `[0, 1]` (88 entries total). Across all **1,875 / 1,875** RGB triplets
929 (`*_r`/`*_g`/`*_b`) present in the same modifier, `b` is identical across all three channels (`1,554` with `0`,
930 `301` with `1`, `20` fractional — `0` mismatches).
9313. **Only three variables take `b` outside `[0, 1]` (349 entries, all keyframe variables), where `(a, b)` is a
932 same-unit value/range pair:** `far_clip` (`172/172` with `b > 1`, `a` in `0..5,000`, `b` in `40..5,000`,
933 `a == b` in 110, `a == 0` in 54, `0 < a < b` in 7, `a > b` in 1), `fog_start` (`161` with `b > 1`, `7` with
934 `b < 0`, `a` in `-1,000..5,000`, `b` in `-3..5,000`, `a == b` in 94, `a < b` in 89, `a > b` in 7), and
935 `fog_isotropic_phase` (`a == b` in all `10/10`, `1.0..6.0`).
936
937Not measured here (hypothesis): the hour of each of the 13 samples (GTA V's are fixed in code), how the two
938regions are chosen at runtime, the exact runtime rule distinguishing `b == 0` from `b == 1` on the 343 variables
939where both occur, and how `controlValue` maps onto game state.
626## Vehicle and tyre XML documents 940## Vehicle and tyre XML documents
627 941
628Four roots account for 37 of the 45 documents (4,547,932 inflated bytes) in the vehicles/tyres category: 942Four roots account for 37 of the 45 documents (4,547,932 inflated bytes) in the vehicles/tyres category:
@@ -714,14 +1028,15 @@ and 4 (twice); `interpolation_type` is `EASE_LINEAR_IN` on 9 samples and `EASE_Q
714region names. So unlike GTA V, where the 13 sample times are compiled in, this build reads them (and the easing 1028region names. So unlike GTA V, where the 13 sample times are compiled in, this build reads them (and the easing
715between them) from `time_data`; their count matches the 13 values of every keyframe variable. 1029between them) from `time_data`; their count matches the 13 values of every keyframe variable.
716 1030
717Not measured here (hypothesis): how the two regions are chosen at runtime, what the two plain-modifier numbers 1031Not measured here (hypothesis): how the two regions are chosen at runtime, the exact runtime rule distinguishing
718are (GTA V reads them as a value pair blended by strength), and how `controlValue` maps onto game state. 1032`b == 0` from `b == 1` on the 343 plain-modifier variables where both occur (see *Plain-modifier number pairs*
1033above), and how `controlValue` maps onto game state.
719 1034
720## Relationship to `data.rpf` and `script.rpf` 1035## Relationship to `data.rpf` and `script.rpf`
721 1036
722| Archive | Size | Streams | Inflated | Dominant payloads | XML | `RBF0` | `PSIN` | 1037| Archive | Size | Streams | Inflated | Dominant payloads | XML | `RBF0` | `PSIN` |
723|---|---:|---:|---:|---|---:|---:|---:| 1038|---|---:|---:|---:|---|---:|---:|---:|
724| `common.rpf` | 6.6 MB | 954 | 50.2 MB | XML/config, text, `MHIU`, `PAMH`, `SPS1Z` | 844 streams | 0 | 0 | 1039| `common.rpf` | 6.6 MB | 954 | 50.2 MB | XML/config, text, `MHIU`, `PAMH`, `SPS1` | 844 streams | 0 | 0 |
725| `data.rpf` | 481.5 MB | 28,509 | 1,403.3 MB | models/GPU pages, 1,263 `RBF0`, 2,281 `PSIN`, 3,132 resource pages | 0 | 1,263 | 2,281 | 1040| `data.rpf` | 481.5 MB | 28,509 | 1,403.3 MB | models/GPU pages, 1,263 `RBF0`, 2,281 `PSIN`, 3,132 resource pages | 0 | 1,263 | 2,281 |
726| `script.rpf` | 4.4 MB | 714 | 5.0 MB | 671 `PSIN` plus binary | 0 | 0 | 671 | 1041| `script.rpf` | 4.4 MB | 714 | 5.0 MB | 671 `PSIN` plus binary | 0 | 0 | 671 |
727 1042
@@ -777,30 +1092,69 @@ Measured over the 434 patches and 7,839 points:
777 `ShoreWaveMaxAmplitude` and `ShoreWaveWindScale` fields of the `CContentsOfWeatherXmlFile` weather data 1092 `ShoreWaveMaxAmplitude` and `ShoreWaveWindScale` fields of the `CContentsOfWeatherXmlFile` weather data
778 (its layout is documented in #1175). 1093 (its layout is documented in #1175).
779- **`maxDistance`** ranges 3.0 to 120.4 (median 74.9): how far the wave runs from the line. 1094- **`maxDistance`** ranges 3.0 to 120.4 (median 74.9): how far the wave runs from the line.
780- **`lateralCoord`** is a float in -2.94..3.50 with 7,820 distinct values. It is not arc length and not monotonic 1095- **`lateralCoord`** is a float in -2.94..3.50 with 7,820 distinct values. It is a coordinate *along* the line,
781 along 433 of the 434 patches, so it is not a running texture coordinate along the line. 1096 not across it: within a patch it is linear in arc length (distance along the polyline from the first point),
782 1097 `lateralCoord ≈ a + b × arc length`.
783Not measured here (hypothesis): what the five `waveType` values select, and what `lateralCoord` encodes (an 1098 - The least-squares fit leaves a median largest residual of 0.012 per patch (90th percentile 0.059).
784offset across the line is one reading). 1099 - The per-patch correlation with arc length has magnitude at least 0.994 on more than three quarters of the
1100 patches.
1101 - The rate is the same everywhere: |b| has a median of 0.00200 per world unit, so it changes by 1.0 every
1102 500 world units (median 500.4; 10th to 90th percentile 473 to 544). The median rate per `waveType` is 0.00199
1103 to 0.00202, so the wave type doesn't set it.
1104 - It *decreases* along the point order: strictly on 416 of the 434 patches, and b < 0 on 426. Only 197 of the
1105 7,405 point-to-point steps go against the patch's direction, by a median of 0.018. (It is monotonic, just not
1106 increasing; an earlier count here only tested increasing.)
1107 - On those 426 patches, `direction` points to the left of the polyline, so the coordinate runs the same way
1108 relative to the waves everywhere.
1109 - The offset a spreads over -2.0 to 3.4 (median 0.70), and a whole patch changes it by a median of -0.33. So
1110 neighbouring patches can continue one another rather than each starting at 0 (10 start within 1e-4 of 0).
1111
1112 Hypothesis, from the shape rather than a consumer: a phase or texture coordinate along the coast that repeats
1113 every 500 world units.
1114- **`waveType`** doesn't change `amplitude` (1.0 at every point of every type) or the `lateralCoord` rate, and the
1115 types overlap across the map. What differs:
1116 - Type 3 (147 patches) has the shortest reach: its `maxDistance` median is 64.6, with the only values below
1117 17 (down to 3.0). Types 0, 1 and 4 have medians of 72.4 to 78.1.
1118 - The six type 2 patches lie in one area (patch centres x 358 to 1,560, y -1,685 to 6,041). The other types
1119 span the whole coastline box.
1120
1121Not measured here: what the five `waveType` values select. Reach is the only measured difference besides type 2's
1122location; a consumer of the field would settle it.
785 1123
786## Readable vs binary 1124## Readable vs binary
787 1125
788Readable: the 266 XML documents, 3 text/INI-like files, and the two `MHIU` 2048 x 2048 1126Readable: the 266 XML documents, 3 text/INI-like files, and the two `MHIU` 2048 x 2048
789heightmaps plus the `PAMH` max/min heightmap and the `SPS1Z` header. The XML is ordinary text 1127heightmaps plus the `PAMH` max/min heightmap and the `SPS1` shader-preset table. The XML is ordinary text
790and can be consumed by any parser. `tools/gamedata_maps.py` decodes the `MHIU` row table and 1128and can be consumed by any parser. `tools/gamedata_maps.py` decodes the `MHIU` row table and
791packed heights and the `PAMH` row table and max/min arrays. `SPS1Z` is a NUL-separated 1129packed heights and the `PAMH` row table and max/min arrays, and `tools/gamedata_sps1.py` decodes the
792table of path/key strings with per-entry type/length markers; its structure is visible but its consumer is not 1130`858`-entry `SPS1` preset table and joins it to `shaders.rpf`'s `SGD5` effect records.
793implemented.
794 1131
795Not fully readable: the 8.6% unread span, the two opaque binary blobs, and the missing first blocks of the 9 1132Not fully readable: the 8.6% unread span, the two opaque binary blobs, and the missing first blocks of the 9
796tail-only documents (their retained tails are readable but incomplete). The encrypted table of contents is 1133tail-only documents (their retained tails are readable but incomplete). The encrypted table of contents is
797outside this work by rule; names and exact file boundaries stay unknown until a documented table reader exists. 1134outside this work by rule; names and exact file boundaries stay unknown until a documented table reader exists.
798 1135
1136## Text and binary tables (`tools/gamedata_blobs.py`)
1137
1138`tools/gamedata_blobs.py` decodes all five non-XML text and binary payloads in `common.rpf` (counts and structural
1139bounds only; zero names or raw bytes):
1140
1141| Payload | Inflated B (streams) | Format & measured structure |
1142|---|---:|---|
1143| `0x64e000` (`.fx` preload list 0) | 24,285 (1) | `965` unique `<effect>.fx` lines (`0` comments, `0` folder separators): all **910 of 910** `shaders.rpf` `SGD5` Database 0 effect records appear in exact index order (`0..909`), plus `55` unshipped `.fx` names |
1144| `0x64f1c0` (`.fx` preload list 1) | 575 (1) | `22` unique `<effect>.fx` lines (`0` comments): all **22 of 22** match `SGD5` Database 1 (`0x10289C81`) in exact index order (`0..21`) |
1145| `0x640000` (`VFX_SETTINGS_FILE` `.dat`) | 117,176 (2) | `3,198` lines: `2,566` data lines (`2,537` `<dotted.key> <scalar>` pairs, `2` `key = value` lines, `27` multi-value rows of `5..24` tokens), `248` comments, `384` blanks (`13` of `122` distinct key prefixes, `381` data lines, match an `SGD5` Database 0 effect name) |
1146| `0xad000` (fixed table) | 1,038,100 (16) | `u32 count = 801` followed by `801 x 1,296` B records to EOF (`4 + 801 x 1,296 = 1,038,100` B, `0` trailing bytes). Every record opens with `{u32 w0, u32 w1, u32 w2, u32 w3}` where `(w0, w1) == (w2, w3)` in **801 of 801** (`801` distinct pairs) before an undecoded `1,280`-byte record body (arithmetic permits `64 x 20` B; sub-record layout is not decoded by the tool) |
1147| `0x23c000` (3-region spatial grid) | 3,274,036 (50) | **Region 1** (`0x000000..0x07FFFF`, `131,072` `u32` cells): `32` empty `0xC0000000` sentinels and `131,040` populated cells whose low 23 bits point (`131,040 / 131,040` aligned) into **Region 3** (`0x166934..0x31F533`, EOF `0x31F534`, `451,328` `u32` words partitioned by the `46,019` distinct cell offsets into spans of `1..24` words); located as the trailing run of 4-byte-aligned offsets matching `min(cell_offs)` (`0x166934`), with every word (`451,328 of 451,328`) falling in **Region 2** (`0x080000..0x166933`, `944,436` B partitioned with zero gaps into `21,662` records: `21,273` of `44` B, `313` of `24` B, `76` of `12` B) |
1148
1149```powershell
1150python -I tools/gamedata_blobs.py <work>\carve\common --shaders shaders.rpf --json blobs.json
1151```
1152
799## Dirt and canned colours (`CGraphicsDefinitionsData`) 1153## Dirt and canned colours (`CGraphicsDefinitionsData`)
800 1154
801One `CGraphicsDefinitionsData` document holds the dirt/grime presets for peds, vehicles and props and the 1155One `CGraphicsDefinitionsData` document holds the dirt/grime presets for peds, vehicles and props and the
802colour table they draw from. Seven sections, each a list of `Item key="..."` records (counts; no values or 1156colour table they draw from. Seven sections, each a list of `Item key="..."` records (the table gives counts,
803names): 1157no values or names):
804 1158
805| Section | Items | Fields per item | `key` | 1159| Section | Items | Fields per item | `key` |
806|---|---:|---:|---| 1160|---|---:|---:|---|
@@ -809,7 +1163,7 @@ names):
809| `DirtDefinitions` | 24 | 25 (alpha curves and thresholds, vertex multipliers, normal/roughness/material contribution, spawn range, 6 `ClothHideDirtModifiers`) | equals `Name` in 22 of 24 | 1163| `DirtDefinitions` | 24 | 25 (alpha curves and thresholds, vertex multipliers, normal/roughness/material contribution, spawn range, 6 `ClothHideDirtModifiers`) | equals `Name` in 22 of 24 |
810| `VehDirtDefinitions` | 1 | 12, including a `DirtTunings` block of tile, detail-map, mud and modulate start/end values | equals `Name` | 1164| `VehDirtDefinitions` | 1 | 12, including a `DirtTunings` block of tile, detail-map, mud and modulate start/end values | equals `Name` |
811| `VehDirtControls` | 5 | 13 | equals `Name` | 1165| `VehDirtControls` | 5 | 13 | equals `Name` |
812| `VehSpawnIntensities` | 31 | 5 | equals `Name` | 1166| `VehSpawnIntensities` | 31 | Name, `IntensitySets` (7 `Item`s of `DirtMin`/`DirtMax`/`MudMin`/`MudMax`), `DirtRainChance`, `DirtRainMin`, `DirtRainMax` | equals `Name` |
813| `PropDirtDefinitions` | 9 | 4 | equals `Name` | 1167| `PropDirtDefinitions` | 9 | 4 | equals `Name` |
814 1168
815The keys are plain text, not joaat hashes, and a loader can index each section by `key`. 1169The keys are plain text, not joaat hashes, and a loader can index each section by `key`.
@@ -836,8 +1190,48 @@ with the `VehSpawnIntensities` keys, which is not evidence of a reference.
836`AlphaChannels` probabilities do not sum to 1 in any of the 7 entries, so they are not a probability 1190`AlphaChannels` probabilities do not sum to 1 in any of the 7 entries, so they are not a probability
837distribution over the listed channels (independent chances or weights would fit). The `Channel` values are 0, 1 or 2. 1191distribution over the listed channels (independent chances or weights would fit). The `Channel` values are 0, 1 or 2.
838 1192
839Not measured here (hypothesis): which texture channel numbering `Channel` uses, and how `VehSpawnIntensities` 1193**`Channel` numbers the mask texture's channels in component order: 0 = R, 1 = G, 2 = B** (ASSET-304). The
840are chosen at spawn. 1194dirt presets are ped presets, and `textures.rpf` holds one texture whose name marks it as the ped dirt masks
1195(1024×1024 BC7, 11 mips, next to the ped dirt normal/roughness map). `tools/mask_channels.py` on its export:
1196
1197| Channel | Range | Mean | Cover ≥ 64 / 128 | Blobs ≥ 64 / 128 | Largest blob ≥ 64 |
1198|---|---|---:|---:|---:|---:|
1199| R | 0-255 | 124.1 | 66.5% / 49.3% | 4,612 / 9,167 | 92.0% |
1200| G | 90-255 | 193.6 | 100% / 99.5% | 1 / 7 | 100% |
1201| B | 0-255 | 88.4 | 50.7% / 34.9% | 35,175 / 49,374 | 21.0% |
1202| A | 255 only | 255 | 100% | 1 | 100% |
1203
1204Alpha is constant, so the three `Channel` values can only be R, G and B; an order that counts alpha leaves one
1205value on a channel with nothing in it. G is a soft layer that never drops below 90, and the two entries whose names
1206describe a light dusty or urban grime use only `Channel` 1. R is a broad layer, one connected region at ≥ 64, and
1207the snow entry uses only 0. B is the speckled one, with 7.6 times R's blobs at ≥ 64, and the entry named for spots
1208uses only 2. The reversed order (0 = B) would put the spots on the broad layer and the snow on the speckled one.
1209The three mixed entries combine 0 and 2. Each tie is a name read against measured texture content, so this is
1210measured, not confirmed against the shader that samples the mask.
1211
1212Not measured here (hypothesis): how `VehSpawnIntensities` are chosen at spawn.
1213**Spawn intensities are keyed by vehicle class.** Measured on 2026-11-23 from one retail Xbox Series
12141.0.2.1 install with `tools/veh_spawn_intensities.py` (numbers and ranges only; the tool never prints
1215entry names). The 31 entries are 30 generic vehicle-class tokens plus one entry whose rain fields differ
1216from every other chance-0.5 entry; each carries 7 intensity bands, so the section's own "5 fields" summary
1217is top-level children only:
1218
1219| Measure | Value |
1220|---|---|
1221| `IntensitySets` bands per entry | 7 in all 31 |
1222| distinct band signatures | 9, carrying 12, 8, 3, 2, 2, 1, 1, 1, 1 entries |
1223| band 7 ranges over the signatures | `DirtMin` 0.353400..0.804305, `DirtMax` 0.450900..1.240000 |
1224| mud (a `MudMin`/`MudMax` above zero) | in band 6 of 1 signature, band 7 of 6 signatures; everywhere it exists the range is 0.8..1.0 |
1225| bands overlap | yes: each band is a draw range, not a partition (band 1's `DirtMax` exceeds band 2's `DirtMin` in the largest signature) |
1226| `DirtRainChance` groups | 4: 0.5 in 24 entries (`DirtRainMin` 0.818644 except one at 0.7), 0.0 in 6, 0.3 in 1 |
1227
1228Band 1 to band 7 in the largest signature ladder through the same recurring endpoints
1229(0.007828, 0.174168, 0.391389, 0.485323, 0.659491, 0.804305), so a run draws its dirt intensity from one
1230of the seven ranges, and rain applies another random factor gated by `DirtRainChance`. Each entry has 7
1231bands while `AlphaChannels` has 7 entries and `DirtDefinitions` references 5 of them; whether a spawn picks
1232one band per `AlphaChannels` entry is open.
1233
1234Not measured here (hypothesis): whether a spawn selects one `IntensitySets` band per `AlphaChannels` entry.
841 1235
842## Entity component sets and component LOD 1236## Entity component sets and component LOD
843 1237
@@ -932,8 +1326,6 @@ Four representative roots in the world/navigation/map category (826,397 B across
932 `o` in `Loopkup`.) Contains four keyed lookup tables (`key=`): 1326 `o` in `Loopkup`.) Contains four keyed lookup tables (`key=`):
933 - `LocationNames/Item` × 2,318 (`Name` on all 2,318; `TextureDictionary` and `Texture` on 46). 1327 - `LocationNames/Item` × 2,318 (`Name` on all 2,318; `TextureDictionary` and `Texture` on 46).
934 - `InteriorNames/Item` × 1,358, holding `2,280` nested `<Item>` records with `{Name, Pos}`. Their 2,280 3D positions 1328 - `InteriorNames/Item` × 1,358, holding `2,280` nested `<Item>` records with `{Name, Pos}`. Their 2,280 3D positions
935 span `x = -9,673.0..4,705.3`, `y = -7,308.0..8,589.9`, `z = -78.0..820.9` — 100% inside the world bounds of the
936 `PAMH` heightmap and `GridAtlasInfo` grids above.
937 span `x = -9,673.0..4,705.3`, `y = -7,308.0..8,589.9`, `z = -78.0..820.9` — their 2D `x`/`y` coordinates fall 100% 1329 span `x = -9,673.0..4,705.3`, `y = -7,308.0..8,589.9`, `z = -78.0..820.9` — their 2D `x`/`y` coordinates fall 100%
938 inside the `x`/`y` extent of the `PAMH` heightmap (`-13,312..5,120`, `-9,728..11,264`) and `GridAtlasInfo` grids 1330 inside the `x`/`y` extent of the `PAMH` heightmap (`-13,312..5,120`, `-9,728..11,264`) and `GridAtlasInfo` grids
939 above, while `z` reaches `820.9` (above the `PAMH` `404` m ceiling). 1331 above, while `z` reaches `820.9` (above the `PAMH` `404` m ceiling).
@@ -952,6 +1344,46 @@ Four representative roots in the world/navigation/map category (826,397 B across
952 `CAIConditionGatorPit` [36], `CAIConditionAmbientEventDirection` [5], `CAIConditionOr` [1], `CAIConditionAnd` [1]). 1344 `CAIConditionGatorPit` [36], `CAIConditionAmbientEventDirection` [5], `CAIConditionOr` [1], `CAIConditionAnd` [1]).
953 All **18 of 18** non-empty transition target `<Node>` references resolve to one of the 20 `CHazardNode` keys. 1345 All **18 of 18** non-empty transition target `<Node>` references resolve to one of the 20 `CHazardNode` keys.
954 1346
1347## Door interaction, ped loadouts, climbing, lasso and AI rule schemas
1348
1349Fourteen previously undocumented well-formed `common.rpf` documents span **1,682,656 inflated bytes** across **32**
1350streams. Counts, schemas, `type` classes and internal/cross-document key resolutions only; no entry names or values:
1351
1352### `CDoorInteractionDataList` (404,957 B, 7 streams, 5,831 elements)
1353
1354Fourteen top-level keyed sections (all 14 named across the reference paths and target sections below; `372` `key=` attributes, `979` `type=` attributes across `31` classes, `44` `content="matrix34"` transforms, `133` vectors, `791` `value=` scalars) form a self-contained internal lookup graph:
1355
1356| Section / reference path | Count | Resolves to / notes |
1357|---|---:|---|
1358| `DoorTypeToDataSetCollectionsMapping` / `List/Item` | 7 / 80 | `CDoorAssetList`; **80 of 80** resolve to `DataSetCollections` (`18` distinct) |
1359| `DataSetCollections` / `List/Item` | 21 / 60 | `CDoorAssetList`; **60 of 60** resolve to `DoorInteractionDataSets` (`56` of `56` sets) |
1360| `DoorInteractionDataSets` (`key=`, `type="CDoorInteractionDataSet"`) | 56 | `40` carry `parentPath`, all **40 of 40** resolving via `../Item[@key='...']` (`gamedata_graph.md`); `DoorType` (**20 of 20** → `DoorTypeToDataSetCollectionsMapping`), `OverlayDataSet` (**9 of 9** → `DoorInteractionAnimOverlayDataSets`), `PedHeadingData` (**11 of 11** non-empty → `DoorInteractionHeadingDatas`), `Interactions/Item` (**93 of 93** → `DoorInteractionDatas`), `PostAlignInteractions/Item` (**11 of 11** → `DoorInteractionPostAlignDatas`) |
1361| `DoorInteractionDatas` (`91`) & `DoorInteractionPostAlignDatas` (`11`) | 102 | `DoorType` (**91 of 91** on interactions), `BreakoutData` (**91 of 91** + **11 of 11** → `DoorInteractionBreakoutDatas` [`6`]), `UpperbodyRequestData` (**91 of 91** + **11 of 11** → `DoorInteractionUpperbodyPoseDatas` [`8`]), `MTHWeightData` (**73 of 73** non-empty → `DoorInteractionMTHDatas` [`3`]), `InterruptToIdleBlendout` (**7 of 7** → `DoorInteractionBodyBlendOutDatas` [`1`]), `PedHeadingData` (**11 of 11** on interactions; **73 of 73** non-empty across all `.//PedHeadingData` → `DoorInteractionHeadingDatas` [`5`]), `AnimData/UpperbodyBodyBlendFilterTemplateOrSelector` (**4 of 4** → `HashSelectors` [`1`]) |
1362| `DoorInteractionAnimOverlayDataSets` (`1`) & `DoorInteractionAnimOverlayDatas` (`8`) | 9 | `OverlayDatas/Item`: **8 of 8** resolve to `DoorInteractionAnimOverlayDatas` |
1363| `DoorInteractionUpperbodyPoseDatas` (`8`) & `UpperbodyPoseRequiredBlackboardVariables` (`4`) | 12 | `WeaponData1H/DesiredPose` (**8 of 8**) and `WeaponData2H/DesiredPose` (**8 of 8**) resolve to `UpperbodyPoseRequiredBlackboardVariables` |
1364
1365### Ped loadouts, task tuning, headbob, speeds, motivation and motion prediction
1366
1367| Root | Inflated B (streams) | Measured schema and key resolution |
1368|---|---:|---|
1369| `CPedInventoryLoadOutManager` | 411,101 (7) | `8,103` elements, `5` `type` classes (`1,692` nested `Items/Item` across the document): `LoadOuts/Item` × `569` (`Name`, `Items`, holding `1,013` direct items: `601` `CLoadOutWeapon`, `302` `CLoadOutRef`, `110` `CLoadOutRandom`) and `NamedLoadoutItems/Item` × `191` (`key=`: `136` `CLoadOutRandom`, `45` `CLoadOutWeapon`, `10` `CLoadOutRef`). `DefaultLoadout` resolves **1 of 1** to `LoadOuts`, and **521 of 521** `CLoadOutRef/Name` elements (`184` distinct) resolve case-insensitively to `NamedLoadoutItems` (`518 of 521` / `185` distinct under exact case); `CLoadOutWeapon` carries `551` `WeaponRecipe` and `546` `WeaponPreset` (`231` distinct) fields |
1370| `CTaskDataInfoManager` | 192,988 (3) | `3,532` elements (`2,990` `value=`): `aTaskData/Item` × `49` (`type="CTaskDataInfo"`, `27` distinct child fields) and `DefaultSet ref` (**1 of 1** → `aTaskData`). In `FleeStyleSets/{Base,InVehicle,OnMount}`, **47 of 49** entries each (`41` of `42` distinct) resolve case-insensitively to `aTaskData` (`16 of 49` / `13 of 42` under exact case) |
1371| `STPedNavigationPredictiontPresetContainer` | 92,999 (2) | `1,648` elements (`1,597` `value=`; preserves `Predictiont` spelling): `mapPredictionPresets/Item` × `14` (`key=`), holding `21` `arPredictionSetConfigs/Item` blocks (`1..8` per preset, `71..75` fields each, `81` distinct field names across the 21 blocks covering collision, capsule, drops, step-ups, walls, cover shadows, corners, slope and climb flags) |
1372| `STPedMotionPredictionSetContainer` | 50,327 (1) | `898` elements (`864` `value=`): `mapPredictionPresets/Item` × `10` (`key=`), holding `12` `arPredictionSets/Item` blocks (`1..3` per preset, `67` fields each from the same prediction-flag schema) |
1373| `CPedHeadbobSettingsManager` → `CHeadbobConditionManager` | 88,190 (2) + 16,610 (1) | `CPedHeadbobSettingsManager` (`1,347` elements) defines `OnFootSettings` (`12` `IntensitySettingsMap/Item`, `6` `BodyBlendSettingsMap/Item`) and `InTransportSettings` (`12` and `0`) across `CPedHeadbobSettings` (`2`), `CPedHeadbobIntensitySettings` (`24`) and `CPedHeadbobBodyBlendSettings` (`6`). All **84 of 84** `pCondition ref` links (`15` distinct) resolve **across documents** to `CHeadbobConditionManager/Conditions/Item/@key` (`18` `CHeadbobCondition` entries built from `CAICondition*` condition trees) |
1374| `CPedSpeedDataBlock` | 86,390 (2) | `2,248` elements (`1,455` `value=`, `0` `type=`): `Data/Item` × `16` (distinct `Name` entries, each with `WanderSpeeds`, `Default`, `Combat`, `Flee` over `{Walk,Jog,Run,Sprint}{Min,Max}` plus `QuadBike`, `EScooter`, `MobScooter`, `Caddy` × `16` and `Bike` × `15`, and `1` `ItemSpeeds/Item`) plus `DefaultItemSpeeds/Item` × `1` |
1375| `CPedMotivationInfoManager` | 32,388 (1) | `872` elements (`499` `value=`): `EventMotivationImpactProfiles/Item` × `7` (`key=`, `35` `EventTypes/Item` across `5` keys, `51` `MotivationImpacts/Item` pairs `{Motivation, ImpactParams}`), `PedMotivationDefinitions/Item` × `14`, and `aFearResponseProfiles/Item` × `4`; `DefaultFearProfileName` resolves **1 of 1** to `aFearResponseProfiles` |
1376
1377### Lasso, climbing, animal attack behaviours, relationships and AI search POIs
1378
1379| Root | Inflated B (streams) | Measured schema and key resolution |
1380|---|---:|---|
1381| `CLassoDataManager` | 126,639 (2) | `2,718` elements across `11` top-level sections (`99` `key=`, `692` `value=`, `380` 3D vectors with `7` `w`): `LassoHogtieFlagSets/Item` (`8`, referenced **24 of 24** by `ModelToLassoHogtieFlagsKey` plus all **3** default flag fields), `EntityLassoAttachInfo/Item` (`18`, referenced **26 of 26** by `ModelNameToEntityLassoAttachInfo` plus `DefaultHumanEnityLassoAttachInfo` and `DefaultHorseEnityLassoAttachInfo` [`Enity` preserved in XML]), and `LassoAttachments/Item` (`23`, referenced **18 of 18** by `DefaultAttachment` and **20 of 20** by `Attachments/Item`), plus `LassoWeaponLoopBoneTags/Item` × `15` |
1382| `CAnimalAttackBehaviours` | 55,388 (1) | `877` elements (`378` `type=`): `Behaviours/Item` × `6` (`type="CAnimalAttackBehaviour"`, `{Name, AnimalTuning, Task, Triggers}`) holding `64` `CAnimalAttackTrigger` entries, `58` gated by `CAICondition*` boolean trees (`308` nodes across `32` condition classes, led by `CAIConditionAnd` [`53`], `CAIConditionNot` [`31`], `CAIConditionDistanceBetweenEntities` [`21`]) |
1383| `CClimbTuneMgr` | 54,137 (1) | `1,102` elements across `12` top-level sections (`TraversalData`, `LandData`, `PlayerClimbData` [20 scalars], `PlayerStepUpData` [15 scalars], `PlayerLedgeGrabData` [16 entries], `PlayerJumpData` [11 entries], `AnimalJumpData` [11 scalars], `InputControlData` [4 scalars], `aClimbParams/Item` × `2` [`CClimbParams`], `aDropdownDetectorParams/Item` × `2` [`CDropDownDetectorParams`, with `matOverride` `content="matrix34"`]); `DefaultClimbParams ref` and `DefaultDropDownParams ref` resolve **1 of 1** each |
1384| `Relationships__GroupsData` | 35,555 (1) | `554` elements: `Groups/Item` × `64` (`key=`) containing `423` `Relationships/Item` entries across `4` relationship-level text values (`62` distinct targets); all **423 of 423** resolve internally to `Groups/Item/@key` |
1385| `CSearchPointOfInterestRuleSet` | 34,987 (1) | `684` elements (`47` `CAICondition*` nodes across `14` classes): `PointOfInterestDefinitions/PointOfInterest` × `12` (`key=`) and `SearchSituations/Situation` × `13` (`key=`). All **112 of 112** `AllowedPointsOfInterest/Type/@key` (`12` of `12` POIs) resolve to `PointOfInterestDefinitions`, and all **7 of 7** non-empty `NextSituation` links (`6` distinct) resolve to `SearchSituations` |
1386
955## No-sharing rule 1387## No-sharing rule
956 1388
957The archive, every carved `.bin`, `index.json` (its `head`/`pre` fields contain payload bytes), XML 1389The archive, every carved `.bin`, `index.json` (its `head`/`pre` fields contain payload bytes), XML
diff --git a/docs/gamedata_graph.md b/docs/gamedata_graph.md
index 7b58ffef5..de247ed7c 100644
--- a/docs/gamedata_graph.md
+++ b/docs/gamedata_graph.md
@@ -8,7 +8,8 @@ name or target path is committed.
8 8
9`tools/gamedata_graph.py` rebuilds the documents with `gamedata_index.py` and 9`tools/gamedata_graph.py` rebuilds the documents with `gamedata_index.py` and
10`gamedata_xml.load_documents`, then keeps the reference strings long enough to join them. It is 10`gamedata_xml.load_documents`, then keeps the reference strings long enough to join them. It is
11standard-library only and reads the same carve as the index and catalog. 11standard-library only and reads the same carve as the index and catalog. XML with an unsupported
12encoding counts as an unparsed payload; it supplies no edges and does not stop the other documents.
12 13
13## Graph model 14## Graph model
14 15
diff --git a/docs/gameinput.md b/docs/gameinput.md
index 90e0a3d2e..4b617b487 100644
--- a/docs/gameinput.md
+++ b/docs/gameinput.md
@@ -227,7 +227,9 @@ intensity 0; waveform indices other than 0 are `E_INVALIDARG`.
227Pads whose SDL gamepad reports both a gyroscope and an accelerometer (a DualSense, a Switch Pro, Steam Input pads) get 227Pads whose SDL gamepad reports both a gyroscope and an accelerometer (a DualSense, a Switch Pro, Steam Input pads) get
228`GameInputKindMotion` in `supportedInput` and a `motionInfo` (`GameInputMotionInfo`, Microsoft's v0 layout); `IGameInputReading::GetMotionState` 228`GameInputKindMotion` in `supportedInput` and a `motionInfo` (`GameInputMotionInfo`, Microsoft's v0 layout); `IGameInputReading::GetMotionState`
229returns a `GameInputMotionState` on their readings, and `GetCurrentReading`/`GetNextReading` answer a 229returns a `GameInputMotionState` on their readings, and `GetCurrentReading`/`GetNextReading` answer a
230`GameInputKindMotion` query for such a pad and return `GAMEINPUT_E_READING_NOT_FOUND` for a pad without sensors. The 230`GameInputKindMotion` query for such a pad and return `GAMEINPUT_E_READING_NOT_FOUND` for a pad without sensors. A
231reading callback registered for `GameInputKindMotion` hears only such pads: like a device callback, it is limited to
232devices that support at least one of the kinds it names (Microsoft's `RegisterReadingCallback` reference). The
231sensors are enabled when the pad is opened, at SDL's requested rate, and every poll reads the latest sample. 233sensors are enabled when the pad is opened, at SDL's requested rate, and every poll reads the latest sample.
232 234
233- The state carries **signed fractions of the maxima `motionInfo` reports** (1.0 = full magnitude), which is the 235- The state carries **signed fractions of the maxima `motionInfo` reports** (1.0 = full magnitude), which is the
@@ -451,8 +453,8 @@ rests on a transcription rather than on a side-by-side compile.
451 first twin's id equal to the single-pad id). Motion runs on a virtual pad with sensors (`nsensors` in the 453 first twin's id equal to the single-pad id). Motion runs on a virtual pad with sensors (`nsensors` in the
452 virtual-joystick description, fed with `SDL_SendJoystickVirtualSensorData`): the kind and `motionInfo` on a sensor 454 virtual-joystick description, fed with `SDL_SendJoystickVirtualSensorData`): the kind and `motionInfo` on a sensor
453 pad and not on a plain one, no motion before the first sample, normalisation against the `motionInfo` maxima, the 455 pad and not on a plain one, no motion before the first sample, normalisation against the `motionInfo` maxima, the
454 accuracy values, the ±1 clamp, the ~8 ms cadence, and that a motion query on a pad without sensors is 456 accuracy values, the ±1 clamp, the ~8 ms cadence, that a motion query on a pad without sensors is
455 `GAMEINPUT_E_READING_NOT_FOUND`. The keyboard pad is 457 `GAMEINPUT_E_READING_NOT_FOUND`, and that a Motion reading callback hears only the sensor pad. The keyboard pad is
456 driven through `rt::gameinput::set_keyboard_source` and `set_cursor_source` with fake keys, focus and cursor: every 458 driven through `rt::gameinput::set_keyboard_source` and `set_cursor_source` with fake keys, focus and cursor: every
457 binding, two keys at once, each WASD direction, opposite keys cancelling, diagonals, the mouse moving the right 459 binding, two keys at once, each WASD direction, opposite keys cancelling, diagonals, the mouse moving the right
458 stick, clamping and decaying to 0, the mouse-button triggers, no input out of focus, release of buttons, sticks and 460 stick, clamping and decaying to 0, the mouse-button triggers, no input out of focus, release of buttons, sticks and
@@ -464,6 +466,22 @@ rests on a transcription rather than on a side-by-side compile.
464 tables, the kind and status bits, a reading's raw report (newest declared id, without the id byte, an undeclared id 466 tables, the kind and status bits, a reading's raw report (newest declared id, without the id byte, an undeclared id
465 ignored), creating, sending and reading back output and feature reports with their id byte, `SetRawData`'s exact 467 ignored), creating, sending and reading back output and feature reports with their id byte, `SetRawData`'s exact
466 size, the item calls, `E_INVALIDARG` / `E_FAIL` / `E_NOTIMPL`, and the HID device closing on unplug. 468 size, the item calls, `E_INVALIDARG` / `E_FAIL` / `E_NOTIMPL`, and the HID device closing on unplug.
469- `gameinput_probe [--seconds N] [--rumble] [--force-feedback]` (by hand, with a pad connected): lists the pads with
470 each one's raw HID report tables (or why it has none), plays each motor and trigger for a second with `--rumble`,
471 holds a constant force at magnitude 1.0 on motor 0 for a second with `--force-feedback` (skipped, with the reason
472 printed, on a pad the shim reports no force-feedback motor for), and prints whether SDL created that effect and is
473 running it, separately from GameInput accepting it, then prints the live reading and the newest raw input report.
474
475On hardware so far, with `gameinput_probe` and SDL 3.4.20 on Windows 11: a DualSense (`054c:0ce6`) over USB. It
476connects as player 1 with trigger effects and gyro (`motors=0xf forcefeedback=0 haptic=2`). Pressed one at a time,
477each of the 14 gamepad buttons set the one bit of the name [Mapping](#mapping) gives it: Cross, Circle, Square and Triangle
478as `A`, `B`, `X` and `Y`, the d-pad, L1/R1, L3/R3, Create as `View` and Options as `Menu`. Both triggers reached
4791.00 and both sticks -1.00 and +1.00 on each axis. At rest the accelerometer read about 0.5 on one axis and the gyro
4800.0; shaking the pad by hand reached 1.00 on the accelerometer. With `--rumble` (the default `rumble` trigger mode)
481and `LEONIDA_DS_LIGHTBAR=00ff00`, the person holding the pad reported the motors, the trigger effects and the lightbar
482as working; nothing measured them, and the `resistance` mode was not tried.
483 size, the item calls, `E_INVALIDARG` / `E_FAIL` / `E_NOTIMPL`, the HID device closing on unplug, and a held
484 reading's `GetRawReport` waiting while a reconnect rebuilds the report tables.
467- `gameinput_probe [--seconds N] [--rumble]` (by hand, with a pad connected): lists the pads with each one's raw HID 485- `gameinput_probe [--seconds N] [--rumble]` (by hand, with a pad connected): lists the pads with each one's raw HID
468 report tables (or why it has none), plays each motor and trigger for a second with `--rumble`, then prints the live 486 report tables (or why it has none), plays each motor and trigger for a second with `--rumble`, then prints the live
469 reading and the newest raw input report. 487 reading and the newest raw input report.
@@ -489,7 +507,8 @@ These need the game executable or a test on hardware:
489- **`UnregisterCallback` timeout** is not honoured; it waits for a callback that is running. 507- **`UnregisterCallback` timeout** is not honoured; it waits for a callback that is running.
490- **Motion normalisation maxima** (2 g accel, 2000 deg/s gyro) are this shim's choice; SDL exposes no sensor range, 508- **Motion normalisation maxima** (2 g accel, 2000 deg/s gyro) are this shim's choice; SDL exposes no sensor range,
491 and whether the game reads motion, and against what scale, is unknown until it runs. The accelerometer range a 509 and whether the game reads motion, and against what scale, is unknown until it runs. The accelerometer range a
492 DualSense exposes can also be wider than 2 g, so hard shakes may clamp at 1.0. 510 DualSense exposes can also be wider than 2 g, so hard shakes may clamp at 1.0: a hand shake of a real DualSense
511 did reach 1.00 on one axis.
493- **Motion members the shim does not provide** (magnetic field, orientation) are zero with 512- **Motion members the shim does not provide** (magnetic field, orientation) are zero with
494 `GameInputMotionAccuracyUnknown`; whether a title wants a synthesised quaternion there is unknown. 513 `GameInputMotionAccuracyUnknown`; whether a title wants a synthesised quaternion there is unknown.
495- **Device family**: every pad is reported as `GameInputFamilyXboxOne`; a title that filters on family sees only 514- **Device family**: every pad is reported as `GameInputFamilyXboxOne`; a title that filters on family sees only
@@ -525,11 +544,15 @@ These need the game executable or a test on hardware:
525- **Haptic waveforms**: the single intensity waveform (usage 0x0F/0x58) is this shim's choice, not the pad's table, so 544- **Haptic waveforms**: the single intensity waveform (usage 0x0F/0x58) is this shim's choice, not the pad's table, so
526 a title that asks for a particular waveform gets intensity-only behaviour. Whether the game uses haptic motors at 545 a title that asks for a particular waveform gets intensity-only behaviour. Whether the game uses haptic motors at
527 all — as opposed to `SetRumbleState` — is unknown. 546 all — as opposed to `SetRumbleState` — is unknown.
528- **Raw HID on a real pad**: only the synthetic tests and the XInput refusal have run. 547- **Raw HID on a real pad**: the synthetic tests, the XInput refusal and one DualSense over USB have run.
529 - What ran: an Xbox Series X controller over Bluetooth on Windows 11 connects and plays normally, with no raw I/O, 548 - What ran: an Xbox Series X controller over Bluetooth on Windows 11 connects and plays normally, with no raw I/O,
530 and the log names the reason. 549 and the log names the reason.
531 - Still to confirm: a DualSense, DualShock 4 or Switch Pro through `gameinput_probe`, which should print the 550 - What ran: a DualSense (`054c:0ce6`) over USB on Windows 11 through `gameinput_probe`. Its descriptor gives 1
532 descriptor's reports and changing raw input bytes. 551 input report (id 1, 63 bytes), 1 output report (id 2, 47 bytes) and 20 feature reports, and the raw input report
552 changed on every reading (2,442 distinct reports in a 40 s capture). No output or feature report was sent
553 through the raw calls.
554 - Still to confirm: a DualSense over Bluetooth, a DualShock 4 or a Switch Pro through `gameinput_probe`, which
555 should print the descriptor's reports and changing raw input bytes.
533 - Size convention: report sizes exclude the id byte, and `GetRawData` returns the payload without it. What 556 - Size convention: report sizes exclude the id byte, and `GetRawData` returns the payload without it. What
534 Microsoft's runtime does for a device with report ids is not documented on the reference pages. 557 Microsoft's runtime does for a device with report ids is not documented on the reference pages.
535 - Readings: a pad that streams reports makes a reading for each changed one, like the runtime's 558 - Readings: a pad that streams reports makes a reading for each changed one, like the runtime's
diff --git a/docs/gbuffer.md b/docs/gbuffer.md
index eae783c60..936c6ea85 100644
--- a/docs/gbuffer.md
+++ b/docs/gbuffer.md
@@ -10,37 +10,43 @@ Counts, target masks, numeric constants and format requirements only; no shader
10## 1. Corpus census of deferred pixel-shader output signatures (`OSG1` / `PSV0`) 10## 1. Corpus census of deferred pixel-shader output signatures (`OSG1` / `PSV0`)
11 11
12Every DXBC container in `shaders.rpf` carries an `OSG1` (and `PSV0`) output signature table with `{register, 12Every DXBC container in `shaders.rpf` carries an `OSG1` (and `PSV0`) output signature table with `{register,
13semantic_index, component_type, mask, min_precision}` per `SV_TargetN` output, and the unpacked FSSM header records the 13semantic_index, component_type, mask, min_precision}` per declared output element. (The FSSM header dword at `+0x0FC`
14exported target count as `u32` at `+0x0FC`. 14holds `5` and `6` on the two sampled `PS_DeferredTextured` blobs below, but holds `16` and `18` on two stock vehicle
15deferred passes, so target counts must be read from `OSG1` rather than FSSM `+0x0FC`.)
15 16
16Across the **2,989** pixel shaders with `Deferred` in their container name (including **807** `PS_DeferredTextured` 17Depending on whether container names are matched case-insensitively on raw RPF entry names (`2,989` pixel shaders) or
17variants: 380 five-target, 371 six-target and 56 three-target): 18case-sensitively on `Deferred` in the carved `.dxbc` file stems (`3,004` pixel shaders, including `807`
19`PS_DeferredTextured` variants: 380 five-target, 371 six-target and 56 three-target):
18 20
19| Targets declared (`+0x0FC` / `OSG1`) | `*Deferred*` PS count | `PS_DeferredTextured` count | Corpus-wide PS count | `OSG1` component type on all colour targets | Per-target `OSG1` write masks (`SV_Target0..N-1`) | 21| `OSG1` outputs declared | `*Deferred*` PS (entry match / `.dxbc` stem match) | `PS_DeferredTextured` count | Corpus-wide PS (entry / `.dxbc` stem) | `OSG1` component type on all colour targets | Per-target `OSG1` write masks (`SV_Target0..N-1`) |
20|---:|---:|---:|---:|---|---| 22|---|---:|---:|---:|---|---|
21| 6 (`SV_Target0..5`) | 953 | 371 | 955 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3, 0xF` (`mrt4` is 2-component `RG`) | 23| 6 colour (`SV_Target0..5`) | 953 / 949 | 371 | 955 / 955 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3, 0xF` (`SV_Target4` mask is 2-component `RG`) |
22| 6 (`SV_Target0..5`) | 737 | 0 | 747 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF, 0xF` (all six `RGBA`) | 24| 6 colour (`SV_Target0..5`) | 737 / 735 | 0 | 747 / 747 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF, 0xF` (all six `RGBA`) |
23| 5 (`SV_Target0..4`) | 1,160 | 380 | 1,168 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` (`mrt4` is 2-component `RG`) | 25| 5 colour + `SV_Depth` | 0 / 0 | 0 | 1 / 0 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` + `SV_Depth` (`0x1`) |
24| 5 (`SV_Target0..4`) | 2 | 0 | 20 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF` | 26| 5 colour (`SV_Target0..4`) | 1,160 / 1,160 | 380 | 1,168 / 1,166 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` (`SV_Target4` mask is 2-component `RG`) |
25| 3 (`SV_Target0..2`) | 125 | 56 | 248 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0x3` (`mrt2` is 2-component `RG`) | 27| 5 colour (`SV_Target0..4`) | 2 / 2 | 0 | 20 / 20 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF` |
26| other (`0, 1, 2, 4` or `5 + SV_Depth`) | 12 | 0 | — | `float32` (3 single-target `uint32`) | depth-only, discard, or reduced passes | 28| 3 colour (`SV_Target0..2`) | 125 / 125 | 56 | 248 / 248 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0x3` (`SV_Target2` mask is 2-component `RG`) |
29| other (`0..4` outputs) | 12 / 33 | 0 | — | `float32` (3 single-target `uint32`) | depth-only, discard, or reduced passes |
27 30
28In the compiled RDNA2 code of every 5-target and 6-target `PS_DeferredTextured` variant, all exported targets 31The two six-colour-target rows total **1,702** pixel shaders corpus-wide (`955 + 747`; plus 1 five-colour-target +
29(`mrt0..mrt4` or `mrt0..mrt5`) pack their outgoing register pairs with `v_cvt_pkrtz_f16_f32` and export them with 32`SV_Depth` shader with 6 `OSG1` rows = 1,703 six-row `OSG1` tables). In the compiled RDNA2 code across the `*Deferred*`
30`exp mrtN, ... compr` (`EXP_FORMAT_FP16_ABGR`). 33pixel shaders, **16,306 of 16,306 (100%)** `exp mrtN` instructions use compressed half-float export (`compr`,
34`EXP_FORMAT_FP16_ABGR`), fed by `v_cvt_pkrtz_f16_f32`.
31 35
32## 2. G-buffer target layout (`mrt0..mrt5`) 36## 2. G-buffer target layout (`mrt0..mrt5`)
33 37
34Confirming #1891 against the 5-target (`mrt0..mrt4`) and 6-target (`mrt0..mrt5`) `PS_DeferredTextured` programs: 38Comparing #1891 against the 5-target (`mrt0..mrt4`) and 6-target (`mrt0..mrt5`) `PS_DeferredTextured` programs (note
39that the RTV format column below is **inferred from the shader-side encoding and #1891**, not declared by `OSG1` or a
40captured PSO):
35 41
36| Target | `OSG1` mask | Expected RTV format class | Channel layout and encoding in `PS_DeferredTextured` | 42| Target | `OSG1` mask | Inferred RTV format class (from shader encoding / #1891) | Channel layout and shader-side encoding in `PS_DeferredTextured` |
37|---|---|---|---| 43|---|---|---|---|
38| `mrt0` (`SV_Target0`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Albedo + alpha/material byte:** `rgb` holds base colour/albedo; in 6-target variants `a` packs a byte extracted from an integer register and scaled by `1.0 / 255.0` (`0x3b808081`). | 44| `mrt0` (`SV_Target0`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Albedo + alpha/material byte:** `rgb` holds base colour/albedo; in the sampled 6-target variant `a` packs a byte extracted from an integer register (`ubyte0`) and scaled by `1.0 / 255.0` (`0x3b808081`). |
39| `mrt1` (`SV_Target1`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Scalar in `r` + 24-bit octahedral world normal split across `g`, `b`, `a`:** see section 3 below. | 45| `mrt1` (`SV_Target1`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Scalar in `r` + 24-bit octahedral world normal split across `g`, `b`, `a`:** see section 3 below. |
40| `mrt2` (`SV_Target2`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Square-root encoded material/specular channels:** `rgb` values pass through hardware square root (`sqrt(x)`, or `sqrt(1.0 - sqrt(x))` on 6-target variants) before export so the deferred lighting pass squares them back; `a` holds an unencoded `[0, 1]` scalar (`0.5` or a conditional select). | 46| `mrt2` (`SV_Target2`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Square-root encoded channels:** producer applies hardware square root (`sqrt(x)` or `sqrt(1.0 - sqrt(x))`) before `v_cvt_pkrtz_f16_f32` export; #1891 notes that the lighting consumer squares `mrt2` back (tentatively specular / $F_0$ material terms, pending lighting-consumer verification). |
41| `mrt3` (`SV_Target3`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Flags + byte IDs:** `x` and `y` carry clamped `[0, 1]` material/shading flags biased by a dither term (`scale = 2.0 / 255.0` = `0x3c008081`, `offset = -1.0 / 255.0` = `0xbb808081`); `z` and `w` carry two 8-bit integer IDs extracted with byte-to-float conversion (`ubyte0`, `ubyte1`) and multiplied by `1.0 / 255.0` (`0x3b808081`). | 47| `mrt3` (`SV_Target3`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Flags + byte IDs:** `x` and `y` carry clamped `[0, 1]` values biased by a dither term (`scale = 2.0 / 255.0` = `0x3c008081`, `offset = -1.0 / 255.0` = `0xbb808081`); `z` and `w` carry two 8-bit integer IDs extracted with byte-to-float conversion (`ubyte0`, `ubyte1`) and multiplied by `1.0 / 255.0` (`0x3b808081`). |
42| `mrt4` (`SV_Target4`) | `0x3` (`RG`, 2,113 deferred PS) or `0xF` (`RGBA`, 739 deferred PS) | Float format (e.g. `R16G16_FLOAT`) | **Motion vectors:** unscaled signed float screen-space motion offset (`xy`, with `zw` disabled as `off, off` on the 2,113 `mask = 0x3` variants). | 48| `mrt4` (`SV_Target4`) | `0x3` (`RG`, 2,113 / 2,109 deferred PS) or `0xF` (`RGBA`, 739 / 737 deferred PS) | Float format (e.g. `R16G16_FLOAT`) | **Motion vectors:** unscaled signed float screen-space motion offset (`xy`; in the sampled 5- and 6-target `PS_DeferredTextured` disassembly with `mask = 0x3`, exported as `exp mrt4, vN, vN, off, off compr`). |
43| `mrt5` (`SV_Target5`) | `0xF` (`RGBA`, 1,690 deferred PS) | `R8G8B8A8_UNORM` | **Sixth deferred target** on the 6-target permutations (`rgb` material terms + clamped alpha). | 49| `mrt5` (`SV_Target5`) | `0xF` (`RGBA`, 1,690 / 1,684 deferred PS) | `R8G8B8A8_UNORM` | **Sixth deferred target** on the 6-target permutations (`rgb` material terms + clamped alpha). |
44 50
45## 3. The 24-bit octahedral normal in `mrt1.gba` and why binding `f16` targets breaks lighting 51## 3. The 24-bit octahedral normal in `mrt1.gba` and why binding `f16` targets breaks lighting
46semantic_index, component_type, mask, min_precision}` per declared output element. (The FSSM header dword at `+0x0FC` 52semantic_index, component_type, mask, min_precision}` per declared output element. (The FSSM header dword at `+0x0FC`
@@ -96,7 +102,7 @@ captured PSO):
96 multiplied by `1.0 / 255.0` (`0x3b808081`), rounded toward zero to `f16` (`v_cvt_pkrtz_f16_f32`), and exported to 102 multiplied by `1.0 / 255.0` (`0x3b808081`), rounded toward zero to `f16` (`v_cvt_pkrtz_f16_f32`), and exported to
97 `mrt1.g`, `mrt1.b`, and `mrt1.a`. 103 `mrt1.g`, `mrt1.b`, and `mrt1.a`.
98 104
99### Consequence for the runtime and test harnesses 105### Arithmetic across all 256 byte values and consequence for the runtime
100 106
101- **Declared signatures do not separate `UNORM8` from `FLOAT16`:** because `OSG1` and `PSV0` declare `float32` on all 107- **Declared signatures do not separate `UNORM8` from `FLOAT16`:** because `OSG1` and `PSV0` declare `float32` on all
102 six `SV_Target0..5` outputs and the RDNA2 code uses `exp mrtN ... compr` (`EXP_FORMAT_FP16_ABGR`) for all of them, 108 six `SV_Target0..5` outputs and the RDNA2 code uses `exp mrtN ... compr` (`EXP_FORMAT_FP16_ABGR`) for all of them,
diff --git a/docs/gpu_test_results.md b/docs/gpu_test_results.md
new file mode 100644
index 000000000..f92d02d19
--- /dev/null
+++ b/docs/gpu_test_results.md
@@ -0,0 +1,33 @@
1# GPU test results
2
3This page keeps a local record of GPU test runs. The project's public tracker is
4[#166](https://github.com/ItsNotRexed/Leonida/issues/166) (one comment per GPU and driver);
5post counts and pass/fail lines there, never game shaders, logs or private paths.
6
7| GPU | Driver, OS | Commit | build.py | check.py | run_gpu_tests.py | Failed | Entry |
8|---|---|---|---|---|---|---|---|
9| AMD Radeon RX 9070 GRE (RDNA4, GFX1201), subgroup 32..64 | RADV, Mesa 26.3.1-arch3.5, Vulkan 1.4.363, CachyOS | `05961f0` | 264/264 translated and valid | 203/206 pass, 3 skipped | 218/235 passed, 16 skipped (native and emulated) | `ms_wave_info_s3`, flaky (see below) | [local note](gpu-test-results/RX9070GRE.txt) |
10
11## AMD Radeon RX 9070 GRE — 2026-11-23
12
13```
14GPU: AMD Radeon RX 9070 GRE (RDNA4 / GFX1201, Navi 48, PCI 1002:7550), subgroup 32..64
15Driver: RADV (Mesa 26.3.1-arch3.5), Vulkan 1.4.363
16Subgroup: 32..64 (minSubgroupSize 32, maxSubgroupSize 64; default 64)
17OS: CachyOS, kernel 7.3.5-2-cachyos
18Commit: 05961f0eeb24486ce25ddc7dfb453ca87db2be5f (main, 2026-11-23)
19Tools: llvm-mc 23.1.5 (native), SPIRV-Tools v2026.4, CMake 4.4.5 + Ninja 1.13.2, GCC 16.2.1, Python 3.14.9
20build.py: 264 shaders: 264 translated, 264 pass spirv-val (6 mesh fixtures not built: ms_clip, ms_f16_pack, ms_tri, ms_v5_workgroup, ms_w64x_ballot, ms_wave_info_s3)
21check.py: 203 of 206 pass, 3 skipped (the three mesh fixtures built only by run_gpu_tests.py)
22run_gpu_tests.py: 218/235 passed, 16 skipped, 1 failed (native and LEONIDA_W64_EMULATE=1 alike)
23Failed: ms_wave_info_s3: at (0,0) got (-1,-1,-1,-1), want (0.0078,0.0078,0.5,1.0). Flaky on this RADV GPU: 1 pass and 2 fails in three isolated --filter reruns; same signature as the known round-44 mesh regression (#6172, fixed by #5741/#5855). Not a new failure.
24Skipped: 16 skips are the documented "run by d3d12_*_test / w64_graphics.py" cases.
25```
26
27Setup: `cmake -S runtime -B runtime/build/linux -G Ninja -DCMAKE_BUILD_TYPE=Release -DLEONIDA_VULKAN_HEADERS_FETCH=ON`;
28implicit Vulkan layers disabled (`VK_LOADER_LAYERS_DISABLE='~implicit~'`) because MangoHud/Steam layers are installed.
29Inside `run_gpu_tests.py`, 241/241 shaders translated and passed `spirv-val` in both the native and emulated runs.
30Every pixel test other than the flaky mesh fixture was exact (4096/4096).
31
32AI-assisted (Hermes Agent): built `main` at `05961f0`, ran `build.py`, `check.py` and
33`run_gpu_tests.py` (native and emulated) on this GPU, and verified the isolated reruns of the one failure.
diff --git a/docs/i18n/README.md b/docs/i18n/README.md
index 021bd233b..42552796e 100644
--- a/docs/i18n/README.md
+++ b/docs/i18n/README.md
@@ -12,14 +12,14 @@ A language is added when a contributor volunteers to maintain it and keeps the s
12 12
13| Language | File | Synced commit | Maintainer | 13| Language | File | Synced commit | Maintainer |
14|---|---|---|---| 14|---|---|---|---|
15| Français (`fr`) | [`fr/quickstart.md`](fr/quickstart.md) | `e7584c52` | `@Urban225` | 15| Français (`fr`) | [`fr/quickstart.md`](fr/quickstart.md) | `aa2988cc` | `@Urban225` |
16| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `f847748c` | `@Andretuta` | 16| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `f847748c` | `@Andretuta` |
17| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `003e7812` | `@liang-kai-shui` | 17| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `aa2988cc` | `@liang-kai-shui` |
18| Polski (Polish) (`pl-PL`) | [`pl-PL/quickstart.md`](pl-PL/quickstart.md) | `c0ac5fd6` | `@Dom-in` | 18| Polski (Polish) (`pl-PL`) | [`pl-PL/quickstart.md`](pl-PL/quickstart.md) | `f847748c` | `@Dom-in, @t91a60` |
19| Türkçe (`tr`) | [`tr/quickstart.md`](tr/quickstart.md) | `f85582e` | `@emirhan-karaca` | 19| Türkçe (`tr`) | [`tr/quickstart.md`](tr/quickstart.md) | `561b65a` | `@emirhan-karaca` |
20| Русский (`ru`) | [`ru/quickstart.md`](ru/quickstart.md) | `a0acd33` | `@DmitryBykov-ISPO` | 20| Русский (`ru`) | [`ru/quickstart.md`](ru/quickstart.md) | `aa2988cc` | `@DmitryBykov-ISPO` |
21| 日本語 (`ja`) | [`ja/quickstart.md`](ja/quickstart.md) | `003e781` | `@bingll123` | 21| 日本語 (`ja`) | [`ja/quickstart.md`](ja/quickstart.md) | `003e781` | `@bingll123` |
22| Español (`es`) | [`es/quickstart.md`](es/quickstart.md) | `003e7812` | `@NolanCotter` | 22| Español (`es`) | [`es/quickstart.md`](es/quickstart.md) | `aa2988cc` | `@NolanCotter` |
23| Deutsch (`de`) | [`de/quickstart.md`](de/quickstart.md) | `4eb6155d` | `@zGLados` | 23| Deutsch (`de`) | [`de/quickstart.md`](de/quickstart.md) | `aa2988cc` | `@zGLados` |
24| Italiano (`it`) | [`it/quickstart.md`](it/quickstart.md) | `49475796` | `@MeNoSkills` | 24| Italiano (`it`) | [`it/quickstart.md`](it/quickstart.md) | `49475796` | `@MeNoSkills` |
25| العربية (`ar`) | [`ar/quickstart.md`](ar/quickstart.md) | `ec8ec4c9` | `@Mohamed-Leo` | 25| العربية (`ar`) | [`ar/quickstart.md`](ar/quickstart.md) | `561b65a` | `@Mohamed-Leo` |
diff --git a/docs/i18n/ar/quickstart.md b/docs/i18n/ar/quickstart.md
index fdcf03d98..c6d4c93c9 100644
--- a/docs/i18n/ar/quickstart.md
+++ b/docs/i18n/ar/quickstart.md
@@ -2,7 +2,7 @@
2 2
3# دليل البدء السريع لمشروع Leonida 3# دليل البدء السريع لمشروع Leonida
4 4
5الوثائق الإنجليزية هي المرجع المعتمد. يستند هذا الدليل إلى المراجعة `ec8ec4c9` ويغطي خطوات البدء الأساسية. 5الوثائق الإنجليزية هي المرجع المعتمد. يستند هذا الدليل إلى المراجعة `561b65a` ويغطي خطوات البدء الأساسية.
6راجع [ملف README بالإنجليزية](../../../README.md#project-status) لمعرفة حالة المشروع الحالية، و[فهرس الوثائق](../../README.md) للمزيد من التفاصيل. 6راجع [ملف README بالإنجليزية](../../../README.md#project-status) لمعرفة حالة المشروع الحالية، و[فهرس الوثائق](../../README.md) للمزيد من التفاصيل.
7 7
8## ما هو Leonida؟ 8## ما هو Leonida؟
@@ -17,13 +17,14 @@ Leonida مشروع لإعادة ترجمة إصدار Xbox Series من Grand The
17## المتطلبات 17## المتطلبات
18 18
19- نسختك الخاصة من حزمة Xbox Series بالإصدار `1.0.2.1`. اختر المجلد الذي يحتوي على `MicrosoftGame.Config` وأرشيفات `.rpf`. 19- نسختك الخاصة من حزمة Xbox Series بالإصدار `1.0.2.1`. اختر المجلد الذي يحتوي على `MicrosoftGame.Config` وأرشيفات `.rpf`.
20- Windows 10 أو 11 بمعمارية x64، مع نحو 350 غيغابايت متاحة لملفات العمل. يمكن وضعها على قرص آخر باستخدام `--work`. 20- Windows 10 أو 11 بمعمارية x64، مع نحو 400 غيغابايت متاحة لملفات العمل. هذا الرقم للبناء الكامل: التشغيل وحده يكفيه `--stages check,shaders,runtime` بنحو 30 غيغابايت، ومرحلة `assets` وحدها تطلب نحو 370 غيغابايت. يمكن وضعها على قرص آخر باستخدام `--work` و`--out`.
21- Git و[Python 3.12 أو أحدث](https://www.python.org/downloads/) و[حزمة .NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). 21- Git و[Python 3.12 أو أحدث](https://www.python.org/downloads/) و[حزمة .NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
22 عند تثبيت Python على Windows، اختر إضافة `python.exe` إلى `PATH`. 22 عند تثبيت Python على Windows، اختر إضافة `python.exe` إلى `PATH`.
23- [حزمة Vulkan SDK](https://vulkan.lunarg.com/) لتوفير `spirv-as` و`spirv-val` و`vulkaninfo`. 23- [حزمة Vulkan SDK](https://vulkan.lunarg.com/) لتوفير `spirv-as` و`spirv-val` و`vulkaninfo`.
24- [LLVM 21 أو أحدث](https://github.com/llvm/llvm-project/releases) مع دعم AMDGPU في `llvm-mc`. 24- [LLVM 21 أو أحدث](https://github.com/llvm/llvm-project/releases) مع دعم AMDGPU في `llvm-mc`.
25 نسخة LLVM الرسمية لـWindows لا تتضمن هذا الدعم. من جذر المستودع، شغّل `scripts/build_llvm_mc.ps1` من PowerShell لبناء `llvm-mc.exe`. 25 نسخة LLVM الرسمية لـWindows لا تتضمن هذا الدعم. من جذر المستودع، شغّل `scripts/build_llvm_mc.ps1` من PowerShell لبناء `llvm-mc.exe`.
26 يتطلب السكربت Git وأدوات C++ في Visual Studio ويضبط `LLVM_MC`. افتح نافذة PowerShell جديدة بعد انتهائه. 26 يتطلب السكربت Git وأدوات C++ في Visual Studio ويضبط `LLVM_MC`. افتح نافذة PowerShell جديدة بعد انتهائه.
27 إذا كنت تستخدم [conda](https://docs.conda.io/)، فطريقة أسرع هي `conda install -c conda-forge llvm-tools` (نسخة Windows منه تتضمن هدف AMDGPU؛ استخدم [دليل الاختبارات](../../testing.md) الإصدار 23.1.6)، ثم اضبط `LLVM_MC` على المسار الكامل لملف `llvm-mc.exe` الذي يثبّته (يعرض `where.exe llvm-mc` مساره بعد تنشيط البيئة؛ أما `where` المجرد في PowerShell فهو `Where-Object`).
27 إذا ثبّتَّ `llvm-21` على Ubuntu داخل WSL، اضبط `LLVM_MC` في نافذة PowerShell التي ستشغّل منها البناء. 28 إذا ثبّتَّ `llvm-21` على Ubuntu داخل WSL، اضبط `LLVM_MC` في نافذة PowerShell التي ستشغّل منها البناء.
28 29
29 ```powershell 30 ```powershell
@@ -53,6 +54,7 @@ cd Leonida
53 54
54```powershell 55```powershell
55python -I make_game.py --find 56python -I make_game.py --find
57python -I make_game.py --pick
56python -I make_game.py --check 58python -I make_game.py --check
57python -I make_game.py --check --full-check 59python -I make_game.py --check --full-check
58python -I make_game.py --game "D:\path\to\package" --out "D:\Games\Leonida" --work "E:\leonida-work" 60python -I make_game.py --game "D:\path\to\package" --out "D:\Games\Leonida" --work "E:\leonida-work"
diff --git a/docs/i18n/de/quickstart.md b/docs/i18n/de/quickstart.md
index 4846ae313..9627c154d 100644
--- a/docs/i18n/de/quickstart.md
+++ b/docs/i18n/de/quickstart.md
@@ -3,7 +3,7 @@
3> [!NOTE] 3> [!NOTE]
4> Die englische Dokumentation ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) und 4> Die englische Dokumentation ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) und
5> [`docs/README.md`](../../README.md)) ist **maßgeblich**. Diese Anleitung enthält nur die stabilen Schritte zum 5> [`docs/README.md`](../../README.md)) ist **maßgeblich**. Diese Anleitung enthält nur die stabilen Schritte zum
6> Einrichten und Bauen (abgeglichen mit Commit `4eb6155d`). Den aktuellen Projektstand findest du in der 6> Einrichten und Bauen (abgeglichen mit Commit `aa2988cc`). Den aktuellen Projektstand findest du in der
7> [`README.md`](../../../README.md). 7> [`README.md`](../../../README.md).
8 8
9## Was ist Leonida? 9## Was ist Leonida?
@@ -23,11 +23,30 @@ Modelle, Texturen und Audio werden direkt aus deinem Paket gelesen.
23 23
24Das Projekt steht noch am Anfang: **Das Spiel startet noch nicht.** 24Das Projekt steht noch am Anfang: **Das Spiel startet noch nicht.**
25 25
26## Plattformen
27
28Auf keiner Plattform ist bisher etwas spielbar. Was heute wo läuft:
29
30- **Windows**: alles (`make_game.py`, die Tools und die Runtime `gta6rt` mit der D3D12 → Vulkan-Schicht und ihren
31 Tests).
32- **Linux**: Der Übersetzer, die Asset-Tools und die Vulkan-GPU-Testtools bauen und laufen nativ (getestet mit RADV
33 und NVIDIA). Die Runtime ist Windows-Code: Sie wird mit clang-cl und xwin cross-kompiliert, ihre Tests laufen unter
34 Wine oder Proton. Das Spiel soll später genauso laufen (#217).
35- **macOS (Apple Silicon)**: Die Python-Tools und die Vulkan-Testtools laufen nativ, auf MoltenVK (Homebrew) oder
36 KosmicKrisp. Die Runtime läuft wie unter Linux unter Wine. Bekannte Lücken: keine Geometry-Stufe und kein
37 `VK_EXT_mesh_shader`, 32 breite Subgroups (Wave64-Shader laufen emuliert) und MoltenVKs Umgang mit
38 Gleitkommazahlen; [`docs/testing.md`](../../testing.md) listet sie alle auf.
39- **AMD RDNA1 (RX 5000)**: ein unterstütztes Ziel, nah am RDNA2 der Konsole; seine 64 breiten Subgroups führen die
40 Wave64-Shader nativ aus.
41
42GPU-Ergebnisse von allen Plattformen werden in [Issue #166](https://github.com/ItsNotRexed/Leonida/issues/166)
43gesammelt.
44
26## Voraussetzungen 45## Voraussetzungen
27 46
28- **Deine eigene Kopie** des Xbox-Series-Pakets in Version `1.0.2.1` (der Ordner mit `MicrosoftGame.Config` und den 47- **Deine eigene Kopie** des Xbox-Series-Pakets in Version `1.0.2.1` (der Ordner mit `MicrosoftGame.Config` und den
29 `.rpf`-Archiven, als normale, lesbare Dateien auf der Festplatte). 48 `.rpf`-Archiven, als normale, lesbare Dateien auf der Festplatte).
30- **Windows 10/11 x64** mit etwa **350 GB freiem Speicher** für die Arbeitsdateien (mit `--work` auch auf einem 49- **Windows 10/11 x64** mit etwa **400 GB freiem Speicher** für die Arbeitsdateien (mit `--work` auch auf einem
31 anderen Laufwerk). 50 anderen Laufwerk).
32- [Python 3.12+](https://www.python.org/downloads/) (bei der Installation *„Add python.exe to PATH“* anhaken). 51- [Python 3.12+](https://www.python.org/downloads/) (bei der Installation *„Add python.exe to PATH“* anhaken).
33- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). 52- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
@@ -36,7 +55,12 @@ Das Projekt steht noch am Anfang: **Das Spiel startet noch nicht.**
36 - Der offizielle LLVM-Build für Windows enthält das AMDGPU-Target **nicht**. 55 - Der offizielle LLVM-Build für Windows enthält das AMDGPU-Target **nicht**.
37 - Ein natives `llvm-mc.exe` mit AMDGPU baut `.\scripts\build_llvm_mc.ps1`, ausgeführt in PowerShell im 56 - Ein natives `llvm-mc.exe` mit AMDGPU baut `.\scripts\build_llvm_mc.ps1`, ausgeführt in PowerShell im
38 Hauptordner des Repositorys. Das Skript braucht `git` und die C++-Tools von Visual Studio, setzt die Variable 57 Hauptordner des Repositorys. Das Skript braucht `git` und die C++-Tools von Visual Studio, setzt die Variable
39 `LLVM_MC` für deinen Benutzer und bittet dich, danach ein neues Terminal zu öffnen, damit sie sichtbar wird. 58 `LLVM_MC` für deinen Benutzer und bittet dich, danach ein neues Terminal zu öffnen, damit sie sichtbar wird. Das
59 dauert etwa 20-40 Minuten.
60 - Schneller, wenn du [conda](https://docs.conda.io/) nutzt: `conda install -c conda-forge llvm-tools` (der
61 Windows-Build enthält das AMDGPU-Target), dann `LLVM_MC` auf den vollen Pfad des installierten `llvm-mc.exe`
62 setzen (`where.exe llvm-mc` zeigt ihn bei aktivierter Umgebung; das nackte `where` ist in
63 PowerShell das Cmdlet `Where-Object`).
40 - Mit WSL: `llvm-21` in Ubuntu installieren und die Variable in derselben PowerShell-Sitzung setzen, in der du 64 - Mit WSL: `llvm-21` in Ubuntu installieren und die Variable in derselben PowerShell-Sitzung setzen, in der du
41 `make_game.py` startest: 65 `make_game.py` startest:
42 66
@@ -60,6 +84,8 @@ Das Projekt steht noch am Anfang: **Das Spiel startet noch nicht.**
60 ```powershell 84 ```powershell
61 git clone --recursive https://github.com/ItsNotRexed/Leonida 85 git clone --recursive https://github.com/ItsNotRexed/Leonida
62 ``` 86 ```
87 Ein „Download ZIP“ von GitHub lässt `third_party/rpf9-explorer` weg. Der Build holt es nach, wenn `git`
88 installiert ist, und sagt dir sonst, was zu tun ist.
633. Doppelklicke auf **`Build.bat`**. 893. Doppelklicke auf **`Build.bat`**.
64 90
65Der Build findet deine Kopie selbst: Er sucht in Downloads, Desktop, Dokumente (auch dort, wo Windows sie ablegt, 91Der Build findet deine Kopie selbst: Er sucht in Downloads, Desktop, Dokumente (auch dort, wo Windows sie ablegt,
@@ -69,6 +95,16 @@ soll, findet er keine, bittet er dich, den Ordner einzufügen. Vor dem Start prÃ
69genug Platz frei ist, und listet alles Fehlende auf einmal auf. Das Ergebnis landet in `Documents\Leonida`. Ein 95genug Platz frei ist, und listet alles Fehlende auf einmal auf. Das Ergebnis landet in `Documents\Leonida`. Ein
70abgebrochener Build macht beim nächsten Start dort weiter, wo er aufgehört hat. 96abgebrochener Build macht beim nächsten Start dort weiter, wo er aufgehört hat.
71 97
98### Wenig Speicherplatz
99
100Der Platzbedarf oben gilt für den vollständigen Build. Um den Port nur zu *starten*, braucht
101`--stages check,shaders,runtime` etwa 30 GB; die Stufe `assets`, die fast den ganzen Rest belegt, ist nur für die
102Asset-Tools da, und `--wav` kommt mit einem Mehrfachen der Ogg-Opus-Größe hinzu. `--work` und `--out` können auf
103einem anderen Laufwerk liegen. Die Runtime liest das Paket an Ort und Stelle; liegt es auf einem schreibgeschützten
104Laufwerk, brauchst du `gta6rt --overlay <beschreibbarer Ordner>` (eine Option von `gta6rt`, nicht von
105`make_game.py`). Lösche die `.s`-Dateien in `work/shaders/dxbc/disasm` nicht: Ohne sie und ohne
106`work/shaders/spirv/index.json` kann die Stufe `shaders` mit null Shadern fertig aussehen.
107
72### Aus dem Terminal (`make_game.py`) 108### Aus dem Terminal (`make_game.py`)
73 109
74```powershell 110```powershell
@@ -87,14 +123,31 @@ Die Stufen laufen in dieser Reihenfolge: `check` → `shaders` → `assets` →
87- **`--wave64-emulate`**: emuliert Wave64-Compute- und -Mesh-Shader auf GPUs mit 32 breiten Subgroups (NVIDIA und 123- **`--wave64-emulate`**: emuliert Wave64-Compute- und -Mesh-Shader auf GPUs mit 32 breiten Subgroups (NVIDIA und
88 Intel). Der Standard `auto` fragt `vulkaninfo` und schaltet die Emulation selbst ein, wenn sie gebraucht wird. 124 Intel). Der Standard `auto` fragt `vulkaninfo` und schaltet die Emulation selbst ein, wenn sie gebraucht wird.
89 AMD-Karten (RDNA) führen Wave64 nativ aus. 125 AMD-Karten (RDNA) führen Wave64 nativ aus.
90- **`--work`**: am besten ein Laufwerk mit mindestens 350 GB freiem Platz angeben. Die Stufe `shaders` dauert am 126- **`--work`**: am besten ein Laufwerk mit mindestens 400 GB freiem Platz angeben. Die Stufe `shaders` dauert am
91 längsten und nutzt standardmäßig die Hälfte der CPU-Threads (änderbar mit `--jobs`). 127 längsten und nutzt standardmäßig die Hälfte der CPU-Threads (änderbar mit `--jobs`).
92- **`pipelines`**: erstellt jeden übersetzten Shader auf deinem GPU-Treiber und speichert einen Pipeline-Cache, 128- **`pipelines`**: erstellt jeden übersetzten Shader auf deinem GPU-Treiber, prüft, dass er kompiliert, meldet die
93 damit der erste Start sie nicht kompilieren muss. 129 übersprungenen und speichert einen Pipeline-Cache in `pipeline_cache.bin` in `--out`. Die Runtime lädt diesen
94- **Linux und Wine/Proton**: `make_game.py` läuft auch unter Linux. Um die Stufe `runtime` außerhalb von Windows zu 130 Cache noch nicht, er beschleunigt den ersten Start also nicht.
95 nutzen, gib mit `--runtime-build <ordner>` einen Windows-Build an (`gta6rt.exe` und `gta6rt_tls_host.dll`). Das 131- **Fallback-Optionen** für Geräte, denen eine Vulkan-Funktion fehlt; sie werden neben den übersetzten Shadern
96 Skript legt dann `gta6rt.sh` an, das das Programm mit `wine` startet (oder mit dem Wine aus der Variable `WINE`, 132 gespeichert, und eine Änderung übersetzt sie neu: `--no-float-controls`, `--bary-fallback` (ohne
97 etwa von Proton). 133 `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (ohne `VK_KHR_maintenance8`) und `--mesh-compute`
134 (ohne `VK_EXT_mesh_shader`). Siehe [`docs/design.md`](../../design.md).
135- **Was automatisch neu gemacht wird**: Der Build merkt sich Befehl und Version von `llvm-mc`, die Quellen des
136 Übersetzers und den Asset-Decoder (`third_party/rpf9-explorer` und `tools/rpf9dump`). Ändert sich etwas davon,
137 wird nur der betroffene Schritt wiederholt (Disassemblierung, Übersetzung oder Export der Modelle und Texturen).
138- **Linux und Wine/Proton**: `make_game.py` läuft auch unter Linux. Die Stufe `pipelines` nutzt
139 `vk_pipeline_check` (mit CMake in `runtime/build/linux` gebaut; fehlt es, baut das Skript es selbst). Der Loader ist
140 ein Windows-Programm und läuft unter Wine oder Proton: Die Stufe `runtime` cross-kompiliert ihn mit clang-cl und
141 lld-link (LLVM 19+, aber nicht 22.1.7 oder 22.1.8) gegen das Windows SDK, das
142 [xwin](https://github.com/Jake-Shadle/xwin) bereitlegt; siehe [`docs/testing.md`](../../testing.md). Alternativ
143 gibst du mit `--runtime-build <ordner>` einen anderswo gemachten Windows-Build an (`gta6rt.exe` und
144 `gta6rt_tls_host.dll`). In beiden Fällen legt das Skript `gta6rt.sh` an, das das Programm mit `wine` startet (oder
145 mit dem Wine aus der Variable `WINE`, etwa von Proton).
146
147Zu `--wave64-emulate`: `auto` schaltet die Emulation ein, wenn eine GPU keine 64 breiten Subgroups hat oder ihre
148Größe unbekannt ist. Mit dem Windows-Treiber von AMD bleibt `auto` auf RDNA1 und RDNA2 bei nativem Wave64, wenn die
149GPU der Runtime es kann, denn dieser Treiber kann bei emuliertem LDS-Code abstürzen (#857). Der Modus wird neben den
150übersetzten Shadern gespeichert, und eine Änderung übersetzt sie neu.
98 151
99## Häufige Probleme 152## Häufige Probleme
100 153
diff --git a/docs/i18n/es/quickstart.md b/docs/i18n/es/quickstart.md
index 50527bdd8..0e5d9fd65 100644
--- a/docs/i18n/es/quickstart.md
+++ b/docs/i18n/es/quickstart.md
@@ -3,7 +3,7 @@
3> [!NOTE] 3> [!NOTE]
4> La documentación en inglés ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) y 4> La documentación en inglés ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) y
5> [`docs/README.md`](../../README.md)) es **la referencia oficial**. Esta guía solo recoge las instrucciones 5> [`docs/README.md`](../../README.md)) es **la referencia oficial**. Esta guía solo recoge las instrucciones
6> estables de instalación y compilación (sincronizada con el commit `003e7812`). Para el estado del proyecto, que 6> estables de instalación y compilación (sincronizada con el commit `aa2988cc`). Para el estado del proyecto, que
7> cambia a diario, consulte el [`README.md`](../../../README.md). 7> cambia a diario, consulte el [`README.md`](../../../README.md).
8 8
9## Qué es Leonida 9## Qué es Leonida
@@ -26,8 +26,8 @@ El proyecto está en una fase inicial: **el juego todavía no arranca**.
26 26
27- **Su propia copia** del paquete de Xbox Series, versión `1.0.2.1`: la carpeta que contiene `MicrosoftGame.Config` 27- **Su propia copia** del paquete de Xbox Series, versión `1.0.2.1`: la carpeta que contiene `MicrosoftGame.Config`
28 y los archivos `.rpf`, como ficheros legibles en el disco. 28 y los archivos `.rpf`, como ficheros legibles en el disco.
29- **Windows 10/11 x64**, con unos **350 GB libres** para los archivos de trabajo. Pueden ir a otra unidad con 29- **Windows 10/11 x64**, con unos **400 GB libres** para los archivos de trabajo. Pueden ir a otra unidad con
30 `--work`. 30 `--work`; más abajo se explica cómo omitir la exportación de recursos y usar unos 30 GB.
31- [Python 3.12+](https://www.python.org/downloads/) (marque «Add python.exe to PATH» durante la instalación). 31- [Python 3.12+](https://www.python.org/downloads/) (marque «Add python.exe to PATH» durante la instalación).
32- [SDK de .NET 8](https://dotnet.microsoft.com/download/dotnet/8.0). 32- [SDK de .NET 8](https://dotnet.microsoft.com/download/dotnet/8.0).
33- [SDK de Vulkan](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` y `vulkaninfo`). 33- [SDK de Vulkan](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` y `vulkaninfo`).
@@ -36,6 +36,9 @@ El proyecto está en una fase inicial: **el juego todavía no arranca**.
36 - Para compilar un `llvm-mc.exe` nativo con ese destino, ejecute `.\scripts\build_llvm_mc.ps1` en PowerShell 36 - Para compilar un `llvm-mc.exe` nativo con ese destino, ejecute `.\scripts\build_llvm_mc.ps1` en PowerShell
37 desde la raíz del repositorio. El script necesita `git` y las herramientas de C++ de Visual Studio. Define 37 desde la raíz del repositorio. El script necesita `git` y las herramientas de C++ de Visual Studio. Define
38 `LLVM_MC` para su usuario: abra después un terminal nuevo para que la variable se aplique. 38 `LLVM_MC` para su usuario: abra después un terminal nuevo para que la variable se aplique.
39 - Si usa [conda](https://docs.conda.io/), `conda install -c conda-forge llvm-tools` ofrece una alternativa cuyo
40 paquete para Windows incluye AMDGPU. Con el entorno activado, `where.exe llvm-mc` muestra la ruta del
41 ejecutable; asigne esa ruta completa a `LLVM_MC`.
39 - Con WSL, instale `llvm-21` en Ubuntu y pase el comando completo a `LLVM_MC`, en la sesión de PowerShell 42 - Con WSL, instale `llvm-21` en Ubuntu y pase el comando completo a `LLVM_MC`, en la sesión de PowerShell
40 donde vaya a ejecutar `make_game.py`: 43 donde vaya a ejecutar `make_game.py`:
41 44
@@ -62,18 +65,37 @@ El proyecto está en una fase inicial: **el juego todavía no arranca**.
62 ``` 65 ```
633. Haga doble clic en **`Build.bat`**. 663. Haga doble clic en **`Build.bat`**.
64 67
65El script encuentra su copia por sí solo: busca en Descargas, Escritorio, Documentos, Games, su carpeta de usuario 68El script encuentra su copia por sí solo: busca en Descargas, Escritorio y Documentos (también si Windows los ha
66y en la raíz de cada disco, dos niveles de carpetas en profundidad. Si encuentra varias copias, le pregunta cuál 69movido a OneDrive), Games, su carpeta de usuario y en la raíz de cada disco, dos niveles de carpetas en
67usar; si no encuentra ninguna, le pide que pegue la ruta de la carpeta. Antes de empezar comprueba los requisitos 70profundidad. Reconoce la versión por el tamaño de algunos archivos, sin leer archivos grandes. Si encuentra
68y el espacio libre, y enumera de una vez todo lo que falta. El resultado va a `Documents\Leonida`. Una 71varias copias, le pregunta cuál usar; si no encuentra ninguna, le pide que pegue la ruta de la carpeta. Antes de
69compilación interrumpida se reanuda donde quedó. 72empezar comprueba los requisitos y el espacio libre, y enumera de una vez todo lo que falta. El resultado va a
73`Documents\Leonida`. Una compilación interrumpida se reanuda donde quedó.
74
75### Si dispone de poco espacio
76
77Los 400 GB corresponden a la compilación completa. Puede omitir la exportación de recursos con
78`--stages check,shaders,runtime`, que necesita unos **30 GB**. La etapa `assets` (unos 370 GB) sirve para las
79herramientas de recursos; `--wav` añade varias veces el tamaño de los archivos Ogg Opus. La comprobación previa
80ofrece la alternativa sin `assets` cuando esa etapa no cabe. Puede situar tanto `--work` como `--out` en otra
81unidad.
82
83El runtime accede al paquete en su ubicación original. Si la unidad del paquete es de solo lectura, use
84`gta6rt --overlay <carpeta con permisos de escritura>`: `--overlay` es una opción de `gta6rt`.
85
86Conserve los archivos `.s` de `work/shaders/dxbc/disasm`: borrarlos junto con
87`work/shaders/spirv/index.json` puede hacer que la etapa de shaders parezca terminada con cero shaders. Si la
88etapa necesita vaciar `disasm`, rechazará esa carpeta cuando sea un enlace simbólico.
70 89
71### Desde un terminal (`make_game.py`) 90### Desde un terminal (`make_game.py`)
72 91
73```powershell 92```powershell
74python -I make_game.py --find # enumera las copias encontradas en este PC 93python -I make_game.py --find # enumera las copias encontradas en este PC
94python -I make_game.py --pick # elige la carpeta mediante un diálogo
75python -I make_game.py --check # verifica su copia, sin compilar nada 95python -I make_game.py --check # verifica su copia, sin compilar nada
96python -I make_game.py --check --full-check # también comprueba los SHA-256 de todos los archivos (lento)
76python -I make_game.py --game "D:\ruta\al\paquete" --out "D:\Games\Leonida" --work "E:\leonida-work" 97python -I make_game.py --game "D:\ruta\al\paquete" --out "D:\Games\Leonida" --work "E:\leonida-work"
98python -I make_game.py --stages check,shaders,runtime # sin la exportación de recursos (unos 30 GB)
77python -I make_game.py --stages shaders,assets # solo algunas etapas 99python -I make_game.py --stages shaders,assets # solo algunas etapas
78python -I make_game.py --game "D:\ruta\al\paquete" --wav # además decodifica el Opus a WAV PCM (ocupa mucho) 100python -I make_game.py --game "D:\ruta\al\paquete" --wav # además decodifica el Opus a WAV PCM (ocupa mucho)
79python -I make_game.py --wave64-emulate off # auto (predeterminado), on u off 101python -I make_game.py --wave64-emulate off # auto (predeterminado), on u off
@@ -81,10 +103,87 @@ python -I make_game.py --wave64-emulate off # auto (predeterminado),
81 103
82Las etapas se ejecutan en este orden: `check` → `shaders` → `assets` → `runtime` → `pipelines`. 104Las etapas se ejecutan en este orden: `check` → `shaders` → `assets` → `runtime` → `pipelines`.
83 105
106La traducción de shaders es la etapa más larga; por defecto usa la mitad de los hilos del procesador (ajustable
107con `--jobs`). La etapa `pipelines` comprueba que el controlador de su GPU puede crear los shaders traducidos e
108informa de los que debe omitir. Guarda `pipeline_cache.bin` en `--out`, pero el runtime todavía no carga esa
109caché, así que no acelera el primer arranque.
110
111`--wav` está desactivado por defecto, porque el WAV PCM de 16 bits ocupa varias veces más que el Ogg Opus.
112Cuando se activa, decodifica los Ogg Opus a `work/assets/audio/wav` después de exportar los bancos de audio;
113al reanudar, omite los WAV ya existentes.
114
115### Emulación wave64 y compatibilidad de la GPU
116
117`--wave64-emulate` decide si los shaders compute y mesh wave64 se traducen de forma exacta para cualquier tamaño
118de subgrupo. Las GPU NVIDIA e Intel usan subgrupos de 32 y lo necesitan. El valor predeterminado, `auto`, consulta
119`vulkaninfo` y activa la emulación si alguna GPU no admite subgrupos de 64 o su tamaño es desconocido. También
120comprueba que la GPU del runtime admita compute y mesh con subgrupos de 64; con `--mesh-compute` solo necesita
121esa capacidad en compute.
122
123Con el controlador de AMD para Windows, `auto` usa wave64 nativo en RDNA1 y RDNA2 si la GPU del runtime lo admite,
124aunque otra GPU use subgrupos de 32 o no esté disponible `vulkaninfo`. Así evita un fallo del controlador con
125código LDS emulado ([#857](https://github.com/ItsNotRexed/Leonida/issues/857)). En RDNA1 sin mesh nativo comprueba
126la capacidad de compute. Puede forzar la emulación con `--wave64-emulate on` o el modo nativo con
127`--wave64-emulate off`.
128
129Estas opciones ofrecen alternativas para GPU o controladores con capacidades limitadas. Los detalles y sus
130límites están en [`docs/design.md`](../../design.md):
131
132| Opción | Cuándo se usa |
133|---|---|
134| `--no-float-controls` | Cuando la GPU no admite las capacidades de conservación de valores especiales de coma flotante requeridas por los shaders. |
135| `--bary-fallback` | Cuando falta `VK_KHR_fragment_shader_barycentric`. |
136| `--texel-offset-fallback` | Cuando falta `VK_KHR_maintenance8` para los desplazamientos de muestreo. |
137| `--mesh-compute` | Cuando falta `VK_EXT_mesh_shader`: traduce los shaders mesh como compute. |
138| `--f16-interp-fallback` | Interpolación de 16 bits sin entradas `PerVertexKHR`; se activa automáticamente cuando la GPU del runtime no puede usarlas, como ocurre con MoltenVK. |
139| `--pc-tail-ubo` | Para GPU cuyo límite de push constants es insuficiente; se activa automáticamente cuando el runtime detecta ese límite. |
140
141El modo wave64 y estas opciones se guardan junto a los shaders. Cambiarlos vuelve a ejecutar la traducción.
142`auto` normalmente reutiliza los shaders ya emulados, salvo cuando la alternativa de AMD para Windows requiere
143reconstruirlos en modo nativo.
144
145### Reanudar tras una actualización
146
147La compilación registra el comando y la versión de `llvm-mc` que generaron el desensamblado: si cambian, o si la
148carpeta de trabajo es anterior a ese registro, vuelve a desensamblar y traducir, conservando las entradas extraídas.
149También registra los archivos fuente del traductor; un cambio en ellos repite la traducción a partir del
150desensamblado guardado.
151
152Para modelos y texturas registra el commit de `third_party/rpf9-explorer` y el código de `tools/rpf9dump`. Cuando
153cambia ese decodificador, elimina la exportación de cada archivo afectado y la genera de nuevo. Las carpetas
154antiguas sin esos registros necesitan repetir una vez la traducción o la exportación correspondiente.
155
156### Linux y Wine/Proton
157
158`make_game.py` también funciona en Linux. Las herramientas de diagnóstico Vulkan se compilan de forma nativa
159con CMake 3.24+, un compilador C++20 y las cabeceras y el cargador de Vulkan:
160
161```sh
162cmake -S runtime -B runtime/build/linux
163cmake --build runtime/build/linux --parallel
164./runtime/build/linux/vk_pipeline_check /ruta/a/spirv
165```
166
167El último comando recibe la carpeta que contiene `index.json` y los shaders traducidos. La etapa `pipelines`
168usa `vk_pipeline_check` de `runtime/build/linux` o `runtime/build`, y lo compila antes de iniciar el resto del
169trabajo si falta.
170
171El cargador es un programa de Windows y se ejecuta bajo Wine o Proton. En Linux la etapa `runtime` puede
172compilarlo de forma cruzada con `clang-cl` y `lld-link` (LLVM 19+, excepto 22.1.7 y 22.1.8) y el CRT de MSVC y el
173SDK de Windows preparados por [xwin](https://github.com/Jake-Shadle/xwin), en `XWIN_DIR` o
174`~/.local/share/xwin-sdk`. La [guía de pruebas](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton)
175explica la preparación. Si faltan esas herramientas, `runtime` se omite de las etapas predeterminadas; pedirlo
176explícitamente enumera lo que falta antes de empezar.
177
178También puede pasar `--runtime-build <carpeta>` con una compilación de Windows (`gta6rt.exe` y
179`gta6rt_tls_host.dll`), por ejemplo el artefacto `runtime-windows` del trabajo `windows` del workflow Runtime,
180descomprimido. Así evita compilar el runtime; la misma opción funciona en Windows. En Linux el script escribe
181`gta6rt.sh`, que lanza `gta6rt.exe` con `wine`, o con el Wine indicado por la variable `WINE` (para Proton, su
182`files/bin/wine`).
84- **`--wave64-emulate`**: traduce los shaders compute y mesh wave64 de forma exacta cualquiera que sea el tamaño de 183- **`--wave64-emulate`**: traduce los shaders compute y mesh wave64 de forma exacta cualquiera que sea el tamaño de
85 subgrupo de la GPU. Las GPU NVIDIA e Intel usan subgrupos de 32 y lo necesitan. El valor predeterminado, `auto`, 184 subgrupo de la GPU. Las GPU NVIDIA e Intel usan subgrupos de 32 y lo necesitan. El valor predeterminado, `auto`,
86 consulta `vulkaninfo` y activa la emulación salvo que todas las GPU anuncien subgrupos de 64. 185 consulta `vulkaninfo` y activa la emulación salvo que todas las GPU anuncien subgrupos de 64.
87- **`--work`**: elija un disco con al menos 350 GB libres. La traducción de shaders es la etapa más larga; por 186- **`--work`**: elija un disco con al menos 400 GB libres. La traducción de shaders es la etapa más larga; por
88 defecto usa la mitad de los hilos del procesador (ajustable con `--jobs`). 187 defecto usa la mitad de los hilos del procesador (ajustable con `--jobs`).
89- **`--wav`**: desactivado por defecto, porque el WAV PCM de 16 bits ocupa varias veces más que el Ogg Opus. 188- **`--wav`**: desactivado por defecto, porque el WAV PCM de 16 bits ocupa varias veces más que el Ogg Opus.
90- **Linux y Wine/Proton**: `make_game.py` también funciona en Linux. El cargador es un programa de Windows y se 189- **Linux y Wine/Proton**: `make_game.py` también funciona en Linux. El cargador es un programa de Windows y se
@@ -103,7 +202,7 @@ Las etapas se ejecutan en este orden: `check` → `shaders` → `assets` → `ru
103 Instalador de Visual Studio o con `winget install Microsoft.WindowsSDK.10.0.26100`, y luego borre 202 Instalador de Visual Studio o con `winget install Microsoft.WindowsSDK.10.0.26100`, y luego borre
104 `runtime/build` y repita la configuración. 203 `runtime/build` y repita la configuración.
105- **Se quedó sin espacio en `C:`**: pase `--work "D:\leonida-work"` para situar los archivos temporales en otra 204- **Se quedó sin espacio en `C:`**: pase `--work "D:\leonida-work"` para situar los archivos temporales en otra
106 unidad. 205 unidad; también puede cambiar `--out` u omitir `assets` con `--stages check,shaders,runtime` (unos 30 GB).
107- **Windows se niega a lanzar los programas de prueba recién compilados** («An Application Control policy has 206- **Windows se niega a lanzar los programas de prueba recién compilados** («An Application Control policy has
108 blocked this file»): es el control inteligente de aplicaciones de Windows 11. Véase 207 blocked this file»): es el control inteligente de aplicaciones de Windows 11. Véase
109 [`docs/testing.md`](../../testing.md#known-problems). 208 [`docs/testing.md`](../../testing.md#known-problems).
diff --git a/docs/i18n/fr/quickstart.md b/docs/i18n/fr/quickstart.md
index 07a696f92..2685461d2 100644
--- a/docs/i18n/fr/quickstart.md
+++ b/docs/i18n/fr/quickstart.md
@@ -3,7 +3,7 @@
3> [!NOTE] 3> [!NOTE]
4> La documentation en anglais ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) et 4> La documentation en anglais ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) et
5> [`docs/README.md`](../../README.md)) **fait foi**. Ce guide ne reprend que les instructions stables d'installation 5> [`docs/README.md`](../../README.md)) **fait foi**. Ce guide ne reprend que les instructions stables d'installation
6> et de compilation (synchronisé avec le commit `e7584c52`). Pour l'état d'avancement du projet, qui change tous les 6> et de compilation (synchronisé avec le commit `aa2988cc`). Pour l'état d'avancement du projet, qui change tous les
7> jours, consultez le [`README.md`](../../../README.md). 7> jours, consultez le [`README.md`](../../../README.md).
8 8
9## Ce qu'est Leonida 9## Ce qu'est Leonida
@@ -22,6 +22,24 @@ système de la console est réimplémenté sous forme de shims.
22 22
23Le projet en est à ses débuts : **le jeu ne démarre pas encore**. 23Le projet en est à ses débuts : **le jeu ne démarre pas encore**.
24 24
25## Plateformes
26
27Rien n'est jouable, sur aucune plateforme. Ce qui tourne aujourd'hui :
28
29- **Windows** : tout (`make_game.py`, les outils, et le runtime `gta6rt` avec la couche D3D12 → Vulkan et ses tests).
30- **Linux** : le traducteur, les outils de ressources et les outils de test GPU Vulkan tournent nativement (testés
31 sur RADV et NVIDIA). Le runtime est du code Windows : il se compile en croisé avec clang-cl et xwin, et ses tests
32 tournent sous Wine ou Proton. Le jeu est prévu pour tourner de la même façon (#217).
33- **macOS (Apple Silicon)** : les outils Python et les outils de test Vulkan tournent nativement, sur MoltenVK
34 (Homebrew) ou KosmicKrisp. Le runtime tourne sous Wine, comme sous Linux. Limites connues : pas d'étape geometry ni
35 de `VK_EXT_mesh_shader`, sous-groupes de 32 (les shaders wave64 sont émulés) et la gestion des flottants de
36 MoltenVK ; [`docs/testing.md`](../../testing.md) les détaille.
37- **AMD RDNA1 (RX 5000)** : une cible prise en charge, proche du RDNA2 de la console ; ses sous-groupes de 64
38 exécutent les shaders wave64 nativement.
39
40Les résultats GPU de toutes les plateformes sont regroupés dans
41l'[issue #166](https://github.com/ItsNotRexed/Leonida/issues/166).
42
25## Prérequis 43## Prérequis
26 44
27- **Votre propre copie** du paquet Xbox Series, version `1.0.2.1` : le dossier qui contient `MicrosoftGame.Config` et 45- **Votre propre copie** du paquet Xbox Series, version `1.0.2.1` : le dossier qui contient `MicrosoftGame.Config` et
@@ -35,7 +53,12 @@ Le projet en est à ses débuts : **le jeu ne démarre pas encore**.
35 - La version officielle de LLVM pour Windows **n'inclut pas** la cible AMDGPU. 53 - La version officielle de LLVM pour Windows **n'inclut pas** la cible AMDGPU.
36 - Pour compiler un `llvm-mc.exe` natif avec cette cible, lancez `.\scripts\build_llvm_mc.ps1` dans PowerShell 54 - Pour compiler un `llvm-mc.exe` natif avec cette cible, lancez `.\scripts\build_llvm_mc.ps1` dans PowerShell
37 depuis la racine du dépôt. Le script a besoin de `git` et des outils C++ de Visual Studio. Il définit `LLVM_MC` 55 depuis la racine du dépôt. Le script a besoin de `git` et des outils C++ de Visual Studio. Il définit `LLVM_MC`
38 pour votre utilisateur : ouvrez ensuite un nouveau terminal pour que la variable soit prise en compte. 56 pour votre utilisateur : ouvrez ensuite un nouveau terminal pour que la variable soit prise en compte. Comptez
57 20 à 40 minutes.
58 - Plus rapide si vous utilisez [conda](https://docs.conda.io/) : `conda install -c conda-forge llvm-tools` (sa
59 version Windows inclut la cible AMDGPU), puis faites pointer `LLVM_MC` vers le chemin complet du `llvm-mc.exe`
60 installé (`where.exe llvm-mc` l'affiche une fois l'environnement activé ; le `where` seul est
61 l'alias `Where-Object` de PowerShell).
39 - Avec WSL, installez `llvm-21` dans Ubuntu et donnez la commande entière à `LLVM_MC`, dans la session PowerShell 62 - Avec WSL, installez `llvm-21` dans Ubuntu et donnez la commande entière à `LLVM_MC`, dans la session PowerShell
40 où vous lancerez `make_game.py` : 63 où vous lancerez `make_game.py` :
41 64
@@ -59,14 +82,27 @@ Le projet en est à ses débuts : **le jeu ne démarre pas encore**.
59 ```powershell 82 ```powershell
60 git clone --recursive https://github.com/ItsNotRexed/Leonida 83 git clone --recursive https://github.com/ItsNotRexed/Leonida
61 ``` 84 ```
85 Un « Download ZIP » depuis GitHub n'inclut pas `third_party/rpf9-explorer` : la compilation le récupère si `git`
86 est installé, et sinon vous dit quoi faire.
623. Double-cliquez sur **`Build.bat`**. 873. Double-cliquez sur **`Build.bat`**.
63 88
64Le script trouve votre copie tout seul : il cherche dans Téléchargements, Bureau, Documents, Games, votre dossier 89Le script trouve votre copie tout seul : il cherche dans Téléchargements, Bureau, Documents (y compris là où Windows
65utilisateur et à la racine de chaque disque, sur deux niveaux de dossiers. S'il trouve plusieurs copies, il demande 90les range, par exemple dans OneDrive), Games, votre dossier utilisateur et à la racine de chaque disque, sur deux
91niveaux de dossiers. Il reconnaît la version à la taille de quelques fichiers, sans rien lire de volumineux. S'il
92trouve plusieurs copies, il demande
66laquelle utiliser ; s'il n'en trouve aucune, il vous demande de coller le chemin du dossier. Avant de commencer, il 93laquelle utiliser ; s'il n'en trouve aucune, il vous demande de coller le chemin du dossier. Avant de commencer, il
67vérifie les prérequis et l'espace libre, et liste d'un coup tout ce qui manque. Le résultat va dans 94vérifie les prérequis et l'espace libre, et liste d'un coup tout ce qui manque. Le résultat va dans
68`Documents\Leonida`. Une compilation interrompue reprend là où elle s'était arrêtée. 95`Documents\Leonida`. Une compilation interrompue reprend là où elle s'était arrêtée.
69 96
97### Peu d'espace disque
98
99L'espace indiqué plus haut correspond à la compilation complète. Pour *lancer* le portage,
100`--stages check,shaders,runtime` a besoin d'environ 30 Go ; l'étape `assets`, qui prend presque tout le reste, ne sert
101qu'aux outils de ressources, et `--wav` ajoute plusieurs fois la taille de l'Ogg Opus. `--work` et `--out` peuvent être sur un autre disque. Le runtime lit le paquet sur
102place : si son disque est en lecture seule, passez `gta6rt --overlay <dossier accessible en écriture>` (c'est une
103option de `gta6rt`, pas de `make_game.py`). Ne supprimez pas les fichiers `.s` de `work/shaders/dxbc/disasm` : sans
104eux et sans `work/shaders/spirv/index.json`, l'étape `shaders` peut sembler terminée avec zéro shader.
105
70### Depuis un terminal (`make_game.py`) 106### Depuis un terminal (`make_game.py`)
71 107
72```powershell 108```powershell
@@ -80,17 +116,34 @@ python -I make_game.py --game "D:\chemin\vers\le\paquet" --wav # décode aussi
80python -I make_game.py --wave64-emulate off # auto (par défaut), on ou off 116python -I make_game.py --wave64-emulate off # auto (par défaut), on ou off
81``` 117```
82 118
83Les étapes s'exécutent dans cet ordre : `check` → `shaders` → `assets` → `runtime` → `pipelines`. 119Les étapes s'exécutent dans cet ordre : `check` → `shaders` → `assets` → `runtime` → `pipelines`. L'étape
120`pipelines` crée chaque shader traduit avec le pilote de votre GPU, vérifie qu'il compile, signale ceux qu'elle doit
121ignorer et enregistre un cache de pipelines dans `pipeline_cache.bin` (dans `--out`) ; le runtime ne charge pas
122encore ce cache.
84 123
85- **`--wave64-emulate`** : traduit les shaders compute et mesh wave64 de façon exacte quelle que soit la taille des 124- **`--wave64-emulate`** : traduit les shaders compute et mesh wave64 de façon exacte quelle que soit la taille des
86 sous-groupes du GPU. Les GPU NVIDIA et Intel ont des sous-groupes de 32 et en ont besoin. La valeur par défaut, 125 sous-groupes du GPU. Les GPU NVIDIA et Intel ont des sous-groupes de 32 et en ont besoin. La valeur par défaut,
87 `auto`, interroge `vulkaninfo` et active l'émulation sauf si tous les GPU annoncent des sous-groupes de 64. 126 `auto`, interroge `vulkaninfo` et active l'émulation si un GPU n'a pas de sous-groupes de 64 ou si leur taille est
127 inconnue. Avec le pilote Windows d'AMD, `auto` garde le wave64 natif sur RDNA1 et RDNA2 quand le GPU du runtime le
128 permet, car ce pilote peut planter sur le code émulé (#857). Le mode est enregistré à côté des shaders traduits, et
129 le changer les retraduit.
130- **Options de repli** pour les appareils auxquels manque une fonction Vulkan, enregistrées et retraduites de la même
131 façon : `--no-float-controls`, `--bary-fallback` (sans `VK_KHR_fragment_shader_barycentric`),
132 `--texel-offset-fallback` (sans `VK_KHR_maintenance8`) et `--mesh-compute` (sans `VK_EXT_mesh_shader`). Voir
133 [`docs/design.md`](../../design.md).
134- **Ce qui est refait automatiquement** : la compilation enregistre la commande et la version de `llvm-mc`, les
135 sources du traducteur et le décodeur des ressources (`third_party/rpf9-explorer` et `tools/rpf9dump`). Si l'un
136 d'eux change, seule l'étape concernée est refaite (désassemblage, traduction ou export des modèles et textures).
88- **`--work`** : choisissez un disque avec au moins 350 Go libres. La traduction des shaders est l'étape la plus 137- **`--work`** : choisissez un disque avec au moins 350 Go libres. La traduction des shaders est l'étape la plus
89 longue ; elle utilise par défaut la moitié des threads du processeur (réglable avec `--jobs`). 138 longue ; elle utilise par défaut la moitié des threads du processeur (réglable avec `--jobs`).
90- **`--wav`** : désactivé par défaut, car le WAV PCM 16 bits est plusieurs fois plus volumineux que l'Ogg Opus. 139- **`--wav`** : désactivé par défaut, car le WAV PCM 16 bits est plusieurs fois plus volumineux que l'Ogg Opus.
91- **Linux et Wine/Proton** : `make_game.py` fonctionne aussi sous Linux. Le chargeur est un programme Windows et 140- **Linux et Wine/Proton** : `make_game.py` fonctionne aussi sous Linux. L'étape `pipelines` utilise
92 tourne sous Wine ou Proton. Pour l'étape `runtime`, vous pouvez passer `--runtime-build <dossier>` avec une 141 `vk_pipeline_check` (compilé avec CMake dans `runtime/build/linux`, ou par le script lui-même s'il manque). Le
93 compilation Windows (`gta6rt.exe` et `gta6rt_tls_host.dll`) : le script écrit alors `gta6rt.sh`, qui lance 142 chargeur est un programme Windows et tourne sous Wine ou Proton : l'étape `runtime` le compile en croisé avec
143 clang-cl et lld-link (LLVM 19+, sauf 22.1.7 et 22.1.8) et le SDK Windows préparé par
144 [xwin](https://github.com/Jake-Shadle/xwin) ; voir [`docs/testing.md`](../../testing.md). Vous pouvez aussi passer
145 `--runtime-build <dossier>` avec une compilation Windows faite ailleurs (`gta6rt.exe` et `gta6rt_tls_host.dll`) :
146 dans les deux cas, le script écrit `gta6rt.sh`, qui lance
94 `gta6rt.exe` avec `wine`, ou avec le Wine désigné par la variable `WINE` (pour Proton, son `files/bin/wine`). 147 `gta6rt.exe` avec `wine`, ou avec le Wine désigné par la variable `WINE` (pour Proton, son `files/bin/wine`).
95 148
96## Problèmes courants 149## Problèmes courants
diff --git a/docs/i18n/it/quickstart.md b/docs/i18n/it/quickstart.md
index d1dc7e494..aab6a0fa2 100644
--- a/docs/i18n/it/quickstart.md
+++ b/docs/i18n/it/quickstart.md
@@ -26,7 +26,7 @@ Il progetto è in fase iniziale: **il gioco non si avvia ancora**.
26 26
27- **La tua copia** del pacchetto Xbox Series, versione `1.0.2.1` (la cartella che contiene `MicrosoftGame.Config` 27- **La tua copia** del pacchetto Xbox Series, versione `1.0.2.1` (la cartella che contiene `MicrosoftGame.Config`
28 e gli archivi `.rpf` come file normali su disco). 28 e gli archivi `.rpf` come file normali su disco).
29- **Windows 10/11 x64** con circa **350 GB liberi** per i file di lavoro (possono stare su un altro disco con 29- **Windows 10/11 x64** con circa **400 GB liberi** per i file di lavoro (possono stare su un altro disco con
30 `--work`). 30 `--work`).
31- [Python 3.12+](https://www.python.org/downloads/) (spunta «Add python.exe to PATH»). 31- [Python 3.12+](https://www.python.org/downloads/) (spunta «Add python.exe to PATH»).
32- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). 32- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
@@ -111,7 +111,7 @@ avvio non devono essere compilati. La traduzione degli shader è il passaggio pi
111 `--no-float-controls`, `--bary-fallback` (GPU senza `VK_KHR_fragment_shader_barycentric`), 111 `--no-float-controls`, `--bary-fallback` (GPU senza `VK_KHR_fragment_shader_barycentric`),
112 `--texel-offset-fallback` (GPU senza `VK_KHR_maintenance8`) e `--mesh-compute` (GPU senza 112 `--texel-offset-fallback` (GPU senza `VK_KHR_maintenance8`) e `--mesh-compute` (GPU senza
113 `VK_EXT_mesh_shader`). Sono documentate in [`docs/design.md`](../../design.md). 113 `VK_EXT_mesh_shader`). Sono documentate in [`docs/design.md`](../../design.md).
114- **`--work`**: conviene puntarlo a un disco con almeno 350 GB liberi. 114- **`--work`**: conviene puntarlo a un disco con almeno 400 GB liberi.
115- **`--wav`**: disattivato di default perché il WAV PCM a 16 bit occupa molto più dell'Ogg Opus. 115- **`--wav`**: disattivato di default perché il WAV PCM a 16 bit occupa molto più dell'Ogg Opus.
116- **Linux e Wine/Proton**: `make_game.py` funziona anche su Linux. Per la fase `runtime` fuori da Windows passa 116- **Linux e Wine/Proton**: `make_game.py` funziona anche su Linux. Per la fase `runtime` fuori da Windows passa
117 `--runtime-build <cartella>` con una build Windows (`gta6rt.exe` e `gta6rt_tls_host.dll`, per esempio 117 `--runtime-build <cartella>` con una build Windows (`gta6rt.exe` e `gta6rt_tls_host.dll`, per esempio
diff --git a/docs/i18n/ja/quickstart.md b/docs/i18n/ja/quickstart.md
index 0dfae7831..8dc9df70b 100644
--- a/docs/i18n/ja/quickstart.md
+++ b/docs/i18n/ja/quickstart.md
@@ -27,7 +27,7 @@ RDNA2 GPU プログラムは Vulkan 向けの SPIR-V に翻訳され、モデル
27 27
28- **自分用の Xbox Series パッケージ**(バージョン `1.0.2.1`)。`MicrosoftGame.Config` と `.rpf` アーカイブが 28- **自分用の Xbox Series パッケージ**(バージョン `1.0.2.1`)。`MicrosoftGame.Config` と `.rpf` アーカイブが
29 プレーンなファイルとして置かれているフォルダーが、ゲームフォルダーです。 29 プレーンなファイルとして置かれているフォルダーが、ゲームフォルダーです。
30- **Windows 10/11 x64** と、作業ファイル用に約 **350 GB** の空き容量(`--work` で別ドライブに置けます)。 30- **Windows 10/11 x64** と、作業ファイル用に約 **400 GB** の空き容量(`--work` で別ドライブに置けます)。
31- [Python 3.12+](https://www.python.org/downloads/)(インストール時に "Add python.exe to PATH" を有効に)。 31- [Python 3.12+](https://www.python.org/downloads/)(インストール時に "Add python.exe to PATH" を有効に)。
32- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)。 32- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)。
33- [Vulkan SDK](https://vulkan.lunarg.com/)(`spirv-as` / `spirv-val` 用)。 33- [Vulkan SDK](https://vulkan.lunarg.com/)(`spirv-as` / `spirv-val` 用)。
@@ -95,7 +95,7 @@ python -I make_game.py --wave64-emulate off # auto(既定)、onã€
95 ネイティブに実行できる RDNA2 のカードや iGPU の場合は、そのドライバーのシェーダーコンパイラーが 95 ネイティブに実行できる RDNA2 のカードや iGPU の場合は、そのドライバーのシェーダーコンパイラーが
96 エミュレーションされた LDS コードでクラッシュするため(#857)、オフのままにします。設定は翻訳済みシェーダーの 96 エミュレーションされた LDS コードでクラッシュするため(#857)、オフのままにします。設定は翻訳済みシェーダーの
97 隣に保存され、変更すると翻訳し直しになります。 97 隣に保存され、変更すると翻訳し直しになります。
98- **`--work`**: 中間ファイル用のフォルダーです。最低でも 350 GB 空いているドライブを指定してください。 98- **`--work`**: 中間ファイル用のフォルダーです。最低でも 400 GB 空いているドライブを指定してください。
99- **`--wav`**: 既定では無効です。16-bit PCM WAV は Ogg Opus より数倍大きいためです。 99- **`--wav`**: 既定では無効です。16-bit PCM WAV は Ogg Opus より数倍大きいためです。
100- **Linux と Wine/Proton**: `make_game.py` は Linux でも動作します。ローダーは Windows プログラムなので 100- **Linux と Wine/Proton**: `make_game.py` は Linux でも動作します。ローダーは Windows プログラムなので
101 Wine または Proton で動きます。`runtime` ステージは Linux 上で clang-cl と lld-link(LLVM 19 以降)を使い、 101 Wine または Proton で動きます。`runtime` ステージは Linux 上で clang-cl と lld-link(LLVM 19 以降)を使い、
diff --git a/docs/i18n/pl-PL/quickstart.md b/docs/i18n/pl-PL/quickstart.md
index 58122ffc4..c091851c2 100644
--- a/docs/i18n/pl-PL/quickstart.md
+++ b/docs/i18n/pl-PL/quickstart.md
@@ -3,15 +3,16 @@
3> [!NOTE] 3> [!NOTE]
4> Dokumentacja w języku angielskim ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) i 4> Dokumentacja w języku angielskim ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) i
5> [`docs/README.md`](../../README.md)) jest **wersją obowiązującą**. Ten przewodnik zawiera tylko stabilne instrukcje 5> [`docs/README.md`](../../README.md)) jest **wersją obowiązującą**. Ten przewodnik zawiera tylko stabilne instrukcje
6> konfiguracji i budowania (zsynchronizowany z commitem `c0ac5fd6`). Aktualny stan projektu znajdziesz w 6> konfiguracji i budowania (zsynchronizowany z commitem `f847748c`). Aktualny stan projektu znajdziesz w
7> [`README.md`](../../../README.md). 7> [`README.md`](../../../README.md).
8 8
9## Czym jest Leonida 9## Czym jest Leonida
10 10
11Leonida to projekt statycznej rekompilacji Grand Theft Auto VI (Xbox Series), który uruchamia grę natywnie na 11Leonida to projekt statycznej rekompilacji Grand Theft Auto VI (Xbox Series), który uruchamia grę natywnie na
12Windowsie. Port jest budowany **na Twoim komputerze z Twojej własnej kopii gry**. Shadery RDNA2 z konsoli są 12Windowsie. Port jest budowany **na Twoim komputerze z Twojej własnej kopii gry**. Procesor Xbox Series jest x86-64
13tłumaczone na SPIR-V (Vulkan), zasoby gry są odczytywane bezpośrednio z Twojej paczki, a oprogramowanie systemowe 13tak jak w komputerze PC, więc kod gry jest ładowany i wykonywany natywnie, a oprogramowanie systemowe konsoli jest
14konsoli jest zaimplementowane od nowa w postaci tzw. shimów. 14implementowane od nowa w postaci tzw. shimów. Skompilowane wcześniej programy GPU konsoli (RDNA2) są tłumaczone na
15SPIR-V (Vulkan), a modele, tekstury i audio są odczytywane bezpośrednio z Twojej paczki.
15 16
16> [!IMPORTANT] 17> [!IMPORTANT]
17> To repozytorium **nie zawiera gry, kluczy ani pliku wykonywalnego** i nie wyjaśnia, jak je zdobyć. Nic tutaj nie 18> To repozytorium **nie zawiera gry, kluczy ani pliku wykonywalnego** i nie wyjaśnia, jak je zdobyć. Nic tutaj nie
@@ -25,15 +26,15 @@ Projekt jest na wczesnym etapie: **gra jeszcze się nie uruchamia**.
25## Wymagania 26## Wymagania
26 27
27- **Twoja własna kopia** paczki Xbox Series w wersji `1.0.2.1` (folder z plikiem `MicrosoftGame.Config` i archiwami `.rpf` czytelnymi na dysku jako zwykłe pliki). 28- **Twoja własna kopia** paczki Xbox Series w wersji `1.0.2.1` (folder z plikiem `MicrosoftGame.Config` i archiwami `.rpf` czytelnymi na dysku jako zwykłe pliki).
28- **Windows 10/11 x64** z około **350 GB wolnego miejsca** na pliki robocze (mogą trafić na inny dysk dzięki `--work`). 29- **Windows 10/11 x64** z około **400 GB wolnego miejsca** na pliki robocze (mogą trafić na inny dysk dzięki `--work`).
29- [Python 3.12+](https://www.python.org/downloads/) (zaznacz *„Add python.exe to PATH”*). 30- [Python 3.12+](https://www.python.org/downloads/) (zaznacz *„Add python.exe to PATH”*).
30- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). 31- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
31- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` i `vulkaninfo`). 32- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` i `vulkaninfo`).
32- [LLVM 21+](https://github.com/llvm/llvm-project/releases) z **targetem AMDGPU** (`llvm-mc`): 33- [LLVM 21+](https://github.com/llvm/llvm-project/releases) z **targetem AMDGPU** (`llvm-mc`):
33 - Oficjalna wersja LLVM dla Windowsa **nie** zawiera targetu AMDGPU. 34 - Oficjalna wersja LLVM dla Windowsa **nie** zawiera targetu AMDGPU.
34 - Aby zbudować natywny `llvm-mc.exe` z AMDGPU, uruchom `.\scripts\build_llvm_mc.ps1` w PowerShellu w głównym 35 - Aby zbudować natywny `llvm-mc.exe` z AMDGPU, uruchom `.\scripts\build_llvm_mc.ps1` w PowerShellu w głównym
35 folderze repozytorium. Skrypt wymaga `git` i narzędzi C++ z Visual Studio, ustawia zmienną `LLVM_MC` dla 36 folderze repozytorium (WSL nie jest potrzebny). Skrypt wymaga `git` i narzędzi C++ z Visual Studio, ustawia
36 Twojego użytkownika i prosi o otwarcie nowego terminala, żeby zmienna była widoczna. 37 zmienną `LLVM_MC` dla Twojego użytkownika i prosi o otwarcie nowego terminala, żeby zmienna była widoczna.
37 - Jeśli używasz WSL, zainstaluj `llvm-21` w Ubuntu i ustaw zmienną w tej samej sesji PowerShella, w której 38 - Jeśli używasz WSL, zainstaluj `llvm-21` w Ubuntu i ustaw zmienną w tej samej sesji PowerShella, w której
38 uruchamiasz `make_game.py`: 39 uruchamiasz `make_game.py`:
39 40
@@ -43,60 +44,131 @@ Projekt jest na wczesnym etapie: **gra jeszcze się nie uruchamia**.
43 44
44 Więcej szczegółów w [`docs/design.md`](../../design.md#disassembling-shaders). 45 Więcej szczegółów w [`docs/design.md`](../../design.md#disassembling-shaders).
45 - Na Linuksie wystarczy `llvm-mc` w `PATH`. 46 - Na Linuksie wystarczy `llvm-mc` w `PATH`.
46- **Visual Studio 2022** z pakietem *Programowanie aplikacji klasycznych w języku C++* i **Windows SDK `10.0.26100` lub nowszym** (potrzebne do etapu `runtime`, który używa root signatures w wersji 1.2). 47- **Visual Studio 2022** z pakietem *Programowanie aplikacji klasycznych w języku C++* i **Windows SDK `10.0.26100`
47- [ffmpeg](https://ffmpeg.org/download.html) w `PATH` *(opcjonalnie: dekoduje strumienie XMA2 i jest wymagany przy `--wav`)*. 48 lub nowszym** (potrzebne do etapu `runtime`, który używa root signatures w wersji 1.2; starsze SDK ich nie
49 deklarują).
50- [ffmpeg](https://ffmpeg.org/download.html) w `PATH` *(opcjonalnie: dekoduje strumienie XMA2 i jest wymagany przy
51 `--wav`)*.
52
53**Mało miejsca na dysku:** około 400 GB dotyczy pełnego builda. Do *uruchomienia* portu etapy
54`--stages check,shaders,runtime` potrzebują około 30 GB; etap `assets` (~370 GB) służy tylko narzędziom do zasobów,
55a `--wav` dodaje kilkakrotność rozmiaru Ogg Opus. `--work` i `--out` mogą leżeć na innym dysku; paczka na dysku
56tylko do odczytu wymaga `--overlay` (opcja `gta6rt`) na dysku zapisywalnym. Nie usuwaj plików `.s` z
57`work/shaders/dxbc/disasm`: skasowanie ich z pozostawieniem folderu sprawia, że etap wygląda na ukończony z zerem
58shaderów, a `disasm` będący dowiązaniem symbolicznym jest odrzucany.
48 59
49## Jak zbudować 60## Jak zbudować
50 61
51### Prosty sposób (Windows) 62Portu nie pobiera się gotowego. Buduje się go na Twoim komputerze z Twojej kopii.
52 63
531. Zainstaluj powyższe wymagania. 64**Prosty sposób:**
542. Sklonuj repozytorium **razem z submodułem**: 65
661. Zainstaluj wymagania powyżej.
672. Pobierz projekt **razem z submodułem**:
55 ```powershell 68 ```powershell
56 git clone --recursive https://github.com/ItsNotRexed/Leonida 69 git clone --recursive https://github.com/ItsNotRexed/Leonida
57 ``` 70 ```
71 „Download ZIP” z GitHuba pomija `third_party/rpf9-explorer`. Build pobierze go sam, jeśli masz `git`, a w
72 przeciwnym razie powie, co zrobić.
583. Kliknij dwukrotnie **`Build.bat`**. 733. Kliknij dwukrotnie **`Build.bat`**.
59 74
60Skrypt sam znajdzie Twoją kopię gry (Pobrane, Pulpit, Dokumenty, Games, folder użytkownika i główne foldery 75Skrypt sam znajdzie Twoją kopię gry: szuka w Pobranych, na Pulpicie, w Dokumentach (także tam, gdzie Windows je
61wszystkich dysków, do dwóch poziomów w głąb). Rozpoznaje wersję po rozmiarach kilku plików, bez czytania dużych 76trzyma, np. w OneDrive), w Games, w folderze użytkownika i na początku każdego dysku, do dwóch poziomów w głąb.
62danych. Jeśli znajdzie kilka kopii, zapyta, której użyć, a jeśli żadnej — poprosi o wklejenie ścieżki do folderu. 77Rozpoznaje wersję po rozmiarach kilku plików, bez czytania dużych danych. Jeśli znajdzie kilka kopii, zapyta, której
63Przed startem sprawdza wymagania i wolne miejsce, a wynik zapisuje w `Documents\Leonida`. Przerwany build można 78użyć, a jeśli żadnej — poprosi o wklejenie ścieżki do folderu. Przed startem sprawdza, czy wszystko jest zainstalowane
64uruchomić ponownie — będzie kontynuowany od miejsca, w którym się zatrzymał. 79i czy jest dość wolnego miejsca, i wymienia wszystkie braki naraz. Wynik zapisuje w `Documents\Leonida`. Przerwany
80build można uruchomić ponownie — będzie kontynuowany od miejsca, w którym się zatrzymał.
65 81
66### Z terminala (`make_game.py`) 82### Z terminala (`make_game.py`)
67 83
84To samo zachowanie i więcej kontroli:
85
68```powershell 86```powershell
69python -I make_game.py --find # lista kopii gry znalezionych na tym komputerze 87python -I make_game.py --find # lista kopii gry znalezionych na tym komputerze
88python -I make_game.py --pick # wybór folderu gry w oknie dialogowym
70python -I make_game.py --check # sprawdza Twoją kopię, niczego nie buduje 89python -I make_game.py --check # sprawdza Twoją kopię, niczego nie buduje
90python -I make_game.py --check --full-check # dodatkowo porównuje SHA-256 każdego pliku (wolno)
71python -I make_game.py --game "D:\sciezka\do\paczki" --out "D:\Games\Leonida" --work "E:\leonida-work" 91python -I make_game.py --game "D:\sciezka\do\paczki" --out "D:\Games\Leonida" --work "E:\leonida-work"
72python -I make_game.py --stages shaders,assets # tylko wybrane etapy 92python -I make_game.py --stages shaders,assets # tylko wybrane etapy
73python -I make_game.py --game "D:\sciezka\do\paczki" --wav # dodatkowo dekoduje Ogg Opus do PCM WAV (duże pliki) 93python -I make_game.py --game "D:\sciezka\do\paczki" --wav # dodatkowo dekoduje Ogg Opus do PCM WAV (duże pliki)
74python -I make_game.py --wave64-emulate auto # auto (domyślnie), on lub off 94python -I make_game.py --wave64-emulate off # auto (domyślnie), on lub off
75``` 95```
76 96
77Etapy wykonują się w tej kolejności: `check` → `shaders` → `assets` → `runtime` → `pipelines`. 97Etapy wykonują się w tej kolejności: `check` → `shaders` → `assets` → `runtime` → `pipelines`. Etap `pipelines`
78 98tworzy każdy przetłumaczony shader na sterowniku Twojej karty graficznej i zapisuje cache potoków, żeby pierwsze
99uruchomienie nie musiało ich kompilować. Tłumaczenie shaderów trwa najdłużej i domyślnie używa połowy wątków
100procesora (można to zmienić przez `--jobs`).
101
102- **`--wave64-emulate`**: decyduje, czy shadery compute i mesh wave64 są tłumaczone tak, by były dokładne przy
103 dowolnym rozmiarze podgrupy (zobacz „Wave64 emulation” w [`docs/design.md`](../../design.md)). Karty NVIDIA i
104 Intel mają podgrupy 32-wątkowe i potrzebują tej emulacji. Domyślny tryb `auto` pyta `vulkaninfo` (część Vulkan SDK)
105 i włącza emulację, jeśli którejś karcie brakuje podgrup 64-wątkowych albo nie da się ustalić ich rozmiaru. Sprawdza
106 też, czy karta używana przez runtime potrafi uruchamiać shadery compute i mesh z podgrupami 64-wątkowymi; z
107 `--mesh-compute` wystarczy obsługa compute. W sterowniku AMD dla Windowsa `auto` używa natywnego wave64 na RDNA1 i
108 RDNA2, gdy karta runtime to obsługuje — nawet jeśli inna karta ma podgrupy 32-wątkowe albo `vulkaninfo` jest
109 niedostępne; ten sterownik potrafi się wysypać na emulowanym kodzie LDS (#857). Na kartach RDNA1 bez obsługi mesh
110 decyzja opiera się na etapie compute, który potrafi uruchomić wave64 bez natywnego mesh. Tryb jest zapisywany obok
111 przetłumaczonych shaderów, a jego zmiana tłumaczy je ponownie. `auto` zwykle może użyć ponownie wcześniej
112 emulowanych shaderów; obejście dla AMD na Windowsie przebudowuje je w trybie natywnym. Użyj `--wave64-emulate on`,
113 aby wymusić emulację, albo `--wave64-emulate off`, aby wymusić natywne wave64.
114- **Cztery flagi awaryjne** są przekazywane do translatora w ten sam sposób, zapisywane obok przetłumaczonych
115 shaderów, a ich zmiana tłumaczy je ponownie: `--no-float-controls` (usuwa `SignedZeroInfNanPreserve` dla urządzeń,
116 których sprawdzanie potoku pomija shader bez `shaderSignedZeroInfNanPreserveFloat32`; wymaga flagi translatora z
117 PR #664), `--bary-fallback` (czyta surowe barycentryki z interpolowanego wejścia, dla urządzeń bez
118 `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (wlicza przesunięcia `image_sample*_o` do
119 współrzędnej, dla urządzeń bez `VK_KHR_maintenance8`) i `--mesh-compute` (shadery mesh jako compute, dla urządzeń
120 bez `VK_EXT_mesh_shader`). Każda jest opisana w [`docs/design.md`](../../design.md).
121- **`--work`**: najlepiej wskazać dysk z co najmniej 400 GB wolnego miejsca; do samego uruchomienia wystarczy około
122 30 GB (zobacz „Mało miejsca na dysku” powyżej).
123- **`--wav`**: domyślnie wyłączone, bo 16-bitowy PCM WAV jest kilkakrotnie większy od Ogg Opus. Dekoduje przepakowane
124 strumienie Ogg Opus do `work\assets\audio\wav` po etapie banków audio; istniejące pliki WAV są pomijane przy
125 wznawianiu builda.
126- **Linux i Wine/Proton**: `make_game.py` działa też na Linuksie, a etap `pipelines` sam buduje tam
127 `vk_pipeline_check`, jeśli go brakuje. Aby wykonać etap `runtime` poza Windowsem, podaj `--runtime-build <folder>`
128 z buildem dla Windowsa (`gta6rt.exe` i `gta6rt_tls_host.dll`, np. rozpakowany artefakt `runtime-windows` z CI).
129 Skrypt skopiuje te pliki do `--out` i utworzy `gta6rt.sh`, który uruchamia program przez `wine` (albo przez Wine
130 wskazane zmienną `WINE`, np. z Protona: `files/bin/wine`). Ta sama opcja pomija build na Windowsie. Alternatywnie
131 etap `runtime` może na Linuksie cross-kompilować loader przez clang-cl i lld-link (LLVM 19+, ale nie 22.1.7 ani
132 22.1.8) przeciw CRT MSVC i Windows SDK przygotowanym przez [xwin](https://github.com/Jake-Shadle/xwin) w
133 `XWIN_DIR` lub `~/.local/share/xwin-sdk`; szczegóły w
134 [`docs/testing.md`](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton).
135
136Build zapisuje polecenie i wersję `llvm-mc`, które utworzyły pliki `.s`, oraz źródła translatora, które utworzyły
137shadery. Zmiana któregokolwiek z nich, a także użycie starszego folderu roboczego, uruchamia ponownie deasemblację
138albo tłumaczenie z zachowaniem wyodrębnionych wejść shaderów.
79- **`--wave64-emulate`**: emuluje shadery compute/mesh wave64 na kartach z podgrupami 32-wątkowymi (NVIDIA i Intel). Domyślny tryb `auto` pyta `vulkaninfo` i sam włącza emulację, gdy jest potrzebna. 139- **`--wave64-emulate`**: emuluje shadery compute/mesh wave64 na kartach z podgrupami 32-wątkowymi (NVIDIA i Intel). Domyślny tryb `auto` pyta `vulkaninfo` i sam włącza emulację, gdy jest potrzebna.
80- **`--work`**: najlepiej wskazać dysk z co najmniej 350 GB wolnego miejsca. Etap `shaders` trwa najdłużej i domyślnie używa połowy wątków procesora (można to zmienić przez `--jobs`). 140- **`--work`**: najlepiej wskazać dysk z co najmniej 400 GB wolnego miejsca. Etap `shaders` trwa najdłużej i domyślnie używa połowy wątków procesora (można to zmienić przez `--jobs`).
81- **Linux i Wine/Proton**: `make_game.py` działa też na Linuksie. Aby wykonać etap `runtime` poza Windowsem, podaj `--runtime-build <folder>` z buildem dla Windowsa (`gta6rt.exe` i `gta6rt_tls_host.dll`). Skrypt utworzy wtedy `gta6rt.sh`, który uruchamia program przez `wine` (albo przez Wine wskazane zmienną `WINE`, np. z Protona). 141- **Linux i Wine/Proton**: `make_game.py` działa też na Linuksie. Aby wykonać etap `runtime` poza Windowsem, podaj `--runtime-build <folder>` z buildem dla Windowsa (`gta6rt.exe` i `gta6rt_tls_host.dll`). Skrypt utworzy wtedy `gta6rt.sh`, który uruchamia program przez `wine` (albo przez Wine wskazane zmienną `WINE`, np. z Protona).
82 142
83## Częste problemy 143## Częste problemy
84 144
85- **Pobrałeś repozytorium przyciskiem „Download ZIP” na GitHubie**: archiwum ZIP nie zawiera submodułu `third_party/rpf9-explorer`. Użyj `git clone --recursive` albo uruchom `git submodule update --init --recursive` w folderze repozytorium. 145- **Pobrałeś repozytorium przyciskiem „Download ZIP” na GitHubie**: archiwum ZIP nie zawiera submodułu
86- **`llvm-mc` odrzuca `gfx1013` / AMDGPU**: najpewniej masz oficjalny instalator LLVM dla Windowsa. Użyj `scripts\build_llvm_mc.ps1` albo ustaw `LLVM_MC` na `llvm-mc` z WSL (`llvm-21`). 146 `third_party/rpf9-explorer`. Użyj `git clone --recursive`; build pobierze submoduł sam, jeśli masz `git`, a jeśli
87- **Błąd `D3D12_ROOT_SIGNATURE_DESC2` przy budowaniu runtime**: zaktualizuj Windows SDK do `10.0.26100` lub nowszego przez Visual Studio Installer albo `winget install Microsoft.WindowsSDK.10.0.26100`, usuń folder builda i skonfiguruj go ponownie. 147 nie — powie, co zrobić. Możesz też uruchomić `git submodule update --init --recursive` w folderze repozytorium.
148- **`llvm-mc` odrzuca `gfx1013` / AMDGPU**: najpewniej masz oficjalny instalator LLVM dla Windowsa. Użyj
149 `scripts\build_llvm_mc.ps1` albo ustaw `LLVM_MC` na `llvm-mc` z WSL (`llvm-21`).
150- **Błąd `D3D12_ROOT_SIGNATURE_DESC2` przy budowaniu runtime**: zaktualizuj Windows SDK do `10.0.26100` lub nowszego
151 przez Visual Studio Installer albo `winget install Microsoft.WindowsSDK.10.0.26100`, usuń folder builda i
152 skonfiguruj go ponownie.
88- **Brak miejsca na dysku `C:`**: podaj `--work "D:\leonida-work"`, aby przenieść pliki robocze na inną partycję. 153- **Brak miejsca na dysku `C:`**: podaj `--work "D:\leonida-work"`, aby przenieść pliki robocze na inną partycję.
154 Do samego uruchomienia wystarczą etapy `--stages check,shaders,runtime` (około 30 GB); `--out` też może leżeć na
155 innym dysku.
89 156
90## Jak pomóc i uruchomić testy GPU 157## Jak pomóc i uruchomić testy GPU
91 158
921. Przejrzyj otwarte PR-y i [issue koordynacyjne][coord], żeby nie dublować pracy. Zarezerwuj zadanie wpisem 1591. Przejrzyj otwarte PR-y i [issue koordynacyjne][coord], żeby nie dublować pracy, i zarezerwuj zadanie **przed**
93 `claiming: <ID>` albo jednym zdaniem opisu, jeśli zadanie nie ma jeszcze ID. 160 otwarciem PR-a: wpisem `claiming: <ID>` albo jednym zdaniem opisu, jeśli zadanie nie ma jeszcze ID.
942. Uruchom odpowiednie testy na syntetycznych danych wejściowych. Na przykład weryfikator manifestów testujesz 1612. Uruchom odpowiednie testy na syntetycznych danych wejściowych. Na przykład weryfikator manifestów testujesz
95 poleceniem `python -I tests/test_manifest_verifier.py` w głównym folderze repozytorium. 162 poleceniem `python -I tests/test_manifest_verifier.py` w głównym folderze repozytorium, a suite translatora —
163 `python -m unittest discover -s tests/semantic -v`.
963. W PR podaj ID zadania, opisz, co przetestowałeś, a jeśli uruchamiałeś testy GPU — podaj kartę i wersję 1643. W PR podaj ID zadania, opisz, co przetestowałeś, a jeśli uruchamiałeś testy GPU — podaj kartę i wersję
97 sterownika. Zaznacz, czy korzystałeś z pomocy AI. Zasady znajdziesz w [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). 165 sterownika. Zaznacz, czy korzystałeś z pomocy AI, zgodnie z [`AGENTS.md`](../../../AGENTS.md). Zasady znajdziesz
166 w [`CONTRIBUTING.md`](../../../CONTRIBUTING.md).
167
168**Nigdy** nie załączaj do issues ani PR-ów plików gry, wyodrębnionych zasobów ani wygenerowanych shaderów: dziel się
169tylko wynikami (liczby, wyniki testów, klasy błędów).
98 170
99[Przewodnik po testach GPU](../../testing.md) pokazuje, jak uruchomić testy bez plików gry. 171[Przewodnik po testach GPU](../../testing.md) pokazuje, jak uruchomić testy bez plików gry. Wyniki testów GPU
100Wyniki testów GPU publikuj w [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). 172publikuj w [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166).
101 173
102[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 174[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22
diff --git a/docs/i18n/pt-BR/quickstart.md b/docs/i18n/pt-BR/quickstart.md
index e528154fe..636567659 100644
--- a/docs/i18n/pt-BR/quickstart.md
+++ b/docs/i18n/pt-BR/quickstart.md
@@ -3,7 +3,6 @@
3> [!NOTE] 3> [!NOTE]
4> A documentação em inglês ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) e 4> A documentação em inglês ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) e
5> [`docs/README.md`](../../README.md)) é a **referência oficial**. Este guia reúne apenas instruções estáveis de 5> [`docs/README.md`](../../README.md)) é a **referência oficial**. Este guia reúne apenas instruções estáveis de
6> configuração e compilação (sincronizado com o commit `16282101`). Para o status diário do projeto, consulte o
7> configuração e compilação (sincronizado com o commit `f847748c`). Para o status diário do projeto, consulte o 6> configuração e compilação (sincronizado com o commit `f847748c`). Para o status diário do projeto, consulte o
8> [`README.md`](../../../README.md). 7> [`README.md`](../../../README.md).
9 8
@@ -25,7 +24,7 @@ O projeto está em fase inicial: **o jogo ainda não dá boot**.
25## Pré-requisitos 24## Pré-requisitos
26 25
27- **Sua própria cópia** do pacote Xbox Series, versão `1.0.2.1` (pasta com `MicrosoftGame.Config` e os arquivos `.rpf` legíveis em disco). 26- **Sua própria cópia** do pacote Xbox Series, versão `1.0.2.1` (pasta com `MicrosoftGame.Config` e os arquivos `.rpf` legíveis em disco).
28- **Windows 10/11 x64** com cerca de **30 GB livres** para preparar só o runtime ou **350 GB** para o build completo. 27- **Windows 10/11 x64** com cerca de **30 GB livres** para preparar só o runtime ou **400 GB** para o build completo.
29- [Python 3.12+](https://www.python.org/downloads/) (marque *"Add python.exe to PATH"*). 28- [Python 3.12+](https://www.python.org/downloads/) (marque *"Add python.exe to PATH"*).
30- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). 29- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
31- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` e `vulkaninfo`). 30- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` e `vulkaninfo`).
@@ -51,12 +50,9 @@ O projeto está em fase inicial: **o jogo ainda não dá boot**.
51- **Visual Studio 2022** com *Desenvolvimento para desktop com C++* e **Windows SDK `10.0.26100` ou mais recente** (necessário para o estágio `runtime`, que usa root signatures 1.2). 50- **Visual Studio 2022** com *Desenvolvimento para desktop com C++* e **Windows SDK `10.0.26100` ou mais recente** (necessário para o estágio `runtime`, que usa root signatures 1.2).
52- [ffmpeg](https://ffmpeg.org/download.html) no `PATH` *(opcional: decodifica streams XMA2 e é exigido ao usar `--wav`)*. 51- [ffmpeg](https://ffmpeg.org/download.html) no `PATH` *(opcional: decodifica streams XMA2 e é exigido ao usar `--wav`)*.
53 52
54**Pouco espaço em disco:** o valor de ~350 GB refere-se ao build completo. Para *executar* o port, 53**Pouco espaço em disco:** o valor de ~400 GB refere-se ao build completo. Para *executar* o port,
55`--stages check,shaders,runtime` precisa de cerca de **30 GB**; o estágio `assets` (~300 GB) serve apenas para as 54`--stages check,shaders,runtime` precisa de cerca de **30 GB**; o estágio `assets` (~370 GB) serve apenas para as
56ferramentas de extração de assets, e `--wav` adiciona várias vezes o tamanho dos arquivos Ogg Opus. `--work` e `--out` 55ferramentas de extração de assets, e `--wav` adiciona várias vezes o tamanho dos arquivos Ogg Opus. `--work` e `--out`
57podem apontar para outro disco; se o pacote do jogo estiver em uma unidade somente leitura, use `--overlay` em um disco
58gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm`: apagá-los mantendo a pasta faz o estágio parecer
59concluído com zero shaders, e um link simbólico em `disasm` é recusado.
60podem apontar para outro disco; se o pacote do jogo estiver em uma unidade somente leitura, use `--overlay` (no 56podem apontar para outro disco; se o pacote do jogo estiver em uma unidade somente leitura, use `--overlay` (no
61`gta6rt`) em um disco gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm`: apagá-los mantendo a pasta faz 57`gta6rt`) em um disco gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm`: apagá-los mantendo a pasta faz
62o estágio parecer concluído com zero shaders, e um link simbólico em `disasm` é recusado. 58o estágio parecer concluído com zero shaders, e um link simbólico em `disasm` é recusado.
@@ -76,8 +72,8 @@ O script procura automaticamente sua cópia (Downloads, Desktop, Documentos, Gam
76discos até dois níveis), valida os pré-requisitos e o espaço livre e grava o resultado em `Documents\Leonida`. 72discos até dois níveis), valida os pré-requisitos e o espaço livre e grava o resultado em `Documents\Leonida`.
77Se o build for interrompido, basta rodar novamente para retomar de onde parou. 73Se o build for interrompido, basta rodar novamente para retomar de onde parou.
78 74
79**Espaço em disco baixo:** o valor de ~350 GB é para o build completo. Para *rodar* o port, `--stages check,shaders,runtime` 75**Espaço em disco baixo:** o valor de ~400 GB é para o build completo. Para *rodar* o port, `--stages check,shaders,runtime`
80precisa de cerca de 30 GB; o estágio `assets` (~300 GB) é apenas para as ferramentas de assets, e `--wav` adiciona 76precisa de cerca de 30 GB; o estágio `assets` (~370 GB) é apenas para as ferramentas de assets, e `--wav` adiciona
81várias vezes o tamanho do Ogg Opus. `--work` e `--out` podem ficar em outro disco; uma unidade de pacote somente leitura 77várias vezes o tamanho do Ogg Opus. `--work` e `--out` podem ficar em outro disco; uma unidade de pacote somente leitura
82precisa de `--overlay` em uma gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm` no lugar: apagá-los 78precisa de `--overlay` em uma gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm` no lugar: apagá-los
83mantendo a pasta faz o estágio parecer concluído com zero shaders, e um `disasm` com symlink é recusado. 79mantendo a pasta faz o estágio parecer concluído com zero shaders, e um `disasm` com symlink é recusado.
@@ -92,16 +88,15 @@ python -I make_game.py --check --full-check # também compara o SHA-2
92python -I make_game.py --game "D:\caminho\do\pacote" --out "D:\Games\Leonida" --work "E:\leonida-work" 88python -I make_game.py --game "D:\caminho\do\pacote" --out "D:\Games\Leonida" --work "E:\leonida-work"
93python -I make_game.py --stages shaders,assets # roda apenas os estágios escolhidos 89python -I make_game.py --stages shaders,assets # roda apenas os estágios escolhidos
94python -I make_game.py --game "D:\caminho\do\pacote" --wav # também decodifica Ogg Opus para PCM WAV (grande) 90python -I make_game.py --game "D:\caminho\do\pacote" --wav # também decodifica Ogg Opus para PCM WAV (grande)
95python -I make_game.py --wave64-emulate auto # auto (padrão), on ou off 91python -I make_game.py --wave64-emulate off # auto (padrão), on ou off; veja abaixo
96``` 92```
97 93
98Os estágios executam nesta ordem: `check` → `shaders` → `assets` → `runtime` → `pipelines`. 94Os estágios executam nesta ordem: `check` → `shaders` → `assets` → `runtime` → `pipelines`.
99 95
100- **`--wave64-emulate`**: emula shaders compute/mesh wave64 em GPUs com subgrupos de 32 lanes (NVIDIA e Intel). O padrão `auto` consulta `vulkaninfo` e ativa a emulação automaticamente quando necessário (exceto em GPUs AMD RDNA2 no driver Windows que executam wave64 nativamente, onde o compilador do driver falha em código LDS emulado, #857). O modo escolhido fica salvo junto aos shaders traduzidos. 96- **`--wave64-emulate`**: emula shaders compute/mesh wave64 em GPUs com subgrupos de 32 lanes (NVIDIA e Intel). O padrão `auto` consulta `vulkaninfo` e ativa a emulação se alguma GPU não tiver subgrupos de 64 lanes ou se o tamanho for desconhecido, verificando também se a GPU do runtime suporta compute e mesh em 64 lanes (com `--mesh-compute`, apenas o suporte em compute é necessário). No driver Windows da AMD, `auto` usa wave64 nativo em GPUs RDNA1 e RDNA2 quando a GPU do runtime suporta (para placas RDNA1 sem suporte a mesh shaders, a decisão usa o estágio compute), mesmo que outra GPU seja de 32 lanes ou que `vulkaninfo` não esteja disponível, pois o compilador desse driver pode falhar em código LDS emulado (#857). O modo escolhido fica salvo junto aos shaders traduzidos; use `--wave64-emulate on` para forçar a emulação ou `--wave64-emulate off` para forçar wave64 nativo.
101- **Flags de fallback do tradutor**: `--no-float-controls` (omite `SignedZeroInfNanPreserve`), `--bary-fallback` (lê baricêntricas de um input interpolado sem `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (incorpora offsets `image_sample*_o` na coordenada sem `VK_KHR_maintenance8`) e `--mesh-compute` (traduz mesh shaders como compute sem `VK_EXT_mesh_shader`) são repassadas ao tradutor e salvas junto aos shaders; alterá-las retraduz os shaders (veja [`docs/design.md`](../../design.md)). 97- **Flags de fallback do tradutor**: `--no-float-controls` (omite `SignedZeroInfNanPreserve`), `--bary-fallback` (lê baricêntricas de um input interpolado sem `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (incorpora offsets `image_sample*_o` na coordenada sem `VK_KHR_maintenance8`) e `--mesh-compute` (traduz mesh shaders como compute sem `VK_EXT_mesh_shader`) são repassadas ao tradutor e salvas junto aos shaders; alterá-las retraduz os shaders (veja [`docs/design.md`](../../design.md)).
102- **`--work`**: recomenda-se apontar para um disco com pelo menos 350 GB livres para o build completo (ou ~30 GB com `--stages check,shaders,runtime`); o estágio `shaders` é o mais demorado e usa metade das threads da CPU por padrão (ajustável com `--jobs`). 98- **`--work`**: recomenda-se apontar para um disco com pelo menos 400 GB livres para o build completo (ou ~30 GB com `--stages check,shaders,runtime`); o estágio `shaders` é o mais demorado e usa metade das threads da CPU por padrão (ajustável com `--jobs`).
103- **`--wav`**: fica desativado por padrão porque WAV PCM de 16 bits é várias vezes maior que Ogg Opus; quando ativado, decodifica os streams Ogg Opus para `work\assets\audio\wav` e pula arquivos WAV já existentes ao retomar um build. 99- **`--wav`**: fica desativado por padrão porque WAV PCM de 16 bits é várias vezes maior que Ogg Opus; quando ativado, decodifica os streams Ogg Opus para `work\assets\audio\wav` e pula arquivos WAV já existentes ao retomar um build.
104- **`--work`**: escolhe onde ficam os arquivos intermediários. O estágio `shaders` usa metade das threads da CPU por padrão (ajustável com `--jobs`).
105 100
106### Build com pouco espaço em disco 101### Build com pouco espaço em disco
107 102
@@ -111,12 +106,12 @@ Para preparar o runtime e os shaders com cerca de **30 GB livres**, execute na r
111python -I make_game.py --stages check,shaders,runtime 106python -I make_game.py --stages check,shaders,runtime
112``` 107```
113 108
114O estágio `assets` serve às ferramentas de extração e ocupa cerca de 300 GB. A opção `--wav` aumenta ainda mais 109O estágio `assets` serve às ferramentas de extração e ocupa cerca de 370 GB. A opção `--wav` aumenta ainda mais
115o espaço usado pelos áudios. Você pode apontar `--work` e `--out` para outro disco. Se o disco do pacote for 110o espaço usado pelos áudios. Você pode apontar `--work` e `--out` para outro disco. Se o disco do pacote for
116somente leitura, passe `--overlay` ao iniciar o runtime e aponte para uma pasta em um disco gravável. 111somente leitura, passe `--overlay` ao iniciar o runtime e aponte para uma pasta em um disco gravável.
117- **`--wave64-emulate`**: emula shaders compute/mesh wave64 em GPUs com subgrupos de 32 lanes (NVIDIA e Intel). O padrão `auto` consulta `vulkaninfo` e ativa a emulação se alguma GPU não tiver subgrupos de 64 lanes ou se o tamanho for desconhecido, verificando também se a GPU do runtime suporta compute e mesh em 64 lanes (com `--mesh-compute`, apenas o suporte em compute é necessário). No driver Windows da AMD, `auto` usa wave64 nativo em GPUs RDNA1 e RDNA2 quando a GPU do runtime suporta (para placas RDNA1 sem suporte a mesh shaders, a decisão usa o estágio compute), mesmo que outra GPU seja de 32 lanes ou que `vulkaninfo` não esteja disponível, pois o compilador desse driver pode falhar em código LDS emulado (#857). O modo escolhido fica salvo junto aos shaders traduzidos; use `--wave64-emulate on` para forçar a emulação ou `--wave64-emulate off` para forçar wave64 nativo. 112- **`--wave64-emulate`**: emula shaders compute/mesh wave64 em GPUs com subgrupos de 32 lanes (NVIDIA e Intel). O padrão `auto` consulta `vulkaninfo` e ativa a emulação se alguma GPU não tiver subgrupos de 64 lanes ou se o tamanho for desconhecido, verificando também se a GPU do runtime suporta compute e mesh em 64 lanes (com `--mesh-compute`, apenas o suporte em compute é necessário). No driver Windows da AMD, `auto` usa wave64 nativo em GPUs RDNA1 e RDNA2 quando a GPU do runtime suporta (para placas RDNA1 sem suporte a mesh shaders, a decisão usa o estágio compute), mesmo que outra GPU seja de 32 lanes ou que `vulkaninfo` não esteja disponível, pois o compilador desse driver pode falhar em código LDS emulado (#857). O modo escolhido fica salvo junto aos shaders traduzidos; use `--wave64-emulate on` para forçar a emulação ou `--wave64-emulate off` para forçar wave64 nativo.
118- **Flags de fallback do tradutor**: `--no-float-controls` (omite `SignedZeroInfNanPreserve`), `--bary-fallback` (lê baricêntricas de um input interpolado sem `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (incorpora offsets `image_sample*_o` na coordenada sem `VK_KHR_maintenance8`) e `--mesh-compute` (traduz mesh shaders como compute sem `VK_EXT_mesh_shader`) são repassadas ao tradutor e salvas junto aos shaders; alterá-las retraduz os shaders (veja [`docs/design.md`](../../design.md)). 113- **Flags de fallback do tradutor**: `--no-float-controls` (omite `SignedZeroInfNanPreserve`), `--bary-fallback` (lê baricêntricas de um input interpolado sem `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (incorpora offsets `image_sample*_o` na coordenada sem `VK_KHR_maintenance8`) e `--mesh-compute` (traduz mesh shaders como compute sem `VK_EXT_mesh_shader`) são repassadas ao tradutor e salvas junto aos shaders; alterá-las retraduz os shaders (veja [`docs/design.md`](../../design.md)).
119- **`--work`**: recomenda-se apontar para um disco com pelo menos 350 GB livres para o build completo (ou ~30 GB com `--stages check,shaders,runtime`); o estágio `shaders` é o mais demorado e usa metade das threads da CPU por padrão (ajustável com `--jobs`). 114- **`--work`**: recomenda-se apontar para um disco com pelo menos 400 GB livres para o build completo (ou ~30 GB com `--stages check,shaders,runtime`); o estágio `shaders` é o mais demorado e usa metade das threads da CPU por padrão (ajustável com `--jobs`).
120- **`--wav`**: fica desativado por padrão porque WAV PCM de 16 bits é várias vezes maior que Ogg Opus; quando ativado, decodifica os streams Ogg Opus para `work\assets\audio\wav` e pula arquivos WAV já existentes ao retomar um build. 115- **`--wav`**: fica desativado por padrão porque WAV PCM de 16 bits é várias vezes maior que Ogg Opus; quando ativado, decodifica os streams Ogg Opus para `work\assets\audio\wav` e pula arquivos WAV já existentes ao retomar um build.
121 116
122### Diagnóstico do Vulkan no Linux 117### Diagnóstico do Vulkan no Linux
diff --git a/docs/i18n/ru/quickstart.md b/docs/i18n/ru/quickstart.md
index c22c09e79..818e47fe4 100644
--- a/docs/i18n/ru/quickstart.md
+++ b/docs/i18n/ru/quickstart.md
@@ -3,7 +3,7 @@
3> [!NOTE] 3> [!NOTE]
4> Главный источник: английская документация ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) 4> Главный источник: английская документация ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)
5> и [`docs/README.md`](../../README.md)). Этот гайд покрывает только стабильные шаги установки и сборки 5> и [`docs/README.md`](../../README.md)). Этот гайд покрывает только стабильные шаги установки и сборки
6> (сверен с коммитом `a0acd33`). Текущее состояние проекта меняется каждый день, его смотрите в 6> (сверен с коммитом `aa2988cc`). Текущее состояние проекта меняется каждый день, его смотрите в
7> [`README.md`](../../../README.md). 7> [`README.md`](../../../README.md).
8 8
9## Что такое Leonida 9## Что такое Leonida
@@ -21,6 +21,23 @@ Windows. Процессор консоли x86-64, как у ПК, поэтомÑ
21 21
22Проект на раннем этапе: **игра пока не запускается**. 22Проект на раннем этапе: **игра пока не запускается**.
23 23
24## Платформы
25
26Ни на одной платформе пока ничего не играбельно. Что где работает сегодня:
27
28- **Windows**: всё (`make_game.py`, инструменты и runtime `gta6rt` со слоем D3D12 → Vulkan и его тестами).
29- **Linux**: переводчик, инструменты ресурсов и инструменты GPU-тестов Vulkan собираются и работают нативно
30 (проверено на RADV и NVIDIA). Runtime это код для Windows: он кросс-собирается через clang-cl и xwin, а его тесты
31 идут под Wine или Proton. Игра должна запускаться так же (#217).
32- **macOS (Apple Silicon)**: инструменты на Python и инструменты тестов Vulkan работают нативно, на MoltenVK
33 (Homebrew) или KosmicKrisp. Runtime идёт под Wine, как на Linux. Известные ограничения: нет этапа geometry и
34 `VK_EXT_mesh_shader`, подгруппы шириной 32 (шейдеры wave64 эмулируются) и работа MoltenVK с числами с плавающей
35 точкой; все они перечислены в [`docs/testing.md`](../../testing.md).
36- **AMD RDNA1 (RX 5000)**: поддерживаемая цель, близкая к RDNA2 консоли; её подгруппы шириной 64 выполняют
37 шейдеры wave64 нативно.
38
39Результаты GPU со всех платформ собираются в [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166).
40
24## Что нужно 41## Что нужно
25 42
26- **Своя копия** пакета Xbox Series версии `1.0.2.1`: папка, где `MicrosoftGame.Config` и архивы `.rpf` лежат 43- **Своя копия** пакета Xbox Series версии `1.0.2.1`: папка, где `MicrosoftGame.Config` и архивы `.rpf` лежат
@@ -34,7 +51,11 @@ Windows. Процессор консоли x86-64, как у ПК, поэтомÑ
34 - в официальной сборке LLVM для Windows цели AMDGPU нет; 51 - в официальной сборке LLVM для Windows цели AMDGPU нет;
35 - на Windows `scripts\build_llvm_mc.ps1` собирает свой `llvm-mc.exe` с этой целью (без WSL, нужны `git` и 52 - на Windows `scripts\build_llvm_mc.ps1` собирает свой `llvm-mc.exe` с этой целью (без WSL, нужны `git` и
36 инструменты C++ из Visual Studio ниже) и прописывает `LLVM_MC`; после этого откройте новый терминал, чтобы 53 инструменты C++ из Visual Studio ниже) и прописывает `LLVM_MC`; после этого откройте новый терминал, чтобы
37 переменная подхватилась; 54 переменная подхватилась. Сборка занимает 20-40 минут;
55 - быстрее, если вы пользуетесь [conda](https://docs.conda.io/): `conda install -c conda-forge llvm-tools` (в её
56 сборке для Windows цель AMDGPU есть), затем укажите в `LLVM_MC` полный путь к установленному `llvm-mc.exe`
57 (`where.exe llvm-mc` покажет его в активированном окружении; в PowerShell команда `where` без `.exe` — это
58 `Where-Object`);
38 - если ставите `llvm-21` в WSL, передайте `LLVM_MC` целой командой в той же сессии PowerShell, откуда 59 - если ставите `llvm-21` в WSL, передайте `LLVM_MC` целой командой в той же сессии PowerShell, откуда
39 запускаете `make_game.py`: 60 запускаете `make_game.py`:
40 61
@@ -69,6 +90,15 @@ OneDrive), `Games`, домашнюю папку и корень каждого Ð
69хватает, и покажет все недостающие пункты разом. Результат пишется в `Documents\Leonida`. Прерванная 90хватает, и покажет все недостающие пункты разом. Результат пишется в `Documents\Leonida`. Прерванная
70сборка продолжается с того места, где встала. 91сборка продолжается с того места, где встала.
71 92
93### Мало места на диске
94
95Объём, указанный выше, нужен для полной сборки. Чтобы *запустить* порт, `--stages check,shaders,runtime` хватает
96примерно 30 ГБ; этап `assets`, на который приходится почти всё остальное, нужен только инструментам ресурсов, а
97`--wav` добавляет ещё в несколько раз больше, чем занимает Ogg Opus. `--work` и `--out` можно вынести на другой диск. Runtime читает пакет на месте, поэтому для
98диска только для чтения нужен `gta6rt --overlay <папка с правом записи>` (это флаг `gta6rt`, а не `make_game.py`).
99Не удаляйте файлы `.s` в `work/shaders/dxbc/disasm`: без них и без `work/shaders/spirv/index.json` этап `shaders`
100может выглядеть завершённым с нулём шейдеров.
101
72### Из терминала (`make_game.py`) 102### Из терминала (`make_game.py`)
73 103
74```powershell 104```powershell
@@ -83,17 +113,21 @@ python -I make_game.py --wave64-emulate off # auto (по умолча
83``` 113```
84 114
85Этапы идут в таком порядке: `check`, `shaders`, `assets`, `runtime`, `pipelines`. Последний создаёт все 115Этапы идут в таком порядке: `check`, `shaders`, `assets`, `runtime`, `pipelines`. Последний создаёт все
86переведённые шейдеры на драйвере вашей видеокарты и сохраняет кеш конвейеров, чтобы при первой загрузке их не 116переведённые шейдеры на драйвере вашей видеокарты, проверяет, что они компилируются, сообщает о пропущенных и
87пришлось компилировать. Перевод шейдеров самый долгий: он выполняется в `--jobs` процессов (по умолчанию 117сохраняет кеш конвейеров в `pipeline_cache.bin` в `--out`. Runtime этот кеш пока не загружает, так что первую
118загрузку он не ускоряет. Перевод шейдеров самый долгий: он выполняется в `--jobs` процессов (по умолчанию
88половина потоков процессора). 119половина потоков процессора).
89 120
90- **`--wave64-emulate`**: переводить ли compute- и mesh-шейдеры wave64 так, чтобы они работали точно при любом 121- **`--wave64-emulate`**: переводить ли compute- и mesh-шейдеры wave64 так, чтобы они работали точно при любом
91 размере подгруппы (раздел «Wave64 emulation» в [`docs/design.md`](../../design.md)). У NVIDIA и Intel подгруппы 122 размере подгруппы (раздел «Wave64 emulation» в [`docs/design.md`](../../design.md)). У NVIDIA и Intel подгруппы
92 шириной 32, им это нужно. Режим `auto` спрашивает `vulkaninfo` из Vulkan SDK и включает эмуляцию в трёх 123 шириной 32, им это нужно. Режим `auto` спрашивает `vulkaninfo` из Vulkan SDK и включает эмуляцию в трёх
93 случаях: не все видеокарты сообщают подгруппы шириной 64, ответ получить не удалось, или карта для runtime не 124 случаях: не все видеокарты сообщают подгруппы шириной 64, ответ получить не удалось, или карта для runtime не
94 умеет выполнять compute- и mesh-шейдеры на 64. Режим сохраняется рядом с переведёнными шейдерами, и его смена 125 умеет выполнять compute- и mesh-шейдеры на 64 (с `--mesh-compute` нужна только поддержка compute). На драйвере
95 запускает перевод заново. При `auto` рабочая папка, где эмуляция уже использовалась, держит её и дальше, даже 126 AMD для Windows `auto` берёт нативный wave64 на RDNA1 и RDNA2, если карта для runtime его поддерживает, даже
96 если текущая карта умеет wave64 нативно. 127 когда другая карта шириной 32 или `vulkaninfo` недоступен: этот драйвер может падать на эмулированном коде LDS
128 (#857). Режим сохраняется рядом с переведёнными шейдерами, и его смена запускает перевод заново. При `auto`
129 обычно можно переиспользовать уже эмулированные шейдеры; обход для драйвера AMD пересобирает их в нативном
130 режиме.
97- **`--work`**: выберите диск, где свободно хотя бы 350 ГБ. 131- **`--work`**: выберите диск, где свободно хотя бы 350 ГБ.
98- **`--wav`**: по умолчанию выключен, потому что 16-битный PCM WAV в несколько раз больше Ogg Opus. Флаг 132- **`--wav`**: по умолчанию выключен, потому что 16-битный PCM WAV в несколько раз больше Ogg Opus. Флаг
99 декодирует перепакованные потоки Ogg Opus в `work\assets\audio\wav` после этапа аудио; готовые WAV при 133 декодирует перепакованные потоки Ogg Opus в `work\assets\audio\wav` после этапа аудио; готовые WAV при
@@ -107,9 +141,16 @@ python -I make_game.py --wave64-emulate off # auto (по умолча
107(mesh-шейдеры как compute, для устройств без `VK_EXT_mesh_shader`). Каждый описан в 141(mesh-шейдеры как compute, для устройств без `VK_EXT_mesh_shader`). Каждый описан в
108[`docs/design.md`](../../design.md). 142[`docs/design.md`](../../design.md).
109 143
144Сборка запоминает, чем сделаны результаты: команду и версию `llvm-mc`, исходники переводчика и декодер ресурсов
145(коммит `third_party/rpf9-explorer` и исходники `tools/rpf9dump`). Если что-то из этого меняется, заново
146выполняется только нужная часть: дизассемблирование, перевод или экспорт моделей и текстур архива. Старые рабочие
147папки без такой записи один раз проходят эти шаги повторно после обновления.
148
110### Linux и Wine/Proton 149### Linux и Wine/Proton
111 150
112`make_game.py` работает и на Linux. Загрузчик (`gta6rt.exe`) это программа для Windows, поэтому на Linux она 151`make_game.py` работает и на Linux. Этап `pipelines` использует `vk_pipeline_check` (CMake 3.24+, компилятор
152C++20 и заголовки Vulkan; собирается в `runtime/build/linux`, а если его нет, скрипт соберёт его сам до остальной
153работы). Загрузчик (`gta6rt.exe`) это программа для Windows, поэтому на Linux она
113идёт под Wine или Proton. Этап `runtime` на Linux кросс-собирается в `runtime/build/windows` через `clang-cl` и 154идёт под Wine или Proton. Этап `runtime` на Linux кросс-собирается в `runtime/build/windows` через `clang-cl` и
114`lld-link` 155`lld-link`
115(LLVM 19+, но не 22.1.7 и не 22.1.8, см. [`docs/testing.md`](../../testing.md#known-problems)) против CRT от MSVC и 156(LLVM 19+, но не 22.1.7 и не 22.1.8, см. [`docs/testing.md`](../../testing.md#known-problems)) против CRT от MSVC и
diff --git a/docs/i18n/tr/quickstart.md b/docs/i18n/tr/quickstart.md
index 8480a752f..652a707fa 100644
--- a/docs/i18n/tr/quickstart.md
+++ b/docs/i18n/tr/quickstart.md
@@ -3,7 +3,7 @@
3> [!NOTE] 3> [!NOTE]
4> İngilizce dokümantasyon ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) ve 4> İngilizce dokümantasyon ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) ve
5> [`docs/README.md`](../../README.md)) **yetkili kaynaktır**. Bu rehber yalnızca kararlı kurulum ve derleme 5> [`docs/README.md`](../../README.md)) **yetkili kaynaktır**. Bu rehber yalnızca kararlı kurulum ve derleme
6> yönergelerini kapsar (`f85582e` commit'ine göre eşitlenmiştir). Günlük değişen proje durumu için 6> yönergelerini kapsar (`561b65a` commit'ine göre eşitlenmiştir). Günlük değişen proje durumu için
7> [`README.md`](../../../README.md) dosyasına bakın. 7> [`README.md`](../../../README.md) dosyasına bakın.
8 8
9## Leonida Nedir? 9## Leonida Nedir?
@@ -26,8 +26,9 @@ Proje henüz erken aşamadadır: **oyun şu an açılmıyor**.
26 26
27- **Kendi Xbox Series paket kopyanız**, sürüm `1.0.2.1` (`MicrosoftGame.Config` dosyasını ve `.rpf` arşivlerini diskte 27- **Kendi Xbox Series paket kopyanız**, sürüm `1.0.2.1` (`MicrosoftGame.Config` dosyasını ve `.rpf` arşivlerini diskte
28 düz dosyalar olarak barındıran klasör). 28 düz dosyalar olarak barındıran klasör).
29- **Windows 10/11 x64** ve çalışma dosyaları için yaklaşık **350 GB boş disk alanı** (`--work` ile başka bir diske 29- **Windows 10/11 x64** ve çalışma dosyaları için yaklaşık **400 GB boş disk alanı** (`--work` ile başka bir diske
30 yönlendirilebilir). 30 yönlendirilebilir). Bu rakam tam derleme içindir: yalnızca çalıştırmak için `--stages check,shaders,runtime`
31 yaklaşık 30 GB ister, `assets` aşaması ise yaklaşık 370 GB.
31- [Python 3.12+](https://www.python.org/downloads/) (kurulumda *"Add python.exe to PATH"* seçeneğini işaretleyin). 32- [Python 3.12+](https://www.python.org/downloads/) (kurulumda *"Add python.exe to PATH"* seçeneğini işaretleyin).
32- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). 33- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0).
33- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` ve `vulkaninfo` için). 34- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` ve `vulkaninfo` için).
@@ -36,6 +37,10 @@ Proje henüz erken aşamadadır: **oyun şu an açılmıyor**.
36 - AMDGPU destekli yerel `llvm-mc.exe` derlemek için depo kök dizininde PowerShell'den `.\scripts\build_llvm_mc.ps1` 37 - AMDGPU destekli yerel `llvm-mc.exe` derlemek için depo kök dizininde PowerShell'den `.\scripts\build_llvm_mc.ps1`
37 betiğini çalıştırın (`git` ve aşağıdaki Visual Studio C++ araçları gerekir). Betik kullanıcınız için `LLVM_MC` 38 betiğini çalıştırın (`git` ve aşağıdaki Visual Studio C++ araçları gerekir). Betik kullanıcınız için `LLVM_MC`
38 ortam değişkenini ayarlar; geçerli olması için yeni bir terminal açın. 39 ortam değişkenini ayarlar; geçerli olması için yeni bir terminal açın.
40 - Daha hızlı bir yol: [conda](https://docs.conda.io/) kullanıyorsanız `conda install -c conda-forge llvm-tools`
41 (Windows derlemesi AMDGPU hedefini içerir; [`docs/testing.md`](../../testing.md) 23.1.6 sürümünü kullandı), ardından
42 `LLVM_MC` değişkenini kurduğu `llvm-mc.exe` dosyasının tam yoluna ayarlayın (ortam etkinleştirildikten sonra
43 `where.exe llvm-mc` yolunu gösterir; PowerShell'de çıplak `where` komutu `Where-Object` demektir).
39 - Alternatif olarak WSL (Ubuntu) içinde `llvm-21` kurup `make_game.py` çalıştıracağınız PowerShell oturumunda 44 - Alternatif olarak WSL (Ubuntu) içinde `llvm-21` kurup `make_game.py` çalıştıracağınız PowerShell oturumunda
40 `LLVM_MC` değişkenini tam komut olarak ayarlayın: 45 `LLVM_MC` değişkenini tam komut olarak ayarlayın:
41 46
@@ -71,7 +76,9 @@ yazılır; yarım kalan bir derleme kaldığı yerden devam eder.
71 76
72```powershell 77```powershell
73python -I make_game.py --find # bilgisayarda bulunan kopyaları listele 78python -I make_game.py --find # bilgisayarda bulunan kopyaları listele
79python -I make_game.py --pick # oyun klasörünü bir klasör penceresinde seç
74python -I make_game.py --check # kopyayı doğrula, derleme yapma 80python -I make_game.py --check # kopyayı doğrula, derleme yapma
81python -I make_game.py --check --full-check # ayrıca her dosyanın SHA-256 özetini karşılaştır (yavaş)
75python -I make_game.py --game "D:\paket\yolu" --out "D:\Games\Leonida" --work "E:\leonida-work" 82python -I make_game.py --game "D:\paket\yolu" --out "D:\Games\Leonida" --work "E:\leonida-work"
76python -I make_game.py --stages shaders,assets # yalnızca seçili aşamaları çalıştır 83python -I make_game.py --stages shaders,assets # yalnızca seçili aşamaları çalıştır
77python -I make_game.py --game "D:\paket\yolu" --wav # Opus akışlarını ayrıca PCM WAV'a çöz (büyük boyut) 84python -I make_game.py --game "D:\paket\yolu" --wav # Opus akışlarını ayrıca PCM WAV'a çöz (büyük boyut)
@@ -83,7 +90,8 @@ Aşamalar şu sırayla çalışır: `check` → `shaders` → `assets` → `runt
83- **`--wave64-emulate`**: Wave64 compute ve mesh shader'larını her subgroup genişliğinde birebir çalışacak şekilde 90- **`--wave64-emulate`**: Wave64 compute ve mesh shader'larını her subgroup genişliğinde birebir çalışacak şekilde
84 çevirir. NVIDIA ve Intel GPU'lar 32 şeritli subgroup kullandığı için buna ihtiyaç duyar. Varsayılan `auto` modu 91 çevirir. NVIDIA ve Intel GPU'lar 32 şeritli subgroup kullandığı için buna ihtiyaç duyar. Varsayılan `auto` modu
85 `vulkaninfo` çıktısına bakar ve tüm GPU'lar yerel 64 şeritli subgroup bildirmediği sürece emülasyonu otomatik açar. 92 `vulkaninfo` çıktısına bakar ve tüm GPU'lar yerel 64 şeritli subgroup bildirmediği sürece emülasyonu otomatik açar.
86- **`--work`**: En az 350 GB boş alana sahip bir sürücü seçin. En uzun adım shader çevirisidir ve varsayılan olarak 93- **`--work`**: Tam derleme için en az 400 GB boş alana sahip bir sürücü seçin (yalnızca çalıştırmak için yaklaşık
94 30 GB, `assets` aşaması için yaklaşık 370 GB yeterlidir). En uzun adım shader çevirisidir ve varsayılan olarak
87 CPU iş parçacıklarının yarısını kullanır (`--jobs` ile değiştirilebilir). 95 CPU iş parçacıklarının yarısını kullanır (`--jobs` ile değiştirilebilir).
88- **`--wav`**: Varsayılan olarak kapalıdır; 16-bit PCM WAV dosyaları Ogg Opus'tan birkaç kat daha büyüktür. 96- **`--wav`**: Varsayılan olarak kapalıdır; 16-bit PCM WAV dosyaları Ogg Opus'tan birkaç kat daha büyüktür.
89- **Linux ve Wine/Proton**: `make_game.py` Linux'ta da çalışır. Yükleyici (`gta6rt.exe`) bir Windows programıdır ve 97- **Linux ve Wine/Proton**: `make_game.py` Linux'ta da çalışır. Yükleyici (`gta6rt.exe`) bir Windows programıdır ve
diff --git a/docs/i18n/zh-CN/quickstart.md b/docs/i18n/zh-CN/quickstart.md
index 3cf73de36..6dd96ec5c 100644
--- a/docs/i18n/zh-CN/quickstart.md
+++ b/docs/i18n/zh-CN/quickstart.md
@@ -2,7 +2,7 @@
2 2
3> [!NOTE] 3> [!NOTE]
4> 英文文档([`README.md`](../../../README.md)、[`CONTRIBUTING.md`](../../../CONTRIBUTING.md) 和 4> 英文文档([`README.md`](../../../README.md)、[`CONTRIBUTING.md`](../../../CONTRIBUTING.md) 和
5> [`docs/README.md`](../../README.md))是**权威版本**。本文只汇总稳定的安装与构建说明(与 commit `003e7812` 同步)。 5> [`docs/README.md`](../../README.md))是**权威版本**。本文只汇总稳定的安装与构建说明(与 commit `aa2988cc` 同步)。
6> 项目每日进展请查看 [`README.md`](../../../README.md)。 6> 项目每日进展请查看 [`README.md`](../../../README.md)。
7 7
8## Leonida 是什么 8## Leonida 是什么
@@ -18,10 +18,24 @@ Leonida 是一个把 Xbox Series 版 Grand Theft Auto VI **静态重编译**到
18 18
19项目处于早期:**目前还不能启动游戏**。 19项目处于早期:**目前还不能启动游戏**。
20 20
21## 平台
22
23目前在任何平台上都还不能游玩。各平台现在能运行的部分:
24
25- **Windows**:全部(`make_game.py`、各工具,以及带 D3D12 → Vulkan 层及其测试的 runtime `gta6rt`)。
26- **Linux**:翻译器、资源工具和 Vulkan GPU 测试工具可原生构建并运行(在 RADV 和 NVIDIA 上测试过)。runtime 是
27 Windows 代码:用 clang-cl 和 xwin 交叉编译,测试在 Wine 或 Proton 下运行。游戏将来也打算这样运行(#217)。
28- **macOS(Apple Silicon)**:Python 工具和 Vulkan 测试工具可在 MoltenVK(Homebrew)或 KosmicKrisp 上原生运行。
29 runtime 与 Linux 一样在 Wine 下运行。已知缺口:没有 geometry 阶段和 `VK_EXT_mesh_shader`、子组宽度为 32
30 (wave64 着色器以模拟方式运行),以及 MoltenVK 的浮点处理;详见 [`docs/testing.md`](../../testing.md)。
31- **AMD RDNA1(RX 5000)**:受支持的目标,接近主机的 RDNA2;它的 64 宽子组可原生运行 wave64 着色器。
32
33所有平台的 GPU 结果都汇总在 [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166)。
34
21## 前置条件 35## 前置条件
22 36
23- **你自己的拷贝**:Xbox Series 包,版本 `1.0.2.1`(目录里有 `MicrosoftGame.Config` 和明文可读的 `.rpf` 文件)。 37- **你自己的拷贝**:Xbox Series 包,版本 `1.0.2.1`(目录里有 `MicrosoftGame.Config` 和明文可读的 `.rpf` 文件)。
24- **Windows 10/11 x64**,约 **350 GB** 空闲空间给中间文件(可用 `--work` 放到另一块盘)。 38- **Windows 10/11 x64**,约 **400 GB** 空闲空间给中间文件(可用 `--work` 放到另一块盘)。
25- [Python 3.12+](https://www.python.org/downloads/)(勾选 “Add python.exe to PATH”)。 39- [Python 3.12+](https://www.python.org/downloads/)(勾选 “Add python.exe to PATH”)。
26- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)。 40- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)。
27- [Vulkan SDK](https://vulkan.lunarg.com/)(`spirv-as`、`spirv-val`、`vulkaninfo`)。 41- [Vulkan SDK](https://vulkan.lunarg.com/)(`spirv-as`、`spirv-val`、`vulkaninfo`)。
@@ -30,6 +44,10 @@ Leonida 是一个把 Xbox Series 版 Grand Theft Auto VI **静态重编译**到
30 - Windows 上运行 `scripts\build_llvm_mc.ps1` 构建原生 `llvm-mc.exe`(需要 `git` 和 Visual Studio 的 C++ 工具) 44 - Windows 上运行 `scripts\build_llvm_mc.ps1` 构建原生 `llvm-mc.exe`(需要 `git` 和 Visual Studio 的 C++ 工具)
31 并设置 `LLVM_MC`;**或**在 WSL 里安装 `llvm-21` 并设置 45 并设置 `LLVM_MC`;**或**在 WSL 里安装 `llvm-21` 并设置
32 `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`(见 [`docs/design.md`](../../design.md#disassembling-shaders))。 46 `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`(见 [`docs/design.md`](../../design.md#disassembling-shaders))。
47 构建脚本大约需要 20-40 分钟。
48 - 如果你用 [conda](https://docs.conda.io/),更快的办法是 `conda install -c conda-forge llvm-tools`(它的 Windows
49 版本包含 AMDGPU target),然后把 `LLVM_MC` 设为安装好的 `llvm-mc.exe` 的完整路径(激活环境后用
50 `where.exe llvm-mc` 查看;PowerShell 里单独的 `where` 是 `Where-Object`)。
33 - Linux 上 `PATH` 里有 `llvm-mc` 即可。 51 - Linux 上 `PATH` 里有 `llvm-mc` 即可。
34- **Visual Studio 2022**,勾选“使用 C++ 的桌面开发”和 **Windows SDK `10.0.26100` 或更新** 52- **Visual Studio 2022**,勾选“使用 C++ 的桌面开发”和 **Windows SDK `10.0.26100` 或更新**
35 (`runtime` 阶段需要,它使用 root signature 1.2)。 53 (`runtime` 阶段需要,它使用 root signature 1.2)。
@@ -46,10 +64,22 @@ Leonida 是一个把 Xbox Series 版 Grand Theft Auto VI **静态重编译**到
46 git clone --recursive https://github.com/ItsNotRexed/Leonida 64 git clone --recursive https://github.com/ItsNotRexed/Leonida
47 ``` 65 ```
48 66
67 用 GitHub 的 “Download ZIP” 下载会缺少 `third_party/rpf9-explorer`:装了 `git` 时构建会自动获取,否则会告诉你该怎么做。
68
493. 双击 **`Build.bat`**。 693. 双击 **`Build.bat`**。
50 70
51脚本会自动查找你的拷贝(Downloads、Desktop、Documents(也包括 OneDrive 等 Windows 实际存放它的位置)、Games、 71脚本会自动查找你的拷贝(Downloads、Desktop、Documents(也包括 OneDrive 等 Windows 实际存放它的位置)、Games、
52用户目录以及每个盘的根目录往下两层),检查前置条件和可用空间,结果写到 `Documents\Leonida`。构建中断后重新运行即可从断点继续。 72用户目录以及每个盘的根目录往下两层),只根据几个文件的大小识别版本,不读取大文件。找到多份拷贝时会问你用哪一份,
73一份都没找到时会让你粘贴目录路径。开始前它会检查前置条件和可用空间,并一次列出所有缺少的项目,结果写到
74`Documents\Leonida`。构建中断后重新运行即可从断点继续。
75
76### 磁盘空间不足
77
78上面的空间要求针对完整构建。只想*运行*移植版时,`--stages check,shaders,runtime` 约需 30 GB;占了其余绝大部分
79空间的 `assets` 阶段只供资源工具使用,`--wav` 还会再增加数倍于 Ogg Opus 的大小。`--work` 和 `--out` 都可以放在
80其他盘。runtime 原地映射游戏包,所以包所在盘为只读时需要 `gta6rt --overlay <可写目录>`(这是 `gta6rt` 的选项,
81不是 `make_game.py` 的)。不要删除 `work/shaders/dxbc/disasm` 里的 `.s` 文件:连同
82`work/shaders/spirv/index.json` 一起删掉后,`shaders` 阶段可能看起来已完成,却没有任何着色器。
53 83
54### 命令行(`make_game.py`) 84### 命令行(`make_game.py`)
55 85
@@ -64,7 +94,13 @@ python -I make_game.py --game "D:\path\to\package" --wav # 额外把 Ogg Opus è
64python -I make_game.py --wave64-emulate auto # auto(默认)、on 或 off 94python -I make_game.py --wave64-emulate auto # auto(默认)、on 或 off
65``` 95```
66 96
67阶段顺序:`check` → `shaders` → `assets` → `runtime` → `pipelines`。 97阶段顺序:`check` → `shaders` → `assets` → `runtime` → `pipelines`。`pipelines` 阶段在你的 GPU 驱动上创建每个
98翻译后的着色器并检查能否编译,报告必须跳过的着色器,并把管线缓存保存到 `--out` 里的 `pipeline_cache.bin`;
99runtime 目前还不加载这个缓存,所以它不会加快首次启动。
100
101构建会记录产出结果所用的 `llvm-mc` 命令和版本、翻译器源码,以及资源解码器(`third_party/rpf9-explorer` 的
102commit 和 `tools/rpf9dump` 的源码)。其中任何一项改变时,只重做受影响的步骤(反汇编、翻译,或该归档的模型和
103纹理导出)。没有这些记录的旧工作目录在升级后会把这些步骤重做一次。
68 104
69- **`--wave64-emulate`**:决定是否把 wave64 compute/mesh 着色器翻译成在任意子组宽度下都精确的版本 105- **`--wave64-emulate`**:决定是否把 wave64 compute/mesh 着色器翻译成在任意子组宽度下都精确的版本
70 (见 [`docs/design.md`](../../design.md) 中 Wave64 emulation 一行)。NVIDIA 和 Intel GPU 是 32 lane 子组, 106 (见 [`docs/design.md`](../../design.md) 中 Wave64 emulation 一行)。NVIDIA 和 Intel GPU 是 32 lane 子组,
@@ -72,8 +108,9 @@ python -I make_game.py --wave64-emulate auto # auto(默认)、o
72 都会启用;运行时实际使用的 GPU 无法以 64 宽运行 compute/mesh 时也会启用。有一个例外会让它保持关闭:当运行时的 108 都会启用;运行时实际使用的 GPU 无法以 64 宽运行 compute/mesh 时也会启用。有一个例外会让它保持关闭:当运行时的
73 GPU 是 RDNA2 独显或核显(RX 6000、Ryzen 6000/7000/9000 的核显)、使用 AMD Windows 驱动并原生运行 wave64 时 109 GPU 是 RDNA2 独显或核显(RX 6000、Ryzen 6000/7000/9000 的核显)、使用 AMD Windows 驱动并原生运行 wave64 时
74 ——该驱动的着色器编译器在模拟 LDS 代码上会崩溃(#857);否则 Intel 核显搭配 RX 6000 卡时也会被启用。 110 ——该驱动的着色器编译器在模拟 LDS 代码上会崩溃(#857);否则 Intel 核显搭配 RX 6000 卡时也会被启用。
75 该模式会保存在翻译后的着色器旁边,切换它会重新翻译。使用 `auto` 时,之前用过模拟的工作目录在后续翻译和重试中 111 该模式会保存在翻译后的着色器旁边,切换它会重新翻译。使用 `auto` 时通常可以复用之前模拟翻译的着色器;上述 AMD
76 会继续使用模拟,即使当前 GPU 支持原生 wave64;要用原生方式翻译,使用 `--wave64-emulate off`。 112 Windows 驱动的例外会把它们按原生方式重新翻译。要强制模拟用 `--wave64-emulate on`,强制原生 wave64 用
113 `--wave64-emulate off`。
77- **四个 fallback 标志**:它们同样转发给翻译器、保存在翻译后的着色器旁边,切换会重新翻译: 114- **四个 fallback 标志**:它们同样转发给翻译器、保存在翻译后的着色器旁边,切换会重新翻译:
78 `--no-float-controls`(去掉 `SignedZeroInfNanPreserve`,用于设备在缺少 115 `--no-float-controls`(去掉 `SignedZeroInfNanPreserve`,用于设备在缺少
79 `shaderSignedZeroInfNanPreserveFloat32` 时会跳过着色器;需要 PR #664 的翻译器标志)、 116 `shaderSignedZeroInfNanPreserveFloat32` 时会跳过着色器;需要 PR #664 的翻译器标志)、
@@ -81,7 +118,7 @@ python -I make_game.py --wave64-emulate auto # auto(默认)、o
81 `--texel-offset-fallback`(把 `image_sample*_o` 的偏移折叠进坐标,用于没有 `VK_KHR_maintenance8` 的设备)和 118 `--texel-offset-fallback`(把 `image_sample*_o` 的偏移折叠进坐标,用于没有 `VK_KHR_maintenance8` 的设备)和
82 `--mesh-compute`(把 mesh 着色器当作 compute,用于没有 `VK_EXT_mesh_shader` 的设备)。每个标志的说明见 119 `--mesh-compute`(把 mesh 着色器当作 compute,用于没有 `VK_EXT_mesh_shader` 的设备)。每个标志的说明见
83 [`docs/design.md`](../../design.md)。 120 [`docs/design.md`](../../design.md)。
84- **`--work`**:建议指向至少有 350 GB 空闲的磁盘;`shaders` 阶段最慢,默认使用一半 CPU 线程(`--jobs` 可调)。 121- **`--work`**:建议指向至少有 400 GB 空闲的磁盘;`shaders` 阶段最慢,默认使用一半 CPU 线程(`--jobs` 可调)。
85- **Linux 与 Wine/Proton**:`make_game.py` 也能在 Linux 上运行。`runtime` 阶段会在 Linux 上用 clang-cl 和 122- **Linux 与 Wine/Proton**:`make_game.py` 也能在 Linux 上运行。`runtime` 阶段会在 Linux 上用 clang-cl 和
86 lld-link(LLVM 19+,但 22.1.7 和 22.1.8 有已知问题,见 [docs/testing.md](../../testing.md#known-problems); 123 lld-link(LLVM 19+,但 22.1.7 和 22.1.8 有已知问题,见 [docs/testing.md](../../testing.md#known-problems);
87 命令名用不带版本后缀的,或五个 LLVM 工具都用同一版本后缀,例如 `clang-cl-21`)把 loader 交叉编译到 124 命令名用不带版本后缀的,或五个 LLVM 工具都用同一版本后缀,例如 `clang-cl-21`)把 loader 交叉编译到
@@ -92,7 +129,8 @@ python -I make_game.py --wave64-emulate auto # auto(默认)、o
92 也可以使用别处构建好的 Windows 版本,例如 Runtime workflow 的 `runtime-windows` artifact: 129 也可以使用别处构建好的 Windows 版本,例如 Runtime workflow 的 `runtime-windows` artifact:
93 `python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows`。 130 `python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows`。
94 两种方式都会把 `gta6rt.exe` 和 `gta6rt_tls_host.dll` 复制到 `--out`,并在旁边生成 `gta6rt.sh`, 131 两种方式都会把 `gta6rt.exe` 和 `gta6rt_tls_host.dll` 复制到 `--out`,并在旁边生成 `gta6rt.sh`,
95 用 `wine`(或 `WINE` 指定的 Proton)启动。 132 用 `wine`(或 `WINE` 指定的 Proton)启动。`pipelines` 阶段使用 `vk_pipeline_check`(需要 CMake 3.24+、C++20
133 编译器和 Vulkan 开发头文件,构建到 `runtime/build/linux`;缺少时脚本会在其他工作之前自行构建)。
96 134
97## 常见问题 135## 常见问题
98 136
diff --git a/docs/isa_coverage.md b/docs/isa_coverage.md
index cef03230c..999eeef82 100644
--- a/docs/isa_coverage.md
+++ b/docs/isa_coverage.md
@@ -63,17 +63,77 @@ four `_l`/`_lz` forms, packed image formats (`*_pck`, `*_by2`), the 16-bit `v_pk
63`*_saveexec` / `s_nand`/`s_nor`/`s_xnor` scalar forms. `python -I tools/isa_coverage.py --list` has the full list per 63`*_saveexec` / `s_nand`/`s_nor`/`s_xnor` scalar forms. `python -I tools/isa_coverage.py --list` has the full list per
64encoding. 64encoding.
65 65
66Names the translator matches that are not in the RDNA2 XML (16), each checked with 66Names the translator matches that are not in the RDNA2 XML (10), each checked with
67`llvm-mc -arch=amdgcn -mcpu=gfx1013`: 67`llvm-mc -arch=amdgcn -mcpu=gfx1013`:
68 68
69| name | llvm-mc for gfx1013 | verdict | 69| name | llvm-mc for gfx1013 | verdict |
70|---|---|---| 70|---|---|---|
71| `s_and_b32_mask`, `s_or_b32_mask` | invalid instruction | dead: nothing in the repository produces them |
72| `v_add_u16`, `v_sub_u16` | other GPU only | internal: `v_add_nc_u16` / `v_sub_nc_u16` are re-dispatched under these names | 71| `v_add_u16`, `v_sub_u16` | other GPU only | internal: `v_add_nc_u16` / `v_sub_nc_u16` are re-dispatched under these names |
73| `v_subrev_u16`, `v_and_b16`, `v_or_b16`, `v_xor_b16` | other GPU only | dead GFX9 spellings, harmless |
74| `s_delay_alu` | other GPU only (RDNA3) | deliberate, in `NOOPS` | 72| `s_delay_alu` | other GPU only (RDNA3) | deliberate, in `NOOPS` |
75| `v_mac_f32`, `v_mac_legacy_f32`, `v_mad_f32`, `v_mad_legacy_f32`, `v_madak_f32`, `v_madmk_f32`, `s_get_waveid_in_workgroup` | valid | real gfx1013 instructions that AMD's XML omits | 73| `v_mac_f32`, `v_mac_legacy_f32`, `v_mad_f32`, `v_mad_legacy_f32`, `v_madak_f32`, `v_madmk_f32`, `s_get_waveid_in_workgroup` | valid | real gfx1013 instructions that AMD's XML omits |
76 74
77None is a typo that breaks translation, so there is nothing to fix in the translator; the two `_mask` names and the 75`tools/rdna2_decode.py` decodes raw words without LLVM from the opcode and operand tables in
78four dead 16-bit spellings are candidates for removal. No name ends in a suffix `base_op()` strips (`_e32`, `_e64`, 76`tools/rdna2_isa_tables.py`, which are derived from the same `amdgpu_isa_rdna2.xml`. The gfx1013 entries above
79`_sdwa`, `_dpp`), and every `startswith` prefix matches at least one RDNA2 instruction. 77that the XML omits (`v_mac_f32`, `v_mad_f32`, `v_madak_f32`, `v_madmk_f32`, `s_get_waveid_in_workgroup`) are in
78that table, and `v_mad_legacy_f32` is the name the decoder gives VOP3 opcode 0x140 on a gfx101* target. A name
79added there belongs in the table above as well.
80
81None is a typo that breaks translation, so there is nothing to fix in the translator. No name ends in a suffix
82`base_op()` strips (`_e32`, `_e64`, `_sdwa`, `_dpp`), and every `startswith` prefix matches at least one RDNA2
83instruction.
84
85## Which rules the game reaches that hardware has not checked
86
87Several rows of the translator contract in `docs/design.md` say part of a rule is not measured on hardware, or
88not run on the shader corpus. `tools/op_reach.py` counts, over the disassembled corpus, the shaders and
89instructions that use each instruction. It merges the `_e32`/`_e64`/`_sdwa`/`_dpp` encodings and counts only the
90program up to a listing's last `s_endpgm`. The counts say whether 1.0.2.1 depends on the rule at all. They do
91not settle the hardware question.
92
93```sh
94python -I tools/op_reach.py <work>/shaders/dxbc/disasm --index <work>/shaders/dxbc/index.json v_cos_f16 v_log_f16 ...
95```
96
97Measured on the 26,503 1.0.2.1 listings (`shaders.rpf`, LLVM gfx1013; 12,101 PS, 9,282 MS, 2,689 CS, 2,236 VS,
98195 GS). The 2,035 decoded instructions after a listing's last `s_endpgm` are left out: they are data words, and
99the only place `s_cmov_b32` appears (4 listings). The embedded programs (the BVH builder's 52 FSSM programs,
100[embedded_shaders.md](embedded_shaders.md), and the 29 FidelityFX programs, [fspx.md](fspx.md)) are not counted,
101and a later game build may differ.
102
103**No 1.0.2.1 shader uses these instructions**, so on this build the unmeasured parts of their rows have no effect:
104
105| `docs/design.md` row | instructions with 0 shaders |
106|---|---|
107| Sub-dword MUBUF loads | `buffer_load_ubyte`, `_sbyte`, `_ushort`, `_sshort` |
108| 8/16-bit global stores and d16 loads | `global_store_byte`, `_short` and their `_d16_hi` forms; `global_load_{u,s}byte_d16`, `global_load_short_d16` and their `_hi` forms |
109| `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64` | all three |
110| `ds_cmpst_f32`/`_rtn_f32`, `global_atomic_fcmpswap`, `buffer_atomic_fcmpswap` | all four |
111| `ds_add_f32`, `ds_add_rtn_f32` | both |
112| `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | all six |
113| Scalar select and pack | `s_cmov_b32` (program code), `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16` |
114| Vector integer additions | `v_mul_hi_u32_u24`, `v_mul_hi_i32_i24`, `v_lshrrev_b64`, `v_ashrrev_i64`, `v_qsad_pk_u16_u8`, `v_mqsad_pk_u16_u8` |
115| `v_div_fixup_f16`, `v_div_fixup_f64` | both |
116| `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | all three |
117| `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` | both |
118| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | both |
119| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` ("not run on the shader corpus") | both |
120| `v_cmp_class_f16`/`_f64` and the `v_cmpx` forms ("and the shader corpus") | all four |
121| `buffer_atomic_{and,or,xor,swap}_x2` | all four |
122| `v_dot2c_i32_i16`, `v_dot8c_i32_i4` | both |
123
124**These the game does reach**, so their unmeasured parts still matter. Shaders, then instructions in brackets:
125
126| `docs/design.md` row | instruction: shaders (instructions), by stage |
127|---|---|
128| 16-bit interpolation | `v_interp_p1ll_f16` and `v_interp_p2_f16`: 4,776 PS (59,367 each) |
129| `v_interp_mov_f32` p10 / p20 | 3,673 PS (6,926) |
130| `v_cvt_f16_f32` output modifiers | `v_cvt_f16_f32`: 6,306 (44,496): 4,490 MS, 926 CS, 580 PS, 310 VS; the count is the instruction, not its modifiers |
131| Known approximations (`v_fma_mix*` rounding twice; `v_cos/exp/log_f16`) | `v_fma_mix_f32` 9,620 (487,658), `v_fma_mixlo_f16` 6,155 (33,900), `v_fma_mixhi_f16` 842 (2,135); `v_exp_f16` 3 CS (12), `v_cos_f16` 1 CS (2), `v_log_f16` 0 |
132| `v_cndmask_b32` source modifiers | `v_cndmask_b32`: 22,553 (1,490,241); the count is the instruction, not its modifiers |
133| Image atomics, size and LOD queries | `image_get_resinfo` 407 (1,148: 381 PS, 26 CS), `image_get_lod` 653 PS (718) |
134| Ray tracing (gfx1013 not measured) | `image_bvh_intersect_ray` 40 CS (638), `image_bvh64_intersect_ray` 24 CS (78) |
135| `s_bfe_u32` / `s_bfe_i32` past bit 31 | `s_bfe_u32` 15,398 (90,156), `s_bfe_i32` 2,847 (6,040); whether an operand passes bit 31 is not counted |
136
137A row's unmeasured part can be narrower than its instruction: a modifier, an operand range, an inactive lane or
138a special value. Where the count is the instruction alone, the table says so, and the count is an upper bound for
139that part. `tests/test_op_reach.py` checks the tool on hand-written listings.
diff --git a/docs/material_pass_replay.md b/docs/material_pass_replay.md
index 8e9b13590..62afed933 100644
--- a/docs/material_pass_replay.md
+++ b/docs/material_pass_replay.md
@@ -27,4 +27,6 @@ Two further cases varied the buffer word and crossed a half-precision quantizati
27 27
28Compare pixel-stage declarations across the same material's passes. The packed pass has no texture or sampler declaration. The textured sibling declares a 272-byte material constant buffer. Of its 46 authored members, 45 match the program by hash and byte offset. For the last member, the effect's parameter record supplies both the authored and compiled name hashes at the same offset. A different material slot gave only 11 direct matches. The textured shader reads the stored values and uses the first texture handle for a 2-D RGB sample. The drawable supplies four texture references across five declarations. The live handle table, sampler, and the descriptor used for the empty declaration still need independent verification. 28Compare pixel-stage declarations across the same material's passes. The packed pass has no texture or sampler declaration. The textured sibling declares a 272-byte material constant buffer. Of its 46 authored members, 45 match the program by hash and byte offset. For the last member, the effect's parameter record supplies both the authored and compiled name hashes at the same offset. A different material slot gave only 11 direct matches. The textured shader reads the stored values and uses the first texture handle for a 2-D RGB sample. The drawable supplies four texture references across five declarations. The live handle table, sampler, and the descriptor used for the empty declaration still need independent verification.
29 29
30The empty texture declaration has a narrower consequence on the first textured pass. Two stored material values satisfy a uniform branch condition. For an active wave reaching that branch, the taken path skips all four 2-D array sampling sites. Changing either value independently made those sites reachable in a control-flow check. The shader still loads the handle word. This result concerns that material and pass.
31
30Both tested color techniques' mesh and pixel programs translated and passed Vulkan 1.2 SPIR-V validation, including the translator's 32-lane emulation of the mesh stages' 64-lane waves. The stage-interface checker also found compatible mesh outputs and pixel inputs for each original pair in both modes. Reproducing final appearance still requires their draw constants, descriptors, transforms, and the frame's pass selection. 32Both tested color techniques' mesh and pixel programs translated and passed Vulkan 1.2 SPIR-V validation, including the translator's 32-lane emulation of the mesh stages' 64-lane waves. The stage-interface checker also found compatible mesh outputs and pixel inputs for each original pair in both modes. Reproducing final appearance still requires their draw constants, descriptors, transforms, and the frame's pass selection.
diff --git a/docs/mission_logic.md b/docs/mission_logic.md
index 67a15ebf1..d1ee15e51 100644
--- a/docs/mission_logic.md
+++ b/docs/mission_logic.md
@@ -166,6 +166,10 @@ at, from inflated PSIN streams or a directory of carved `.bin` streams:
166python -I tools/mission_tables.py <file-or-dir> [--json] [--limit N] 166python -I tools/mission_tables.py <file-or-dir> [--json] [--limit N]
167``` 167```
168 168
169A lone path is the PSIN file: a file without the `PSIN` magic is one `ERROR: <path>: not a PSIN container`
170line and exit 2, while a folder is the place for the bare carved streams and is scanned as before. A PSIN
171file that holds no records is still a clean run.
172
169It prints per-file record, chunk, state and entity counts, plus each resolved entity's archetype 173It prints per-file record, chunk, state and entity counts, plus each resolved entity's archetype
170hash, link hash, position and rotation. Pointers are scored in three encodings: **file-absolute**, 174hash, link hash, position and rotation. Pointers are scored in three encodings: **file-absolute**,
171**linked pool** (`pool_block_base + (offset >> 4)`), and **block-indexed** (`kind` is a 1-based 175**linked pool** (`pool_block_base + (offset >> 4)`), and **block-indexed** (`kind` is a 1-based
diff --git a/docs/modding.md b/docs/modding.md
index 3414923c5..5ac4bd88c 100644
--- a/docs/modding.md
+++ b/docs/modding.md
@@ -54,6 +54,10 @@ written `0x…`. A swap is one step: a model swapped to another that is itself s
54again, so two mods cannot loop. `when` is `always`; a narrower condition (one mission, one cutscene) is 54again, so two mods cannot loop. `when` is `always`; a narrower condition (one mission, one cutscene) is
55refused until a hook provides the game's mission state, so a mod never silently does more than it says. 55refused until a hook provides the game's mission state, so a mod never silently does more than it says.
56 56
57`mod.json` is UTF-8. A byte-order mark in front is accepted (Notepad's "UTF-8 with BOM", Windows
58PowerShell 5.1's `-Encoding utf8`). A UTF-16 file, which PowerShell 5.1's `>` writes, is skipped with
59`mod.json is UTF-16; save it as UTF-8`.
60
57The format is in `runtime/src/mods.h`; `runtime/test/mods_test.cpp` (ctest `mods`) covers it. 61The format is in `runtime/src/mods.h`; `runtime/test/mods_test.cpp` (ctest `mods`) covers it.
58 62
59## The Mandy mod (`mods/mandy_prison_intro`) 63## The Mandy mod (`mods/mandy_prison_intro`)
@@ -126,7 +130,7 @@ the engine, which shipped a first-person mode), a hit-reaction `RecoveryDirectio
126and a `firstpersonshooter_hud` UI texture. So the mod switches on a mode the engine has rather than building 130and a `firstpersonshooter_hud` UI texture. So the mod switches on a mode the engine has rather than building
127a camera. Whether the game exposes it to the player is not known. 131a camera. Whether the game exposes it to the player is not known.
128 132
129**Assumptions to confirm in the executable:** that the view mode is chosen through one getter of the form 133**ASSUMPTION:** three things to confirm in the executable: that the view mode is chosen through one getter of the form
130`mode = get(context)`, that context 0 is on foot, and that first person is enum value 4 (GTA V's 134`mode = get(context)`, that context 0 is on foot, and that first person is enum value 4 (GTA V's
131`camViewModeSettings` order: third person near, medium, far, cinematic, first person). All three are 135`camViewModeSettings` order: third person near, medium, far, cinematic, first person). All three are
132settings in `mod.json`, so a different answer changes the manifest, not the runtime. 136settings in `mod.json`, so a different answer changes the manifest, not the runtime.
diff --git a/docs/models.md b/docs/models.md
index bebdfecd6..85b805feb 100644
--- a/docs/models.md
+++ b/docs/models.md
@@ -20,8 +20,8 @@ reader. Commits `917e9b9..e293917` add upstream `v1.2` model-discovery changes (
20optional fragment pointers, skipping texture dictionaries in drawable-dictionary scans, 16-bit 20optional fragment pointers, skipping texture dictionaries in drawable-dictionary scans, 16-bit
21bone-palette indices, probe-count parity, and zero-radius drawables) plus BCPack BC1/BC3/BC4/BC5 21bone-palette indices, probe-count parity, and zero-radius drawables) plus BCPack BC1/BC3/BC4/BC5
22decoding (PR #7). A full ten-archive re-count at `e293917` recovers **382,781 models** (**+32,530** 22decoding (PR #7). A full ten-archive re-count at `e293917` recovers **382,781 models** (**+32,530**
23over `917e9b9`'s 350,251) with **0 decode failures**; the `levels.rpf` fragment, bone-binding and 23over `917e9b9`'s 350,251) with **0 decode failures**, **55,417 fragments** and **2,636,248,990
24triangle cells are not independently reproduced (see the table note), and the earlier 24triangles** (the `levels.rpf` cells from a full export, see the table note), and the earlier
25`917e9b9`, `c3708fb`, and `48557ea` measurements are kept below as controls. This page records the 25`917e9b9`, `c3708fb`, and `48557ea` measurements are kept below as controls. This page records the
26measured state; it is not a competing patch. 26measured state; it is not a competing patch.
27 27
@@ -60,22 +60,29 @@ effect of upstream `v1.2` PRs #8–#12:
60| `pack/story000_restofworld/...` | 1 | **3** | 3 | 0 | 0 | 0 | 2,620 | 0 | 0 | 60| `pack/story000_restofworld/...` | 1 | **3** | 3 | 0 | 0 | 0 | 2,620 | 0 | 0 |
61| `pack/story000/story000.rpf` | 4,195 | **7,461** | 4,156 | 3,305 | 0 | 0 | 39,861,747 | 0 | +1 | 61| `pack/story000/story000.rpf` | 4,195 | **7,461** | 4,156 | 3,305 | 0 | 0 | 39,861,747 | 0 | +1 |
62| `packs.rpf` | 26,389 | **26,585** | 23,720 | 2,865 | 2,865 | 26,585 | 64,966,572 | 0 | +2,551 | 62| `packs.rpf` | 26,389 | **26,585** | 23,720 | 2,865 | 2,865 | 26,585 | 64,966,572 | 0 | +2,551 |
63| `levels.rpf` | 235,330 | **343,327** | 130,239 | 213,088 | † | † | † | 71 | +29,327 | 63| `levels.rpf` | 235,330 | **343,327** | 130,239 | 213,088 | 50,731 | 59,544 | 2,509,947,536 | 71 | +29,327 |
64| `textures.rpf` | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 64| `textures.rpf` | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
65| `common.rpf`, `core_restofworld001` | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 65| `common.rpf`, `core_restofworld001` | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
66| **Total** | **270,819** | **382,781** | **159,511** | **223,270** | **†** | **†** | **†** | **72** | **+32,530** | 66| **Total** | **270,819** | **382,781** | **159,511** | **223,270** | **55,417** | **89,887** | **2,636,248,990** | **72** | **+32,530** |
67 67
68† `levels.rpf` was counted with `count.exe recover --verify`, which reports candidates, models, 68`levels.rpf` was first counted with `count.exe recover --verify`, which reports candidates, models,
69dictionary children, standalone models, rejects and decode failures only: no `levels.rpf` manifest 69dictionary children, standalone models, rejects and decode failures only, so its fragment,
70exists and the harness emits no fragment, bone-binding or triangle field. Those three `levels.rpf` 70bone-binding and triangle cells were open. A full `rpf9dump models <levels.rpf> <out>` export at
71cells, and the totals that would include them, are therefore **not independently reproduced**. The 71`e293917` (25 min, about 340 GB of OBJ, deleted afterwards) fills them from its manifest: 235,330
72other archives measure 4,686 fragments, 30,343 bone-bound and 126,301,454 triangles. 72candidates, 235,259 recovered, 71 not recovered, 343,327 entries, `fail=0`, the recovery count to
73the row. Its `Drawable` field is set on 130,239 entries and null on 213,088, the dictionary-children
74and standalone cells above (3,694 dictionaries have a single child, so counting shared offsets
75instead gives 126,545 / 216,782). `IsFragment` is true on 50,731 entries and `HasBoneBindings` on
7659,544; `Tris` sums to 2,509,947,536. The same counting on a fresh `data.rpf` export gives that
77row's 268 / 2,907, 1,758, 2,891 and 3,387,016. The other archives measure 4,686 fragments, 30,343
78bone-bound and 126,301,454 triangles.
73 79
74Every recovered entry was read back from its archive segments and decoded through 80Every recovered entry was read back from its archive segments and decoded through
75`RageModelDecoder.Decode`: **382,781 / 382,781 decoded, 0 decode failures**. The other archives 81`RageModelDecoder.Decode`: **382,781 / 382,781 decoded, 0 decode failures**. The other archives
76measure **236,311 meshes**, **104,183,438 vertices**, **126,301,454 triangles** and **512 embedded 82measure **236,311 meshes**, **104,183,438 vertices**, **126,301,454 triangles** and **512 embedded
77textures**; the `levels.rpf` mesh/vertex/triangle/embedded cells are not independently reproduced 83textures**; `levels.rpf` adds 3,854,587 meshes, 2,364,218,711 vertices, 2,509,947,536 triangles and
78(see the table note). 841,293 embedded textures (the export's own summary line), for **4,090,898 meshes**, **2,468,402,149
85vertices**, **2,636,248,990 triangles** and **1,805 embedded textures** over all ten archives.
79 86
80What moved between `917e9b9` and `e293917`: 87What moved between `917e9b9` and `e293917`:
81 88
@@ -129,7 +136,7 @@ entries are dictionary children.
129### Re-count at `e293917` 136### Re-count at `e293917`
130 137
131A full `rpf9dump models` re-run over the same archives at the current pin (the manifests are 138A full `rpf9dump models` re-run over the same archives at the current pin (the manifests are
132local; `levels.rpf` has a recovery count but no full OBJ export): 139local; `levels.rpf` was exported separately, see the table note above):
133 140
134| Archive | Rows | Non-fragment | Fragments | Delta vs `917e9b9` | 141| Archive | Rows | Non-fragment | Fragments | Delta vs `917e9b9` |
135|---|---:|---:|---:|---:| 142|---|---:|---:|---:|---:|
@@ -141,7 +148,8 @@ local; `levels.rpf` has a recovery count but no full OBJ export):
141| `story000_restofworld` | **3** | 3 | 0 | 0 | 148| `story000_restofworld` | **3** | 3 | 0 | 0 |
142| `common`, `textures`, `story000_script`, `core_restofworld001` | 0 | 0 | 0 | 0 | 149| `common`, `textures`, `story000_script`, `core_restofworld001` | 0 | 0 | 0 | 0 |
143| **Total, excluding `levels.rpf`** | **39,454** | **34,768** | **4,686** | **+3,203** | 150| **Total, excluding `levels.rpf`** | **39,454** | **34,768** | **4,686** | **+3,203** |
144| `levels.rpf` | recovery count only, see below | - | - | +29,327 | 151| `levels.rpf` | **343,327** | 292,596 | 50,731 | +29,327 |
152| **Total** | **382,781** | **327,364** | **55,417** | **+32,530** |
145 153
146The gain outside `levels.rpf` is fragments: upstream `v1.2` PRs #8-#12 recover zero-radius 154The gain outside `levels.rpf` is fragments: upstream `v1.2` PRs #8-#12 recover zero-radius
147fragments that the earlier export skipped (2,551 in `packs.rpf`, 594 in `data.rpf`), plus one 155fragments that the earlier export skipped (2,551 in `packs.rpf`, 594 in `data.rpf`), plus one
@@ -150,8 +158,8 @@ is 0.
150 158
151`levels.rpf` was re-counted at `e293917` (10 shards over 235,330 candidates): **343,327 models** 159`levels.rpf` was re-counted at `e293917` (10 shards over 235,330 candidates): **343,327 models**
152(130,239 dictionary children + 213,088 standalone), against 314,000 at `917e9b9` (206,981 160(130,239 dictionary children + 213,088 standalone), against 314,000 at `917e9b9` (206,981
153candidates; 130,225 children + 183,801). The +29,327 is a recovery count, not a row-for-row delta, 161candidates; 130,225 children + 183,801). The +29,327 is a recovery count, not a row-for-row delta.
154and no full OBJ export was run. Triangle totals were not re-run either. 162The full OBJ export at `e293917` (table note above) gives the same 343,327 rows.
155 163
156The last column is the `c3708fb` recovery for comparison. `story000`'s standalone count is 164The last column is the `c3708fb` recovery for comparison. `story000`'s standalone count is
1573,304 vs 3,305; the full new-pin standalone total is 190,765, 27 below the `c3708fb` 190,792. 1653,304 vs 3,305; the full new-pin standalone total is 190,765, 27 below the `c3708fb` 190,792.
@@ -248,9 +256,8 @@ reproduced the ten-archive total. The `48557ea` column is the pre-fix control:
248The `packs.rpf` row is the pre-dictionary-root control: at `917e9b9` that archive recovers 256The `packs.rpf` row is the pre-dictionary-root control: at `917e9b9` that archive recovers
24924,034 models (26,585 at `e293917`), and the other archives' new-pin counts are in the table above. 25724,034 models (26,585 at `e293917`), and the other archives' new-pin counts are in the table above.
250The rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,251, 258The rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,251,
251and the `e293917` re-count outside `levels.rpf` is 39,454. Triangle totals have not been re-run at 259and the `e293917` re-count outside `levels.rpf` is 39,454. The `e293917` triangle totals of all ten
252either new pin; the `e293917` `levels.rpf` geometry cells are not independently reproduced (see 260archives, `levels.rpf` included, are in the table above.
253the table note above).
254 261
255At `c3708fb`, every candidate is recovered, read back and decoded: 0 decode failures, 0 readback 262At `c3708fb`, every candidate is recovered, read back and decoded: 0 decode failures, 0 readback
256failures, no duplicate model names, and 2.22 billion triangles (1.95 billion before). The 263failures, no duplicate model names, and 2.22 billion triangles (1.95 billion before). The
@@ -443,22 +450,39 @@ records. No unhandled layout tag appears:
443- **Sentinels.** On each surface, 11 entries have every estimate 0 and 10 more have zero speeds with an 450- **Sentinels.** On each surface, 11 entries have every estimate 0 and 10 more have zero speeds with an
444 infinite time (`inf`). `inf` occurs in 38 road and 99 offroad blocks overall, so a parser must accept `inf` 451 infinite time (`inf`). `inf` occurs in 38 road and 99 offroad blocks overall, so a parser must accept `inf`
445 in these fields (it reads as "never reaches the test speed or distance"). 452 in these fields (it reads as "never reaches the test speed or distance").
446- **`fOverallRating` is a weighted mean of the other four ratings** (measured, confirmed to float noise). Over the 453- **`fOverallRating` is a weighted mean of the other four ratings** (measured, confirmed to float noise) on the
447 504 rating blocks, `fOverallRating` = 0.21 `fSpeedRating` + 0.38 `fHandlingRating` + 0.40 454 345 of the 504 rating blocks whose four parts are all above 10: there `fOverallRating` = 0.21
448 `fAccelerationRating` + 0.01 `fBrakesRating`: the four weights sum to 1, so handling and acceleration weigh 455 `fSpeedRating` + 0.38 `fHandlingRating` + 0.40 `fAccelerationRating` + 0.01 `fBrakesRating`, with a residual
449 about twice speed and brakes is 1%. The residual is at most 7e-5 on the 345 rating blocks whose four parts are 456 of at most 7e-5. The four weights sum to 1, so handling and acceleration weigh about twice speed and brakes is 1%.
450 all above 10, and differencing a key's road and offroad blocks gives the same 0.2100 / 0.3800 / 0.4000 / 457 Differencing a key's road and offroad blocks gives the same 0.2100 / 0.3800 / 0.4000 / 0.0100 on the 139 keys
451 0.0100 on the 139 keys that are above 10 on both surfaces, so the weights do not depend on the surface. 458 that are above 10 on both surfaces, so the weights do not depend on the surface.
452- **The same 10 floor is on the overall** (likely). 24 blocks whose four parts run 10.0 to 11.97 carry an 459- **The overall has the same observed minimum of 10.** The other 159 rating blocks each have at least one part
453 `fOverallRating` of exactly 10; and the other 159 rating blocks, which have at least one part at exactly 10, 460 at exactly 10, and the formula does not hold for them: they sit up to 4.1 below the weighted mean, and 24 of
454 sit up to 4.1 below the weighted mean, as parts raised to 10 from a lower value would, while no block without 461 them carry an `fOverallRating` of exactly 10. No block without a part at 10 deviates. The exports show only
455 a part at 10 deviates. 462 this minimum; they cannot tell where, or whether, the engine clamps.
456- **Scale.** The ratings are continuous floats, not a 0-1 or 0-100 score: 342 to 451 distinct values per field 463- **Scale.** The ratings are continuous floats, not a 0-1 or 0-100 score: 342 to 451 distinct values per field
457 over the 504 blocks, a floor of exactly 10, and `fAccelerationRating` the only field past 1,000 (22 blocks, 464 over the 504 blocks, a floor of exactly 10, and `fAccelerationRating` the only field past 1,000 (22 blocks,
458 maximum 1,327). 465 maximum 1,327).
459 466
460Not measured here (hypothesis): whether the estimates are precomputed from handling data or measured by 467Not measured here (hypothesis): whether the estimates are precomputed from handling data or measured by
461simulation, and what fixes the top of the rating scale. 468simulation, and what fixes the top of the rating scale.
469- **The estimates are a separate stored table, not the performance maps.** `common.rpf`'s data area at `0x9580`
470 also holds `CVehiclePerformanceMaps` (285 rows, 10 result fields) and `CTyreDataSet` (40 tyre types). 251 of the
471 252 estimate keys join the performance rows, but no field reproduces an estimate exactly: the best OLS over
472 all ten gives R^2 0.872, and `fAccelerationTime` against `accelZeroSixty` is R^2 0.811 with a median |residual|
473 of 0.54 s. The clearest relation is internal to the estimates: over the 231 rows with a finite top speed,
474 `fStandingQuarterTime = 6.73 + 401.0 / fTopSpeed` (R^2 0.99998, median |residual| 1.01 s; R^2 0.82 over the
475 209 rows under 30 s). For the seven top-speed-limited rows, `fTopSpeed * fStandingQuarterTime` is
476 402.339 +/- 0.0003 m, a quarter mile; the residual tracks the 0-60 time.
477- **The ratings are deterministic functions of the estimates.** Each of the 223 distinct road top speeds gives
478 one `fSpeedRating`; handling/corner has 221 levels, acceleration/acceleration time 204, brakes two collisions,
479 and `fOverallRating` uses more than one field. The rating scale and the overall weighting are still not fitted.
480- **The handling inputs are not in the readable archives.** No `CHandlingData`/`handling.meta`, `fMass`,
481 `fInitialDriveForce`, `fInitialDragCoeff`, `nInitialDriveGears`, `fTractionCurve*`, `fBrakeForce` or
482 `fSuspensionForce` occurs in `common.rpf`, `data.rpf`, `packs.rpf` or `script.rpf`; the executable is absent.
483 `levels.rpf` is map data and was not fully scanned. The table is therefore consistent with an offline
484 estimator fed by handling-derived scalars, but whether it was fitted to handling or copied from a simulation
485 cannot be verified from this package.
462 486
463## Character skeletons 487## Character skeletons
464 488
@@ -485,9 +509,11 @@ python -I tools/character_census.py <models-dir-or-manifest> [--json FILE] [--cs
485It reads every nested `model.json` (the decoded-pack layout: `type`, `vertex_count`, 509It reads every nested `model.json` (the decoded-pack layout: `type`, `vertex_count`,
486`triangle_count`, `materials[].shader_name_hash`, `materials[].textures[].hash64`, 510`triangle_count`, `materials[].shader_name_hash`, `materials[].textures[].hash64`,
487`drawable.skeleton`/`drawable.models[].bone_palette` and `meshes[].skin_influences`), or the 511`drawable.skeleton`/`drawable.models[].bone_palette` and `meshes[].skin_influences`), or the
488`Items[]` of a manifest (`Verts`, `Tris`, `IsFragment`, `HasBoneBindings`, `Materials[]`). It 512`Items[]` of a manifest (`Verts`, `Tris`, `IsFragment`, `HasBoneBindings`, `Materials[]`). The
489prints one row per model with kind, vertex/triangle counts, bones, 8-influence skin, shader 513local exporter does not write an index count, so the index column and total normally stay unknown;
490hashes and texture keys, then totals by kind and by shader hash. A missing or wrongly typed field 514an input that supplies `index_count` is counted, but the field is optional and not part of the
515decoded layout. It prints one row per model with kind, vertex/triangle counts, bones, 8-influence
516skin, shader hashes and texture keys, then totals by kind and by shader hash. A missing or wrongly typed field
491is reported on that row instead of ending the run. An `rpf9dump models` manifest records only 517is reported on that row instead of ending the run. An `rpf9dump models` manifest records only
492`HasBoneBindings`, not a bone count or influence width, so those cells stay `?`. Report paths that 518`HasBoneBindings`, not a bone count or influence width, so those cells stay `?`. Report paths that
493alias an input are refused. The tests are synthetic: `python -I tests/test_character_census.py`. 519alias an input are refused. The tests are synthetic: `python -I tests/test_character_census.py`.
@@ -517,6 +543,11 @@ Names are per model and a building holds glass, decal and opaque shaders alike,
517in absolute terms; the enrichment against bucket 0 is the signal. For export: bucket 1 needs blending, 2 is 543in absolute terms; the enrichment against bucket 0 is the signal. For export: bucket 1 needs blending, 2 is
518a projected decal, 3 needs alpha testing, 6 is a water surface. 544a projected decal, 3 needs alpha testing, 6 is a water surface.
519 545
546`common.rpf` carries the matching preset-to-effect table (`SPS1`, decoded by `tools/gamedata_sps1.py`,
547[`gamedata.md`](gamedata.md#sps1-shader-preset-table)): `858` `.sps` presets map onto `539` `SGD5` Database 0 effects
548with a default `u8` render bucket (`0..7`), `63` effects accept multiple buckets, and the single bucket-`4`
549and bucket-`5` presets both resolve to effect `fc34f08b`.
550
520## Material shader hashes and the carved programs 551## Material shader hashes and the carved programs
521 552
522`rpf9dump` also writes each material's shader hash (`manifest.json` → `Materials[].Shader`, u32 as 8 hex digits). 553`rpf9dump` also writes each material's shader hash (`manifest.json` → `Materials[].Shader`, u32 as 8 hex digits).
@@ -635,7 +666,21 @@ They are reachable through the **effect records** in `shaders.rpf` (found by @je
635are little-endian: 666are little-endian:
636 667
6371. **The effect record.** It starts with a one-byte name length and the name, including its terminator, then a 6681. **The effect record.** It starts with a one-byte name length and the name, including its terminator, then a
638 u32 whose meaning is not known. Six stage lists follow, each a u32 count and that many u32 ordinals. 669 u32 (below). Six stage lists follow, each a u32 count and that many u32 ordinals.
670
671 The u32 is a size computed from the record's own counted fields (@jeremygold02). Let G be the ordinals in the
672 six lists, T the techniques, P the passes, and W the post-pass word count. Let A and B be the two block
673 lengths after them, E the post-pass entry count, I the payload bytes of the entries whose tag is a length
674 (not `0x80000000`), and S the string-pool length. Lengths don't count their own prefixes. Then, with
675 `x = 4W + A + B`:
676
677 ```text
678 word = 48 + 8(G + T + E) + 32P + I + S + (round_up(x, 8) if E else x)
679 ```
680
681 This holds for all 932 records of this build (910 + 22, recomputed here). The value never equals the record's
682 serialized length (0 of 932), so the next record is found by the sequential walk, not by this word. What the
683 runtime uses it for is unknown. Groups 3 and 4 are empty here, so their share of it is unmeasured.
639 684
640 `shaders.rpf` holds **two shader databases** (SGD5), and an ordinal counts within one of them (found by 685 `shaders.rpf` holds **two shader databases** (SGD5), and an ordinal counts within one of them (found by
641 @jeremygold02). Each database stores six program groups, each a u32 count followed by its programs. A program 686 @jeremygold02). Each database stores six program groups, each a u32 count followed by its programs. A program
@@ -682,7 +727,8 @@ record, technique and pass. The record and pass format below was also checked by
682 727
683Two things are still open: 728Two things are still open:
684 729
685- **The u32 after an effect's name.** What it means is still unknown. 730- **The u32 after an effect's name.** It is reproduced from the record's fields; how the runtime uses it is
731 still unknown.
686- **Which technique and pass the game draws with.** That is a run-time choice; it is presumably made in the 732- **Which technique and pass the game draws with.** That is a run-time choice; it is presumably made in the
687 executable (RT-5). 733 executable (RT-5).
688 734
@@ -713,15 +759,29 @@ vehicle models to far-away light recipes. Counts only; no model names.
713 this build the document is an index from model and variant to recipe with the light positions absent, 759 this build the document is an index from model and variant to recipe with the light positions absent,
714 so distant vehicle lights cannot be reconstructed from it. 760 so distant vehicle lights cannot be reconstructed from it.
715 761
762To reproduce the joins, locate the XML roots in the [common carve catalog](gamedata.md) with
763`python -I tools/gamedata_xml.py <common-carve-dir> --json xml.json`. Trim and lowercase the field
764text, then match each nonempty `CVehicleDistantLightData/recipeLights/Item` by `vehicleModelName`
765and its sorted list of `secondaryRecipes/Item` values against `vehicleName` and the same list on
766`CPaletteIndexedRecipeTintsArray` rows at `.//recipeCombinations/Item`. For the carriage check,
767expand the light lists to distinct pairs and compare with `CTrainConfigs` rows at `.//carriages/Item`.
768
716The sampled `CPaletteIndexedRecipeTintsArray` document reuses 746 of the 780 distinct distant-light 769The sampled `CPaletteIndexedRecipeTintsArray` document reuses 746 of the 780 distinct distant-light
717secondary tokens in its own `secondaryRecipes` field. Of the 1,668 distant-light rows with at least one 770secondary tokens in its own `secondaryRecipes` field. Of the 1,668 distant-light rows with at least one
718token, 1,339 match a palette recipe on both vehicle name and the complete token list, ignoring case and 771token, 1,339 match a palette recipe on both vehicle name and the complete token list, ignoring case and
719token order. Replacing each vehicle name with the next of the 319 lowercased names in sorted order 772token order. Replacing each vehicle name with the next of the 319 distinct names from all light rows in sorted order
720(wrapping at the end) and keeping its tokens fixed gives 56 matches among the same 1,668 rows. 773(wrapping at the end) and keeping its tokens fixed gives 56 matches among the same 1,668 rows.
721 774
775For a single-token comparison, the distant-light rows give 1,547 distinct (vehicle, secondary token)
776pairs. Four match the `modelName` and `modelSetName` fields on the same `CTrainConfigs` carriage row,
777after trimming whitespace and ignoring case. These four pairs cover two vehicle models and four model
778sets. Rotating the 319 vehicle names as above gives zero matching pairs. Keeping the vehicle fixed and
779rotating the 780 distinct tokens in sorted order, with wraparound, gives two matching pairs.
780
722In the 34-row `CVehicleBoneOffsetsArray` document, 0 of the 780 distinct tokens match a whole text or 781In the 34-row `CVehicleBoneOffsetsArray` document, 0 of the 780 distinct tokens match a whole text or
723attribute value case-insensitively. In the 2,447-row document of the same type, 178 of the 780 match 782attribute value case-insensitively. In the 2,447-row document of the same type, 178 of the 780 match
724`boneOffsets/Item/name`. These comparisons establish recipe reuse across the light and palette documents. 783`boneOffsets/Item/name`. All 2,447 rows have empty `vehicleName` fields, so those name matches provide
784no same-row vehicle association.
725Which physical parts or liveries a token selects, and where the runtime obtains light positions, remain open. 785Which physical parts or liveries a token selects, and where the runtime obtains light positions, remain open.
726 786
727## Skinned GLB export 787## Skinned GLB export
@@ -739,21 +799,75 @@ the drawable's local joint palette through the drawable and ped tables, and emit
739in [character_skeleton.md](character_skeleton.md#skinned-glb-export). On the 1.0.2.1 package, the 799in [character_skeleton.md](character_skeleton.md#skinned-glb-export). On the 1.0.2.1 package, the
740head (8,983 v) and biker jacket (9,818 v) produce one skin with 596 ped joints (703 with the 800head (8,983 v) and biker jacket (9,818 v) produce one skin with 596 ped joints (703 with the
741jacket's `GM_U01_*` helpers); every weight sums to 255 and the rest-pose reconstruction error is 801jacket's `GM_U01_*` helpers); every weight sums to 255 and the rest-pose reconstruction error is
7426e-8 m. `python -I tests/test_skinned_glb.py` runs 10 synthetic tests and needs no game files. 8026e-8 m. `python -I tests/test_skinned_glb.py` runs 24 synthetic tests and needs no game files.
7436e-8 m. `python -I tests/test_skinned_glb.py` runs 15 synthetic tests and needs no game files. 803
804`tools/glb_inspect.py` reads such a GLB back without a library, so an export can be checked
805before it is opened in a viewer:
806
807```
808python -I tools/glb_inspect.py out.glb [--json report.json]
809```
810
811It prints the chunk layout and padding, the `counts` of scenes, nodes, meshes, materials, images,
812skins and animations, each mesh's primitive, vertex and triangle counts, each material's
813`baseColorTexture`, each skin's joint count, each animation's channels and duration, and the
814POSITION bounding box (marked `partial` when a POSITION accessor has no `min`/`max`). It reports
815what the JSON chunk says — a field the exporter dropped reads `(missing)` — and never infers
816geometry from the BIN chunk. Standard library only; no game files.
744 817
745## What to do next 818## What to do next
746 819
7471. **Done:** [rpf9-explorer PR #1](https://github.com/breadbbbb/rpf9-explorer/pull/1) is merged upstream. 8201. **Done:** [rpf9-explorer PR #1](https://github.com/breadbbbb/rpf9-explorer/pull/1) is merged upstream.
7482. **Done:** the pin is `e293917` (was `917e9b9`, originally `48557ea`). 8212. **Done:** the pin is `e293917` (was `917e9b9`, originally `48557ea`).
7493. **Done:** all ten `MODEL_ARCHIVES` were re-counted and read-back decoded at `e293917` (**382,781 8223. **Done:** all ten `MODEL_ARCHIVES` were re-counted and read-back decoded at `e293917` (**382,781
750 models**, **0 decode failures**; table above; the `levels.rpf` geometry cells are not 823 models**, **0 decode failures**; table above, `levels.rpf` geometry from a full export).
751 independently reproduced).
7524. Investigate the 71 remaining unrecovered fragment candidates in `levels.rpf` (and the 1 8244. Investigate the 71 remaining unrecovered fragment candidates in `levels.rpf` (and the 1
753 texture-dictionary candidate in `textures.rpf`) if further upstream recovery is wanted. 825 texture-dictionary candidate in `textures.rpf`) if further upstream recovery is wanted.
7545. Keep issue #29 in sync with the `e293917` counts. 8265. Keep issue #29 in sync with the `e293917` counts.
7553. **Done:** `tools/rpf9dump models` was re-run over the model-bearing archives at `e293917`; 8273. **Done:** `tools/rpf9dump models` was re-run over the model-bearing archives at `e293917`;
756 the six non-`levels.rpf` archives total 39,454 rows (+3,203, almost all recovered fragments). 828 the six non-`levels.rpf` archives total 39,454 rows (+3,203, almost all recovered fragments).
757 `levels.rpf` has a recovery count (343,327 models, +29,327) but no full OBJ export; triangle 829 `levels.rpf` has the same 343,327 rows in a full export (50,731 fragments, 2,509,947,536
758 totals were not re-run. 830 triangles).
7594. Keep the README and issue #29 in sync with the new counts. 8314. Keep the README and issue #29 in sync with the new counts.
832
833### Predict model offsets for placements
834
835Run `python -I tools/world_drawable_lookup.py entities.jsonl archetypes.json names.json`
836with the placement rows from `world_index.py --entities-out`, the definitions from
837`world_archetypes.py`, and a bounded `rpf9_names.py --types dr,ft` report. The command
838prints local scratch JSON. Supply `--manifest path/to/models/manifest.json` for each
839existing export whose listed identities should be excluded.
840
841The lookup requires agreement between the placement archetype, the definition's name and
842assetName, the resource stem's joaat and its 64-bit placement key. It considers type 1
843fragments and type 2 drawables at page offset +16. Multiple offsets for an identity in
844the indexed window are marked ambiguous. Even a single hit is a prediction: a stream
845can mention another model. Export a window around the predicted offset with
846`rpf9dump models <archive> <outdir> --start BYTES --length BYTES`, compare the manifest offset and
847model identity and run `world_build.py --placements` with the exported geometry.
848
849Save the lookup JSON and run
850`python -I tools/world_drawable_verify.py lookup.json first/models/manifest.json second/models/manifest.json`
851to verify single-offset predictions. Supply completed normal model manifests from the
852same source archive. The verifier reads cached JSON only. It uses the world builder's
853name hashes and counts each identity and its placements once. A matching offset and both
854hashes confirm an observation, including dictionary children sharing an offset. The local
855report counts repeat exact observations and lists other offsets for the same identity.
856Without an exact match, a different name at the offset takes precedence over a matching
857identity elsewhere. The coverage flag independently records whether the predicted offset
858falls in a supplied scan (start inclusive, end exclusive). A full scan covers all offsets.
859A covered prediction with no named evidence remains missing. Geometry loadability is
860checked separately by running the normal world builder on confirmed placement rows.
861
862Add `--window-bytes BYTES` to recommend one scan in the name index's archive.
863The optional `export_window` field gives the decimal `start` and `length` for
864`rpf9dump models`. It maximizes the sum of unmatched placement rows with a
865single predicted offset in that index. Each identity contributes its placement
866count once. Ambiguous identities contribute zero. For a tie it takes the earliest
867last offset, then trims the interval to its first and last included bytes.
868An empty selection yields JSON null. Run the lookup separately for each archive.
869
870The budget bounds the half-open range of candidate **starts**. The exporter can
871inspect prefix bytes and read model segments beyond the range. The report
872predicts coverage. Confirm identities and offsets in the exported manifest and
873check the resulting placement count with `world_build.py`.
diff --git a/docs/movies.md b/docs/movies.md
index 06a24f7f9..a338069bd 100644
--- a/docs/movies.md
+++ b/docs/movies.md
@@ -4,6 +4,10 @@
4of every stream, and the start of every audio track, decode with the package's own Bink 2 library. The RPF9 table 4of every stream, and the start of every audio track, decode with the package's own Bink 2 library. The RPF9 table
5of contents is encrypted, but the streams can be named from the game's mount lists 5of contents is encrypted, but the streams can be named from the game's mount lists
6([section 8](#8-names-from-the-mount-lists)). Nothing here is a playback path yet.** 6([section 8](#8-names-from-the-mount-lists)). Nothing here is a playback path yet.**
7**Status: indexed and decode-checked. All 515 Bink 2 streams have been enumerated, their fixed headers read, and
8frame 0 of every stream decoded with the package's own Bink 2 library (515/515). The RPF9 table of contents is
9encrypted, but the streams can be named from the game's mount lists ([section 8](#8-names-from-the-mount-lists)).
10Nothing here is a playback path yet.**
7 11
8Every number below was measured on the Xbox Series 1.0.2.1 package on 2026-11-21. The archive is read-only. No 12Every number below was measured on the Xbox Series 1.0.2.1 package on 2026-11-21. The archive is read-only. No
9game video, audio, frames, carved streams or reports that quote them are in this repository; the tools write only 13game video, audio, frames, carved streams or reports that quote them are in this repository; the tools write only
@@ -19,7 +23,7 @@ offsets and header facts. Commands are at the end.
19| Data start in the RPF header (word at +4) | 27,328 (0x6AC0) | 23| Data start in the RPF header (word at +4) | 27,328 (0x6AC0) |
20| First stream offset | 28,672 (0x7000) | 24| First stream offset | 28,672 (0x7000) |
21| Zero padding between streams | 1,094,744 bytes (includes 1,344 bytes before the first stream) | 25| Zero padding between streams | 1,094,744 bytes (includes 1,344 bytes before the first stream) |
22| Other bytes after the last stream | 22,812; not a Bink stream and not zero (purpose unknown) | 26| Bytes after the last stream | 22,812: 3,884 zero bytes to the next 4 KiB boundary, then the 18,928-byte RPF trailer (the header's `u32 +12`; [rpf.md](rpf.md#the-trailer-at-eof)) |
23| Other carved file types | none; the whole data area is Bink 2 | 27| Other carved file types | none; the whole data area is Bink 2 |
24| Revisions | 505 `KB2n`, 10 `KB2j` | 28| Revisions | 505 `KB2n`, 10 `KB2j` |
25| Frame rate | 30/1 in all 515 headers | 29| Frame rate | 30/1 in all 515 headers |
@@ -27,12 +31,13 @@ offsets and header facts. Commands are at the end.
27| Total duration at 30 fps | 14,181.3 s (3 h 56 min) | 31| Total duration at 30 fps | 14,181.3 s (3 h 56 min) |
28| Audio tracks (header field) | 319 streams with 0, 165 with 1, 30 with 2, 1 with 4; 229 tracks total | 32| Audio tracks (header field) | 319 streams with 0, 165 with 1, 30 with 2, 1 with 4; 229 tracks total |
29| Decoded samples | 9 streams, 14 frames, both revisions, 512x512 to 3840x2160 | 33| Decoded samples | 9 streams, 14 frames, both revisions, 512x512 to 3840x2160 |
30| Decode test over the archive | 515 of 515 streams: frames 0 and 1; 229 of 229 audio tracks: PCM for the first 60 frames ([below](#decode-coverage-over-the-whole-archive)) | 34| Decode test over the archive | 515 of 515 streams: frames 0 and 1; 229 of 229 audio tracks: `RESULT PASS`, and PCM bytes reported for the first 60 frames ([below](#decode-coverage-over-the-whole-archive)) |
35| Decoded streams (frame 0, `Bink2Scarlett.dll`) | **515 of 515** (0 failed), both revisions, all 19 resolutions |
31| ffprobe decode result | 0 of 515 (`decodes=no` with a forced `-f bink` probe) | 36| ffprobe decode result | 0 of 515 (`decodes=no` with a forced `-f bink` probe) |
32 37
33`8,831,336,892 + 1,094,744 + 22,812 = 8,832,454,448`, the span from the RPF header's data start to EOF. Readable 38`8,831,336,892 + 1,094,744 + 22,812 = 8,832,454,448`, the span from the RPF header's data start to EOF. Readable
34coverage is 100.0%; the 27,328-byte RPF header (before the data start) and the 22,812-byte tail are the only 39coverage is 100.0%; the 27,328-byte RPF header (before the data start) and the 18,928-byte trailer are the only
35unindexed ranges. 40unindexed ranges, and both are part of the RPF container, not of a stream.
36 41
37`KB2n` is the newer of the two revisions. One DLL string mentions Bink 2.2, but the revision-to-version mapping is 42`KB2n` is the newer of the two revisions. One DLL string mentions Bink 2.2, but the revision-to-version mapping is
38not independently established. 43not independently established.
@@ -80,7 +85,7 @@ these fields plus the audio descriptors and never trusts a size past the stored
80 85
81Only the first 0x2C bytes are fixed. When the audio count is non-zero, the next region is: 86Only the first 0x2C bytes are fixed. When the audio count is non-zero, the next region is:
82 87
83- `count` u32 values: maximum decoded size per audio track (for example 0x23A00 = 146,432). 88- `count` u32 values: maximum decoded size per audio track (0x23A00 = 145,920 across all 229 tracks; `BinkGetTrackMaxSize` adds 512 bytes and returns 0x23C00 = 146,432).
84- `count` pairs of u16: sample rate and flags. Every readable track in this archive is 48,000 Hz. 89- `count` pairs of u16: sample rate and flags. Every readable track in this archive is 48,000 Hz.
85- `count` u32 values: track IDs (0 and 1 in the two-track files). 90- `count` u32 values: track IDs (0 and 1 in the two-track files).
86- then the frame index: `frame_count` u32 offsets. FFmpeg treats the low bit of each offset as the keyframe flag. 91- then the frame index: `frame_count` u32 offsets. FFmpeg treats the low bit of each offset as the keyframe flag.
@@ -113,8 +118,10 @@ reads the 44-byte header and audio descriptors, and writes CSV or JSON. It never
113and then only to a temporary file that is deleted. 118and then only to a temporary file that is deleted.
114 119
115On this archive both tools find the same 515 streams, the same 8,831,336,892 bytes, 1,094,744 bytes of zero 120On this archive both tools find the same 515 streams, the same 8,831,336,892 bytes, 1,094,744 bytes of zero
116padding and 22,812 unread bytes. Running `bink_index.py` on the 515 carved `.bk2` files finds 515 streams with zero 121padding and 22,812 bytes after the last stream. Those 22,812 are 3,884 zero bytes and the 18,928-byte RPF trailer
117unread bytes, which confirms the stored sizes cover each file exactly. 122(counted by reading the tail directly); `bink_index.py` now counts them as zero padding and `rpf_trailer`, which for
123this archive gives `unread_bytes` 0 and zero padding 1,098,628 (derived from the measured tail, not a rerun). Running `bink_index.py` on the 515 carved
124`.bk2` files finds 515 streams with zero unread bytes, which confirms the stored sizes cover each file exactly.
118 125
119## 4. Decoding 126## 4. Decoding
120 127
@@ -172,10 +179,11 @@ build dependency. With that copy:
172 Everything stayed in temp; none is in the repository or PR. 179 Everything stayed in temp; none is in the repository or PR.
173- `BinkGoto(handle, 200, 0)` followed by `BinkDoFrame` produced the 4K frame above, so absolute frame seeking 180- `BinkGoto(handle, 200, 0)` followed by `BinkDoFrame` produced the 4K frame above, so absolute frame seeking
174 works at least in this path. The `BinkGoto` flag meaning was not otherwise tested. 181 works at least in this path. The `BinkGoto` flag meaning was not otherwise tested.
175- `BinkDoFrame` and `BinkCopyToBuffer` returned 0 even when they produced a correct frame. The return semantics of 182- `BinkDoFrame` and `BinkCopyToBuffer` returned 0 even when they produced a correct frame. Over the whole archive
176 this GDK build are therefore not established; a caller must not treat 0 as failure without checking the pixels. 183 they return 0 on every call ([ABI over the archive](#abi-over-the-archive)); a caller must not treat 0 as failure
177- `BinkGetSummary` with a guessed `BINKSUMMARY` layout crashed with an access violation. The `HBINK`, 184 without checking the pixels.
178 `BINKSUMMARY`, `BINKTRACK` and related struct layouts are not established. 185- `BinkGetSummary` with a guessed `BINKSUMMARY` layout crashed with an access violation. With a 1,024-byte buffer it
186 writes bytes +0x00..+0x8F on every stream; the fields found in it are in [ABI over the archive](#abi-over-the-archive).
179 187
180### Decode coverage over the whole archive 188### Decode coverage over the whole archive
181 189
@@ -187,7 +195,7 @@ runtime's shim, so no patched copy of the DLL is involved.
187| Test | Scope | Result | 195| Test | Scope | Result |
188|---|---|---| 196|---|---|---|
189| `bink_decode_test` | all 515 streams | 515 exit 0: `BinkOpen` returns a handle, and frames 0 and 1 each replace the sentinel buffer with more than one byte value | 197| `bink_decode_test` | all 515 streams | 515 exit 0: `BinkOpen` returns a handle, and frames 0 and 1 each replace the sentinel buffer with more than one byte value |
190| `bink_audio_test`, `LEONIDA_AUDIO_FRAMES=60` | all 229 tracks of the 196 streams that have audio (`LEONIDA_AUDIO_TRACK` 0..n-1) | 229 `RESULT PASS`, 0 `FAIL` lines: track id, type and maximum size match the header, `BinkOpenTrack` returns a track, and `BinkGetTrackData` returns a non-empty, whole number of 16-bit samples on every track | 198| `bink_audio_test`, `LEONIDA_AUDIO_FRAMES=60` | all 229 tracks of the 196 streams that have audio (`LEONIDA_AUDIO_TRACK` 0..n-1) | 229 `RESULT PASS`, 0 `FAIL` lines: track id and type match the header, the maximum size covers the header's, and `BinkOpenTrack` returns a track. Separately, the test's per-track `track N: ... bytes=` line is non-zero for 229 of 229 runs; the test itself checks for whole 16-bit samples only when a track returned some, and does not fail on a track that returns none |
191 199
192Measured at `main` `16282101` and again at `f847748c`, with the same counts, on Windows 11 (MSVC 14.44, 200Measured at `main` `16282101` and again at `f847748c`, with the same counts, on Windows 11 (MSVC 14.44,
193RelWithDebInfo). This is a decode check of the start of 201RelWithDebInfo). This is a decode check of the start of
@@ -208,6 +216,35 @@ The nine sampled streams (all at 30 fps):
208| `KB2n` | 720x1280 | 150 | 5.0 s | 1 | 216| `KB2n` | 720x1280 | 150 | 5.0 s | 1 |
209| `KB2n` | 3840x2160 | 450 | 15.0 s | 1 | 217| `KB2n` | 3840x2160 | 450 | 15.0 s | 1 |
210 218
219### Full 515-stream decode check (ASSET-328)
220
221Using the same temporary `xmem.dll` → `msvcrt.dll` (`malloc`/`free`) copy of `Bink2Scarlett.dll` on Windows 11,
222every one of the 515 indexed streams in `movies.rpf` was opened directly from the archive with
223`BinkSetFileOffset(offset)` + `BinkOpen(archive, BINKFILEOFFSET)` (`0x20`), decoded (`BinkDoFrame`), and copied
224into a pre-filled sentinel BGRA buffer (`BinkCopyToBuffer(..., BINKSURFACE32)`). No frames, pixels, audio, or
225carved `.bk2` files were saved.
226
227- **Result:** **515 / 515 decoded, 0 failed** (2.9 s total). Every stream returned a non-null `HBINK` handle,
228 overwrote the sentinel buffer with non-zero BGRA bytes on frame 0, and returned `0` from both `BinkDoFrame` and
229 `BinkCopyToBuffer` (confirming the earlier 9-stream observation across the full corpus).
230- **By revision:** `KB2j` **10 / 10** decoded (`0` failed); `KB2n` **505 / 505** decoded (`0` failed).
231- **By stored stream size:**
232
233| Stream size bucket | Decoded | Failed |
234|---|---:|---:|
235| `< 1 MB` | 50 | 0 |
236| `1–10 MB` | 352 | 0 |
237| `10–50 MB` | 74 | 0 |
238| `>= 50 MB` | 39 | 0 |
239| **Total** | **515** | **0** |
240
241- **By resolution:** all 19 distinct header resolutions (`512x256` through `3840x2160`, matching the resolution
242 table in [section 1](#resolution-distribution-header-width-x-height)) decoded 100% (`0` failed).
243
244This establishes that every indexed stream in `movies.rpf` opens and decodes frame 0 with `Bink2Scarlett.dll`;
245only the four frames from the earlier sample were visually inspected, and decoding all 425,440 frames or audio
246tracks remains untested.
247
211To turn a decoded BGRA buffer into a viewable image without a Bink 2 decoder: 248To turn a decoded BGRA buffer into a viewable image without a Bink 2 decoder:
212 249
213```sh 250```sh
@@ -216,28 +253,102 @@ ffmpeg -f rawvideo -pix_fmt bgra -s 1280x720 -i frame.raw -frames:v 1 frame.png
216 253
217The raw buffer and PNG stay in temp. FFmpeg is only the raw-to-PNG step here; it never sees the `.bk2`. 254The raw buffer and PNG stay in temp. FFmpeg is only the raw-to-PNG step here; it never sees the `.bk2`.
218 255
256### ABI over the archive
257
258[`runtime/test/bink_abi_test.cpp`](../runtime/test/bink_abi_test.cpp) ([notes](../runtime/test/bink_abi_test.md)) maps `Bink2Scarlett.dll` with `rt::Loader` and
259opens each of the 515 streams inside `movies.rpf` (`BinkSetFileOffset`, then `BinkOpen` with flag `0x20`), so nothing
260is extracted. For each stream, it reads the first 256 bytes of the `HBINK` and the `BINKSUMMARY` that `BinkGetSummary`
261writes, and keeps the 32-bit word offsets that hold the stream header's value. An offset is listed only if it
262matched on all 515 streams.
263
264Every stream of 1.0.2.1 runs at 30/1 fps, so the header alone can't separate the rate fields. The test therefore
265reopens one stream after `BinkSetFrameRate(24000, 1001)`. Of the 32 single-bit `BinkOpen` flags, only `0x1000` makes
266that rate take effect. RAD's Bink 1 value, `0x00080000`, changes nothing.
267
268| Field | `HBINK` | `BINKSUMMARY` | How it was told apart |
269|---|---|---|---|
270| width | `+0x00` | `+0x28` | 11 distinct widths |
271| height | `+0x04` | `+0x2c` | 14 distinct heights |
272| frame count | `+0x08` | `+0x48` | 278 distinct counts |
273| current frame (1-based) | `+0x0c` | | 1 after `BinkOpen`, 2 after `BinkNextFrame`, N after `BinkGoto(N)` |
274| playback frame rate | `+0x14` / `+0x18` | `+0x3c` / `+0x40` | the forced 24000/1001 lands here |
275| file frame rate | | `+0x34` / `+0x38` | keeps 30/1 under the forced rate |
276| audio track count | `+0x38` | | values 0, 1, 2 and 4 |
277
278- `BinkGetSummary` writes every byte from +0x00 to +0x8F and none after, on all 515 streams. The test fills a
279 1,024-byte buffer with `0xCD`, then again with `0x5A`. A written byte differs from at least one of the two, so a
280 byte that kept the sentinel both times was not written. This bounds what the call writes, not the declared size of
281 the structure, which may have padding past +0x8F.
282- `BinkDoFrame` and `BinkCopyToBuffer` return 0 on every call. That covers 515 x 3 decodes: frame 1, frame 2, and
283 the frame after `BinkGoto` to the middle of the stream. `BinkCopyToBuffer` replaced the sentinel buffer on every
284 stream.
285- `BinkWait` returns 0 before the first frame. It returns 1 when it is called straight after a decode, that is,
286 before the next frame is due at the stream's rate.
287- The `HBINK` is readable for at least 256 bytes. Fields that matched no header value are not named here; the
288 `BINKTRACK` prefix is in [`bink_audio_test.md`](../runtime/test/bink_audio_test.md).
289### Audio track decoding (`BinkOpenTrack` / `BinkGetTrackData`, ASSET-323)
290
291Using the same temporary `xmem.dll` → `msvcrt.dll` (`malloc`/`free`) copy of `Bink2Scarlett.dll` on Windows 11,
292all **196** audio-bearing streams (**229** tracks total) in `movies.rpf` were opened directly via
293`BinkSetFileOffset` + `BinkOpen(archive, BINKFILEOFFSET)` (`0x20`) and queried through the track API (both with
294default open state and after `BinkSetSoundTrack(0, NULL)`, which behaved identically). No audio bytes were saved.
295
296- **All 229 / 229 tracks opened and decoded (0 failed, 0.98 s total):** `BinkOpenTrack(handle, i)` takes the
297 0-based positional index `i` (`0..audio_tracks - 1`), not the logical track ID, and returned a non-null
298 `HBINKTRACK` for every track (including streams with non-consecutive IDs such as `(3, 1)`, `(1, 3)`, and `(0, 2)`).
299- **Header-to-DLL mapping (229 / 229 exact matches):**
300 - `BinkGetTrackID(handle, i)` equals the header's `track_ids[i]` in **229 / 229** tracks. Header track-ID tuples
301 across the 196 audio-bearing streams: `(0,)` in 165 streams, `(0, 1)` in 21, `(3, 1)` in 6, `(1, 3)` in 2,
302 `(0, 2)` in 1, and `(0, 1, 2, 3)` in 1.
303 - `BinkGetTrackType(handle, i)` packs `(header_flags[i] << 16) | header_rate[i]` in **229 / 229** tracks:
304 `0x7000bb80` (`0x7000`, 48,000 Hz) in 227 tracks and `0x3000bb80` (`0x3000`, 48,000 Hz) in 2 tracks.
305 - `BinkGetTrackMaxSize(handle, i)` returns `146,432` (`0x23C00` = `header_max_size + 512`) for all 229 tracks.
306- **Decoded packet sizes (`BinkGetTrackData` after `BinkDoFrame`):** every track overwrote the sentinel buffer with
307 decoded bytes — **145,920 bytes** on frame 0 (initial pre-roll, matching `header_max_size` in 229/229) and
308 **7,680 bytes** on frame 1 (229/229; confirmed through frame 2 on 1-, 2-, and 4-track samples).
309The loader-side runs behind these numbers are recorded in [`runtime/test/bink_decode_test.md`](../runtime/test/bink_decode_test.md),
310[`runtime/test/bink_audio_test.md`](../runtime/test/bink_audio_test.md) and
311[`runtime/test/bink_play.md`](../runtime/test/bink_play.md).
312
219## 5. What is still unknown 313## 5. What is still unknown
220 314
221- **Roles.** The RPF9 table of contents is encrypted, but `tools/bink_names.py` recovers each stream's path from 315- **Roles.** The RPF9 table of contents is encrypted, but `tools/bink_names.py` recovers each stream's path from
222 the mount lists ([section 8](#8-names-from-the-mount-lists)), and the folder names group the streams by use. What 316 the mount lists ([section 8](#8-names-from-the-mount-lists)), and the folder names group the streams by use. What
223 the game does with each folder at run time is not established. 317 the game does with each folder at run time is not established.
224- **Audio association.** The header gives a track count, sample rate, flags and track IDs, but not which audio 318- **Audio association.** The header gives a track count, sample rate, flags and track IDs, but not which audio
225 belongs to which video frame beyond the interleaving described by the Bink format. `BinkOpenTrack` and 319 belongs to which video frame beyond the interleaving described by the Bink format. `BinkOpenTrack`,
226 `BinkGetTrackData` return 16-bit PCM for all 229 tracks (`runtime/test/bink_audio_test.md`, 320 `BinkGetTrackID`, `BinkGetTrackType`, `BinkGetTrackMaxSize`, and `BinkGetTrackData` succeed on all 229 tracks
227 [coverage above](#decode-coverage-over-the-whole-archive)), but no track was matched to a language or a mix. 321 across the 196 audio-bearing streams
322 ([section 4](#audio-track-decoding-binkopentrack--binkgettrackdata-asset-323)) and return 16-bit PCM for every
323 one of them (the byte count each run prints; `runtime/test/bink_audio_test.md`,
324 [coverage above](#decode-coverage-over-the-whole-archive)): positional track index `i` maps 1:1 to header
325 `track_ids[i]` (`0..3`), `BinkGetTrackType` returns `(flags << 16) | sample_rate`, and `BinkGetTrackData`
326 returned 145,920 bytes on frame 0 and 7,680 bytes on frame 1 across all 229 tracks (with frame 2 also checked on
327 1-, 2-, and 4-track samples; later frames were not swept and may return 7,680 or 0 bytes). Which language or mix
328 role the game assigns to track IDs `0, 1, 2, 3` at run time remains unknown.
228- **Playback integration.** The executable is not in the package. Where the game calls `BinkOpen`, which flags it 329- **Playback integration.** The executable is not in the package. Where the game calls `BinkOpen`, which flags it
229 passes, whether it uses `BinkDoFrameAsync`, `BinkGoto`, subtitles or the GPU path, and how it schedules movies 330 passes, whether it uses `BinkDoFrameAsync`, `BinkGoto`, subtitles or the GPU path, and how it schedules movies
230 against streaming are all unknown. 331 against streaming are all unknown.
231- **Bink2Scarlett ABI.** The struct layouts, the real return values of `BinkDoFrame`/`BinkCopyToBuffer`, the 332- **Bink2Scarlett ABI.** [ABI over the archive](#abi-over-the-archive) gives the `HBINK` and `BINKSUMMARY` fields
232 `BinkGetSummary` layout, the async API, the GPU API and the XAudio2 setup are not established. The DLL loads on 333 that match the stream header, the bytes `BinkGetSummary` writes (+0x00..+0x8F), and the return values of `BinkWait`, `BinkDoFrame` and
334 `BinkCopyToBuffer`. The rest of both structures, the async API, the GPU API and the XAudio2 setup are not
335 established. The DLL loads on
233 Windows only after the missing `xmem.dll` imports are supplied; a proper port needs an allocator shim with the 336 Windows only after the missing `xmem.dll` imports are supplied; a proper port needs an allocator shim with the
234 Xbox semantics, not necessarily `malloc`. 337 Xbox semantics, not necessarily `malloc`.
235- **Why 22,812 bytes at the end are unread.** They are not a `KB2` stream and not zero. They may be an RPF footer 338- **What the RPF trailer holds.** The 22,812 bytes after the last stream are no longer unexplained (ASSET-318):
236 or leftover table data; the encrypted TOC prevents a name-level answer. 339 3,884 zeros pad to a 4 KiB boundary, and the remaining 18,928 bytes, to EOF, are exactly the header's `u32 +12`,
340 the RPF9 trailer ([rpf.md](rpf.md#the-trailer-at-eof); confirmed in 14 of the package's 22 archives, 8
341 undecided, none against). Its contents are high-entropy (7.99 bits per byte) with no zlib or `KB2` header, like the TOC; this
342 project does not decode them.
237- **Whether every frame of all 515 streams decodes correctly.** All 515 open and decode their first two frames 343- **Whether every frame of all 515 streams decodes correctly.** All 515 open and decode their first two frames
238 through the package's DLL ([coverage above](#decode-coverage-over-the-whole-archive)); nine were decoded as a 344 through the package's DLL ([coverage above](#decode-coverage-over-the-whole-archive)); nine were decoded as a
239 sample with frames viewed. No stream was decoded from its first frame to its last, and nothing compares the 345 sample with frames viewed. No stream was decoded from its first frame to its last, and nothing compares the
240 output with a reference. 346 output with a reference.
347- **Why 22,812 bytes at the end are unread.** They are not a `KB2` stream and not zero. They may be an RPF footer
348 or leftover table data; the encrypted TOC prevents a name-level answer.
349- **Full-stream playback beyond frame 0.** All 515 streams open and decode frame 0 with `Bink2Scarlett.dll`
350 (0 failed; see [Full 515-stream decode check](#full-515-stream-decode-check-asset-328)), settling stream-level
351 decodability. Decoding every one of the 425,440 frames and playing back the 229 audio tracks remain untested.
241 352
242## 6. No-sharing rule 353## 6. No-sharing rule
243 354
@@ -261,7 +372,8 @@ python -I tools/bink_index.py <temp>/movies --out <temp>/movies-probe.csv --prob
261``` 372```
262 373
263The measured run produced 515 rows, 8,831,336,892 stream bytes, 1,094,744 zero bytes and 22,812 unread bytes from 374The measured run produced 515 rows, 8,831,336,892 stream bytes, 1,094,744 zero bytes and 22,812 unread bytes from
264the archive, and the same 515 rows with zero unread from the carved directory. `--probe` produced 515 `no` values. 375the archive (before `bink_index.py` split off the RPF trailer; see section 3), and the same 515 rows with zero
376unread from the carved directory. `--probe` produced 515 `no` values.
265 377
266## Appendix A: `Bink2Scarlett.dll` exports 378## Appendix A: `Bink2Scarlett.dll` exports
267 379
diff --git a/docs/navmesh.md b/docs/navmesh.md
index fa6f1bca0..9027ea2c7 100644
--- a/docs/navmesh.md
+++ b/docs/navmesh.md
@@ -32,7 +32,7 @@ is in this document or the repository.
32| Inflated bytes | 20,551,068,624 (3.14x stored) | 32| Inflated bytes | 20,551,068,624 (3.14x stored) |
33| Zero padding | 161,191,191 (2.40%) | 33| Zero padding | 161,191,191 (2.40%) |
34| Unread (non-zero, non-stream) | 6,080,993 (0.09%) | 34| Unread (non-zero, non-stream) | 6,080,993 (0.09%) |
35| Tiny continuations recovered (`16–48` B) | 10 (`3` `0DRP`, `7` `0x00010015`) | 35| Tiny continuations recovered (`16–48` B) | 10 (`3` `0DRP`, `7` `0x00010015`) |
36| Bink 2 streams | 0 | 36| Bink 2 streams | 0 |
37 37
38Every stream in the earlier 53,026 "other" bucket is now classified into continuations or the Band-3 `grid` class 38Every stream in the earlier 53,026 "other" bucket is now classified into continuations or the Band-3 `grid` class
@@ -55,9 +55,9 @@ sub-RPF header/TOC gaps (`5,947,550` bytes total) plus `117,745` non-zero bytes
55 55
56| Band | Archive offset range | Contents | 56| Band | Archive offset range | Contents |
57|---|---|---| 57|---|---|---|
58| **Band 1** (`0DRP`) | `0x0000037010` – `0x002ed51619` | All `9,603` `0DRP` cover-point resources (`7,122` 1-stream, `2,481` 2-stream) | 58| **Band 1** (`0DRP`) | `0x0000037010` – `0x002ed51619` | All `9,603` `0DRP` cover-point resources (`7,122` 1-stream, `2,481` 2-stream) |
59| **Band 2** (`0x00010015`) | `0x002ed87000` – `0x0174b93f8f` | All `27,644` navmesh tiles (`4,598` 1-stream, `23,046` 2-stream) + `11` `PSIN` (`10` regional + `1` non-grid) | 59| **Band 2** (`0x00010015`) | `0x002ed87000` – `0x0174b93f8f` | All `27,644` navmesh tiles (`4,598` 1-stream, `23,046` 2-stream) + `11` `PSIN` (`10` regional + `1` non-grid) |
60| **Band 3** (`grid`) | `0x0174bbc000` – `0x018fcab8bf` | All `27,482` `grid` resources (`27,476` 1-stream, `6` 2-stream) + `11` `PSIN` (`10` identical regional pairs + `1` EOF v79) | 60| **Band 3** (`grid`) | `0x0174bbc000` – `0x018fcab8bf` | All `27,482` `grid` resources (`27,476` 1-stream, `6` 2-stream) + `11` `PSIN` (`10` identical regional pairs + `1` EOF v79) |
61 61
62Within Bands 2 and 3, static tiles are packed into 10 regional sub-RPF partitions (`2,448` unique tiles each, headed by 62Within Bands 2 and 3, static tiles are packed into 10 regional sub-RPF partitions (`2,448` unique tiles each, headed by
6310 byte-for-byte identical `PSIN` version-256 pairs), plus an overlay partition of `3,002` variant tiles (`940` unique 6310 byte-for-byte identical `PSIN` version-256 pairs), plus an overlay partition of `3,002` variant tiles (`940` unique
@@ -72,13 +72,13 @@ pointer base (`offset = u64_ptr - 0x50000000` when the upper 32 bits are zero an
72- `+0x00` (`u64`): always `0` (`64,729 / 64,729`). 72- `+0x00` (`u64`): always `0` (`64,729 / 64,729`).
73- `+0x08` (`u64`): pointer to a block-map descriptor (`24` bytes on `0DRP`, `32` bytes on `0x00010015` and `grid`): 73- `+0x08` (`u64`): pointer to a block-map descriptor (`24` bytes on `0DRP`, `32` bytes on `0x00010015` and `grid`):
74 - `+0x00` (`u64`): `0` 74 - `+0x00` (`u64`): `0`
75 - `+0x08` (`u64`): **exact logical zlib stream count (`1` or `2`)** â€â€� matches actual stream membership on 75 - `+0x08` (`u64`): **exact logical zlib stream count (`1` or `2`)** — matches actual stream membership on
76 `9,603 / 9,603` `0DRP`, `27,644 / 27,644` `0x00010015`, and `27,482 / 27,482` `grid` resources (`0` resources span 76 `9,603 / 9,603` `0DRP`, `27,644 / 27,644` `0x00010015`, and `27,482 / 27,482` `grid` resources (`0` resources span
77 more than 2 streams). 77 more than 2 streams).
78 - `+0x10` (`u64`): `0` (and `+0x18` `u64` is `0` on `100%` of `0x00010015` and `grid`; on `105` `0DRP` pages the next 78 - `+0x10` (`u64`): `0` (and `+0x18` `u64` is `0` on `100%` of `0x00010015` and `grid`; on `105` `0DRP` pages the next
79 object begins at `+0x18`, confirming the `0DRP` block map is 24 bytes). 79 object begins at `+0x18`, confirming the `0DRP` block map is 24 bytes).
80 80
81## `0DRP` directory pages (`9,603` pages â€â€� `0x7a` cover-point resources) 81## `0DRP` directory pages (`9,603` pages — `0x7a` cover-point resources)
82 82
83`0DRP` pages in `navmeshes.rpf` are **self-describing `0x7a` resources** (the same container format documented in 83`0DRP` pages in `navmeshes.rpf` are **self-describing `0x7a` resources** (the same container format documented in
84[world.md](world.md) and [page_directory.md](page_directory.md)). Reconciling the full `9,603`-page corpus settles the 84[world.md](world.md) and [page_directory.md](page_directory.md)). Reconciling the full `9,603`-page corpus settles the
@@ -93,18 +93,18 @@ fields previously marked "not decoded" (`+0x48` eight `u16` values, `+0x60` "key
93| `+0x10` | 4 | `30 44 52 50` (`0DRP`) | `0x7a` container magic | 93| `+0x10` | 4 | `30 44 52 50` (`0DRP`) | `0x7a` container magic |
94| `+0x14` | 4 | `122` (`0x7A`, `9,603 / 9,603`) | format version | 94| `+0x14` | 4 | `122` (`0x7A`, `9,603 / 9,603`) | format version |
95| `+0x18` | 8 | zero (`9,603 / 9,603`) | reserved | 95| `+0x18` | 8 | zero (`9,603 / 9,603`) | reserved |
96| `+0x20` | 4 | `1–6` (`3`: 7,650, `4`: 932, `2`: 779, `6`: 219, `5`: 22, `1`: 1) | **1-based index into `q38` naming the root object block** (`1 <= u20 <= n_blocks` and `blocks[u20-1].hash` is in `q28` on `9,603 / 9,603`) | 96| `+0x20` | 4 | `1–6` (`3`: 7,650, `4`: 932, `2`: 779, `6`: 219, `5`: 22, `1`: 1) | **1-based index into `q38` naming the root object block** (`1 <= u20 <= n_blocks` and `blocks[u20-1].hash` is in `q28` on `9,603 / 9,603`) |
97| `+0x24` | 4 | zero (`9,603 / 9,603`) | high half of `+0x20` | 97| `+0x24` | 4 | zero (`9,603 / 9,603`) | high half of `+0x20` |
98| `+0x28` | 8 | `0x50xxxxxx`, 8-byte aligned | pointer to `q28` struct schema table (`32` B/record) | 98| `+0x28` | 8 | `0x50xxxxxx`, 8-byte aligned | pointer to `q28` struct schema table (`32` B/record) |
99| `+0x30` | 8 | `0x50xxxxxx` (`9,600`) or `0` (`3`) | pointer to `q30` enum schema table (`24` B/record) | 99| `+0x30` | 8 | `0x50xxxxxx` (`9,600`) or `0` (`3`) | pointer to `q30` enum schema table (`24` B/record) |
100| `+0x38` | 8 | `0x50xxxxxx`, 16-byte aligned | pointer to `q38` instance block table (`16` B/record) | 100| `+0x38` | 8 | `0x50xxxxxx`, 16-byte aligned | pointer to `q38` instance block table (`16` B/record) |
101| `+0x40` | 8 | `0x50xxxxxx`, 8-byte aligned | pointer to `q40` auxiliary table (`{u32 count, count x {u32 tag, u32 size}, payloads}`) | 101| `+0x40` | 8 | `0x50xxxxxx`, 8-byte aligned | pointer to `q40` auxiliary table (`{u32 count, count x {u32 tag, u32 size}, payloads}`) |
102| `+0x48` | 2 | `2–12` | `n_structs`: number of `q28` struct definitions | 102| `+0x48` | 2 | `2–12` | `n_structs`: number of `q28` struct definitions |
103| `+0x4a` | 2 | `0–4` | `n_enums`: number of `q30` enum definitions | 103| `+0x4a` | 2 | `0–4` | `n_enums`: number of `q30` enum definitions |
104| `+0x4c` | 2 | `2–6` | `n_blocks`: number of `q38` instance blocks | 104| `+0x4c` | 2 | `2–6` | `n_blocks`: number of `q38` instance blocks |
105| `+0x4e` | 2 | `0` (`2,578`) or `1..602` (`7,025`) | **`pages_4k`:** `0` or `ceil(data_end / 4096)` (`9,603 / 9,603`; see rule below) | 105| `+0x4e` | 2 | `0` (`2,578`) or `1..602` (`7,025`) | **`pages_4k`:** `0` or `ceil(data_end / 4096)` (`9,603 / 9,603`; see rule below) |
106| `+0x50` | 16 | zero (`9,603 / 9,603`) | reserved (covers the trailing four `u16`s of `+0x48..+0x57` plus `+0x58..+0x5f`) | 106| `+0x50` | 16 | zero (`9,603 / 9,603`) | reserved (covers the trailing four `u16`s of `+0x48..+0x57` plus `+0x58..+0x5f`) |
107| `+0x60` | â€â€� | first `q38` instance block (`9,603 / 9,603`) | **payload, not a header field** | 107| `+0x60` | — | first `q38` instance block (`9,603 / 9,603`) | **payload, not a header field** |
108 108
109#### Decoding `u16@0x4e` (`pages_4k`) 109#### Decoding `u16@0x4e` (`pages_4k`)
110 110
@@ -128,14 +128,14 @@ Across all **9,603 / 9,603** pages (`0` exceptions), `u16@0x4e` is either `0` or
128- **`q38` instance blocks (`16` B/record):** `{u32 struct_or_type_hash, u32 byte_size, ptr64 target}`. Disjoint with **0 overlaps** across all `9,603` pages (`54,898` total records, including `18` on the 3 tiny-continuation pages); every page has a block starting at `+0x60`. 128- **`q38` instance blocks (`16` B/record):** `{u32 struct_or_type_hash, u32 byte_size, ptr64 target}`. Disjoint with **0 overlaps** across all `9,603` pages (`54,898` total records, including `18` on the 3 tiny-continuation pages); every page has a block starting at `+0x60`.
129- **`q40` auxiliary table:** `{u32 count, count x {u32 tag, u32 size}, payload bytes}`. Fits cleanly in-bounds on `9,603 / 9,603` pages. On `8,275` world-grid `CCoverPointRegion` pages it holds a single tag `0x101` (`32/48/64/80` B = `2..5` 16-byte entries); on all `137` non-grid `CCoverPointRegion` pages and all `1,187` `0x4712787b` pages `count == 0`; the 4 singleton pages carry larger `0x101`, `0x207` or `0x211` tables. 129- **`q40` auxiliary table:** `{u32 count, count x {u32 tag, u32 size}, payload bytes}`. Fits cleanly in-bounds on `9,603 / 9,603` pages. On `8,275` world-grid `CCoverPointRegion` pages it holds a single tag `0x101` (`32/48/64/80` B = `2..5` 16-byte entries); on all `137` non-grid `CCoverPointRegion` pages and all `1,187` `0x4712787b` pages `count == 0`; the 4 singleton pages carry larger `0x101`, `0x207` or `0x211` tables.
130 130
131Only **10 distinct schemas** (6 root structs) occur across all `9,603` `0DRP` pages â€â€� **all cover-point data, not 131Only **10 distinct schemas** (6 root structs) occur across all `9,603` `0DRP` pages — **all cover-point data, not
132navmesh polygons**. Struct/enum/member hashes match standard RAGE cover names under **case-sensitive joaat32** 132navmesh polygons**. Struct/enum/member hashes match standard RAGE cover names under **case-sensitive joaat32**
133(verified from hand-typed clean-room candidates in `tools/navmesh_decode.py`): 133(verified from hand-typed clean-room candidates in `tools/navmesh_decode.py`):
134 134
135| Root struct (joaat32) | Pages | Schemas | Summary | 135| Root struct (joaat32) | Pages | Schemas | Summary |
136|---|---:|---:|---| 136|---|---:|---:|---|
137| `CCoverPointRegion` (`0x2283b2cb`, `304` B) | 8,412 | 2 (`11–12` structs) | `8,275` 128 m × 128 m world-grid cover tiles + `137` smaller local/interior tiles; `15,474,729` `CCoverPointNode` (`0x0bcb00e4`, `160` B) instances (`+0xA0` `u16` array count `== block_count` on `8,412 / 8,412`; `+0x04` `i32` point count matches on `8,411 / 8,412`, with 1 local tile at `0x2e329010` having `23` vs `8` serialized nodes); world bounds (`+0x10`/`+0x20`) `X ∈ [-10,368, +10,411.9]`, `Y ∈ [-8,448, +9,472]`, `Z ∈ [-500, +1,350]` m; `256` sub-regions (`0xde5f1345`, `4,096` B) + `CCoverSpatialTreeNode` (`0xbb5a70d8`, `64` B) | 137| `CCoverPointRegion` (`0x2283b2cb`, `304` B) | 8,412 | 2 (`11–12` structs) | `8,275` 128 m × 128 m world-grid cover tiles + `137` smaller local/interior tiles; `15,474,729` `CCoverPointNode` (`0x0bcb00e4`, `160` B) instances (`+0xA0` `u16` array count `== block_count` on `8,412 / 8,412`; `+0x04` `i32` point count matches on `8,411 / 8,412`, with 1 local tile at `0x2e329010` having `23` vs `8` serialized nodes); world bounds (`+0x10`/`+0x20`) `X ∈ [-10,368, +10,411.9]`, `Y ∈ [-8,448, +9,472]`, `Z ∈ [-500, +1,350]` m; `256` sub-regions (`0xde5f1345`, `4,096` B) + `CCoverSpatialTreeNode` (`0xbb5a70d8`, `64` B) |
138| `0x4712787b` (`48` B, name open) | 1,187 | 4 (`3–9` structs) | Local-space dynamic/entity cover sets (`155,250` `CCoverPointNode` instances on `1,173` pages, `0` nodes on `14` pages; node `+0x38` `f32[3]` positions in `[-63.1, +67.0] × [-36.0, +35.4] × [-72.1, +6.9]` m; `q40` always empty) | 138| `0x4712787b` (`48` B, name open) | 1,187 | 4 (`3–9` structs) | Local-space dynamic/entity cover sets (`155,250` `CCoverPointNode` instances on `1,173` pages, `0` nodes on `14` pages; node `+0x38` `f32[3]` positions in `[-63.1, +67.0] × [-36.0, +35.4] × [-72.1, +6.9]` m; `q40` always empty) |
139| `CCoverPointRegionManifest` (`0xe842b0d6`, `48` B) | 1 | 1 (`4` structs) | Singleton at `0xca9d010`: `6,446` `CCoverPointRegionDef` (`0xbea9889e`, `64` B) entries | 139| `CCoverPointRegionManifest` (`0xe842b0d6`, `48` B) | 1 | 1 (`4` structs) | Singleton at `0xca9d010`: `6,446` `CCoverPointRegionDef` (`0xbea9889e`, `64` B) entries |
140| `0xb6dbe11b` (`16` B, name open) | 1 | 1 (`2` structs) | Singleton at `0x24c9a010`: `1,829` `0x0904902e` (`24` B) entries mapping hashes/strings to `RegionIndex` | 140| `0xb6dbe11b` (`16` B, name open) | 1 | 1 (`2` structs) | Singleton at `0x24c9a010`: `1,829` `0x0904902e` (`24` B) entries mapping hashes/strings to `RegionIndex` |
141| `0x339accda` / `0x2bf76252` (`24` B, names open) | 2 | 2 (`2` structs each) | Two singleton map tables (`0x2e43e010`, `0x2ed47010`) | 141| `0x339accda` / `0x2bf76252` (`24` B, names open) | 2 | 2 (`2` structs each) | Two singleton map tables (`0x2e43e010`, `0x2ed47010`) |
@@ -157,12 +157,12 @@ first `q38` payload block starting at `+0x60`:
157 157
158| Block placed at `+0x60` | Pages | `+0x60..+0x8f` byte layout | 158| Block placed at `+0x60` | Pages | `+0x60..+0x8f` byte layout |
159|---|---:|---| 159|---|---:|---|
160| `CCoverPointNode[]` (`0x0bcb00e4`, `160` B/node) | **9,378** (`8,205` region + `1,173` dynamic) | Node 0 starts with **three 16-byte `CCoverNodeId` (`0xa33600ff`) structs** at `+0x60`, `+0x70`, `+0x80`, each `{u64 id_key, u32 field_08, u32 local_index}`. `+0x60..+0x67` is `Uid.id_key` (always nonzero); `+0x68..+0x6b` is `0` on all `1,173` local/dynamic `0x4712787b` pages; `+0x6c..+0x6f` is `Uid.local_index` (`0` on all `9,378` pages because it is node 0). **`+0x70..+0x7f`** is the second `CCoverNodeId` (repeating `Uid.id_key` on `1,186` pages and holding sentinel `0xffffffff` at `+0x7c` on `3,966` pages and at `+0x78` on `1,912` pages — the `+0x70` pattern). **`+0x80..+0x8f`** is the third `CCoverNodeId` (repeating `id_key` on `2,237` pages, `local_index == 1` on `9,105` pages, `0xffffffff` on `203` pages). | 160| `CCoverPointNode[]` (`0x0bcb00e4`, `160` B/node) | **9,378** (`8,205` region + `1,173` dynamic) | Node 0 starts with **three 16-byte `CCoverNodeId` (`0xa33600ff`) structs** at `+0x60`, `+0x70`, `+0x80`, each `{u64 id_key, u32 field_08, u32 local_index}`. `+0x60..+0x67` is `Uid.id_key` (always nonzero); `+0x68..+0x6b` is `0` on all `1,173` local/dynamic `0x4712787b` pages; `+0x6c..+0x6f` is `Uid.local_index` (`0` on all `9,378` pages because it is node 0). **`+0x70..+0x7f`** is the second `CCoverNodeId` (repeating `Uid.id_key` on `1,186` pages and holding sentinel `0xffffffff` at `+0x7c` on `3,966` pages and at `+0x78` on `1,912` pages — the `+0x70` pattern). **`+0x80..+0x8f`** is the third `CCoverNodeId` (repeating `id_key` on `2,237` pages, `local_index == 1` on `9,105` pages, `0xffffffff` on `203` pages). |
161| `0xde5f1345[]` (`256 × 16` B sub-regions) | **207** (all `CCoverPointRegion`) | First `atArray<u16>` descriptor. On **`194`** pages the first sub-region is empty (`{0, 0, 0}` -> exact match for all **194** zero `+0x60` values and `194` of the `u32_68 == 0` pages); on `13` pages it is non-empty. | 161| `0xde5f1345[]` (`256 × 16` B sub-regions) | **207** (all `CCoverPointRegion`) | First `atArray<u16>` descriptor. On **`194`** pages the first sub-region is empty (`{0, 0, 0}` -> exact match for all **194** zero `+0x60` values and `194` of the `u32_68 == 0` pages); on `13` pages it is non-empty. |
162| `0x00000100` (map-pair array) | **16** (`14` empty `0x4712787b` + `2` singletons) | Map entry array; contributes the remaining `14` `u32_68 == 0` pages (`1,173 + 194 + 14 = 1,381` exact). | 162| `0x00000100` (map-pair array) | **16** (`14` empty `0x4712787b` + `2` singletons) | Map entry array; contributes the remaining `14` `u32_68 == 0` pages (`1,173 + 194 + 14 = 1,381` exact). |
163| `CCoverPointRegionDef[]` / `0x0904902e[]` | **2** (`2` singletons) | First manifest/index record (accounts for 2 of the 3 nonzero `+0x6c` words; `0x339accda` accounts for the 3rd). | 163| `CCoverPointRegionDef[]` / `0x0904902e[]` | **2** (`2` singletons) | First manifest/index record (accounts for 2 of the 3 nonzero `+0x6c` words; `0x339accda` accounts for the 3rd). |
164 164
165## Typed data pages (`27,644` pages â€â€� `0x00010015` navmesh tiles) 165## Typed data pages (`27,644` pages — `0x00010015` navmesh tiles)
166 166
167The 27,644 pages with `u32 0x00010015` at `+0x14` are the actual **navmesh geometry tiles** (RAGE `CNavMesh`-family 167The 27,644 pages with `u32 0x00010015` at `+0x14` are the actual **navmesh geometry tiles** (RAGE `CNavMesh`-family
168layout, fixed `0xF0`-byte header, `14.36 GiB` / `15,420,757,856` bytes inflated including continuations). 168layout, fixed `0xF0`-byte header, `14.36 GiB` / `15,420,757,856` bytes inflated including continuations).
@@ -172,10 +172,10 @@ layout, fixed `0xF0`-byte header, `14.36 GiB` / `15,420,757,856` bytes inflated
172| Offset | Size | Type | Verified meaning | Full-corpus check (`27,644` pages) | 172| Offset | Size | Type | Verified meaning | Full-corpus check (`27,644` pages) |
173|---:|---:|---|---|---| 173|---:|---:|---|---|---|
174| `+0x00` | 8 | `u64` | `pgBase` vtable slot | `0` on `27,644 / 27,644` | 174| `+0x00` | 8 | `u64` | `pgBase` vtable slot | `0` on `27,644 / 27,644` |
175| `+0x08` | 8 | `ptr64` | Pointer to 32-byte block map | `bm[1] == stream_count` (`4,598` × 1, `23,046` × 2) on `27,644 / 27,644` | 175| `+0x08` | 8 | `ptr64` | Pointer to 32-byte block map | `bm[1] == stream_count` (`4,598` × 1, `23,046` × 2) on `27,644 / 27,644` |
176| `+0x10` | 4 | `u32` | Navmesh flags bitmask | `{9: 18791, 11: 5507, 3: 3149, 7: 161, 1: 35, 69: 1}` | 176| `+0x10` | 4 | `u32` | Navmesh flags bitmask | `{9: 18791, 11: 5507, 3: 3149, 7: 161, 1: 35, 69: 1}` |
177| `+0x14` | 4 | `u32` | Format word (`0x00010015`, low16 = `21`) | `0x00010015` on `27,644 / 27,644` | 177| `+0x14` | 4 | `u32` | Format word (`0x00010015`, low16 = `21`) | `0x00010015` on `27,644 / 27,644` |
178| `+0x20` | 64 | `f32[16]` | Transform matrix (padded 3×4) | Identity `(1,0,0,0 / 0,1,0,0 / 0,0,1,0 / 0,0,0,0)` on `27,644 / 27,644` | 178| `+0x20` | 64 | `f32[16]` | Transform matrix (padded 3×4) | Identity `(1,0,0,0 / 0,1,0,0 / 0,0,1,0 / 0,0,0,0)` on `27,644 / 27,644` |
179| `+0x60` | 12 | `f32[3]` | 3D tile extents `(dx, dy, dz)` | Matches `quadtree_root.vMax - vMin` (`< 0.02` m) on `27,644 / 27,644`; `(128, 128)` on all `27,482` static tiles | 179| `+0x60` | 12 | `f32[3]` | 3D tile extents `(dx, dy, dz)` | Matches `quadtree_root.vMax - vMin` (`< 0.02` m) on `27,644 / 27,644`; `(128, 128)` on all `27,482` static tiles |
180| `+0x70` | 8 | `ptr64` | `aiSplitArray` of compressed vertices (`6` B: `u16[3]`) | Valid & total `== u32@0xC0` (`138,041,746` verts, max `52,608`) on `27,644 / 27,644` | 180| `+0x70` | 8 | `ptr64` | `aiSplitArray` of compressed vertices (`6` B: `u16[3]`) | Valid & total `== u32@0xC0` (`138,041,746` verts, max `52,608`) on `27,644 / 27,644` |
181| `+0x78` | 8 | `ptr64` | Uncompressed vertex array (unused; bit 0 always set) | `0` on `27,644 / 27,644` | 181| `+0x78` | 8 | `ptr64` | Uncompressed vertex array (unused; bit 0 always set) | `0` on `27,644 / 27,644` |
@@ -189,7 +189,7 @@ layout, fixed `0xF0`-byte header, `14.36 GiB` / `15,420,757,856` bytes inflated
189| `+0xB8` | 8 | `ptr64` | Nullable 96-byte obstacle footprint array (count `u32@0xDC`) | Present on `9,425` pages (`6,246,890` records = `3,123,445` outer/inner contour pairs); in-bounds & valid `27,644 / 27,644` | 189| `+0xB8` | 8 | `ptr64` | Nullable 96-byte obstacle footprint array (count `u32@0xDC`) | Present on `9,425` pages (`6,246,890` records = `3,123,445` outer/inner contour pairs); in-bounds & valid `27,644 / 27,644` |
190| `+0xC0` | 4 | `u32` | Vertex count | Min `4`, max `52,608`, sum `138,041,746` | 190| `+0xC0` | 4 | `u32` | Vertex count | Min `4`, max `52,608`, sum `138,041,746` |
191| `+0xC4` | 4 | `u32` | Polygon count | Min `1`, max `71,803`, sum `124,768,148` | 191| `+0xC4` | 4 | `u32` | Polygon count | Min `1`, max `71,803`, sum `124,768,148` |
192| `+0xC8` | 4 | `u32` | 512 × 512 sector ID (`0` if `flags & 4`) | `0` iff `flags & 4` (`162` pages); exact `136 × 180 = 24,480` static grid | 192| `+0xC8` | 4 | `u32` | 512 × 512 sector ID (`0` if `flags & 4`) | `0` iff `flags & 4` (`162` pages); exact `136 × 180 = 24,480` static grid |
193| `+0xCC` | 4 | `u32` | Core mesh data byte size | `6*c0 + 14*pool + 44*c4 + 32*d4 == u32@0xCC` with **0 residual** on `27,644 / 27,644` | 193| `+0xCC` | 4 | `u32` | Core mesh data byte size | `6*c0 + 14*pool + 44*c4 + 32*d4 == u32@0xCC` with **0 residual** on `27,644 / 27,644` |
194| `+0xD4` / `+0xD8` / `+0xDC` | 12 | `u32[3]` | Special-link, link-index, and `+0xB8` record counts | Sums `26,679,246` / `26,903,247` / `6,246,890` | 194| `+0xD4` / `+0xD8` / `+0xDC` | 12 | `u32[3]` | Special-link, link-index, and `+0xB8` record counts | Sums `26,679,246` / `26,903,247` / `6,246,890` |
195| `+0xE8` | 4 | `u8[4]` | Build stamp (`0` if `flags & 4`): second, minute, hour, day of month | `7` distinct values (`0` on `162`, `0x09090516` on `24,474`, `0x160e3132` on `3,003`, 4 rare on `5`); see [Build stamp](#build-stamp-0xe8) | 195| `+0xE8` | 4 | `u8[4]` | Build stamp (`0` if `flags & 4`): second, minute, hour, day of month | `7` distinct values (`0` on `162`, `0x09090516` on `24,474`, `0x160e3132` on `3,003`, 4 rare on `5`); see [Build stamp](#build-stamp-0xe8) |
@@ -221,10 +221,13 @@ the first four fields of C's `struct tm` in their order. No month or year is sto
221 positions (the `u32@0xC8` sector, above). The 3,002 extra tiles are all on 940 positions that hold 2 to 40 tiles, 221 positions (the `u32@0xC8` sector, above). The 3,002 extra tiles are all on 940 positions that hold 2 to 40 tiles,
222 and every one of those positions has day-22 tiles. 2,984 of the 3,003 day-22 tiles share their position with a 222 and every one of those positions has day-22 tiles. 2,984 of the 3,003 day-22 tiles share their position with a
223 day-9 tile, and on all 938 positions with both, the day-22 tiles come later in the archive. The other 19 are on two 223 day-9 tile, and on all 938 positions with both, the day-22 tiles come later in the archive. The other 19 are on two
224 positions without a day-9 tile: 17 at sector (255, 248), and 2 with the day-24 tile at (248, 246). On 450 of the 938, the first day-22 tile has the same vertex and polygon 224 positions without a day-9 tile: 17 at sector (255, 248), and 2 with the day-24 tile at (248, 246). On 450 of the
225 counts as the day-9 tile. What the stacked tiles are for is not measured. 225 938, the first day-22 tile has the same vertex and polygon counts as the day-9 tile. What the stacked tiles are for
226- **Neighbouring tiles share a stamp.** Of the 48,644 pairs of grid neighbours (one tile per position), 98.12% have 226 is not measured.
227 the same stamp, against 92.58% for stamps placed at random with the same frequencies. 227- **Neighbouring tiles share a stamp.** Taking the last tile in the archive at each position (the day-22 one where a
228 position has both), 98.12% of the 48,644 pairs of grid neighbours have the same stamp, against 92.58% for stamps
229 placed at random with the same frequencies. Taking the first tile instead gives 99.95% against 99.95%, which says
230 nothing, because almost every first tile is day 9.
228 231
229Method: `tools/navmesh_decode.py`'s own scan of `navmeshes.rpf`, with each tile's `u32@0xE8`, `u32@0xC8`, flags, 232Method: `tools/navmesh_decode.py`'s own scan of `navmeshes.rpf`, with each tile's `u32@0xE8`, `u32@0xC8`, flags,
230counts and archive offset recorded per tile. No geometry was kept. 233counts and archive offset recorded per tile. No geometry was kept.
@@ -233,10 +236,10 @@ The `+4` word of a polygon packs `(index start << 4) | count`; the runs tile the
233(`tools/navmesh_decode.py --deep` checks it on all `124,768,148` polygons, 0 failures), which caps a polygon at 15 236(`tools/navmesh_decode.py --deep` checks it on all `124,768,148` polygons, 0 failures), which caps a polygon at 15
234vertices. 6stars independently reads the same packing. Its polygon `+0x28` bit 17 and `+0x18` bit 27 237vertices. 6stars independently reads the same packing. Its polygon `+0x28` bit 17 and `+0x18` bit 27
235road/pavement labels were not adopted: a 1,027,984-polygon sample over 238 tiles sets both bits on 258 polygons, so 238road/pavement labels were not adopted: a 1,027,984-polygon sample over 238 tiles sets both bits on 258 polygons, so
236they are not a partition and neither meaning is confirmed. No 6stars code was copied; the repository has no 239they are not a partition, and in the lane-graph count [below](#polygon-flags-under-the-lane-graph) neither is under
237licence. 240most lane nodes; `+0x18` bits 8 and 13 are. No 6stars code was copied; the repository has no licence.
238 241
239### Flags (`u32@0x10`) and 512 × 512 world grid 242### Flags (`u32@0x10`) and 512 × 512 world grid
240 243
241- **Bit 0 (`0x01`)**: set on `27,644 / 27,644` (compressed 6-byte vertices at `+0x70`, `+0x78 == 0`). 244- **Bit 0 (`0x01`)**: set on `27,644 / 27,644` (compressed 6-byte vertices at `+0x70`, `+0x78 == 0`).
242- **Bit 1 (`0x02`)**: exact bijection (`27,644 / 27,644`) with special links (`+0xA8/+0xB0` non-null, `u32@0xD4/0xD8 > 0`; `8,817` tiles). 245- **Bit 1 (`0x02`)**: exact bijection (`27,644 / 27,644`) with special links (`+0xA8/+0xB0` non-null, `u32@0xD4/0xD8 > 0`; `8,817` tiles).
@@ -254,7 +257,7 @@ world_min_x = (sector_x - 256) * 128.0 # -12,288 .. +4,992 m (max +5,120 m)
254world_min_y = (sector_y - 256) * 128.0 # -9,856 .. +13,056 m (max +13,184 m) 257world_min_y = (sector_y - 256) * 128.0 # -9,856 .. +13,056 m (max +13,184 m)
255``` 258```
256 259
257The `24,480` unique static sector IDs form a complete, gap-free `136 × 180` rectangle (`Z ∈ [-78.55, +403.84]` m). 260The `24,480` unique static sector IDs form a complete, gap-free `136 × 180` rectangle (`Z ∈ [-78.55, +403.84]` m).
258 261
259### Adjacent-polygon edges (`+0x88`, `493,024,188` records) and special links (`+0xA8`/`+0xB0`, `26,679,246` records) 262### Adjacent-polygon edges (`+0x88`, `493,024,188` records) and special links (`+0xA8`/`+0xB0`, `26,679,246` records)
260 263
@@ -284,11 +287,16 @@ The `24,480` unique static sector IDs form a complete, gap-free `136 × 180`
284 `poly1 < u32@0xC4` (`26,535,333 / 26,535,333`). 287 `poly1 < u32@0xC4` (`26,535,333 / 26,535,333`).
285 - `+0x18..+0x1B` (`u16 flags0, u16 flags1`): link attribute and traversal type words (`flags1` top values: `0x0050` 288 - `+0x18..+0x1B` (`u16 flags0, u16 flags1`): link attribute and traversal type words (`flags1` top values: `0x0050`
286 on `11,492,614`, `0x0040` on `9,705,698`, `0x0030` on `4,281,168`, `0x0060` on `425,369`). 289 on `11,492,614`, `0x0040` on `9,705,698`, `0x0030` on `4,281,168`, `0x0060` on `425,369`).
287 - `+0x1C..+0x1D` (`u16 heading`): 8-bit quantized heading angle (`0..254`, `< 256` on `26,679,246 / 26,679,246`). 290 - `+0x1C..+0x1D` (`u16 heading`): 8-bit quantized heading angle (`< 256` on `26,679,246 / 26,679,246`; `u8@0x1C`
291 in `0..254`, `u8@0x1D == 0`).
288 - `+0x1E..+0x1F` (`u16 pad`): zero padding (`0` on `26,679,246 / 26,679,246`). 292 - `+0x1E..+0x1F` (`u16 pad`): zero padding (`0` on `26,679,246 / 26,679,246`).
289 - Across all `26,903,247 / 26,903,247` entries of `+0xB0`, every entry `li = u16@(b0 + 2*k)` in polygon `pi`'s slice 293 - Across all `26,903,247 / 26,903,247` entries of `+0xB0`, every entry `li = u16@(b0 + 2*k)` in polygon `pi`'s slice
290 `[link_start .. link_start + link_count)` indexes a 32-byte link at `+0xA8` satisfying 294 `[link_start .. link_start + link_count)` indexes a 32-byte link at `+0xA8` satisfying
291 `(poly0 == pi or poly1 == pi) and (sector0 == u32@0xC8 or sector1 == u32@0xC8)` (`0` failures). 295 `(poly0 == pi or poly1 == pi) and (sector0 == u32@0xC8 or sector1 == u32@0xC8)`, and every referenced link is
296 listed by all of its local-tile endpoints (`poly0` when `sector0 == u32@0xC8`, and `poly1` when
297 `sector1 == u32@0xC8`; on cross-tile links where the foreign endpoint polygon index is `< u32@0xC4`, the offline
298 builder also indexed the link under that polygon index because it matched `poly0/poly1 == pi` without filtering
299 by `sector0/sector1 == u32@0xC8`).
292 300
293### Split arrays and quadtree layout 301### Split arrays and quadtree layout
294 302
@@ -315,6 +323,53 @@ shares the identical 20-byte prefix `+0x00..+0x13` (`3,123,445 / 3,123,445`):
315| `+0x16` | 64 | `i16[32]` | Up to 16 relative 2D `(dx, dy)` footprint vertices in signed 16-bit fixed point around `(x, y)`; trailing unused slots `+0x16 + 4*N .. +0x55` are zero on `6,246,890 / 6,246,890` | 323| `+0x16` | 64 | `i16[32]` | Up to 16 relative 2D `(dx, dy)` footprint vertices in signed 16-bit fixed point around `(x, y)`; trailing unused slots `+0x16 + 4*N .. +0x55` are zero on `6,246,890 / 6,246,890` |
316| `+0x56` / `+0x58` | 4 | `i16`, `u16` | Vertical/extent words (`u16@0x56` range `0..65,535`, high bit set on `1,846,885`; `u16@0x58` range `3..65,534`, high bit set on `13,629`) | 324| `+0x56` / `+0x58` | 4 | `i16`, `u16` | Vertical/extent words (`u16@0x56` range `0..65,535`, high bit set on `1,846,885`; `u16@0x58` range `3..65,534`, high bit set on `13,629`) |
317| `+0x5A` | 6 | `u8[6]` | Trailing zero padding (`0` on `6,246,890 / 6,246,890`) | 325| `+0x5A` | 6 | `u8[6]` | Trailing zero padding (`0` on `6,246,890 / 6,246,890`) |
326### Polygon flags under the lane graph
327
328`tools/navmesh_nodes.py` puts the lane graph of `levels.rpf` ([world_lights_paths.md](world_lights_paths.md)) on
329the navmesh: for each node it takes the polygon of the node's tile that contains the node in plan view and is
330closest in height, and counts that polygon's flag bits. A polygon's height is the mean of its vertex heights, not
331the surface height under the node, so on a slope the two differ (the 3 m cutoff below absorbs that). For comparison
332it sums the plan area of the polygons that carry each bit over the same tiles; surfaces above one another, such as a
333bridge over a road or the stacked tiles that share one sector id, each add their own area. A bit that most road
334nodes stand on while it covers little of the area marks where the roads are.
335
336A vertex is `tile minimum + u16 / 65535 * tile extent` (the minimum is the quadtree root's, the extent `+0x60`).
337The node heights confirm it: of the 63,806 nodes with a finite position (63,808 read),
33863,802 lie over a polygon and 63,793 have one within 3 m above or below; the height
339difference is 0.032 m at the median, 0.095 m at the 90th percentile and 0.28 m at the 99th.
340
341Measured over the 6,970 static tiles that hold a node (77,880,896 polygons with three
342or more vertices, 120.2 km2 of plan area; 0 tiles unreadable). "Nodes" is how many of the 63,793
343nodes stand on a polygon with the bit; "area" is the share of the plan area such polygons cover:
344
345| Word | Bit | Nodes | Polygons | Area | Reading |
346|---|---|---:|---:|---:|---|
347| `+0x18` | 13 (`0x2000`) | 57,559 (90.2%) | 3,357,132 | 12.0% | under nine in ten nodes; SixNG's "road surface" |
348| `+0x18` | 8 (`0x100`) | 58,528 (91.7%) | 251,917 | 2.6% | under nine in ten nodes, on a fifth of bit 13's area; not named |
349| `+0x18` | 12 (`0x1000`) | 787 (1.2%) | 18,746,182 | 33.6% | not road: a third of the area, almost no node |
350| `+0x18` | 19 (`0x80000`) | 3,980 (6.2%) | 3,263,052 | 23.6% | the water candidate above |
351| `+0x18` | 27 (`0x8000000`) | 5,526 (8.7%) | 2,489,161 | 3.2% | 6stars's label; under few nodes |
352| `+0x28` | 17 (`0x20000`) | 21,246 (33.3%) | 1,083,157 | 4.7% | 6stars's label; seven times its area share, but only a third of the nodes |
353
354No other bit of either word has more than 5% of the nodes, except `+0x28` bit 18 (4,520 nodes, 7.1%, on 1.6% of
355the area).
356
357Bits 8 and 13 are mostly set together. The tool counts the four combinations:
358
359| `+0x18` bits 8 and 13 | Nodes | Polygons | Area |
360|---|---:|---:|---:|
361| both | 57,181 (89.6%) | 236,753 | 2.5% |
362| bit 8 only | 1,347 (2.1%) | 15,164 | 0.1% |
363| bit 13 only | 378 (0.6%) | 3,120,379 | 9.5% |
364| neither | 4,887 (7.7%) | 74,508,600 | 87.8% |
365
366So nine in ten lane nodes stand on polygons that carry both bits, which cover 2.5% of the area. Bit 13
367alone covers almost four times that area (9.5%) with almost no node on it, and bit 8 alone is rare.
368[SixNG](https://github.com/holdmysocks/SixNG) labels bit 13 "road surface" after a visual check
369(`crates/sixng-core/src/navmesh.rs`, commit `0619601`, GPL-3.0; see [related_projects.md](related_projects.md)).
370The count is consistent with that if road surface is wider than the driven lanes. It does not settle which bit,
371or which combination, means road surface. That stays open, as do bit 8's meaning and the other bits. The vertex
372formula above is stated in the same file and is confirmed by the heights.
318 373
319## Band-3 `grid` resources (`27,482` resources) 374## Band-3 `grid` resources (`27,482` resources)
320 375
@@ -323,16 +378,16 @@ The final 433 MiB of `navmeshes.rpf` holds `27,482` `pgBase` resources (`+6` con
323 378
324| Offset | Size | Type | Verified meaning (`27,482 / 27,482`) | 379| Offset | Size | Type | Verified meaning (`27,482 / 27,482`) |
325|---:|---:|---|---| 380|---:|---:|---|---|
326| `+0x00` / `+0x08` | 16 | `u64`, `ptr64` | `0`, pointer to 32-byte block map (`bm[1] == stream_count`: `27,476` × 1, `6` × 2) | 381| `+0x00` / `+0x08` | 16 | `u64`, `ptr64` | `0`, pointer to 32-byte block map (`bm[1] == stream_count`: `27,476` × 1, `6` × 2) |
327| `+0x10` / `+0x14` | 8 | `u32`, `u32` | Power-of-2 group count (`8..2048`), active entry count `N` (`85..14,903`; sum `53,835,068`) | 382| `+0x10` / `+0x14` | 8 | `u32`, `u32` | Power-of-2 group count (`8..2048`), active entry count `N` (`85..14,903`; sum `53,835,068`) |
328| `+0x18` / `+0x20` | 16 | `ptr64`, `ptr64` | Hash-table pointer (always `+0x60`, `groups × 272` B), payload pointer (`u32[N]`) | 383| `+0x18` / `+0x20` | 16 | `ptr64`, `ptr64` | Hash-table pointer (always `+0x60`, `groups × 272` B), payload pointer (`u32[N]`) |
329| `+0x28` / `+0x34` | 16 | `u32[3]`, `u32` | Cubic volume extent (`128³ / 256³ / 512³ / 1024³ / 4096³` m), 512 × 512 sector ID | 384| `+0x28` / `+0x34` | 16 | `u32[3]`, `u32` | Cubic volume extent (`128³ / 256³ / 512³ / 1024³ / 4096³` m), 512 × 512 sector ID |
330| `+0x40` | 12 | `f32[3]` | World origin `(ox, oy, oz)` (`ox, oy` match sector ID on `27,482 / 27,482`; `oz ∈ {-2048..+256}`) | 385| `+0x40` | 12 | `f32[3]` | World origin `(ox, oy, oz)` (`ox, oy` match sector ID on `27,482 / 27,482`; `oz ∈ {-2048..+256}`) |
331| `+0x50` | 4 | `u32` | Mirror of entry count (`u32@0x50 == u32@0x14` on `27,482 / 27,482`) | 386| `+0x50` | 4 | `u32` | Mirror of entry count (`u32@0x50 == u32@0x14` on `27,482 / 27,482`) |
332 387
333Reserved slots `+0x38..+0x3f`, `+0x4c..+0x4f`, and `+0x54..+0x5f` are zero on `27,482 / 27,482`. Each 272-byte group at 388Reserved slots `+0x38..+0x3f`, `+0x4c..+0x4f`, and `+0x54..+0x5f` are zero on `27,482 / 27,482`. Each 272-byte group at
334`+0x60` is a 16-way SwissTable block (`16` control bytes where `0x80` = empty and `< 0x80` = occupied tag, followed by 389`+0x60` is a 16-way SwissTable block (`16` control bytes where `0x80` = empty and `< 0x80` = occupied tag, followed by
335`16 × {u64 key, u64 value}`). Across all `27,482 / 27,482` resources, occupied slots equal `N` and their `value` fields 390`16 × {u64 key, u64 value}`). Across all `27,482 / 27,482` resources, occupied slots equal `N` and their `value` fields
336form an exact bijection onto `[0 .. N - 1]`: `value` indexes the `u32[N]` payload. 391form an exact bijection onto `[0 .. N - 1]`: `value` indexes the `u32[N]` payload.
337 392
338**Keys (ASSET-287).** The `u64` keys are sentinel-bit linear octree keys over the cubic volume: `1` is the root and a 393**Keys (ASSET-287).** The `u64` keys are sentinel-bit linear octree keys over the cubic volume: `1` is the root and a
@@ -361,8 +416,10 @@ counts.
3613. **`0DRP` unnamed structs and fields.** Several `0x7a` struct/member hashes (including `0x4712787b`, `0x57ad0b12`, 4163. **`0DRP` unnamed structs and fields.** Several `0x7a` struct/member hashes (including `0x4712787b`, `0x57ad0b12`,
362 `0xdd53676a`, `0xf2dd6348`, `0xde5f1345`, and 3 of the 4 singletons) are not yet matched to engine names. 417 `0xdd53676a`, `0xf2dd6348`, `0xde5f1345`, and 3 of the 4 singletons) are not yet matched to engine names.
3634. **Per-record bitfields inside `0x00010015` tiles.** `u32@0x10` bit 3's secondary trigger on `289` tiles and bit 6's 4184. **Per-record bitfields inside `0x00010015` tiles.** `u32@0x10` bit 3's secondary trigger on `289` tiles and bit 6's
364 name, `u32@0xE8` build-stamp encoding, polygon/adjacent-edge/special-link flag bitfields, and the exact C++ class name 419 name, `u32@0xE8` build-stamp encoding, the polygon flag bits (`+0x18` bits 8 and 13 lie under nine in ten lane
365 and `+0x56/+0x58` vertical unit of the paired 96-byte `+0xB8` footprint records remain open. 420 nodes; which of them is road surface is open; see above), the adjacent-edge and special-link flag bitfields, and
421 the exact C++ class name and `+0x56/+0x58` vertical unit of the paired 96-byte `+0xB8` footprint records remain
422 open.
3665. **Band-3 `grid` subsystem and EOF `PSIN` v79.** The Band-3 subsystem identity, the x/y order of the octree key's 4235. **Band-3 `grid` subsystem and EOF `PSIN` v79.** The Band-3 subsystem identity, the x/y order of the octree key's
367 octant bits 0/1, the cube's placement against its sector and the meaning of the `u32[N]` leaf fields are open 424 octant bits 0/1, the cube's placement against its sector and the meaning of the `u32[N]` leaf fields are open
368 (the key encoding and the inner-node word are decoded above), as is why the final `PSIN` (version `79`) 425 (the key encoding and the inner-node word are decoded above), as is why the final `PSIN` (version `79`)
@@ -370,8 +427,9 @@ counts.
370 427
371## Vehicle navmesh settings (`CVehiclePoints`, `common.rpf`) 428## Vehicle navmesh settings (`CVehiclePoints`, `common.rpf`)
372 429
373Navmeshes on vehicles that peds walk around on are configured outside this archive, by 32 `CVehiclePoints` XML 430The settings for navmeshes on vehicles that peds walk around on are outside this archive, in 32 `CVehiclePoints`
374documents in `common.rpf` (see [gamedata.md](gamedata.md)). One document per vehicle; counts only, no names. 431XML documents in `common.rpf` (see [gamedata.md](gamedata.md)); the meshes themselves are stored here (below).
432One document per vehicle; counts only, no names.
375 433
376| Field | Documents | Values | 434| Field | Documents | Values |
377|---|---:|---| 435|---|---:|---|
@@ -396,18 +454,162 @@ rated vehicles. Of the mod part names, only the 5 `RoofModName` values that are
39649 chassis, 32 utility, 35 exterior-propset and 4 interior names match no archive entry, so they are probably 45449 chassis, 32 utility, 35 exterior-propset and 4 interior names match no archive entry, so they are probably
397fragment-part or kit names rather than models. 455fragment-part or kit names rather than models.
398 456
399Not measured here (hypothesis): whether the vehicle navmeshes are generated at runtime from these parameters or 457### Stored vehicle navmeshes (ASSET-332)
400stored elsewhere, and which vehicles the 31 are (wagons, boats and trains would fit the field set). 458
459The vehicle navmeshes are **stored**, not left to a runtime generator: the 161 local-space non-grid meshes in this
460archive (`flags = 7`, the non-grid partition above) were built on cell grids, and 9 of them on the one cell size
461only these documents set. Measured over all 161 on 1.0.2.1 with `tools/navmesh_cell_fit.py`:
462
463- **Cell grid.** A mesh's `u16` vertices are dequantised over its `+0x60` extents (step `extent / 65535`, at most
464 0.0011 m on these meshes) and an x or y coordinate counts as on a grid of cell size `c` when it is within 1.5 steps
465 of a multiple of `c`. Every mesh fits one of the three nonzero `fNavOverrideRecastCellSize` values: at
466 least 90.9% of its x and y coordinates sit on that grid (20,100 vertices in all). The quantisation step alone
467 cannot put them there: over all 65,536 levels of a mesh's own step, at most 5.1% land on its grid (mean 1.0% at
468 0.0625, 1.7% at 0.03125, 0.7% at 0.0325). Taking the coarsest of the three that fits:
469
470 | Cell size | Meshes | Distinct x × y extents | Documents with that value |
471 |---:|---:|---:|---:|
472 | 0.0625 | 87 | 42 | 1 |
473 | 0.03125 | 65 | 20 | 23 |
474 | 0.0325 | 9 | 1 | 3 |
475
476 No mesh fits both 0.03125 and 0.0325. Of six other values tried (0.1, 0.125, 0.15, 0.2, 0.25, 0.5), only 0.125
477 fits any mesh: 2 at the 90.9% cut (4 at 90%), all among the 87 at 0.0625, whose coordinates a coarser grid can
478 also hold. Every mesh's x and y extents are a whole number of its cells.
479- **The static tiles are on a grid too.** Every 200th static 128 m tile (137 tiles) fits 0.0625 and 0.03125 (chance
480 baselines 9.4% and 18.8% at their step of 128/65535 m), and none fits 0.0325. So the world navmesh is built on a
481 0.0625 grid as well, and a fit at 0.0625 or 0.03125 alone does not show that a mesh used a vehicle override.
482- **The 0.0325 meshes.** 0.0325 is the one value that is not a power of two and that no static tile fits, so it
483 is the test that ties meshes to these documents. All 9
484 meshes on it share one footprint, 1.755 × 5.1675 m, which is exactly 54 × 159 cells of 0.0325. They are flat
485 (z extent 0) and have 47 vertices (6) or 55 (3). The 3 documents with that value name 3 different models.
486- **No name hash.** None of the 161 meshes (nor the whole-world coarse mesh) contains the `joaat` of any of
487 the 31 model names, as written, lower-cased, or with `.yft` appended, at any byte offset. So a mesh is not tied
488 to its model by a stored name hash. Where the link is is not measured; the encrypted table of contents is one
489 candidate (see [rpf.md](rpf.md)).
490
491Not measured (hypothesis): which mesh belongs to which model, and so which vehicles they are. 161 meshes for 31
492models means either several meshes per model (states or variants) or meshes for vehicles without a
493`CVehiclePoints` document. The 87 meshes at 0.0625 against 1 document with that value, and the static tiles on the
494same grid, would fit 0.0625 being the default cell size when the override is 0 or absent (5 documents: 4 with 0,
4951 without the field).
496**Stored vs runtime-generated and vehicle classes (ASSET-332).** Cross-checking the 31 distinct `CVehiclePoints`
497models (and 55 `ModDefs/Item` part names) against `navmeshes.rpf`, `common.rpf` metadata, and other package
498archives resolves the earlier hypothesis: **vehicle navmeshes are pre-baked and stored in `navmeshes.rpf` Band 2**,
499so the port does not need a runtime Recast navmesh generator for these vehicles. The `CVehiclePoints` Recast fields
500are authoring/build-time inputs to that partition:
501
502- **Stored in `navmeshes.rpf` Band 2 (`flags = 7` dynamic partition):** the non-grid `PSIN` container at
503 `0x1749fe000` (`37,120` B, version `256`, `493` `LSNS` records) heading the `161` local-space dynamic navmeshes
504 (`0x174a02010..0x174b91010`) contains the lowercase `joaat` hash of **25 of the 31** `CVehiclePoints` model names
505 (100% of the 25 present in the `.yft` catalog) and **20 of the 55** `ModDefs/Item` part names. The remaining 6
506 models appear in neither the `.yft` catalog, `CVehiclePerformanceMaps`, `CTrainConfigs`, nor `PSIN 0x1749fe000`.
507- **Absent from other archives:** scanning `packs.rpf`, `data.rpf`, `common.rpf`, and `story000.rpf` finds **0**
508 `0x00010015` navmesh streams outside `navmeshes.rpf`.
509- **Dynamic partition dimensions (`161` `flags = 7` meshes):** extents `dx` `1.31..63.0` m, `dy` `2.94..69.38` m,
510 `dz` `0.0..13.2` m (`max(dx, dy)`: `81` `<= 10` m, `67` `10..25` m, `11` `25..60` m, `2` `> 60` m); `4..1,058`
511 vertices, `1..631` polygons, `2..1,694` special links, and `0` `+0xB8` volume records on all `161`.
512- **Vehicle class breakdown of the 31 `CVehiclePoints` models** (via `CVehiclePerformanceMaps` and `CTrainConfigs`
513 in `common.rpf`):
514
515| Class (`common.rpf` metadata) | `CVehiclePoints` models | Matched in `PSIN 0x1749fe000` | Broader `common.rpf` set in `PSIN 0x1749fe000` |
516|---|---:|---:|---:|
517| Watercraft (`CVehiclePerformanceMaps` Doc 1, `buoyancyOffsetZ != 0`) | 20 | 20 / 20 | 31 / 34 |
518| Ground/land (`CVehiclePerformanceMaps` Doc 0, `takeOffSpeed == 0`) | 4 | 4 / 4 | 12 / 251 |
519| Air (`CVehiclePerformanceMaps` Doc 0, `takeOffSpeed > 0`) | 0 | 0 | — |
520| Train (`CTrainConfigs`) | 1 | 1 / 1 | — |
521| Absent from `CVehiclePerformanceMaps`, `CTrainConfigs`, and `.yft` catalog | 6 | 0 / 6 | — |
522| **Total** | **31** | **25 / 31** | |
401 523
402## Tools 524## Tools
403 525
526- `tools/navmesh_cell_fit.py` (stdlib-only) measures the cell grid of the local-space meshes and, with `--common`,
527 counts the `CVehiclePoints` cell sizes and searches the meshes for the models' name hashes; `--static-every N`
528 adds a static-tile control. It prints aggregates only (ASSET-332).
404- `tools/navmesh_index.py` (stdlib-only) performs the quick `0DRP` header inventory (`offset`, sizes, version, `+0x20`, 529- `tools/navmesh_index.py` (stdlib-only) performs the quick `0DRP` header inventory (`offset`, sizes, version, `+0x20`,
405 raw `+0x60`/`+0x68`). 530 raw `+0x60`/`+0x68`). For a carve directory, `--pattern` selects paths recursively. Each matching pathname
531 counts once, including when the pattern itself contains `**`.
406- `tools/navmesh_decode.py` (stdlib-only) decodes all four resource classes (`0DRP`, `0x00010015`, `grid`, `PSIN`), 532- `tools/navmesh_decode.py` (stdlib-only) decodes all four resource classes (`0DRP`, `0x00010015`, `grid`, `PSIN`),
407 joins continuations (including tiny `< 64`-byte continuations), validates structural invariants, and writes aggregate 533 joins continuations (including tiny `< 64`-byte continuations), validates structural invariants, and writes aggregate
408 JSON and optional numeric CSV metadata. It never writes payload bytes and never touches the TOC. 534 JSON and optional numeric CSV metadata. It never writes payload bytes and never touches the TOC.
409- `tools/navmesh_links.py` (stdlib-only) decodes and verifies the 12-byte `+0x88` adjacent-polygon edges, the polygon 535- `tools/navmesh_links.py` (stdlib-only) decodes and verifies the 12-byte `+0x88` adjacent-polygon edges, the polygon
410 `+0x20` special-link prefix-sum chain, and the 32-byte `+0xA8` special links and `+0xB0` index table. 536 `+0x20` special-link prefix-sum chain, and the 32-byte `+0xA8` special links and `+0xB0` index table.
537 Pass `--reciprocity` to include a `reciprocity` object. `tiles_counted` covers tiles with verified pool bounds
538 and contiguous polygon spans. Within each tile, `excess_directed` sums the positive differences between the
539 counts of A to B and B to A for each ordered polygon pair. Self edges contribute zero excess. The report counts
540 valid same-tile records, all-ones open targets and invalid targets separately. This measures polygon references
541 without testing geometric edge alignment.
542 Pass `--endpoint-agreement` to compare two ways to associate slot *j* of the adjacency span with its
543 polygon boundary. Under `outgoing` it runs from vertex *j* to the next vertex. Under `incoming` it runs
544 from the previous vertex to *j*. Both wrap within the polygon and compare all three stored u16 coordinates
545 at `+0x70` through the `+0x80` indices. The unit is a directed slot. With one occurrence on each polygon,
546 matching endpoints count as `reversed`, `same_direction`, or `degenerate` (identical endpoints).
547 If a return exists and either polygon repeats the same unordered endpoints for this neighbor, all affected
548 slots count as `repeated`. A slot with no return to its source at those exact coordinates counts as
549 `no_exact_return`. Open, invalid and self targets have separate totals.
550
551 Across all 27,644 Xbox 1.0.2.1 tiles, each convention accounts for 458,728,869 directed same-tile slots.
552 The endpoint agreement supports slot *j* describing the outgoing boundary edge. A unique return can run
553 in either direction. Another 34,295,319 slots were open. None had invalid or self targets.
554
555 | Boundary tested | Reversed | Same direction | Degenerate | Repeated | No exact return |
556 |---|---:|---:|---:|---:|---:|
557 | Outgoing | 449,013,586 | 9,676,624 | 42 | 94 | 38,523 |
558 | Incoming | 702 | 102,408 | 2 | 3 | 458,625,754 |
559
560 Pass `--relative-winding` to subdivide uniquely matched outgoing slots by the winding of the two
561 polygon rings. The first two words of each vertex at `+0x70` are its tile-space X and Y coordinates
562 (see [the lane-graph height check](#polygon-flags-under-the-lane-graph)). Translation and positive
563 per-axis scaling by the tile extents at `+0x60` preserve the sign of the shoelace area, so the test uses
564 exact integer arithmetic. Dynamic meshes use their local XY plane. Endpoint matching still uses XYZ.
565 Either ring makes the pair ambiguous if it has fewer than three projected vertices, zero signed area,
566 a repeated point, or a boundary that crosses, touches itself or doubles back. Nonpositive or nonfinite
567 horizontal extents also make the pair ambiguous.
568
569 | Unique outgoing match (directed slots) | Same winding | Opposite winding | Ambiguous |
570 |---|---:|---:|---:|
571 | Same direction | 61,128 | 592 | 9,614,904 |
572 | Reversed | 448,891,156 | 11,896 | 110,534 |
573
574 Across the whole archive, only 592 same-direction slots have demonstrably opposite XY winding. Of the
575 61,720 same-direction slots with classifiable rings, 61,128 have the same winding. The remaining
576 9,614,904 slots admit no conclusion from this projection. Reversed slots overwhelmingly join rings
577 of the same winding.
578
579 Pass `--coplanar-winding` to examine the 9,614,904 XY-ambiguous same-direction directed slots.
580 The three unsigned words per vertex at `+0x70` give tile-space XYZ. Positive per-axis scaling and
581 translation preserve coplanarity and the relative orientation of rings in a common plane. A zero
582 extent collapses that axis. The test requires finite, nonnegative extents. It finds a plane from
583 three noncollinear ring points and verifies all remaining points against it with integer arithmetic.
584 Dropping an axis with a nonzero normal component maps that plane one-to-one onto a coordinate plane,
585 where the existing simple-ring and signed-area tests apply. Two parallel planes containing the same
586 edge coincide, so both rings use the same projection. For different planes the relative sign can
587 depend on the viewing direction.
588
589 A private census over all 27,644 tiles classified each ring separately. For planar rings with
590 distinct vertices, the segment checks stop at the first boundary defect in vertex order. When the
591 two rings have different conditions, the first listed below takes precedence. Each reciprocal
592 pair contributes two directed slots.
593
594 | First applicable 3D condition | Directed slots |
595 |---|---:|
596 | Fewer than three vertices | 6,375,984 |
597 | Repeated XYZ vertex in a ring | 84 |
598 | All vertices collinear | 1,100,732 |
599 | Adjacent segments double back in a planar ring | 89,984 |
600 | Nonadjacent segments intersect or touch in a planar ring | 738,318 |
601 | Nonplanar ring | 596,656 |
602 | Both rings simple and planar | 713,146 |
603
604 Among the 713,146 slots with two simple planar rings, 713,102 join different planes. The coplanar
605 group contains 20 slots of equal winding, 20 of opposite winding and 4 with coincident boundaries.
606 The coincidence test ignores extra vertices along straight sides. The remaining 8,901,758 slots
607 have at least one undefined ring. These counts describe polygon geometry only.
608
609- `tools/navmesh_nodes.py` (stdlib-only) counts the polygon flag bits under the lane-graph nodes
610 ([above](#polygon-flags-under-the-lane-graph)). It reads `navmeshes.rpf` and `levels.rpf` and writes counts only.
611 An `--out` this run cannot write (a folder that cannot be created or written, a read-only existing summary, or
612 one of the two archives) is one `ERROR` line and exit 2 before either archive is read.
411 613
412```powershell 614```powershell
413python -I tools/navmesh_decode.py <package>\navmeshes.rpf --out <temp>/navmesh-decode.json --csv <temp>/navmesh-decode.csv 615python -I tools/navmesh_decode.py <package>\navmeshes.rpf --out <temp>/navmesh-decode.json --csv <temp>/navmesh-decode.csv
@@ -416,6 +618,9 @@ python -I tools/navmesh_decode.py <carve-dir> --out <temp>/carved-decode.json
416python -I tools/navmesh_links.py <package>\navmeshes.rpf --out <temp>/navmesh-links.json 618python -I tools/navmesh_links.py <package>\navmeshes.rpf --out <temp>/navmesh-links.json
417python -I -W error::ResourceWarning tests/test_navmesh_decode.py -v 619python -I -W error::ResourceWarning tests/test_navmesh_decode.py -v
418python -I tests/test_navmesh_links.py -v 620python -I tests/test_navmesh_links.py -v
621python -I tools/navmesh_nodes.py <package>\navmeshes.rpf <package>\levels.rpf --jobs 8 --out <temp>/navmesh-nodes.json
622python -I -W error::ResourceWarning tests/test_navmesh_decode.py -v
623python -I tests/test_navmesh_nodes.py
419python -I tests/test_navmesh_index.py 624python -I tests/test_navmesh_index.py
420``` 625```
421 626
@@ -432,3 +637,15 @@ failures**, in 236 s. Both test suites build synthetic archives in memory/tempdi
432The package is read-only. Do not commit, upload or share the archive, any carved page, a key, an extracted name, 637The package is read-only. Do not commit, upload or share the archive, any carved page, a key, an extracted name,
433or a report that quotes payload bytes. Only aggregate counts, offsets, verified layouts and four-byte magics belong in 638or a report that quotes payload bytes. Only aggregate counts, offsets, verified layouts and four-byte magics belong in
434this repository. 639this repository.
640
641## Inspect one tile locally
642
643Run `python -I tools/navmesh_tile_obj.py navmeshes.rpf --tile 0 --out <private-folder>/tile.obj`
644with a zero-based tile ordinal. The reader walks complete navmesh resources in archive order and stops at the
645selection. Dynamic tiles count toward the ordinal and lack the static world-space placement required for export.
646
647Each `polygon_N` group corresponds to record N in the selected tile. A single slot becomes a point, two slots
648become a line, and three or more become a polyline closed back to the first slot. Empty records keep their group.
649Repeated or collinear slots remain in order, including zero-length edges. OBJ vertex numbers are local to this
650export. The boundary drawing makes no claim about surface triangulation, connections or navigability.
651Keep generated OBJ files in your private work folder.
diff --git a/docs/page_directory.md b/docs/page_directory.md
index 5e9334609..d28c78d8e 100644
--- a/docs/page_directory.md
+++ b/docs/page_directory.md
@@ -95,6 +95,28 @@ What the samples did not show:
95The per-archive tables further down (common sizes, common hashes, payload classes) are still the 64 MiB and 256 MiB 95The per-archive tables further down (common sizes, common hashes, payload classes) are still the 64 MiB and 256 MiB
96slices where they say navmesh or animation; the `data.rpf` columns were complete from the start. 96slices where they say navmesh or animation; the `data.rpf` columns were complete from the start.
97 97
98### `levels.rpf` in full
99
100`levels.rpf` was counted whole with a temp-only streaming runner that calls the same `scan_rpf`, `parse_page` and
101`resource_of` functions and accumulates the summary one page at a time (the stock tool keeps every page; this
102archive reached 17.4 GB RSS and had to be stopped). The runner reproduces the stock `data.rpf` row exactly
103(28,509 / 15,768 / 60,880 / 158), so the counts are the same fields:
104
105| | `levels.rpf` |
106|---|---:|
107| zlib streams | 1,116,073 |
108| `0DRP` pages, all version 122, all complete | 188,449 |
109| `q38` records | 465,611 |
110| pages with one continuation stream (none has more) | 3,281 |
111| `+0x20` | 1-44 |
112| first `q38` payload at +0x60 | **52,776 of 188,449** |
113
114The page total agrees with the existing levels census (188,449). The +0x60 rule is the one place where this
115archive differs from the other three: only 52,776 of its pages put the first `q38` payload at +0x60. The rest are
116counted and parsed, but this check does not establish the +0x60 key claim for them; their first target or table
117sits elsewhere. This was a count run (17.7 min), so it does not fill the payload-class, span or q28-declared
118tables below; those keep their labelled sample scopes.
119
98## Fixed header (0x60 bytes) 120## Fixed header (0x60 bytes)
99 121
100The core sample is 15,768 `data.rpf` pages plus 1,132 navmesh and 12,398 animation pages = **29,298 pages**. 122The core sample is 15,768 `data.rpf` pages plus 1,132 navmesh and 12,398 animation pages = **29,298 pages**.
@@ -110,7 +132,7 @@ sample; the meaning column separates decoded fields from unresolved ones.
110| +0x10 | 4 | `30 44 52 50` | `0DRP` | 132| +0x10 | 4 | `30 44 52 50` | `0DRP` |
111| +0x14 | 4 | 122 in all 29,298 | version | 133| +0x14 | 4 | 122 in all 29,298 | version |
112| +0x18 | 8 | zero in all pages | unused | 134| +0x18 | 8 | zero in all pages | unused |
113| +0x20 | 4 | 1-89 in `data.rpf`, 2-3 in navmesh, 1-38 in anim (whole archives: 1-6 and 1-41) | presumed page count; **unit unresolved** | 135| +0x20 | 4 | 1-89 in `data.rpf`, 2-3 in navmesh, 1-38 in anim (whole archives: 1-6, 1-41; 1-44 in `levels.rpf`) | presumed page count; **unit unresolved** |
114| +0x24 | 4 | zero in all pages | high half of the +0x20 qword | 136| +0x24 | 4 | zero in all pages | high half of the +0x20 qword |
115| +0x28 | 8 | `0x5000xxxx`, 8-byte aligned | pointer to the `q28` table | 137| +0x28 | 8 | `0x5000xxxx`, 8-byte aligned | pointer to the `q28` table |
116| +0x30 | 8 | zero or `0x5000xxxx` | pointer to the `q30` table | 138| +0x30 | 8 | zero or `0x5000xxxx` | pointer to the `q30` table |
@@ -374,12 +396,12 @@ boundaries by itself.
374 396
375This is the cross-check the navmesh report asked for: the `0x50000000` base is shared by directory pages and typed 397This is the cross-check the navmesh report asked for: the `0x50000000` base is shared by directory pages and typed
376data pages, but only the directory page carries the offset/size table. The typed prefix is not a `q38` payload 398data pages, but only the directory page carries the offset/size table. The typed prefix is not a `q38` payload
377magic; 0 of 60,880 `data.rpf` records, 0 of 6,645 navmesh records and 0 of 269,320 animation records started with 399magic; 0 of 60,880 `data.rpf` records and 0 of the 6,645 navmesh and 269,320 animation records in their sampled
378`0x00010015` at +0x14. 400windows started with `0x00010015` at +0x14.
379 401
380## Distribution of the +0x20 count 402## Distribution of the +0x20 count
381 403
382| Value | `data.rpf` | `navmeshes.rpf` | `anim.rpf` | 404| Value | `data.rpf` | `navmeshes.rpf` (64 MiB) | `anim.rpf` (256 MiB) |
383|---:|---:|---:|---:| 405|---:|---:|---:|---:|
384| 1 | 1,247 | 0 | 480 | 406| 1 | 1,247 | 0 | 480 |
385| 2 | 14,485 | 147 | 5,240 | 407| 2 | 14,485 | 147 | 5,240 |
@@ -438,8 +460,8 @@ path or resource type is present in a `0DRP` page.
438 **open**. 460 **open**.
4396. **Full-corpus runs.** The tool is bounded by `--limit`; run it on a whole archive before quoting a count for 4616. **Full-corpus runs.** The tool is bounded by `--limit`; run it on a whole archive before quoting a count for
440 that archive. `data.rpf`, `navmeshes.rpf` and `anim.rpf` are read whole in *Whole-archive pass*; `levels.rpf` 462 that archive. `data.rpf`, `navmeshes.rpf` and `anim.rpf` are read whole in *Whole-archive pass*; `levels.rpf`
441 is still the 64 MiB sample here (its full pass is `docs/world_census.md`), and the common-size, common-hash and 463 is read whole in *`levels.rpf` in full*, and its map contents are in `docs/world_census.md`. The common-size,
442 payload-class tables are still slices for navmesh and animation. 464 common-hash and payload-class tables are still slices for navmesh and animation.
4437. **`q28` tables past the `q38` boundary.** 1,581 pages declare a `q28` table that ends beyond the streams the 4657. **`q28` tables past the `q38` boundary.** 1,581 pages declare a `q28` table that ends beyond the streams the
444 `q38` records need. Reading the following stream for it would settle whether a resource can be longer than its 466 `q38` records need. Reading the following stream for it would settle whether a resource can be longer than its
445 `q38` records say. 467 `q38` records say.
@@ -479,6 +501,7 @@ Validation on the package used here:
479| `anim.rpf` first 256 MiB | 24,232 | 12,398 | 269,320 | 12,398 | 7,865 | 25 s | 501| `anim.rpf` first 256 MiB | 24,232 | 12,398 | 269,320 | 12,398 | 7,865 | 25 s |
480| `navmeshes.rpf` full | 90,295 | 9,603 | 54,898 | 9,603 | 2,170 | 2.8 min | 502| `navmeshes.rpf` full | 90,295 | 9,603 | 54,898 | 9,603 | 2,170 | 2.8 min |
481| `anim.rpf` full | 130,470 | 22,823 | 527,439 | 22,823 | 11,760 | 2.5 min | 503| `anim.rpf` full | 130,470 | 22,823 | 527,439 | 22,823 | 11,760 | 2.5 min |
504| `levels.rpf` full (streaming runner) | 1,116,073 | 188,449 | 465,611 | 188,449 | 3,281 | 17.7 min |
482 505
483The summary also counts the `q28` side: `q28_declared` (the sum of `n28`), `q28_records` (read), `q28_null_targets` 506The summary also counts the `q28` side: `q28_declared` (the sum of `n28`), `q28_records` (read), `q28_null_targets`
484and `q28_tables_unread`. 507and `q28_tables_unread`.
diff --git a/docs/ped_catalogues.md b/docs/ped_catalogues.md
new file mode 100644
index 000000000..9264152a2
--- /dev/null
+++ b/docs/ped_catalogues.md
@@ -0,0 +1,172 @@
1# Ped Appearance Catalogues (`0x8dcb4cf5`)
2
3Compiled ped and wardrobe appearance catalogues share one schema rooted at struct `0x8dcb4cf5`, stored in two container framings:
4
51. **Resource-packed `0DRP` v122 containers** inside `packs.rpf` (per-archetype ped catalogues).
62. **Standalone `PSIN` containers** (e.g. the player/wardrobe catalogue, whose multi-megabyte body mixes deflate and raw 64 KiB chunks inside the archive and is read once extracted as a `.pso` file).
7
8Both framings expose a 1-based block table and use the same internal 64-bit pointer encoding:
9
10```text
11block_1based = ptr & 0xfffff
12byte_offset = ptr >> 20
13```
14
15Parser and CLI: `tools/ped_catalogues.py` (stdlib only, `python -I`). Synthetic test suite: `tests/test_ped_catalogues.py`.
16
17---
18
19## Container framings
20
21### Resource-packed `0DRP` v122 (`0x7a`)
22
23Uses the standard `0x60`-byte standalone `0DRP`/`0x7a` header validated by `tools/odrp_7a.py` (see [page_directory.md](page_directory.md)):
24
25| Offset | Type | Field | Notes |
26|---:|---|---|---|
27| `+0x00` | `u64` | zero prefix | Always `0` |
28| `+0x08` | `u64` | page-map pointer | `0x50000000`-based virtual pointer |
29| `+0x10` | `char[4]` | magic | `b"0DRP"` (`0x50524430`) |
30| `+0x14` | `u32` | version | `122` (`0x7a`) |
31| `+0x18` | `u64` | reserved | Always `0` |
32| `+0x20` | `u32` | `root_block` | 1-based index into block directory (`+0x24` is `0`) |
33| `+0x28` | `u64` | struct table ptr | `0x50000000`-based virtual pointer (`ns` x 32 B) |
34| `+0x30` | `u64` | enum table ptr | `0` or `0x50000000`-based virtual pointer (`ne` x 24 B) |
35| `+0x38` | `u64` | block directory ptr | `0x50000000`-based virtual pointer (`nb` x 16 B) |
36| `+0x40` | `u64` | optional table ptr | `0` or `0x50000000`-based virtual pointer |
37| `+0x48` | `4 x u16` | `(ns, ne, nb, u4e)` | Struct, enum, and block counts |
38| `+0x50` | `u64` | optional ptr | `0` or `0x50000000`-based virtual pointer |
39| `+0x58` | `u64` | reserved | Always `0` |
40
41Each 16-byte block directory row at `+0x38` is `(u32 type_hash, u32 byte_size, u64 virtual_ptr)`. Virtual pointers resolve to `virtual_ptr - 0x50000000` within the inflated resource buffer. When a resource spans two contiguous deflate streams, the block directory or a block payload extends past the first stream's end; continuation streams must only be joined while the resource is truncated and must stop before a new `0DRP`/`PSIN` header (a complete resource whose size happens to be a multiple of 64 KiB can sit immediately before another `0DRP` catalogue).
42
43### Standalone `PSIN`
44
45Uses the standard `PSIN` header, `0xaa`-filled 16-byte block table, `0x70` table terminator, `LSCH`/`LENM` schema sections, and `LRSC` `0DRP` v122 summary record (`u32@+0x10` = 1-based root block index), decoded via `tools/psin_data.py` (see [psin.md](psin.md)).
46
47---
48
49## Schema and record layouts
50
51All offsets below were read directly from `LSCH` and verified across every `0x8dcb4cf5` catalogue in `packs.rpf`.
52
53### Root catalogue — `0x8dcb4cf5` (192 bytes)
54
55| Offset | Size | Field hash | Type | Meaning |
56|---:|---:|---|---|---|
57| `+0x00` | 96 B | `0x05269a03` | `0x50` (`0x60bcb6f3[2]`) | Two 48-byte preset buckets; each holds a `0x5c` array (`0x593bc9c3` at `+0x08`) of `0xf795e8ba` presets |
58| `+0x60` | 96 B | `0x9bcf5f90` | `0x50` (`0x4c70a132[2]`) | Two 48-byte secondary buckets; each holds a `0x5c` array (`0x593bc9c3` at `+0x08`) of `0xa9d57751` records |
59
60### Preset record — `0xf795e8ba` (88 bytes)
61
62| Offset | Size | Field hash | Type | Meaning |
63|---:|---:|---|---|---|
64| `+0x00` | 4 B | `0x65121749` | `0x4a` (`u32`) | `preset_id` (unique within a catalogue) |
65| `+0x04` | 4 B | `0x080eec39` | `0x4a` (`u32`) | `parent_id` (`0` = root preset, else parent `preset_id` in the same catalogue) |
66| `+0x08` | 16 B | `0xebacf18c` | `0x5c` (`{u32 count, u32 cap, u64 ptr}`) | Array of 184-byte `0x37e52277` drawable/texture state records |
67| `+0x18` | 4 B | `0xb53667be` | `0x4a` (`u32`) | Category hash (e.g. `0x378ad10c` head; `0x3817131d`, `0x44925bfd`, `0x9d283797` body skin) |
68| `+0x1c` | 4 B | `0x5ecf9331` | `0x4a` (`u32`) | Secondary hash |
69| `+0x20` | 4 B | `0xc4d75d79`..`0xa41d353b` | `3 x u8` + `0x60` enum | Preset flags and `0x25529dba` enum byte |
70| `+0x24` | 4 B | `0xe13ebaf8` | `0x4a` (`u32`) | Auxiliary hash |
71| `+0x28` | 24 B | `0x12f85293` | `0x71` sorted map | Preset tag map: `u64 flag` (`+0x28`), `u64 ptr` (`+0x30`), `u16 count` (`+0x38`), `u16 cap` (`+0x3a`) |
72| `+0x40` | 24 B | `0x9a289423` | `0x71` sorted map | `u32` hash -> `array<s32>` map |
73
74Each slot in the `0x12f85293` tag map is **24 bytes** inside a synthetic anonymous map-slot block (`0x100..0x1ff`):
75
76```text
77+0x00 u32 key (tag key hash, e.g. 0x4bfd27dd or 0x1c114e61 for drawable joaat32)
78+0x04 u32 pad
79+0x08 u32 count (number of u32 values)
80+0x0c u32 capacity
81+0x10 u64 value_ptr (internal pointer into a type-0x4a block of u32 hashes)
82```
83
84Synthetic block IDs (`0x100..0x1ff`) depend on per-file schema emission order. Across `packs.rpf`, `0x12f85293` uses `0x100` in 1,685 `0DRP` catalogues and `0x101` in 1,030 catalogues; hardcoding `0x100` drops 37.9% of catalogues.
85
86### Drawable / texture state record — `0x37e52277` (184 bytes)
87
88| Offset | Size | Field hash | Type | Meaning |
89|---:|---:|---|---|---|
90| `+0x00` | 4 B | `0x3eaddcd7` | `0x4a` (`u32`) | State ID / slot hash |
91| `+0x04` | 4 B | `0x46d26d93` | `0x15` (`u32`) | State flags |
92| `+0x08` | 56 B | `0xe7cb9e1b` | `0x05` (`0x147fdab5`) | Embedded drawable/texture + extension-map record (see below) |
93| `+0x40` | 4 B | `0x1d52bc91` | `0x4a` (`u32`) | Auxiliary hash |
94| `+0x48` | 16 B | `0x83698d93` | `0x5c` (`array<0x4a>`) | Auxiliary hash list |
95| `+0x58` | 72 B | `0x35ff19d7`, `0x3b7601de`, `0x7e43b9a9` | `3 x 0x71` maps | Bitset/mask maps |
96| `+0xa0` | 24 B | `0x12f85293` | `0x71` sorted map | State-level tag map (`u64 ptr` at `+0xa8`, `u16 count` at `+0xb0`) |
97
98### Embedded state body (`0x147fdab5`, 56 bytes at `0x37e52277 + 0x08`)
99
100| Local offset | `0x37e52277` offset | Field hash | Type | Meaning |
101|---:|---:|---|---|---|
102| `+0x00` | `+0x08` | `0x41acf8eb` | `0x4f` (`u64`) | Primary drawable `murmur64` (`h0`, MurmurHash3 x64_128 low word, seed 0) |
103| `+0x08` | `+0x10` | `0xead733fc` | `0x4f` (`u64`) | Albedo texture `murmur64` |
104| `+0x10` | `+0x18` | `0xd689b17f` | `0x4f` (`u64`) | Normal texture `murmur64` |
105| `+0x18` | `+0x20` | `0x9d1000d8` | `0x4f` (`u64`) | Fourth 64-bit asset hash (`extra_hash`) |
106| `+0x20` | `+0x28` | `0xb70a22c1` | `0x71` sorted map | Extension map: `u64 flag` (`+0x28`), `u64 ptr` (`+0x30`), `u16 count` (`+0x38`), `u16 cap` (`+0x3a`) |
107
108### `cull_drawable` chain (`0x147fdab5` -> `0xb70a22c1` -> `0x46e1a048` -> `0x3d780b74`)
109
110Each slot in the `0xb70a22c1` extension map is **16 bytes** inside a synthetic anonymous block (`0x100..0x1ff` — measured across `0x100`, `0x101`, `0x102`, `0x103` in `packs.rpf`):
111
112```text
113+0x00 u32 key (extension key hash; 0x46e1a048 == joaat("cull_drawable"))
114+0x04 u32 pad
115+0x08 u64 target_ptr (0x07 polymorphic struct pointer: block = p & 0xfffff, off = p >> 20)
116```
117
118When `key == 0x46e1a048`, `target_ptr` resolves into a block of type `0x3d780b74` (**16-byte** records):
119
120| Offset | Size | Field hash | Type | Meaning |
121|---:|---:|---|---|---|
122| `+0x00` | 8 B | — | `u64` | Zero header (always `0` in all 43,626 measured records) |
123| `+0x08` | 8 B | `0x7deba6f8` | `0x4f` (`u64`) | Alternate culled drawable `murmur64` |
124
125---
126
127## Preset inheritance and resolution algorithm
128
129Within a single catalogue, `0xf795e8ba` presets form a forest keyed by `preset_id` via `parent_id`. Child presets commonly carry texture overrides (e.g. face albedo and normal) while placing the drawable tag (`0x4bfd27dd` or `0x1c114e61`, `joaat32` of the lowercased drawable name) on a parent or grandparent preset with zero texture hashes.
130
131`tools/ped_catalogues.py` resolves each state in deterministic precedence order:
132
1331. **Direct preset drawable tag** (`0x4bfd27dd` / `0x1c114e61` on the preset's `+0x28` tag map, `joaat32`).
1342. **Direct state drawable tag** (`0x4bfd27dd` / `0x1c114e61` on the state's `+0xa0` tag map, `joaat32`).
1353. **Inherited ancestor drawable tag**: walk `parent_id` within `presets_by_id`, maintaining a `visited` set (cycle guard) and depth cap (`MAX_PARENT_DEPTH = 16`; corpus maximum is 3), stopping at the nearest ancestor defining a drawable tag.
1364. **State drawable hash**: direct `murmur64` `drawable_hash` (`h0` at `0x37e52277 + 0x08`).
1375. **`cull_drawable` target**: resolved through `0x147fdab5` -> `0xb70a22c1` (`0x46e1a048`) -> `0x3d780b74 + 0x08` (`murmur64`), attached to every resolved state binding and searchable directly.
138
139---
140
141## Verified corpus counts (Xbox package `1.0.2.1`, `packs.rpf`)
142
143Measured read-only with `tools/ped_catalogues.py` (0 parse errors, 0 warnings):
144
145| Metric | Resource-packed `0DRP` (`packs.rpf`) | Standalone `PSIN` (`00011ccb2000.pso`) | Combined |
146|---|---:|---:|---:|
147| `0x8dcb4cf5` catalogues | 2,715 | 1 | 2,716 |
148| `0xf795e8ba` presets | 612,950 | 19,828 | 632,778 |
149| Root-bucket (`0x60bcb6f3`) presets | 612,950 (100%) | 19,828 (100%) | 632,778 (100%) |
150| Duplicate `preset_id`s within a catalogue | 0 | 0 | 0 |
151| Presets with `parent_id != 0` | 334,146 | 11,634 | 345,780 |
152| Maximum `parent_id` chain depth | 3 | 3 | 3 |
153| Parent cycles / unresolved parents | 0 / 0 | 0 / 0 | 0 / 0 |
154| `0x37e52277` states (reached / in blocks) | 878,374 / 878,374 | 17,741 / 17,741 | 896,115 / 896,115 |
155| States with non-zero drawable `h0` | 559,139 | 7,227 | 566,366 |
156| States with non-zero albedo | 623,350 | 7,642 | 630,992 |
157| States with non-zero normal | 598,104 | 7,248 | 605,352 |
158| Catalogues with `cull_drawable` | 2,206 (81.25%) | 1 | 2,207 |
159| Resolved `0x46e1a048` -> `0x3d780b74` links | 42,882 | 744 | 43,626 |
160| `0x3d780b74` block records (all non-zero `murmur64`) | 42,882 (100%) | 744 (100%) | 43,626 (100%) |
161| Observed `0x12f85293` tag-map block IDs | `0x100` (1,685), `0x101` (1,030) | `0x100` (1) | `0x100`, `0x101` |
162| Observed `0xb70a22c1` ext-map block IDs | `0x100` (1,030), `0x101` (1,411), `0x102` (3), `0x103` (1) | `0x101` (1) | `0x100`..`0x103` |
163
164---
165
166## CLI usage
167
168```powershell
169python -I tools/ped_catalogues.py census <file|dir|archive.rpf> --json
170python -I tools/ped_catalogues.py inspect <catalogue.pso|catalogue.0drp> --limit 10
171python -I tools/ped_catalogues.py resolve <file|dir|archive.rpf> --name <drawable_name> --cull-only --json
172```
diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md
index ef90efbd5..62e5417a3 100644
--- a/docs/pipeline_check.md
+++ b/docs/pipeline_check.md
@@ -6,6 +6,11 @@ constant contract. It is a driver-level check: it proves the modules and pipelin
6the Vulkan implementation, not that the shader results are correct. Value-level checks are in 6the Vulkan implementation, not that the shader results are correct. Value-level checks are in
7`docs/shader_validation.md`. 7`docs/shader_validation.md`.
8 8
9Timing and memory figures in this page were measured with `MESA_SHADER_CACHE_DISABLE=true`. Without it, RADV's
10on-disk shader cache (`~/.cache/mesa_shader_cache`, about 1.1 GB after a full corpus run) turns a repeated module
11into a cache hit: 0.1 s and ~114 MB instead of a real compilation. That is what a resume run wants, but not what a
12measurement should report.
13
9The checker exits nonzero if a module fails to load, a pipeline fails to compile, or the requested final 14The checker exits nonzero if a module fails to load, a pipeline fails to compile, or the requested final
10cache save fails. It still finishes checking the other entries and attempts the final save so the next run 15cache save fails. It still finishes checking the other entries and attempts the final save so the next run
11can reuse successful pipelines. Before creating a Vulkan shader module, it checks that the file has a 16can reuse successful pipelines. Before creating a Vulkan shader module, it checks that the file has a
@@ -46,6 +51,11 @@ normal driver check. Mesh pipelines on devices without mesh shader support still
46same pipeline. Use it before driver compilation to locate missing varyings, overlapping components, type 51same pipeline. Use it before driver compilation to locate missing varyings, overlapping components, type
47mismatches and per-primitive mesh declarations. It reads local modules and needs only Python. 52mismatches and per-primitive mesh declarations. It reads local modules and needs only Python.
48 53
54The declarations come from `tools/spirv_interface.py`, a standard-library reader of one module's interface
55(the normalized `Location`/`Component` model, one array level and literal specialization defaults) with its
56tests in `tests/test_spirv_interface.py`. It reflects declarations only, not instructions, device features or
57resource bindings, so it does not replace `spirv-val`.
58
49```powershell 59```powershell
50python -I tools/shader_link_check.py check --vs <vertex.spv> --ps <pixel.spv> 60python -I tools/shader_link_check.py check --vs <vertex.spv> --ps <pixel.spv>
51python -I tools/shader_link_check.py check --vs <vertex.spv> --gs <geometry.spv> --ps <pixel.spv> 61python -I tools/shader_link_check.py check --vs <vertex.spv> --gs <geometry.spv> --ps <pixel.spv>
@@ -53,8 +63,13 @@ python -I tools/shader_link_check.py check --ms <mesh.spv> --ps <pixel.spv>
53python -I tools/shader_link_check.py inspect <shader.spv> 63python -I tools/shader_link_check.py inspect <shader.spv>
54``` 64```
55 65
66Direct checks use `main` for every stage unless `--entry` sets another shared default.
67Use a stage-specific override for modules with different entry names, for example
68`check --vs vertex.spv --vs-entry Vertex --ps pixel.spv --ps-entry Fragment`.
69
56To audit a batch, give it the shader names from your local translation directory in a JSON file. A stage can 70To audit a batch, give it the shader names from your local translation directory in a JSON file. A stage can
57use a string or a `shader` and `entry` object. Names refer to `<name>.spv` in `--shader-dir`. 71use a string or a `shader` and `entry` object. Names refer to `<name>.spv` in `--shader-dir`. The manifest is read as
72UTF-8 with or without the byte order mark, so a copy saved by Notepad or `Out-File -Encoding utf8` is taken as is.
58 73
59```json 74```json
60{ 75{
@@ -114,6 +129,65 @@ In strict mode, exit 1 means at least one result other than `exact` or `partitio
114Invalid inputs or an unavailable Vulkan probe exit 2. This checks width fidelity from metadata. 129Invalid inputs or an unavailable Vulkan probe exit 2. This checks width fidelity from metadata.
115Vulkan pipeline creation and drawing still need their own tests. See [Wave64 graphics in the 130Vulkan pipeline creation and drawing still need their own tests. See [Wave64 graphics in the
116translator contract](design.md) for how the tiers are assigned. 131translator contract](design.md) for how the tiers are assigned.
132## Test Mesa pipeline compilation without a physical GPU
133
134On Linux, Mesa's DRM shims expose GPU profiles to its Vulkan drivers. This lets `vk_pipeline_check`
135measure shader compile time and reproduce compiler failures on a machine without that hardware.
136Readback and dispatch correctness still require a Vulkan device that executes commands.
137See the [Mesa DRM shim guide](https://docs.mesa3d.org/ci/drm-shim.html).
138
139From the Leonida root, build the checker and translate a synthetic fixture. The fixture build needs
140`spirv-as`, `spirv-val` and LLVM 21 or later with the AMDGPU target. Set `LLVM_MC` if the assembler
141has a versioned name.
142
143```sh
144cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=Release
145cmake --build runtime/build --target vk_pipeline_check
146fixtures=$(mktemp -d)
147python3 -I runtime/test/shaders/build.py "$fixtures" cs_buf_fmt8
148```
149
150### AMD RADV
151
152Build Mesa with `-Dvulkan-drivers=amd -Dtools=drm-shim`. Set `mesa_build` to that build directory
153and `radv_icd` to the absolute path of the matching RADV Vulkan ICD manifest.
154
155```sh
156AMDGPU_GPU_ID=gfx1201 \
157LD_PRELOAD="$mesa_build/src/amd/drm-shim/libamdgpu_noop_drm_shim.so" \
158VK_DRIVER_FILES="$radv_icd" MESA_SHADER_CACHE_DISABLE=true \
159 runtime/build/vk_pipeline_check "$fixtures/spirv" --jobs 1 --slow 0
160```
161
162The checker should select a device whose name includes `RADV GFX1201` and report one compute pipeline
163compiled. For comparisons, use the same Mesa version, GPU profile and translation flags each time.
164Run each comparison in a fresh process and leave the pipeline cache filename out.
165
166Mesa 25.0.7 also supports a null device directly through the installed RADV ICD. On Debian 13
167this runs the same compile check with the distro driver.
168
169```sh
170RADV_FORCE_FAMILY=GFX1201 VK_DRIVER_FILES=/usr/share/vulkan/icd.d/radeon_icd.json \
171MESA_SHADER_CACHE_DISABLE=true runtime/build/vk_pipeline_check "$fixtures/spirv" --jobs 1 --slow 0
172```
173
174### Intel ANV
175
176Build the Intel shim with `-Dtools=drm-shim,intel` and use an ANV ICD from the same Mesa version.
177When using a prebuilt driver, the shim can be built with `-Dvulkan-drivers= -Dgallium-drivers=`.
178Set `intel_icd` to the absolute path of its ANV manifest and `intel_shim_build` to the shim's
179Mesa build directory.
180
181```sh
182INTEL_STUB_GPU_PLATFORM=bmg \
183LD_PRELOAD="$intel_shim_build/src/intel/tools/libintel_noop_drm_shim.so" \
184VK_DRIVER_FILES="$intel_icd" MESA_SHADER_CACHE_DISABLE=true \
185 runtime/build/vk_pipeline_check "$fixtures/spirv" --jobs 1 --slow 0
186```
187
188The example selects a Battlemage profile. Use `dg2` for an Alchemist profile or `adl` for Alder Lake.
189On Mesa 26.1.6 all three compiled the example, including when it was rebuilt with
190`LEONIDA_PC_TAIL_UBO=1` to move the push-constant tail to a uniform buffer.
117 191
118## Corpus 192## Corpus
119 193
@@ -156,8 +230,11 @@ modules and pipelines with **0 failures** and a 3.81 GB cache; see the "Full-cor
156compile-time stall, not a project-wide limit. 230compile-time stall, not a project-wide limit.
157 231
158The recurring slow family at every shard tail was a set of 6.7-7.2 MB ray-tracing resolve compute 232The recurring slow family at every shard tail was a set of 6.7-7.2 MB ray-tracing resolve compute
159shaders. One observed single-module stall exceeded 27 minutes. The tool has no per-shader timer, so 233shaders. One observed single-module stall exceeded 27 minutes, read from the run's progress output.
160these are lower bounds, not exact compile times. 234The tool times each pipeline: `--slow SEC` prints `SLOW <stage> <name> (w<N>, <sec>s)` for a pipeline
235that takes longer than SEC, and each stage's summary ends with
236`compile time: <total>s total, <mean>s mean, slowest <name> (<sec>s)`. A run with `--slow 0` therefore
237reports such a stall with its duration, not as a lower bound.
161 238
162## Bounded guaranteed-finish sample 239## Bounded guaranteed-finish sample
163 240
@@ -223,6 +300,48 @@ The report above therefore states the limit and the skip count; a later run on a
223completed the full 26,503-entry set without them (`docs/design.md`). `--max-bytes` remains a visibility 300completed the full 26,503-entry set without them (`docs/design.md`). `--max-bytes` remains a visibility
224tool, not a pass: a skipped module has not been validated. 301tool, not a pass: a skipped module has not been validated.
225 302
303## Stack reserve (BUILD-1457)
304
305A driver compiles on the thread that creates the shader module or the pipeline, and its compiler can recurse with
306the shader's control-flow nesting. On Windows a thread that asks for no stack size gets the reserve written in the
307executable's PE header, 1 MB by default. That is the checker's main thread and every `std::thread` worker.
308
309`vk_pipeline_check` is linked with an **8 MB** reserve: `/STACK:8388608` in `runtime/CMakeLists.txt` and on the
310checker's `cl` line in `scripts/build_runtime.ps1`. The CTest `vk_pipeline_check_stack` reads `SizeOfStackReserve`
311back from the built file (`runtime/test/check_stack_reserve.cmake`; the program is not run), and
312`tests/test_build_runtime_fallback.py` keeps the two numbers the same.
313
314Measured on an AMD Radeon RX 9070 XT, AMD 26.11.2 (LLPC, Windows driver 32.0.32029.2010), each module alone with
315no cache file (`--jobs 1 --start N --count 1`), on a 1.0.2.1 corpus translated at `aa2988cc` with native wave64.
316The reserve was changed with `editbin /STACK` on copies of one binary. Counts only.
317
318| Reserve | The 26 mesh modules that overflow at 1 MB | 28 structured compute modules that overflow at 1 MB |
319|---|---|---|
320| 1 MB | 26 exit 0xC00000FD (stack overflow) | 28 exit 0xC00000FD |
321| 2 MB | 26 create their pipeline | 18 create theirs, 10 exit 0xC00000FD |
322| 4 MB | 26 create their pipeline | 28 create their pipeline |
323| 8 MB | 26 create their pipeline | 28 create their pipeline |
324
325The 26 are what a corpus translated on `main` hits: 2.42 to 2.79 MB of SPIR-V each, among 846 mesh and vertex
326modules of 1 MiB or more that were tried one by one at 1 MB (the other 820 pass). The 28 come from a sample of 60
327compute modules, picked evenly by size, of the 781 that take the structured form once the structured depth bound
328is 64 instead of 16 (SHADER-427): every sampled module from 4.76 MB up overflows 1 MB. So 2 MB is enough today and
329not for the deeper trees. With the linked 8 MB, the same 26 and 28 create their pipelines, and with that binary's
330reserve put back to 1 MB all 54 overflow again.
331
332Not measured: other AMD GPU families, other vendors' Windows drivers, and a corpus translated with
333`--wave64-emulate`.
334
335**The runtime.** The D3D12 shim creates a pipeline on the thread that asks for it
336(`runtime/shims/d3d12_vulkan_device.cpp`), so there the compiler runs on a game thread. The entry thread has 8 MB
337from `run_entry` (`runtime/shims/process_shim.h`). A thread the game starts with `dwStackSize` 0, a thread-pool
338thread and a `std::thread` of the shims get the reserve in `gta6rt.exe`'s header, because the game's `CreateThread`
339is Windows' own. `gta6rt` is therefore linked with the same 8 MB (`GTA6RT_STACK` in `runtime/CMakeLists.txt`, and
340the loader's `cl` line in `scripts/build_runtime.ps1`). The CTest `gta6rt_stack` reads the header, and
341`run_tiny_game_stack` asks Windows from inside a program the loader runs: the entry thread and a thread created
342with `dwStackSize` 0 both report 8 MB. Not covered: a thread the title creates with an explicit smaller size keeps
343that size. Which threads the game creates pipelines on is not known without its executable.
344
226## Build-stage batches (BUILD-1030) 345## Build-stage batches (BUILD-1030)
227 346
228`make_game.py` runs the pipelines stage in fresh checker processes over at most **500 index entries** each, on 347`make_game.py` runs the pipelines stage in fresh checker processes over at most **500 index entries** each, on
@@ -243,20 +362,26 @@ writes/clears its in-flight report even when validation fails. Exit 1 without a
243of repeating failed setup for the remaining batches; diagnostic probes use the same distinction. Each process 362of repeating failed setup for the remaining batches; diagnostic probes use the same distinction. Each process
244starts with a cleared report path, so an earlier process's report cannot hide an initialization failure. 363starts with a cleared report path, so an earlier process's report cannot hide an initialization failure.
245 364
365An abnormal diagnostic-probe exit confirms a module crash only when that probe's fresh in-flight report names
366the selected module. A missing, empty or unrelated report makes the result inconclusive and stops the stage
367without blaming that module. The native report is periodic for small modules, so even a real fast crash can
368leave no evidence; this conservative fallback does not guess its cause or add an unconfirmed crash-list entry.
369
246The batch size limits the index range, **not total memory usage**. Concurrent heavy modules, loading a large 370The batch size limits the index range, **not total memory usage**. Concurrent heavy modules, loading a large
247saved cache or compiling one large shader can still exceed a process's available memory; a range that 371saved cache or compiling one large shader can still exceed a process's available memory; a range that
248cannot complete even alone fails with a diagnostic rather than being counted as checked. 372cannot complete even alone fails with a diagnostic rather than being counted as checked.
249 373
250`tests/test_make_game_pipeline_batches.py` runs the real build-stage orchestration against scripted child processes: 374`tests/test_make_game_pipeline_batches.py` runs the real build-stage orchestration against scripted child processes:
251bounded coverage and cache checkpoints, collective memory-crash recovery, a genuinely crashing module, validation 375bounded coverage and cache checkpoints, collective memory-crash recovery, a genuinely crashing module, validation
252failures, interruptions, setup failures and compatibility with older checkers. It needs no game files or GPU. 376failures, interruptions, setup failures, inconclusive probes and compatibility with older checkers. It needs no
377game files or GPU.
253 378
254## Crash isolation (`--isolate`) 379## Crash isolation (`--isolate`)
255 380
256A driver that dies while compiling one module (for example the RADV `SIGFPE` in 381A driver that dies while compiling one module (for example the RADV `SIGFPE` in
257[#1721](https://github.com/ItsNotRexed/Leonida/issues/1721)) ends the whole process, so the rest of the corpus 382[#1721](https://github.com/ItsNotRexed/Leonida/issues/1721)) ends the whole process, so the rest of the corpus
258used to need that module excluded by hand with `--start/--count`. With `--isolate` (POSIX only; on Windows it 383used to need that module excluded by hand with `--start/--count`. With `--isolate` the tool runs the check in
259prints an error and exits with 2) the tool runs the check in child processes instead: 384child processes on native Windows and POSIX:
260 385
261```sh 386```sh
262vk_pipeline_check <spirv dir> cache.bin --isolate [--isolate-batch 256] [--jobs N ...] 387vk_pipeline_check <spirv dir> cache.bin --isolate [--isolate-batch 256] [--jobs N ...]
@@ -272,6 +397,7 @@ vk_pipeline_check <spirv dir> cache.bin --isolate [--isolate-batch 256] [--jobs
272 that needs several threads at once), the batch is reported as `MODULE CRASH [a, b) not reproduced ...` and 397 that needs several threads at once), the batch is reported as `MODULE CRASH [a, b) not reproduced ...` and
273 counts as a failure. A child that fails before it starts work (no device, bad arguments) stops the run 398 counts as a failure. A child that fails before it starts work (no device, bad arguments) stops the run
274 with exit status 1. 399 with exit status 1.
400- Windows reports exception exit codes in hexadecimal, for example `driver exited with status 0xc0000005`.
275- The pipeline cache: children run one after another and each seeds from and saves to the same `cache.bin`, 401- The pipeline cache: children run one after another and each seeds from and saves to the same `cache.bin`,
276 like the chunked runs above; the save is atomic, a crashed child saves nothing, so the file stays valid and 402 like the chunked runs above; the save is atomic, a crashed child saves nothing, so the file stays valid and
277 holds everything the finished children compiled. The parent prints its size at the end. 403 holds everything the finished children compiled. The parent prints its size at the end.
@@ -282,8 +408,9 @@ vk_pipeline_check <spirv dir> cache.bin --isolate [--isolate-batch 256] [--jobs
282 There is no timeout: a hung compile still hangs. 408 There is no timeout: a hung compile still hangs.
283 409
284Test hook, not for normal use: `VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL]` makes the 410Test hook, not for normal use: `VK_PIPELINE_CHECK_SIMULATE_CRASH=<module name substring>[:SIGNAL]` makes the
285process raise `SIGNAL` (default `SIGFPE`; `SEGV`, `ABRT`, `KILL`, ... also accepted) just before the pipeline of a 411process simulate a crash just before creating a matching module's pipeline. The default is `SIGFPE`.
286matching module is created. `tests/test_vk_pipeline_check_isolate.py` uses it with five hand-assembled compute 412On Windows, `SIGFPE` and `SIGSEGV` use the corresponding exception exit codes.
413`tests/test_vk_pipeline_check_isolate.py` uses it with five hand-written compute
287shaders to check `--isolate` without a crashing driver; it skips when the tool isn't built or there is no 414shaders to check `--isolate` without a crashing driver; it skips when the tool isn't built or there is no
288Vulkan device. 415Vulkan device.
289 416
diff --git a/docs/progress_dashboard.md b/docs/progress_dashboard.md
index 41ebf6967..c5e7f48a4 100644
--- a/docs/progress_dashboard.md
+++ b/docs/progress_dashboard.md
@@ -16,11 +16,13 @@ The page is one self-contained HTML file: no network, no packages, it opens from
16## Sources 16## Sources
17 17
18Each source is optional. A missing one is listed under "Sources" on the page; it is never counted as zero or as a failure. 18Each source is optional. A missing one is listed under "Sources" on the page; it is never counted as zero or as a failure.
19For `--junit`, keep the original XML encoding. UTF-16 reports and reports with a supported encoding declaration
20are read directly; there is no need to re-save them as UTF-8.
19 21
20| Panel | Source | Unit | 22| Panel | Source | Unit |
21|---|---|---| 23|---|---|---|
22| Unit tests | `--run-tests` runs `tests/test_*.py` with the selection `ci.yml` uses (standard-library files with a `__main__` block), one process each; the outcome and the commit it ran on are kept in `<out>/unit_results.json`. That is CI's standard-library loop only: `tests/semantic` (the translator suite) and files that need pytest or numpy are not run, so the panel is not the whole test suite; feed those through `--junit` (`python -m pytest tests/semantic --junitxml <file>`) to see them in the runtime-tests panel | test file | 24| Unit tests | `--run-tests` runs `tests/test_*.py` with the selection `ci.yml` uses (standard-library files with a `__main__` block), one process each; the outcome and the commit it ran on are kept in `<out>/unit_results.json`. That is CI's standard-library loop only: `tests/semantic` (the translator suite) and files that need pytest or numpy are not run, so the panel is not the whole test suite; feed those through `--junit` (`python -m pytest tests/semantic --junitxml <file>`) to see them in the runtime-tests panel | test file |
23| Runtime tests | `runtime/build/Testing/Temporary/LastTest.log` and any `--junit` file (CTest `--output-junit` or pytest `--junitxml`) | test | 25| Runtime tests | `runtime/build/Testing/Temporary/LastTest.log` and any `--junit` file (CTest `--output-junit` or pytest `--junitxml`). CTest logs and XML reports are age-checked by file modification time | test |
24| GPU tests | `--gpu-log <file>[=<GPU, driver, OS>]`: the saved output of `runtime/test/shaders/check.py`, one group per GPU; a log older than the last commit touching `runtime/test/shaders` or `tools/rdna2spirv.py` counts as needing a re-run | test program | 26| GPU tests | `--gpu-log <file>[=<GPU, driver, OS>]`: the saved output of `runtime/test/shaders/check.py`, one group per GPU; a log older than the last commit touching `runtime/test/shaders` or `tools/rdna2spirv.py` counts as needing a re-run | test program |
25| Translator contract | the contract table in [design.md](design.md#translator-status-and-runtime-contract), each row classified by how it says it was confirmed | contract row | 27| Translator contract | the contract table in [design.md](design.md#translator-status-and-runtime-contract), each row classified by how it says it was confirmed | contract row |
26| Runtime imports | the measured tables in [runtime_imports.md](runtime_imports.md) | import | 28| Runtime imports | the measured tables in [runtime_imports.md](runtime_imports.md) | import |
@@ -44,7 +46,7 @@ it continues) and its pull requests. Nothing is posted: every `gh` call is a rea
44|---|---|---|---|---|---| 46|---|---|---|---|---|---|
45| VERIFIED | passed, and nothing it depends on changed since | names a GPU check and leaves nothing open | image with 0 unimplemented imports | — | — | 47| VERIFIED | passed, and nothing it depends on changed since | names a GPU check and leaves nothing open | image with 0 unimplemented imports | — | — |
46| IMPLEMENTED | — | confirmed by an LLVM/Mesa reference, a corpus count or a CPU test, not a GPU | bound to a shim, the host or a module | merged into `main` | a PR merged into `main` and none open | 48| IMPLEMENTED | — | confirmed by an LLVM/Mesa reference, a corpus count or a CPU test, not a GPU | bound to a shim, the host or a module | merged into `main` | a PR merged into `main` and none open |
47| PARTIAL | passed before a change to the test, `tools/`, `scripts/` or `make_game.py` (CTest: before the last commit touching `runtime/`) | waits for a GPU measurement, or names a GPU check with an item still open | — | open | pull request open | 49| PARTIAL | passed before a change to the test, `make_game.py`, or a Python file under `tools/`, `scripts/` or `runtime/test/shaders/` (CTest: before the last commit touching `runtime/`) | waits for a GPU measurement, or names a GPU check with an item still open | — | open | pull request open |
48| FAILED | failed on its last run | — | — | — | — | 50| FAILED | failed on its last run | — | — | — | — |
49| MISSING | — | — | unimplemented | — | unclaimed | 51| MISSING | — | — | unimplemented | — | unclaimed |
50| UNKNOWN | skipped, or git can't tell what changed | states no confirmation method | — | — | claimed, no code yet | 52| UNKNOWN | skipped, or git can't tell what changed | states no confirmation method | — | — | claimed, no code yet |
diff --git a/docs/psin.md b/docs/psin.md
index 9999e89a9..49945614e 100644
--- a/docs/psin.md
+++ b/docs/psin.md
@@ -261,6 +261,41 @@ Uniform bytes in exact 16-byte units that repeat record by record fit a determin
261also fit 128-bit hashes of inputs outside the tested dictionary and functions. Which one it is has not been 261also fit 128-bit hashes of inputs outside the tested dictionary and functions. Which one it is has not been
262established. Per the project rules, no decryption is attempted. 262established. Per the project rules, no decryption is attempted.
263 263
264## `PMAP`, `PSCH`, `PSIG` and `STNS`: the PSO-style variant
265
266The 57 complete `PSIN` streams without `LSCH` (54 in `data.rpf`, 2 in `packs.rpf`, 1 in `anim.rpf`) replace
267`LSCH`/`LENM`/`LSNS`/`LRSC` with a big-endian PSO schema chain: `PMAP`, `PSCH`, `PSIG`, optional `STFN`/`STDN`, `STNS`
268and `CHKS`. Measured with `tools/psin_psch.py` over all **54** containers in `data.rpf` (`54/54` valid):
269
270- **Header and instance region:** bytes `+0x08..+0x0F` hold `pppppppp` (`0x70` x 8) and instance data blocks sit at
271 `+0x10..first_section` (in contrast to `LSCH` containers, which place the block table at `+8`).
272- **`PMAP` (287 blocks across 54 files):** starts with a 16-byte big-endian header (`u32 root_block_id`, `u16 flags`,
273 `u16 0`, `u16 block_count`, 6-byte `pppppp` fill), followed by `block_count` x 16-byte rows `{u32 name_hash, u32 offset,
274 u32 0, u32 length}`. On **54 of 54**, blocks begin at `0x10` and end at exact `first_section`; 237 blocks reference a
275 struct in `PSCH` (`237/237` have `length % struct_size == 0`) and 50 are anonymous (`0x1`: 41, `0xc`: 7, `0x8`: 1,
276 `0x6`: 1).
277- **`PSCH` (`689` structs / `69` distinct, `3,250` members / `500` distinct, `146` enums / `17` distinct, `662` values):**
278 `u32be entry_count` followed by `entry_count` directory pairs `(u32be name_hash, u32be section_offset)`. Kind `0`
279 entries are structs (`u8 0`, `u8 flags`, `u16be member_count`, `u32be byte_size`, `u32be 0`, then `12`-byte big-endian
280 members `{u32 hash, u8 type, u8 sub, u16 offset, u32 ref}`); kind `1` entries are enums (`u8 1`, `u8 flags`, `u16be
281 value_count`, then `16`-byte values `{u32 hash, u32 0, i64be value}`). Every array member (`0x0d`, 226/226) and map
282 member (`0x10`, 3/3 key/value pairs) points at `0x100` element descriptors inside its struct; all 185 enum members
283 (`0x0e`) resolve locally, and 718 struct members (`0x0c`) hold `671` local hashes, `11` zero references, `33`
284 cross-file `data.rpf` references and `3` external references.
285- **`PSIG` and `STNS`/`STDN`/`STFN`:** `PSIG` stores `entry_count` big-endian `u32` layout signatures (`83` distinct).
286 `STNS` mirrors `LSNS` as a little-endian `u32 block_count` table of `(u32 kind, u32 bytes)` pairs and 16-byte-aligned
287 records (`867` total across `54` blocks) padded with zeros to a 16-byte payload boundary
288 (`align16(4 + 8 * block_count + data_bytes)` on all 54 containers: 4 zero bytes for `1`-block sections and 12 zero
289 bytes for `0`- and `2`-block sections). Where present, `STDN` (`2/2`) matches the prefix of `STNS`'s block data
290 byte-for-byte.
291
292```text
293python -I tools/psin_psch.py <file_or_carve_dir_or_rpf> [--carve-dir DIR] [--json FILE]
294```
295
296`tests/test_psin_psch.py` builds synthetic `PMAP`/`PSCH`/`PSIG`/`STDN`/`STNS` containers and tests block validation,
297member descriptor checks, carve-directory filtering and `--json` collision refusal.
298
264## Instance data 299## Instance data
265 300
266The region between the 8-byte header and `LSCH` is a block table followed by its data blocks. The schema in 301The region between the 8-byte header and `LSCH` is a block table followed by its data blocks. The schema in
@@ -364,11 +399,12 @@ python -I tools/psin_data.py <PSIN file or carve directory> [--json] [--limit N]
364python -I tools/psin_data.py <PSIN file> --dump 399python -I tools/psin_data.py <PSIN file> --dump
365``` 400```
366 401
367The default output is the counts above, for one file or every `.bin` in a carve directory. `--dump` prints one 402The default output is the counts above, for one file or every `.bin` in a carve directory. A single file that does
368container's decoded tree (hashes as hex) on stdout, for local inspection only. It writes no file and must not be 403not start with the `PSIN` magic is one `ERROR:` line and exit 2; inside a directory such a file is skipped, since a
369pasted into an issue or a pull request. `tests/test_psin_data.py` builds containers from invented names and covers 404carve folder holds other streams too. `--dump` prints one container's decoded tree (hashes as hex) on stdout, for
370every layout above, the end padding, a bad fill, pointers out of range, an unlisted enum value, a skipped type and 405local inspection only. It writes no file and must not be pasted into an issue or a pull request.
371the CLI. 406`tests/test_psin_data.py` builds containers from invented names and covers every layout above, the end padding, a
407bad fill, pointers out of range, an unlisted enum value, a skipped type and the CLI.
372 408
373### Name hashes in the data 409### Name hashes in the data
374 410
@@ -426,6 +462,22 @@ field table. `--refs` writes one row per resolved value: file, struct, field, ty
426so keep them in your local work folder; only the counts belong in git, issues or pull requests. On the data above the 462so keep them in your local work folder; only the counts belong in git, issues or pull requests. On the data above the
427run takes about 50 s. `tests/test_psin_names.py` builds containers from invented names. 463run takes about 50 s. `tests/test_psin_names.py` builds containers from invented names.
428 464
465#### Vehicle names in the navmesh PSIN map
466
467The version 256 PSIN at `navmeshes.rpf` offset `0x1749fe000` has a root map of type `0x73`. Its pointer
468resolves to an anonymous `0x100` block of 28,672 bytes. The schema gives a `0x4a` key at slot offset
469`+0x00` and a 48-byte struct value at `+0x08`, for a stride of 56 bytes. The map declares 512 slots and
470209 entries. Counting distinct nonzero keys gives 209.
471
472On the 1.0.2.1 package, compare the lower-case joaat hashes of `ModelName` and the nonempty
473`ModDefs/Item` names in the 32 `CVehiclePoints` documents in `common.rpf` with every occupied slot.
474Of 31 distinct model names, 25 match the map key. Of 55 distinct part names, 20 match `0x4a` members
475in the value: 6 at slot `+0x18`, 2 at `+0x1c`, 4 at `+0x28`, and 8 at `+0x34`. Appending `#zq`
476to the model names gives zero key matches. All the original matches lie in the instance block before
477the first section. The container's 493 `LSNS` records have zero matches for either set of hashes.
478The map identifies vehicles and parts in the container. Which entry refers to each of the 161
479local-space navmeshes remains open.
480
429## What it does not give 481## What it does not give
430 482
431- No plaintext script code, function names or string table. `LSNS` has a decoded block layout, but its 483- No plaintext script code, function names or string table. `LSNS` has a decoded block layout, but its
@@ -482,6 +534,61 @@ A section that runs past the end of a truncated stream is shown as raw bytes. `t
482synthetic container, checks it with `psin_index.py` and `psin_data.block_table`, and when ImHex is installed compares 534synthetic container, checks it with `psin_index.py` and `psin_data.block_table`, and when ImHex is installed compares
483the pattern's output with both. 535the pattern's output with both.
484 536
537## Non-PSIN object-tree table in `script.rpf`
538
539Besides its 1,012 `PSIN` containers (1,015 streams, 3,477,872 inflated bytes), `script.rpf` contains one large non-`PSIN`
540binary container carved at offset `0x53000` (`42` contiguous deflate streams: 41 x 65,536 + 15,408 = **2,702,384**
541inflated bytes / `0x293C30`, 461,333 stored bytes, 43.7% of `script.rpf`'s inflated output). It is not `PSIN`, `RBF0`
542or `0DRP`, and carries no strings: it is a dense 483-tree forest serialized in preorder with `0x71717171` (`'qqqq'`)
543relocatable pointers, measured with `tools/script_qtable.py` on package 1.0.2.1.
544
545### Layout and header (`0x000000..0x293C2F`)
546
547| Region | Offset | Size | Layout |
548|---|---:|---:|---|
549| Header | `0x000000` | 40 B | ten `u32` words: `record_count = 30,683` (`0x000077DB`) at `+0x14`; all other nine words `0` |
550| Offset table | `0x000028` | 245,464 B | `30,683` strictly ascending, 16-byte-aligned `u64` offsets (`0x03BF00` to `0x293C00`) |
551| Record pool | `0x03BF00` | 2,456,880 B | `30,683` 16-byte-aligned records (`32` to `6,704` bytes), ending at exact EOF (`0x293C30`) |
552
553Each record `i` begins with an 8-byte prefix before its body at `offsets[i] + 8`:
554
555- **`+0x00` `u32 root_key_hash`**: non-zero on **483** records (`483` distinct values) and `0` on the other **30,200**
556 records.
557- **`+0x04` `u32 root_flags`**: `0` on all 30,200 non-root records; on the 483 roots, `0xFFFF0000` (385), `0` (86) or
558 `(1..8) << 16` (12).
559
560### Relocatable pointers and tree bijection
561
562Every 8-byte-aligned `u64` word from `+0x08` onward whose high 32 bits equal `0x71717171` (`'qqqq'`) is an internal
563pointer whose low 32 bits equal `offsets[target] + 8` (the start of record `target`'s body):
564
565- **30,200 of 30,200** `0x71717171` pointers resolve to a valid record (`0` unresolved, `0` outside the pool).
566- **Exact root bijection:** the **483** records with `root_key_hash != 0` are the exact **483** records with
567 in-degree `0`; all **30,200** records with `root_key_hash == 0` have in-degree `1`.
568- **Contiguous preorder forest:** all **30,200** edges point strictly forward (`target > source`, `0` back-edges or
569 cycles), remain inside their root's contiguous index slice `[root_k, root_{k+1})` (`0` cross-tree edges), and match
570 strict depth-first preorder in stored pointer-field sibling order across all **30,683** positions. Tree sizes range
571 from `1` to `1,131` nodes (median `53`, depths `0..9`).
572
573### Array and struct records
574
575| Kind | Count | Header at `+0x08` | Notes |
576|---|---:|---|---|
577| Array records | 10,294 | `+0x08 = 0x14`, `+0x0C = 0`, `+0x10 = +0x14 = count` (`0..220`), `+0x18 = stride`, `+0x1C = flags`, `+0x20 = 0` (`u64`), `+0x28 = element_type_hash` (35 distinct, none 0), `+0x2C = 0` | Elements start at `+0x30`; `align16(48 + count * stride) == len(rec)` holds on **10,294 of 10,294**. `flags = 0` (8,211 value/struct arrays, strides `4, 8, 12, 16, 20, 24, 32, 48, 64, 128`) and `flags = 0x10000` (2,083 pointer arrays, all stride `8`, holding 7,297 `0x71717171` pointers). |
578| Typed struct records | 20,389 | `+0x08 = struct_type_hash` (66 distinct hashes), `+0x0C = 0` on all 20,389 | Sizes `32` B (17,106: 12,332 wrapper nodes pointing at `+0x10` to `i + 1` with `+0x18 = 0`, 3,540 single-pointer at `+0x18`, 3 two-pointer, 1,231 leaves), `48` B (1,642: 1,641 two-pointer, 1 leaf) and `64` B (1,641 leaves). |
579
580```text
581python -I tools/script_qtable.py <carve_dir_or_rpf_or_bin> [--root-hash HEX] [--type-hash HEX] [--json FILE]
582```
583
584Accepts an `rpf9_carve.py` carve directory (`script`), a `script.rpf` archive or a joined `.bin` payload.
585Default stdout and `--json` output emit aggregate counts, histograms and structural invariant checks only; `--root-hash`
586and `--type-hash` report local tree/type counts in hex. `tests/test_script_qtable.py` covers synthetic multi-tree parsing,
58764 KiB stream reassembly across a carve folder, pointer validation and output collision guards. A target that does not
588exist, or that cannot be read, stops the tool with one `ERROR:` line and exit 2 before anything is parsed; a readable
589file that is not an object-tree payload is exit 1, the scan's verdict, and a `--json` file that cannot be written is
590exit 2 as well.
591
485## Limits 592## Limits
486 593
487- The 64 KiB split is not joined automatically. A caller that has the archive order can join adjacent 594- The 64 KiB split is not joined automatically. A caller that has the archive order can join adjacent
diff --git a/docs/pso_cache.md b/docs/pso_cache.md
new file mode 100644
index 000000000..1d3d448c5
--- /dev/null
+++ b/docs/pso_cache.md
@@ -0,0 +1,242 @@
1# PSO/shader cache
2
3One cache blob was found in the package data, stored as a single resource in the data area of a top-level RPF9
4archive. It is a chain of 4,205 adjacent zlib streams: 4,204 full 64 KiB streams and a 27,436-byte last one, with
531,437 bytes of zero padding between the streams. Concatenating the inflated bytes in archive order gives
6**275,540,780 bytes** (0x106C6B2C); the first stream starts at archive offset 0x10579000 and the chain is the last
7resource in the archive. This page describes that file; `tools/psocache_inspect.py` checks a carved copy of it.
8
9The blob is little-endian. In the tables, *measured* means the field's value and the region arithmetic were checked
10on this file. *Unproven* means the field is only located and described, not decoded.
11
12## Header
13
14The header is 0x80 bytes; the first 0x70 record of the next region starts exactly at 0x80.
15
16| Offset | Size | Value measured | Status |
17|---:|---:|---:|---|
18| 0x00 | 4 | `50 53 00 09` | magic `PS\0\x09`, measured |
19| 0x04 | 10 | NUL-terminated ASCII string | meaning unproven |
20| 0x24 | 11 | NUL-terminated ASCII string | meaning unproven |
21| 0x48 | 8 | 8 bytes | 8-byte value, meaning unproven |
22| 0x50 | 4 | 25,471 | count of the 0x70-byte records, measured; the "graphics PSO" role is inferred from the record shape, unproven |
23| 0x54 | 4 | 2,693 | count of the 0x18-byte records, measured; the "compute PSO" role is likewise inferred, unproven |
24| 0x58 | 4 | 54,576 | meta-index entries, measured (54,576 × 8 ends where the next region starts) |
25| 0x5c | 4 | 21,522 | shader-index entries, measured |
26| 0x60 | 4 | 31,120,020 | meta blob size, measured (the meta index covers exactly this) |
27| 0x64 | 4 | 240,894,464 | code blob size, measured (the last shader entry ends 24 bytes before it) |
28| 0x68 | 0x18 | zero | unused in this file |
29
30Two cross-checks tie the counts to the records. The u32 fields at +0x08, +0x0C and +0x50..+0x5C of the 0x70 records
31are 0xFFFFFFFF or below 54,576 (50,942 values that are not 0xFFFFFFFF, maximum 54,441). All 10,772 fields at
32+0x08..+0x14 of the 0x18 records are below 54,576 (maximum 54,575, the last meta-index entry). A wrong count or
33stride breaks both.
34
35## Regions
36
37| Region | Offset | Size | End |
38|---|---:|---:|---:|
39| header | 0x0 | 0x80 | 0x80 |
40| 0x70 records, 25,471 | 0x80 | 2,852,752 | 0x2B8810 |
41| 0x18 records, 2,693 | 0x2B8810 | 64,632 | 0x2C8488 |
42| meta index, 54,576 × 8 | 0x2C8488 | 436,608 | 0x332E08 |
43| shader index, 21,522 × 8 | 0x332E08 | 172,176 | 0x35CE98 |
44| meta blob | 0x35CE98 | 31,120,020 | 0x210A92C |
45| code blob | 0x210A92C | 240,894,464 | 0x106C6B2C |
46
47The regions are laid end to end and add up to the file size exactly:
48
49```
500x80 + 25,471 * 0x70 + 2,693 * 0x18 + 54,576 * 8 + 21,522 * 8 + 31,120,020 + 240,894,464
51 = 128 + 2,852,752 + 64,632 + 436,608 + 172,176 + 31,120,020 + 240,894,464
52 = 275,540,780 = 0x106C6B2C
53```
54
55## Indexes
56
57Both tables are arrays of `(u32 offset, u32 size)` pairs, 8 bytes per entry, relative to their blob.
58
59- Meta index: 54,576 entries over the meta blob. The first offset is 0 and each entry starts where the previous one
60 ends; the last ends at 31,120,020, so there is no gap, overlap or entry past the blob.
61- Shader index: 21,522 entries over the code blob, offsets strictly ascending and all distinct. The largest
62 `offset + size` is 0xE5BC1E8, 24 bytes before the declared code size 0xE5BC200.
63
64A shader-index entry is not one program. Counting `s_endpgm` inside each entry's range gives 16,992 entries with one,
654,508 with two, 21 with three or more, and one with none. The code blob holds 26,092 `s_endpgm` (0xBF810000) and
661,070,769 `s_code_end` (0xBF9F0000), and 21,463 of the 21,522 entries end on an `s_code_end` dword (58 end on a zero
67dword and one on another word). The run after the last `s_endpgm` is filler, so `s_code_end` is not a program
68terminator and the `s_endpgm` count does not equal the shader count. A whole-file marker scan also finds two
69`s_endpgm` words outside the code blob (one in the meta blob) and no `s_code_end`, so the marker count has to be
70bounded to the code region.
71
72## Meta blob
73
74The blob spans [0x35CE98, 0x210A92C) and is 31,120,020 bytes. A meta-index entry starts with a short header and, in
7520,318 of the 54,576 entries, continues with 32-byte chunks. The header length is the first multiple of 4 from 0 to
760x40 for which `(size - header) % 32 == 0` and every chunk's first dword is 0x41, 0x42 or 0x43. Measured headers:
770x10 on 17,634 entries, 0x14 on 2,684, 0x18 on 2,684 and 0x1c on 665. Another 3,349 entries fit that shape with zero
78chunks. The remaining 30,909 entries do not parse as chunk lists at all; their layout is not decoded here.
79
80| Chunk | Count | 32-byte body |
81|---|---:|---|
82| 0x41 | 402,328 | first dword 0x41, then seven dwords |
83| 0x42 | 371,387 | first dword 0x42, then seven dwords |
84| 0x43 | 20,318 | first dword 0x43, a 16-byte value, then 12 zero bytes (all 20,318) |
85
86The second dword of a 0x41 chunk takes six measured values. An external layout note names the first four; that
87mapping is not proven here.
88
89| Value | Count | Meaning |
90|---:|---:|---|
91| 0x300 | 289,590 | named SRV by the external note, unproven |
92| 0x302 | 46,186 | named CBV by the external note, unproven |
93| 0x303 | 11,328 | named UAV by the external note, unproven |
94| 0x002 | 13,897 | named sampler by the external note, unproven |
95| 0x401 | 33,596 | no name |
96| 0x100 | 7,731 | no name |
97
98The third dword of a 0x42 chunk takes 26 distinct values shaped like 0x000SSIIRR (0x00070001, 0x000D0201 and so on),
99which is consistent with space/index/register slots, but the fields are not decoded.
100
101## Meta records: what the chunks decode to
102
103The chunk lists have a fixed order: all 0x41 chunks, then all 0x42 chunks, then exactly one 0x43. That holds for
10420,318 of 20,318 records, so one record belongs to one stage. The decode below is measured shape plus an
105inference per field.
106
107### 0x41: user-data entries
108
109| Word | Role measured | Confidence |
110|---:|---|---|
111| +0 | 0x41 kind | high |
112| +4 | offset, always a multiple of 8, 0..0x820; zero for 0x2, 0x100 and 0x401 | high that it is 8-byte-granular; the table it points into is not identified |
113| +8 | key 0..0x1fd; repeats, 0 is common | low, it is not a unique binding id |
114| +0xc | count 0..0x800, 73 distinct for 0x300 | low |
115| +0x10 | three bytes: `a` (bits 16..31), `b` (bits 8..15), size (bits 0..7) | high on the split, meaning below |
116| +0x14 | 0xffffffff | measured |
117| +0x18 | 0 | measured |
118
119Per kind: 0x401 has offset 0, `b`=0, size 4 and `a`=1..24, consistent with a number of 32-bit constants
120(medium); 0x2 has offset 0, `b`=5..13 and size 4 (sampler-like, medium); 0x100 has offset 0, `b`=6..11 and
121size 2 (low); 0x300/0x302/0x303 carry the nonzero offsets, `b`=4..13, and size 4 or 8 (0x300, 0x303) or 4
122(0x302). Reading `b` as a register space and `a` as a base register for descriptors, or as a count for 0x401,
123fits the values but has no independent check (medium/low).
124
125### 0x42: register slots
126
127The slot splits as 0x00SS_IIRR: SS 1..16, II 0..3, RR 1..2. The slots follow the 0x41 descriptors in order. In
128the 5,230 records where their counts are equal, positional pairing gives II=0 for 23,047 of 23,049 0x300
129entries, II=1 for 4,144 of 4,146 0x303 entries and II=2 for all 6,100 0x302 entries. That is the order
130SRV=0, UAV=1, CBV=2 of D3D12_DESCRIPTOR_RANGE_TYPE, so II is probably the range type (medium-high). SS is
131probably a register space or table index (medium) and RR (1 or 2) a width (low).
132
133The 0x2 samplers and the 0x401 constants take no slot at all (0 of 13,897 and 0 of 33,596). Static samplers
134taking no user-data dwords matches the layer's contract in [d3d12_vulkan.md](d3d12_vulkan.md) 3.5 (medium-high).
135Another 15,068 records have more slots than descriptors, usually one or two; those extras all have RR=2, a
136zero key and w4=0, with (SS,II) mostly (14,3), (2,0) or (10,0). They are not decoded (low).
137
138### Relation to the 32 user-data dwords
139
140Within one record the cost is small: a graphics chunk record carries 11 constant dwords and one or two tables,
14115 dwords under two dwords per table. The 32-dword block is therefore the union of the tables and constants,
142not one dword per 0x41 entry (medium). The 0x41 offsets also exceed 128 bytes for half the entries (range
1430..0x820, 49.5% at or below 0x78), which fits a per-table descriptor index better than a dword offset. The
144records that do not fit are elsewhere: 4,519 of the 20,318 chunk records exceed 32 dwords under two dwords per
145table (4,202 under one), and none of them is on the graphics path. Of those 4,519, 1,017 are named by a compute
146PSO and the other 3,502 are not named by the graphics or compute records measured here. The extreme record has
147231 constant dwords; the largest slot count is 281. No mapping from a slot to a user-SGPR index was confirmed.
148
149### Which PSOs reference which records
150
151- A graphics PSO's u32 at +8 names a stage record (sizes 380..520) and +0xC an input-layout record; +0x50..+0x5C
152 are 0xFFFFFFFF in this corpus.
153- The stage record names chunk records at +4 (entry 4 on 13,409 PSOs, entry 6 on 12,062), at +0x2C (entry 2 on
154 25,469) and further at +0x78, +0x90, +0x150 and +0x1A4. Graphics PSOs share eight chunk records in total, not
155 one per PSO.
156- A compute PSO's +8 and +0xC name 20- and 28-byte hash records, +0x10 a mixed record and +0x14 a chunk record
157 (2,693 references, 2,684 distinct records).
158
159## Graphics user signature
160
161`tools/psocache_usersig.py` resolves a graphics PSO to its user data and prints, per chunk, the kind, register
162space, base register, count, element size and the slot bytes. A PSO uses 3 to 5 distinct chunk records after
163duplicates are removed (four on 23,625 of 25,471 PSOs); the eight layouts are shared across the corpus.
164
165| Chunk or field | Reading | Confidence |
166|---|---|---|
167| 0x300 / 0x302 / 0x303 | descriptor entries | high that they are descriptors, medium for the SRV/CBV/UAV names |
168| 0x002 | sampler entry, no slot | medium-high; none of the eight graphics records carries one |
169| 0x401 | 32-bit constants, `a` = count | medium |
170| 0x100 | unknown, not consumed | low |
171| 0x41 offset (w2) | descriptor index inside the table, 8-byte granular | medium |
172| 0x41 `b` | register space | medium |
173| 0x41 `a` | base register for descriptors | medium |
174| 0x41 size | element size 2, 4 or 8 | high |
175| 0x41 key (w3) | unknown | low |
176| 0x41 count (w4) | descriptor count | low |
177| 0x42 SS | descriptor-table / root-parameter index | medium-high |
178| 0x42 II | range type: 0 SRV, 1 UAV, 2 CBV, 3 sampler | medium-high |
179| 0x42 RR | width, 1 normally and 2 on extra slots | low |
180
181The kind-to-range-type correspondence is exact in the positional pairing: 23,047 of 23,049 0x300 entries sit on
182II=0, 4,144 of 4,146 0x303 on II=1 and all 6,100 0x302 on II=2. One distinct SS is read as one
183`D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE`, each (SS, II) pair as one `D3D12_DESCRIPTOR_RANGE`, and each 0x401
184as one `D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS`. That mapping is one-to-one for the measured graphics
185records, but it is an inference: SS could be a register space and `b` the table index instead, and the cache
186does not say whether a table costs one or two user-data dwords.
187
188Under both table models all 25,471 graphics PSOs fit 32 dwords (15 dwords with two per table). A later
189`CreateGraphicsPipelineState` path would group the slots by SS into tables, take II as the range type and the
1900x41 entries as the range contents, take each 0x401 as a constants parameter, and pack them in root-parameter
191order. The record does not carry that order, so it would have to come from SS or from the shader's reads, which
192is not measured.
193
194## What remains unknown
195
196- The meaning of the two header strings, the 0x48 value and the six 0x41 second-dword values. The SRV/CBV/UAV/sampler
197 names are the external note's, not this file's.
198- The `a` and `b` bytes of 0x41 w5 and the SS/II/RR meanings of the 0x42 slot word: the readings above are
199 inferences from value ranges and order, not confirmed by the shader code.
200- The encoding of the w3 key and w4 count, and the 15,068 records with extra slots.
201- The 0x43 16-byte value was not matched against any hash in the package.
202- The 30,909 meta entries that are not chunk lists.
203- Whether the code blob is raw RDNA2. The evidence is the two marker words and the `s_code_end` filler; no
204 disassembly or translation was run on this blob.
205
206## Checking and carving a copy
207
208`tools/psocache_extract.py` finds the cache in an RPF9 archive without the TOC: it walks the archive's stream
209table in order, inflates each stream to learn its extent, keeps only the first 4 bytes, and stops at the first
210stream whose output starts with the magic. It then appends the following contiguous streams (up to 1 MiB of zero
211padding) until the header's declared total is reached, writes the file under the temporary directory and runs
212the checks below. `--budget` bounds the compressed bytes examined and `--max-streams` the number of streams; a
213source folder is scanned in sorted order and the report names the archive index and the stream offset, never the
214path.
215
216```
217python -I tools/psocache_extract.py <archive.rpf|folder> <cache-in-tmp>
218```
219
220`tools/psocache_inspect.py` reads the cache file only:
221
222```
223python -I tools/psocache_inspect.py <cache> --meta
224```
225
226It checks the magic, reads the four counts and two sizes above, bounds all six regions against the file, checks that
227the meta index is contiguous over the meta blob and that every shader entry stays inside the code blob, parses the
228chunk lists and counts `s_endpgm` and `s_code_end` in the code blob. `--meta` adds the aggregate 0x41/0x42 decode
229described above, `--entry N` lists one meta index entry and `--limit N` bounds how many records `--meta` reads. It
230prints offsets, sizes and counts, names every field that does not fit instead of stopping, and exits 0 when the
231regions add up to the file size, 1 on a disagreement and 2 when the file is not a cache. `--json` prints the same
232report as JSON. It does not decode a chunk payload, disassemble the code or verify a hash.
233
234`tools/psocache_usersig.py` turns one or more graphics PSOs into the per-record user signature and the 32-dword
235fit described above:
236
237```
238python -I tools/psocache_usersig.py <cache> [--entry N] [--limit N] [--json]
239```
240
241It reuses the parser from `tools/psocache_inspect.py`, prints the aggregate over the first `--limit` graphics PSOs
242(all by default) or one PSO with `--entry N`, and never prints a hash.
diff --git a/docs/rbf0.md b/docs/rbf0.md
index 43ad49762..2a8629083 100644
--- a/docs/rbf0.md
+++ b/docs/rbf0.md
@@ -421,7 +421,8 @@ carry `descriptor`, `type`, `payload_offset`, `size` and `value`; text nodes car
421`--csv PATH` writes one flat row per node. The `parent` column is the parent element's byte offset, `slot` is 421`--csv PATH` writes one flat row per node. The `parent` column is the parent element's byte offset, `slot` is
422`attribute` or `content`, `sibling` is the index in that list, and `child_index` is the index among child elements; 422`attribute` or `content`, `sibling` is the index in that list, and `child_index` is the index among child elements;
423`attrs`, `children`, `content_count`, `type`, `length`, `nul`, `utf8` and `value` describe the node. The CSV is a 423`attrs`, `children`, `content_count`, `type`, `length`, `nul`, `utf8` and `value` describe the node. The CSV is a
424convenience view of the same structural tree, not a second parse. 424convenience view of the same structural tree, not a second parse. Use `source` (the starting filename) with
425`resource` (the archive offset) to group rows: two files in a carve directory can specify the same offset.
425 426
426XML is a rendering, not a round-trip; the JSON tree is the form that encodes back to bytes (9.6). Fixed tags avoid descriptor names that cannot be used as XML element names: 427XML is a rendering, not a round-trip; the JSON tree is the form that encodes back to bytes (9.6). Fixed tags avoid descriptor names that cannot be used as XML element names:
427`<node name="...">`, `<attr>`, `<value>` and `<text>`. A string containing XML markup is escaped by the writer. The 428`<node name="...">`, `<attr>`, `<value>` and `<text>`. A string containing XML markup is escaped by the writer. The
@@ -479,7 +480,9 @@ The 23 refused resources are exactly those that hold the 26 invalid UTF-8 text p
479occurs, and with them `--check` exits 1 on this corpus. So the tree loses no byte anywhere else: element words, attribute counts, descriptor order, value widths, 480occurs, and with them `--check` exits 1 on this corpus. So the tree loses no byte anywhere else: element words, attribute counts, descriptor order, value widths,
480float bits and NUL terminators all survive. The encoder also writes an edited tree, for example a JSON report 481float bits and NUL terminators all survive. The encoder also writes an edited tree, for example a JSON report
481changed by hand. It then checks each string and text against the recorded byte length when one is present, so a 482changed by hand. It then checks each string and text against the recorded byte length when one is present, so a
482change that alters a length needs that field dropped or updated. 483change that alters a length needs that field dropped or updated. Report-to-folder export also exits 1 if any resource is refused,
484even when it writes the valid resources; on the measured corpus it writes 1,240 resources and refuses 23.
485An export with no refusals exits 0.
483 486
484## 10. Reproduction 487## 10. Reproduction
485 488
diff --git a/docs/related_projects.md b/docs/related_projects.md
index 06f296981..df0c28c18 100644
--- a/docs/related_projects.md
+++ b/docs/related_projects.md
@@ -6,6 +6,21 @@ cannot be mixed with this repository. This page records what we may learn from e
6The rule is the same for every entry: **facts are fine; code is not.** A format layout, an ABI observation or a 6The rule is the same for every entry: **facts are fine; code is not.** A format layout, an ABI observation or a
7measured behaviour can be reimplemented independently. The source that expressed it cannot be copied. 7measured behaviour can be reimplemented independently. The source that expressed it cannot be copied.
8 8
9## ivall/xcl
10
11<https://github.com/ivall/xcl>
12
13An Xbox Series compatibility layer for Windows. It runs a title's x64 code natively and reimplements the console
14system libraries, in the spirit of Wine. It recompiles RDNA2 shaders to HLSL/DXIL instead of SPIR-V. Its README
15reports several retail titles as playable, and its design notes record measured facts relevant here: root-argument
16placement in user SGPRs, thread-group lane layout on PC drivers and GFX10 texture tiling.
17
18**Licence:** **GPL-2.0-only**, which is **incompatible with GPL-3.0-or-later**, as for americas-recomp below. **No
19code, tables or comments may be copied.**
20
21**What we use it for:** its measured facts only. Verify each one with Leonida's own census, a synthetic test or a
22public specification before relying on it. This repository never contains game data, so a fact XCL measured on a retail package is checked here with synthetic inputs or a contributor's own copy.
23
9## rpatty-dev/PercyStar 24## rpatty-dev/PercyStar
10 25
11<https://github.com/rpatty-dev/PercyStar> 26<https://github.com/rpatty-dev/PercyStar>
@@ -27,10 +42,21 @@ specification. Do not paste even a small function "to save time".
27 42
28A **GPL-2.0-only** fork of [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5), on its `xbox-series` branch. It 43A **GPL-2.0-only** fork of [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5), on its `xbox-series` branch. It
29recompiles the same Xbox Series shaders and has run the package's DLLs against a PC D3D12 device behind an Xbox-ABI 44recompiles the same Xbox Series shaders and has run the package's DLLs against a PC D3D12 device behind an Xbox-ABI
30proxy. 45proxy. Since 2026-11-22 its pull requests are limited to collaborators and its README points contributors here.
31 46
32**Licence:** GPL-2.0-only is **incompatible with GPL-3.0-or-later**. GPLv2-only code cannot be combined into a 47**Licence:** the repository is **GPL-2.0-only** (`LICENSE`), which is **incompatible with GPL-3.0-or-later**: GPLv2-only
33GPLv3 work, so **no code may be copied**, and there is no "just this one file" exception. 48code cannot be combined into a GPLv3 work, so none of it may be copied, and there is no "just this one file" exception.
49Since 2026-11-22 its `REUSE.toml` on `xbox-series` (commit `f1c25d72`) lists **88 files under MIT**, each relicensed with
50the agreement of everyone who wrote lines in it ([realdody/americas-recomp#179](https://github.com/realdody/americas-recomp/issues/179),
51still open, so the list can change): 35 files at the top of its tools/xbox directory, 30 in tools/xbox/platform (for
52example `xbox_dxil_lower.py`, `d3d12_xs.cpp`, `xmem.cpp`, `xbox_device_proxy.h`), one each under tools/xbox/msvc and
53tools/xbox/platform/xgr, its 20 tools/tests/test_xbox_*.py tests and its docs/xbox/BVH_CONTAINER.md. Everything else,
54including the recompiler in its core directory and the `xgameruntime` stand-in sources, stays GPL-2.0-only.
55
56**Rule until the maintainer decides:** **no americas-recomp code is copied into Leonida**, MIT-listed or not. MIT is
57compatible with GPL-3.0-or-later, so the listed files could be used the way `third_party/xtaskqueue` is (per file, only
58paths listed in `REUSE.toml` at the commit used, the MIT notice kept); whether Leonida does that is the maintainer's
59decision, not a contributor's.
34 60
35**What we use it for:** the measured ABI facts only. The useful findings are summarised in 61**What we use it for:** the measured ABI facts only. The useful findings are summarised in
36[d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi): the Xbox device entry point, the slot 62[d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi): the Xbox device entry point, the slot
@@ -99,6 +125,23 @@ lands), the IID/extension tables, and the call-sequence observations that Leonid
99[d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) still lists as unknown. SCARAB forwards to 125[d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) still lists as unknown. SCARAB forwards to
100D3D12; Leonida translates to Vulkan. The ABI facts carry over, the forwarding architecture does not. 126D3D12; Leonida translates to Vulkan. The ABI facts carry over, the forwarding architecture does not.
101 127
128## holdmysocks/SixNG
129
130<https://github.com/holdmysocks/SixNG>
131
132A Rust extractor for the same package: models, textures, map placements, collision, navmesh, the lane graph and
133audio, with format notes in its module headers.
134
135**Licence:** GPL-3.0, compatible with this project's GPL-3.0-or-later. As with SCARAB, **facts first**: nothing of
136it is copied here.
137
138**What we use it for:** two navmesh facts, read in `crates/sixng-core/src/navmesh.rs` at commit `0619601` and
139re-measured on this package by `tools/navmesh_nodes.py`
140([navmesh.md](navmesh.md#polygon-flags-under-the-lane-graph)): its label "road surface" for polygon `+0x18` bit
14113, which it bases on a visual check, and the vertex formula `tile minimum + u16 / 65535 * extent`. The formula is
142confirmed by the lane-graph heights. The label is consistent with the count, but not settled by it: nine in ten
143lane nodes stand on polygons with both bit 8 and bit 13, and which bit or combination means road surface is open.
144
102## microsoft/libHttpClient 145## microsoft/libHttpClient
103 146
104<https://github.com/microsoft/libHttpClient> 147<https://github.com/microsoft/libHttpClient>
diff --git a/docs/restofworld.md b/docs/restofworld.md
index e069e6025..ae2bb90c3 100644
--- a/docs/restofworld.md
+++ b/docs/restofworld.md
@@ -454,6 +454,19 @@ and a valid zlib checksum. That restores the normal draw binding. Both the
454diagnostic and the pinned model reader recover the containing dictionary's 11 454diagnostic and the pinned model reader recover the containing dictionary's 11
455children. 455children.
456 456
457`rpf9_carve.py` and the carved-folder model join use the same short final-system-page
458exception, so a carve retains that page and can reproduce the archive join. Unrelated
459streams still need at least 64 inflated bytes. When a carve has an `index.json`, the folder join uses its file list, offsets,
460compressed sizes and preceding bytes to check root alignment and zero padding just
461as the archive join does. An omitted stream between pages therefore interrupts the
462join. Extra files are ignored, and missing indexed files or size mismatches are errors.
463The index describes the original archive and cannot authenticate a same-size replacement
464payload. Without an index, folder mode still uses file order and inflated file sizes
465and can join across bytes the carver omitted.
466The folder reader follows the carver's file types: `.bin` contains an inflated zlib
467payload and `.bk2` contains raw video. A `KB2` prefix inside a `.bin` remains resource
468data, while a raw `.bk2` interrupts the model's continuation run.
469
457| Pointed-to group start relative to the target stream (original survey) | Blocks | 470| Pointed-to group start relative to the target stream (original survey) | Blocks |
458|---|---:| 471|---|---:|
459| Preceding stream | 68 | 472| Preceding stream | 68 |
@@ -708,6 +721,19 @@ Bit 30 set means `cross(normal, tangent)` runs along `+v`. The shaders turn a se
708which operand order they use was not traced here. The 8-bit form in core_restofworld fits least; 721which operand order they use was not traced here. The 8-bit form in core_restofworld fits least;
709this check does not say why. 722this check does not say why.
710 723
724An independent `data.rpf` sample says the tangent decode itself is not the weak part. On one mesh with all
725809 triangles usable, the decoded 8-bit vector pointed toward increasing UV0 U on **1,992 of 1,992** eligible
726corner uses; its median |dot| with the U tangent was **0.999598** (0.000025 with V and 0.027633 with the face
727normal), and permuting the candidate vectors within the same mesh lowers the U median to 0.697877. Four
728bit-31-clear resources from the first 12 qualifying ones in archive order gave **114 of 114** positive U
729comparisons (median +0.987002). Bit 30 agreed with the side of `dP/dv` that `cross(normal, tangent)` points
730to on **101 of 104** corner uses. All three exceptions are one indexed vertex whose five adjoining triangles
731have three negative and two positive UV determinants while its stored bit stays set; a single per-vertex bit
732cannot represent that vertex, so a consumer reconstructing a tangent frame should take handedness per
733triangle or accept that documented exception. This does not by itself explain the lower core_restofworld
7348-bit score above, whose per-block UV coverage was not measured here; the mixed-determinant vertex is one
735candidate.
736
711Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` record contents, the bodies of the 737Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` record contents, the bodies of the
712`RSC8` headers, the nested RPF9 payloads, and the whole `appdata0` data area. Across the 971 738`RSC8` headers, the nested RPF9 payloads, and the whole `appdata0` data area. Across the 971
713core graphics blocks, final-slot widths remain unresolved (`0x21`, the last unread component type, 739core graphics blocks, final-slot widths remain unresolved (`0x21`, the last unread component type,
diff --git a/docs/retail_boot_chain.md b/docs/retail_boot_chain.md
new file mode 100644
index 000000000..f46c698b9
--- /dev/null
+++ b/docs/retail_boot_chain.md
@@ -0,0 +1,102 @@
1# The retail boot chain: what stops `gta6rt --run`, in order
2
3**Status: measured on one machine, 2026-11-23. A measurement for RT-5, not a claim; RT-5 stays with its owners
4on the coordination issue.** Each row is the first failure with every fix above it in place. Nothing here quotes
5the executable: no addresses, offsets, IID values or bytes; only export names, public SDK types, vtable slot
6numbers, call shapes and counts. [boot.md](boot.md) has the runbook that produced the traces; #6715 maps the same
7executable under `--dry-run`.
8
9Setup: `main` `1cc6e3c12` with #6709, #4531, #6582, #4313, #4348 and #2490 merged locally, plus the local
10stand-ins named below (not pull requests yet). Own 1.0.2.1 copy, Windows 11, RTX 4090 (driver 617.42),
11`LEONIDA_D3D12=vulkan`, MSVC 2022 `RelWithDebInfo` build.
12
13## 1. The chain
14
15| # | Stop | What clears it |
16|---|---|---|
17| 1 | The first `XMemVirtualAlloc` calls: two 64 KiB reserve forms, then 2 MiB pages | #6709, #4531 |
18| 2 | The 2 MiB reserve+commit calls carry attribute words the shim refuses, and `PAGE_GRAPHICS_*` bits (0x800..0x40000) on top of `PAGE_READWRITE` | Local: accept the attribute word, drop the graphics bits and keep the CPU protection. All seven startup allocations then succeed. #6843 measures the attribute words; no PR changes the check yet |
19| 3 | `xgameruntime.lib`'s thunk treats a missing `XErrorReport` as fatal | #6582 |
20| 4 | Access violation in the title's allocator: its `/GA` code reads its TLS from module index 0 | #4313 |
21| 5 | Fatal assert when `DStorageGetFactory` returns null | #4348 |
22| 6 | `XMemAllocatePhysicalPages` unimplemented; the title asserts on FALSE | Local stand-in, §2 |
23| 7 | `D3D12XboxCreateDevice` succeeds; device slot 26 is called with its arguments swapped | Local, §3.1 |
24| 8 | Device slot 48 is forwarded to the PC slot 48 and fails | Local, §3.2 |
25| 9 | Device slot 73 is forwarded to the PC slot 73; the title then reads through a null list | #2490's list proxy plus local routing, §3.3 |
26| 10 | An `XMemVirtualAlloc` reserve of about 185 MiB with type `0x42000`, attribute 7 and `PAGE_NOACCESS` is refused with `ERROR_INVALID_PARAMETER`. `0x40000` is `MEM_RESERVE_PLACEHOLDER` on the PC, which `VirtualAlloc` refuses and only `VirtualAlloc2` accepts; stop 11 supports the same reading on the console | Local: reserve it with `VirtualAlloc2(MEM_RESERVE \| MEM_RESERVE_PLACEHOLDER)` |
27| 11 | The title carves five sub-ranges out of that placeholder with `MEM_RESERVE \| MEM_REPLACE_PLACEHOLDER \| MEM_PHYSICAL \| MEM_LARGE_PAGES` (`0x20406000`) at addresses inside it, then allocates a second batch of physical pages | Local: a physical reserve inside a known placeholder stays a placeholder (the page maps split it); other `MEM_REPLACE_PLACEHOLDER` calls split the range and allocate it in place |
28| 12 | Device slot 133 is called; the proxy table had 128 slots, so the call went through a null pointer | Local: a 192-slot table, and a slot 133 stand-in, §3.4 |
29| 13 | **Current stop**: right after the first `CreateDescriptorHeap`, the title calls the heap's slot 9 (`GetCPUDescriptorHandleForHeapStart` on the PC), takes the handle from `rax` and asserts that it equals a value it already holds. Hypothesis: a console descriptor heap starts at an address the title chose or can predict, which the PC handle doesn't match | Open: a question for the descriptor model ([boot.md](boot.md) Q4) |
30
31At stop 13 the D3D12 trace holds 1,185 calls: the device, 5 command queues, 5 fences, 7 command allocators,
32581 command lists created and closed, a shader cache session, `XboxIDXGIDevice::GetAdapter`, one failed
33`ID3D12Device10::CreateReservedResource2`, the first `CreateSampler2`, one committed resource (the slot 133
34stand-in) and the first descriptor heap.
35
36Without a debugger, the unhandled `int3` of a fatal assert ends the process with `C0000374` (heap corruption) or
37`C0000005` during teardown, not `80000003`. An exit code of `C0000374` from `--run` can be such an assert, not a
38heap bug.
39
40## 2. Physical pages (`xmem.dll`)
41
42The shapes, from the call sites and the checks that follow them:
43
44| Export | Shape |
45|---|---|
46| `XMemAllocatePhysicalPages` | `BOOL (ULONG64 attributes, ULONG_PTR* page_count /*in/out, 64 KiB pages*/, ULONG_PTR* page_array)`; the title checks both TRUE and the count written back. Attributes seen: `0x280`, `0x380` |
47| `XMemVirtualAlloc` | the range for those pages is reserved with `MEM_RESERVE \| MEM_PHYSICAL \| MEM_LARGE_PAGES` (`0x20402000`) and no `MEM_COMMIT` |
48| `XMemMapPhysicalPages` | `(va, page_count, page_array)`; a null `page_array` unmaps; non-null return on success |
49| `XMemMapPhysicalPagesScatter` | `(va_array, page_count, page_array)`, the same with one VA per page |
50| `XMemFreePhysicalPages` | `(page_count, page_array)` |
51
52The local stand-in that gets past stop 6 is CPU-only: one pagefile section per 64 KiB page
53(`CreateFileMappingW(INVALID_HANDLE_VALUE, …, SEC_COMMIT)`), page numbers handed out as indexes into that table,
54the physical reserve made with `VirtualAlloc2(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)`, each map a
55`VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` split followed by `MapViewOfFile3(MEM_REPLACE_PLACEHOLDER)`,
56and each unmap `UnmapViewOfFile2(MEM_PRESERVE_PLACEHOLDER)`. #5381 has the CPU half of physical pages with dirty
57tracking and #5378 a Vulkan sparse-binding mapper; neither is wired to these exports.
58
59## 3. Device calls whose Xbox shape differs from the PC
60
61### 3.1 Struct-returning methods take the return buffer first
62
63Device slot 26 (`GetCustomHeapProperties`, which returns a `D3D12_HEAP_PROPERTIES`) is called as
64`(return buffer, this, node_mask, heap_type)`: the first register holds the return buffer, the second the device
65proxy. The PC MSVC method expects `(this, return buffer, …)`. A proxy thunk can tell the two apart: in the swapped
66call the `this` register does not point at the proxy, and the second argument does. Calling the real method with
67the two exchanged and returning the buffer pointer gets past it. Other struct-returning slots probably follow the
68same rule; only slot 26 was reached.
69
70### 3.2 Device slot 48 creates a command queue
71
72Xbox device slot 48 is `(desc, riid, out)` with `riid = IID_ID3D12CommandQueue`. `desc` starts with a PC
73`D3D12_COMMAND_QUEUE_DESC` (Type, Priority, Flags, NodeMask) followed by Xbox words. On the PC, slot 48 is
74`OpenExistingHeapFromAddress`, so forwarding by number fails. Creating the queue from the 16-byte PC prefix, with
75`Flags` limited to `D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT`, through the existing queue proxy works: four
76queues come from this slot, the first of them a compute queue. The first queue comes from slot 8, as on the PC.
77
78### 3.3 Device slot 73 creates a command list
79
80Xbox device slot 73 is `(desc, allocator, pso, riid, out)`. `desc` is 16 bytes and its first word reads as the
81`D3D12_COMMAND_LIST_TYPE`. `riid` is a console command-list IID that is not in the PC SDK (#3520 records that the
82package doesn't export it). The shim's unknown-IID log names it on the player's machine. Creating an
83`ID3D12GraphicsCommandList` of that type and handing out #2490's console list
84proxy gets all 581 lists created and closed.
85
86### 3.4 Device slot 133 places a resource at a virtual address
87
88Xbox device slot 133 is `(va, const D3D12_RESOURCE_DESC*, state, clear, riid, out)` with `riid = IID_ID3D12Resource`
89and `state = 0xFFFFFFFF`, which isn't a valid PC state. At the first call, `va` is the start of a physical-page
90range the title had just reserved, and `desc` is a buffer of that range's size with Xbox bits in `Flags` above
91the PC flags. The shape matches the console `CreatePlacedResourceX`. The local stand-in creates a committed
92DEFAULT-heap buffer from the desc, with `Flags` limited to the PC bits and `D3D12_RESOURCE_STATE_COMMON`. It is
93not tied to the VA, so what the title writes there doesn't reach the GPU. A real implementation needs the page
94mapper (#5378) or an imported host allocation.
95
96The proxy's slot table must also be longer than the title's highest slot. A shorter table leaves a null pointer,
97not an `E_NOTIMPL`.
98
99## 4. What this does not show
100
101These are one run's first failures, not a list of what is missing. Every stand-in above is local and untested
102beyond "the title goes on to the next call". Nothing has reached a draw or a present yet.
diff --git a/docs/rpf.md b/docs/rpf.md
index a72fc55d6..7bc656845 100644
--- a/docs/rpf.md
+++ b/docs/rpf.md
@@ -157,12 +157,32 @@ both paths. It is used to check exported assets without keeping a second copy.
157of each zlib stream and indexes the measured `name.#dr`/`#ft`/`#dd` spellings with their archive offsets. It 157of each zlib stream and indexes the measured `name.#dr`/`#ft`/`#dd` spellings with their archive offsets. It
158does not decode a resource or need the TOC; see [resource_names.md](resource_names.md). 158does not decode a resource or need the TOC; see [resource_names.md](resource_names.md).
159 159
160### The trailer at EOF
161
162The header's `u32 +12` is the size of a block that ends the file: the last `+12` bytes of an RPF9 are not part of
163any stored file (ASSET-318, measured on the 22 RPF9 archives of the 1.0.2.1 package, offsets and counts only).
164`+12` is a multiple of 16 in all 22 (64 to 119,520 bytes); `+8` is always larger than `+12` except in `levels.rpf`
165and `core_bvh4.rpf`, and its role is not established.
166
167| Evidence | Archives |
168|---|---|
169| The data before it ends in zeros up to a 4 KiB boundary, and exactly `+12` non-zero bytes follow to EOF | 10: `anim`, `audio`, `common`, `data`, `levels`, `movies`, `packs`, `shared_minigame000`, `story000`, `core_bvh4` |
170| Files are packed at 16-byte alignment; walking the zlib streams to the end leaves exactly `+12` bytes after the last one | 4: `core_licenses_data`, `core_restofworld`, `shared_minigame000_bvh4`, `story000_bvh4` |
171| Undecided: the last stored file is not zlib (or the walk stops at a non-zlib file), so its end is not known without the TOC | 8: `appdata0`, `navmeshes`, `script`, `shaders`, `textures`, `core_restofworld001`, `story000_script`, `story000_restofworld` |
172
173No archive contradicts the rule, but 8 don't test it. In the 14, the trailer starts with no zlib or Bink 2 header and is
174high-entropy like the TOC after the header: 7.95 to 8.00 bits per byte in the nine of 3 KiB or more, and 6.6 to 7.9
175in the five smaller ones (random 144-byte blocks average about 6.7); what they hold is not
176decoded here. `tools/bink_index.py` counts it as `rpf_trailer` instead of unread bytes, only for an `RPF9` header
177whose `+12` is a multiple of 16 and fits in the tail after the last stream; in `movies.rpf` it is the
17818,928 bytes after 3,884 zeros that [movies.md](movies.md) listed as unread.
179
160### Viewing a header in ImHex 180### Viewing a header in ImHex
161 181
162[tools/imhex/rpf9.hexpat](../tools/imhex/rpf9.hexpat) is a pattern for the [ImHex](https://imhex.werwolv.net/) hex 182[tools/imhex/rpf9.hexpat](../tools/imhex/rpf9.hexpat) is a pattern for the [ImHex](https://imhex.werwolv.net/) hex
163editor. It names the magic and the data offset at `+4`, shows the u32s at `+8` and `+12` unnamed, and shows the range 183editor. It names the magic, the data offset at `+4` and the trailer size at `+12`, shows the u32 at `+8` unnamed,
164from `+0x10` to the data offset (the rest of the header and the TOC) as one opaque byte array. It decodes nothing in 184and shows the range from `+0x10` to the data offset (the rest of the header and the TOC) as one opaque byte array.
165that range. `python -I tests/test_imhex_patterns.py` runs it on a synthetic header when ImHex is installed. 185It decodes nothing in that range. `python -I tests/test_imhex_patterns.py` runs it on a synthetic header when ImHex is installed.
166 186
167## Limits 187## Limits
168 188
diff --git a/docs/rsc8_audio.md b/docs/rsc8_audio.md
index 68a1b70d1..2a5766207 100644
--- a/docs/rsc8_audio.md
+++ b/docs/rsc8_audio.md
@@ -158,8 +158,8 @@ The name word is 0 on 96 records (78 tags start with one); what a nameless recor
158 `0xE5C74063` (418,838 records, 402,357 of them on speech streams with a `0x5c` clip) and `0xdbedd43c` (330,756, 158 `0xE5C74063` (418,838 records, 402,357 of them on speech streams with a `0x5c` clip) and `0xdbedd43c` (330,756,
159 all on such streams and all with `extra = 0`) are not known. 159 all on such streams and all with `extra = 0`) are not known.
160- **`value`** is a whole number stored as `f32` on every record of those six names. On five of the other names it 160- **`value`** is a whole number stored as `f32` on every record of those six names. On five of the other names it
161 is `joaat("start")` or `joaat("end")` in equal or near-equal numbers (196/197, 101/101, 54/54, 49/49, 20/19), 161 is `joaat("start")` (`0x84dc271f`) or `joaat("end")` (`0xb0c485d7`). Matched record by record, 418 of the 420
162 which reads as region start/end pairs (hypothesis: the split was counted, not matched record by record). 162 `start` records are followed by their `end`; see [Region cues](#region-cues-start-and-end-records).
163- The same reference states that an AWC tag id is the low byte of the joaat of the chunk name. That holds for 163- The same reference states that an AWC tag id is the low byte of the joaat of the chunk name. That holds for
164 `markers` (`0xbd`), `data` (`0x55`), `peak` (`0x36`), `seektable` (`0xa3`) and `streamformat` (`0x48`), which 164 `markers` (`0xbd`), `data` (`0x55`), `peak` (`0x36`), `seektable` (`0xa3`) and `streamformat` (`0x48`), which
165 `tests/test_rsc8_audio.py` checks, and by the same rule `0x5a` and `0xd9` are `granulargrains` and 165 `tests/test_rsc8_audio.py` checks, and by the same rule `0x5a` and `0xd9` are `granulargrains` and
@@ -167,6 +167,60 @@ The name word is 0 on 96 records (78 tags start with one); what a nameless recor
167 `stream_format`, and with the underscore the rule fails (`0xb8` and `0xf9`). It does not hold for `0x5c`, 167 `stream_format`, and with the underscore the rule fails (`0xb8` and `0xf9`). It does not hold for `0x5c`,
168 `0x76` and `0xb2` under the names `animation`, `format` and `metadata` either, so those three names stay open. 168 `0x76` and `0xb2` under the names `animation`, `format` and `metadata` either, so those three names stay open.
169 169
170#### Region cues: `start` and `end` records
171
172The five names whose `value` is the hash of `start` or `end` have 841 records in 22 tags of `audio.rpf`: 420
173`start`, 420 `end` and one with a third value. An earlier version of this page read the near-equal counts per name
174(196/197, 101/101, 54/54, 49/49, 20/19) as region pairs without matching them. `tools/rsc8_audio.py` now matches
175them (`pair_marker_regions`, the `marker_regions` block of every scan summary): inside one tag it takes the
176records of one name in stored order, and a pair is a `start` whose next record of the same name is an `end` at the
177same or a later offset. Every other record of such a name is counted as an exception.
178
179| Name | Tags | `start` | `end` | Pairs | Not paired | Pair length in samples (min / median / max) |
180|---|---:|---:|---:|---:|---|---:|
181| `0xda559149` | 22 | 196 | 197 | 196 | 1 `end` | 172,602 / 857,823 / 3,899,077 |
182| `0x1df219ec` | 1 | 101 | 101 | 101 | none | 25,289 / 95,237 / 497,606 |
183| `0x77edd3a2` | 1 | 54 | 54 | 53 | 1 `start`, 1 `end`, the record with the third value | 44,984 / 90,546 / 209,958 |
184| `0x994ee645` | 1 | 49 | 49 | 49 | none | 22,233 / 93,644 / 212,156 |
185| `0xccb465d1` | 1 | 20 | 19 | 19 | 1 `start` | 36,146 / 92,928 / 186,375 |
186| **Total** | **22** | **420** | **420** | **418** | **5 records** | |
187
188So the reading holds for 418 pairs, and equal counts did not prove it: the 54/54 name has two unpaired records.
18920 of the 22 tags pair completely (a tag holds 1 to 181 pairs, median 3). The five exceptions sit in two tags:
190
191- `0xda559149` has a second `end` 16,717 samples after the `end` that closes the region before it (record 744 of
192 its tag's 1,435). Nothing opens it.
193- A `0x77edd3a2` `start` (record 40 of 834) is followed, 118,171 samples later, by a record of the same name whose
194 value is `0xdaa2d5ec`, the only value on these names that is neither word. Hypothesis: that record closes the
195 region under another word; the distance is inside the name's pair lengths.
196- A `0xccb465d1` `start` (record 773 of the same tag, the last record of its name) is directly followed by a
197 `0x77edd3a2` `end` that no `start` opens (record 774), 114,697 samples later. Hypothesis: one region whose two
198 records carry different names; the distance is inside the pair lengths of both.
199
200If both hypotheses hold, every one of the 420 `start` records has a closing record and only the second `end`
201is left over. None of the five is a region left open at an edge of its tag: none is the tag's first or last
202record, the nearest to an edge is 40 records in, and the unclosed `0xccb465d1` `start` is 18,219,408 samples
203before its tag's last offset.
204
205Also measured on the 418 pairs:
206
207- No pair has a zero length, and `extra` is the same on a pair's two records (418 / 418).
208- Regions of one name cannot overlap under this matching; an overlap would show as an unpaired `start` followed
209 by a `start`, and there is none. Regions of different names do overlap: 54 pairs of regions share samples, 43
210 with one region inside the other and 11 crossing (each starts or ends inside the other). All 54 are between
211 `0xda559149` and one of the other four names (`0x1df219ec` 13 inside / 7 crossing, `0x77edd3a2` 19 / 4,
212 `0x994ee645` 2 / 0, `0xccb465d1` 9 / 0); the other four never overlap each other. So a sample can lie in
213 regions of two names at once.
214- None of the 22 streams has a `0x76` tag (`tags_with_sample_count` is 0), so this parser has no sample count to
215 compare a region's end with.
216
217The other three archives with `ADAT` banks have `0xbd` tags as well (226,788 in `story000.rpf`, 1,959 in
218`shared_minigame000.rpf`, 22 in `story000_restofworld.rpf`) and not one record with either value.
219
220Not known: the words behind the five names and behind `0xdaa2d5ec`, what a region does in the game, and whether
221the two hypotheses above are right. The lengths are in the unit of `offset`; they were not converted to seconds,
222because the rate of these 22 streams is not read here.
223
170## Binary format of `RSC8` (version `8001`) 224## Binary format of `RSC8` (version `8001`)
171 225
172All integers and IEEE-754 floats are little-endian. Every `RSC8` tag payload is 16-byte aligned. 226All integers and IEEE-754 floats are little-endian. Every `RSC8` tag payload is 16-byte aligned.
@@ -368,6 +422,10 @@ python -I tools/rsc8_audio.py <package>\pack\shared_minigame000\shared_minigame0
368python -I tools/rsc8_audio.py <package>\pack\story000\story000.rpf --summary-only 422python -I tools/rsc8_audio.py <package>\pack\story000\story000.rpf --summary-only
369python -I tools/rsc8_audio.py <package>\audio.rpf --summary-only 423python -I tools/rsc8_audio.py <package>\audio.rpf --summary-only
370 424
425# Every summary also has the cue counts (marker_* keys) and the region pairing (marker_regions): pairs and
426# exceptions per name hash, pair lengths, overlaps between names and where each exception sits in its tag.
427# The numbers of "Region cues" above are the audio.rpf summary's (57 to 87 s over three runs of the 28.5 GB archive).
428
371# Also decode every clip's keyframes and count the outcome (slower: about 40 clips per second per process; 429# Also decode every clip's keyframes and count the outcome (slower: about 40 clips per second per process;
372# split a large archive with --start/--limit and add the summaries) 430# split a large archive with --start/--limit and add the summaries)
373python -I tools/rsc8_audio.py <package>\pack\shared_minigame000\shared_minigame000.rpf --summary-only --curves 431python -I tools/rsc8_audio.py <package>\pack\shared_minigame000\shared_minigame000.rpf --summary-only --curves
diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md
index 0a0daa17b..934dae376 100644
--- a/docs/runtime_imports.md
+++ b/docs/runtime_imports.md
@@ -4,9 +4,10 @@
4registry or the host, and prints a report. It does **not** call `DllMain`, TLS callbacks or the entry point, so 4registry or the host, and prints a report. It does **not** call `DllMain`, TLS callbacks or the entry point, so
5this page measures mapping and binding only; it does not claim the modules work. 5this page measures mapping and binding only; it does not claim the modules work.
6 6
7The game executable is still missing from the package available here. Every other PE that the package ships is 7The game executable is not in the package. Every other PE that the package ships is present, and all of them are
8present, and all of them are Xbox Series builds. Running the dry-run over those images is the closest thing to a 8Xbox Series builds. Running the dry-run over those images is the closest thing to a loader test that does not need
9loader test that does not need the executable. 9the executable; [The retail executable](#the-retail-executable-rt-5) below is the dry-run over the executable
10itself, supplied separately.
10 11
11## Reproduce 12## Reproduce
12 13
@@ -22,10 +23,13 @@ runtime\build\gta6rt.exe --dry-run "$game\XboxBvhBuilder.dll" --game-dir $game
22Each run prints one line per mapped module: 23Each run prints one line per mapped module:
23 24
24``` 25```
25XboxBvhBuilder.dll base=0000000180000000 size=909312 entry=+0x227cc shim=2 host=55 module=0 unimplemented=0 26XboxBvhBuilder.dll base=0000000180000000 size=909312 entry=+0x227cc shim=4 host=53 module=0 unimplemented=0
26 shim d3d12_xs.dll!D3D12SerializeVersionedRootSignature 27 shim d3d12_xs.dll!D3D12SerializeVersionedRootSignature
27 shim xmem.dll!XMemVirtualQuery 28 shim xmem.dll!XMemVirtualQuery
29 shim api-ms-win-crt-runtime-l1-1-0.dll!_configure_narrow_argv
30 shim api-ms-win-core-libraryloader-l1-2-0.dll!DisableThreadLibraryCalls
281 module(s) mapped, 0 unimplemented import(s) 311 module(s) mapped, 0 unimplemented import(s)
32unimplemented by return policy: hresult=0 other=0
29``` 33```
30 34
31`shim` counts imports served by the clean-room tables, `host` counts imports served by the desktop DLLs, 35`shim` counts imports served by the clean-room tables, `host` counts imports served by the desktop DLLs,
@@ -33,30 +37,45 @@ XboxBvhBuilder.dll base=0000000180000000 size=909312 entry=+0x227cc shim=2 hos
33 37
34## Measured result 38## Measured result
35 39
36All 16 DLLs in the package map at their preferred base `0x180000000` with no relocation, and every import binds: 40All 16 DLLs in the package map at their preferred base `0x180000000` with no relocation, and every import binds. `gta6rt --init` on each one also runs its TLS callbacks and `DllMain` and exits 0 (counts re-measured with `--dry-run` and `--init` on `main` `aa2988cc`, Windows 11):
37 41
38| Image | Size of image | Entry RVA | Shim | Host | Module | Unimplemented | 42| Image | Size of image | Entry RVA | Shim | Host | Module | Unimplemented | `--init` |
39|---|---:|---:|---:|---:|---:|---:| 43|---|---:|---:|---:|---:|---:|---:|---|
40| `Bink2Scarlett.dll` | 278,528 | `0x2ac1c` | 3 | 57 | 0 | 0 | 44| `Bink2Scarlett.dll` | 278,528 | `0x2ac1c` | 4 | 56 | 0 | 0 | exit 0 |
41| `XboxBvhBuilder.dll` | 909,312 | `0x227cc` | 4 | 53 | 0 | 0 | 45| `XboxBvhBuilder.dll` | 909,312 | `0x227cc` | 4 | 53 | 0 | 0 | exit 0 |
42| `amd_fidelityfx_upscaler_xbox.dll` | 802,816 | `0x26780` | 6 | 80 | 0 | 0 | 46| `amd_fidelityfx_upscaler_xbox.dll` | 802,816 | `0x26780` | 6 | 80 | 0 | 0 | exit 0 |
43| `amd_fidelityfx_loader_xbox.dll` | 32,768 | `0x18d0` | 5 | 17 | 0 | 0 | 47| `amd_fidelityfx_loader_xbox.dll` | 32,768 | `0x18d0` | 5 | 17 | 0 | 0 | exit 0 |
44| `libHttpClient.GDK.dll` | 999,424 | `0x11f0` | 11 | 187 | 0 | 0 | 48| `libHttpClient.GDK.dll` | 999,424 | `0x11f0` | 26 | 172 | 0 | 0 | exit 0 |
45| `XCurl.dll` | 188,416 | `0x17b0` | 9 | 131 | 0 | 0 | 49| `XCurl.dll` | 188,416 | `0x17b0` | 24 | 116 | 0 | 0 | exit 0 |
46| `concrt140.dll` | 303,104 | `0x29160` | 2 | 101 | 0 | 0 | 50| `concrt140.dll` | 303,104 | `0x29160` | 2 | 101 | 0 | 0 | exit 0 |
47| `msvcp140.dll` | 577,536 | `0x525a0` | 9 | 178 | 0 | 0 | 51| `msvcp140.dll` | 577,536 | `0x525a0` | 13 | 174 | 0 | 0 | exit 0 |
48| `msvcp140_1.dll` | 36,864 | `0x15c0` | 2 | 31 | 0 | 0 | 52| `msvcp140_1.dll` | 36,864 | `0x15c0` | 2 | 31 | 0 | 0 | exit 0 |
49| `msvcp140_2.dll` | 192,512 | `0x1efa0` | 2 | 94 | 0 | 0 | 53| `msvcp140_2.dll` | 192,512 | `0x1efa0` | 2 | 94 | 0 | 0 | exit 0 |
50| `msvcp140_atomic_wait.dll` | 81,920 | `0x3c80` | 4 | 60 | 0 | 0 | 54| `msvcp140_atomic_wait.dll` | 81,920 | `0x3c80` | 4 | 60 | 0 | 0 | exit 0 |
51| `msvcp140_codecvt_ids.dll` | 28,672 | `0x1340` | 2 | 22 | 0 | 0 | 55| `msvcp140_codecvt_ids.dll` | 28,672 | `0x1340` | 2 | 22 | 0 | 0 | exit 0 |
52| `vccorlib140.dll` | 344,064 | `0x27e50` | 7 | 107 | 0 | 0 | 56| `vccorlib140.dll` | 344,064 | `0x27e50` | 7 | 107 | 0 | 0 | exit 0 |
53| `vcomp140.dll` | 86,016 | `0x6580` | 7 | 71 | 0 | 0 | 57| `vcomp140.dll` | 86,016 | `0x6580` | 7 | 71 | 0 | 0 | exit 0 |
54| `vcruntime140.dll` | 110,592 | `0xf890` | 3 | 38 | 0 | 0 | 58| `vcruntime140.dll` | 110,592 | `0xf890` | 3 | 38 | 0 | 0 | exit 0 |
55| `vcruntime140_1.dll` | 49,152 | `0x3e90` | 1 | 33 | 0 | 0 | 59| `vcruntime140_1.dll` | 49,152 | `0x3e90` | 1 | 33 | 0 | 0 | exit 0 |
56 60
57Since the library-loader shims (`runtime/shims/library_loader.cpp`), a module's `LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress` and `FreeLibrary` imports count as shim, through `kernel32`, `kernelbase` or the `api-ms-win-core-libraryloader-*` set it names. That is why every image above has a few more shim and fewer host imports than before; the Xbox-specific imports below are unchanged. `DisableThreadLibraryCalls` is served the same way: a mapped module gets `TRUE` (the real function refuses a module the Windows loader did not map, which failed the `DllMain` of the four `msvcp140_*` satellite DLLs), and any other handle goes to the real function. 61Since the library-loader shims (`runtime/shims/library_loader.cpp`), a module's `LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress` and `FreeLibrary` imports count as shim, through `kernel32`, `kernelbase` or the `api-ms-win-core-libraryloader-*` set it names. That is why every image above has a few more shim and fewer host imports than before; the Xbox-specific imports below are unchanged. `DisableThreadLibraryCalls` is served the same way: a mapped module gets `TRUE` (the real function refuses a module the Windows loader did not map, which failed the `DllMain` of the four `msvcp140_*` satellite DLLs), and any other handle goes to the real function.
58 62
59The process shim (`runtime/shims/process.cpp`) serves `ExitProcess` and `GetCommandLineA/W` the same way: through `kernel32`, `kernelbase`, and `api-ms-win-core-processthreads-l1-1-0` and `api-ms-win-core-processenvironment-l1-1-0`, the sets the API-set umbrella libraries (`OneCore_apiset.lib`, `mincore.lib`) bind them to. `vcomp140.dll` imports `ExitProcess` from the first of these. The UCRT's `_get_narrow_winmain_command_line` and `_get_wide_winmain_command_line` are served too, so a `WinMain` executable gets the game's command line as `lpCmdLine`. The table above is `gta6rt --dry-run` on each DLL at the commit that added this paragraph. 63The process shim (`runtime/shims/process.cpp`) serves `ExitProcess` and `GetCommandLineA/W` the same way: through `kernel32`, `kernelbase`, and `api-ms-win-core-processthreads-l1-1-0` and `api-ms-win-core-processenvironment-l1-1-0`, the sets the API-set umbrella libraries (`OneCore_apiset.lib`, `mincore.lib`) bind them to. `vcomp140.dll` imports `ExitProcess` from the first of these. The UCRT's `_get_narrow_winmain_command_line` and `_get_wide_winmain_command_line` are served too, so a `WinMain` executable gets the game's command line as `lpCmdLine`. `abort()` raises `SIGABRT` when the guest installed a handler (the guest's `signal()` import binds to the host CRT, so its table is the one raised here); with the default or ignore disposition, or a handler that returns, the run still ends with code 3. `run_tiny_game_abort_exit_codes` compares that with a native run of the stand-in image. The table above is `gta6rt --dry-run` on each DLL at the commit that added this paragraph.
64
65The shims added since account for the rest of the difference from the first version of the table. The UCRT's `_configure_narrow_argv`, `_configure_wide_argv`, `__p___argc`, `__p___wargv` and `abort` are served by `runtime/shims/process.cpp`, which is why almost every DLL gained one or two. The file-system calls listed in *Console paths and the write overlay* below (`CreateFile2`, `CopyFile2`, `CreateDirectoryW`, `FindFirstFileExW`, `SetFileAttributesW` and the rest) account for `msvcp140.dll`, `vcomp140.dll`, `Bink2Scarlett.dll`'s `CreateFile2` and part of the two HTTP clients. `winhttp.dll` is a module the shims own (*WinHTTP offline* below), so every `WinHttp*` import binds to it: 15 in `libHttpClient.GDK.dll` (all 16 but `WinHttpCrackUrl`) and 15 in `XCurl.dll` (all but `WinHttpQueryOption`). That is why the two HTTP clients moved the most: 11 to 26 and 9 to 24 shim imports.
66
67The UCRT argv configuration imports honor the executable's startup mode. Each run starts with `argc == 0` and
68null narrow/wide argument tables, while `GetCommandLineA/W` is already available to TLS and process-attach
69callbacks. Default startup publishes unexpanded arguments for its chosen width. `setargv.obj` / `wsetargv.obj`
70startup expands wildcard arguments against the host working directory, including quoted patterns; an unmatched
71pattern stays literal. Narrow expansion searches the ACP-converted pattern and converts matching names back to
72ACP, so its matches can differ from wide startup. The two widths retain independent tables, and the most recently
73configured width sets the shared `argc`. `noarg.obj` leaves the initial tables null; later no-argument
74configuration is a no-op that preserves existing pointers and counts. These are guest-owned tables, without
75changing the host CRT's argument globals. This does not add console-path wildcard routing or change the legacy
76`msvcrt!__getmainargs` wildcard policy. `run_argv_modes` compares the same six linker-selected MSVC fixtures
77natively and through the loader; `run_startup_cmdline` also checks native preconfiguration and command-line
78identity through attach and entry.
60 79
61The six unique Xbox-specific imports (eight consumer/import pairs) are exactly the set recorded in 80The six unique Xbox-specific imports (eight consumer/import pairs) are exactly the set recorded in
62[`d3d12_vulkan.md` §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi): 81[`d3d12_vulkan.md` §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi):
@@ -75,6 +94,102 @@ The six unique Xbox-specific imports (eight consumer/import pairs) are exactly t
75The video path (`Bink2Scarlett.dll`), the BVH builder and the FidelityFX upscaler therefore all go through the 94The video path (`Bink2Scarlett.dll`), the BVH builder and the FidelityFX upscaler therefore all go through the
76two shim DLLs that already exist. `libHttpClient.GDK.dll` and `XCurl.dll` import only desktop APIs. 95two shim DLLs that already exist. `libHttpClient.GDK.dll` and `XCurl.dll` import only desktop APIs.
77 96
97`xmem.dll!XMemTransferMemory` is not imported by any of these DLLs, but a Series executable calls it during startup
98(reported in [#5934](https://github.com/ItsNotRexed/Leonida/issues/5934#issuecomment-7101779516)). Its GDK reference
99page is an NDA topic, but Microsoft's public [NetRumble](https://github.com/microsoft/XBOX-MonoGame-NetRumble/blob/203255e785f2ab2671a9d83b724eaa14d5b07414/console/NetRumble.Bootstrap/Main.cpp#L135-L145)
100sample and FNA's [NativeAOT-Xbox](https://github.com/FNA-XNA/NativeAOT-Xbox/blob/b9dc547afd0e05f45764d670ec49e0ac7997a301/Bootstrap/Main.cpp#L117-L124)
101bootstrap call it as `if (!XMemTransferMemory(XMemTransferTitleToSystem, size))` with a `size_t` in multiples of
1022 MiB, to move budget from the title's memory partition to the system's. A PC has no such partition, so the shim
103returns `TRUE` for every direction and size and allocates nothing; with `--trace` it records each distinct direction
104and size as an `xmem_transfer` event, because the enum values are not public. `xmem_test` covers it.
105
106Seven more `xmem.dll` imports follow argument shapes measured locally at a title's call sites (the comments in
107`runtime/shims/xmem.cpp` give each shape):
108
109- `XMemAllocDefault` and `XMemFreeDefault` take `XMemAlloc`'s and `XMemFree`'s arguments and share their heap.
110- `XMemAllocatePhysicalPages(attributes, UINT64* count, UINT64* pages)` returns a `BOOL` and the count it allocated.
111 Each call is one pagefile-backed section of `count` 64 KiB pages. A page number is a 4 KiB frame number: a
112 non-zero multiple of 16 below 2^25, which is what the measured title assumes when it packs them. `0` means "unmap".
113- `XMemMapPhysicalPages(address, UINT64 count, pages)` returns the address. A null page array unmaps.
114 `XMemMapPhysicalPagesScatter(addresses, UINT32 count, pages)` returns a `BOOL`, and a `0` entry unmaps.
115 `XMemFreePhysicalPages(UINT64 count, pages)` returns a `BOOL`. Every page is its own view, mapped with
116 `MapViewOfFile3` into a 64 KiB placeholder, so a page keeps its contents across remaps and can be mapped twice.
117- The windows are reserve-only 64 KiB-page `XMemVirtualAlloc` regions. The shim reserves them as placeholders and
118 keeps their protection, which mapped pages get (AWE's rule). The measured title also reserves a placeholder with
119 `MEM_RESERVE_PLACEHOLDER` and carves windows out of it with `MEM_REPLACE_PLACEHOLDER`, and the shim passes both
120 through. **ASSUMPTION:** nothing commits into a window with `kernel32!VirtualAlloc`, which a placeholder refuses.
121- `XMemVirtualAlloc` used to refuse 2 MiB pages, and five of the 23 measured calls commit them. They are now
122 committed 2 MiB-aligned through `VirtualAlloc2`. The attribute word is recorded (`xmem_attributes`) and the
123 console's `PAGE_GRAPHICS_*` bits are dropped from the protection, as before.
124- `XMemIsToolsMemAvailable()` is `FALSE`: a PC has no development-kit tools memory. The measured title asks only
125 on an out-of-memory path, after an allocation has already failed.
126
127## The retail executable (RT-5)
128
129`game_scarlett_master.exe` (120,181,760 bytes on disk, SHA-256
130`e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993`) is a PE32+ x86-64 image with no resource
131section. `gta6rt --dry-run` maps it at its preferred base together with the four package DLLs it imports, and
132exits 0 with nothing on stderr:
133
134```powershell
135$game = "D:\path\to\your\package"
136$scratch = Join-Path $env:TEMP 'leonida-overlay'
137runtime\build\gta6rt.exe --dry-run "D:\path\to\game_scarlett_master.exe" --game-dir $game --overlay $scratch
138```
139
140`--overlay` points the write overlay away from `<game-dir>\overlay`, so a dry run writes nothing into the package.
141Measured at `1cc6e3c1`, Windows 11, MSVC 14.44:
142
143| Image | Base | Size of image | Entry RVA | Shim | Host | Module | Unimplemented |
144|---|---|---:|---:|---:|---:|---:|---:|
145| `game_scarlett_master.exe` | `0x140000000` | 184,995,840 | `0x56a1ec8` | 53 | 432 | 72 | **30** |
146| `XboxBvhBuilder.dll` | `0x180000000` | 909,312 | `0x227cc` | 5 | 52 | 0 | 0 |
147| `amd_fidelityfx_loader_xbox.dll` | relocated | 32,768 | `0x18d0` | 6 | 16 | 0 | 0 |
148| `libHttpClient.GDK.dll` | relocated | 999,424 | `0x11f0` | 28 | 170 | 0 | 0 |
149| `Bink2Scarlett.dll` | relocated | 278,528 | `0x2ac1c` | 5 | 55 | 0 | 0 |
150
151The 72 module imports are served by those four DLLs. The 30 unimplemented imports all fall under the dry-run's
152policy "other" (none is counted as returning an `HRESULT`), and they come from seven Xbox-only DLLs:
153
154| DLL | Unimplemented imports | What the names suggest (not measured) |
155|---|---:|---|
156| `xmem.dll` | 7: `XMemAllocDefault`, `XMemAllocatePhysicalPages`, `XMemFreeDefault`, `XMemFreePhysicalPages`, `XMemIsToolsMemAvailable`, `XMemMapPhysicalPages`, `XMemMapPhysicalPagesScatter` | the console's physical page and default allocation routines; `XMemAlloc`, `XMemFree`, `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` already bind |
157| `d3d12_xs.dll` | 1: `D3D12ConfigureVirtualMemoryX` | GPU virtual memory setup |
158| `xg_xs.dll` | 2: `XGCreateTextureComputer`, `XGSuggestSwizzleMode` | texture layout computation |
159| `XCRDAPI.dll` | 1: `DStorageGetFactory` | DirectStorage |
160| `chad.dll` | 5: `XDspActivate`, `XDspConnectWithMaximumStreamLimit`, `XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand` | the audio DSP |
161| `xapu.dll` | 5: `XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, `XApuEnqueueCommand`, `XApuGetResultCount` | the audio processing unit |
162| `AcpHal.dll` | 9: `AcpHalAllocateShapeContexts`, `AcpHalCreate`, `AcpHalReleaseShapeContexts`, `ApuAlloc`, `ApuCreateHeap`, `ApuFree`, `ApuIsVirtualAddressValid`, `ApuMapApuAddress`, `ApuMapVirtualAddress` | the audio hardware layer |
163
164The game executable imports two functions from `xg_xs.dll`, the console's texture layout library:
165`XGSuggestSwizzleMode` (2 call sites, in the helper that fills a texture description) and `XGCreateTextureComputer`
166(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). The runtime has no model of the console
167resource layout, so `runtime/shims/xg_xs.cpp` computes none: both return `E_NOTIMPL` and write no layout. Two of the
168four `XGCreateTextureComputer` callers ignore the HRESULT and call through the object at once, so the shim still stores
169a static object in the out pointer; its slot 1 (read as `Release`) does nothing, and every other slot up to 31 logs its
170index and caller once and returns `E_NOTIMPL` without writing its arguments. The call shapes and the reasoning are at
171the top of the file; `xg_xs_test` covers them. Textures whose layout the game asks for are therefore not laid out yet.
172The table above was measured before this shim and still lists these two as unimplemented; they are served now.
173
174Only two of these DLLs have a shim in the repository (`xmem.dll` and `d3d12_xs.dll`), and they are not complete:
175they hold 8 of the 30 unimplemented imports. The other 22 are in five DLLs (`xg_xs.dll`, `XCRDAPI.dll`, `chad.dll`,
176`xapu.dll`, `AcpHal.dll`) with no shim at all.
177
178The seven `xmem.dll` imports are served now (see the `xmem.dll` notes above), so the same dry run lists 23.
179
180`--init` on the same files also exits 0 with nothing on stderr. Its `--trace` file has 15 lines: the four package DLLs'
181`DllMain(DLL_PROCESS_ATTACH)` each return 1, the executable's two TLS callbacks run at process attach (reason 1) and
182again at detach (reason 0), and there is no `exception`, `error` or `unimplemented_call` event. So none of the 30
183unimplemented imports is reached by the TLS callbacks or the `DllMain`s.
184
185What this does not show: `--run` has not been run, so the entry point has not been called and no import is known to be
186reached on the way to the first frame. A bound import is not a working one (the binding only says a function with
187that name exists), and an unimplemented import stops the run only if the title calls it
188([When an unimplemented import is called](#when-an-unimplemented-import-is-called)). The executable imports 25
189functions from `ws2_32.dll` (23 by ordinal, plus `getaddrinfo` and `freeaddrinfo`) and the loader binds them to the
190host's, so a `--run` can open real sockets: run it with the network off. `winhttp.dll` is served by the offline shim,
191which opens none.
192
78## Console paths and the write overlay 193## Console paths and the write overlay
79 194
80A title's file calls name the console's drives, so `GAME:\data\x.sps` is a file inside the installed game folder. 195A title's file calls name the console's drives, so `GAME:\data\x.sps` is a file inside the installed game folder.
@@ -92,12 +207,18 @@ and the `api-ms-win-core-file-*` sets a GDK title links against.
92 not see (RT-218; the other console layers map those two drives this way, and only the executable can say which 207 not see (RT-218; the other console layers map those two drives this way, and only the executable can say which
93 spelling GTA VI uses). A path under `--game-dir` or the overlay is always a host path, so a package that sits on 208 spelling GTA VI uses). A path under `--game-dir` or the overlay is always a host path, so a package that sits on
94 a host drive `G:` keeps working, and with no folders configured `G:` and `T:` stay host drives. 209 a host drive `G:` keeps working, and with no folders configured `G:` and `T:` stay host drives.
210 `T:\` is a drive root like `GAME:\`: its folder is made on the first `T:` call, so it is a folder before anything
211 is written there, and removing or moving it fails with `ERROR_ACCESS_DENIED`.
95- An open that can write, and `DeleteFile`, use the overlay: `--overlay DIR`, default `<game-dir>\overlay`. A 212- An open that can write, and `DeleteFile`, use the overlay: `--overlay DIR`, default `<game-dir>\overlay`. A
96 write-open of a package file copies it into the overlay first, so `OPEN_EXISTING` keeps its bytes. The copy is 213 write-open of a package file copies it into the overlay first, so `OPEN_EXISTING` keeps its bytes. The copy is
97 written under `<overlay>\.gta6rt-copy` and renamed into place, one copy-up at a time, so a process killed mid-copy 214 written under `<overlay>\.gta6rt-copy` and renamed into place, one copy-up at a time, so a process killed mid-copy
98 or two threads opening the same file never leave a truncated copy under its name; a delete of a 215 or two threads opening the same file never leave a truncated copy under its name; a delete of a
99 package file leaves an empty marker under `<overlay>\.gta6rt-deleted`, which reads and listings treat as gone. The 216 package file leaves an empty marker under `<overlay>\.gta6rt-deleted`, which reads and listings treat as gone. The
100 package is never written. 217 package is never written.
218- `DeleteFileA/W` checks the visible file's `FILE_ATTRIBUTE_READONLY`: a read-only package file with no overlay is
219 refused with `ERROR_ACCESS_DENIED` before writing a deletion marker. An overlay copy supplies its own attributes,
220 so a writable overlay can still be deleted when the package file underneath is read-only. The native A/W controls
221 in `file_system_test` cover these cases and mixed hidden, system and archive attributes.
101- Reads prefer the overlay copy and then the package. `FindFirstFile` merges the two folders, the overlay winning on a 222- Reads prefer the overlay copy and then the package. `FindFirstFile` merges the two folders, the overlay winning on a
102 name, and hides deleted names, the marker folder and the copy folder. 223 name, and hides deleted names, the marker folder and the copy folder.
103- A path that climbs above `GAME:` with `..`, or names another drive, fails with `ERROR_INVALID_NAME`, so a title 224- A path that climbs above `GAME:` with `..`, or names another drive, fails with `ERROR_INVALID_NAME`, so a title
@@ -114,12 +235,27 @@ and the `api-ms-win-core-file-*` sets a GDK title links against.
114 `ERROR_ACCESS_DENIED` (as deleting one does), a move between `GAME:` and a host path with `ERROR_NOT_SAME_DEVICE`, and 235 `ERROR_ACCESS_DENIED` (as deleting one does), a move between `GAME:` and a host path with `ERROR_NOT_SAME_DEVICE`, and
115 `MOVEFILE_DELAY_UNTIL_REBOOT` with `ERROR_INVALID_PARAMETER`. 236 `MOVEFILE_DELAY_UNTIL_REBOOT` with `ERROR_INVALID_PARAMETER`.
116- `CopyFile`, `CopyFileEx` and `CopyFile2` read the source the way a read does and write a `GAME:` destination in the 237- `CopyFile`, `CopyFileEx` and `CopyFile2` read the source the way a read does and write a `GAME:` destination in the
117 overlay; fail-if-exists counts a name only the package has. Either side can be a host path. Where the host has no 238 overlay; fail-if-exists counts a name only the package has. Either side can be a host path. `CopyFile2` checks its
118 `CopyFile2` (Wine 9, whose loader binds the import to a stub that aborts the process), the shim copies with 239 parameter block before preparing the destination: one shorter than `COPYFILE2_EXTENDED_PARAMETERS` is
119 `CopyFileExW` instead: the flags both calls define and the cancel flag are passed on, CopyFile2-only hints are 240 `E_INVALIDARG` and writes nothing, as Windows answers. Where the host has no `CopyFile2` (Wine 9, whose loader binds
120 dropped, and a `COPYFILE2` progress routine is not called. 241 the import to a stub that aborts the process), the shim copies with `CopyFileExW` instead: the flags both calls
242 define and the cancel flag are passed on (a flag already set cancels before anything is written), CopyFile2-only
243 requests that leave the contents as `CopyFileExW` writes them (no offload, compressed traffic, sparse copy, ...)
244 are dropped, and a `COPYFILE2` progress routine is not called. A call it can't run as asked (`SKIP_ALTERNATE_STREAMS`,
245 `DIRECTORY`, `OPEN_AND_COPY_REPARSE_POINT`, `IGNORE_SOURCE_ENCRYPTION`, an unknown flag, or a longer V2 block) is
246 `ERROR_NOT_SUPPORTED` and writes nothing. `rt::fs::force_copy_file2_fallback` makes the test take this path on
247 Windows too. A cancel flag that is already set is answered before the host's `CopyFile2` is called as well, since
248 Wine 10 and 11 export `CopyFile2` but ignore the flag; clearing it lets the same call be retried.
121- `SetFileAttributes*` sets the attributes on the overlay copy, copying a package file up (or mirroring a package 249- `SetFileAttributes*` sets the attributes on the overlay copy, copying a package file up (or mirroring a package
122 folder) first, so the package keeps its own. 250 folder) first, so the package keeps its own.
251- A folder has to exist in the title's view before it is used. An open that writes fails with `ERROR_PATH_NOT_FOUND`
252 when its folder is missing, was removed, or is a file, and creates nothing (`T:` is the exception: a create there
253 makes its parent folders); `FindFirstFile` fails the same way for a
254 listing inside such a folder (a pattern that matches nothing in a folder that exists is still
255 `ERROR_FILE_NOT_FOUND`, and a listing directly below a file is `ERROR_DIRECTORY`, as on the host).
256- `MoveFile*` onto the same name succeeds and changes nothing. A rename that changes only the case renames the overlay
257 entry; a package file gets an overlay copy under the new spelling, and a package folder is refused like any other
258 move of one.
123 259
124`runtime/test/file_system_test.cpp` (ctest `file_system`) covers this over folders it makes in `%TEMP%`. 260`runtime/test/file_system_test.cpp` (ctest `file_system`) covers this over folders it makes in `%TEMP%`.
125 261
@@ -160,17 +296,18 @@ mostly correspond one to one to the `xgameruntime.lib` functions. The executable
160 296
161Bound to the host, those calls would load the PC's Gaming Services runtime, or fail, and never reach the offline 297Bound to the host, those calls would load the PC's Gaming Services runtime, or fail, and never reach the offline
162shims. `runtime/shims/library_loader.cpp` therefore answers `LoadLibrary*` and `GetModuleHandle*` for a module the 298shims. `runtime/shims/library_loader.cpp` therefore answers `LoadLibrary*` and `GetModuleHandle*` for a module the
163shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `gameinput.dll`) with a 299shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `xg_xs.dll`, `gameinput.dll`)
164pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name the registry doesn't serve is `NULL` 300with a pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name the registry doesn't serve is `NULL`
165with `ERROR_PROC_NOT_FOUND` and is logged once. Every other module goes to the host unchanged. 301with `ERROR_PROC_NOT_FOUND` and is logged once. Every other module goes to the host unchanged.
166 302
167`runtime/shims/xgameruntime.cpp` serves the five entry points. The initializers succeed offline and log the GDK 303`runtime/shims/xgameruntime.cpp` serves the five entry points. The initializers succeed offline and log the GDK
168version and mode once. `QueryApiImpl` serves `XThreadingImpl` and `XErrorImpl` (below), and `XUserImpl`, `XGameSaveImpl`, `XStoreImpl`, 304version and mode once. `QueryApiImpl` serves `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl`, `XSystemImpl`,
169`XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`, `XDisplayImpl` and `XUserDeviceImpl` from xgameruntime-docs' 305`XPersistentLocalStorageImpl`, `XPackageImpl`, `XGameImpl`, `XGameRuntimeFeatureImpl` and `XSystemAnalyticsImpl`
170layout (below); for any other class it logs 306(below), and `XUserImpl`, `XGameSaveImpl`, `XStoreImpl`, `XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`,
307`XDisplayImpl`, `XUserDeviceImpl`, `XAccessibilityImpl` and `XLauncherImpl` from xgameruntime-docs' layout (below); for any other class it logs
171the class and interface id and returns `0x80070032`, the documented error for a class the runtime doesn't provide, so 308the class and interface id and returns `0x80070032`, the documented error for a class the runtime doesn't provide, so
172the first boot with the executable lists the classes to implement next. `xgameruntime_test` drives this path through 309the first boot with the executable lists the classes to implement next. `xgameruntime_test` drives this path through
173the api-set binding `XCurl.dll` uses, and calls the two classes slot by slot. 310the api-set binding `XCurl.dll` uses, and calls the classes `xgameruntime.cpp` serves slot by slot.
174 311
175`XCurl.dll` has a second way in. One of its functions reads `HKLM\Microsoft\GamingServices` value 312`XCurl.dll` has a second way in. One of its functions reads `HKLM\Microsoft\GamingServices` value
176`ServiceRetryTimeout`, then `LoadLibraryExW(L"gameplatformservices.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)` and 313`ServiceRetryTimeout`, then `LoadLibraryExW(L"gameplatformservices.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)` and
@@ -198,7 +335,7 @@ count and width, the function at that position of xgameruntime-docs' "Layout" li
198| `XErrorImpl` (`IXErrorImpl`, slots 3-5) | 3 (`XCurl.dll`) | slot 3, the docs' `_unknown_`, takes an HRESULT and a pointer: `XErrorReport(HRESULT, const char*)` | 335| `XErrorImpl` (`IXErrorImpl`, slots 3-5) | 3 (`XCurl.dll`) | slot 3, the docs' `_unknown_`, takes an HRESULT and a pointer: `XErrorReport(HRESULT, const char*)` |
199| `XNetworkingImpl` (`IXNetworkingImpl2`, slots 3-20) | 11-17 (`XCurl.dll`), 3-20 (`libHttpClient.GDK.dll`, each in its documented argument shape, e.g. 18-20 (enum, u64 pointer / u64 / pointer)) | the Utf16 `XNetworkingQuerySecurityInformationForUrl*` trio, `XNetworkingVerifyServerCertificate`, `XNetworkingGetConnectivityHint`, `XNetworkingRegister/UnregisterConnectivityHintChanged` (pointer, bool). Served offline, asked for with `IXNetworkingImpl2`'s id | 336| `XNetworkingImpl` (`IXNetworkingImpl2`, slots 3-20) | 11-17 (`XCurl.dll`), 3-20 (`libHttpClient.GDK.dll`, each in its documented argument shape, e.g. 18-20 (enum, u64 pointer / u64 / pointer)) | the Utf16 `XNetworkingQuerySecurityInformationForUrl*` trio, `XNetworkingVerifyServerCertificate`, `XNetworkingGetConnectivityHint`, `XNetworkingRegister/UnregisterConnectivityHintChanged` (pointer, bool). Served offline, asked for with `IXNetworkingImpl2`'s id |
200| `XSystemImpl` (`IXSystemImpl5`, slots 3-8 known) | 3-8 (`libHttpClient.GDK.dll`) | 3-5 `XSystemGetConsoleId` / `GetXboxLiveSandboxId` / `GetAppSpecificDeviceId` (size, pointer, pointer each), 6 `XSystemHandleTrack` (two pointers, IXSystemImpl3), 7 `XSystemIsHandleValid` (pointer), 8 `XSystemAllowFullDownloadBandwidth` (bool, IXSystemImpl4); IXSystemImpl2 and 5 add no known method. Served offline | 337| `XSystemImpl` (`IXSystemImpl5`, slots 3-8 known) | 3-8 (`libHttpClient.GDK.dll`) | 3-5 `XSystemGetConsoleId` / `GetXboxLiveSandboxId` / `GetAppSpecificDeviceId` (size, pointer, pointer each), 6 `XSystemHandleTrack` (two pointers, IXSystemImpl3), 7 `XSystemIsHandleValid` (pointer), 8 `XSystemAllowFullDownloadBandwidth` (bool, IXSystemImpl4); IXSystemImpl2 and 5 add no known method. Served offline |
201| `XPersistentLocalStorageImpl` (`IXPersistentLocalStorageImpl3`, slots 3-8) | none called (the table of ids only) | slots 3-7 are `XPersistentLocalStorageGetPathSize` / `GetPath` / `GetSpaceInfo` / `PromptUserForSpaceAsync` / `PromptUserForSpaceResult`, slot 8 `XPersistentLocalStorageMountForPackage` (IXPersistentLocalStorageImpl3). Slots from the public xgameruntime-docs and Wine IDL, not measured in a caller. Served offline: the folder is `<overlay>\persistent`, the quota is the 2048 MB of `MicrosoftGame.Config`, a prompt for space the quota holds succeeds, and `MountForPackage` is `E_NOTIMPL` | 338| `XPersistentLocalStorageImpl` (`IXPersistentLocalStorageImpl3`, slots 3-8) | none called (the table of ids only) | slots 3-7 are `XPersistentLocalStorageGetPathSize` / `GetPath` / `GetSpaceInfo` / `PromptUserForSpaceAsync` / `PromptUserForSpaceResult`, slot 8 `XPersistentLocalStorageMountForPackage` (IXPersistentLocalStorageImpl3). Slots from the public xgameruntime-docs and Wine IDL, not measured in a caller. Served offline: the folder is `<overlay>\.gta6rt-persistent`, which `GAME:` does not see, the quota is the 2048 MB of `MicrosoftGame.Config`, a prompt for space the quota holds succeeds, and `MountForPackage` is `E_NOTIMPL` |
202| `XPackageImpl` (`IXPackageImpl3`) | 3-19, 22, 24-27, 30, 32-34, 37-40 (`libHttpClient.GDK.dll`) | slots 3-34 are IXPackageImpl's 32 entries, 35-38 IXPackageImpl2's 4, 39-40 IXPackageImpl3's 2. Served offline: 3 identifier, 4 packaged process, 11 user locale, 24-26 mount path size / path / close; the rest log once and return `E_NOTIMPL` | 339| `XPackageImpl` (`IXPackageImpl3`) | 3-19, 22, 24-27, 30, 32-34, 37-40 (`libHttpClient.GDK.dll`) | slots 3-34 are IXPackageImpl's 32 entries, 35-38 IXPackageImpl2's 4, 39-40 IXPackageImpl3's 2. Served offline: 3 identifier, 4 packaged process, 11 user locale, 24-26 mount path size / path / close; the rest log once and return `E_NOTIMPL` |
203| `XGameImpl` (`IXGameImpl3`, slots 3-5) | none in the package's DLLs (`libHttpClient.GDK.dll` holds its id only in the linked id table); the executable's requests are unmeasured | from the xgameruntime IDL: 3 `XGameGetXboxTitleId` (pointer), 4 `XLaunchNewGame` (two strings and a user handle, `void`), 5 `XLaunchRestartOnCrash` (string, u32). Served offline: the title id is `MicrosoftGame.Config`'s `<TitleId>` (`E_FAIL` without one), a new game launch is logged and ignored, a crash restart succeeds with nothing registered | 340| `XGameImpl` (`IXGameImpl3`, slots 3-5) | none in the package's DLLs (`libHttpClient.GDK.dll` holds its id only in the linked id table); the executable's requests are unmeasured | from the xgameruntime IDL: 3 `XGameGetXboxTitleId` (pointer), 4 `XLaunchNewGame` (two strings and a user handle, `void`), 5 `XLaunchRestartOnCrash` (string, u32). Served offline: the title id is `MicrosoftGame.Config`'s `<TitleId>` (`E_FAIL` without one), a new game launch is logged and ignored, a crash restart succeeds with nothing registered |
204 341
@@ -218,12 +355,15 @@ answer 0. `XErrorImpl` logs each report and hands it to the callback `XErrorSetC
218`XNetworkingImpl` answers as a console without a network would: the connectivity hint is initialized with no 355`XNetworkingImpl` answers as a console without a network would: the connectivity hint is initialized with no
219connectivity (level None), the port and URL security-information queries fail with 356connectivity (level None), the port and URL security-information queries fail with
220`HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE)` (the `*Async` ones complete with it through XAsync), the 357`HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE)` (the `*Async` ones complete with it through XAsync), the
221certificate check fails the same way, change registrations return tokens that never fire, and the three 358certificate check fails the same way, the two change registrations send the one initial notification Microsoft
222`IXNetworkingImpl2` additions are `E_NOTIMPL`. 359documents (on the queue's completion port, the process queue when none is given: the hint above, or port 0) and
360none after, and the three `IXNetworkingImpl2` additions are `E_NOTIMPL`.
223 361
224`XUserImpl` (`runtime/shims/xgameruntime_user.cpp`) is served from xgameruntime-docs' layout alone. No package DLL 362`XUserImpl` (`runtime/shims/xgameruntime_user.cpp`) is served from xgameruntime-docs' layout alone. No package DLL
225calls an `XUser*` slot (`libHttpClient.GDK.dll` only holds the GUID table), so its slots are **not measured** yet. 363calls an `XUser*` slot (`libHttpClient.GDK.dll` only holds the GUID table). The executable links thunks for
226The executable's first boot confirms them, or names the slots that differ. 364`IXUserImpl` slots 3-5, 7-14, 19-25 and 33-34 and `IXUserGamertagImpl` slot 3 (`tools/gdk_runtime_calls.py`, from the
365file alone): none of the slots logged on first use below, and of the offline failures only the token-and-signature
366trio (23-25). What the slots must answer is still **not measured**; that is the executable's first boot.
227- **Interfaces:** the class id doubles as `IXUserImpl`'s; `IXUserImpl2`-`6` answer with the same 50-slot vtable; 367- **Interfaces:** the class id doubles as `IXUserImpl`'s; `IXUserImpl2`-`6` answer with the same 50-slot vtable;
228 `IXUserGamertagImpl` (`XUserGetGamertag`) is a second interface. 368 `IXUserGamertagImpl` (`XUserGetGamertag`) is a second interface.
229- **The user:** one offline local user, always signed in. `XUserAddAsync` adds it with or without 369- **The user:** one offline local user, always signed in. `XUserAddAsync` adds it with or without
@@ -265,7 +405,8 @@ The executable's first boot confirms them, or names the slots that differ.
265 405
266`xgameruntime_gamesave_test` drives every slot against a temporary `LEONIDA_SAVE_DIR`. 406`xgameruntime_gamesave_test` drives every slot against a temporary `LEONIDA_SAVE_DIR`.
267 407
268`XStoreImpl` (`runtime/shims/xgameruntime_store.cpp`), from the same layout, also **not measured**: 408`XStoreImpl` (`runtime/shims/xgameruntime_store.cpp`), from the same layout; the game-license struct is measured
409on the executable, the rest is not:
269- **Interfaces:** the class id doubles as `IXStoreImpl`'s; `IXStoreImpl2`-`6` answer with the same 84-slot vtable. 410- **Interfaces:** the class id doubles as `IXStoreImpl`'s; `IXStoreImpl2`-`6` answer with the same 84-slot vtable.
270- **Offline answers:** the game license is active and not a trial; a package's license is acquirable and valid; 411- **Offline answers:** the game license is active and not a trial; a package's license is acquirable and valid;
271 there are no add-on licenses, no products in any query and no package updates. License-changed and license-lost 412 there are no add-on licenses, no products in any query and no package updates. License-changed and license-lost
@@ -273,14 +414,19 @@ The executable's first boot confirms them, or names the slots that differ.
273- **Not available offline:** purchases, consumables, license tokens, collections and purchase ids, downloads and 414- **Not available offline:** purchases, consumables, license tokens, collections and purchase ids, downloads and
274 every store UI fail before starting (`E_FAIL`, logged once). The docs' three unnamed slots and 415 every store UI fail before starting (`E_FAIL`, logged once). The docs' three unnamed slots and
275 `XStoreIsAvailabilityPurchasable` (no documented signature) answer `E_NOTIMPL`. 416 `XStoreIsAvailabilityPurchasable` (no documented signature) answer `E_NOTIMPL`.
276- **UNVERIFIED:** `STORE_SKU_ID_SIZE` = 18, `SKU_ID_SIZE` = 5 and `TRIAL_UNIQUE_ID_MAX_SIZE` = 64, which fix 417- **Measured on the executable:** `XStoreGameLicense` is 104 bytes. The title's `XStoreQueryGameLicenseResult`
277 `XStoreGameLicense` (104 bytes) and `XStoreCanAcquireLicenseResult` (12 bytes). The public pages give no values; 418 call passes a 104-byte stack buffer and reads the SKU id as a C string at +0x00, the three booleans at
278 confirm them from the buffer the executable passes to `XStoreQueryGameLicenseResult` before a boot relies on it. 419 +0x13..+0x15, the trial id as a C string at +0x1C and the expiration time at +0x60. That fixes
420 `STORE_SKU_ID_SIZE` = 18 and the 104-byte total.
421- **UNVERIFIED:** `SKU_ID_SIZE` = 5 and the exact `TRIAL_UNIQUE_ID_MAX_SIZE` = 64. The executable bounds the
422 trial id to at most 68 bytes (the expiration time is at +0x60) but reads it as a C string, so it does not name
423 the bound; 64 is the public source's value. It does not call either can-acquire slot (24-27), so
424 `XStoreCanAcquireLicenseResult` (12 bytes) is unmeasured.
279 425
280`xgameruntime_store_test` drives the license check, add-ons, updates, package licenses and product queries. 426`xgameruntime_store_test` drives the license check, add-ons, updates, package licenses and product queries.
281 427
282`XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`, `XDisplayImpl` and `XUserDeviceImpl` 428`XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`, `XDisplayImpl`, `XUserDeviceImpl`, `XAccessibilityImpl` and
283(`runtime/shims/xgameruntime_offline.cpp`), from the same layout, also **not measured**: 429`XLauncherImpl` (`runtime/shims/xgameruntime_offline.cpp`), from the same layout, also **not measured**:
284- **`XGameEventWrite`** succeeds; the events are dropped. The first one's name is logged, and 430- **`XGameEventWrite`** succeeds; the events are dropped. The first one's name is logged, and
285 `LEONIDA_LOG_GAME_EVENTS=1` logs each with its dimensions and measurements. 431 `LEONIDA_LOG_GAME_EVENTS=1` logs each with its dimensions and measurements.
286- **Dialogs:** a message dialog's title, text and buttons go to the log (`[rt] game dialog:`), and it completes at 432- **Dialogs:** a message dialog's title, text and buttons go to the log (`[rt] game dialog:`), and it completes at
@@ -292,19 +438,48 @@ The executable's first boot confirms them, or names the slots that differ.
292 are no clients, and the connection-state registration hands out a token that never fires. Every per-client slot 438 are no clients, and the connection-state registration hands out a token that never fires. Every per-client slot
293 answers `E_GAMESTREAMING_NOT_INITIALIZED` (0x89245400), which a caller reading a bool sees as false (low byte 439 answers `E_GAMESTREAMING_NOT_INITIALIZED` (0x89245400), which a caller reading a bool sees as false (low byte
294 0). 440 0).
295- **ASSUMPTION:** the parameter lists of `XGameUiShowMessageDialogAsync` and 441- **Not reached by the executable:** the parameter lists of `XGameUiShowMessageDialogAsync` and
296 `XGameStreamingRegisterConnectionStateChanged`, from the GDK reference, not re-checked against the executable. 442 `XGameStreamingRegisterConnectionStateChanged` are the GDK reference's, and the executable has no caller to check
297 443 them against. `tools/gdk_runtime_calls.py` finds no thunk for the message dialog and none for any
444 `XGameStreamingImpl` or `XUserDeviceImpl` slot. Of `XGameUiImpl` it links slots 7-8 and 17-19 only: the profile
445 card and text entry, which fail before starting.
446
447- **Accessibility and speech** (`IXAccessibilityImpl2`, slots 3-21): `XHighContrastGetMode` (5) answers Off and
448 `XClosedCaptionSetEnabled` (4) is accepted. No voice is installed: `XSpeechSynthesizerEnumerateInstalledVoices`
449 (8) calls back zero times and returns `S_OK`, `XSpeechSynthesizerCreate` (9) fails (`E_FAIL`) with a null handle,
450 and the handle calls (10-16, 21: close, default and custom voice, streams from text and SSML, stream size and
451 data) refuse the handle they were never given (`E_INVALIDARG`, outputs zeroed). The closed-caption properties (3)
452 and the speech-to-text display calls (6, 7, 17-20) fail with `E_FAIL`, writing nothing: their parameter lists
453 are not in the docs' layout.
454- **`XLauncherImpl`** (`IXLauncherImpl`, slots 3-5): `XLaunchUri`, `XDisplayAcquireTimeoutDeferral` (null handle)
455 and `XDisplayCloseTimeoutDeferralHandle` fail with `E_FAIL`; nothing is launched.
456- **ASSUMPTION:** the parameter lists of the speech calls and `XHighContrastGetMode` (Off is 0), from the GDK
457 reference; only the argument counts were measured, from `tools/gdk_runtime_calls.py` on the executable.
298- **HDR:** `XDisplayTryEnableHdrMode` answers Disabled, because the host output is SDR. With `LEONIDA_HDR=1` it 458- **HDR:** `XDisplayTryEnableHdrMode` answers Disabled, because the host output is SDR. With `LEONIDA_HDR=1` it
299 answers Enabled with the documented default tone-map luminances (0.01, 1000, 1000 nits). 459 answers Enabled with the documented default tone-map luminances (0.01, 1000, 1000 nits).
300- **Devices:** every device belongs to the offline user (`XUserFindForDevice` hands out an `XUserHandle` the title 460- **Devices:** every device belongs to the offline user (`XUserFindForDevice` hands out an `XUserHandle` the title
301 closes). Association and audio-endpoint registrations hand out tokens that never fire. The user has no audio 461 closes). Association and audio-endpoint registrations hand out tokens that never fire. The user has no audio
302 endpoint of its own (`ERROR_NOT_FOUND`). Finding a controller shows no UI and gives an all-zero device id, as 462 endpoint of its own (`ERROR_NOT_FOUND`). Finding a controller shows no UI and gives an all-zero device id, as
303 documented for desktop. **ASSUMPTION:** `APP_LOCAL_DEVICE_ID` is 32 bytes. 463 documented for desktop. `APP_LOCAL_DEVICE_ID` is taken to be 32 bytes; no caller in the executable confirms it.
304 464
305`xgameruntime_offline_test` drives the five classes; `xgameruntime_offline_hdr` runs it again with 465`xgameruntime_offline_test` drives the five classes; `xgameruntime_offline_hdr` runs it again with
306`LEONIDA_HDR=1`. 466`LEONIDA_HDR=1`.
307 467
468Two more classes are served from `tools/gdk_runtime_calls.py`'s measurement of `libHttpClient.GDK.dll` (it finds the
469thunks in the code without running it and prints, per class, the interface id asked for, the slots called and the
470argument count each passes after `this`). Their thunks are in the DLL but nothing in it calls them; a title linked with
471the same `xgameruntime.lib` gets the same thunks. Every slot is the function at that position of xgameruntime-docs'
472layout with the documented argument count, and each behaves as Microsoft's reference page for that function says
473(`runtime/shims/xgameruntime.cpp` cites both):
474
475| Class | Interface asked for | Slots (args after `this`) | Offline behaviour |
476|---|---|---|---|
477| `XGameRuntimeFeatureImpl` | its class id | 3 `XGameRuntimeIsFeatureAvailable` (1, returns `bool`) | True when `QueryApiImpl` serves the class the feature's functions go through (whichever `xgameruntime*.cpp` serves it) and the feature is documented for Windows: today XAccessibility, XSpeechSynthesizer, XLauncher, XAsync, XAsyncProvider, XTaskQueue, XThread, XError, XGame, XGameSave, XGameUI, XNetworking, XPackage, XPersistentLocalStorage, XStore, XSystem, XUser, XGameEvent, XGameStreaming. False for XDisplay (served, but documented for the consoles only), for the classes not served (XAppCapture, XGameInvite) and for values past the enum |
478| `XSystemAnalyticsImpl` | its class id | 3 `XSystemGetAnalyticsInfo` (1: the result's address, as MSVC passes a returned struct to a member function) | The named export's `XSystemAnalyticsInfo` |
479
480Not served yet, though `libHttpClient.GDK.dll` has thunks for them: `XAppCaptureImpl` and `XGameInviteImpl`,
481among others.
482
308Which classes the package's GDK modules reference, from a byte search for the class and interface GUIDs that 483Which classes the package's GDK modules reference, from a byte search for the class and interface GUIDs that
309xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; counts only, nothing else read): 484xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; counts only, nothing else read):
310 485
@@ -316,8 +491,48 @@ xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; co
316 491
317So `XCurl.dll` needs threading, error reporting and networking from the runtime, and the interface versions in 492So `XCurl.dll` needs threading, error reporting and networking from the runtime, and the interface versions in
318`libHttpClient.GDK.dll` date the GDK the package was built with: newer than the first `IXUserImpl5`, older than 493`libHttpClient.GDK.dll` date the GDK the package was built with: newer than the first `IXUserImpl5`, older than
319`IXUserImpl6`. The executable's own set is still unmeasured. `tools/gdk_runtime_calls.py` gives it from the file 494`IXUserImpl6`.
320(below), and `QueryApiImpl`'s log on the first boot. 495
496### The retail executable's runtime classes (RT-5)
497
498`python -I tools/gdk_runtime_calls.py game_scarlett_master.exe` (from the file alone, nothing executed; `main`
499`1cc6e3c1`) finds one `QueryApiImpl` helper at RVA `0x55de048` and **161** `xgameruntime.lib` thunks that reach **17**
500runtime classes. 158 of the thunks are referenced from the image; three are present and unreferenced (one each in
501`XPackageImpl`, `XThreadingImpl` and `XAccessibilityImpl`).
502
503The executable does not import `xgameruntime.dll`. Its import table has no such module, so the thunks are linked into
504the image like `libHttpClient.GDK.dll`'s. The name occurs in the image as a UTF-16 string, which
505`tools/pe_inspect.py` lists among the run-time load candidates (a string is where to look, not proof of a
506`LoadLibrary`). The registry
507therefore needs no module name beyond the `xgameruntime.dll` it already has, which settles the assumption at the top of
508`runtime/shims/xgameruntime.cpp`.
509
510| Class | Thunks | Referenced | Served |
511|---|---:|---:|---|
512| `XAccessibilityImpl` | 10 | 9 | no |
513| `XAppCaptureImpl` | 1 | 1 | no |
514| `XLauncherImpl` | 3 | 3 | no |
515| `XDisplayImpl` | 1 | 1 | yes |
516| `XGameEventImpl` | 1 | 1 | yes |
517| `XGameImpl` | 2 | 2 | yes |
518| `XGameRuntimeFeatureImpl` | 1 | 1 | yes |
519| `XGameSaveImpl` | 20 | 20 | yes |
520| `XGameUiImpl` | 5 | 5 | yes |
521| `XNetworkingImpl` | 10 | 10 | yes |
522| `XPackageImpl` | 18 | 17 | yes |
523| `XPersistentLocalStorageImpl` | 2 | 2 | yes |
524| `XStoreImpl` | 44 | 44 | yes |
525| `XSystemAnalyticsImpl` | 1 | 1 | yes |
526| `XSystemImpl` | 3 | 3 | yes |
527| `XThreadingImpl` | 18 | 17 | yes |
528| `XUserImpl` | 21 | 21 | yes |
529
530"Served" is the tool's answer for the runtime sources at that commit. The three that are not: `XAccessibilityImpl`
531(the speech-synthesizer slots 8-13, 15, 16 and 21 are referenced; slot 14 is not), `XAppCaptureImpl` (slot 5,
532`XAppCaptureTakeScreenshot`) and `XLauncherImpl` (slots 3-5: `XLaunchUri` and the two display timeout-deferral calls).
533Open pull requests serve them: #4235, #4307 and #4248. The slots of `XUserImpl`, `XStoreImpl` and `XGameSaveImpl` the
534executable calls, and the argument counts the tool estimates from the registers, are in the report the tool writes.
535`XErrorImpl`, which `XCurl.dll` and `libHttpClient.GDK.dll` call, is not among the executable's classes.
321 536
322### Measuring which runtime classes a binary calls 537### Measuring which runtime classes a binary calls
323 538
@@ -388,8 +603,9 @@ end to end with a synthetic bundled DLL importing `xmem.dll!XMemAlloc` and `XMem
388- Sessions, connections and requests are local handles: no name is resolved and no socket is opened. 603- Sessions, connections and requests are local handles: no name is resolved and no socket is opened.
389- `WinHttpSendRequest` fails with `ERROR_WINHTTP_CANNOT_CONNECT`. On a `WINHTTP_FLAG_ASYNC` session it returns `TRUE` 604- `WinHttpSendRequest` fails with `ERROR_WINHTTP_CANNOT_CONNECT`. On a `WINHTTP_FLAG_ASYNC` session it returns `TRUE`
390 and the failure arrives as WinHTTP delivers one: `WINHTTP_CALLBACK_STATUS_REQUEST_ERROR` with `{API_SEND_REQUEST, 605 and the failure arrives as WinHTTP delivers one: `WINHTTP_CALLBACK_STATUS_REQUEST_ERROR` with `{API_SEND_REQUEST,
391 ERROR_WINHTTP_CANNOT_CONNECT}`, on a thread-pool thread, with the request's context. A request closed first gets 606 ERROR_WINHTTP_CANNOT_CONNECT}`, on a thread-pool thread, with the request's context. A `dwContext` of 0 keeps the
392 no error callback. 607 context set with `WINHTTP_OPTION_CONTEXT_VALUE`, as the host's `winhttp.dll` does. A request closed first gets no
608 error callback.
393- Reading a response and `WinHttpWriteData` fail with `ERROR_WINHTTP_INCORRECT_HANDLE_STATE`. Options, timeouts and 609- Reading a response and `WinHttpWriteData` fail with `ERROR_WINHTTP_INCORRECT_HANDLE_STATE`. Options, timeouts and
394 headers are accepted; `WINHTTP_OPTION_CONTEXT_VALUE` and `WINHTTP_OPTION_HANDLE_TYPE` can be queried. 610 headers are accepted; `WINHTTP_OPTION_CONTEXT_VALUE` and `WINHTTP_OPTION_HANDLE_TYPE` can be queried.
395- A status callback is inherited by child handles, and so is the parent's `WINHTTP_OPTION_CONTEXT_VALUE` as it is 611- A status callback is inherited by child handles, and so is the parent's `WINHTTP_OPTION_CONTEXT_VALUE` as it is
diff --git a/docs/saves.md b/docs/saves.md
index 81527dd2c..f590f523c 100644
--- a/docs/saves.md
+++ b/docs/saves.md
@@ -81,7 +81,26 @@ The checksum at 0x160 matched none of these:
81It's left as **open**. Copy the header verbatim whenever the payload is unchanged. 81It's left as **open**. Copy the header verbatim whenever the payload is unchanged.
82 82
83Payloads: settings (kind 2) are hash-keyed JSON text with tabs and CRLF **(confirmed)**. The profile record (kind 3) 83Payloads: settings (kind 2) are hash-keyed JSON text with tabs and CRLF **(confirmed)**. The profile record (kind 3)
84is 1,644 bytes, only the first 112 non-zero, starting `u32 10, u32 3`. It isn't decoded yet. 84is 1,644 bytes (first 112 bytes non-zero, starting `u32 10, u32 3`, followed by 1,532 bytes of zero padding) **(confirmed)**.
85
86## Profile record (kind 3, confirmed)
87
88```
890x000 u32 version = 10 confirmed
900x004 u32 kind = 3 confirmed
910x008 u32 subversion / format tag likely
920x00C u32 flags likely
930x010 u64 account / profile identifier likely
940x018 u32[22] profile settings & attributes (first 112 bytes non-zero)
950x070 byte[1532] zero padding (reserved area) confirmed
96```
97
98The profile record (kind 3) has a fixed 1,644-byte payload. Only the first 112 bytes (0x70) contain active profile
99fields, starting with format version 10 and kind 3; the remaining 1,532 bytes (0x5FC) are zero padding reserved for
100future profile expansion and cloud sync.
101
102`tools/saves.py info` reports the profile version, active bytes and verifies the zero-padding boundary;
103`tools/saves.py extract` writes `profile.json`.
85 104
86## SLAYER1: packed copy (not decoded) 105## SLAYER1: packed copy (not decoded)
87 106
@@ -104,8 +123,10 @@ to it holds the same save. The wrapper's header is the only place the autosave's
104The runtime's offline `XGameSaveImpl` (`runtime/shims/xgameruntime_gamesave.cpp`, 123The runtime's offline `XGameSaveImpl` (`runtime/shims/xgameruntime_gamesave.cpp`,
105[runtime_imports.md](runtime_imports.md)) keeps `XGameSave` data in 124[runtime_imports.md](runtime_imports.md)) keeps `XGameSave` data in
106`LEONIDA_SAVE_DIR\local-user\<container>\<blob>`, defaulting to `%LOCALAPPDATA%\Leonida\saves`, with names 125`LEONIDA_SAVE_DIR\local-user\<container>\<blob>`, defaulting to `%LOCALAPPDATA%\Leonida\saves`, with names
107%-encoded. `python -I tools/saves.py import <save folder>... [--out DIR] [--map OLD=CONTAINER/BLOB]` writes payloads 126%-encoded. `python -I tools/saves.py import <save folder>... [--out DIR] [--map OLD=CONTAINER/BLOB] [--with-packed]`
108in that layout with the same encoding, plus `import-manifest.json` (source, size, SHA-256). 127writes payloads in that layout with the same encoding, plus `import-manifest.json` (source, size, SHA-256).
128`--with-packed` also imports `chives.dat`, the packed `SLAYER1` copy of the same save (below), as a blob of its own;
129without it only the plain payload is imported.
109 130
110Checked earlier with the shim of the open #279, which used the same layout: four imported blobs (2 KB to 1.2 MB) 131Checked earlier with the shim of the open #279, which used the same layout: four imported blobs (2 KB to 1.2 MB)
111read back byte-identical through its `XGameSaveReadBlobData`. 132read back byte-identical through its `XGameSaveReadBlobData`.
@@ -141,13 +162,16 @@ resolve most of them. The resolved names are game data and stay local; only coun
141 162
142## Tool 163## Tool
143 164
165`verify` reports on every supplied file. Its exit status is 2 if any file could not be read or parsed,
166otherwise 1 if any rebuild differed, otherwise 0.
167
144```powershell 168```powershell
145python -I tools/saves.py info <file or folder>... 169python -I tools/saves.py info <file or folder>...
146python -I tools/saves.py verify <JSAV> # parse every block, rebuild, compare byte for byte 170python -I tools/saves.py verify <JSAV>... # parse every block, rebuild, compare byte for byte
147python -I tools/saves.py extract <JSAV|ASAV> <outdir> # blocks/*.json, index.json, save.pretty.json 171python -I tools/saves.py extract <JSAV|ASAV> <outdir> # blocks/*.json, index.json, save.pretty.json
148python -I tools/saves.py pack <outdir> <JSAV> # after editing blocks/*.json 172python -I tools/saves.py pack <outdir> <JSAV> # after editing blocks/*.json
149python -I tools/saves.py diff <JSAV a> <JSAV b> 173python -I tools/saves.py diff <JSAV a> <JSAV b>
150python -I tools/saves.py import <save folder>... [--out DIR] [--map OLD=CONTAINER/BLOB] [--dry-run] [--force] 174python -I tools/saves.py import <save folder>... [--out DIR] [--map OLD=CONTAINER/BLOB] [--with-packed] [--dry-run] [--force]
151python -I tools/save_keys.py collect <save file or extract folder>... # distinct $0x… keys 175python -I tools/save_keys.py collect <save file or extract folder>... # distinct $0x… keys
152python -I tools/save_keys.py resolve <saves>... --dict <files>... [--compose N] [--out FILE] 176python -I tools/save_keys.py resolve <saves>... --dict <files>... [--compose N] [--out FILE]
153``` 177```
diff --git a/docs/shader_inputs.md b/docs/shader_inputs.md
index aa9da8759..72d5404f9 100644
--- a/docs/shader_inputs.md
+++ b/docs/shader_inputs.md
@@ -93,22 +93,20 @@ dword and the buffer's bounds first.
93 93
94#### Light shape size 94#### Light shape size
95 95
96Reported by @Silliana [on the pull request](https://github.com/ItsNotRexed/Leonida/pull/3157): +0x3C holds two f16, 96+0x3C holds two f16. How they are used depends on the light type (bits 30–31 at +0x28):
97the low half a sphere radius and the high half a range. Since intensity is radiance, the light's power grows with
98radius², so a radius that's too big (for example the range written into both halves) gives scattered single-pixel
99specular blowups that look like a translator bug.
100 97
101What the shader shows confirms the two f16 halves, but their use depends on the light type (bits 30–31 at +0x28): 98| Type | Low half | High half | Source |
99|---|---|---|---|
100| 0 | Sphere radius: clamped against the reflection ray to pick the closest point on the light. Brightness grows with radius², since intensity is radiance. | No effect. | Tested by @Silliana [on the pull request](https://github.com/ItsNotRexed/Leonida/pull/3157): radius 60 → 5 dimmed the light about 134× (radius² predicts 144×). |
101| not decoded | Half-size along one axis of a rectangle. | Half-size along the other axis. | Shader: the light's position is moved by ± each half along its axis, and points are clamped to those bounds. |
102| not decoded | — | A length along the light's axis (clamped to ± half of it), also squared and compared against a distance. Probably a tube light's length (@Silliana's hypothesis, not tested). | Shader. |
102 103
103- In one path they are the two half-sizes of a rectangle. The light's position is moved by ± the low half along one 104The low half also sets one blend factor. No range-style falloff was found: neither half divides a distance, and the
104 axis and ± the high half along the other, and points are clamped to those bounds. 105early reading of the high half as a range is dropped.
105- In another path the high half is a length along the light's axis (clamped to ± half of it), and it is also squared
106 and compared against a distance.
107- The low half also sets one blend factor.
108- No range-style falloff was found: neither half divides a distance.
109 106
110So a wrong value here makes the light the wrong size, and an oversized area light is a likely cause of the blowups. 107A value that's too big makes the light too large. On a sphere light, the brightness grows with the square of the
111Which light type reads the low half as a sphere radius isn't decoded yet. 108radius. That gives scattered single-pixel specular blowups that look like a translator bug, for example when a range
109is written into both halves (reported by @Silliana).
112 110
113#### Correction to #1892 111#### Correction to #1892
114 112
@@ -254,3 +252,53 @@ same 32-bit word to all four components of the storage image. The data is useles
254says. The layer's UAV path for `R9G9B9E5_SHAREDEXP` already covers this: on a GPU without native RGB9E5 storage it 252says. The layer's UAV path for `R9G9B9E5_SHAREDEXP` already covers this: on a GPU without native RGB9E5 storage it
255binds an `R32_UINT` storage view ([`d3d12_vulkan.md`](d3d12_vulkan.md), from #1375 and #1388). 253binds an `R32_UINT` storage view ([`d3d12_vulkan.md`](d3d12_vulkan.md), from #1375 and #1388).
256`CS_Transmittance` and `CS_SkyAtmosphereLUT` contain no RGB9E5 packing. 254`CS_Transmittance` and `CS_SkyAtmosphereLUT` contain no RGB9E5 packing.
255
256### The shared atmosphere constant buffer
257
258Reported by @Silliana in [#3990](https://github.com/ItsNotRexed/Leonida/issues/3990): the four passes read one
259atmosphere struct, each through its own buffer descriptor fetched from the resource table. Confirmed in the
260disassembly of the 1.0.2.1 package (llvm-mc 23.1.5, gfx1013): the 26,503-program corpus has exactly one program for
261each of the four names, and each reads the offsets below through a single descriptor. The three `sky_scattering`
262passes fetch that descriptor from table offset **+0x220**; `CS_SkyAtmosphereLUT` fetches it from **+0xC60**. So when
263one pass looks right and another looks wrong, check the slot binding before the layout. The +0xD0 output-format
264dword above sits in this same buffer.
265
266Everything is in km (#3990). Field names are #3990's reading; the offsets and the "consumed by" column are measured.
267A pass can load a dword as part of a wider load without using it, so "consumed" means an instruction reads the
268register before it is overwritten.
269
270| Offset | Type | Field (#3990) | Consumed by |
271|---|---|---|---|
272| +0x20 | f32 | Planet radius | all four |
273| +0x30 | f32 | Rayleigh scale height | none (loaded, see below) |
274| +0x34 | 3 × f32 | Rayleigh scattering RGB | all four |
275| +0x40 | f32 | Mie scale height | none (loaded, see below) |
276| +0x44 | 3 × f32 | Mie scattering RGB | all four |
277| +0x50 | f32 | Top of the atmosphere | all four |
278| +0x60 | 3 × f32 | Mie absorption RGB | all four |
279| +0x6C | f32 | Mie g (phase asymmetry) | `CS_SkyView` only |
280| +0x70 | f32 | Ozone layer width | all four |
281| +0x74 | 2 × f32 | Ozone below the layer: constant, slope | all four |
282| +0x7C | 2 × f32 | Ozone above the layer: constant, slope | all four |
283| +0x84 | 3 × f32 | Ozone absorption RGB | all four |
284| +0x90 | 3 × f32 | Sun direction | `CS_SkyView` only |
285| +0xA0 | 3 × f32 | Moon direction | `CS_SkyView` only |
286
287The two scale-height dwords are where the disassembly adds to #3990: every pass loads them inside a wide scalar
288load, but in all four programs the registers holding +0x30 and +0x40 are overwritten or never touched again before
289any instruction reads them. Only the RGB coefficients next to them are consumed. A wrong value in those two dwords
290cannot by itself explain a bad sky from these passes.
291
292The ozone block matches #3990's two-layer linear reading: the dword at +0x70 is compared per lane with a float
293(`v_cmp_gt_f32`) in the ozone block, the constant/slope pairs feed `v_fma_f32`, and the absorption RGB feeds the
294per-channel accumulate. `CS_SkyView` reads the sun direction at +0x90 and a second direction at +0xA0,
295which #3990 reads as the moon; its second output is the sky lit by that direction. The fourth dword of each
296direction (+0x9C, +0xAC) is not consumed.
297
298Some neighbouring dwords are read but not decoded here: +0x24 to +0x2C (next to the planet radius), +0x54 to +0x5C
299(`CS_SkyView`), and +0x04 to +0x13 (`CS_SkyView` and `CS_SkyAtmosphereLUT`).
300
301Sanity checks from #3990 (GPU experiments, not repeated here): zeroing the Rayleigh RGB makes the zenith go basically
302white, zeroing the ozone absorption mostly bumps green, and raising Mie g brightens the sky toward the sun. With
303Earth-like values `CS_Transmittance` lands within about 0.01 of a reference transmittance table, which makes it the
304cheapest pass to sanity-check a translation.
diff --git a/docs/shader_library.md b/docs/shader_library.md
new file mode 100644
index 000000000..6e29edc89
--- /dev/null
+++ b/docs/shader_library.md
@@ -0,0 +1,172 @@
1# The pipeline library in `shaders.rpf`
2
3**Status: measured** on the 1.0.2.1 package. `shaders.rpf` holds one more file behind its 26,503 shader entries:
4a library of precompiled pipelines, with 25,471 graphics and 2,693 compute pipeline records and the 21,522 native
5RDNA2 programs they run. `tools/shader_carve.py` reads only the raw-deflate shader entries, so until now nothing
6read this file. No program, blob or record is reproduced here; the tables hold counts, sizes and offsets.
7
8## 1. Where it is
9
10The archive's data area has two parts. The first 274 MB are the shader entries `shader_carve.py` reads (name,
11kind, sizes, raw deflate). The rest, from file offset `0x10579000`, is 4,205 zlib streams: 4,204 inflate to
1265,536 bytes and the last to 27,436. Concatenated, they form one 275,540,780-byte file. That is the 33.4%
13stream coverage [world_census.md](world_census.md) measured for `shaders.rpf`. The gaps between the streams are 0
14to 12 bytes.
15
16`tools/shader_library.py` finds the first stream that inflates to the header below and appends streams until it
17has the size the header gives. It fails if the sizes don't match exactly.
18
19**No shaders elsewhere.** The other 74 RPF9 and TTPF archives of the package (214 GB: the root archives except
20`movies.rpf`, and everything under `pack/` and `data/`) were scanned raw and through every zlib stream (about 420 GB
21inflated) for `DXBC`, `XBCH`, `FSSM`, `FSPX` and the shader entries' `_Wrapped` names. There are no shader entries,
22and none of the 148 `XBCH`/`FSSM` hits is a record: no `XBCH` inflates to an `FSSM` blob, and no `FSSM` has a code
23offset with an `s_endpgm` after it. The same checks accept the 52 records of `XboxBvhBuilder.dll` and 200 of 200
24carved FSSM blobs. No `DXBC` hit has a valid header. So the game's shader programs are the shader entries, this
25library and the two DLLs' containers ([embedded_shaders.md](embedded_shaders.md)), as far as raw and zlib data go.
26
27## 2. Layout
28
29All values little-endian.
30
31| offset | size | field |
32|---|---:|---|
33| 0x00 | 4 | `'P' 'S' 00 09` |
34| 0x04 | 32 | name, NUL-padded: `0x65F41EDD` |
35| 0x24 | 36 | version string, NUL-padded: `930.048.020` |
36| 0x48 | 8 | hash |
37| 0x50 | 4 × 4 | graphics pipelines G = 25,471, compute pipelines C = 2,693, blobs B = 54,576, programs P = 21,522 |
38| 0x60 | 4 | blob section size, 31,120,020 |
39| 0x64 | 4 | code section size, 240,894,464 |
40| 0x80 | G × 0x70 | graphics pipeline records |
41| | C × 24 | compute pipeline records |
42| | B × 8 | blob table: (offset, size) into the blob section |
43| | P × 8 | program table: (offset, size) into the code section; every offset is 256-byte aligned |
44| | | blob section, then code section |
45
46The sections add up to the file size exactly: 0x80 + 25,471 × 0x70 + 2,693 × 24 + 54,576 × 8 + 21,522 × 8 +
4731,120,020 + 240,894,464 = 275,540,780. Every blob and program entry lies inside its section. The blob entries
48are contiguous; the program entries are in increasing offset order.
49
50**Graphics record** (0x70 bytes): u64 hash, u32 state blob, u32 pipeline blob, 40 bytes not decoded, then seven
51(u32 program, u32 stage blob) pairs. 0xFFFFFFFF means no program. The slot gives the stage. Slot 0 is the pixel
52shader, slot 1 the vertex shader and slot 2 the mesh shader. The source containers named in §3 have those stages
53in every use §3 links: 24,090 of the 24,111 slot-0 uses, 13,388 of 13,409 slot-1 and all 12,062 slot-2. No linked
54use names a source of another stage. Slot 6 is used by 2 records with one program and no stage blob; it is not
55identified. Slots 3 to 5 are never used.
56
57| stages | pipelines |
58|---|---:|
59| VS + PS | 13,383 |
60| MS + PS | 10,726 |
61| MS only | 1,336 |
62| VS only | 24 |
63| VS + PS + slot 6 | 2 |
64
65The state blob is 388 to 472 bytes (5,680 distinct). The pipeline blob holds the input layout, with element
66names such as `POSITION`, `COLOR`, `TEXCOORD`, `NORMAL`, `TANGENT`, `BLENDWEIGHT` and `BLENDINDICES` for vertex
67pipelines (80 bytes, with no elements, for mesh pipelines).
68
69**Compute record** (24 bytes): u64 hash, u32 state blob, u32 blob, u32 program, u32 layout blob. The four parts
70have the sizes and shapes of the four [FSPX](fspx.md) kinds:
71
72| record field | size | FSPX kind |
73|---|---|---|
74| state blob | 28 bytes in all 2,693 | kind 0, dispatch state: thread-group size in words 3-4, wave32 flag (word 4 bit 20), RSRC1, RSRC2 |
75| blob | 20 bytes in all 2,693 | kind 1 |
76| program | | kind 6 |
77| layout blob | 56 to 10,552 bytes | kind 7 |
78
791,529 of the 2,684 compute programs set the wave32 flag. 90 set RSRC2 `TG_SIZE_EN` (bit 10), which none of the
802,689 carved compute shaders do.
81
82**Programs.** 52 to 239,464 bytes (median 3,968; 238,829,764 in total), padded to 256 bytes with `s_code_end`.
8321,463 of them start with the 36-byte prologue FSPX programs have, three 12-byte VOP3 opcode-0x180 words with
84literals (`fspx_unpack.code_range` finds it); 59 have none. The code runs from there to the last 4-byte-aligned
85`s_endpgm`, as for FSSM blobs. 579 of the first 3,000 pixel programs have more than one. Ending at the first one,
86as for FSPX, cut off code their branches reach: 2,281 "branch target outside code" and 1,662 "branch into data" over
87all stages.
88Each program belongs to exactly one stage: 9,996 PS, 7,498 MS, 2,684 CS, 1,343 VS and the one slot-6 program.
89
90## 3. Where the programs come from
91
92A graphics stage blob and a compute layout blob share one layout. Word 0 is the kind (2 for a graphics stage, 3
93for compute). Then comes a head of 16 bytes (kind 2) or 24 bytes (kind 3), whose last word is tagged `0x40`. Then
94come 32-byte records tagged `0x41` or `0x42`, then a word `0x43`, a 16-byte digest and 12 zero bytes. All 20,318
95distinct stage and layout blobs follow this. In FSPX, the 16 bytes after kind 7's `0x43` word are the container's
96`HASH` digest ([fspx.md](fspx.md)). Here they are too: **21,509 of the 21,522 programs** have the `HASH` digest of
97one of the carved containers, and every linked program has its container's stage (2,680 CS, 9,991 PS, 7,498 MS,
981,340 VS; the carve index's stage comes from the container's `DXIL` program header). They come from 6,522
99distinct carved shaders, and a source has 1 to 257 programs.
100
101None of the programs is byte-identical to its source's FSSM code. Only 47 distinct code bodies, from
102`s_inst_prefetch` to the first `s_endpgm`, occur in both. So the library holds **pipeline builds**: the same
103shaders compiled again with their pipeline's state. The 13 programs whose digest names no carved container (4 CS,
1045 PS, 3 VS, the slot-6 program) are the only ones with no source in the shader entries.
105
106## 4. Tool
107
108```sh
109python -I tools/shader_library.py <package>/shaders.rpf --out <work>/library --disasm --carve <work>/shaders/dxbc
110python -I tools/rdna2spirv.py <work>/library/disasm --out <work>/library/spirv
111```
112
113* It writes `fspx/<name>.code` and `fspx/<name>.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py`
114 reads (`native_blob`, `cs_dispatch_state`). It also writes `index.json` with each program's stage, and
115 `library.json` with the header and both pipeline tables, stage to program name. Programs are named
116 `lib_<stage>_<index>`.
117* `--disasm` writes `disasm/<name>.s` for the code after the prologue, as `fspx_unpack.py --disasm` does.
118* `--carve` names each program's source shaders. It copies the first source container to `<name>.dxbc`, because
119 the translator reads the stage's signatures and `PSV0` from there. Pipeline compilation keeps the D3D12 stage
120 interface.
121* `--save` writes the reassembled library. A saved file is also accepted as input.
122* `--stages` limits the output to some stages.
123
124The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and
125archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest
126walk. It also checks the `--carve` copy and the translator's reads of the compute sidecar.
127
128## 5. Translation
129
130With `--carve` and `rdna2spirv.py` at `main` `aa2988cc` (llvm-mc 23, `gfx1013`), **17,955 of the 21,522 programs
131translate and pass `spirv-val`**:
132
133| stage | programs | pass `spirv-val` |
134|---|---:|---:|
135| VS | 1,343 | 1,333 (99.3%) |
136| MS | 7,498 | 7,059 (94.1%) |
137| PS | 9,996 | 7,719 (77.2%) |
138| CS | 2,684 | 1,844 (68.7%) |
139| slot 6 | 1 | 0 (stage not identified) |
140
141What stops the rest, by the translator's message:
142
143* **2,533 programs: "reachable instruction with normalized encoding".** llvm-mc rejects scalar register tuples that
144 run into `vcc` (SGPRs 106 and 107): `s_load_dwordx8`/`x4`/`x16` writing `s[100:107]`, `s[104:107]` or
145 `s[92:107]`, and image instructions whose resource is `s[100:107]`. In the compute programs alone that is 37,952
146 SMEM, 22,248 MIMG and 2,298 MUBUF words. The same words with the register field one tuple lower decode; with
147 `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. A decoder
148 fallback for these encodings would cover most of the remaining programs. The translator already reads
149 `[s100,...,vcc_lo,vcc_hi]` lists (design.md *Scalar/buffer memory*).
150* **443: an instruction llvm-mc prints with another encoding than the blob's** (`v_fma_mix*`, `v_interp_p2_f16`):
151 the existing `check_printed_encodings` refusal.
152* **90 CS: "CS thread-group-size SGPR"**: RSRC2 `TG_SIZE_EN`, which no FSSM compute shader sets.
153* **68 translate but fail `spirv-val`**, mostly "requires a previous definition".
154* Fewer than 30 each: `ds_append`, `s_bitreplicate_b64_b32` and `s_flbit_i32_b64` on a lane mask, `v_cmp` and mask
155 destinations, 25 branches into data, 10 undecodable words that can't be re-anchored, and a few `vcc`/`ttmp`
156 operands.
157* Programs with no source container: a PS or MS one has no signatures and is `Unsupported` (the reads now raise
158 that instead of `FileNotFoundError`, which stopped the whole run). A VS that fetches no inputs translates without
159 one.
160
161None of the programs has been run on a GPU.
162
163## 6. What this changes
164
165* **Pipeline pairing is in the package.** [d3d12_vulkan.md](d3d12_vulkan.md) question 14 asks whether a PSO pairs
166 two code-base stages, and says the pairing is in the executable. The graphics records give it for 25,471
167 pipelines: each names its VS or MS and its PS. Each source can be found through §3.
168* **A second compiled form of 6,522 shaders.** The pipeline builds differ from the FSSM code. Which form the game
169 runs for a pipeline is not measured here (that needs the executable). Either way, a translated pipeline build can
170 be compared with the translated FSSM shader of the same pipeline.
171* **Not decoded.** The graphics state blob, the 40 bytes in each graphics record, the compute kind-1 blob, the
172 records inside the stage blobs, and slot 6.
diff --git a/docs/shader_validation.md b/docs/shader_validation.md
index ef4d44edc..fe9b6b4d7 100644
--- a/docs/shader_validation.md
+++ b/docs/shader_validation.md
@@ -5,7 +5,7 @@ the corpus is correct. The CPU differential oracle in `tools/shader_diff.py` is
5tested (`tests/test_shader_diff.py`): it compares the ISA model in `tools/cpu_ref.py` against 5tested (`tests/test_shader_diff.py`): it compares the ISA model in `tools/cpu_ref.py` against
6translated SPIR-V run in `tests/semantic/spirv_mini_interp.py` over seeded straight-line programs. 6translated SPIR-V run in `tests/semantic/spirv_mini_interp.py` over seeded straight-line programs.
7Run it with `python -I tools/shader_diff.py --programs 200 --seed 7` (`--self-test` checks the 7Run it with `python -I tools/shader_diff.py --programs 200 --seed 7` (`--self-test` checks the
8harness itself). The GPU-side runners are described below: `tools/valu_fuzz.py` (16-bit and memory ops), `tools/lds_fuzz.py`, `tools/crosslane_fuzz.py` and `tools/cf_diff.py`. 8harness itself). The GPU-side runners are described below: `tools/valu_fuzz.py` (16-bit and memory ops), `tools/lds_fuzz.py`, `tools/crosslane_fuzz.py`, `tools/cf_diff.py` and `tools/ab_control_flow.py` (corpus pixel shaders in both control-flow forms).
9 9
10## Why `spirv-val` is not enough 10## Why `spirv-val` is not enough
11 11
@@ -48,6 +48,14 @@ a reference to be trusted. A hand-written SPIR-V twin of a test program is a use
48checks the harness and driver without involving the translator, so a harness failure is not blamed on 48checks the harness and driver without involving the translator, so a harness failure is not blamed on
49translation. 49translation.
50 50
51Assembling needs no external `spirv-as` binary: `tools/spirv_asm.py` encodes SPIR-V assembly text into binary
52words in process, as a module (`assemble(text, target_env="vulkan1.2")`) or from the command line
53(`python -I tools/spirv_asm.py in.spvasm -o out.spv`, with `--target-env` choosing the environment and
54`vulkan1.2` the default), using the Khronos SPIRV-Headers grammar kept in `tools/spirv_asm_tables.py`.
55`tools/rdna2spirv.py --assembler python` takes that path instead of the `spirv-as` subprocess and its
56temporary `.spvasm` file; `spirv-val` stays the external validator. `tests/test_spirv_asm.py` and
57`tests/test_spirv_asm_tables.py` cover the assembler and the tables.
58
51The CPU model is deliberately not a second translator. It interprets the listing's mnemonics and 59The CPU model is deliberately not a second translator. It interprets the listing's mnemonics and
52operands; it never consumes SPIR-V. That independence is what makes a disagreement meaningful. 60operands; it never consumes SPIR-V. That independence is what makes a disagreement meaningful.
53 61
@@ -177,8 +185,8 @@ Setup on Windows, about 800 MB and no admin rights:
177 185
178- **Driver.** The AMD Windows driver ships the HIP runtime as `amdhip64_7.dll` in System32; nothing else is 186- **Driver.** The AMD Windows driver ships the HIP runtime as `amdhip64_7.dll` in System32; nothing else is
179 loaded from the SDK. `LEONIDA_HIP_DLL` overrides the path. Drivers from 2024 ship `amdhip64_6.dll` instead and 187 loaded from the SDK. `LEONIDA_HIP_DLL` overrides the path. Drivers from 2024 ship `amdhip64_6.dll` instead and
180 refuse code object v6 (LLVM 23's default) with error 209; the oracle then assembles as v5 (seen with driver 188 refuse code object v6 (LLVM 23's default) with error 209 (`hipErrorNoBinaryForGpu`) or 303 (`hipErrorSharedObjectInitFailed`);
181 32.0.11020.1002 on gfx1103). 189 the oracle then assembles as v5 (seen with driver 32.0.11020.1002 on gfx1103 and 31.0.24002.92 on gfx1036).
182- **true16.** LLVM 23 wants `v8.l`, not `v8`, for 16-bit operands on GFX11. The oracle asks the assembler once and 190- **true16.** LLVM 23 wants `v8.l`, not `v8`, for 16-bit operands on GFX11. The oracle asks the assembler once and
183 uses the spelling it takes, for the ops its tools run: the two f16/f32 conversions and `f16_trans_sweep.py`'s 191 uses the spelling it takes, for the ops its tools run: the two f16/f32 conversions and `f16_trans_sweep.py`'s
184 seven. Another f16 op needs adding to `asm.true16_spelling`. 192 seven. Another f16 op needs adding to `asm.true16_spelling`.
@@ -186,7 +194,9 @@ Setup on Windows, about 800 MB and no admin rights:
186 target. The ROCm wheel has one: 194 target. The ROCm wheel has one:
187 `py -m venv .venv` then `.venv\Scripts\python -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ "rocm-sdk-core==10.0.0"`; 195 `py -m venv .venv` then `.venv\Scripts\python -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ "rocm-sdk-core==10.0.0"`;
188 `clang.exe` ends up in `.venv\Lib\site-packages\_rocm_sdk_core\lib\llvm\bin`. A `.venv` in the working 196 `clang.exe` ends up in `.venv\Lib\site-packages\_rocm_sdk_core\lib\llvm\bin`. A `.venv` in the working
189 directory or repository is found by itself; otherwise set `LEONIDA_AMD_CLANG` to that `clang.exe`. 197 directory or repository is found by itself, and so is the wheels' `amdclang` on PATH: that launcher has no
198 `ld.lld` beside it, so the oracle uses the `clang.exe` in the folder it reports as `InstalledDir`. Otherwise set
199 `LEONIDA_AMD_CLANG` to that `clang.exe`.
190- **Linux** has a launcher of its own, without ROCm: see the next list. `hw_oracle.c` is the Windows one (it loads 200- **Linux** has a launcher of its own, without ROCm: see the next list. `hw_oracle.c` is the Windows one (it loads
191 the driver's DLL). 201 the driver's DLL).
192- **Host C compiler.** `tools/hw_oracle/hw_oracle.c` is built once into the temp folder by MinGW gcc (on PATH or in 202- **Host C compiler.** `tools/hw_oracle/hw_oracle.c` is built once into the temp folder by MinGW gcc (on PATH or in
@@ -220,8 +230,13 @@ through the kernel driver (`libdrm_amdgpu`), so nothing sits between the instruc
220 object, so the `.amdhsa_*` directives take effect as they do under the HIP runtime: register counts, float 230 object, so the `.amdhsa_*` directives take effect as they do under the HIP runtime: register counts, float
221 rounding and denormal modes, IEEE mode, DX10 clamp. A test checks that an f32 rounding mode set there changes 231 rounding and denormal modes, IEEE mode, DX10 clamp. A test checks that an f32 rounding mode set there changes
222 a sum on the hardware. 232 a sum on the hardware.
223 - A descriptor that asks for something the launcher does not provide (LDS, scratch memory, more than the 233 - The descriptor's group segment becomes `COMPUTE_PGM_RSRC2.LDS_SIZE` (bits 15..23, 512-byte units). The
224 kernarg pointer in the user SGPRs) is refused instead of being run differently. 234 assembler leaves that field 0, so the launcher programs it from the group segment, as the HIP runtime does;
235 a kernel with LDS reads back what it wrote there (`tests/test_hw_oracle.py`, measured on gfx1036).
236 - A descriptor that asks for something the launcher does not provide (scratch memory, more than the kernarg
237 pointer in the user SGPRs, more than 65,536 bytes of LDS) is refused instead of being run differently.
238 - The output buffer takes up to 16,384 words, as the Windows launcher does, so a 64x64 `image_fuzz` case (16,384
239 words) runs here too.
225 - Every submission gets command memory of its own. While one buffer was rewritten in place, the second kernel of 240 - Every submission gets command memory of its own. While one buffer was rewritten in place, the second kernel of
226 a process ran the first one's commands, every time; `tests/test_hw_oracle.py` runs 300 distinct kernels to 241 a process ran the first one's commands, every time; `tests/test_hw_oracle.py` runs 300 distinct kernels to
227 catch that. 242 catch that.
@@ -510,9 +525,19 @@ python -I tools/lds_fuzz.py --oracle hw --programs 50 --seed 1 --wave 32 --only
510 **`ds_cmpstore_rtn_b32` takes the value to store before the compare value**, the reverse of GFX10's 525 **`ds_cmpstore_rtn_b32` takes the value to store before the compare value**, the reverse of GFX10's
511 `ds_cmpst_rtn_b32 vdst, vaddr, cmp, store`; llvm-mc encodes both spellings of the same text identically, so only 526 `ds_cmpst_rtn_b32 vdst, vaddr, cmp, store`; llvm-mc encodes both spellings of the same text identically, so only
512 the operand order says which. Unswapped, every program with a `cmpst` failed on gfx1150 (each minimized to that one 527 the operand order says which. Unswapped, every program with a `cmpst` failed on gfx1150 (each minimized to that one
513 op); swapped, none does. This is measured on GFX11 only: on gfx12xx the programs with a `cmpst` are skipped with 528 op); swapped, none does. GFX12 takes the same order (measured on an RX 9070 XT, gfx1201: with 7 in the dword and
514 that reason. The model keeps the GFX10 order. Nothing else the generator emits is missing on GFX11, so no other 529 data `v1 = 9`, `v2 = 7` it becomes 9, with `v1 = 7`, `v2 = 9` it stays 7, for `ds_cmpstore_rtn_b32` and
515 program is skipped for its semantics; an assembler rejection is counted as `rejected`, never as a pass. 530 `ds_cmpstore_b32`; gfx1036's `ds_cmpst` does the opposite), and with `--perturb cmpst_swap` 275 of 1,000 wave32
531 programs mismatch there. The model keeps the GFX10 order. Nothing else the generator emits is missing on GFX11, so
532 no other program is skipped for its semantics; an assembler rejection is counted as `rejected`, never as a pass.
533- **GFX12** (`hw_oracle/asm.py` `sync_lines`): there is no `s_barrier` (a workgroup barrier is
534 `s_barrier_signal -1` then `s_barrier_wait -1`), and the LDS wait is `s_wait_dscnt 0` instead of the legacy
535 `s_waitcnt lgkmcnt(0)`. **A wave64 `ds_bpermute_b32` reaches all 64 lanes on GFX12**, while RDNA2 (and gfx1150)
536 keep each 32-lane half separate: with every lane asking for lane `(l + 32) mod 64`, the RX 9070 XT returns lane
537 `l ^ 32` and a gfx1036 iGPU returns lane `l`. The model describes RDNA2, so on gfx12xx a wave64 program with a
538 `ds_bpermute` is skipped with that reason; under `--perturb bpermute_wave64_cross` all 1,000 wave64 programs of
539 seed 1 match there. RX 9070 XT, AMD 26.11.2, `--programs 1000`, seeds 1 and 2: wave32 1,000/1,000 match; wave64
540 537 and 506 match, 0 mismatch, the rest skipped for that reason. The gfx1036 iGPU gives 1,000/1,000 in both.
516- **Wider op mix**, opt-in so that a seed keeps its programs: `--permute` (`ds_permute_b32`), `--swizzle-exec` 541- **Wider op mix**, opt-in so that a seed keeps its programs: `--permute` (`ds_permute_b32`), `--swizzle-exec`
517 (`ds_swizzle_b32` under EXEC masks), `--threads`, `--extended` (all three). `ds_permute_b32` and a masked 542 (`ds_swizzle_b32` under EXEC masks), `--threads`, `--extended` (all three). `ds_permute_b32` and a masked
518 `ds_swizzle_b32` carry a hypothesis (the model's reading of the ISA text); on the hardware a failing one is a 543 `ds_swizzle_b32` carry a hypothesis (the model's reading of the ISA text); on the hardware a failing one is a
@@ -569,10 +594,20 @@ hardware gives 0 (the swizzle hypothesis above). So the translator differs from
569fixed here. Partial-wave programs (`--threads` 32 594fixed here. Partial-wave programs (`--threads` 32
570in wave64) are skipped for the translator, which cannot launch them. NVIDIA was not run. 595in wave64) are skipped for the translator, which cannot launch them. NVIDIA was not run.
571 596
572**Other backends.** The Linux libdrm launcher of #1265 (`tools/hw_oracle/drm.py`) does not run these programs yet: 597**Other backends.** The Linux libdrm launcher of #1265 (`tools/hw_oracle/drm.py`) now runs these programs too. It
573it refuses a kernel with LDS and caps the output at 4096 words, and `lds_fuzz` turns that refusal into exit 77 598programs `COMPUTE_PGM_RSRC2.LDS_SIZE` from the descriptor's group segment (the assembler leaves that field 0, so the
574("unavailable"). Linux RDNA2 results need LDS and a larger word count in that backend first; the gfx1036 numbers 5994,096 bytes of LDS `lds_fuzz` asks for reach the hardware) and its output buffer takes 16,384 words like the Windows
575above come from the Windows HIP launcher. 600launcher's, so a 64x64 `image_fuzz` case fits. On the integrated Radeon of a Ryzen 7 7700X (gfx1036, RDNA2, Linux
6017.3.5-zen1-1-zen, libdrm 2.4.134, AMD clang 23.1.5):
602
603| Run | Programs / cases | Mismatches |
604| --- | --- | --- |
605| `lds_fuzz.py --oracle hw --programs 500 --seed 1` (wave32 and wave64) | 1,000 | 0 |
606| `image_fuzz.py --oracle hw --programs 120 --seed 1` (60 cases per wave; 8 to 64 per side, four 64x64 cases) | 120 | 0 |
607
608`lds_fuzz --oracle hw` no longer exits 77 on Linux for LDS or the word count. The gfx1036 numbers earlier in this
609section are still from the Windows HIP launcher; these two runs put the same model on the same architecture through
610libdrm.
576 611
577**Overlap with #789.** #789 adds `ds_permute_b32` to the default op mix of `lds_fuzz.py`; here it is opt-in 612**Overlap with #789.** #789 adds `ds_permute_b32` to the default op mix of `lds_fuzz.py`; here it is opt-in
578(`--permute`) so that existing seeds keep their programs. Whichever lands second reconciles the two. 613(`--permute`) so that existing seeds keep their programs. Whichever lands second reconciles the two.
@@ -614,7 +649,10 @@ instruction. The reference decodes elements from the GFX10 format *name* in `too
614MUBUF repeats missing channels (*c* mod *n*) and DST_SEL 1 gives integer 1 for UINT/SINT and 1.0f 649MUBUF repeats missing channels (*c* mod *n*) and DST_SEL 1 gives integer 1 for UINT/SINT and 1.0f
615otherwise (SHADER-86, RX 6700). MTBUF loads return instruction-format channels in order, zero-fill 650otherwise (SHADER-86, RX 6700). MTBUF loads return instruction-format channels in order, zero-fill
616missing channels and return zero for an INVALID V# format (native gfx1036, wave32 and wave64). 651missing channels and return zero for an INVALID V# format (native gfx1036, wave32 and wave64).
617Elements are naturally aligned. 652Elements are naturally aligned. A half NaN widens to f32 with its payload shifted into the f32 mantissa
653and its sign and quiet bit unchanged (`f16_to_f32`, bit-level so the Python version cannot change it);
654the translator used to canonicalise it, which is the one class this fuzzer found
655(`docs/shader_validation.md`, "Widening a 16-bit float NaN in a typed buffer load").
618 656
619Over 5,000 programs the reference and translator match bit for bit; breaking the `16_16_SNORM` kind, the 657Over 5,000 programs the reference and translator match bit for bit; breaking the `16_16_SNORM` kind, the
620`8_8_8_8_UINT` widths or the DST_SEL order in the translator makes 33, 37 and 191 of 300 programs fail. 658`8_8_8_8_UINT` widths or the DST_SEL order in the translator makes 33, 37 and 191 of 300 programs fail.
@@ -677,6 +715,7 @@ c / 255. llvmpipe multiplies by an f32 1/255, which is one ulp above that for 12
6770x3dd8d8da, not 0x3dd8d8d9), and a run stops at its first mismatch, so on llvmpipe no case after the first 7150x3dd8d8da, not 0x3dd8d8d9), and a run stops at its first mismatch, so on llvmpipe no case after the first
678`R8G8B8A8_UNORM` one ran. The translator oracle therefore accepts one ulp on a UNORM8 texel component, never on 716`R8G8B8A8_UNORM` one ran. The translator oracle therefore accepts one ulp on a UNORM8 texel component, never on
679another format or on a sentinel, and the summary says how many components needed it. `--oracle hw` stays bit exact. 717another format or on a sentinel, and the summary says how many components needed it. `--oracle hw` stays bit exact.
718
680Each run keeps its generated files in a unique output folder. With `--work DIR`, it is a new child of `DIR` and its 719Each run keeps its generated files in a unique output folder. With `--work DIR`, it is a new child of `DIR` and its
681path is printed; existing contents and other runs are left alone. Without `--work`, it is in the system temporary folder. 720path is printed; existing contents and other runs are left alone. Without `--work`, it is in the system temporary folder.
682 721
@@ -691,9 +730,10 @@ Covered: 2D `image_load`, `R8G8B8A8_UNORM`, `R16G16B16A16_SFLOAT`, `R32G32B32A32
691and `R8G8B8A8_UINT`/`SINT`, all as sampled images, as the runtime binds a read-only texture (integer formats are 730and `R8G8B8A8_UINT`/`SINT`, all as sampled images, as the runtime binds a read-only texture (integer formats are
692read through the translator's uint/sint aliases of the sampled array). The shader converts the loaded 8-bit integer values to float for 731read through the translator's uint/sint aliases of the sampled array). The shader converts the loaded 8-bit integer values to float for
693readback; every such value is exactly representable, including signed negatives. Wider integers are not covered. 732readback; every such value is exactly representable, including signed negatives. Wider integers are not covered.
694Texture sizes divide the 64x64 draw (8/16/32/64), so every texel is read at least once. The nonzero masks cycle from 733Texture sizes divide the 64x64 draw (8/16/32/64), so every texel is read at least once. The mask cycle starts with
695`0xf` through `0x1`–`0xe`; 90 programs cover all 15 masks for each of the six default formats. Selected channels 734`0xf` and `0x5`, so the default eight programs already exercise packing across a gap. With 90 programs, each of the
696are packed into consecutive destination registers, while unwritten registers keep initialized sentinel values. 735six default formats exercises all 15 nonzero masks. Selected channels are packed into consecutive destination
736registers, while unwritten registers keep initialized sentinel values.
697The packing model follows the image VGPR usage description in AMD's 737The packing model follows the image VGPR usage description in AMD's
698[RDNA 1.0 ISA guide](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna-shader-instruction-set-architecture.pdf); 738[RDNA 1.0 ISA guide](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna-shader-instruction-set-architecture.pdf);
699the Vulkan test compares translated shaders on the host GPU, not native RDNA2 execution. 739the Vulkan test compares translated shaders on the host GPU, not native RDNA2 execution.
@@ -783,11 +823,10 @@ Negative control (`--oracle hw --programs 180 --seed 1 --negative-control`): the
783`sint_unsigned` 30, `alpha_zero` 16, `dmask_in_place` 132, `no_sentinels` 168, `transpose` 166), and a kernel built 823`sint_unsigned` 30, `alpha_zero` 16, `dmask_in_place` 132, `no_sentinels` 168, `transpose` 166), and a kernel built
784with the next format's `FORMAT` code is caught on every format (24 to 30 of 30 cases each). So the GFX10 T# words of 824with the next format's `FORMAT` code is caught on every format (24 to 30 of 30 cases each). So the GFX10 T# words of
785`hw_oracle/tsharp.py` and the texel-fetch model hold on RDNA2 for these formats; `--oracle translator,hw` was not run 825`hw_oracle/tsharp.py` and the texel-fetch model hold on RDNA2 for these formats; `--oracle translator,hw` was not run
786there. The Linux libdrm backend of #1265 826there. The Linux libdrm backend of #1265 (`tools/hw_oracle/drm.py`) now runs these cases too: `--oracle hw
787(`tools/hw_oracle/drm.py`) was not tried: it copies only `.text` (the texture is in `.text`, so that works in 827--programs 120 --seed 1` on the same gfx1036 iGPU matched on 120 of 120 cases (60 per wave), four of them 64x64 and
788principle, but it needs the loaded code to be 256-byte aligned, which the kernel checks and reports) and the LDS 828therefore 16,384 words, with no rejections (Linux 7.3.5-zen1-1-zen, libdrm 2.4.134, AMD clang 23.1.5). It copies
789section above records a 4096-word output cap there, while a 64x64 case stores 16,384 words. The RDNA2 results above 829only `.text`, which is where the texture lives, and the loaded code is 256-byte aligned.
790are from the Windows HIP launcher only.
791 830
792### 32-bit integer VALU in every encoding (`tools/vint_diff.py`) 831### 32-bit integer VALU in every encoding (`tools/vint_diff.py`)
793 832
@@ -1006,6 +1045,9 @@ every scalar. `vk_compute_test` reads them back with `VKC_OUT_WORDS` / `VKC_DUMP
1006 On a discrete RDNA2 card (RX 6700 XT, gfx1031, Windows, Adrenalin 26.8.1, through the HIP DLL of the driver; 1045 On a discrete RDNA2 card (RX 6700 XT, gfx1031, Windows, Adrenalin 26.8.1, through the HIP DLL of the driver;
1007 BUILD-162): with `--dpp`, seeds 1 to 8, 1,000 programs each (500 per wave size), all 8,000 match, 984 of them 1046 BUILD-162): with `--dpp`, seeds 1 to 8, 1,000 programs each (500 per wave size), all 8,000 match, 984 of them
1008 `hyp_dpp` and 1,964 `hyp_permlane`. 1047 `hyp_dpp` and 1,964 `hyp_permlane`.
1048 On RDNA4 (RX 9070 XT, gfx1201, Windows, Adrenalin 26.11.2, `amdhip64_7.dll`, AMD clang 23.0.0git from the
1049 `rocm-sdk` wheels): the same eight runs, all 8,000 match, with the same 984 `hyp_dpp` and 1,964 `hyp_permlane`
1050 programs. gfx1201 is not RDNA2: the match supports the model and settles nothing about the console.
1009- **DPP sweep (`--dpp-sweep`, BUILD-162).** The random `--dpp` programs run full waves, four ops and mostly 1051- **DPP sweep (`--dpp-sweep`, BUILD-162).** The random `--dpp` programs run full waves, four ops and mostly
1010 `row_mask`/`bank_mask` 0xF, so a rare control or mask pair can go untested for many seeds. `--dpp-sweep` replaces 1052 `row_mask`/`bank_mask` 0xF, so a rare control or mask pair can go untested for many seeds. `--dpp-sweep` replaces
1011 the random programs with one short program per case: an EXEC write, then one DPP op. It covers every DPP16 control 1053 the random programs with one short program per case: an EXEC write, then one DPP op. It covers every DPP16 control
@@ -1027,6 +1069,9 @@ every scalar. `vk_compute_test` reads them back with `VKC_OUT_WORDS` / `VKC_DUMP
1027 run (`--oracle translator,hw`), the translator matches all of them as well: 7,206 wave32 native and 7,206 wave64 1069 run (`--oracle translator,hw`), the translator matches all of them as well: 7,206 wave32 native and 7,206 wave64
1028 `--wave64-emulate`, with 0 rejected and 0 harness errors. One `vk_compute_test` runs per case, so the translator 1070 `--wave64-emulate`, with 0 rejected and 0 harness errors. One `vk_compute_test` runs per case, so the translator
1029 side takes about 90 minutes there; the hardware side takes about one. 1071 side takes about 90 minutes there; the hardware side takes about one.
1072 On the RX 9070 XT (gfx1201, the setup above), `--dpp-sweep --oracle hw --wave both`: 14,412 cases, match 14,412,
1073 mismatch 0 in every family, 40 of them `hyp_dpp`, in half a minute. The same DPP rules hold on RDNA4; the
1074 translator side was not run there.
1030 First results (Radeon 880M, driver 26.11.2): 24,000 programs on the hardware, half wave32 and half native 1075 First results (Radeon 880M, driver 26.11.2): 24,000 programs on the hardware, half wave32 and half native
1031 wave64, seeds 11 to 16 (4,000 programs each), with and without `--dpp`, 12 to 60 ops, with and without 1076 wave64, seeds 11 to 16 (4,000 programs each), with and without `--dpp`, 12 to 60 ops, with and without
1032 `--no-maskdata` and `--no-hw-guard`: match 24,000, mismatch 0, hyp_only 0, rejected 0. 7,652 of them contained 1077 `--no-maskdata` and `--no-hw-guard`: match 24,000, mismatch 0, hyp_only 0, rejected 0. 7,652 of them contained
@@ -1049,8 +1094,47 @@ First results on an RTX 4090 (subgroup 32, driver 621.14):
1049 should be left unwritten (invalid source without `bound_ctrl`, or a lane off in `row_mask`/`bank_mask`), and 1094 should be left unwritten (invalid source without `bound_ctrl`, or a lane off in `row_mask`/`bank_mask`), and
1050 DPP16 ignored `fi:1`. Each was confirmed with a hand-written program. 1095 DPP16 ignored `fi:1`. Each was confirmed with a hand-written program.
1051- **Everything else matches.** On `main`, 1,000 programs (`--seed 8 --ops 28 --no-maskdata --no-w32-hi-lanes`, 500 wave32 native and 500 wave64 emulated) give 0 mismatches. 297 of them are `hyp_only` (permlane with FI = 0 and an inactive source), and with `--permlane-fetch-inactive` all 1,000 match. Native wave64 on the 32-wide card mismatches as documented: `s_bcnt1` of EXEC counts one half, and a `v_readlane` from the other half wraps. 1096- **Everything else matches.** On `main`, 1,000 programs (`--seed 8 --ops 28 --no-maskdata --no-w32-hi-lanes`, 500 wave32 native and 500 wave64 emulated) give 0 mismatches. 297 of them are `hyp_only` (permlane with FI = 0 and an inactive source), and with `--permlane-fetch-inactive` all 1,000 match. Native wave64 on the 32-wide card mismatches as documented: `s_bcnt1` of EXEC counts one half, and a `v_readlane` from the other half wraps.
1097- **Native wave64 on a 64-wide device: one driver fault (SHADER-705).** With `--wave 64 --w64-native --dpp --no-maskdata
1098 --seed 82001 --programs 600`, AMD's Windows driver on a gfx1036 integrated GPU (`32.0.21045.16010` and
1099 `32.0.21042.62`, two machines; found by @Vonsek, reduced by @zzEmmazz) gives one native mismatch:
1100 `cs_xl64_8200346406` (index 403) differs in 96 words, lanes 32-63 of each wave on the first driver and lanes 0-15
1101 and 32-47 on the second. The emulated build matches there.
1102 - **The same run under RADV** (Mesa 26.3.1, Linux) on another gfx1036 (a Ryzen 9 7950X3D's) and on an RX 7900 XTX:
1103 454 match, 0 mismatch, 146 `hyp_only`, natively and emulated. The program alone, and the 12 instructions it was
1104 reduced to, are exact natively on both devices: as 192 threads and as one 64-thread group, with the driver's
1105 default subgroup size and with `vk_compute_test --require-wave64`.
1106 - **Hardware:** `--oracle hw` on that gfx1036 matches the model in all 600 programs.
1107 - **So the native wave64 SPIR-V is right and that driver is not.** The wrong instruction is a `v_permlanex16_b32`
1108 that reads a register a DPP op with a partial `row_mask` has just written; equivalent rewrites of the shuffle
1109 index only move the wrong lanes (@zzEmmazz).
1110 - **In the game's shaders that shape does not occur.** Of 26,503, 2,293 use `v_permlanex16_b32` and 27 a DPP op with
1111 a partial `row_mask`. 6 have both, all wave32 compute, and in none does the shuffle read a register that such a
1112 DPP op wrote last (program order, branches ignored).
1113 - **Not checked:** the driver's generated code, so the fault is not located and other shapes may trigger it; the
1114 Windows driver with `--require-wave64` (the fuzzer's native run does not request a subgroup size); AMD's
1115 Windows driver on RDNA3 or newer.
1116 - `--wave64-emulate auto` stays native on that driver, because it can crash on emulated LDS code (#857).
1052- **Closed question (#374):** what hardware does for permlane with FI = 0 was measured on RDNA2 and RDNA3.5 (see above). 1117- **Closed question (#374):** what hardware does for permlane with FI = 0 was measured on RDNA2 and RDNA3.5 (see above).
1053 1118
1119### Wave and cross-lane ops on the CPU (`tools/wave_diff.py`)
1120
1121The same family as `crosslane_fuzz.py`, without a GPU or llvm-mc, so it can run wherever the translator tests run.
1122The reference is `cf_ref.WaveMachine` (FUZZ-8) extended in `wave_diff.WaveRef` with the instructions it leaves out:
1123`v_readlane`, `v_readfirstlane`, `v_writelane`, `ds_bpermute_b32` (per 32-lane half, an inactive source reads 0),
1124`v_permlane16/x16` (FI = 0 with an inactive source leaves vD, as measured above), `s_bcnt0/1` and `s_ff0/1`
1125(`_b32`/`_b64`, constants sign-extended to the operand width) and `s_not`. Each rule is written next to its instruction.
1126The translated side is `spirv_mini_interp.run_workgroup`, every lane of the wave in one subgroup of the wave's size, and
1127all 12 dwords every lane stores are compared (four VGPRs, two masks, VCC and the final EXEC as each lane's bit, four
1128scalars). Programs are straight-line wave32 and wave64 compute under random EXEC (`v_cmpx`, saveexec, constants).
1129
1130By default the generator keeps lane masks and 64-bit data in separate registers and only issues `v_permlane` with every
1131lane on, so a default run is a regression check. Two known gaps on `main` are opt-in: `--masks-as-data` (#210, #293) and
1132`--permlane-partial` (SHADER-74, #580).
1133
1134Results (`--max-ops 16`, half wave32, half wave64, nothing skipped): it found `s_and_b32 exec_lo, exec_lo, K` in
1135wave32 and `s_ff0_i32_b64` of a negative constant (#1409), both fixed on `main` since; on `main` 7b7d73f8, 600 of
1136600 match (seeds 401 to 403).
1137
1054### 32-bit float VALU on the GPU (`tools/f32_fuzz.py`, FUZZ-3) 1138### 32-bit float VALU on the GPU (`tools/f32_fuzz.py`, FUZZ-3)
1055 1139
1056`--oracle hw` (or `translator,hw`) runs the same seeded VOP1/VOP2/VOP3 f32 programs natively on the AMD GPU and judges 1140`--oracle hw` (or `translator,hw`) runs the same seeded VOP1/VOP2/VOP3 f32 programs natively on the AMD GPU and judges
@@ -1090,7 +1174,8 @@ python -I tools/f32_fuzz.py --oracle hw --perturb mul_rtz --programs 500 # o
1090 `7cfc` on gfx1150); only mnemonics are shared. omod and clamp exist in VOP3 on both; no op_sel is used for f32. 1174 `7cfc` on gfx1150); only mnemonics are shared. omod and clamp exist in VOP3 on both; no op_sel is used for f32.
1091 The transcendental unit is separate on GFX11, so a `s_nop 7` follows the instruction in the native kernel 1175 The transcendental unit is separate on GFX11, so a `s_nop 7` follows the instruction in the native kernel
1092 (`--no-hw-guard` leaves it out). 1176 (`--no-hw-guard` leaves it out).
1093 - *Not covered:* wave64 (the f32 ALU does not depend on it), `v_fma_mix*`, f16 and f64 arithmetic. 1177 - *Not covered:* wave64 (the f32 ALU does not depend on it), `v_fma_mix*` and f16 arithmetic. The translated f64 VALU
1178 forms have a separate CPU differential harness in `tools/f64_diff.py` (below).
1094- **Programs.** The seeded random ones, plus `--probes N` (default 12) per op and kind: denormal operand, denormal 1179- **Programs.** The seeded random ones, plus `--probes N` (default 12) per op and kind: denormal operand, denormal
1095 result, NaN payloads, clamp of NaN/-0, invalid operations (inf - inf, 0 * inf, ...), and `cancel` (`z = -round(x * y)`, 1180 result, NaN payloads, clamp of NaN/-0, invalid operations (inf - inf, 0 * inf, ...), and `cancel` (`z = -round(x * y)`,
1096 which separates fused from unfused). `v_min/max/min3/max3/med3_f32` are in the table for the hardware only, with the 1181 which separates fused from unfused). `v_min/max/min3/max3/med3_f32` are in the table for the hardware only, with the
@@ -1224,8 +1309,172 @@ interpreter that quiets the NaN. That form is left out unless `--known` (`class-
1224``` 1309```
1225python -I tools/fmisc_diff.py --programs 3000 --seed 11 --max-ops 8 1310python -I tools/fmisc_diff.py --programs 3000 --seed 11 --max-ops 8
1226python -I tools/fmisc_diff.py --oracle hw --programs 500 --seed 1 1311python -I tools/fmisc_diff.py --oracle hw --programs 500 --seed 1
1312python -I tools/fmisc_diff.py --oracle hw,vk --programs 600 --seed 11 --max-ops 8 [--wave 64]
1227python -I tests/test_fmisc_diff.py 1313python -I tests/test_fmisc_diff.py
1228``` 1314```
1315
1316`--oracle hw,vk` also runs the translated programs on a real Vulkan GPU (`tools/vk_fuzz_run.py`: llvm-mc for gfx1013,
1317`rdna2spirv.py`, `runtime/build/vk_compute_test`, `LEONIDA_VK_DEVICE`, `--build DIR`) as one wave of 32 or, with
1318`--wave 64`, 64 identical lanes (the lane masks as 64-bit pairs; the hardware kernels run in the same wave size), and
1319judges lane 0's four words against the hardware's, not the reference's: the interpreter cannot see a driver's denormal,
1320NaN and rounding rules. The seeds are computed from the buffer fill at run time (`--vk-constants` keeps them as
1321literals), because the AMD Windows driver (26.10.1) folds an ordered compare of a literal NaN to true in a wave32
1322pipeline (`v_cmp_lt_f32 vcc_lo, -10.0, NaN`, fine in wave64 and on the RTX 5080; with run-time operands it is right).
1323Differences are `denormal` (the reference declines the program for a denormal: f32 denormals are left to the driver),
1324`omod_neg_zero` (an output modifier made the hardware's -0 a +0, the translated -0 stayed; #1281) and `mismatch`,
1325which fails the run. Seeds 11 to 13, 600 programs each, up to 8 ops: Radeon gfx1036 wave32 597 match, 3 omod_neg_zero;
1326wave64 593 match, 3 denormal, 4 omod_neg_zero; RTX 5080 wave32 595 match, 3 omod_neg_zero, 2 denormal; no mismatch.
1327
1328### Translated programs on a Vulkan GPU: `--oracle hw,vk` of `pk16_diff`, `vint_diff`, `wint_diff`, `sdwa_diff` and `fmisc_diff`
1329
1330These fuzzers judge the translator in `spirv_mini_interp`, which cannot see what a driver does with the SPIR-V. `f32_fuzz`
1331has no Vulkan path (its GPU oracle is `--oracle hw`, above). With
1332`--oracle hw,vk` each program also runs through llvm-mc (gfx1013), `rdna2spirv.py` and `runtime/build/vk_compute_test`
1333(`tools/vk_fuzz_run.py`; `--build DIR`, `--work DIR`, `LEONIDA_VK_DEVICE`) as one wave, and its words are judged against
1334the hardware's words from a kernel run in the same wave size (`--wave 32` or `--wave 64`; wave64 needs native 64-wide
1335subgroups, so the Radeon and not the RTX 5080). `pk16_diff`, `vint_diff` and `fmisc_diff` run identical lanes and judge
1336lane 0, `sdwa_diff` too (its VCC seed differs per lane), `wint_diff` runs its per-lane programs in the wave size they were
1337generated for and judges every lane. The `v_mov_b32 vN, K` seeds of the lane-identical tools become `K ^ 0xEEEEEEEE`
1338xor the buffer fill vk_compute_test leaves in the output (`--vk-constants` keeps literals): the AMD Windows driver
1339(26.10.1) folds an ordered compare of a literal NaN to true in a wave32 pipeline, which says nothing about a shader given
1340a NaN at run time.
1341
1342```
1343python -I tools/pk16_diff.py --oracle hw,vk --programs 500 --seed 201 --max-ops 8 [--wave 64]
1344python -I tools/vint_diff.py --oracle hw,vk --programs 500 --seed 203
1345python -I tools/sdwa_diff.py --oracle hw,vk --family f16 --programs 500 --seed 211
1346python -I tools/wint_diff.py --oracle hw,vk --wave both --programs 400 --seed 221
1347```
1348
1349Fresh seeds, 400 to 500 programs each (AMD Radeon iGPU gfx1036, driver 26.10.1, and NVIDIA GeForce RTX 5080, driver
1350616.92; the f16 SDWA programs also count `nan`: the reference declines an f16 NaN, the hardware kernels run with IEEE on):
1351
1352| tool | Radeon wave32 | Radeon wave64 | RTX 5080 wave32 |
1353|---|---|---|---|
1354| `pk16_diff` | 492 match, 8 mismatch | 492 match, 8 mismatch | 500 match |
1355| `vint_diff` | 500 match | 500 match | 500 match |
1356| `sdwa_diff --family int` | 500 match | 498 match, 2 mismatch | 500 match |
1357| `sdwa_diff --family f16` | 499 match, 1 nan | 498 match, 2 mismatch | 490 match, 10 nan |
1358| `wint_diff` | 398 match, 2 mismatch (wave32 and wave64 programs together) | | 400 match |
1359
1360The pk16 mismatches were `v_med3_i16` with a constant operand (seven of eight on wave64, five of eight on wave32; the
1361rest `v_pk_*` or `v_min_i16`): the AMD driver returned a bound instead of the middle value for the translated
1362min/max/clamp median (fixed by the sum-minus-min-and-max form, GPU test `cs_med3_i16`). The others are Radeon-only and
1363not fixable in the translator as far as measured: `v_not_b32_sdwa v4, v3 dst_sel:WORD_0 dst_unused:UNUSED_PAD
1364src0_sel:BYTE_0` with v3 = 0xffff gives 0xffffff00 where the hardware gives 0x0000ff00 in a wave64 pipeline (the same
1365with the field extracts written as shifts and a mask), and `v_cvt_f32_f16_sdwa ... dst_sel:WORD_1` of an f16 denormal
1366differs in the low bits of the result.
1367
1368### binary64 VALU on the CPU and Vulkan (`tools/f64_diff.py`, FUZZ-55)
1369
1370`tools/f64_diff.py` covers the 47 binary64 instruction forms `tools/rdna2spirv.py` translates on main: four rounding
1371ops, add, f64-to-f32 conversion, reciprocal/reciprocal-square-root/square-root, division fixup and scaled FMA, both
1372frexp results, all 16 `v_cmp_*_f64` and 16 `v_cmpx_*_f64` predicates, and both class compares. It generates one-lane
1373programs with VGPR and SGPR pairs, float immediates, inline constants, 32-bit literals where the translator marks
1374them as upper-half f64 literals, and full-width literals in other instruction forms; it compares the four exported
1375dwords. Compare predicates are read through a mask-to-word operation, and `v_cmpx` cases also export the resulting
1376`EXEC` mask. Its reference decodes IEEE binary64 words and uses exact
1377`Fraction` arithmetic for finite addition and fused multiply-add; it does not import code from the translator or the
1378other fuzzer references. It models all four `MODE.FP_ROUND[3:2]` encodings for addition; the translator currently
1379rejects directed rounding (+infinity and -infinity), so those generated cases are counted skips. Any NaN matches any
1380NaN. Binary64 subnormal operands or results for `v_rcp_f64`, `v_rsq_f64` and `v_sqrt_f64`, and subnormal f32 results
1381from `v_cvt_f32_f64`, are counted skips because shader drivers may flush them to zero (FTZ).
1382
1383`--sweep` (the default) tries each translated form, followed by `--programs N` seeded programs (`--seed S` and
1384`--max-ops N` control the campaign). `--no-sweep`, `--ops`, `--no-literals`, `--known`, `--all-failures`,
1385`--list-ops` and `--self-test` are available. The translator oracle executes generated SPIR-V with the local semantic
1386interpreter. The current CPU interpreters do not implement binary64 `OpFConvert` or `OpFDiv`; these are reported as
1387counted skips. Negative-input `Sqrt` and
1388`InverseSqrt` cases are also skipped because GLSL.std.450 leaves them undefined. `s_round_mode` encodings for directed
1389rounding that the translator rejects are counted as skips. The reference uses IEEE binary64 for reciprocal and square
1390root; native RDNA2 `v_rcp_f64`, `v_rsq_f64` and `v_sqrt_f64` have about 26 bits of precision (PROC-216), so this
1391oracle checks the translated SPIR-V contract, not the native instruction's approximation. Other unsupported interpreter
1392instructions are counted as skips with their reason. Vulkan's [SPIR-V environment](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html)
1393leaves the precision of these GLSL [extended instructions](https://registry.khronos.org/SPIR-V/specs/unified1/GLSL.std.450.html)
1394implementation-defined for binary64; the GPU oracle therefore counts `v_rsq_f64` and
1395`v_sqrt_f64` as unjudged skips instead of requiring bit-exact results. This was confirmed on an NVIDIA RTX 4070 with
1396`shaderFloat64`: `v_rsq_f64 3.25` produced matching high 32 bits but zero low 32 bits, unlike the exact reference.
1397
1398Known divergence probes are excluded and counted by default, then reinserted with `--known`: binary64 output modifiers
1399(SHADER-721), binary64 `OpFNegate`/`FAbs` that the CPU interpreter rounds through binary32 (TEST-912, #4172),
1400driver-dependent NaN or signed-zero clamp results, and `v_div_fixup_f64` with a NaN `S0` and an ordinary finite
1401division. The latter follows the RDNA2 ISA reference (`NaN(S0) -> signed infinity`), while the current translator
1402preserves the NaN payload. Therefore `--known` can intentionally return 1 when this known mismatch is reproduced;
1403the minimized case is printed. `--oracle gpu` translates the same
1404fragment shader and runs it through `runtime/build/vk_harness`, comparing the raw RGBA32F output words. It assembles
1405the fragment module with `spirv-as` and the full-screen vertex shader with the Vulkan SDK's `glslc`; use `--exe PATH`
1406to select another `vk_harness`. It exits 77 if the executable, SDK tools, Vulkan device or required `shaderFloat64`
1407feature is unavailable. `--oracle hw` runs the same programs natively on an AMD GPU through `tools/hw_oracle` (one lane
1408of a wave32 compute kernel, as `tools/fmisc_diff.py` does) and compares the four words with the reference only, not with
1409the translator; `--hw-arch` picks the architecture to assemble for (default: detected). The campaign is one launch, and a
1410failing program is re-run alone while it is shrunk. The hardware runs every form, so the known-divergence exclusions
1411(translator limits) do not apply: output modifiers, clamp, negated/absolute operands and directed rounding are compared
1412too, and the kernels start in the game's inferred float MODE (IEEE off, DX10_CLAMP on). `v_rcp_f64`, `v_rsq_f64` and
1413`v_sqrt_f64` are counted skips there, because the native results are approximations (PROC-216) and the reference is exact;
1414an architecture that cannot set that MODE (gfx1170 and later) or a program the assembler rejects is a counted skip with the
1415runner's reason. It exits 77 only when the `tools/hw_oracle` tools or device are missing. The path is covered by
1416`tests/test_f64_diff.py` with a fake oracle (routing, `--hw-arch`, exit 77, skips, shrinking); **no AMD hardware run has
1417been done for it yet**.
1418Exit codes are 0 for no unexpected
1419mismatch, 1 for a mismatch (with instruction-removal shrinking), 2 for CLI/harness errors and 77 for unavailable
1420oracles. Skips always include a reason.
1421
1422```
1423python -I tools/f64_diff.py --programs 300 --seed 1
1424python -I tools/f64_diff.py --known --programs 300 --seed 1
1425python -I tools/f64_diff.py --oracle gpu --programs 300 --seed 1
1426python -I tools/f64_diff.py --oracle hw --programs 300 --seed 1
1427python -I tools/f64_diff.py --self-test
1428python -I tests/test_f64_diff.py
1429```
1430
1431**Vulkan check on an NVIDIA GeForce RTX 4070** (Windows 11, driver 621.01, Vulkan `shaderFloat64` enabled):
1432
1433| Command | Match | Mismatch | Total | Skips |
1434|---|---:|---:|---:|---:|
1435| `--oracle gpu --programs 300 --seed 1` | 331 | 0 | 347 | 16 |
1436| `--oracle gpu --programs 200 --seed 2 --max-ops 4` | 218 | 0 | 247 | 29 |
1437| `--oracle gpu --ops v_cvt_f32_f64,v_rcp_f64,v_rsq_f64,v_sqrt_f64 --programs 80 --seed 1` | 39 | 0 | 84 | 45 |
1438| `--oracle gpu --ops v_cmpx_lt_f64,v_cmpx_eq_f64,v_cmpx_class_f64 --programs 40 --seed 1` | 43 | 0 | 43 | 0 |
1439
1440The skips are counted by reason: subnormal FTZ, implementation-defined binary64 `InverseSqrt`/`Sqrt` precision,
1441non-finite scaled FMA, and translator-rejected directed rounding. The compared cases had no mismatches.
1442
1443### Output modifiers of the binary64 and f16 division ops (`tools/f64_omod_probe.py`)
1444
1445`tools/f64_omod_probe.py` measures what `mul:2`, `mul:4`, `div:2` and `clamp` do to six VOP3 results: the binary64
1446conversions `v_cvt_f64_i32` and `v_cvt_f64_u32`, `v_cvt_f32_f64` (an f32 destination), `v_frexp_mant_f64`,
1447`v_div_fixup_f64` and `v_div_fixup_f16`. Each case is measured plain and with each modifier in the same kernel launch,
1448so the probe compares the modifier's effect and not the semantics of the op. A hand-written kernel writes the whole
1449destination (both words for binary64, the low half only for the 16-bit form, as the ISA defines) and runs once in
1450wave32 and once in wave64, which must agree word for word. It needs `tools/hw_oracle` on a GFX10 AMD GPU: the kernels
1451set their own MODE from the descriptor, and a device of another family is reported as unavailable, since the gate was
1452measured on RDNA2. It reads no game files.
1453
1454The five MODEs are `game_i0_d3` (the game's, and the translator's: IEEE 0, `denorm_mode_16_64 = 3`,
1455`denorm_mode_32 = 0`, DX10_CLAMP 1), `i0_d0`, `i1_d3`, `i1_d0` and `i0_d3_f32keep` (`denorm_mode_32 = 3`). The gate
1456turns out to be **per result precision, not per instruction family**: the f32 result of `v_cvt_f32_f64` follows
1457`denorm_mode_32` and scales whenever it is 0, while the f16 and binary64 results scale only with IEEE 0 and
1458`denorm_mode_16_64 = 0` and ignore the modifiers in the game's MODE. `clamp` applies in every MODE. That is why
1459`tools/rdna2spirv.py` keeps only `clamp` for these destinations, and the rows for these ops in `docs/design.md` carry
1460the measurement.
1461
1462`--modes` takes a comma-separated subset of the five (all by default), `--waves` the wave sizes (`32,64` by default),
1463`--hw-arch` the architecture handed to `tools/hw_oracle`, and `--json` a path for the report: the device, the
1464architecture, the modes, the wave sizes, the modifier forms, the ops and the counts `scaling_gated_on`,
1465`scaling_gated_off`, `scaling_changed_value`, `clamp_changed_value`, `mismatches` and `wave_diffs`, with the first
1466cases of each. `--self-test` checks the model's own cases without a GPU. Exit 0 when every word matches the model and
1467the wave sizes agree, 1 on a mismatch or a wave difference (the first cases are printed), 2 on a CLI or harness error
1468and 77 when the oracle or a GFX10 device is missing. `tests/test_f64_omod_probe.py` covers the gate and the CLI with a
1469fake oracle.
1470
1471```
1472python -I tools/f64_omod_probe.py # all five MODEs, wave32 and wave64
1473python -I tools/f64_omod_probe.py --waves 64 --json f64_omod.json
1474python -I tools/f64_omod_probe.py --self-test
1475python -I tests/test_f64_omod_probe.py
1476```
1477
1229**Default-mode DX9 multiply regression.** `v_mul_legacy_f32` now explicitly flushes each f32 operand before the 1478**Default-mode DX9 multiply regression.** `v_mul_legacy_f32` now explicitly flushes each f32 operand before the
1230DX9 `0 * anything => +0` override, and flushes the nonzero product before its VOP3 output modifier. The output is 1479DX9 `0 * anything => +0` override, and flushes the nonzero product before its VOP3 output modifier. The output is
1231flushed again before the active omod's `-0 => +0` rule. Previously it emitted an unguarded `OpFMul`, so on a Vulkan 1480flushed again before the active omod's `-0 => +0` rule. Previously it emitted an unguarded `OpFMul`, so on a Vulkan
@@ -1243,8 +1492,8 @@ The `16-bit results` row of `docs/design.md` listed `v_exp_f16`/`v_log_f16` and
1243unverified. f16 has only 65,536 bit patterns, so instead of sampling, this tool runs every one of them through 1492unverified. f16 has only 65,536 bit patterns, so instead of sampling, this tool runs every one of them through
1244`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16` and `v_cos_f16` on the hardware 1493`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16` and `v_cos_f16` on the hardware
1245oracle (setup above; exit 77 without it). Each op is 8 raw kernels of 1,024 threads. Each thread computes 8 inputs 1494oracle (setup above; exit 77 without it). Each op is 8 raw kernels of 1,024 threads. Each thread computes 8 inputs
1246and stores them packed two to a dword, which is 4,096 words per kernel, the launcher's limit. The op runs in wave32 1495and stores them packed two to a dword, which is 4,096 words per kernel; 8 kernels cover every input. The op runs in
1247and wave64 and under five MODEs, and MODE is read back with `s_getreg_b32` first: 1496wave32 and wave64 and under five MODEs, and MODE is read back with `s_getreg_b32` first:
1248 1497
1249| Mode | IEEE | f16 denormals | f16 rounding | 1498| Mode | IEEE | f16 denormals | f16 rounding |
1250|---|---|---|---| 1499|---|---|---|---|
@@ -1370,6 +1619,48 @@ Measured on an RX 6700 (gfx1031, AMD Windows driver 32.0.21045.29003, ROCm wheel
1370each value is staged once, and that the kernels assemble for gfx1031. A fake oracle plays the GPU to check the exit 1619each value is staged once, and that the kernels assemble for gfx1031. A fake oracle plays the GPU to check the exit
1371codes. On a GFX10 GPU the test runs UNORM8 and checks the controls. 1620codes. On a GFX10 GPU the test runs UNORM8 and checks the controls.
1372 1621
1622### Widening a 16-bit float NaN in a typed buffer load (`tools/f16_widen_probe.py`)
1623
1624A typed buffer load of a half NaN had never been measured: `tools/mem_diff.py` decoded 16_FLOAT with
1625`struct`'s `'<e'` (payload kept from Python 3.14, canonical before) while the translator decoded it with
1626`UnpackHalf2x16`, whose result for a NaN is undefined and which the mini interpreter canonicalises to
16270x7FC00000. The probe stages one half word with an untyped `buffer_store_dword`, waits, loads it with
1628`buffer_load_format_*` / `tbuffer_load_format_*`, waits, and stores the f32 lanes back.
1629
1630```
1631python -I tools/f16_widen_probe.py --json f16_widen.json # 380 kernels of one thread (190 per wave); exit 77 without the oracle
1632python -I tools/f16_widen_probe.py --self-test # the three candidate rules, no GPU
1633```
1634
1635- Formats 13 (`16_FLOAT`), 29 (`16_16_FLOAT`) and 71 (`16_16_16_16_FLOAT`), `buffer_` and `tbuffer_`
1636 forms, `_x`/`_xy`/`_xyzw`, wave32 and wave64. Every NaN word came back the same in every component of
1637 every format and form:
1638
1639 | half | f32 | |
1640 | --- | --- | --- |
1641 | 0x7ddb | 0x7fbb6000 | sNaN, payload kept, quiet bit still 0 |
1642 | 0x7fe6 | 0x7ffcc000 | qNaN |
1643 | 0x7fbb | 0x7ff76000 | |
1644 | 0xffb2 | 0xfff64000 | negative, sign kept |
1645 | 0x7fcb | 0x7ff96000 | |
1646 | 0xff96 | 0xfff2c000 | |
1647 | 0x7c01 | 0x7f802000 | sNaN, smallest payload |
1648 | 0xfc01 | 0xff802000 | |
1649 | 0x3c00 | 0x3f800000 | 1.0 |
1650 | 0xc000 | 0xc0000000 | −2.0 |
1651
1652- The rule is `sign | 0x7F800000 | (payload << 13)`: the sign is kept, the 10-bit payload moves into the
1653 f32 mantissa unchanged, and the quiet bit is **not** forced, so an sNaN stays signalling. The
1654 negative NaNs (for example 0xffb2 and 0xff96) keep their sign.
1655- `v_cvt_f32_f16` on the same halves (the instruction a driver lowers `UnpackHalf2x16` to) differs on an
1656 sNaN: 0x7ddb gives 0x7ffb6000 (quieted, payload kept) and 0x7c01 gives 0x7fc02000, while every qNaN is
1657 the same as the typed load. The translator therefore builds the NaN case from the bits with integer ops
1658 and uses `UnpackHalf2x16` only for the other halves, whose conversion is exact.
1659- Verdict: the hardware keeps the payload, so `mem_diff`'s Python 3.14 reference was right and the
1660 canonicalising translator was wrong. `mem_diff` now pins the rule in `f16_to_f32` (bit-level, Python
1661 version independent) and `tests/semantic/test_buffer_f16_widen_hw.py` pins the ten measured words for
1662 MUBUF and MTBUF, formats 13/29/71.
1663
1373### `image_get_resinfo` and `image_get_lod` (`tools/image_query_probe.py`, SHADER-388) 1664### `image_get_resinfo` and `image_get_lod` (`tools/image_query_probe.py`, SHADER-388)
1374 1665
1375`docs/design.md` ("Image atomics, size and LOD queries") took resinfo's depth word, the clamped LOD under a linear mip 1666`docs/design.md` ("Image atomics, size and LOD queries") took resinfo's depth word, the clamped LOD under a linear mip
@@ -1538,6 +1829,55 @@ on k + 0.5, the error's sign gives floor(p) + 1 or floor(p), and a zero error ke
1538probe then exits 0 on the same iGPU: all 134 words equal the translator's in all ten runs (wave32 and wave64, five 1829probe then exits 0 on the same iGPU: all 134 words equal the translator's in all ten runs (wave32 and wave64, five
1539MODEs), including the 28 near ties. 1830MODEs), including the 28 near ties.
1540 1831
1832### Division fixup (`tools/div_fixup_diff.py`)
1833
1834No other fuzzer generates `v_div_fixup_f16`, `v_div_fixup_f32` or `v_div_fixup_f64`. `tools/div_fixup_diff.py`
1835runs them through the translator and `tests/semantic/spirv_mini_interp.py`, against a model of the `docs/design.md`
1836rows that works on the operand bits and shares no code with the translator, and compares the four exported words bit
1837for bit. The model:
1838
1839- `abs` then `neg` act on the sign bit of S0, S1 and S2, NaNs included.
1840- f32 reads an S1 or S2 denormal as a zero of its sign and keeps an S0 denormal. f16 and f64 keep every denormal.
1841- The first rule that holds gives the result: NaN(S2), NaN(S1), 0/0 or inf/inf (the negative quiet NaN), a zero
1842 numerator or an inf denominator (zero), a zero denominator or an inf numerator (inf), the exponent cutoff
1843 (`exp(S2) - exp(S1)` at most -151 on f32 and -1076 on f64, none on f16; zero), NaN(S0) (inf), S0's magnitude.
1844 The sign is sign(S1) ^ sign(S2).
1845- On f32, `mul:2`/`mul:4`/`div:2` scale the result, then `clamp` takes a NaN or any negative value to +0.
1846- On f16 and f64, `mul:2`/`mul:4`/`div:2` change nothing: the `docs/design.md` row (#6314, measured on gfx1036 with
1847 `tools/f64_omod_probe.py`) drops the scaling under `denorm_mode_16_64 = 3`, the game's `MODE`, while an f16 `clamp`
1848 still saturates. The measured inputs are normal values; the reference applies the row to every result.
1849
1850`tests/test_div_fixup_diff.py` pins the model to the 73 gfx1036 rows of `tests/semantic/test_alu_div_fixup_f32.py`
1851and to the f16 and f64 rows of `test_alu_div_fixup.py`, the measured exponent cutoffs among them.
1852
1853Sources are VGPRs, SGPRs, a literal (not on f64) and integer and float inline constants, within the GFX10 literal and
1854constant-bus limits. An f64 source is a VGPR pair (odd first registers too), an SGPR pair or an inline constant, and
1855`0.15915494309189532` is the binary64 1/(2 pi). Modifiers are `neg`/`abs`, `op_sel` on the f16 register sources and
1856the destination, `clamp` on f16 and f32, and the output multipliers on all three. Not generated: a literal on f64
1857(#3791 moves it to bits 63:32) and `clamp` on f64 (the translation needs Float64, which the interpreter does not run).
1858
1859An f32 NaN that went through an output multiplier matches any NaN. Some programs are counted as not judged, with the
1860reason:
1861- an f64 exponent cutoff that depends on how a denormal's exponent counts (only normal operands were measured);
1862- an output multiplier on -0 without `clamp` (the hardware gives +0, not modelled), or on an f32 denormal;
1863- `clamp` of a positive f32 denormal, of an f16 -0 or of an f16 NaN (`FClamp` of a NaN is undefined);
1864- reading part of an f32 NaN whose payload is not modelled.
1865
1866Stages:
18671. A sweep of every encodable source-kind combination of each op.
18682. An edge grid: special values as S1 and S2 under five S0 values, the exponent cutoff one below, at and one above
1869 (also against a NaN or inf S0, and on f64 with a denormal numerator), `abs`/`neg` on every kind of value, and
1870 the output modifiers on each rule's result (f16 multipliers in both destination halves, with and without `clamp`).
18713. Random seeded programs, which read earlier results, f64 halves as f32 or f16 values included.
1872
1873A translator skip exits 1, as a mismatch does.
1874
1875```
1876python -I tools/div_fixup_diff.py --programs 3000 --seed 11 --max-ops 8
1877python -I tools/div_fixup_diff.py --ops v_div_fixup_f64 --programs 1000
1878python -I tests/test_div_fixup_diff.py
1879```
1880
1541### `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` denormal flush on RDNA1 (`tools/mad_denorm_probe.py`, SHADER-340) 1881### `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` denormal flush on RDNA1 (`tools/mad_denorm_probe.py`, SHADER-340)
1542 1882
1543`docs/design.md` ("Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32`") had no hardware measurement: GFX10.3+ 1883`docs/design.md` ("Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32`") had no hardware measurement: GFX10.3+
@@ -1687,9 +2027,74 @@ metadata to copy the conventions from. With the built-in `interp2` template on g
1687the perspective I/J barycentrics are in v0/v1, M0 comes from s2 (`s_mov_b32 m0, s2`), and parameters 0 and 1 are 2027the perspective I/J barycentrics are in v0/v1, M0 comes from s2 (`s_mov_b32 m0, s2`), and parameters 0 and 1 are
1688the vertex shader's locations 0 = (u, v, 0, 1) and 1 = (u, v, 0, 0), u and v going 0..2 across the screen. 2028the vertex shader's locations 0 = (u, v, 0, 1) and 1 = (u, v, 0, 0), u and v going 0..2 across the screen.
1689 2029
2030```powershell
1690$env:LEONIDA_VK_DEVICE = "radeon" 2031$env:LEONIDA_VK_DEVICE = "radeon"
1691python -I tools/ps_oracle.py --build <runtime build> --template interp2 --show-template 2032python -I tools/ps_oracle.py --build <runtime build> --template interp2 --show-template
1692python -I tools/ps_oracle.py --build <runtime build> --template interp2 --asm body.s --size 4 1 [--json out.json] 2033python -I tools/ps_oracle.py --build <runtime build> --template interp2 --asm body.s --size 4 1 [--json out.json]
2034```
2035
2036Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary (there is no
2037check over the code), the patched code runs as the pixel shader, and `v_interp_p1/p2_f32` of `attr0.x` at the four
2038pixel centres of a 4 x 1 target gives u = 0.125, 0.375, 0.625, 0.875, with `v_interp_mov_f32` reading the
2039parameter words P0 = 0 and P10 = 2.0 (`tests/test_ps_oracle.py`, which runs it on hardware when
2040`LEONIDA_PS_ORACLE_BUILD` names a runtime build). On other drivers the binary is not a single PAL ELF (the NVIDIA
2041driver returns two blobs) and the tool exits 77.
2042
2043`--format` picks the color target (rgba32f by default; rgba16f/unorm/snorm/u/i, rg32f, r32f, rgba8*, rgb10a2unorm,
2044...), and the driver picks the export format for it as for a game pipeline; the readback is the target's texels as
2045stored. Measured on gfx1036 with the `const` template (EGEN-TOOL-PS-ORACLE-FORMATS):
2046
2047| Target | `col_0_export_format` | What reaches the target |
2048|---|---|---|
2049| RGBA32F, RGBA32_UINT | 9 (32_ABGR) | the four exported dwords as they are; a channel exported as `off` is 0 |
2050| RG32F | 2 (32_GR) | R = the last enabled of x, z; G = the last enabled of y, w (all four enabled: z, w) |
2051| R32F | 1 (32_R) | the last enabled channel (all four enabled: w) |
2052| RGBA16F, RG16F, RGBA8_UNORM/SNORM, RGB10A2 | 4 (FP16_ABGR) | a `compr` export's halves as f16, converted by the CB; an f16 NaN half becomes `0xfe00` in an f16 target, 0 in a normalized one |
2053| RGBA16 UNORM/SNORM/UINT/SINT, RG16_UNORM | 5 / 6 / 7 / 8 | a `compr` export's 16-bit halves bit for bit (unorm16/snorm16/integer values, not f16) |
2054| RGBA8_UINT | 7 (UINT16_ABGR) | the 16-bit halves clamped to 255 |
2055
2056A 16-bit export format takes a `compr` export; an uncompressed one into it is not meaningful (the target got the z
2057and w dwords). Limits: one draw of one triangle, mrt0 only; the vertex
2058stage is the template's, compiled by the driver; the SPI behaviour comes from the driver's metadata, so a `--set`
2059the hardware does not support is not refused here.
2060
2061### Packed 16-bit integer operations on RDNA2 (SHADER-302)
2062
2063*Measured on an RDNA2 iGPU (gfx1036), Windows 11, AMD Windows driver 32.0.21045.29003, HIP backend (`amdhip64_6.dll`), AMD clang 23.0.0git (`rocm-sdk-core 10.0.0`).*
2064
2065380 raw compute kernels covering all 11 packed 16-bit integer instructions (`v_pk_add_u16`, `v_pk_sub_u16`, `v_pk_add_i16`, `v_pk_sub_i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16`, `v_pk_mad_i16`, `v_pk_max_u16`, `v_pk_min_u16`, `v_pk_max_i16`, `v_pk_min_i16`), tested in both wave32 and wave64:
2066
2067- **Constant operands under `op_sel` / `op_sel_hi`:** Integer constants under VOP3P are uniformly treated as 32-bit dwords `C`. When `op_sel[i] == 0`, bits `[15:0]` are selected; when `op_sel[i] == 1`, bits `[31:16]` are selected. Positive inline constants zero-extend (`5` → `0x00000005`: lo=`0x0005`, hi=`0x0000`; `64` → `0x00000040`: lo=`0x0040`, hi=`0x0000`). Negative inline constants sign-extend (`-1` → `0xFFFFFFFF`: lo=`0xFFFF`, hi=`0xFFFF`; `-16` → `0xFFFFFFF0`: lo=`0xFFF0`, hi=`0xFFFF`). 32-bit literals preserve their full dword (`0x12345678`: lo=`0x5678`, hi=`0x1234`; `0x80017fff`: lo=`0x7fff`, hi=`0x8001`). Float inline tokens (`0.5`, `1.0`, `-2.0`, `4.0`) assemble as their 32-bit IEEE 754 bit patterns (`1.0` → `0x3f800000`: lo=`0x0000`, hi=`0x3f80`).
2068- **`clamp` saturation:** Unsigned add/mad saturate to `0xFFFF`; unsigned sub saturates underflow to `0x0000`; signed add/sub/mad saturate to `[-32768, 32767]`.
2069- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences).
2070### Pixel-shader ISA on the hardware (`tools/ps_oracle.py`, EGEN-TOOL-PS-ORACLE)
2071
2072`tools/hw_oracle` only launches compute kernels, so what only a pixel shader has (`v_interp_*` and the parameter
2073words the SPI writes into LDS, the barycentric VGPRs, exports and their formats, helper lanes) could not be
2074measured there. `tools/ps_oracle.py` runs hand-written RDNA2 pixel-shader ISA in a real draw on an AMD GPU, through
2075Vulkan's `VK_KHR_pipeline_binary`:
2076
20771. `vk_harness` builds a pipeline from a template vertex + pixel shader and writes its binary (`VKH_BINARY_OUT`).
2078 On the AMD Windows driver that is one PAL ELF: `.text` with `_amdgpu_gs_main` (the vertex stage) and
2079 `_amdgpu_ps_main`, and a `.note` with the PAL metadata in msgpack, from which the driver programs the register
2080 counts and the SPI setup (`spi_ps_input_ena/addr`, `spi_ps_input_cntl` per parameter, `spi_shader_col_format`).
20812. The code under test is assembled with AMD clang (`LEONIDA_AMD_CLANG`, as for hw_oracle) and replaces
2082 `_amdgpu_ps_main`; `.text` grows if needed and the pixel stage's VGPR/SGPR counts are raised to the registers
2083 the code names. `--set PATH=JSON` changes a metadata entry as well, e.g.
2084 `.graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode=true`.
20853. `vk_harness` builds the pipeline from the patched binary (`VKH_BINARY_IN`), draws one full-screen triangle into
2086 an RGBA32F target and reads every pixel's four mrt0 dwords back bit for bit.
2087
2088The template sets what the code finds when it starts, so `--show-template` prints the template's own ISA and SPI
2089metadata to copy the conventions from. With the built-in `interp2` template on gfx1036 the pixel stage is wave64,
2090the perspective I/J barycentrics are in v0/v1, M0 comes from s2 (`s_mov_b32 m0, s2`), and parameters 0 and 1 are
2091the vertex shader's locations 0 = (u, v, 0, 1) and 1 = (u, v, 0, 0), u and v going 0..2 across the screen.
2092
2093```powershell
2094$env:LEONIDA_VK_DEVICE = "radeon"
2095python -I tools/ps_oracle.py --build <runtime build> --template interp2 --show-template
2096python -I tools/ps_oracle.py --build <runtime build> --template interp2 --asm body.s --size 4 1 [--json out.json]
2097```
1693 2098
1694Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary (there is no 2099Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary (there is no
1695check over the code), the patched code runs as the pixel shader, and `v_interp_p1/p2_f32` of `attr0.x` at the four 2100check over the code), the patched code runs as the pixel shader, and `v_interp_p1/p2_f32` of `attr0.x` at the four
@@ -1777,6 +2182,85 @@ pixel stage (`RADV_PERFTEST=pswave32`) and GFX11+ exit 77. Not measured: wave32,
1777- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences). 2182- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences).
1778 2183
1779 2184
2185### Real pixel shaders on two GPUs (`tools/ps_sweep.py`, `runtime/test/vk_ps_sweep.cpp`)
2186
2187The oracles above run hand-written programs. This one draws translated corpus pixel shaders, to find what only real
2188shaders trigger. `ps_sweep.py sample` takes a fixed-seed stratified sample of the translated pixel shaders (strata:
2189needs barycentrics, descriptor bindings none / 0-3 only / any above 3, control-flow style; at least 10 per stratum,
2190the rest in proportion). `vk_ps_sweep` draws one of them with a generated vertex shader (a viewport-covering triangle
2191and a vec4 at every input location), the runtime's bindless set 0 with only its fallbacks, a zeroed 1 MiB heap, the
2192push-constant block and 32x32 `RGBA32F` targets cleared to -1. Everything is identical on every GPU, so the same
2193sample can be run on each and compared; `ps_sweep.py compare` classifies each shader: OK on both, differs beyond
2194tolerance (1e-3 absolute plus relative), NaN or all-zero on one GPU only, fails on one GPU, fails on both, timeout.
2195When both workers exit successfully, `compare` requires matching target counts (1–8) and exactly 16,384 bytes per
2196target in each raw file (32 × 32 pixels × 16 bytes). A missing file, a wrong byte length or an invalid or mismatched
2197count is reported as `invalid readback`, not as a GPU result. Failed and timed-out draws are classified by exit
2198code without reading either file. The size check establishes completeness; this command still compares float values
2199with tolerance, not byte-for-byte equality.
2200Variant `t` (`VKS_TEX=1`) replaces the fallback images with an 8x8 gradient (2D, 2D array, 1D, 3D) and a linear
2201sampler so sampled values are not all zero.
2202
2203Warning: a few sampled shaders hang NVIDIA GPUs with the zeroed heap (see "Fails on one GPU, NVIDIA" below). The
2204`--timeout` of `ps_sweep.py run` only bounds the wait on the host side; the driver resets the GPU (TDR). On a GPU that
2205also drives the display the desktop freezes until each reset (a tester saw five in six minutes on an RTX 3060 around
2206shaders 120 to 310 of the 480). Run it on a GPU with no display attached, or expect a freeze of a few seconds per hang;
2207`--lo`/`--hi`/`--only` run part of the sample.
2208
2209RTX 4080 SUPER and Intel UHD 770 (32.0.101.6129), Windows 11, 480 of 12,101 pixel shaders (seed 20261122):
2210
2211| class | variant z (fallback images) | variant t (gradient textures) |
2212|---|---|---|
2213| OK on both | 262 | 260 |
2214| differs beyond tolerance | 0 | 1 |
2215| NaN or zero on one GPU only | 0 | 0 |
2216| fails on one GPU | 214 | 215 |
2217| fails on both | 0 | 0 |
2218| timeout (both) | 4 | 4 |
2219
2220- **Fails on one GPU, Intel (210 in both variants):** the module needs `fragmentShaderBarycentric` (206) or
2221 `shaderResourceMinLod` (3) or both (1), and the UHD 770 has neither feature. The runtime's barycentric fallback is not
2222 part of this sweep. 5,298 of the 12,101 pixel shaders need barycentrics and 29 need MinLod.
2223- **Fails on one GPU, NVIDIA (4 in z, 5 in t):** `VK_ERROR_DEVICE_LOST` after a few seconds while the Intel GPU
2224 returns at once with every pixel unwritten. All are tier C shaders; in the one disassembled, a scalar loop reads a
2225 list from a buffer until an entry's low 16 bits are `0xffff`, and the zeroed heap has no terminator, so the loop
2226 never ends. A 10-line GLSL
2227 fragment shader with the same loop (`while ((heap[i] & 0xffff) != 0xffff) i++;` on a zeroed buffer reached through
2228 its device address) hangs the same way. The synthetic input, not the translation, is the cause; a real heap holds the
2229 terminator.
2230- **Timeout (4, both GPUs, 40 s):** large `dispatch loop` shaders; not root-caused.
2231- **Differs beyond tolerance (1, variant t):** a tier C shader (`wave64_graphics` C), 92 of 4,096 values of one target
2232 (about 2 % of the pixels), differences up to 0.06. It is identical with a constant texture and with a NEAREST sampler,
2233 so the cause is the two GPUs' linear-filter weights, not the translation.
2234- The 262 / 260 shaders that run on both agree to 4.9e-4 at most; 239 of the 260 in variant t are bit-identical.
2235 Of those, 107 write non-zero values and 153 write only zeros or nothing (a shader whose descriptors come from a
2236 zeroed heap mostly samples zero or discards). That is the limit of the synthetic inputs: a
2237 seeded heap was tried and abandoned, because a pointer read from float data is a wild address and takes NVIDIA's
2238 device down.
2239
2240**With the fallbacks (`--bary-fallback` plus the MinLod fallback of #4642, same 480 shaders, variant z).** The same sample was
2241retranslated with both flags and drawn through `<name>.bary_gs.spv` where a shader reads raw barycentrics (`VKS_GS`,
2242`tools/bary_fallback_gs.py`). The Intel UHD 770 creates 440 of the 480 (265 before; the 207 that needed
2243`fragmentShaderBarycentric` or `shaderResourceMinLod` are gone), 32 time out (zeroed-heap loops, which the same
2244translation also hits on the RTX 4080 SUPER), and 8 are not translated (`computed I/J pair under --bary-fallback`,
2245#3898). Intel against NVIDIA on the same fallback translation: 434 OK on both, 0 differ, 4 NVIDIA device losses
2246(the unterminated loop above), 8 not translated, 34 timeouts on both. Intel with the fallbacks against NVIDIA with
2247the default translation: 373 OK, 53 differ by more than 0.1 and 8 are NaN on one side. The same 61 differ between the
2248two translations on NVIDIA alone, so it is the translation, not the GPU. **Cause (counted on the same 480 translated
2249again, `--bary-fallback` alone, without the MinLod flag of #4642, against the default):** 199 modules differ between the two translations, 190 that read a
225016-bit interpolant (`v_interp_p1ll/p1lv/p2_f16`) and the 9 that read raw barycentrics; the other 273 translated under
2251both are byte-identical, so ordinary `v_interp_p1/p2/mov_f32` is not translated differently (the remaining 8 are not
2252translated under the fallback). `--bary-fallback` has no `PerVertexKHR` inputs, so a 16-bit interpolant is read as the
2253smooth f32 of its packed word (design.md, "16-bit interpolation"); `--f16-interp-fallback` is its companion, and
2254`make_game.py` turns it on with it wherever the device has no per-vertex inputs, as an Intel UHD has none. The sweep
2255used the first flag without the second, and its generated vertex shader wrote the decoded halves nowhere. The synthetic
2256`ps_interp_f16_high` drawn with `vs_f16_pack` agrees: with `--bary-fallback` alone its f16 halves are off by 0.984 on
2257both GPUs, with both flags and by default they are within 2e-3 on both, and `ps_interp_f32_mods` / `ps_interp_mov_mods`
2258(plain f32 and mov reads) are exact with `--bary-fallback`. `ps_sweep.py` now builds the vertex shader of a pixel
2259shader with `f16_halves` in its index entry so that the halves are decoded from the same words a default translation
2260reads per vertex. Not shown: the 61 individually (a 12-shader subset of the 190 agreed between the two translations on
2261the RTX 4080 SUPER; draws of these shaders take about 20 s each). Only 9 of the 480 read raw
2262barycentrics and need the geometry shader; all 9 agree on both GPUs.
2263
1780## Coverage plan and cost 2264## Coverage plan and cost
1781 2265
1782Start with straight-line scalar/vector ALU because it is deterministic, needs no descriptors and 2266Start with straight-line scalar/vector ALU because it is deterministic, needs no descriptors and
@@ -1794,6 +2278,10 @@ covers the operations most shaders use. Then add, in order:
1794 loops, two-entry cycles), run by `tools/cf_ref.py` (cpu_ref plus branches, compares and saveexec) 2278 loops, two-entry cycles), run by `tools/cf_ref.py` (cpu_ref plus branches, compares and saveexec)
1795 and by `tests/semantic/spirv_wave_interp.py` (every invocation of a subgroup, with structured 2279 and by `tests/semantic/spirv_wave_interp.py` (every invocation of a subgroup, with structured
1796 reconvergence), compared lane by lane in both the structured and the dispatch-loop form. 2280 reconvergence), compared lane by lane in both the structured and the dispatch-loop form.
2281 The corpus-side counterpart is `tools/ab_control_flow.py`: it renders branchy pixel shaders
2282 translated both ways (real loops and conditionals, and `--dispatch-loop`) and compares the two
2283 images byte for byte. It needs a finished shaders stage and `runtime/build/vk_texture_test`, and
2284 writes the outcome of each shader to `outcomes.tsv`.
17974. **LDS, global memory, buffers and images.** These need a memory model and descriptor setup; the 22854. **LDS, global memory, buffers and images.** These need a memory model and descriptor setup; the
1798 existing `vk_compute_test`/`vk_store_test`/`vk_texture_test` programs show the shape. 2286 existing `vk_compute_test`/`vk_store_test`/`vk_texture_test` programs show the shape.
17995. **Wave operations.** Ballot, shuffles, DPP, `readlane`/`writelane`, `permlane`, `mbcnt`, and the 22875. **Wave operations.** Ballot, shuffles, DPP, `readlane`/`writelane`, `permlane`, `mbcnt`, and the
diff --git a/docs/story.md b/docs/story.md
index 9d255f0f1..a0a0e1770 100644
--- a/docs/story.md
+++ b/docs/story.md
@@ -23,21 +23,55 @@ first 1 GiB of the data area, and the full-file non-inflating signature scan is
23Readable is the carver's `stored / span`; Bink 2 streams count as readable. The first `story000` 23Readable is the carver's `stored / span`; Bink 2 streams count as readable. The first `story000`
24row scans file offsets `0xA120`-`0x4000A11F`. 24row scans file offsets `0xA120`-`0x4000A11F`.
25 25
26A full 20 GB walk was attempted. At 72% (about 14.4 billion bytes, 106,000 streams) the run was 26A first full 20 GB walk was stopped at 72% (about 14.4 billion bytes, 106,000 streams) with one process at
27stopped; one zlib candidate had expanded to 8.5 GB in memory. It is not reported as a full index. 278.5 GB in memory. A later full walk with `tools/story_index.py` (after #2726 stopped the scanners copying the
28The bounded windows below and the non-inflating signature scan cover the rest without that risk. 28gaps between streams) completes in about 10 minutes and is the full index below; no zlib candidate in the
29archive inflates past 512 MiB.
30
31**Full index.** `python -I tools/story_index.py story000.rpf out.json` over all 20,022,508,672 bytes:
32**141,385 streams**, 10,231,531,520 bytes stored (51.1% of the span) and 17,094,635,373 inflated, 182,253,050
33bytes of zero padding and 9,608,682,854 unread (the raw `RSC8` region). By class: zero-prefix 56,228, `0DRP`
3448,084, `42 40 00 00` 5,589, `PSIN` 5,348, type-hash 1,393, clip-stream 875, Bink 2 264, MoVE 119, XML 32, and
3523,327 streams in 12,463 other first-word classes. By 1 GiB bucket (a stream counts where it starts, so a bucket
36whose streams run into the next one is shown as 100%):
37
38| GiB | Streams | Stored | Inflated | Readable | Main classes |
39|---:|---:|---:|---:|---:|---|
40| 0 | 55,282 | 1,002,378,056 | 3,963,018,176 | 93.4% | zero-prefix 22,679, `0DRP` 21,980 |
41| 1 | 18,210 | 1,045,208,660 | 1,484,948,432 | 97.3% | zero-prefix 15,640 |
42| 2 | 13,901 | 1,055,312,755 | 1,880,941,536 | 98.3% | zero-prefix 7,464, `0DRP` 3,067, type-hash 459 |
43| 3 | 2,020 | 1,068,996,430 | 1,487,761,024 | 99.6% | zero-prefix 1,302 |
44| 4 | 2,340 | 463,305,742 | 617,702,940 | 43.1% | `PSIN` 735, zero-prefix 732, MoVE 119 |
45| 5 | 0 | 0 | 0 | 0.0% | — |
46| 6 | 0 | 0 | 0 | 0.0% | — |
47| 7 | 0 | 0 | 0 | 0.0% | — |
48| 8 | 0 | 0 | 0 | 0.0% | — |
49| 9 | 0 | 0 | 0 | 0.0% | — |
50| 10 | 0 | 0 | 0 | 0.0% | — |
51| 11 | 0 | 0 | 0 | 0.0% | — |
52| 12 | 0 | 0 | 0 | 0.0% | — |
53| 13 | 31,714 | 638,135,783 | 1,356,633,857 | 59.4% | `0DRP` 17,584, `PSIN` 4,537, zero-prefix 3,658 |
54| 14 | 13,803 | 1,055,814,600 | 1,879,292,779 | 98.3% | zero-prefix 4,725, `42 40 00 00` 3,282, `0DRP` 1,751 |
55| 15 | 3,928 | 1,060,254,688 | 1,582,210,186 | 98.7% | `0DRP` 3,702, Bink 2 78, XML 31 |
56| 16 | 169 | 1,155,442,136 | 1,155,442,136 | 100.0% | Bink 2 169 |
57| 17 | 10 | 1,107,140,984 | 1,107,140,984 | 100.0% | Bink 2 10 |
58| 18 | 8 | 579,541,686 | 579,543,323 | 83.4% | Bink 2 7, XML 1 |
59
60The bounded windows below were the measurements before the full index; they agree with it where they overlap.
29 61
30## `story000.rpf` layout 62## `story000.rpf` layout
31 63
32The archive is not uniform. A 64 MiB magic-count scan of the whole 20 GB file, plus the carver 64The archive is not uniform. A 64 MiB magic-count scan of the whole 20 GB file and the full index above separate
33samples below, separates four regions: 65these regions:
34 66
35| Region | zlib carver result | Full-file signature result | 67| Region | zlib carver result | Full-file signature result |
36|---|---|---| 68|---|---|---|
37| GiB 0-4 | 93-100% readable in 1 GiB and 256 MiB samples; `0DRP` pages, `zero-prefix` pages, type-hash and clip headers | no RSC8 | 69| GiB 0-4 | 91,753 streams (full index); GiB 0-3 93.4-99.6% readable, GiB 4 43.1%; `0DRP` pages, `zero-prefix` pages, type-hash and clip headers, `PSIN` from GiB 4 | no RSC8 |
38| GiB 5-13 | 0 streams in every sampled window: 5, 6, 8, 10 and 12 GiB | 225,281 `RSC8` headers, all version 8001, u32@8 sum 2,677,370,916 | 70| GiB 5-12 | 0 streams in every 1 GiB bucket (full index) | 225,281 `RSC8` headers (in GiB 6-13), all version 8001, u32@8 sum 2,677,370,916 |
39| GiB 14 | 2,547 streams / 268,670,234 stored / 472,245,792 inflated in a 256 MiB window; 780 `42 40 00 00` pages | no RSC8 | 71| GiB 13 | 31,714 streams, 59.4% readable (full index): `0DRP` 17,584, `PSIN` 4,537, zero-prefix 3,658 | the last 6,736 `RSC8` headers |
40| GiB 15-18 | Bink 2 only in the sampled windows; 42 streams at 16 GiB, 2 at 18 GiB | 264 valid Bink 2 streams, 3,327,650,728 bytes | 72| GiB 14 | 13,803 streams, 98.3% readable (full index); 3,282 `42 40 00 00` pages (780 in the first 256 MiB) | no RSC8 |
73| GiB 15 | 3,928 streams (full index): `0DRP` 3,702, Bink 2 78, XML 31 | first Bink 2 bucket |
74| GiB 16-18 | Bink 2 only: 169, 10 and 7 streams (plus one XML at 18 GiB) | 264 valid Bink 2 streams in all, 3,327,650,728 bytes |
41 75
42Window samples (each starts at the stated file offset and scans 256 MiB unless noted): 76Window samples (each starts at the stated file offset and scans 256 MiB unless noted):
43 77
@@ -379,16 +413,30 @@ chunks on a 256-byte boundary behind zero padding; the walk stops there (`stoppe
379| cones: axis within 25° / every face inside within 0.05 | 89.5% / 94.2% of 228,244 | 413| cones: axis within 25° / every face inside within 0.05 | 89.5% / 94.2% of 228,244 |
380 414
381The stored centres match the box centre less often here: 25.7% of axes in the same step, 41.5% within one, 415The stored centres match the box centre less often here: 25.7% of axes in the same step, 41.5% within one,
382against 50.1% / 71.8% in the minigame archive. 625 meshlets use the 1/8 m step. Since the radius still covers the 416against 50.1% / 71.8% in the minigame archive. 625 meshlets use the 1/8 m step. Since the radius still covers the farthest vertex from the stored
383farthest vertex from the stored centre in 93.2%, the decoding holds; these assets seem to store a centre other
384than the box midpoint (a sphere centre would fit).
385against 50.1% / 71.8% in the minigame archive. Since the radius still covers the farthest vertex from the stored
386centre in 93.2%, the decoding holds. These assets seem to store a centre other than the box midpoint; a sphere 417centre in 93.2%, the decoding holds. These assets seem to store a centre other than the box midpoint; a sphere
387centre would fit. The centre and radius counts in this table were taken before the step exponent was read in 418centre would fit. The centre and radius counts in this table were taken before the step exponent was read in
388full: they read only w2 bit 28. `story000` also has e = 2 to 4 on about 456 meshlets (@zzEmmazz's count), so those 419full: they read only w2 bit 28. `story000` also has e = 2 to 4 on about 456 meshlets (@zzEmmazz's count), so those
389few rows will move slightly when recounted. Most of the remaining misses come from the group-to-block binding: 420few rows will move slightly when recounted. Most of the remaining misses come from the group-to-block binding:
390several blocks in a page share a vertex count (@Pipodi's count on #2991). 421several blocks in a page share a vertex count (@Pipodi's count on #2991).
391 422
423**Which `42 40` block a group is checked against (ASSET-294).** `--faces` and `--centres` decode a group with
424a `42 40` block of its vertex count in the same page. When several blocks have that count, the order in the
425page doesn't decide it. In `Q0 Q1 G0 G1` pages, G0 is built on Q0 in some pages and on Q1 in others, and taking
426the k-th block for the k-th group fits only 9,295 of the 15,997 `story000` groups that have several blocks and a
427fitting one. The link is in the drawable's pointers, outside the page. So the walker takes the block whose vertex
428boxes are closest to the group's stored centres (`centre_distance`, summed over its meshlets), keeping the nearest
429block before the group on a tie. Over all of `story000.rpf` (all 7,577 mesh pages parsed), before and after:
430
431| Pairing | Groups with several blocks | Block changed | Shared edges | Faces within ~25° | Opposed |
432|---|---:|---:|---:|---:|---:|
433| nearest block before | 16,059 | — | 36,707,506 | 33,342,470 (90.8%) | 518,120 (1.41%) |
434| closest centres | 16,059 | 8,668 | 36,719,379 | 34,037,683 (92.7%) | 16,415 (0.045%) |
435
436The face check doesn't use the centres, so it is the independent evidence. The centre counts rise too (same step
437212,479 → 222,572 of 827,496 axes), but for those 8,668 groups they no longer measure the centres on their own.
438The tables above were counted with the old pairing; the first row is the story000 face count above.
439
392Still open: the +0x5C word, the type-1 normal's 440Still open: the +0x5C word, the type-1 normal's
393bits 20-31, and what the `42 40` colour and UV slots hold beyond rpf9-explorer's reading. 441bits 20-31, and what the `42 40` colour and UV slots hold beyond rpf9-explorer's reading.
394 442
diff --git a/docs/strand_grooms.md b/docs/strand_grooms.md
new file mode 100644
index 000000000..02d59bea7
--- /dev/null
+++ b/docs/strand_grooms.md
@@ -0,0 +1,320 @@
1# GPU Strand Grooms (`smh`)
2
3Hair, beards, brows, lashes, body hair, and animal fur in the Xbox Series build are not authored as static
4triangle drawables. Each such item's `.#dr` drawable is a one-triangle stub, while the hair geometry is stored
5separately as a **groom LOD resource** consumed by the `smh_*` compute and strand-rendering shaders.
6
7This document specifies the measured binary layout of `smh` groom LOD resources, the shader-verified compute
8pipeline (`smh_pose_0_CS_PreSkinSimGuides` and `smh_gen_1_CS_InterpolateStrands`), the exact Class 0 strand
9scattering RNG, barycentric strand interpolation, and aggregate corpus measurements verified with the pure
10standard-library decoder in `tools/smh_groom.py`. No game data or shader disassembly is included.
11
12## Pipeline overview
13
14Rendered strands are **not stored** in the archive. Each groom LOD stores a scalp triangle mesh whose vertices
15are **guides** (polylines of rest-pose nodes, skin weights, arc lengths, root UVs, and per-guide attributes)
16plus per-triangle strand density counts and optional region IDs. At runtime the `smh_*` GPU pipeline generates
17and shades strands in stages:
18
191. **Guide pose & simulation (`smh_pose_*`, `smh_sim_*`)**: `smh_pose_0_CS_PreSkinSimGuides` reads guide rest
20 positions (`+0x44`), bone indices (`+0x10`), and bone weights (`+0x14`) from the GPU asset buffer and skins
21 guide curves into posed runtime buffers (21/21/22-bit packed positions). `smh_sim_0_CS_LodBlend` cross-fades
22 simulated guides across LOD transitions.
232. **Strand scattering & interpolation (`smh_gen_*_CS_InterpolateStrands`)**: dispatches one thread per strand
24 for each active strand class, picks a scalp triangle and uniform barycentric coordinates deterministically
25 from the thread ID and asset seed, tests the triangle's region ID against a per-instance 256-bit style mask,
26 blends the three corner guides' posed nodes, lengths, and UVs, trims each strand to its randomized target
27 length, and writes 16 bytes per strand point (with the last dword of a strand's block zeroed when culled).
283. **Style modification & visibility (`smh_modify_*`, `smh_draw_64`/`smh_draw_128` `CS_VisHair`,
29 `VS_HairStrandGeometry`, `PS_HairStrandVBuffer`, `hair_resolve_*`)**: applies runtime clump, curl, frizz,
30 and width parameters from per-instance style records and rasterizes all strands in one batch.
31
32### What the two strand classes are (`smh_gen_*` and `smh_draw_*`)
33
34Shader inspection of `smh_gen_*`, `smh_draw_64`, `smh_draw_128`, `VS_HairStrandGeometry`, and
35`PS_HairStrandVBuffer` confirms that **neither class 0 nor class 1 is "the detailed one"**. They are two
36placement sets of one groom, generated alike and drawn together:
37
38- **Same strand shape and style inputs**: every `smh_gen_*` variant reads points-per-strand from per-instance
39 record `+0x54` bits 16–23, writes 16 bytes per point, and reads the same shared style/texture fields
40 (`+0x11c` texture value range, `+0x128` texture heap index, `+0x58` style record index into SRV `t72`).
41- **Drawn together as one batch**: both the software strand rasterizer (`smh_draw_64`, `smh_draw_128` /
42 `CS_VisHair`) and the hardware visibility-buffer path (`VS_HairStrandGeometry` + `PS_HairStrandVBuffer`) load
43 both counts and draw `(count0 + count1) * (points - 1)` segments together. A secondary point count at
44 `+0x54` bits 24–31 replaces the primary count in cheaper/shadow passes.
45- **Per-instance record (`t71`, `0x150` bytes)**:
46
47| Instance offset | Meaning |
48|---|---|
49| `+0x50` | Feature bit `128` parameter |
50| `+0x54` | Bits 16–23 = points per strand; bits 24–31 = secondary point count (shadow / cheaper passes) |
51| `+0x58` | Style index into SRV `t72` (`0xb0`-byte style records; `+0x10` = 256-bit region mask) |
52| `+0x6c` | Class 1 output buffer offset (read by `smh_gen_2`, `_4`, `_8`, `_16`) |
53| `+0xa0`, `+0x148` | Feature bit `32` parameters |
54| `+0xc8..+0xd0` | Feature bit `128` parameters |
55| `+0xe0`, `+0xe4`, `+0xe8` | Skin matrix buffer handles |
56| `+0xf0` | Feature bit `256` parameter |
57| `+0x100`, `+0x104` | Class 1 start index and strand count (`smh_gen_2`, `_4`, `_8`, `_16`) |
58| `+0x108`, `+0x10c`, `+0x110` | Class 0 start index, strand count, and output buffer offset (`smh_gen_1`) |
59| `+0x11c` | Two `float16` values: texture value range (shared by both classes) |
60| `+0x120` | Descriptor-heap index of the GPU asset buffer |
61| `+0x124`, `+0x12c` | Feature bit `64` parameters (accompanied by two additional textures) |
62| `+0x128` | Shared texture heap index (length/attribute lookup) |
63
64- **`smh_gen_N` variant bitmask**:
65 - **Low 5 bits (placement mode)**: bit `1` generates **class 0** (`+0x108`/`+0x10c`/`+0x110`, per-triangle
66 count byte 0, asset header seed `+0x7c`); bits `2`, `4`, `8`, and `16` select four placement modes of
67 **class 1** (`+0x100`/`+0x104`/`+0x6c`, additionally reading asset header `+0x64`, `+0x70`, seed `+0x80`,
68 and the `+0x90..+0x9f` lookup curve; `smh_gen_2` reads `tri_count` byte 3 and `smh_gen_4` reads bytes 1
69 and 3).
70 - **Higher feature bits (`32..480`)**: bit `32` reads `+0x148` and `+0xa0`; bit `64` reads `+0x124`,
71 `+0x12c`, and two additional textures; bit `128` reads `+0x50` and `+0xc8..+0xd0`; bit `256` reads `+0xf0`.
72
73## Binary container and system page layout
74
75On disk inside RPF9 archives (see [rpf.md](rpf.md)), each groom LOD is stored as a native RAGE resource: a
7616-byte all-zero prefix on a 16-byte boundary followed by one zlib-compressed **system page** (464 to 672 bytes
77inflated), padded to a 16-byte boundary, followed by one or more 16-byte-aligned zlib-compressed chunks that
78concatenate to the **GPU asset buffer**.
79
80System pointers use base `0x50000000` (`SYS_BASE`); GPU buffer pointers use base `0x60000000` (`GPU_BASE`).
81
82| System offset | Type | Meaning |
83|---|---|---|
84| `+0x00` | `u8[8]` | Zero vtable placeholder before resource fixup |
85| `+0x1c` | `u32` | Constant type ID `0x7d8f3db3` in every groom LOD resource |
86| `+0x30` | `float4` | Primary bounding box minimum `(x, y, z, w)` in metres (skeleton-root space, Z-up) |
87| `+0x40` | `float4` | Primary bounding box maximum `(x, y, z, w)` in metres (skeleton-root space, Z-up) |
88| `+0x50..+0x6f` | `float4[2]` | Secondary bounds floats (within the `+0x48..+0x70` float block); left unset at `+FLT_MAX` (`0x7f7fffff`, LE `ff ff 7f 7f`) / `-FLT_MAX` (`0xff7fffff`) on child rigs |
89| `+0x70` | `u64` | System pointer (`- 0x50000000`) to the GPU buffer descriptor (`+0x08`: `u32` dword count, `+0x0c`: `u16` stride = `4`, `+0x0e`: `u16` flags = `8`, `+0x18`: `u64` GPU pointer = `0x60000000`) |
90| `+0x98` / `+0xa0` | `u32`, `u64` | Count and system pointer to `u32` skinning bone name hashes (`joaat32`, see [character_skeleton.md](character_skeleton.md)) |
91| `+0xa8` / `+0xb0` | `u32`, `u64` | Region record count (`0..64`) and system pointer to 12-byte region records (`<HHHBBI`: triangles, guides, class 0 strands, pad, region ID, class 1 strands) |
92| `+0xb8` | `u32[6]` | Six metadata hashes: slots `0..3` skinning bone hashes (`0x34c53e77` = `SKEL_Head`, `0x89ea2ed6` = unused slot fill), slot `4` (`+0xc8`) style preset hash, slot `5` (`+0xcc`) part class hash |
93| `+0xd0` | `u32, u32, u32, u16, u16` | Class 0 strand total, class 1 strand total, reserved word, triangle count, guide count |
94| `+0xe8..+0x10f` | `float16[20]` | Half-float style parameters (width, longest guide, braid parameter, and two 6-half-float curl/frizz blocks) |
95
96### System page `+0xb8` metadata hashes and part classes
97
98The six 32-bit hashes at `+0xb8..+0xcf` carry bone, style-preset, and part-class metadata (none is a texture
99hash, as texture indices use 64-bit hashes):
100
101- **Slots `0..3` (`+0xb8..+0xc7`)**: skinning bone name hashes (`0x34c53e77` = `SKEL_Head`; unused slots are
102 filled with `0x89ea2ed6`).
103- **Slot `4` (`+0xc8`)**: style preset hash (`425` distinct values across the corpus; the most frequent value
104 `0x74792000` appears in `968` grooms).
105- **Slot `5` (`+0xcc`)**: part class hash (`30` distinct values across the corpus). Measured classes exposed in
106 `tools/smh_groom.py` (`PART_CLASS_NAMES`):
107
108| `+0xcc` hash | Part class | Observed properties |
109|---|---|---|
110| `0xd54a2d40` | `main_hair` | Primary scalp hair volume |
111| `0x27b342a3` | `short_hair` | Short scalp hair |
112| `0xe61e1493` | `long_hair` | Long scalp hair |
113| `0x1caeb442` | `fuzz` | Hairline / fade fuzz (~1 cm guides, 500+ guides of 2–3 nodes) |
114| `0xe2500e92` | `braids_ties` | Braids and ties (few guides; 82% have a single LOD) |
115| `0x44d2709f`, `0x42c7e1d0` | `beard` | Facial hair / beards |
116| `0x83a664e7` | `lashes` | Eyelashes (91% have a single LOD) |
117| `0xa228cc57` | `body_hair` | Body hair |
118| `0x304dd218`, `0xc50e7d12` | `animal_fur` | Animal fur grooms |
119
120### System page `+0xe8` half-float style parameters
121
122Decoded by `parse_system_page()` in `tools/smh_groom.py` (IEEE 754 `float16`, little-endian):
123
124| System offset | Field | Meaning |
125|---|---|---|
126| `+0xe8` | `strandWidth` | Strand width parameter (`0.1` in most grooms, `0.03` in some) |
127| `+0xea`, `+0xee` | `longestGuideM`, `longestGuideAltM` | Longest guide arc length in metres |
128| `+0xf0` | `braidParam` | Correlates with braided styles across rig runs (`r = 0.75`) |
129| `+0xf8..+0x103` | `curlFrizz0` | Six half-floats: two amounts (`+0xf8`, `+0xfa`), two radii in metres (typically a few mm: `+0xfc`, `+0xfe`), two frequencies per metre (`+0x100`, `+0x102`) |
130| `+0x104..+0x10f` | `curlFrizz1` | Six half-floats: two amounts (`+0x104`, `+0x106`), two radii in metres (`+0x108`, `+0x10a`; `+0x10a` correlates with curly styles at `r = 0.81`), two frequencies per metre (`+0x10c`, `+0x10e`; ~70/m in dense curly styles) |
131
132## GPU asset buffer header (`0xA0` bytes)
133
134The GPU asset buffer begins with 40 little-endian `u32` words (`0x00..0x9f`). Offset fields hold byte offsets
135from the start of the GPU buffer (`0` means the optional array is absent). Element domains are **G** (per guide),
136**N** (per node, stored guide-major as `node = guide * nodes_per_guide + k`), and **T** (per scalp triangle).
137
138| Header offset | Name | Stride | Domain | Layout and shader usage |
139|---|---|---:|---|---|
140| `+0x00` | `attr_a` | 4 B | G | Three threshold bytes + `0xff` (`smh_gen`: compared against RNG) |
141| `+0x04` | `attr_b` | 4 B | G | Three threshold bytes + pad (`smh_gen`) |
142| `+0x08` | `uv` | 4 B | G | Two IEEE 754 `float16` values: root UV (`smh_gen`) |
143| `+0x0c` | `attr_c` | 4 B | G | Four attribute bytes |
144| `+0x10` | `bone_index` | 8 B | G | Eight `u8` skinning bone palette indices (`smh_pose`, `smh_gen`) |
145| `+0x14` | `bone_weight` | 8 B | G | Eight `u8` skinning weights, normalized by their sum (`smh_pose`, `smh_gen`) |
146| `+0x18` | `ext_18` | 12 B | G | Optional per-guide array (always paired with `ext_1c`) |
147| `+0x1c` | `ext_1c` | 8 B | G | Optional per-guide array (always paired with `ext_18`) |
148| `+0x20` | `tail` | var | — | Optional variable-size tail block (bounded by the next array offset or buffer end) |
149| `+0x24` | `ext_24` | 4 B | G | Optional per-guide array (always paired with `direction`) |
150| `+0x28` | `direction` | 4 B | G | Optional per-guide direction: three bytes decoded as `2 * b / 255 - 1` (`smh_gen`) |
151| `+0x2c` | `sentinel` | — | — | Not an offset: `0xffffffff` in most LODs, `0x0001ffff` in 39 LODs |
152| `+0x30` | `length` | 2 B | G | IEEE 754 `float16` guide arc length in metres (`smh_gen`) |
153| `+0x34` | `node_4` | 4 B | N | Optional per-node array (always paired with `node_2`) |
154| `+0x38` | `node_2` | 2 B | N | Optional per-node array (always paired with `node_4`) |
155| `+0x3c` | `ext_3c` | — | — | Optional array offset (element layout not yet decoded; bounds `tail` when present) |
156| `+0x40` | `triangle` | 6 B | T | Three `u16` guide vertex indices (`smh_gen`) |
157| `+0x44` | `position` | 8 B | N | Four IEEE 754 `float16` values `(x, y, z, w)` rest position in metres (`smh_pose`, `smh_gen`) |
158| `+0x48` | `tri_count` | 4 B | T | Four `u8` per-triangle strand counts by class; byte 0 = class 0 (`smh_gen_1`), byte 3 / bytes 1+3 (`smh_gen_2`/`_4`) |
159| `+0x4c` | `tri_region` | 1 B | T | Optional `u8` region ID (`0` = none), tested against a 256-bit style mask (`smh_gen`) |
160| `+0x50` | `flags` | — | — | `u32` feature/layout flags |
161| `+0x54` | `nodes_packed` | — | — | `(nodes << 8) | low_byte`; `nodes = guides * nodes_per_guide` (`smh_sim`) |
162| `+0x58` | `counts` | — | — | `guides | (triangles << 16)` (`smh_pose`, `smh_gen`) |
163| `+0x5c` | `nodes_per_guide` | — | — | Low byte = nodes per guide (`smh_pose`) |
164| `+0x60` | `length_random` | — | — | Two IEEE 754 `float16` values: `(amount, min_factor)` (`smh_gen`) |
165| `+0x64`, `+0x70` | class 1 params | — | — | Additional placement parameters read by class 1 variants (`smh_gen_2`, `_4`, `_8`, `_16`) |
166| `+0x7c` | `seed_0` | — | — | `u32` RNG seed for strand class 0 (`smh_gen_1`) |
167| `+0x80` | `seed_1` | — | — | `u32` RNG seed for strand class 1 (`smh_gen_2`, `_4`, `_8`, `_16`) |
168| `+0x90..0x9f` | `curve` | — | — | 16-byte monotonic lookup curve (read by class 1 variants) |
169
170Stored guide lengths at `+0x30` match the polyline arc lengths integrated from `+0x44` to half-float rounding
171precision (worst measured discrepancy 1.7 mm, median 0.37 mm across the corpus).
172
173## LOD chains, spatial calibration, and archive structure
174
175### LOD chains and split-chain structure
176
177A logical groom asset owns 1 to 4 LOD resources stored in descending guide-count order: guide count and scalp
178triangle count drop by roughly `0.6x` per LOD while `nodes_per_guide`, `flags`, bounding box, and target strand
179totals remain stable. Because guides are what `smh_pose_*` and `smh_sim_*` skin and simulate, asset LODs reduce
180simulation cost; any distance reduction in strand count (`+0x10c`/`+0x104`) or points per strand (`+0x54` bits
18124–31) is controlled by runtime game code rather than stored per LOD.
182
183Entries inside the nested groom archive (`packs.rpf`, offset `0xf10fb000`) sort in **item-name order**. Most LOD
184chains are contiguous, but **`396` split assets** in `packs.rpf` enclose **`413` inner assets** (`276` in scalp
185hair, `48` in story-character grooms, `24` in beards, `26` in animals, and `39` across other blocks): the outer
186asset's LOD 0 appears first, followed by one or more inner assets whose names share the outer asset's prefix,
187followed by the outer asset's LODs 1..3. `tools/smh_groom.py` rejoins split chains when `nodes_per_guide`,
188`flags`, bounding boxes (within 3 cm), and class 0/1 strand totals (within `max(12, 5%)`) match and guide count
189strictly decreases.
190
191Exhaustive byte-level scanning of system page `0x00..0x130` and GPU buffer header `0x00..0x380` confirmed **no
192per-item identifier or grouping marker field** is stored in groom resources (the only consistent cross-group
193byte difference in `0x00..0x130` is the unset `+0x50..+0x6f` floats on child rigs). Likewise, the nested groom
194archive holds `20,010` groom LODs plus `1,890` other resources in `80` clusters (no per-item file), and each
195stub drawable holds one material with a system page of `1,712` or `1,728` bytes varying only by name length.
196
197### Standing-height calibration and bone-based face/scalp discrimination
198
199- **Root vertical offset**: all human rigs share a single `1.0 m` vertical root offset (`groom z + 1.0 m =
200 standing height`). Measured stub drawable heights by rig class: adult male `1.736 m`, adult female `1.626 m`,
201 child `0.974 m`, infant `0.563 m`.
202- **Fitted scalp head spheres** (in skeleton-root space, measured across scalp guide roots with `5 mm` residual):
203 - Adult male: centre `(0.000, 0.000, 0.721) m`, radius `0.091 m`.
204 - Adult female: centre `(0.000, -0.011, 0.624) m`, radius `0.087 m`.
205- **Why sphere geometry alone cannot separate male beards from female scalp**: male facial hair sits on the
206 female head sphere (`13 mm` residual against `6 mm` for female scalp), and female fringes occupy the same
207 front-of-head volume as male beards.
208- **Skinning bone discrimination**: the bone hash list at `+0x98/+0xa0` separates them — `9` skinning bone
209 hashes occur in beards and never in scalp grooms, while `13` occur in scalp grooms and never in beards. Grooms
210 skinned only to the single head bone (`49` of `182` beard grooms and `835` of `2,415` scalp hair grooms) remain
211 undecided by bones alone.
212
213## Class 0 RNG and barycentric strand interpolation
214
215`tools/smh_groom.py` implements the exact 32-bit unsigned integer arithmetic of `smh_gen_1_CS_InterpolateStrands`
216in pure Python standard library code:
217
218### 1. Scalp triangle selection (4 attempts)
219
220For each strand thread ID `t` in `0 .. count - 1`, all integer ops wrap modulo `2^32`:
221
2221. Initialize `v3 = t * 0x19660D + 0xEF3EFB11`.
2232. For `attempt` in `0, 1, 2, 3`:
224 - Compute `s0 = attempt * 0x19660D + 0x86945BED` and `v11 = s0 * 0x153E39CE + v3`.
225 - Mix `v5`, `v6`, `v7`, `v8`, `v10` using the shader's multiply-add and `x ^= x >> 16` sequence.
226 - Candidate triangle index: `pick = (v8 >> 16) % triangles`.
227 - Look up `rid = tri_region[pick]`. If `rid != 0` and bit `rid` is set in the 256-bit style mask, mark the
228 strand culled for this attempt and continue to the next attempt.
229 - Otherwise record `v20 = v5 >> 8` and test `(v6 & 0xFFFFFF) * 2^-24 < clamp_f32(tri_count[pick][0] * density_scale, 0, 1)`.
230 If accepted, stop searching.
2313. If all four attempts fail to accept, the final attempt's `tri`, `culled`, and last live `v20` remain.
232
233`density_scale` is supplied per instance at runtime; offline export defaults to `1 / max(tri_count[:, 0])` so
234the densest scalp triangle is always accepted.
235
236### 2. Barycentric coordinates (`v_mad_u32_u24` cascade)
237
238Using `mul24(a, b) = ((a & 0xFFFFFF) * (b & 0xFFFFFF)) & 0xFFFFFFFF` and constant `k = 0xC083C5`:
239
240- `seed = (0x3C1 * (tri & 0xFFFF) + seed_0 * 0x8A30D + v20 * 31) & 0xFFFFFFFF`
241- Six `mul24` + add steps with `0x3C6EF35F` and `x ^= x >> 12` folding yield two 24-bit integers `a` and `b`.
242- `u1 = a * 2^-24`, `u2 = b * 2^-24`, `r = sqrt(u1)`.
243- Uniform barycentric weights on the scalp triangle: `bary = (1 - r, (1 - u2) * r, u2 * r)`.
244
245### 3. Rest-pose blending and length trimming
246
247For each unculled strand on triangle `(g0, g1, g2)` with weights `(b0, b1, b2)`:
248
249- Blend each node `k` of the three guides: `P[k] = b0 * pos[g0][k] + b1 * pos[g1][k] + b2 * pos[g2][k]`.
250- Blend stored guide arc length: `L_guide = b0 * len[g0] + b1 * len[g1] + b2 * len[g2]`.
251- Compute per-strand PCG hash of `seed`:
252 `v = seed * 0x2C9277B5 + 0xAC564B05`, `w = (((v >> ((v >> 28) + 4)) ^ v) * 0x108EF2D9)`,
253 `u_len = ((w >> 22) ^ (w & 0xFFFFFF)) * 2^-24`.
254- Target length from header `+0x60` `(amount, low)`:
255 `factor = low + u_len * (1 - low)`, `L_target = max(L_guide * (1 + (factor - 1) * amount), 0)`.
256- Walk segments `k = 1 .. nodes_per_guide - 1`, clamping each segment to the remaining length (using a minimum
257 segment length floor of `2^-23` m and zeroing steps below `1e-9` m). Trailing nodes past the trimmed tip repeat
258 the tip coordinate.
259
260## Measured corpus census
261
262Aggregate counts measured with `python -I tools/smh_groom.py census` across the two package archives that hold
263groom resources (other archives such as `data.rpf`, `story000`, and `shared_minigame000` hold none):
264
265| Archive | Groom assets | LOD resources | Decode errors | GPU buffer bytes | Class 0 strands | Class 1 strands |
266|---|---:|---:|---:|---:|---:|---:|
267| `packs.rpf` | 5,741 | 20,010 | 0 | 902,231,288 | 77,123,314 | 35,359,612 |
268| `core_restofworld.rpf` | 10 | 36 | 0 | 225,568 | 3,099 | 5,596 |
269| **Total** | **5,751** | **20,046** | **0** | **902,456,856** | **77,126,413** | **35,365,208** |
270
271Additional corpus-wide properties across all 20,046 decoded LODs and 5,751 LOD 0 assets:
272
273- **Decode coverage**: 20,046 / 20,046 LOD resources decode cleanly (0 failures).
274- **Geometry ranges**: 3 to 5,185 guides per LOD; 2 to 80 nodes per guide.
275- **LOD depths**: 4,534 assets have 4 LODs, 341 have 3 LODs, 11 have 2 LODs, and 865 have 1 LOD (82% of the
276 `braids_ties` class and 91% of `lashes` are single-LOD).
277- **Per-triangle strand sums**: summing `tri_count[:, 0]` equals system page `+0xd0` in 5,716 / 5,751 LOD 0
278 assets; summing `tri_count[:, 1]` equals `+0xd4` in 3,158 / 5,751 LOD 0 assets (confirming class 1 placement
279 uses the four additional shader placement modes `smh_gen_2`, `_4`, `_8`, and `_16`).
280- **System page metadata**: `425` distinct `+0xc8` style preset hashes (`0x74792000` in 968 grooms), `30`
281 distinct `+0xcc` part class hashes, and `2,457` / `5,741` `packs.rpf` assets (including child-rig hair
282 grooms) with unset `+0x50..+0x6f` secondary bounds floats (`0x7f7fffff` / `0xff7fffff`).
283- **Split chains**: `396` split assets enclosing `413` inner assets in `packs.rpf`.
284- **Optional arrays**: `node_4` / `node_2` appear together in 12,101 LODs; `ext_18` / `ext_1c` appear together
285 in 10,684 LODs; `ext_24` / `direction` appear together in 5,718 LODs; `+0x3c` is non-zero in 10,756 LODs;
286 header `+0x2c` is `0x0001ffff` in 39 LODs (`0xffffffff` in all other 20,007 LODs).
287- **Heuristic bounding-box placement classes** (5,751 assets): 1,462 Facial hair, 1,371 Body hair, 1,119 Scalp
288 hair, 1,076 Fur and other, 723 Brows and lashes.
289
290## What is exact vs. modelled or open
291
292| Component | Status | Notes |
293|---|---|---|
294| Binary layout (system page, `+0xb8` hashes, `+0x50..+0x6f` child-rig float sentinels, `+0xe8` half-float style params, GPU header, guides, nodes, triangles, skin, lengths, UVs, counts, regions) | Exact | Verified across all 20,046 LODs (0 decode failures) against `smh_pose_0_CS_PreSkinSimGuides` and `smh_gen_*_CS_InterpolateStrands` |
295| Strand class relationship (class 0 vs. class 1) | Exact (shader-verified) | Neither class is more detailed; both are placement sets of one groom generated with the same points-per-strand (`+0x54` bits 16–23, 16 B/pt) and drawn together as `(count0 + count1) * (points - 1)` segments in one batch |
296| Class 0 root triangle selection & barycentric RNG | Exact | Bit-exact 32-bit unsigned integer port of `smh_gen_1_CS_InterpolateStrands`; `density_scale` defaults to `1 / max(tri_count)` |
297| Rest-pose strand shape and length trimming | Modelled | Barycentric blend of three guides trimmed via `+0x60` PCG length variation; omits runtime style record (clump/curl/frizz/region mask), length texture, skinning, and simulation |
298| Class 1 strand scattering | Approximate | Class 1 total is exact; the four placement modes (`smh_gen_2`, `_4`, `_8`, `_16`) are not yet ported |
299| Optional arrays `ext_18`, `ext_1c`, `ext_24`, `node_4`, `node_2`, `+0x3c`, `tail` | Undecoded | Spans are parsed and reported; per-field semantics remain open |
300| Groom-to-item name linking | Partial / encrypted TOC | Groom resources store no per-item marker or name hash, and the nested RPF9 file table is encrypted (see [rpf.md](rpf.md) and [character_models.md](character_models.md)) |
301
302## CLI usage (`tools/smh_groom.py`)
303
304`tools/smh_groom.py` uses only the Python standard library (`python -I`) and reuses the binary glTF 2.0 container
305primitives from `tools/glb_writer.py`. Synthetic unit tests live in `tests/test_smh_groom.py`.
306
307```powershell
308# Inspect a carved .smh file or an archive member at a byte offset
309python -I tools/smh_groom.py inspect <file.smh> --json
310python -I tools/smh_groom.py inspect <archive.rpf> --offset 0x1000
311
312# Run an aggregate census over one or more archives, carved .smh files, or directories
313python -I tools/smh_groom.py census <archive.rpf> --json
314
315# Export a groom to glTF 2.0 binary (.glb) as 3-sided tubes, flat ribbons, LINES, or LINE_STRIP
316python -I tools/smh_groom.py export-glb <file.smh> out_tubes.glb --geometry tubes --strands 6000
317python -I tools/smh_groom.py export-glb <file.smh> out_ribbons.glb --geometry ribbons --strands 4000
318python -I tools/smh_groom.py export-glb <file.smh> out_curves.glb --curves --strands 12000
319python -I tools/smh_groom.py export-glb <file.smh> out_strips.glb --geometry line-strip --no-scalp --no-guides
320```
diff --git a/docs/testing.md b/docs/testing.md
index 47a9f4a22..060869fd0 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -20,12 +20,16 @@ This page collects the setup steps and the problems testers have run into so far
20 - `llvm-21` in WSL, with `LLVM_MC` set to the whole command: 20 - `llvm-21` in WSL, with `LLVM_MC` set to the whole command:
21 `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`. 21 `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`.
22 22
23 On Linux and macOS, the distribution's or Homebrew's `llvm-mc` on `PATH` is enough, if it is 21 or newer. 23 On Linux, the distribution's `llvm-mc` on `PATH` is enough, if it is 21 or newer. On macOS, Homebrew's `llvm` is
24 keg-only, so `brew install llvm` doesn't put `llvm-mc` on `PATH`: the pytest suites find it in
25 `/opt/homebrew/opt/llvm*/bin` (or `/usr/local/opt/llvm*/bin` on Intel), and the other tools need
26 `LLVM_MC="$(brew --prefix llvm)/bin/llvm-mc"`.
24 27
25 An older `llvm-mc` is not enough for everything. Ubuntu 24.04's `llvm-18` (18.1.3) runs `run_gpu_tests.py`, 28 An older `llvm-mc` is not enough for everything. Ubuntu 24.04's default `llvm-18` (18.1.3) works for
26 `valu_fuzz.py --family mem` and `lds_fuzz.py`, but rejects `op_sel` on the 16-bit integer VOP3 forms that 29 `valu_fuzz.py --family mem` and `lds_fuzz.py`, but rejects `ps_sdwa_f16_const`. LLVM 19+ assembles the stock CI
27 `valu_fuzz.py --family f16` generates (`v_ashrrev_i16_e64 ... op_sel:[0,0,0]`: "not a valid operand"), so no f16 30 test fixtures. However, full f16 fuzzing with `valu_fuzz.py --family f16` requires LLVM 21+, as LLVM 19 still
28 program assembles. 23.1.6 assembles them. 31 rejects `op_sel` on the 16-bit integer VOP3 forms that the fuzzer generates
32 (`v_ashrrev_i16_e64 ... op_sel:[0,0,0]`: "not a valid operand").
29 33
30 On Windows, ROCm 7.2's bundled `llvm-mc.exe` reports LLVM 21.0.0git. It assembled the TEST-71 memory and 34 On Windows, ROCm 7.2's bundled `llvm-mc.exe` reports LLVM 21.0.0git. It assembled the TEST-71 memory and
31 LDS programs but rejected the 16-bit shift used by the f16 generator. To check an assembler directly in 35 LDS programs but rejected the 16-bit shift used by the f16 generator. To check an assembler directly in
@@ -96,6 +100,14 @@ Actions -> Runtime, and check out the commit it built, or start a run of the com
96python -I scripts/run_gpu_tests.py --build <unzipped runtime-windows> 100python -I scripts/run_gpu_tests.py --build <unzipped runtime-windows>
97``` 101```
98 102
103If you also have neither `llvm-mc` nor SPIRV-Tools (`spirv-as` / `spirv-val`) installed, `--disasm-dir` runs the
104pre-disassembled subset in `tests/semantic/fixtures/disasm` and `--assembler python` (the default under `auto` when
105`spirv-as` is absent) assembles SPIR-V with `tools/spirv_asm.py`:
106
107```sh
108python -I scripts/run_gpu_tests.py --build <unzipped runtime-windows> --disasm-dir tests/semantic/fixtures/disasm --assembler python
109```
110
99`build.py` and `check.py` take the same folder as their second argument: 111`build.py` and `check.py` take the same folder as their second argument:
100 112
101```sh 113```sh
@@ -105,6 +117,22 @@ python -I runtime/test/shaders/check.py <out dir> <unzipped runtime-windows>
105 117
106The artifact belongs to the commit that built it, so run the scripts from that commit as well (see the note above). 118The artifact belongs to the commit that built it, so run the scripts from that commit as well (see the note above).
107 119
120#### Run one test from the Windows artifact
121
122For a focused GPU check without building locally, extract the artifact and open
123PowerShell in the directory containing the test executable. Keep the extracted
124files together so the test can find any fixtures relative to that directory.
125For example, to run the synthetic depth/stencil resolve test without game files:
126
127```powershell
128.\d3d12_depth_resolve_test.exe
129Write-Output "Test exit code: $LASTEXITCODE"
130```
131
132Report the executable name, the workflow run and its commit, your GPU and driver,
133the exit code, and the test summary in [#166](https://github.com/ItsNotRexed/Leonida/issues/166).
134Label it as a single-test run so the result is easy to distinguish from a full suite run.
135
108## Run them 136## Run them
109 137
110The whole suite, assembled, translated and run in one go: 138The whole suite, assembled, translated and run in one go:
@@ -118,8 +146,8 @@ Add `--require-pass` when verifying a specific path: an all-skipped run exits 1
118Skips still appear as `SKIP`, and individual skips are allowed if at least one test passes and none fail. 146Skips still appear as `SKIP`, and individual skips are allowed if at least one test passes and none fail.
119 147
120A GPU test program that runs longer than 120 seconds is killed and counted as a failure, so a hung driver does 148A GPU test program that runs longer than 120 seconds is killed and counted as a failure, so a hung driver does
121not stall the suite. `LEONIDA_GPU_TEST_TIMEOUT` sets the limit in seconds for both `check.py` and 149not stall the suite. `LEONIDA_GPU_TEST_TIMEOUT` sets the limit in seconds for `check.py`, `run_gpu_tests.py` and
122`run_gpu_tests.py`; `0` turns the limit off. 150the `valu_fuzz.py` translator oracle; `0` turns the limit off.
123**Rebuild the test programs after pulling.** The programs carry the V# and push-constant layout the translator expects. An executable from an older commit still loads and runs every shader, so a stale `vk_compute_test` does not fail loudly: when a newer translator starts enforcing a descriptor rule the old program does not set up (the raw V# in `pc[2..3]`, for one), every compute test reports the untouched `0xEEEEEEEE` fill pattern and the run looks like a translator regression. If all the compute tests in a run return that pattern, rebuild first (`cmake --build runtime/build/linux`, or `cmake --build runtime\build` on Windows) and run again before reading anything into the words. 151**Rebuild the test programs after pulling.** The programs carry the V# and push-constant layout the translator expects. An executable from an older commit still loads and runs every shader, so a stale `vk_compute_test` does not fail loudly: when a newer translator starts enforcing a descriptor rule the old program does not set up (the raw V# in `pc[2..3]`, for one), every compute test reports the untouched `0xEEEEEEEE` fill pattern and the run looks like a translator regression. If all the compute tests in a run return that pattern, rebuild first (`cmake --build runtime/build/linux`, or `cmake --build runtime\build` on Windows) and run again before reading anything into the words.
124 152
125The two-step form, which `CONTRIBUTING.md` describes: 153The two-step form, which `CONTRIBUTING.md` describes:
@@ -163,10 +191,13 @@ That mode requires Vulkan, but not a translated shader or WARP. The GPU runner s
163Use `--filter cs_imgload_mip` to check 2D `image_load_mip` on FLOAT (UNORM), UINT and SINT sampled views with 191Use `--filter cs_imgload_mip` to check 2D `image_load_mip` on FLOAT (UNORM), UINT and SINT sampled views with
164both full-width and D16 loads; mip 0 contains decoy data and mip 1 holds the expected texels. 192both full-width and D16 loads; mip 0 contains decoy data and mip 1 holds the expected texels.
165 193
166The shader test programs (`vk_harness`, `vk_compute_test`, `vk_store_test`, `vk_texture_test`, `vk_bindless_test`, 194`vk_compute_test`, `vk_bindless_test` and `vk_image_fuzz` read `LEONIDA_VK_VALIDATION` too (`vk_compute_test`
167`vk_sampler_test`, `vk_image_fuzz`) don't read `LEONIDA_VK_VALIDATION`. To check one, load the layer through the 195through `runtime/test/vk_validation.h`): each validation message goes to stderr and a validation error makes the
168loader and run it by hand, for example 196program exit 1, so `LEONIDA_VK_VALIDATION=1 VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 python scripts/run_gpu_tests.py` fails
169`VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 vk_compute_test x.spv 1 dump`. 197every compute test the layer objects to; the program's output ends with "N validation errors". The other shader test
198programs (`vk_harness`, `vk_store_test`, `vk_texture_test`, `vk_sampler_test`) don't read it.
199To check one, load the layer through the loader and run it by hand, for example
200`VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 vk_harness vs.spv ps.spv out.raw`.
170The layer prints its messages to stdout and the program's exit status doesn't change, and `run_gpu_tests.py` shows 201The layer prints its messages to stdout and the program's exit status doesn't change, and `run_gpu_tests.py` shows
171only each test's last line, so read the program's own output. GPU-assisted validation (`..._GPUAV_ENABLE=1`) 202only each test's last line, so read the program's own output. GPU-assisted validation (`..._GPUAV_ENABLE=1`)
172instruments the translated shaders and reports what they actually do at run time: out-of-bounds buffer accesses, and 203instruments the translated shaders and reports what they actually do at run time: out-of-bounds buffer accesses, and
@@ -199,20 +230,64 @@ Vulkan instance with, so every Vulkan test fails with `vkCreateInstance failed (
199as CI does: `WINEPREFIX="$HOME/.local/share/leonida-wine" xvfb-run -a ctest --test-dir runtime/build/windows` 230as CI does: `WINEPREFIX="$HOME/.local/share/leonida-wine" xvfb-run -a ctest --test-dir runtime/build/windows`
200(packages `xvfb` and `xauth`, which `xvfb-run` needs). With Mesa installed, the tests then run on llvmpipe. 231(packages `xvfb` and `xauth`, which `xvfb-run` needs). With Mesa installed, the tests then run on llvmpipe.
201 232
233A virtual X server has no presentable surface, so presentation cannot be judged under it. With a real display (here
234Wine 11.22 on a Wayland session, through XWayland) the same 123-test list gives 92 passed, 6 failed and 25 skipped,
235and `vk_presenter_sync`, `xbox_present` and `dxgi_swapchain` pass, while they fail under `xvfb-run`. Use a real
236compositor for those three. Six still failed with a real display: `device_proxy`, `d3d12_xs_root_signature`,
237`xdxr_build`, `d3d12_xdxr_rt`, `d3d12_present` and `d3d12_compute`.
238
202The build type defaults to `RelWithDebInfo`: xwin leaves out the debug CRT, so `Debug` needs `--include-debug-libs`. 239The build type defaults to `RelWithDebInfo`: xwin leaves out the debug CRT, so `Debug` needs `--include-debug-libs`.
203`make_game.py`'s `runtime` stage makes this same build on Linux when the tools and the SDK are there (`--runtime-build 240`make_game.py`'s `runtime` stage makes this same build on Linux when the tools and the SDK are there (`--runtime-build
204runtime/build/windows` takes a folder made by hand like a Windows build). CMake packages are 241runtime/build/windows` takes a folder made by hand like a Windows build). CMake packages are
205looked up only inside the SDK folder, so a Windows SDL3 for the GameInput shim is passed as `-DSDL3_DIR=<its 242looked up only inside the SDK folder, so a Windows SDL3 for the GameInput shim is passed as `-DSDL3_DIR=<its
206cmake folder>` (`CMAKE_PREFIX_PATH` is not searched here). 243cmake folder>` (`CMAKE_PREFIX_PATH` is not searched here).
207 244
208For Proton, start any program once with `proton run` (with `STEAM_COMPAT_DATA_PATH` and 245### Proton's wine
209`STEAM_COMPAT_CLIENT_INSTALL_PATH` set), so that it puts vkd3d-proton and DXVK into the prefix, then configure with 246
210`-DCMAKE_CROSSCOMPILING_EMULATOR="<Proton>/files/bin/wine"` and run `ctest` with 247Proton's wine runs the suite against the D3D12 a Proton game gets: the prefix's vkd3d-proton and DXVK. Start any
211`WINEPREFIX=$STEAM_COMPAT_DATA_PATH/pfx WINEDLLOVERRIDES="d3d12=n;d3d12core=n;dxgi=n"`. `proton run` itself doesn't 248program once with `proton run` so that it lays down the prefix libraries; the `STEAM_COMPAT_DATA_PATH` folder has to
212pass the program's output on, so the tests can't run through it. 249exist first, because Proton opens `<data>/pfx.lock` in it:
213 250
214The tests that compare with the host's D3D12 (`root_sig_test`, `root_sig`, `device_proxy`, `d3d12_vulkan_device`) 251```sh
215check against Wine's vkd3d or vkd3d-proton here, not Microsoft's runtime, so some of them fail for that reason. 252mkdir -p ~/.local/share/leonida-proton
253STEAM_COMPAT_DATA_PATH="$HOME/.local/share/leonida-proton" \
254STEAM_COMPAT_CLIENT_INSTALL_PATH="$HOME/.local/share/Steam" \
255 "$HOME/.local/share/Steam/steamapps/common/Proton 11.0/proton" run cmd /c exit 0
256cmake -S runtime -B runtime/build/proton --toolchain "$PWD/runtime/cmake/clang-cl-xwin.cmake" \
257 -DXWIN_DIR="$HOME/.local/share/xwin-sdk" \
258 -DCMAKE_CROSSCOMPILING_EMULATOR="$HOME/.local/share/Steam/steamapps/common/Proton 11.0/files/bin/wine"
259cmake --build runtime/build/proton --parallel 2
260WINEPREFIX="$HOME/.local/share/leonida-proton/pfx" WINEDLLOVERRIDES="d3d12=n;d3d12core=n;dxgi=n" \
261 WINEDEBUG=-all ctest --test-dir runtime/build/proton
262```
263
264`proton run` itself doesn't pass the program's output on, so the tests can't run through it. `WINEPREFIX` must be
265the prefix the emulator made: a prefix from another wine version fails every test with "wine client error: version
266mismatch". The tests need a real display here as well.
267
268Measured on 2026-11-23 with Proton 11.0 (wine-11.0, vkd3d-proton 3.0) on an RX 7600 XT (radv): 155 tests
269registered, 154 run, 127 passed, 20 skipped, one disabled and seven failed. The skips are the usual ones (game data,
270`LEONIDA_FIRST_LIGHT_DIR`, no independent Vulkan queue for `d3d12_queue_wait`, and so on). All seven failures are in
271the comparisons with the host D3D12, which is vkd3d-proton here:
272
273- `d3d12_fence_timing`, `d3d12_private_data`, `d3d12_sampler2` and `d3d12_subresource_copy` disagree with
274 vkd3d-proton on a return value or a field it writes (`GetCustomHeapProperties` of a custom heap type,
275 `SetName(nullptr)`, unknown sampler flags, CPU-copy boxes).
276- `d3d12_r9g9b9e5_uav` compares a clear with WARP, and Proton's dxgi answers `EnumWarpAdapter` with the first
277 hardware adapter ("WARP not supported"), so the compared value is the hardware's.
278- `d3d12_compute` and `d3d12_method_variants` crash with an access violation inside `d3d12core.dll` on their
279 null-argument checks, not on device creation: `GetCachedBlob(nullptr)` and `CreateCommandQueue1(nullptr, ...)`
280 are not validated by vkd3d-proton (filed upstream as vkd3d-proton issues 3512 and 3513; Wine's builtin d3d12
281 crashes on the queue one too). `d3d12_compute` passes with only `WINEDLLOVERRIDES="dxgi=n"`, where the host is
282 Wine's own d3d12 and the comparison skips.
283
284The host's D3D12 here is Wine's vkd3d or vkd3d-proton, not Microsoft's runtime, and Proton's `EnumWarpAdapter`
285returns the hardware adapter, so "WARP" is vkd3d-proton on the GPU. Most tests that compare with the host or WARP
286skip that comparison under Wine and Proton (`runtime/test/host_wine.h`), and most of them still check the layer
287against Microsoft's answers recorded in the test (`d3d12_subresource_copy` and `d3d12_private_data` keep theirs in
288`d3d12_subresource_copy_answers.h` and `d3d12_private_data_answers.h`).
289A few still compare with the host (`root_sig`, `device_proxy`, and some of `d3d12_vulkan_device`'s cases), so some
290of those fail for that reason.
216 291
217## GPUs with 32-wide subgroups (NVIDIA, Intel, Apple) 292## GPUs with 32-wide subgroups (NVIDIA, Intel, Apple)
218 293
@@ -251,12 +326,15 @@ partition invariance"). `runtime/test/shaders/w64_graphics.py` checks those tier
251must differ. CI has no GPU, and the CPU wave interpreter (`tests/semantic/test_wave64_halves.py`) runs vertex shaders 326must differ. CI has no GPU, and the CPU wave interpreter (`tests/semantic/test_wave64_halves.py`) runs vertex shaders
252only, so this comparison needs real hardware. 327only, so this comparison needs real hardware.
253 328
254Vulkan can require a subgroup size for pixel shaders (`VKH_SUBGROUP_SIZE`) but not for vertex or geometry shaders, so 329Vulkan can require a subgroup size for pixel shaders (`VKH_SUBGROUP_SIZE`) where the driver lists the fragment stage in
255those two use a RADV switch instead: on GFX10 and newer, RADV runs them as wave64 by default and as wave32 with 330`requiredSubgroupSizeStages`, but not for vertex or geometry shaders, so those two use a RADV switch instead: on GFX10
256`RADV_PERFTEST=gewave32`. The runner sets it itself and checks the result with a probe fixture per stage 331and newer, RADV runs them as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32`. The runner sets it itself
257(`vs_w64_c_lane_id`, `gs_w64_c_lane_id`): the largest lane id must reach 32 at wave64 and stay below 32 at wave32. On 332and checks the result with a probe fixture per stage (`vs_w64_c_lane_id`, `gs_w64_c_lane_id`): the largest lane id
258other drivers (AMD Windows, NVIDIA, Intel) the probe sees no change, and only the default-size checks run; tier C is 333must reach 32 at wave64 and stay below 32 at wave32. On other drivers (AMD Windows, NVIDIA, Intel) the probe sees no
259then a `SKIP`, not a failure. 334change, and only the default-size checks run; tier C is then a `SKIP`, not a failure. Not every driver lists the
335fragment stage either: on an RX 6800 (RDNA2) with AMD's Windows driver 26.11.2 the list is compute only, no size can
336be requested for pixel shaders (they run at the 64-wide default), and the tier C pixel fixtures are a `SKIP` too
337(2026-11-22, [d3d12_vulkan.md](d3d12_vulkan.md), "Subgroup size").
260 338
261Build and run it on Linux with RADV, pinned to one GPU (`LEONIDA_VK_DEVICE`, see "Choosing the GPU"): 339Build and run it on Linux with RADV, pinned to one GPU (`LEONIDA_VK_DEVICE`, see "Choosing the GPU"):
262 340
@@ -283,8 +361,9 @@ Each line prints `ok`, a `SKIP` with its reason, or what differed. To add a fixt
283The translated shaders take 144 bytes of push constants: s0..s31, then the heap base and the code base. A device whose 361The translated shaders take 144 bytes of push constants: s0..s31, then the heap base and the code base. A device whose
284`maxPushConstantsSize` is 128, Vulkan's minimum, can't take that, so the texture tests and every test drawn through 362`maxPushConstantsSize` is 128, Vulkan's minimum, can't take that, so the texture tests and every test drawn through
285`vk_harness` skip there (`unsupported: need 144 push constant bytes, device has 128`); `vulkaninfo` shows the limit. 363`vk_harness` skip there (`unsupported: need 144 push constant bytes, device has 128`); `vulkaninfo` shows the limit.
286AMD's Windows driver reports 128 on RDNA2 iGPUs (Radeon 680M, 610M, the Ryzen 7000 iGPU); RADV reports more on the 364AMD's older Windows drivers report 128 on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5
287same chips. 3657600's iGPU on 24.10.24); 26.11.2 reports 256 on a Radeon 610M, where these tests run without the variable below.
366RADV reports more on the same chips.
288 367
289To run them anyway, set `LEONIDA_PC_TAIL_UBO=1` **for both `build.py` and `check.py`** (or for 368To run them anyway, set `LEONIDA_PC_TAIL_UBO=1` **for both `build.py` and `check.py`** (or for
290`run_gpu_tests.py`). The shaders are then translated with `--pc-tail-ubo`: s0..s31 stay in 128 push-constant bytes, 369`run_gpu_tests.py`). The shaders are then translated with `--pc-tail-ubo`: s0..s31 stay in 128 push-constant bytes,
@@ -300,8 +379,9 @@ constants, so those tests skip.
300The translated shaders take 144 bytes of push constants: s0..s31, then the heap base and the code base. A device whose 379The translated shaders take 144 bytes of push constants: s0..s31, then the heap base and the code base. A device whose
301`maxPushConstantsSize` is 128, Vulkan's minimum, can't take that, so the texture tests and every test drawn through 380`maxPushConstantsSize` is 128, Vulkan's minimum, can't take that, so the texture tests and every test drawn through
302`vk_harness` skip there (`unsupported: need 144 push constant bytes, device has 128`); `vulkaninfo` shows the limit. 381`vk_harness` skip there (`unsupported: need 144 push constant bytes, device has 128`); `vulkaninfo` shows the limit.
303AMD's Windows driver reports 128 on RDNA2 iGPUs (Radeon 680M, 610M, the Ryzen 7000 iGPU); RADV reports more on the 382AMD's older Windows drivers report 128 on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5
304same chips. 3837600's iGPU on 24.10.24); 26.11.2 reports 256 on a Radeon 610M, where these tests run without the variable below.
384RADV reports more on the same chips.
305 385
306To run them anyway, set `LEONIDA_PC_TAIL_UBO=1` **for both `build.py` and `check.py`** (or for 386To run them anyway, set `LEONIDA_PC_TAIL_UBO=1` **for both `build.py` and `check.py`** (or for
307`run_gpu_tests.py`). The shaders are then translated with `--pc-tail-ubo`: s0..s31 stay in 128 push-constant bytes, 387`run_gpu_tests.py`). The shaders are then translated with `--pc-tail-ubo`: s0..s31 stay in 128 push-constant bytes,
@@ -318,7 +398,10 @@ Without `VK_EXT_mesh_shader`, the `ms_*` tests are skipped; that's expected, not
318runs them anyway, set `LEONIDA_MESH_COMPUTE=1` for `run_gpu_tests.py`, together with `LEONIDA_W64_EMULATE=1` on a 398runs them anyway, set `LEONIDA_MESH_COMPUTE=1` for `run_gpu_tests.py`, together with `LEONIDA_W64_EMULATE=1` on a
31932-wide GPU (every mesh shader is wave64). The mesh shaders are then translated with `--mesh-compute`, dispatched as 39932-wide GPU (every mesh shader is wave64). The mesh shaders are then translated with `--mesh-compute`, dispatched as
320compute and drawn by a generated vertex shader (`docs/design.md`, "Mesh shaders as compute"), so the device needs 400compute and drawn by a generated vertex shader (`docs/design.md`, "Mesh shaders as compute"), so the device needs
321`bufferDeviceAddress` and `shaderInt64` instead. 401`bufferDeviceAddress` instead, and `shaderInt64` for a module that declares `Int64`. The standalone tools
402(`vk_harness`, `vk_compute_test`, `vk_texture_test`, `vk_store_test`, `vk_bindless_test`) read the modules'
403capabilities first: they enable `shaderInt64` only for one that declares `Int64` (or `Int64Atomics`), and report 77
404(SKIP, with the reason) when the device lacks it.
322 405
323## Without a GPU: Mesa llvmpipe 406## Without a GPU: Mesa llvmpipe
324 407
@@ -327,32 +410,55 @@ for every pull request that touches the runtime, the scripts or a tool the jobs
327lists them), and you can do the same on Linux without a GPU: 410lists them), and you can do the same on Linux without a GPU:
328 411
329```sh 412```sh
330sudo apt-get install -y libvulkan-dev mesa-vulkan-drivers vulkan-tools spirv-tools llvm-18 413sudo apt-get install -y libvulkan-dev mesa-vulkan-drivers vulkan-tools spirv-tools llvm-19
331cmake -S runtime -B runtime/build/linux && cmake --build runtime/build/linux --parallel 414cmake -S runtime -B runtime/build/linux && cmake --build runtime/build/linux --parallel
332python -I scripts/run_gpu_tests.py --build runtime/build/linux --llvm-mc /usr/lib/llvm-18/bin/llvm-mc 415python -I scripts/run_gpu_tests.py --build runtime/build/linux --llvm-mc /usr/lib/llvm-19/bin/llvm-mc
333LEONIDA_W64_EMULATE=1 python -I scripts/run_gpu_tests.py --build runtime/build/linux \ 416LEONIDA_W64_EMULATE=1 python -I scripts/run_gpu_tests.py --build runtime/build/linux \
334 --llvm-mc /usr/lib/llvm-18/bin/llvm-mc --filter cs_ 417 --llvm-mc /usr/lib/llvm-19/bin/llvm-mc --filter cs_
335LEONIDA_BARY_FALLBACK=1 python -I scripts/run_gpu_tests.py --build runtime/build/linux \ 418LEONIDA_BARY_FALLBACK=1 python -I scripts/run_gpu_tests.py --build runtime/build/linux \
336 --llvm-mc /usr/lib/llvm-18/bin/llvm-mc 419 --llvm-mc /usr/lib/llvm-19/bin/llvm-mc
337``` 420```
338 421
339With Mesa 25.2 (llvmpipe, LLVM 20) the first run passes 52 of 88 and skips 36, the second passes 37 of 39 and 422With Mesa 25.2 (llvmpipe, LLVM 20) the first run passes 52 of 88 and skips 36, the second passes 37 of 39 and
340skips 2. The skips are expected: llvmpipe has 8-wide subgroups (so every wave64 test skips without emulation, and 423skips 2. The skips are expected: llvmpipe has 8-wide subgroups (so every wave64 test skips without emulation, and
341the 32-lane tests `ps_bitmask_perm`, `cs_wqm_w32` and `cs_w32_lane_wrap` skip in both runs), no 424the 32-lane tests `ps_bitmask_perm`, `cs_wqm_w32` and `cs_w32_lane_wrap` skip in both runs), no
342`VK_KHR_fragment_shader_barycentric` (`ps_bary`, `ps_uniform_branch`, `ps_scc_mask32`) and no 425`VK_KHR_fragment_shader_barycentric` (`ps_bary`, `ps_persp_bary`, `ps_uniform_branch`, `ps_scc_mask32`) and no
343`VK_KHR_maintenance8` (`ps_texoff`). The third run draws those three barycentric tests through the fallback below 426`VK_KHR_maintenance8` (`ps_texoff`). The third run draws those four barycentric tests through the fallback below
344(with Mesa 26.0.8 it passes 123 of 189, the first run 120), and CI fails it unless every shader that got a fallback 427(with Mesa 26.0.8 it passes 123 of 189, the first run 120), and CI fails it unless every shader that got a fallback
345geometry shader passes. With 428geometry shader passes. With
346`LEONIDA_W64_EMULATE=1` the mesh tests abort inside llvmpipe's compiler ("LLVM ERROR: Cannot emit physreg copy 429`LEONIDA_W64_EMULATE=1` the mesh tests fail on llvmpipe, which is why the second run is limited to compute. This is
347instruction"), which is why the second run is limited to compute. llvmpipe is not a substitute for a result from a 430an llvmpipe bug, not the translator's (TEST-782, #3127): llvmpipe stores a mesh shader's per-primitive
431`CullPrimitiveEXT` by bitcasting the boolean (`<N x i1>`) to a float vector, an invalid LLVM cast
432(`emit_store_mesh_chan` in `lp_bld_nir_soa.c`, Mesa 26.3.1 and `main`). A constant cull flag is folded away before
433that, so the native mesh tests pass; the emulated ones carry it through memory, so it reaches the cast. What the
434cast becomes depends on the backend: on x86_64 at 256 bits, LLVM aborts ("LLVM ERROR: Cannot emit physreg copy
435instruction"); at 128 bits (`LP_NATIVE_VECTOR_WIDTH=128`) some draw correctly and some draw nothing (with Mesa
43626.0.3, `ms_tri`, `ms_w64x_ballot`, `ms_clip` and `ms_f16_pack` pass, while `ms_wave_info_s3` and `ms_v5_workgroup`
437stay at the clear color); on arm64 (128 bits) `ms_tri`'s primitive comes out culled, so nothing is drawn. Storing a
438constant `false` there instead makes the emulated `ms_tri` draw a frame byte-identical to RADV's (Mesa 26.3.1), and
439`ms_tri`, `ms_wave_info_s3`, `ms_w64x_ballot` and `ms_v5_workgroup` byte-identical to NVIDIA's at both widths (Mesa
44026.0.3, [measured by @TreXito](https://github.com/ItsNotRexed/Leonida/pull/3838#issuecomment-7086696759), with a 42-line reduced
441reproducer). llvmpipe is not a substitute for a result from a
348real GPU in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): it catches regressions, not hardware 442real GPU in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): it catches regressions, not hardware
349differences. 443differences.
350 444
445## Macs in CI
446
447The `macos` job in `.github/workflows/runtime.yml` builds the runtime on GitHub's `macos-26` arm64 runner and runs
448`ctest` and `run_gpu_tests.py` on MoltenVK; `macos-python` in `ci.yml` runs the Python suites. The runner is a VM
449whose Metal device is "Apple Paravirtual device" (Metal family Mac2, not Apple7): MoltenVK runs on it with 32-wide
450subgroups, so the wave64 and "32 lanes on request" tests skip there (about 75 of 190 in November 2026), and Mesa's
451KosmicKrisp finds no device. `macos-15` can't build the runtime: Xcode 16's libc++ has no floating-point
452`std::from_chars`. A test known to fail on MoltenVK is listed in the step's `EXPECTED_FAILURES` with the pull
453request or coordination-issue finding that tracks it; it still runs, and `scripts/ci_expected_failures.py` fails the step
454on any other failure. It takes `FAILED_LIST EXIT_STATUS [EXPECTED ...]`, answers `--help`, and reports a list it cannot
455read or a non-numeric status as one line with exit code 2.
456
351## GPUs without fragment barycentrics (NVIDIA Volta, Pascal and older) 457## GPUs without fragment barycentrics (NVIDIA Volta, Pascal and older)
352 458
353`ps_bary`, `ps_uniform_branch` and `ps_scc_mask32` read raw barycentrics, which need 459`ps_bary`, `ps_persp_bary`, `ps_uniform_branch` and `ps_scc_mask32` read raw barycentrics, which need
354`VK_KHR_fragment_shader_barycentric`. NVIDIA has it from Turing on; Volta (V100, Titan V) and older lack it, as do 460`VK_KHR_fragment_shader_barycentric`. NVIDIA has it from Turing on; Volta (V100, Titan V) and older lack it, as do
355llvmpipe and some other drivers. Where the device lacks it those three are skipped; that's expected, not a failure. 461llvmpipe and some other drivers. Where the device lacks it those four are skipped; that's expected, not a failure.
356To test the fallback that runs them anyway, set `LEONIDA_BARY_FALLBACK=1`, **for both `build.py` and `check.py`** 462To test the fallback that runs them anyway, set `LEONIDA_BARY_FALLBACK=1`, **for both `build.py` and `check.py`**
357(or for `run_gpu_tests.py`; CI does this on llvmpipe). The shaders are then translated with `--bary-fallback` and 463(or for `run_gpu_tests.py`; CI does this on llvmpipe). The shaders are then translated with `--bary-fallback` and
358drawn through a pass-through geometry shader that supplies the barycentrics (`docs/design.md`, "Barycentric 464drawn through a pass-through geometry shader that supplies the barycentrics (`docs/design.md`, "Barycentric
@@ -363,6 +469,20 @@ too and which `--bary-fallback` can't express. With `LEONIDA_F16_INTERP_FALLBACK
363exports decoded instead (see Macs, below) and run with or without the bary fallback; `run_gpu_tests.py` turns that 469exports decoded instead (see Macs, below) and run with or without the bary fallback; `run_gpu_tests.py` turns that
364on by itself where the device lacks the extension. Under the bary fallback without it they skip. 470on by itself where the device lacks the extension. Under the bary fallback without it they skip.
365 471
472Intel Arc with Mesa ANV currently advertises the native barycentric feature but has a driver bug where translated
473pixel shaders can read `BaryCoordKHR.i` as zero (SHADER-925). `make_game.py` detects ANV and automatically translates
474with `--bary-fallback`; both entry points accept `LEONIDA_BARY_FALLBACK=1` to force it and
475`LEONIDA_BARY_FALLBACK=0` to force native barycentrics. The CLI `--bary-fallback` flag also remains available for
476game builds and other manually built fixtures.
477
478AMD's Windows driver on gfx90c iGPUs (Renoir, Lucienne, Cezanne, Barcelo: Ryzen 4000/5000 mobile and 5000G, GCN 5)
479also advertises the feature but returns a wrong third `BaryCoordKHR` component, about 0.99 where a small value is
480expected (#5933: Vega 8, PCI 1002:15E7, driver 31.0.21921.13001). `ps_bary`, `ps_persp_bary` and `ps_ij_computed`
481fail natively; through the fallback `ps_bary` and `ps_persp_bary` pass. `tools/vk_subgroup_info.py` reports
482`barycentric_fallback` for these PCI IDs under `VK_DRIVER_ID_AMD_PROPRIETARY`, so `make_game.py` and
483`run_gpu_tests.py` turn the fallback on by themselves there, with the same `LEONIDA_BARY_FALLBACK` override. RADV and
484other GCN 5 GPUs are not covered: none has been measured.
485
366## Macs: 16-bit interpolation without PerVertexKHR 486## Macs: 16-bit interpolation without PerVertexKHR
367 487
368`ps_interp_f16_high` (and `ms_f16_pack`) normally read 16-bit interpolants through `PerVertexKHR` inputs, which 488`ps_interp_f16_high` (and `ms_f16_pack`) normally read 16-bit interpolants through `PerVertexKHR` inputs, which
@@ -413,6 +533,11 @@ specification allows a driver to split GLSL `Fma` into two roundings, which is w
413`LEONIDA_FMA=exact` (`--fma exact`) builds the single rounding from plain f32 operations and needs no extension; with 533`LEONIDA_FMA=exact` (`--fma exact`) builds the single rounding from plain f32 operations and needs no extension; with
414it `cs_fma_fused` passes on both of those, on an RTX 3050 Laptop (617.42), an RTX 5060 Laptop (621.01), an RTX 5070 Ti 534it `cs_fma_fused` passes on both of those, on an RTX 3050 Laptop (617.42), an RTX 5060 Laptop (621.01), an RTX 5070 Ti
415(621.24) and a Radeon 780M (26.11.2). 535(621.24) and a Radeon 780M (26.11.2).
536Intel UHD Graphics (Xe-LP, Windows 101.7088) splits it too, words 0, 2, 3 and 5 (`v_fma_f32`, `v_fmaak_f32`,
537`v_fmac_f32`), and has no `VK_KHR_shader_fma`, so `khr` can't be used there. For such a device,
538`LEONIDA_FMA=exact` (`--fma exact`) builds the single rounding from plain f32 operations and needs no extension;
539under it, as under `khr`, all 8 words must be strictly fused, and they are on that Intel UHD and on an RTX 3050
540Laptop (617.42).
416 541
417## Hardware oracle (optional, AMD) 542## Hardware oracle (optional, AMD)
418 543
@@ -438,23 +563,39 @@ over integrated, the first on a tie, `vulkan_device_rank` in `runtime/src/vulkan
438`LEONIDA_VK_DEVICE=radeon`. The D3D12 tests (`vk_test_device.h`) and the layer's standalone device read it, 563`LEONIDA_VK_DEVICE=radeon`. The D3D12 tests (`vk_test_device.h`) and the layer's standalone device read it,
439and a value that matches no device fails the run instead of testing 564and a value that matches no device fails the run instead of testing
440another GPU. For the host side of the comparison tests, `LEONIDA_HOST_ADAPTER` picks the D3D12 adapter the same way. 565another GPU. For the host side of the comparison tests, `LEONIDA_HOST_ADAPTER` picks the D3D12 adapter the same way.
566Unset, the host side is the adapter behind the layer's Vulkan device (`runtime/test/host_adapter.h`; `d3d12_buffer_tiles`
567by the layer's `GetAdapterLuid()`), so on a PC with two GPUs the layer is compared with its own GPU's driver.
441The GPU tools of `runtime/test/shaders` (`vk_compute_test`, `vk_harness`, ...) read it the same way through 568The GPU tools of `runtime/test/shaders` (`vk_compute_test`, `vk_harness`, ...) read it the same way through
442`vk_device_pick.h`, and fail with a message naming the filter when it matches no device. 569`vk_device_pick.h`, and fail with a message naming the filter when it matches no device.
443 570
571Two test settings make the layer's standalone device look like a GPU with fewer Vulkan queues, so D3D12 queues share
572them (`docs/d3d12_vulkan.md` section 4.4) on any GPU: `LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N` (1 to 16) creates at most
573N Vulkan queues per queue family, and `LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1` puts COMPUTE and COPY queues in the
574graphics family, as on a GPU without async compute or transfer families. Both together give the shape of the Intel
575UHD 770 on Windows and of lavapipe, one family with one queue; the `d3d12_queue_share_one_queue` and
576`d3d12_queue_wait_one_queue` tests run that way, and any other test can be run so by hand. The device logs what it
577applied; a queue count outside 1 to 16 is ignored, with a message. Only tests apply them: the device that
578`gta6rt --run` creates for a game (`LEONIDA_D3D12=vulkan`) ignores both and prints `... is a test setting; the
579game's device ignores it`, so leaving them set cannot slow a game down (`run_tiny_frame_queue_test_settings`).
580
444## Known problems 581## Known problems
445 582
446| What you see | Cause | What to do | 583| What you see | Cause | What to do |
447|---|---|---| 584|---|---|---|
585| Under Wine 9.0 (Ubuntu 24.04's `wine`), a test or the runtime waits out every `std::condition_variable` timeout: `wait_registration_admission` ("native drainage complete"), `vk_presenter_sync` (`unblocked_during_present`), `frame_pacer`, `vk_fence_dispatcher_sync`, `context_concurrent_detach` | The STL's timed wait (`_Cnd_timedwait_for_unchecked`) is linked statically from `msvcprt.lib` and reads Windows' `_Mtx_t` layout, while `_Mtx_lock`/`_Mtx_unlock` come from Wine's builtin msvcp140, which used another layout until wine-10.1 (757bd7909fda); the wait never released the mutex (#3796) | Fixed in the build: `runtime/src/crt_timed_wait.cpp` routes the wait through msvcp140's own `_Cnd_timedwait` in every `/MD` binary, and `crt_timed_wait_test` checks it. A binary built before that fix still needs Wine 10.1 or newer (or Proton) |
448| `ctest` passes but runs far fewer tests than expected (about 45 instead of 125 on Windows), no `d3d12_*` GPU tests, and `LEONIDA_D3D12=vulkan` does nothing | CMake found no Vulkan headers: `VULKAN_SDK` was not set in the environment that ran CMake (for example a user variable set after the terminal opened), and `CMakeCache.txt` keeps that failed lookup. The configure prints a `CMake Warning` "Vulkan headers not found" | Set `VULKAN_SDK` in that environment (or pass `-DLEONIDA_VULKAN_HEADERS_FETCH=ON`), delete `CMakeCache.txt` and configure again. `-DLEONIDA_REQUIRE_VULKAN=ON` makes this a configure error; CI and `scripts/build_runtime.ps1` (with `VULKAN_SDK` set) pass it | 586| `ctest` passes but runs far fewer tests than expected (about 45 instead of 125 on Windows), no `d3d12_*` GPU tests, and `LEONIDA_D3D12=vulkan` does nothing | CMake found no Vulkan headers: `VULKAN_SDK` was not set in the environment that ran CMake (for example a user variable set after the terminal opened), and `CMakeCache.txt` keeps that failed lookup. The configure prints a `CMake Warning` "Vulkan headers not found" | Set `VULKAN_SDK` in that environment (or pass `-DLEONIDA_VULKAN_HEADERS_FETCH=ON`), delete `CMakeCache.txt` and configure again. `-DLEONIDA_REQUIRE_VULKAN=ON` makes this a configure error; CI and `scripts/build_runtime.ps1` (with `VULKAN_SDK` set) pass it |
449| Windows refuses to start freshly built test programs ("An Application Control policy has blocked this file"), and the runner stops with a traceback | Smart App Control on Windows 11 | Turn Smart App Control off for the run | 587| Windows refuses to start freshly built test programs ("An Application Control policy has blocked this file"), and the runner stops with a traceback | Smart App Control on Windows 11 | Turn Smart App Control off for the run |
588| `tools/hw_oracle` works once, then stops with "hardware oracle unavailable: Windows Defender blocked the launcher ... (WinError 225)" (older runs: an `OSError: [WinError 225] ... contains a virus or potentially unwanted software` traceback) | Defender's machine-learning check flags the small unsigned `leonida_hw_oracle_<hash>.exe` that the runner builds in `%TEMP%` (seen as `Trojan:Win32/Bearfoos.A!ml`) and quarantines it; every later run rebuilds and loses it again | Add an exclusion for the build folder (`%TEMP%`) in Windows Security, Virus & threat protection, Manage settings, Exclusions, restore the file from Protection history if you want it back, and rerun. The program is built from `tools/hw_oracle/hw_oracle.c` and is a false positive |
450| Validation errors without a VUID, or messages from a layer you didn't ask for | An implicit Vulkan layer from other software (Rockstar Social Club, ReShade, MangoHud, an overlay) | Set `VK_LOADER_LAYERS_DISABLE=~implicit~`. Overlays that hook the swapchain (RivaTuner `VK_LAYER_RTSS`, OBS `VK_LAYER_OBS_HOOK`) can stay loaded: see the next row | 589| Validation errors without a VUID, or messages from a layer you didn't ask for | An implicit Vulkan layer from other software (Rockstar Social Club, ReShade, MangoHud, an overlay) | Set `VK_LOADER_LAYERS_DISABLE=~implicit~`. Overlays that hook the swapchain (RivaTuner `VK_LAYER_RTSS`, OBS `VK_LAYER_OBS_HOOK`) can stay loaded: see the next row |
451| Validation errors that only your machine shows (e.g. `xbox_present`'s sRGB swapchain `STORAGE` message), with MSI Afterburner/RivaTuner or OBS installed | An overlay layer that hooks the swapchain: while RivaTuner Statistics Server is running, its `VK_LAYER_RTSS` adds `STORAGE` usage to it (OBS's `VK_LAYER_OBS_HOOK` injects `VK_IMAGE_USAGE_STORAGE_BIT` too). In an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE` (`VK_LOADER_DEBUG=all` says so), so `~implicit~` leaves the layer in | Run the tests from a normal terminal, close the overlay application, or set the layer's own switch, which works elevated too: `DISABLE_RTSS_LAYER=1`, `DISABLE_VULKAN_OBS_CAPTURE=1` (OBS). Any other layer's switch is the `disable_environment` entry in its manifest (the JSON listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers` or `HKCU\...`). `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted | 590| Validation errors that only your machine shows (e.g. `xbox_present`'s sRGB swapchain `STORAGE` message), with MSI Afterburner/RivaTuner or OBS installed | An overlay layer that hooks the swapchain: while RivaTuner Statistics Server is running, its `VK_LAYER_RTSS` adds `STORAGE` usage to it (OBS's `VK_LAYER_OBS_HOOK` injects `VK_IMAGE_USAGE_STORAGE_BIT` too). In an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE` (`VK_LOADER_DEBUG=all` says so), so `~implicit~` leaves the layer in | Run the tests from a normal terminal, close the overlay application, or set the layer's own switch, which works elevated too: `DISABLE_RTSS_LAYER=1`, `DISABLE_VULKAN_OBS_CAPTURE=1` (OBS). Any other layer's switch is the `disable_environment` entry in its manifest (the JSON listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers` or `HKCU\...`). `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted |
591| GPU tests crash with an access violation (`0xC0000005`, exit `-1073741819`) right after device creation, with no layer message and validation off (e.g. `d3d12_method_variants` 9 of 10 runs, `xbox_present` 10 of 10, on `main` 561b65a83, RTX 4070 Ti, NVIDIA 616.56) | An implicit layer from an overlay or game tool you did not install for these tests. FPS Monitor's `fpsmonvk64.json` (listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers`) names itself `VK_LAYER_RENDERDOC_Capture`, so `DISABLE_VULKAN_OBS_CAPTURE=1` does not disable it | `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted. That manifest's `disable_environment` is `DISABLE_LAYER=1`; `DISABLE_LAYER=1` or `VK_LOADER_LAYERS_DISABLE=~implicit~` gave 20 of 20 clean runs (a layer's own switch is its `disable_environment` entry, as the row above says) |
452| `vk_sync_validation` fails with `LEONIDA_VK_VALIDATION=1` ("the write-after-write hazard was not reported") | Synchronization validation is off although the tests ask for it: an older layer, or a layer setting such as `VK_KHRONOS_VALIDATION_VALIDATE_SYNC=false` or a `vk_layer_settings.txt` that overrides it. Every other GPU test then reports "0 validation errors" without having been checked | Remove the override or update the Vulkan SDK, then rerun `ctest -R vk_sync_validation` until it passes | 592| `vk_sync_validation` fails with `LEONIDA_VK_VALIDATION=1` ("the write-after-write hazard was not reported") | Synchronization validation is off although the tests ask for it: an older layer, or a layer setting such as `VK_KHRONOS_VALIDATION_VALIDATE_SYNC=false` or a `vk_layer_settings.txt` that overrides it. Every other GPU test then reports "0 validation errors" without having been checked | Remove the override or update the Vulkan SDK, then rerun `ctest -R vk_sync_validation` until it passes |
453| On RADV with Mesa 25.2 (Ubuntu 24.04's default; 25.2.8 measured) or 25.3 (from the source, not run), `cs_w32_salu64` fails with word 2 = `0` (want `0xFFFFFFFF`) and `cs_signed_zero_nan` fails with word 5 = `0` (want `1`) | Two Mesa bugs, not translator bugs (#166). `cs_w32_salu64`: ACO's `combine_add_sub_b2i` reads a temporary without counting the use, so dead-code elimination removes it (`ACO ERROR: ... never defined` with `MESA_SHADER_CACHE_DISABLE=true`); `RADV_DEBUG=llvm` passes. `cs_signed_zero_nan`: NIR's range analysis (`fmul_is_a_number`) calls `0 * x` a number when `x` may be infinite, so the `x != x` check folds to false despite `SignedZeroInfNanPreserve`. The same NIR code is behind llvmpipe's word 5 (#664) | Expected with these Mesa versions. From the source, the ACO function is gone from Mesa 26.0 and the NIR code was replaced in 26.1 (neither run); RADV from Mesa 26.3.1 passes both on an 8060S (gfx1151) | 593| On RADV with Mesa 25.2 (Ubuntu 24.04's default; 25.2.8 measured) or 25.3 (from the source, not run), `cs_w32_salu64` fails with word 2 = `0` (want `0xFFFFFFFF`) and `cs_signed_zero_nan` fails with word 5 = `0` (want `1`). The `cs_signed_zero_nan` failure alone is also measured on RADV 25.0.7 (RX 7800 XT, Debian 13; @mrbean56, #4421) and on ANV 25.2.8 (Intel UHD 630; @theswiss24, #4571); llvmpipe on Mesa 26.0.8 (Ubuntu 26.04) still gives word 5 = `0`, which `check.py` does not judge there (`UNJUDGED_WORDS`) | Two Mesa bugs, not translator bugs (#166). `cs_w32_salu64`: ACO's `combine_add_sub_b2i` reads a temporary without counting the use, so dead-code elimination removes it (`ACO ERROR: ... never defined` with `MESA_SHADER_CACHE_DISABLE=true`); `RADV_DEBUG=llvm` passes. `cs_signed_zero_nan`: NIR's range analysis (`fmul_is_a_number`) calls `0 * x` a number when `x` may be infinite, so the `x != x` check folds to false despite `SignedZeroInfNanPreserve`. The same NIR code is behind llvmpipe's word 5 (#664) and ANV's, since both drivers run NIR; `cs_w32_salu64` is ACO's, so only RADV has it | Expected with these Mesa versions. From the source, the ACO function is gone from Mesa 26.0 and the NIR code was replaced in 26.1 (neither run); RADV from Mesa 26.3.1 passes both on an 8060S (gfx1151) |
454| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer | 594| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer |
455| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` | 595| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` |
456| `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old | 596| `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old |
457| `ps_bary` and `ps_uniform_branch` fail by about 0.9 | The GPU runs pixel shaders wave64 without fragment barycentrics (GCN3 and RDNA1 on RADV), or an old AMD Windows driver (22.40) | Current `main` skips them on such devices; on Windows, update the driver | 597| `ps_bary` and `ps_uniform_branch` fail by about 0.9 | The GPU runs pixel shaders wave64 without fragment barycentrics (GCN3 and RDNA1 on RADV), or an old AMD Windows driver (22.40) | Current `main` skips them on such devices; on Windows, update the driver |
598| `ps_bary`, `ps_persp_bary` and `ps_ij_computed` read the third barycentric as about 0.99 on a gfx90c iGPU (Vega 8, AMD Windows driver 31.0.21921.13001; #5933) | The driver's native `BaryCoordKHR` is wrong there: the same tests pass through `--bary-fallback`, and natively on RADV (Radeon 8060S) | `tools/vk_subgroup_info.py` turns the fallback on by itself for gfx90c under AMD's driver, and `make_game.py`, `run_gpu_tests.py`, `build.py` and `check.py` follow it when `LEONIDA_BARY_FALLBACK` is unset; `=1` forces the fallback and `=0` forces native barycentrics, where they still fail |
458| `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation | 599| `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation |
459| `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). | 600| `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). |
460| `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") | 601| `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") |
@@ -464,7 +605,10 @@ The GPU tools of `runtime/test/shaders` (`vk_compute_test`, `vk_harness`, ...) r
464| `cs_dpp_ops` fails on a Mac with MoltenVK 1.4.2: `out[0..7] = 100 100 11 ...`, want `100 10 11 ...` | MoltenVK 1.4.2's SPIRV-Cross moves the DPP lowering's subgroup ballot and shuffle into a short-circuiting `&&` and `?:`, so only some lanes run them and lane 1 sees its source lane 0 as inactive. SPIRV-Cross `5c372ffb` (in MoltenVK `main`) keeps them out of `?:`; a ballot on the right of `&&` is still moved there in SPIRV-Cross `57e4efcc` | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` (point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib`) and on KosmicKrisp | 605| `cs_dpp_ops` fails on a Mac with MoltenVK 1.4.2: `out[0..7] = 100 100 11 ...`, want `100 10 11 ...` | MoltenVK 1.4.2's SPIRV-Cross moves the DPP lowering's subgroup ballot and shuffle into a short-circuiting `&&` and `?:`, so only some lanes run them and lane 1 sees its source lane 0 as inactive. SPIRV-Cross `5c372ffb` (in MoltenVK `main`) keeps them out of `?:`; a ballot on the right of `&&` is still moved there in SPIRV-Cross `57e4efcc` | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` (point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib`) and on KosmicKrisp |
465| `check.py`'s `cs_fma_fused` fails on a Mac with MoltenVK 1.4.2: word 7 reads `15360` (`0x3c00`), want `29521` (`0x7351`) | The f16 multiply-add (round to odd). The MSL of 1.4.2 and of MoltenVK `main` differ only in SPIRV-Cross's precise-arithmetic helpers (`[[clang::optnone]]` and `fma(l, r, 0)` against `math_mode(safe)` and `fma(l, r, -0.0)`, the SHADER-182 / SHADER-234 change) | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` | 606| `check.py`'s `cs_fma_fused` fails on a Mac with MoltenVK 1.4.2: word 7 reads `15360` (`0x3c00`), want `29521` (`0x7351`) | The f16 multiply-add (round to odd). The MSL of 1.4.2 and of MoltenVK `main` differ only in SPIRV-Cross's precise-arithmetic helpers (`[[clang::optnone]]` and `fma(l, r, 0)` against `math_mode(safe)` and `fma(l, r, -0.0)`, the SHADER-182 / SHADER-234 change) | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` |
466| `gs_tri` and `ms_tri` fail on a Mac | MoltenVK has no geometry stage and no `VK_EXT_mesh_shader` | Current `main` reports them as skipped | 607| `gs_tri` and `ms_tri` fail on a Mac | MoltenVK has no geometry stage and no `VK_EXT_mesh_shader` | Current `main` reports them as skipped |
608| With `LEONIDA_W64_EMULATE=1` on llvmpipe, the `ms_*` tests fail. Measured with Mesa 26.3.1: on x86_64 at 256-bit vectors (the default there) all six abort with "LLVM ERROR: Cannot emit physreg copy instruction"; on arm64 (128-bit) `ms_tri` draws nothing (the frame stays at the clear color); on x86_64 at 128 bits (`LP_NATIVE_VECTOR_WIDTH=128`) `ms_tri` happened to draw correctly, but with Mesa 26.0.3 `ms_wave_info_s3` and `ms_v5_workgroup` draw nothing there (4 of 6 pass, [measured by @TreXito](https://github.com/ItsNotRexed/Leonida/pull/3838#issuecomment-7086696759)) ([measured runs](https://github.com/ItsNotRexed/Leonida/issues/3127#issuecomment-7086469679)) | An llvmpipe bug: a mesh shader's runtime `CullPrimitiveEXT` is stored through an invalid `bitcast <N x i1> to <N x float>` (TEST-782, #3127; see "Without a GPU: Mesa llvmpipe") | Run the mesh tests on llvmpipe without `LEONIDA_W64_EMULATE`, or add `LEONIDA_MESH_COMPUTE=1` (the compute fallback): with it all 6 `ms_*` pass emulated on llvmpipe (x86_64, 256-bit) |
467| On a Mac, `valu_fuzz.py --family f16` reads `+0` where the model wants `-0`, from a multiply whose exact product is -0 (`v_mul_f16`, `v_pk_mul_f16`) or from an FMA whose product and addend are both -0 (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) | MoltenVK computes a `NoContraction` multiply as `fma(l, r, +0)`, which drops the sign. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-182, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions. To run the rest of the fuzzer clean, add `--skip-op` for each of the five ops. To see them match, install Homebrew's `mesa` and use its KosmicKrisp driver: `LEONIDA_VULKAN_LOADER=/opt/homebrew/opt/vulkan-loader/lib/libvulkan.1.dylib VK_DRIVER_FILES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json python3 -I tools/valu_fuzz.py --family f16 --build runtime/build/linux`. Or build MoltenVK with SPIRV-Cross `300681bb` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision`, and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | 609| On a Mac, `valu_fuzz.py --family f16` reads `+0` where the model wants `-0`, from a multiply whose exact product is -0 (`v_mul_f16`, `v_pk_mul_f16`) or from an FMA whose product and addend are both -0 (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) | MoltenVK computes a `NoContraction` multiply as `fma(l, r, +0)`, which drops the sign. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-182, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions. To run the rest of the fuzzer clean, add `--skip-op` for each of the five ops. To see them match, install Homebrew's `mesa` and use its KosmicKrisp driver: `LEONIDA_VULKAN_LOADER=/opt/homebrew/opt/vulkan-loader/lib/libvulkan.1.dylib VK_DRIVER_FILES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json python3 -I tools/valu_fuzz.py --family f16 --build runtime/build/linux`. Or build MoltenVK with SPIRV-Cross `300681bb` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision`, and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` |
610| A pixel shader exporting non-canonical f32 NaNs reads back `0x7fc00000` from an RGBA32F color attachment | KosmicKrisp (Mesa 26.3.1), reproduced on Apple M3 Max, M2 Ultra and M1 Pro ([#3125](https://github.com/ItsNotRexed/Leonida/issues/3125)): `nir_to_msl` emits `(NAN)` for `float`-typed NaN constants (`MESA_KK_DEBUG=msl`); MoltenVK 1.4.2 preserved both tested payloads on the same hardware | `ps_nan_payload` allows the measured canonical word only for the NaN channels and only when `vk_harness` reports `driver: KosmicKrisp`. Finite channels and other drivers still require exact words. Integer or storage-buffer readback still canonicalizes constants that NIR infers as `float` (see the `cs_bvh` row below). |
611| `cs_bvh` and `cs_bvh32` fail on a Mac with KosmicKrisp: `out[3]` reads `0x7fc00000`, want `0xffffffff` | KosmicKrisp's `nir_to_msl` compiler (Mesa 26.3.1, measured on Apple M2 Ultra, macOS 27.3), not the translator or the buffer format. The triangle branch writes bitcast `float` words and the box branch writes `OpSelect %uint` with `0xffffffff` (`-1`) into the same VGPRs; NIR erases `OpBitcast`, type inference marks the shared register and `bcsel` as `float`, and `nir_to_msl` prints any `float`-typed 32-bit constant in the IEEE-754 NaN range (`0x7f800001..0x7fffffff`, `0xff800001..0xffffffff`) as `(NAN)` (`0x7fc00000`) | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) return `0xffffffff` on the same machine. Do not weaken `vk_compute_test`'s expected BVH words |
468| CMake stops with "needs the Windows SDK 10.0.26100 or newer", or MSVC reports `'Desc_1_2': is not a member of 'D3D12_VERSIONED_ROOT_SIGNATURE_DESC'` | A Windows SDK older than 10.0.26100 (10.0.22621 is the common one), which has no version 1.2 root signatures | `winget install Microsoft.WindowsSDK.10.0.26100`, or add it in the Visual Studio Installer, then delete `runtime/build` and configure again | 612| CMake stops with "needs the Windows SDK 10.0.26100 or newer", or MSVC reports `'Desc_1_2': is not a member of 'D3D12_VERSIONED_ROOT_SIGNATURE_DESC'` | A Windows SDK older than 10.0.26100 (10.0.22621 is the common one), which has no version 1.2 root signatures | `winget install Microsoft.WindowsSDK.10.0.26100`, or add it in the Visual Studio Installer, then delete `runtime/build` and configure again |
469| `ctest` lists `fsr_dispatch` and `bvh_builder` as failed (`Not Run`) after clang-cl hits an internal compiler error in `fsr_dispatch_test.cpp` and `bvh_builder_test.cpp` | clang-cl 22.1.8 on Fedora (Linux cross-build) and Windows, plus 22.1.7 on Windows | Use clang-cl 23.1.6 (both files compile on Windows) | 613| `ctest` lists `fsr_dispatch` and `bvh_builder` as failed (`Not Run`) after clang-cl hits an internal compiler error in `fsr_dispatch_test.cpp` and `bvh_builder_test.cpp` | clang-cl 22.1.8 on Fedora (Linux cross-build) and Windows, plus 22.1.7 on Windows | Use clang-cl 23.1.6 (both files compile on Windows) |
470| `d3d12_compute`, `d3d12_draw` or another test that writes a shader library under the temp directory fails now and then (a PSO creation `line N: SUCCEEDED(...)`, or exit 3 with no message) but passes when run alone | Two copies running at once (`ctest -j`, or two suites sharing one Wine prefix or `TMPDIR`) used the same `leonida_<test>` folder under the temp directory, and one copy deleted the shader modules the other was loading: 6 of 40 runs failed with four copies of `d3d12_compute` at once on a Mac under Wine | Current `main` gives each process its own folder (`<temp>/leonida_<test>_<pid>`) | 614| `d3d12_compute`, `d3d12_draw` or another test that writes a shader library under the temp directory fails now and then (a PSO creation `line N: SUCCEEDED(...)`, or exit 3 with no message) but passes when run alone | Two copies running at once (`ctest -j`, or two suites sharing one Wine prefix or `TMPDIR`) used the same `leonida_<test>` folder under the temp directory, and one copy deleted the shader modules the other was loading: 6 of 40 runs failed with four copies of `d3d12_compute` at once on a Mac under Wine | Current `main` gives each process its own folder (`<temp>/leonida_<test>_<pid>`) |
@@ -475,6 +619,63 @@ The GPU tools of `runtime/test/shaders` (`vk_compute_test`, `vk_harness`, ...) r
475| `vulkaninfo` lists `Microsoft Direct3D12 (<gpu>)` next to the real GPU and the tests run on it | The Windows "OpenCL™, OpenGL® and Vulkan® Compatibility Pack" installs Mesa's Dozen, a Vulkan-on-D3D12 layer that reports `DISCRETE_GPU` like the native card | Current `main` prefers a native ICD over Microsoft's vendor (`0x1414`) in the runtime and every harness; set `LEONIDA_VK_DEVICE=<part of the real GPU name>` to select explicitly. See #915. | 619| `vulkaninfo` lists `Microsoft Direct3D12 (<gpu>)` next to the real GPU and the tests run on it | The Windows "OpenCL™, OpenGL® and Vulkan® Compatibility Pack" installs Mesa's Dozen, a Vulkan-on-D3D12 layer that reports `DISCRETE_GPU` like the native card | Current `main` prefers a native ICD over Microsoft's vendor (`0x1414`) in the runtime and every harness; set `LEONIDA_VK_DEVICE=<part of the real GPU name>` to select explicitly. See #915. |
476| A GPU test that uses `image_load` (or lighting built from real shaders) reads zeros from its image; @Silliana saw every texel except pixel (0,0) come back zero in their own layer (#603, not reproduced here) | In this runtime the shader turns the T# words into an index through the descriptor hash table (`runtime/src/descriptor_table.h`: a miss gives index 0), and index 0 is a 1×1 image of zeros (`runtime/src/vulkan_bindless.h`), so a hand-built or zeroed T# that was never registered reads zeros even at (0,0). The translator does not compare coordinates with the T# size, and `cs_imgload.asm` only uses its T# words as a hash key | Register the descriptor through the runtime (for D3D12, create it with `CreateShaderResourceView`) so its T# hits the table, with the image's real width and height (stored as size − 1, see `runtime/src/gfx10_descriptors.h`) | 620| A GPU test that uses `image_load` (or lighting built from real shaders) reads zeros from its image; @Silliana saw every texel except pixel (0,0) come back zero in their own layer (#603, not reproduced here) | In this runtime the shader turns the T# words into an index through the descriptor hash table (`runtime/src/descriptor_table.h`: a miss gives index 0), and index 0 is a 1×1 image of zeros (`runtime/src/vulkan_bindless.h`), so a hand-built or zeroed T# that was never registered reads zeros even at (0,0). The translator does not compare coordinates with the T# size, and `cs_imgload.asm` only uses its T# words as a hash key | Register the descriptor through the runtime (for D3D12, create it with `CreateShaderResourceView`) so its T# hits the table, with the image's real width and height (stored as size − 1, see `runtime/src/gfx10_descriptors.h`) |
477| `cs_sample_lz_int_d16`, `ps_sample_implicit_sint`, `ps_ssharp`, `ps_tex`, `ps_texture_mip0`, `ps_texture_sample` and `ps_texture_sample_d16` crash (exit -11 or 139) on an Intel GPU on Linux, while NVIDIA and llvmpipe pass them (TEST-399) | A bug in Mesa ANV's shader compiler: compiling these texture-sampling shaders, `nir_opt_gcm` (`nir_opt_gcm.c:430`, `gcm_schedule_early_src`) dereferences a phi source an earlier pass has freed. The SPIR-V passes `spirv-val`. Seen with Mesa 26.1.6 (Arrow Lake) and 26.2.7 (Iris Xe, ADL GT2); Mesa 26.3.1 and `main` (bb98606) pass the whole suite on the same Iris Xe | Use Mesa 26.3.1 or newer. To check a newer Mesa without installing it, build its Intel Vulkan driver and point `VK_DRIVER_FILES` at its `src/intel/vulkan/intel_devenv_icd.x86_64.json` | 621| `cs_sample_lz_int_d16`, `ps_sample_implicit_sint`, `ps_ssharp`, `ps_tex`, `ps_texture_mip0`, `ps_texture_sample` and `ps_texture_sample_d16` crash (exit -11 or 139) on an Intel GPU on Linux, while NVIDIA and llvmpipe pass them (TEST-399) | A bug in Mesa ANV's shader compiler: compiling these texture-sampling shaders, `nir_opt_gcm` (`nir_opt_gcm.c:430`, `gcm_schedule_early_src`) dereferences a phi source an earlier pass has freed. The SPIR-V passes `spirv-val`. Seen with Mesa 26.1.6 (Arrow Lake) and 26.2.7 (Iris Xe, ADL GT2); Mesa 26.3.1 and `main` (bb98606) pass the whole suite on the same Iris Xe | Use Mesa 26.3.1 or newer. To check a newer Mesa without installing it, build its Intel Vulkan driver and point `VK_DRIVER_FILES` at its `src/intel/vulkan/intel_devenv_icd.x86_64.json` |
622| A test exits with `3221225477` (`0xC0000005`, an access violation) on AMD, only when `VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump` is set (`d3d12_sparse_queue_family_contract` sets it itself) | The Vulkan SDK's API dump layer (1.4.363.0) crashes the test process now and then: on an RX 9060 XT (RDNA4, Windows driver 32.0.32029.2010) `d3d12_buffer_tiles` and `d3d12_queue_wait` crashed in 1 and 4 of 8 runs in one session and in 3 and 1 of 30 in another; the layer's `detailed` and `pre_dump` settings make no difference. Not seen in 24 runs of those tests without the layer, nor in 8 runs each of the SDK's `vkcube` and `vulkaninfo` with it, so it is not simply the layer on that driver | Run the test again. Do not read a crash under the layer as a failure of the test: run the same program without the layer to check its result, and use `LEONIDA_VK_VALIDATION=1` (the Khronos layer) for validation messages |
623| On an AMD integrated GPU (gfx1036) with AMD's Windows driver (`32.0.21042.62` and `32.0.21045.16010` measured), `crosslane_fuzz.py --wave 64 --w64-native --dpp --no-maskdata --seed 82001 --programs 600` reports one native mismatch: `cs_xl64_8200346406` differs in 96 words (32 lanes of each of its three waves), while `--wave64-emulate` and the hardware oracle match | AMD's Windows driver, not the translator (SHADER-705; the driver's generated code was not inspected). The same native wave64 SPIR-V is exact under RADV (Mesa 26.3.1) on another gfx1036 and on an RX 7900 XTX, and in the CPU interpreter. The wrong instruction is a `v_permlanex16_b32` that reads a register a DPP op with a partial `row_mask` has just written ([shader_validation.md](shader_validation.md), FUZZ-7) | Nothing to change in a build: no shader of the game has that shape (0 of 26,503; the two instructions meet in 6 shaders, all wave32 compute). `--wave64-emulate auto` stays native on this driver because of #857, and the emulated translation of the program matches there |
624| With `--wave64-emulate` (or `LEONIDA_W64_EMULATE=1`) on an NVIDIA RTX 5080 with Windows driver 32.0.16.1692 (616.92), `crosslane_fuzz.py --seed 91001 --dpp --no-maskdata` reports a hard mismatch for `cs_xl64_9100373886`: after `s_xor_b64 s[16:17], vcc, vcc` (0 in every lane), the second of two nested `v_cndmask_b32_e64 … s[16:17]` returns the old register instead of the lane id | An NVIDIA driver miscompile, not the translator (SHADER-720). The same SPIR-V (spirv-val clean) matches the model on an RTX 3060 with 616.64, an RTX 5060 Ti (Blackwell) with 621.14, an RTX 5070 Ti with 621.24 and an RTX 5080 with the Linux 580.65.06 driver. Hand edits narrow it to a value selected through the `%active` gate of a store; on the Linux 580 driver a similar pattern, a subgroup shuffle selected by an `%active` that is false, still fails in three wave32 `v_permlane16`/`v_permlanex16` programs of the same seed (#3796, #3918) | Update the NVIDIA driver to 621.14 or newer on Windows. If a crosslane mismatch only shows on one driver, check another driver or GPU before changing the translator |
625| `lds_fuzz.py --wave 64` (native, not `--emulate`) reports a `ds_bpermute_b32` mismatch on an AMD GPU on Windows, e.g. `cs_ldsfuzz_s7031_496_w64` (seed 7031): small values like `0x14` where the model wants another lane's data, while `--oracle hw` and `--emulate` on another GPU agree with the model | The AMD Windows driver (32.0.21042.62, gfx1036) miscompiles a native wave64 compute shader with two subgroup shuffles; a reduced SPIR-V module is in #4613 | Not a translator regression: check the same seed with `--oracle hw` and with `--emulate`. Native wave64 results on that driver need that cross-check |
626| On AMD's Windows driver a compute pipeline creation takes tens of minutes: `vk_pipeline_check` prints `still compiling <name> after ...s` with one busy thread, or a compute PSO creation through the D3D12 layer seems never to return | The driver's compiler on one module in the dispatch-loop form (`"control_flow": "dispatch loop"` in the translated `index.json`). Measured on a Radeon gfx1036 iGPU, driver 32.0.21042.62 (SHADER-995): `XboxBvhBuilder.dll`'s `LeafRehydration` in that form (a 581-case switch in a loop) was created after 34 minutes of one busy thread (XXTESTING), while its structured module is created in 2.9 s and an RTX 3070 (NVIDIA 610.74) created the dispatch-loop one in 11 s. It is not every such module: ten other programs of that DLL compile in that form on the Radeon in 0.4 to 40 s ([embedded_shaders.md](embedded_shaders.md), section 7). Not tried on another AMD GPU or driver branch | Translate with current `main`. Since SHADER-427 only a tree nested deeper than 64, a graph that cannot be made reducible or `--dispatch-loop` gives that form, and none of that DLL's programs has it; the shaders stage translates again by itself when the translator changed. A wave64 compute shader that still has it comes out in another form with `--wave64-emulate on` (12.4 s for this program on that driver), which that driver can crash on for other programs (#857) |
627
628### Signed zero in a float storage image (SHADER-605)
629
630Build `vk_store_test` as above and put `spirv-as` and `spirv-val` on PATH. Run this standalone
631probe from the repository root, passing the path to the executable you built:
632
633```powershell
634python -I runtime/test/shaders/probe_signed_zero.py runtime/build/vulkan/vk_store_test.exe
635```
636
637The probe assembles and validates two hand-written Vulkan 1.2 compute modules. Each requests
638`SignedZeroInfNanPreserve 32` and executes three constant `OpImageWrite` instructions into
639a `VK_FORMAT_R32G32B32A32_SFLOAT` image. Only the SPIR-V image format changes (`Unknown` or
640`Rgba32f`). The harness copies the images back, issues a transfer-write to host-read barrier,
641waits for completion, and compares all 768 words, including 756 prefilled guard words.
642A bit mismatch prints the word index and returns exit code 1. Both variants run even if the
643first comparison fails.
644
645On a GeForce RTX 5070 with Windows driver 616.56, both formats matched 765/768 words.
646In the first texel, `(-0, +0, +0, +0)`, word 0 read back as positive zero. The second texel,
647`(-0, 1, +0, +0)`, retained every bit. In the third, `(-0, -0, +0, +0)`, words 8 and 9 both
648read back as positive zero. All guards matched. This reproduces the discrepancy independently
649of RDNA translation. Independent runs of the same probe reproduced those three mismatches on
650a Linux RTX 5090 (595.99.02). On Windows, a Ryzen 7 9800X3D Radeon iGPU (25.10.30.02),
651an RTX 3080 (616.64) and an RTX 3060 (621.14) preserved all 768 words in both formats.
652The device reports are in [PR #3260](https://github.com/ItsNotRexed/Leonida/pull/3260).
653
654### Which known problems the game's shaders reach
655
656Several rows of the table above are tied to particular instructions. A GPU test or fuzzer that hits one does
657not by itself mean the game does. The counts below say how many of the 26,503 1.0.2.1 shaders (`shaders.rpf`,
658LLVM gfx1013) contain those instructions, by stage and by the wave size their FSSM header gives. They are
659counts of instructions over the program up to each listing's last `s_endpgm`. They are not reproductions: a
660shader that contains an instruction does not have to take the exact path a row describes.
661
662```sh
663python -I tools/op_reach.py <work>/shaders/dxbc/disasm --index <work>/shaders/dxbc/index.json \
664 --fssm <work>/shaders/dxbc/fssm s_bfe_i64 '*_dpp' v_permlanex16_b32 ds_bpermute_b32 v_mul_f16 ...
665```
666
667The corpus has 2,662 wave32 shaders (1,535 CS, 1,127 PS) and 23,841 wave64 shaders (every VS, GS and MS, 1,154
668CS, 10,974 PS).
669
670| Row | What the game's shaders contain (1.0.2.1) |
671|---|---|
672| `cs_w32_salu64` on RDNA1 / RADV 25.2.8 (the high word of `s_bfe_i64`) | **No shader uses `s_bfe_i64`** (nor `s_bfe_u64`). The fixture's failure does not reach a game shader. |
673| `lds_fuzz.py --wave 64` `ds_bpermute_b32` on AMD's Windows driver | **No wave64 shader uses `ds_bpermute_b32`**: it occurs in 5 wave32 CS (74 instructions), and `ds_permute_b32` in none. |
674| `crosslane_fuzz.py --wave 64` on an AMD iGPU (a `v_permlanex16_b32` after a partial-`row_mask` DPP) | DPP in 4,313 shaders, 2,496 of them wave64 (2,364 PS, 113 CS, 17 MS, 2 VS). `v_permlanex16_b32` in 2,293 shaders, 561 of them wave64. Whether any of them pairs the two with a partial `row_mask` is not counted, so these are upper bounds. |
675| `cs_dpp_ops` on MoltenVK 1.4.2 | DPP (any `*_dpp`) in 4,313 shaders (66,354 instructions): 1,817 wave32, 2,496 wave64. |
676| `valu_fuzz.py --family f16` signed zero on MoltenVK | `v_mul_f16` 124 shaders, `v_fma_f16` 124, `v_fmac_f16` 130, `v_pk_mul_f16` 55, `v_pk_fma_f16` 47, mostly PS (113–115 for the scalar forms). |
677| `ps_interp_f16_high` on MoltenVK (16-bit interpolation) | `v_interp_p1ll_f16` / `v_interp_p2_f16` in 4,776 PS (679 wave32, 4,097 wave64), 59,367 instructions each. The count is the instruction, not the `high` operand. |
678| `gs_tri` and `ms_tri` on a Mac | 195 GS and 9,282 MS, all wave64. |
478 679
479## Posting your result 680## Posting your result
480 681
@@ -482,3 +683,16 @@ Use the template at the top of [#166](https://github.com/ItsNotRexed/Leonida/iss
482range, OS, the commit you built, the tool versions and the counts each script printed. Post counts and pass/fail 683range, OS, the commit you built, the tool versions and the counts each script printed. Post counts and pass/fail
483lines only, never shaders or logs from the game. A failure that isn't in the table above gets its own issue, linked 684lines only, never shaders or logs from the game. A failure that isn't in the table above gets its own issue, linked
484from your entry. 685from your entry.
686
687The CPU, GPU, VRAM and RAM fields come from `tools/pc_checker.py`, which compares this PC with the Xbox Series X
688reference specs (or `--profile 2` for the community 1080p Low estimate). Run it in text mode; the default form opens a
689window:
690
691```powershell
692python -I tools/pc_checker.py --cli --check # spec lines, then exit 0 good, 1 weak, 2 unknown
693python -I tools/pc_checker.py --cli --check --json
694```
695
696`--cpu`, `--gpu` and `--ram` override the detected values when a VM or a remote session hides them. Its scores are
697rough estimates made for this tool, not benchmarks, so put the detected model names in the #166 entry, not the score.
698`python -I tests/test_pc_checker.py` checks the parsing and the comparison with the window mocked.
diff --git a/docs/text.md b/docs/text.md
index 9de8d2560..ce293518f 100644
--- a/docs/text.md
+++ b/docs/text.md
@@ -124,7 +124,7 @@ Measured with the per-table guess (counts only):
124|---|---:|---:|---:|---:| 124|---|---:|---:|---:|---:|
125| Nested archives (all) | 41 | 436 | 48 | 18 | 125| Nested archives (all) | 41 | 436 | 48 | 18 |
126| Nested archives holding string tables | 13 | 13 | 13 | 0 | 126| Nested archives holding string tables | 13 | 13 | 13 | 0 |
127| Tables in them / all tables | 14,440 / 14,440 | 15,831 / 15,831 | 78 / 78 | 0 / 0 | 127| Tables in them / all tables | 14,482 / 14,482 | 15,831 / 15,831 | 78 / 78 | 0 / 0 |
128| Tables per archive | 1,109-1,113 | 1,214-1,220 | 6 | - | 128| Tables per archive | 1,109-1,113 | 1,214-1,220 | 6 | - |
129| Per-table guess equal to its archive's language | 57.7%-99.9% | 72.2%-100% | 66.7%-100% | - | 129| Per-table guess equal to its archive's language | 57.7%-99.9% | 72.2%-100% | 66.7%-100% | - |
130| Tables whose language changes | 2,075 | 849 | 5 | 0 | 130| Tables whose language changes | 2,075 | 849 | 5 | 0 |
@@ -167,7 +167,7 @@ About 7-12% of lines have no text in a given language: the label's hash is in no
167 167
168`--labels` takes word lists or a `hashdict.py` JSON. Each table is then grouped by the longest `_`-prefix (up to three 168`--labels` takes word lists or a `hashdict.py` JSON. Each table is then grouped by the longest `_`-prefix (up to three
169parts) that at least half of its resolved labels share, usually a mission or feature code. With about 3 million 169parts) that at least half of its resolved labels share, usually a mission or feature code. With about 3 million
170harvested identifiers as labels, 1,869,883 of 7,172,826 strings (26%) resolve, and 9,409 of 30,349 tables get a 170harvested identifiers as labels, 1,869,883 of 7,172,826 strings (26%) resolve, and 9,409 tables get a
171group. 171group.
172 172
173## Usage 173## Usage
diff --git a/docs/textures.md b/docs/textures.md
index 2a6fb2df9..7644272ff 100644
--- a/docs/textures.md
+++ b/docs/textures.md
@@ -32,7 +32,12 @@ resumes from the DDS files already written.
32stdlib-only BCPack decoder (`tools/bcpack.py`, `tools/bcpack_tables.py`, 32stdlib-only BCPack decoder (`tools/bcpack.py`, `tools/bcpack_tables.py`,
33`tools/bcpack_tables_bptc.py`) now decodes the rANS entropy layer and rebuilds BC blocks 33`tools/bcpack_tables_bptc.py`) now decodes the rANS entropy layer and rebuilds BC blocks
34for all six active modes (BC1, BC3, BC4, BC5, BC6H and BC7 — 100% of BCPack codecs in the 34for all six active modes (BC1, BC3, BC4, BC5, BC6H and BC7 — 100% of BCPack codecs in the
35corpus). Strict confirmed-history mode is the default; `--allow-provisional` enables the 35corpus). To inspect or decode one raw BCPack stream from the command line, `tools/bcpack_tool.py`
36wraps the same decoder: `inspect <in.bin> --codec <1..7> --size <uncompressed_bytes> [--json]` prints
37the stream's header, entropy statistics and validation results; `decode <in.bin> <out.bin> --codec <1..7>
38--size <uncompressed_bytes> [--provisional]` writes the rebuilt BC blocks; `profile <in.bin> --codec <1..7>
39--size <uncompressed_bytes>` reports per-symbol frequency statistics. Strict confirmed-history mode is
40the default; `--allow-provisional` enables the
36provisional and last-resort history entries, and `--history <path>` supplies locally 41provisional and last-resort history entries, and `--history <path>` supplies locally
37calibrated BC6H/BC7 initial history JSON tables at run time (no fitted BC6H/BC7 history 42calibrated BC6H/BC7 initial history JSON tables at run time (no fitted BC6H/BC7 history
38data is embedded in the repository). `rpf9dump`'s C# `TtpfReader` (submodule pin `e293917`, 43data is embedded in the repository). `rpf9dump`'s C# `TtpfReader` (submodule pin `e293917`,
@@ -184,6 +189,15 @@ mode 1/32 descriptors have a known element size (4 mode 1, 11 mode 32); all fift
184other 19 mode 1 records formerly counted as unknown-format 2D entries are two-slice 2D arrays 189other 19 mode 1 records formerly counted as unknown-format 2D entries are two-slice 2D arrays
185(`depth = 2`, DXGI 28/71/83/98; see `docs/textures_arrays.md`). 190(`depth = 2`, DXGI 28/71/83/98; see `docs/textures_arrays.md`).
186 191
192Where one descriptor's mode is still in doubt, `tools/tex_mode_probe.py <textures index.json>
193<carve dir> [--fmt BC1] [--n 12]` scores every 4 KiB and 64 KiB addrlib colour pattern of the
194element size, crossed with both placements of the top mip (at the data offset, or at the end of
195the chain, since GFX10 stores mips smallest first), by the smoothness of the decoded BC1/BC2/BC3
196average colours. It prints the best and second-best pattern with the placement and the linear
197(untiled) score per texture, then a tally of the winners and how many textures no candidate fit.
198It needs numpy, like `tests/test_tex_mode_probe.py`, which covers it on synthetic blobs with no
199game files.
200
187### The layout is the AMD mip tail 201### The layout is the AMD mip tail
188 202
189The compact profile is the Gfx10 mip chain: standalone mips are padded to whole blocks and 203The compact profile is the Gfx10 mip chain: standalone mips are padded to whole blocks and
@@ -423,7 +437,7 @@ The RDS5 index is readable without game code:
423| chunk table | 0x18, 8 bytes per entry, `(count − 1) * 8` bytes | 437| chunk table | 0x18, 8 bytes per entry, `(count − 1) * 8` bytes |
424| ETPF index | `align(0x18 + (count − 1) * 8, 0x100)`; version 634 (`0x27A`) | 438| ETPF index | `align(0x18 + (count − 1) * 8, 0x100)`; version 634 (`0x27A`) |
425| texture records | a 16-byte ETPF header, then `area` bytes of records (at least 16 × textures) | 439| texture records | a 16-byte ETPF header, then `area` bytes of records (at least 16 × textures) |
426| asset keys | one u64 per record after the descriptor array; IDs are 32 bytes each | 440| asset keys | one u64 per record after the descriptor array; the array continues into the ID region when it is longer than the record area leaves room for (the area is at least 16 × textures), so a reader must load it across that boundary. IDs are 32 bytes each. In the 57 pools of this install, 15 have a straddling array and 28,666 of the 357,115 keys sit past the record area |
427 441
428Chunk entry `(u64 value)`: 442Chunk entry `(u64 value)`:
429 443
@@ -555,8 +569,11 @@ semantics, not as a claim that they are globally unique across every shader.
555hash, role and texture name, resolves only the five measured character slots, and reports any 569hash, role and texture name, resolves only the five measured character slots, and reports any
556other hash as `unknown 0x...`. A garment-shader material (`d5ed50f4`, `ea8d09d0`, `39ddb9ca`) 570other hash as `unknown 0x...`. A garment-shader material (`d5ed50f4`, `ea8d09d0`, `39ddb9ca`)
557with no `0xC8E8C282` binding is flagged `garment-no-albedo`, so a renderer keeps that part clay 571with no `0xC8E8C282` binding is flagged `garment-no-albedo`, so a renderer keeps that part clay
558instead of painting `speculartex` as colour. `--json` and `--csv` write the same rows to a 572instead of painting `speculartex` as colour. The `texture` column retains the display value,
559report, which may not overwrite an input: 573including the eight-digit `Name` hash from `rpf9dump models`. The appended `asset_key` column
574holds the 16-digit `Id64` for matching against a texture pool's `AssetKey`. An absent or malformed
575ID appears as `-` in the terminal, an empty CSV cell and JSON `null`. Report paths must be
576distinct from the inputs:
560 577
561 python -I tools/character_textures.py <model.json|dir> [--json FILE] [--csv FILE] 578 python -I tools/character_textures.py <model.json|dir> [--json FILE] [--csv FILE]
562 579
@@ -982,8 +999,33 @@ with per-instance data, the shape of a per-tile or per-cell map. One of the othe
982 999
983**The 121 other streams** start with no known magic (`RDS5`, `0DRP`, `TTPF`, `RSC8`, `PSIN`, `RBF0`, DDS) in 1000**The 121 other streams** start with no known magic (`RDS5`, `0DRP`, `TTPF`, `RSC8`, `PSIN`, `RBF0`, DDS) in
984their first 4 KiB, and the large ones are high-entropy (7.3 to 7.7 bits per byte over the first 64 KiB, except 1001their first 4 KiB, and the large ones are high-entropy (7.3 to 7.7 bits per byte over the first 64 KiB, except
985one at 4.1). They are left as opaque raw data here; matching them to the `data/ttdb` texture pools is the 1002one at 4.1). They are left as opaque raw data here.
986obvious next check. 1003
1004**They are not copies of the texture pools.** Each of the 121 streams was compared with every chunk of all 57
1005`.ttpf` pools in the package (1,026,833 chunks: 918,223 zlib, 102,725 BCPack BC1, 5,167 BC7, 718 other BCPack
1006codecs, 5 raw), as stored and, for zlib chunks, inflated: the SHA-1 of the whole stream against the SHA-1 of each
1007chunk, and the stream's first 64 bytes against each chunk's first 64 bytes (85 of the 121 streams start with more
1008than four distinct byte values; the other 36 start with near-constant bytes and only take the whole-content test).
1009
1010| Result | Streams |
1011|---|---:|
1012| Identical to a pool chunk (stored zlib bytes and inflated content) | 1 (4 KiB, a shared `data/ttdb` pool) |
1013| Same first 212,464 to 582,338 bytes as a 4 MiB `data/ttdb` chunk, then different | 3 (6, 12 and 32 MiB) |
1014| Same first 1,010 to 2,800 bytes as hundreds of chunks (a common leading pattern, not a copy) | 3 |
1015| No match | 114 |
1016
1017Sizes of the 121: 62 below 64 KiB, 16 of exactly 64 KiB, 32 from 64 KiB to 16 MiB, 11 of 16 MiB or more. So,
1018apart from one 4 KiB stream, the opaque data of `textures.rpf` is not pool texture data, and three of the large
1019streams share a long identical start with a pool chunk and then diverge.
1020
1021Following them past the divergence with an in-order alignment (extend identical runs; on a mismatch, resync on a
102264-byte piece of the chunk taken up to 64 KiB ahead, found within the next 256 KiB of the stream): in the 6 MiB and
102332 MiB streams, five different 4 MiB `data/ttdb` chunks each reappear in order for 65.8% to 97.5% of their bytes,
1024in short runs broken by 164 to 1,007 gaps, while the stream advances about 1.4 to 1.5 times the chunk's length; in
1025the 12 MiB stream only 8.6%. That five different chunks align this well with the same two streams says the chunks
1026are alike among themselves, so repetitive content may account for part of it: this measures shared runs, not a
1027copy, and what the streams are remains open. Method: the carve's
1028inflated streams and `tools/ttpf_mips.py`'s `Pool` chunk table; counts only.
987 1029
988**Measured keying and format codes (ASSET-274):** 1030**Measured keying and format codes (ASSET-274):**
989All 1,315 system streams are RAGE `pgDictionary<grcTexture>` pages containing descriptor pointers and a 32-bit 1031All 1,315 system streams are RAGE `pgDictionary<grcTexture>` pages containing descriptor pointers and a 32-bit
@@ -1018,7 +1060,7 @@ All 1,315 system streams are RAGE `pgDictionary<grcTexture>` pages containing de
1018 1060
1019## Reproduce 1061## Reproduce
1020 1062
1021The normal `make_game.py` assets stage now fills missing and partial BCPack DDS entries in the same pool manifests used for model texture lookup. It uses strict decoding by default and discovers an optional local reconstruction profile at `<work>/bcpack-calibration.json`. The single-entry exporter accepts the same profile through `--calibration`. Build instructions, the JSON schema and the game-independent test are in the [calibrated export guide](../tools/bcpack_calibration/README.md). 1063The normal `make_game.py` assets stage now fills missing and partial BCPack DDS entries in the same pool manifests used for model texture lookup. It uses strict decoding by default and discovers an optional local reconstruction profile at `<work>/bcpack-calibration.json`. The pass stamp in each pool manifest hashes the decoder modules (`ttpf_assets.DECODER_SOURCES`) and the profile, so a pool is done again after either changes. The single-entry exporter accepts the same profile through `--calibration`. Build instructions, the JSON schema and the game-independent test are in the [calibrated export guide](../tools/bcpack_calibration/README.md).
1022 1064
1023`tools/ttpf_mips.py` is the read-only measurement and decode tool (with `tools/bcpack.py` 1065`tools/ttpf_mips.py` is the read-only measurement and decode tool (with `tools/bcpack.py`
1024enabled in strict confirmed-history mode by default), and `tools/bcpack_history_calib.py` 1066enabled in strict confirmed-history mode by default), and `tools/bcpack_history_calib.py`
@@ -1033,6 +1075,7 @@ python -I tools/ttpf_mips.py check <pool.ttpf> <index> [--allow-provisional] [--
1033python -I tools/ttpf_mips.py export <pool.ttpf> <index> <out.dds> [--allow-provisional] [--history <path>] 1075python -I tools/ttpf_mips.py export <pool.ttpf> <index> <out.dds> [--allow-provisional] [--history <path>]
1034python -I tests/test_bcpack.py 1076python -I tests/test_bcpack.py
1035python -I tests/test_bcpack_history_calib.py 1077python -I tests/test_bcpack_history_calib.py
1078python -I tests/test_bcpack_tool.py
1036python -I tests/test_tex_headers.py 1079python -I tests/test_tex_headers.py
1037python -I tests/test_ttpf_mips.py 1080python -I tests/test_ttpf_mips.py
1038``` 1081```
diff --git a/docs/textures_arrays.md b/docs/textures_arrays.md
index 400f30f57..4f8f5c64c 100644
--- a/docs/textures_arrays.md
+++ b/docs/textures_arrays.md
@@ -174,10 +174,19 @@ adjacent-Z voxel difference:
174 174
175| Pool / index | Dimensions | DXGI format | B/voxel | 3D tile | `padded_d` | Span (B) | 3D Z-diff | 2D stacked control | Ratio | 175| Pool / index | Dimensions | DXGI format | B/voxel | 3D tile | `padded_d` | Span (B) | 3D Z-diff | 2D stacked control | Ratio |
176|---|---|---|---:|---|---:|---:|---:|---:|---:| 176|---|---|---|---:|---|---:|---:|---:|---:|---:|
177| `ttdb_graphics.ttpf` #901 | 256×32×8 | 54 `R16_FLOAT` | 2 | 16×8×16 | 16 | 262,144 | 0.023623 | 0.124305 | 5.3× smoother | 177| `ttdb_graphics.ttpf` #901 | 256×32×8 | 54 `R16_FLOAT` | 2 | 8×16×16 | 16 | 262,144 | 0.004238 | 0.124305 | 29.3× smoother |
178| `ttdb_graphics.ttpf` #575 | 32×32×32 | 10 `R16G16B16A16_FLOAT` | 8 | 8×8×8 | 32 | 262,144 | 0.036721 | 0.565428 | 15.4× smoother | 178| `ttdb_graphics.ttpf` #575 | 32×32×32 | 10 `R16G16B16A16_FLOAT` | 8 | 8×8×8 | 32 | 262,144 | 0.036721 | 0.565428 | 15.4× smoother |
179| `ttdb_graphics.ttpf` #200 | 32×64×32 | 10 `R16G16B16A16_FLOAT` | 8 | 8×8×8 | 32 | 524,288 | 0.016793 | 0.110316 | 6.6× smoother | 179| `ttdb_graphics.ttpf` #200 | 32×64×32 | 10 `R16G16B16A16_FLOAT` | 8 | 8×8×8 | 32 | 524,288 | 0.016793 | 0.110316 | 6.6× smoother |
180 180
181The intra-tile bit order (`VOLUME_PATTERNS_4K` in `tools/ttpf_mips.py`) and the tile extents
182(`_VOLUME_4K_TILE` in `tools/tex_headers.py`) are Mesa addrlib's `GFX10_SW_4K_S3_PATINFO` (the RbPlus table is
183identical), the same as rpf9-explorer's `VolumePatterns`. Until this was corrected, the rows for 2-, 4- and
18416-byte elements matched no GFX10 pattern in addrlib, and the 2-byte tile was taken as 16×8×16 instead of
1858×16×16. Only #901 uses one of those rows. The adjacent-Z check above could not catch it (the wrong order still
186kept most Z neighbours together: 5.3× against the control), but the X/Y neighbours could: as a share of the mean
187difference between random voxel pairs, adjacent-Y differences were 0.357 with the old order and are 0.067 now, and
188adjacent-Z 0.029 and 0.007 (adjacent-X 0.007 and 0.015). The two 8-byte volumes use the unchanged row.
189
181## 43-bit `(meta, extra)` streaming chunk-page metadata 190## 43-bit `(meta, extra)` streaming chunk-page metadata
182 191
183Decoded by `decode_etpf_chunk_pages` and `etpf_streaming_padding` in `tools/tex_headers.py`, and 192Decoded by `decode_etpf_chunk_pages` and `etpf_streaming_padding` in `tools/tex_headers.py`, and
@@ -220,6 +229,28 @@ With 2D compact layouts plus 2D arrays, cubemaps, and 3D volumes enabled in
220has landed in `breadbbbb/rpf9-explorer` PRs #5, #6, and #7 (compact layouts, multi-slice shapes, 229has landed in `breadbbbb/rpf9-explorer` PRs #5, #6, and #7 (compact layouts, multi-slice shapes,
221and BCPack BC1/BC3/BC4/BC5) and is carried by the `e293917` submodule pin. 230and BCPack BC1/BC3/BC4/BC5) and is carried by the `e293917` submodule pin.
222 231
232## Preview a DDS plane
233
234The header lists the mip count, array size, volume depth and cube faces available
235to the PNG decoder. A cube array's `array_size` counts whole cubes.
236
237```powershell
238python -I tools/dds_png.py cubemap.dds --info
239python -I tools/dds_png.py cubemap.dds face.png --layer 1 --face nz --mip 2
240python -I tools/dds_png.py array.dds layer.png --layer 3 --max-size 256
241python -I tools/dds_png.py volume.dds slice.png --mip 1 --z 2
242```
243
244Indices start at zero. Faces are `px`, `nx`, `py`, `ny`, `pz` and `nz`
245(positive and negative X, Y and Z). A legacy cube can omit faces. The default
246preview uses mip 0 of the first layer, first stored face or first volume slice.
247For volumes, `--z` is relative to the selected mip, whose depth halves at each
248level down to one. `--max-size` downsizes that plane after decoding. For a
249seekable file, the converter reads the header and the selected plane.
250
251For uncompressed data, a declared top-level row pitch applies to each layer
252or slice. Lower mips use tightly packed rows, as written by the project exporter.
253
223## Reproduce 254## Reproduce
224 255
225```powershell 256```powershell
diff --git a/docs/weather.md b/docs/weather.md
new file mode 100644
index 000000000..2e01a7eb1
--- /dev/null
+++ b/docs/weather.md
@@ -0,0 +1,137 @@
1# Weather XML in `common.rpf`
2
3This note measures the one `CContentsOfWeatherXmlFile` document that drives weather (106,816 bytes inflated at
4stream offset 0x207000 in `common.rpf`). `gamedata.md` has the element tree and the link checks; this page adds
5what the `Mod*` axes correlate with, the exact vocabulary mismatches, and the measured behavior of the numeric
6fields. Counts, schema names and small constants only, no values dump. Everything is reproducible from any
7copy of the Xbox 1.0.2.1 package with the tooling in `gamedata.md`: carve with `tools/rpf9_carve.py`, then
8`python -I tools/gamedata_reader.py <work>/carve/common --out <scratch>` and read
9`CContentsOfWeatherXmlFile_207000.json` (game data, stays local).
10
11The root has 18 direct children. The load-bearing ones:
12
13| Child | Count | What it is |
14|---|---:|---|
15| `WeatherTypes` | 168 | named weather states the game can select |
16| `WeatherTypeDatas` | 25 | numeric field sets a type borrows via `DataName` (72 fields each) |
17| `WeatherAppTypeDatas` | 26 | weather-app presentation entries (19 of them referenced) |
18| `WeatherCycles` | 2 | named cycles with a `TimeMult` |
19| `WeatherTimeCycleFileNames` | 25 | `COMMON:/DATA/TIMECYCLE/W_<family>.XML` references |
20| 8 `Mod*List`s | 3..17 | vocabularies for the `Mod*` tags |
21| `WeatherTypeIndirectionList` | 15 | `From`/`To` pairs (13 complete, per `gamedata.md`) |
22| `SkipDebugCycling` | 1 | top-level flag, `True` |
23| `SinglePlayerOnlyWeathers` | 1 | an empty string |
24
25## The 168 types and their `Mod*` tags
26
27Every type carries `Name`, `ShortName`, `DataName`, `SkipDebugCycling`, and either all eight or none of the
28`Mod*` tags: `ModAtmosphere`, `ModPrecipitation`, `ModTemperature`, `ModHumidity`, `ModWind`, `ModFetch`,
29`ModMisc`, `ModNiceness`. The split is 151 fully tagged, 17 with nothing, and it is exactly a family split.
30The 151 tagged types live in the nine `CLOUDSCAPE_*` families (2 to 38 types each by `DataName`). The 17
31untagged ones are the 16 single-type families plus one stray variant of a `CLOUDSCAPE_*` data set. Eleven of
32the 17 have `Name == DataName` exactly; the other six differ only in case (like `MISTY` borrowing `misty`).
33
34The `Mod*` axes are not restatements of the numeric data. All eight axes change *within* a family; seven of
35the eight do it in at least 6 of the nine `CLOUDSCAPE_*` families (`ModTemperature` and `ModFetch` in 8 of 9,
36`ModMisc` only in 3). Every one of the 151 tagged
37types references one of 19 distinct `WeatherAppDataName` entries; none of the 17 untagged types has one.
38`SkipDebugCycling` per type is `True` for 137 and `False` for 31; all 31 `False` ones are tagged (120 of the
39151), and every untagged type is `True`.
40
41### The vocabularies, exact case
42
43Comparing type tokens to their list case-sensitively:
44
45| Axis | List | Used | Off-list (exact case) |
46|---|---:|---:|---|
47| `ModAtmosphere` | 17 | 14 | none |
48| `ModPrecipitation` | 16 | 11 | none |
49| `ModTemperature` | 9 | 9 | `W_MOD_temperature_cool` x1 |
50| `ModHumidity` | 5 | 5 | none |
51| `ModWind` | 11 | 14 | `_Light` x3, `_Mid` x1 (case), `_camlLight` x1 (typo) |
52| `ModFetch` | 5 | 8 | `_Low` x10, `_High` x26, `_mid` x1 (case) |
53| `ModMisc` | 7 | 6 | `W_MOD_misc_None` x135, `W_MOD_misc_High` x2 (real misses) |
54| `ModNiceness` | 3 | 3 | none |
55
56Case-insensitively only three tokens remain off-list: `W_MOD_wind_camlLight` (one type; two characters from
57the list's `calmLight`, a genuine typo), and the two `ModMisc` values above, which is what `gamedata.md`
58already flags (137 of 151 types use a `ModMisc` no list defines). A loader should rank-match case-insensitively
59and never reject a type over `ModMisc`.
60
61The vocabularies themselves read as ordered scales, with two catches. `ModPrecipitation` is 15 tokens
62`W_MOD_precip_{20..100 step 20}` x `{drizzle, rain, HeavyRain}` plus a bare `W_MOD_precip_0`, so the intensity
63is the middle number, not the list position. `ModHumidity` and `ModNiceness` are written top-down
64(`VeryHigh` first, `good` first), the other lists bottom-up.
65
66## What each axis tracks in the numbers
67
68Ranking each axis by its own scale (precipitation by the embedded intensity; humidity and niceness
69bottom-up; the rest by list order; temperature excluding its one `TEST_Mid` entry) and correlating with the
70fields of the borrowed data set (Spearman, average ranks, over the 151 tagged types):
71
72| Axis | Best correlation | Value |
73|---|---|---:|
74| `ModNiceness` | `Niceness` field | +0.621 |
75| `ModHumidity` | `WindMax` | +0.598 |
76| `ModWind` | `WindMin` (n=150) | +0.496 |
77| `ModPrecipitation` | `WindMax` | +0.451 |
78| `ModFetch` | `WindGustsSpeedMax` | +0.309 |
79| `ModTemperature` | `WindMax` | +0.292 |
80| `ModAtmosphere` | `Rain` | +0.149 |
81
82Three readings fall out of this. The `ModNiceness` label is a coarse view of the numeric `Niceness` field
83(bucket means 5.47 bad / 6.69 neutral / 9.85 good, values 1 to 10). Humidity, precipitation and wind all
84correlate with wind strength rather than with their nominal subject, which says the 25 data sets are ordered
85mostly by storminess and the axes ride along. And `ModAtmosphere` correlates with nothing, consistent with it
86being a categorical label (pressure, clarity, haze, mist groups) rather than a scale.
87
88The `Rain` field does not follow the top precipitation token. It is nonzero in exactly 7 of the 25 data sets
89(`DRIZZLE` 0.4, `Rain` 0.6, `THUNDERSTORM` 1.0, `HURRICANE` 0.8, `Shower` 0.2, `HAIL` 0.3, `CLOUDSCAPE_HURRICANE`
900.8), and read per type through the borrowed set, 8 of the 168 types are nonzero: the 6 untagged storm names
91(`DRIZZLE`, `RAIN`, `THUNDERSTORM`, `HURRICANE`, `SHOWER`, `HAIL`) plus `AM_Hurricane` and `AM_Hurricane_Au`.
9212 of the 14 types tagged `W_MOD_precip_100_HeavyRain` borrow a data set whose `Rain` is 0, so `Rain > 0` is a
93property of the borrowed set, not of the precipitation token.
94
95## The 25 data sets
96
97Each `WeatherTypeDatas` entry is 72 numeric fields borrowed by name. Measured ranges: `WindMin` 0.5 to 26,
98`WindMax` 0.9 to 32, `WindGustsChance` 10 to 100, `WindGustsSpeedMax` 0.5 to 20, `CloudType` 0.01 to 0.67,
99`Niceness` 1 to 10 (8 distinct), `Fog` binary, `MaxWeatherAccumulation` two values (0 and 0.12). Dead fields
100in this build: `Honor` is 0.0 in all 25, `IsBlizzard` 0 in all 25, and `MudWashSpeed` and `OceanWaveWindScale`
101are constant (0 and 0.7). The `IsNice` flag is not a threshold on `Niceness`: the values 5 and 6 each appear
102with the flag set both ways.
103
104## `WeatherCycles` and `TimeMult`
105
106Two cycles: `SUNNY` with `TimeMult` 2 and `HIGHPRESSURE` with `TimeMult` 1. `TimeMult` is the only numeric
107field the block has. Each cycle name is the `@name` of one of the 25 referenced `timecycle_keyframe_data`
108documents, and those documents are structurally ordinary (2 regions, 1,142 variables per region, same as the
109other 23). Nothing in the archive carries a duration, stage count or keyframe spacing that `TimeMult` could
110multiply, so it is a pure runtime scalar; what it scales is a runtime question, but it demonstrably changes
111nothing about the cycle's keyframe structure.
112
113## The `Honor*` values
114
115`WeatherMiscData` holds four values: `HonorThresholdForGraph` 0.1, `HonorThresholdForWeatherChange` 0.1,
116`HonorDecreaseWaitTime` 30.0, `HonorWeatherChangeTime` 30.0. Read plainly: an honor change has to move at
117least 0.1 to show on the graph or to trigger a weather change, and both paths wait 30 units. With the per-type
118`Honor` field at 0.0 in all 25 data sets, there is nothing for these thresholds to gate, so the
119honor-driven weather path is inert as shipped.
120
121## App entries and keyframe documents
122
123`WeatherAppTypeDatas` has 26 uniquely named entries; the 151 types reference 19 of them. The 7 unreferenced
124ones (like `PatchyMist` and `Seafog`) carry empty icons and descriptions, placeholders for app states this
125build never selects.
126
127All 25 `TimeCycleName` values match a `timecycle_keyframe_data` document `@name` case-insensitively (21 match
128exactly; the four mixed-case families `misty`, `Fog`, `Rain`, `Shower` have uppercase timecycle names). The 27
129keyframe documents are those 25 plus two small ones no weather type references: `underwater_deep` (2 regions,
130515 variables each) and `sleet` (2 regions, 520 variables each).
131
132## How to reproduce
133
134Carve and dump as above, then count what this note claims: the 151/17 tag split and its family alignment, the
135exact-case off-list table, the 7 nonzero-`Rain` data sets and the 8 types that read them, the seven Spearman
136figures (average ranks, borrowed family fields), the constant `Honor`/`IsBlizzard` fields, and the two
137unreferenced keyframe documents. None of it needs a key and none of it leaves the local copy.
diff --git a/docs/world.md b/docs/world.md
index f6562e925..7d0951465 100644
--- a/docs/world.md
+++ b/docs/world.md
@@ -420,11 +420,14 @@ and joins them with the `InteriorNames` section (full archive, `--jobs 15`, abou
420|---|---:| 420|---|---:|
421| `CMloArchetypeDef` definitions / distinct names | 1,706 / 1,706 | 421| `CMloArchetypeDef` definitions / distinct names | 1,706 / 1,706 |
422| `CMloInstanceDef` placements / distinct interiors placed | 2,590 / 1,704 | 422| `CMloInstanceDef` placements / distinct interiors placed | 2,590 / 1,704 |
423| placements of a name with no `CMloArchetypeDef` | 0 |
423| keys naming an interior (confirmed by the 64-bit key) | 1,357 (1,357) | 424| keys naming an interior (confirmed by the 64-bit key) | 1,357 (1,357) |
424| keys whose interior is placed | 1,356 | 425| keys whose interior is placed | 1,356 |
425| ... with as many positions as placements | 1,268 | 426| ... with as many positions as placements | 1,268 |
426| ... with more positions than placements | 64 | 427| ... with more positions than placements | 64 |
427| ... with fewer positions than placements | 24 | 428| ... with fewer positions than placements | 24 |
429| ... whose placements have no `position` to measure from | 0 |
430| inner-item `Pos` values that are not three numbers (dropped) | 0 |
428 431
429So a key selects one interior archetype, and its inner items are, in most cases, one per placed copy of that 432So a key selects one interior archetype, and its inner items are, in most cases, one per placed copy of that
430interior: the `Name` of each item labels that copy. 433interior: the `Name` of each item labels that copy.
@@ -440,8 +443,15 @@ positions to the nearest placed copy of its own interior's box (0 = inside):
440 443
441| Rotation | Inside | ≤ 1 m | ≤ 2 m | ≤ 5 m | ≤ 25 m | ≤ 100 m | Median | In a non-`limbo` room box | 444| Rotation | Inside | ≤ 1 m | ≤ 2 m | ≤ 5 m | ≤ 25 m | ≤ 100 m | Median | In a non-`limbo` room box |
442|---|---:|---:|---:|---:|---:|---:|---:|---:| 445|---|---:|---:|---:|---:|---:|---:|---:|---:|
443| stored quaternion | 315 | 1,015 | 1,189 | 1,443 | 1,867 | 2,199 | 1.72 m | 213 | 446| stored quaternion | 315 | 1,015 | 1,189 | 1,443 | 1,867 | 2,199 | 1.72 m | 215 |
444| conjugated | 571 | 950 | 1,121 | 1,416 | 1,863 | 2,199 | 2.10 m | 482 | 447| conjugated | 571 | 950 | 1,121 | 1,416 | 1,863 | 2,199 | 2.10 m | 484 |
448
449The interior and room boxes are scaled by each placement's `scaleXY` and `scaleZ` before measuring. Only 6 of
450the 2,590 placements are scaled at all (`scaleZ` 0.998), so this changes two room hits per convention and none
451of the distances. A point within 1e-6 m of an interior or room face counts as inside it (`EPS`), since the
452inverse of a float32 rotation can leave a face point about 1e-17 m outside. Positions are float32 and resolve to
453about 1 mm near the map edge, so a tolerance this far below that decides as exact arithmetic would; on the full
454archive it changes no count above.
445 455
446The interior box's largest side has a median of 16.7 m. Most positions are therefore just outside or just inside 456The interior box's largest side has a median of 16.7 m. Most positions are therefore just outside or just inside
447the interior shell, which fits an entry or label point; that they are doors is a hypothesis (portals were not 457the interior shell, which fits an entry or label point; that they are doors is a hypothesis (portals were not
@@ -452,8 +462,9 @@ compared). The conjugated rotation puts more positions inside rooms, consistent
452Interior rooms (`CMloRoomDef` `0b1811f1`, 0x70 bytes: `name` +0x00, `bbMin` +0x10, `bbMax` +0x20) are reached 462Interior rooms (`CMloRoomDef` `0b1811f1`, 0x70 bytes: `name` +0x00, `bbMin` +0x10, `bbMax` +0x20) are reached
453through the interior's array members, which use the `InstanceList` reference of 463through the interior's array members, which use the `InstanceList` reference of
454[Instanced props and grass](#instanced-props-and-grass) (1-based block index, offset from bit 20, u16 count). Room 464[Instanced props and grass](#instanced-props-and-grass) (1-based block index, offset from bit 20, u16 count). Room
455names are lower-cased joaat; in all 908 resources that hold one interior, its first room is `limbo`. A room's hash member `a261e0a9` (+0x34) 465names are lower-cased joaat; all 1,706 interiors have rooms, and in every one the first room is `limbo`
456holds the hash of 267 interior keys. 466(`interiors_first_room_limbo`). A room's hash member `a261e0a9` (+0x34) holds the joaat of 267 interior keys
467(`keys_in_a_room_key_member`).
457 468
458```powershell 469```powershell
459python -I tools\gamedata_reader.py <work>\common --root GameShape__Data__LocationNameLoopkup --out <work>\gamedata 470python -I tools\gamedata_reader.py <work>\common --root GameShape__Data__LocationNameLoopkup --out <work>\gamedata
@@ -572,6 +583,11 @@ MINX,MINY,MAXX,MAXY` bounds the RAGE world X/Y. `world.json` then has `"layout":
572`placed_unverified` (no key in the row), `key_mismatch`, `unresolved_archetype` (no exported model has that name), 583`placed_unverified` (no key in the row), `key_mismatch`, `unresolved_archetype` (no exported model has that name),
573`model_not_loadable`, `degenerate_scale`, `mirrored` and `distinct_models`. 584`model_not_loadable`, `degenerate_scale`, `mirrored` and `distinct_models`.
574 585
586`--max-tex-size` limits the longest edge of embedded DDS previews to 512 pixels by default.
587When shrinking a DDS tagged sRGB, the converter averages RGB in linear light, weights each texel by its
588alpha, and encodes the result as sRGB again. An opaque black and white pair averages to 188 in sRGB
589and 128 in an untagged RGBA8 texture.
590
575### Shared geometry (`--instancing`) 591### Shared geometry (`--instancing`)
576 592
577A city has 1.55 M HD placements of about 120 k models, and most models are placed many times. By default 593A city has 1.55 M HD placements of about 120 k models, and most models are placed many times. By default
@@ -816,8 +832,10 @@ only; no names.
816 67 to 254, not contiguous), and none of those 149 has a tag: they read as unused placeholder slots, which would 832 67 to 254, not contiguous), and none of those 149 has a tag: they read as unused placeholder slots, which would
817 keep the slot index (the value a material would store) stable. The other 106 names occur once each, and 833 keep the slot index (the value a material would store) stable. The other 106 names occur once each, and
818 only one of them has neither tag. 834 only one of them has neither tag.
819- `MaterialDataList`, which would carry each material's procedural tag, survives only from mid-document (see 835- Five retained fragments of `MaterialDataList` contain 399 complete material records with 1,433 nested tag
820 the snow and mud section below); 1 of the 107 tag names occurs in its retained part. 836 entries. One of the 107 procedural table names occurs as a substring in the retained text, but none matches
837 a field value in those records exactly. The fragments cover only part of the list (see the snow and mud
838 section below). A numeric value in the slot range (0–254) alone does not identify a slot reference.
821 839
822Not measured here (hypothesis): whether materials index this table by slot, as in GTA V, and where the 840Not measured here (hypothesis): whether materials index this table by slot, as in GTA V, and where the
823object and plant definitions live. 841object and plant definitions live.
@@ -851,9 +869,55 @@ Cross-checks:
851 name and no texture-dictionary item name or its joaat hash in the local catalog (118,925 named items). The 869 name and no texture-dictionary item name or its joaat hash in the local catalog (118,925 named items). The
852 catalog is incomplete for names, so this does not show the textures are absent. 870 catalog is incomplete for names, so this does not show the textures are absent.
853 871
854Not measured here (hypothesis): which surfaces the 16 entries are (their names suggest snow, mud and sand 872### The 16 surface entries and the deformation map (ASSET-305)
855variants), how `Type` selects a track type for peds, animals and vehicles, and the size of the deformation map 873
856(`DeformationWorldSpaceWidth` is the obvious input). 874Measured on a 1.0.2.1 package (one `CSnowTrackData` document, one complete stream, found with
875`tools/gamedata_xml.py` on a `rpf9_carve.py` carve of `common.rpf`). Classes and counts only; the entry and
876material strings are not reproduced.
877
878- **11 surfaces are defined and 5 slots are empty.** Entries 0 to 10 each have a `Name`, a distinct opaque
879 `DebugColor` and their own parameter set (11 distinct parameter sets). Entries 11 to 15 have no `Name`
880 text, a `DebugColor` of `0x00000000`, no physics material, and one shared parameter set that equals none of
881 the 11 (their terrain render scales are 0). The array is 16 long whatever the content, which fits a
882 fixed-size table indexed by a 4-bit surface id; the index is not read in a shader here.
883- **The 11 surfaces, by class** (from the `Name` and the physics-material names of each entry):
884
885 | Entry | Class | Physics materials |
886 |---:|---|---:|
887 | 0 | snow | 1 |
888 | 1 | quicksand | 1 |
889 | 2 | mud (grass, wet, sticky, soft periphyton) | 4 |
890 | 3 | scree / gravel | 2 |
891 | 4 | sand and loose dirt | 4 |
892 | 5 | compact dirt, clay, dry mud | 3 |
893 | 6 | algae and soft debris (seaweed, rubbish, bagasse, tar pit) | 6 |
894 | 7 | plastic mulch | 1 |
895 | 8 | parallax-only (named after POM), no physics material | 0 |
896 | 9 | gravel trap | 1 |
897 | 10 | wet sand | 1 |
898
899 So the 24 physics materials go to 10 of the 11 surfaces; the 6 surfaces without a material are entry 8 and the
900 5 empty slots. `SupportPropFlatten` is set on the 2 sand entries (4 and 10).
901- **Cross-check with the material table.** The retained part of `MaterialDataList` is one stream without its
902 head, kept as five contiguous fragments (four 64 KiB blocks and a short tail, 403 `name` elements in all).
903 All 14 `isDeformableTerrain` items of the stream are in the first fragment, and all are `"true"`. 13 of them
904 belong to exactly the 13 of the 24 surface materials whose names occur in the stream (all 13 names are in the
905 first fragment); the 14th belongs to a record whose name is before the start of the stream. No other record
906 carries the flag, and no surface material lacks it. The other 11 surface materials do not occur in the
907 retained stream.
908- **Deformation map size.** `GlobalDeepSurfaceParams` gives `DeformationWorldSpaceWidth` = **96 m** and
909 `ParallaxWorldSpaceWidth` = **48 m**: one world-space width each. The document gives no second dimension, so a
910 square window is an assumption, not a reading. No field in the document gives a texel count, and no other carved XML in
911 `common.rpf` names `DeformationWorldSpaceWidth`; the map resolution is therefore not in the data files read
912 here (it would be in the executable or the render-target setup, neither of which is in the package), so the
913 size in texels, and where the renderer sets it, stay open.
914- **Track types.** The 9 `TrackTypeData` entries are 1 human, 6 animals and 2 vehicles (a car class and a
915 cycle). `Type` is `kSnowTracksBiped` on 5 (the human and 4 animals, including the horse),
916 `kSnowTracksQuadraped` on 2 animals and `kSnowTracksVehicle` on the 2 vehicles. Which entry a given ped model
917 uses is not in this document.
918
919Not measured here (hypothesis): the texel resolution and the second dimension of the deformation map, where it is centred (camera or
920player), and how an entry is chosen at run time (the material's flag, the surface index, or both).
857 921
858## Map lights and the vehicle lane graph 922## Map lights and the vehicle lane graph
859 923
diff --git a/docs/world_lights_paths.md b/docs/world_lights_paths.md
index 07ef7f457..f619f9a33 100644
--- a/docs/world_lights_paths.md
+++ b/docs/world_lights_paths.md
@@ -80,6 +80,10 @@ with `scale = (scaleXY, scaleXY, scaleZ)`, the same transform `world_build.py --
80([world.md](world.md)). Directions are rotated without the translation. Entity lights are placed through 80([world.md](world.md)). Directions are rotated without the translation. Entity lights are placed through
81their own entity. 81their own entity.
82 82
83When an archetype is defined more than once, placement uses its first light list. The summary counts that
84archetype once in `archetype_light_definitions_differ` if any other list differs in length, order or decoded
85light fields, including the effect offset.
86
83| Measure | Count | 87| Measure | Count |
84|---|---:| 88|---|---:|
85| Map entities read (`world_index.py --entities-out`) | 1,670,435 | 89| Map entities read (`world_index.py --entities-out`) | 1,670,435 |
diff --git a/docs/world_names.md b/docs/world_names.md
index bd0a83b0d..1a4731c61 100644
--- a/docs/world_names.md
+++ b/docs/world_names.md
@@ -163,6 +163,8 @@ python -I tools\world_names.py resolve --dict <work>\world\names.json `
163 163
164`resolve` adds the counts of several `--archetypes` files, so make one whole-archive file rather than one per 164`resolve` adds the counts of several `--archetypes` files, so make one whole-archive file rather than one per
165window; `--rpf9-names` may be given once per window. 165window; `--rpf9-names` may be given once per window.
166When several `--maps` files cover different windows of the same world, a child in one can link
167to a parent map in another. Each child row counts once regardless of file order.
166 168
167`resolve` accepts `world_index`/`world_census` map JSON (or a row list) and an aggregate archetype file: 169`resolve` accepts `world_index`/`world_census` map JSON (or a row list) and an aggregate archetype file:
168 170
diff --git a/docs/xbox_d3d12_xs.md b/docs/xbox_d3d12_xs.md
new file mode 100644
index 000000000..8eea48de9
--- /dev/null
+++ b/docs/xbox_d3d12_xs.md
@@ -0,0 +1,895 @@
1# The `d3d12_xs` graphics ABI, from Microsoft's public GDK reference
2
3Status: reference, sourced. This page transcribes, for the items the D3D12-to-Vulkan layer proxies, the exact C
4signatures and constraints Microsoft publishes for the Xbox GDK graphics API, and names what the public reference does
5not cover. It is not a design document and not a reimplementation guide; [d3d12_vulkan.md](d3d12_vulkan.md) holds the
6plan and [d3d12_xs_surface.md](d3d12_xs_surface.md) holds the measured export surface.
7
8Source: <https://docs.xbox.com>. The site serves Markdown per page (append `.md`) behind plain-text indexes. The path
9taken was <https://docs.xbox.com/llms.txt> → <https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference.txt>
10→ the `d3d12` sub-index → the page URLs listed in each section below. All pages were read on 2026-11-23.
11
12How to read the quotes: **Documented** means the text block is copied from the page as published, including its
13inconsistencies. Where a published block contradicts itself or cannot be the real ABI, the item is marked **Doc
14quirk** and the reason is stated; nothing is silently corrected. **Not documented in the public GDK reference** means
15the page does not exist (404) or the index does not list it, and no value is guessed.
16
17## 1. What the reference covers
18
19The graphics index has two units: `d3d12` (520 pages) and `d3d12_xs` (7 pages). The console-specific pages are thin:
20six enums (`D3D_FEATURE_LEVEL`, `D3D_NAME`, `D3D_SHADER_INPUT_TYPE`, `D3D12_MESH_SHADER_TIER`,
21`D3D12_STANDARD_MULTISAMPLE_QUALITY_LEVELS`, `D3D12_WAVE_MMA_TIER`), one function (`D3D10CreateBlob`) and one struct
22(`DXGI_ADAPTER_DESC2`) ([index](https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference.txt)).
23
24Everything about root signatures, state objects, DXIL libraries, hit groups and shader caches lives in the `d3d12`
25unit and is labelled "(XBOX Series consoles)" in its title, with `Header: d3d12_xs.h` and `Library: d3d12_xs.lib` in
26its Requirements block. Those labels are the only machine-readable difference from the PC pages; the signatures are
27the PC shapes.
28
29The `d3d12_xs/interfaces/...` paths that several `See Also` links point at (`d3d12_xs/interfaces/ID3D12StateObject/...`,
30`d3d12_xs/interfaces/ID3D12PipelineState/id3d12pipelinestate_xs.md`, `d3d12_xs/interfaces/ID3D12CommandQueue/...`) all
31return 404, and the `_llms` index does not list them. **The console interface pages are not documented in the public
32GDK reference.**
33
34## 2. Root signatures
35
36### 2.1 `D3D12_LOCAL_ROOT_SIGNATURE`
37
38```cpp
39typedef struct D3D12_LOCAL_ROOT_SIGNATURE
40{
41 ID3D12RootSignature pLocalRootSignature;
42} D3D12_LOCAL_ROOT_SIGNATURE
43```
44
45`pLocalRootSignature` is "the root signature that will function as a local root signature. A state object holds a
46reference to this signature." The subobject is optional; the global plus local signatures attached to a shader
47function must cover every resource binding the shader declares, with no overlap. If one function in a call graph is
48associated with a local root signature, every other function in that graph must use the same one or none, and the
49shader entry (the graph root) must be associated with it, because all code reachable from an entry runs from a single
50shader record carrying one set of local root arguments.
51
52Requirements: `Header: d3d12_xs.h or d3d12_x.h`, `Library: d3d12_xs.lib or d3d12_x.lib`, both console families.
53Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_local_root_signature_public.md>
54
55**Doc quirk:** the block declares `ID3D12RootSignature pLocalRootSignature;` but the member table types it
56`ID3D12RootSignature *` and the prose says the state object "holds a reference". The published block has no pointer
57star and no trailing semicolon; that is a transcription of the page, not the header.
58
59### 2.2 `D3D12_GLOBAL_ROOT_SIGNATURE`
60
61```cpp
62typedef struct D3D12_GLOBAL_ROOT_SIGNATURE
63{
64 ID3D12RootSignature pGlobalRootSignature;
65} D3D12_GLOBAL_ROOT_SIGNATURE
66```
67
68Same no-overlap rule, stated per global signature. The page adds the console constraint that matters to a replay
69layer: every shader a particular
70[`DispatchRays`](https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12graphicscommandlist4/methods/id3d12graphicscommandlist4_dispatchrays_public.md)
71reaches from a command list must carry the same global root signature as the compute root signature bound on that
72command list, while one large state object may hold several global root signatures for different shader subsets.
73Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_global_root_signature_public.md>
74
75### 2.3 The graphics/compute root signature, shared with the PC shape
76
77```cpp
78typedef struct D3D12_ROOT_SIGNATURE_DESC
79{
80 UINT NumParameters;
81 const D3D12_ROOT_PARAMETER pParameters;
82 UINT NumStaticSamplers;
83 const D3D12_STATIC_SAMPLER_DESC pStaticSamplers;
84 D3D12_ROOT_SIGNATURE_FLAGS Flags;
85} D3D12_ROOT_SIGNATURE_DESC
86```
87
88`NumParameters` is "the number of slots in the root signature" and the length of `pParameters`. The page states that
89"there is one graphics root signature, and one compute root signature", and that this struct is consumed by
90`D3D12SerializeRootSignature` and returned by `ID3D12RootSignatureDeserializer::GetRootSignatureDesc`.
91Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_root_signature_desc_public.md>
92
93```cpp
94typedef struct D3D12_ROOT_PARAMETER
95{
96 D3D12_ROOT_PARAMETER_TYPE ParameterType;
97 D3D12_ROOT_DESCRIPTOR_TABLE DescriptorTable;
98 D3D12_ROOT_CONSTANTS Constants;
99 D3D12_ROOT_DESCRIPTOR Descriptor;
100 D3D12_SHADER_VISIBILITY ShaderVisibility;
101} D3D12_ROOT_PARAMETER
102```
103
104`ParameterType` selects the union member: `DescriptorTable` (ranges contiguous in a heap), `Constants` (inline
105constants that appear to the shader as one constant buffer), `Descriptor` (inline CBV/SRV/UAV). `ShaderVisibility`
106limits which shaders may read the slot.
107Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_root_parameter_public.md>
108
109```cpp
110typedef enum D3D12_ROOT_PARAMETER_TYPE
111{
112 D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE = 0,
113 D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS = 0,
114 D3D12_ROOT_PARAMETER_TYPE_CBV = 0,
115 D3D12_ROOT_PARAMETER_TYPE_SRV = 0,
116 D3D12_ROOT_PARAMETER_TYPE_UAV = 0
117} D3D12_ROOT_PARAMETER_TYPE
118```
119
120**Doc quirk, and the one that matters most to a traceless implementation:** every constant is published as `0`, so
121the page cannot be used to recover the numeric values. The prose still distinguishes the five slot kinds
122(descriptor table, 32-bit constants, CBV, SRV, UAV). Take the values from the header the title is compiled against,
123not from this page.
124Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_root_parameter_type_public.md>
125
126```cpp
127typedef enum D3D_ROOT_SIGNATURE_VERSION
128{
129 D3D_ROOT_SIGNATURE_VERSION_1 = 1,
130 D3D_ROOT_SIGNATURE_VERSION_1_0 = 1,
131 D3D_ROOT_SIGNATURE_VERSION_1_1 = 2
132} D3D_ROOT_SIGNATURE_VERSION
133```
134
1351.1 is the version that adds the `D3D12_ROOT_SIGNATURE_DESC1` / `D3D12_ROOT_PARAMETER1` / `D3D12_DESCRIPTOR_RANGE1`
136family; the page links Microsoft's "Root Signature Version 1.1" article but does not restate the differences.
137Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d_root_signature_version_public.md>
138
139```cpp
140HRESULT CreateRootSignature(
141 UINT nodeMask,
142 const void pBlobWithRootSignature,
143 SIZE_T blobLengthInBytes,
144 const IID & riid,
145 void ppvRootSignature
146)
147```
148
149`nodeMask` is zero for single-GPU operation. The blob is the serialized signature produced by
150`D3D12SerializeRootSignature`; `E_INVALIDARG` means the blob is invalid. Header `d3d12_xs.h or d3d12_x.h`.
151Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_createrootsignature_public.md>
152
153`ID3D12RootSignature` itself documents only that "currently, there is one graphics and one compute root signature per
154app" and that command lists link to the resources the shaders require.
155Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12rootsignature/id3d12rootsignature_public.md>
156
157### 2.4 How the console model differs from the PC model
158
159Three differences are documented:
160
161- **A second axis: global versus local.** On the console a root signature can be attached to a state object as a
162 subobject, and the pair (global, local) is what a shader function binds. The PC root signature has no such split;
163 it is the signature bound on the command list. (§2.1, §2.2.)
164- **State objects carry root signatures by reference.** `D3D12_LOCAL_ROOT_SIGNATURE` and
165 `D3D12_GLOBAL_ROOT_SIGNATURE` hold an `ID3D12RootSignature`, so a state object outlives and ref-counts the
166 signature it was built from.
167- **The graphics/compute signature stays the PC object.** `D3D12_ROOT_SIGNATURE_DESC`, `CreateRootSignature` and the
168 `SetGraphicsRootSignature`/`SetComputeRootSignature` pair are documented with the same shapes and the same
169 `d3d12_xs.h` header, so a console title serializes and creates signatures exactly as a PC title does before the
170 state-object path enters the picture.
171
172**User-data slots: not documented in the public GDK reference.** No page in the graphics index contains the term, no
173`D3D12_ROOT_PARAMETER_TYPE_USER_DATA`-style constant appears in the published enum, and the `D3D12_SHADER_VISIBILITY`
174and `D3D12_ROOT_PARAMETER` pages describe only the three inline kinds plus descriptor tables. What the reference does
175document is the inline-constant mechanism (`D3D12_ROOT_CONSTANTS`, exposed through
176`SetGraphicsRoot32BitConstant(s)` and `SetComputeRoot32BitConstant(s)`), so any console notion of a fixed user-data
177window per stage is outside this reference. The working model in this repository is measured, not documented:
178parameters are placed inline in user SGPRs from `s4` in root order while they fit whole, and the first that does not
179fit plus everything after it go into a packed array reached through a 40-bit pointer at `s[0:1]`
180([d3d12_vulkan.md §8.2 item 3](d3d12_vulkan.md#82-unknown--open-questions)).
181
182**`D3D12_ROOT_SIGNATURE_FLAGS`: not documented in the public GDK reference.** Both
183`d3d12/enums/d3d12_root_signature_flags_public.md` and `d3d12_xs/enums/d3d12_root_signature_flags_xs.md` return 404,
184although `D3D12_ROOT_SIGNATURE_DESC::Flags` is typed by it and the PC page links the Xbox name. The console flag
185values, including the high-byte bits this repository measures as `0x03000000`
186([d3d12_vulkan.md §8.2 item 19](d3d12_vulkan.md#82-unknown--open-questions)), have no public page.
187
188## 3. State objects, DXIL libraries and hit groups
189
190### 3.1 `D3D12_STATE_SUBOBJECT_TYPE`
191
192```cpp
193typedef enum D3D12_STATE_SUBOBJECT_TYPE
194{
195 D3D12_STATE_SUBOBJECT_TYPE_STATE_OBJECT_CONFIG = 0,
196 D3D12_STATE_SUBOBJECT_TYPE_GLOBAL_ROOT_SIGNATURE = 1,
197 D3D12_STATE_SUBOBJECT_TYPE_LOCAL_ROOT_SIGNATURE = 2,
198 D3D12_STATE_SUBOBJECT_TYPE_NODE_MASK = 3,
199 D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY = 5,
200 D3D12_STATE_SUBOBJECT_TYPE_EXISTING_COLLECTION = 6,
201 D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION = 7,
202 D3D12_STATE_SUBOBJECT_TYPE_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION = 8,
203 D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_SHADER_CONFIG = 9,
204 D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG = 10,
205 D3D12_STATE_SUBOBJECT_TYPE_HIT_GROUP = 11,
206 D3D12_STATE_SUBOBJECT_TYPE_MAX_VALID = 0
207} D3D12_STATE_SUBOBJECT_TYPE
208```
209
210The console-relevant constraint in the constant table: a `NODE_MASK` subobject carrying node `0` is mishandled by
211some runtime versions (it should mean node 1), so the page says to write an explicit `1` or omit the subobject.
212Requirements say `Header: d3d12_x.h`, `Library: d3d12_x.lib`, `Supported Platforms: XBOX One family`, which conflicts
213with the other state-object pages that say `d3d12_xs`; treat the header line as a copy of the Xbox One page.
214
215**Doc quirk:** `D3D12_STATE_SUBOBJECT_TYPE_MAX_VALID` is published as `0`, which collides with
216`STATE_OBJECT_CONFIG`. `4` is unused in the list; the page does not say why and does not name a type 4.
217Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_state_subobject_type_public.md>
218
219### 3.2 `D3D12_DXIL_LIBRARY_DESC`
220
221```cpp
222typedef struct D3D12_DXIL_LIBRARY_DESC
223{
224 D3D12_SHADER_BYTECODE DXILLibrary;
225 UINT NumExports;
226 D3D12_EXPORT_DESC pExports;
227} D3D12_DXIL_LIBRARY_DESC
228```
229
230Constraints the page states:
231
232- `DXILLibrary` "must have been compiled with library target 6.3 or higher".
233- The same library may appear several times in one state object or collection, or across collections, "as long as the
234 names exported each time don't conflict in a given state object".
235- `NumExports` is the length of `pExports`; `0` means "everything gets exported from the library".
236- `pExports` is optional. Requirements: `Header: d3d12_xs.h`, `Library: d3d12_xs.lib`, `XBOX Series consoles`.
237
238Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_dxil_library_desc_public.md>
239
240```cpp
241typedef struct D3D12_SHADER_BYTECODE
242{
243 const void pShaderBytecode;
244 SIZE_T BytecodeLength;
245} D3D12_SHADER_BYTECODE
246```
247
248The bytecode pointer is opaque to the API and may be a whole compiled blob as loaded from disk. This is the type the
249library, the compute PSO and the graphics PSO all carry their programs in.
250Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_shader_bytecode_public.md>
251
252### 3.3 `D3D12_EXPORT_DESC` and `D3D12_EXPORT_FLAGS`
253
254```cpp
255typedef struct D3D12_EXPORT_DESC
256{
257 LPCWSTR Name;
258 LPCWSTR ExportToRename;
259 D3D12_EXPORT_FLAGS Flags;
260} D3D12_EXPORT_DESC
261```
262
263`Name` is the export name; for an overloaded function a compiler-modified name (retrievable from HLSL reflection)
264disambiguates. With a non-null `ExportToRename`, `Name` is the new name and must be the unmodified one, while
265`ExportToRename` may be modified or unmodified; one internal name may be exported several times under different
266renames.
267Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_export_desc_public.md>
268
269```cpp
270typedef enum D3D12_EXPORT_FLAGS
271{
272 D3D12_EXPORT_FLAG_NONE = 0
273} D3D12_EXPORT_FLAGS
274```
275
276The page states plainly that "no export flags are defined in the current release", so a layer can reject every
277non-zero flag value it sees on the console build without losing documented behaviour.
278Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_export_flags_public.md>
279
280### 3.4 `D3D12_HIT_GROUP_DESC` and `D3D12_HIT_GROUP_TYPE`
281
282```cpp
283typedef struct D3D12_HIT_GROUP_DESC
284{
285 LPCWSTR HitGroupExport;
286 D3D12_HIT_GROUP_TYPE Type;
287 LPCWSTR AnyHitShaderImport;
288 LPCWSTR ClosestHitShaderImport;
289 LPCWSTR IntersectionShaderImport;
290} D3D12_HIT_GROUP_DESC
291```
292
293`AnyHitShaderImport` and `ClosestHitShaderImport` are optional and legal for every hit-group type.
294`IntersectionShaderImport` is optional and legal only for a procedural-primitive hit group.
295Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_hit_group_desc_public.md>
296
297```cpp
298typedef enum D3D12_HIT_GROUP_TYPE
299{
300 D3D12_HIT_GROUP_TYPE_TRIANGLES = 0,
301 D3D12_HIT_GROUP_TYPE_PROCEDURAL_PRIMITIVE = 1
302} D3D12_HIT_GROUP_TYPE
303```
304
305A triangle hit group "can't contain an intersection shader"; a procedural-primitive hit group "must contain" one.
306Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_hit_group_type_public.md>
307
308### 3.5 The two raytracing configuration subobjects
309
310```cpp
311typedef struct D3D12_RAYTRACING_SHADER_CONFIG
312{
313 UINT MaxPayloadSizeInBytes;
314 UINT MaxAttributeSizeInBytes;
315} D3D12_RAYTRACING_SHADER_CONFIG
316```
317
318`MaxPayloadSizeInBytes` is the payload budget in scalars of 4 bytes; `MaxAttributeSizeInBytes` is the attribute
319budget, capped at `D3D12_RAYTRACING_MAX_ATTRIBUTE_SIZE_IN_BYTES`. A pipeline needs one such configuration; if several
320are present, for example one per collection so each compiles early, they must all match when combined.
321Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_raytracing_shader_config_public.md>
322
323```cpp
324typedef struct D3D12_RAYTRACING_PIPELINE_CONFIG
325{
326 UINT MaxTraceRecursionDepth;
327} D3D12_RAYTRACING_PIPELINE_CONFIG
328```
329
330The recursion limit "must be in the range of 0 to 31"; a `TraceRay` at the limit puts the device into removed state.
331Duplicating this subobject per collection buys no early compilation, unlike the shader config above.
332Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_raytracing_pipeline_config_public.md>
333
334### 3.6 The state-object container
335
336```cpp
337typedef struct D3D12_STATE_OBJECT_DESC
338{
339 D3D12_STATE_OBJECT_TYPE Type;
340 UINT NumSubobjects;
341 const D3D12_STATE_SUBOBJECT pSubobjects;
342} D3D12_STATE_OBJECT_DESC
343```
344
345Passed to `ID3D12Device5::CreateStateObject`; `NumSubobjects` is the length of `pSubobjects`.
346Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_state_object_desc_public.md>
347
348```cpp
349typedef struct D3D12_STATE_SUBOBJECT
350{
351 D3D12_STATE_SUBOBJECT_TYPE Type;
352 const void pDesc;
353} D3D12_STATE_SUBOBJECT
354```
355
356`Type` selects the meaning and layout of `pDesc`. The related-topics block of this page links
357`d3d12_xs/enums/d3d12_state_subobject_type_xs.md`, which 404s; the live page is the `d3d12` one in §3.1.
358Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_state_subobject_public.md>
359
360```cpp
361typedef enum D3D12_STATE_OBJECT_TYPE
362{
363 D3D12_STATE_OBJECT_TYPE_COLLECTION = 0,
364 D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE = 3
365} D3D12_STATE_OBJECT_TYPE
366```
367
368Two values only: a collection, and a raytracing pipeline. Value 3 with no documented 1 or 2 is what the page
369publishes; the enum is shared with the PC shape, where those numbers historically held graphics and compute state
370objects. A collection is the unit `D3D12_EXISTING_COLLECTION_DESC` re-exports.
371Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_state_object_type_public.md>
372
373```cpp
374typedef struct D3D12_EXISTING_COLLECTION_DESC
375{
376 ID3D12StateObject pExistingCollection;
377 UINT NumExports;
378 D3D12_EXPORT_DESC pExports;
379} D3D12_EXISTING_COLLECTION_DESC
380```
381
382The enclosing object ref-counts the collection; `NumExports` 0 exports the whole collection.
383Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_existing_collection_desc_public.md>
384
385```cpp
386typedef struct D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION
387{
388 const D3D12_STATE_SUBOBJECT pSubobjectToAssociate;
389 UINT NumExports;
390 LPCWSTR pExports;
391} D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION
392```
393
394This is how a local root signature, a shader config or another subobject is bound to named exports. `NumExports == 0`
395declares a default association, which is also what omitting the subobject means. With cross-linkage opted into
396through `D3D12_STATE_OBJECT_CONFIG`, an associated export need not exist yet in the current state object and is
397resolved later, at RTPSO creation.
398Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_subobject_to_exports_association_public.md>
399
400```cpp
401typedef struct D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION
402{
403 LPCWSTR SubobjectToAssociate;
404 UINT NumExports;
405 LPCWSTR pExports;
406} D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION
407```
408
409The whole page is one sentence: "this subobject is unsupported in the current release." It is still a valid
410`D3D12_STATE_SUBOBJECT_TYPE` value (8), so a layer sees the type and must reject it rather than guess semantics.
411Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_dxil_subobject_to_exports_association_public.md>
412
413### 3.7 Creating and querying a state object
414
415```cpp
416HRESULT CreateStateObject(
417 const D3D12_STATE_OBJECT_DESC pDesc,
418 const IID & riid,
419 void ppStateObject
420)
421```
422
423On `ID3D12Device5`. `riid` is `__uuidof(ID3D12StateObject)`. Documented failures: `E_INVALIDARG` for a bad input,
424`E_OUTOFMEMORY` for the handle. Header `d3d12_xs.h`, `Library: d3d12_xs.lib`, `XBOX Series consoles`.
425Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device5/methods/id3d12device5_createstateobject_public.md>
426
427```cpp
428const GetShaderIdentifier(
429 LPCWSTR pExportName
430)
431```
432
433On `ID3D12StateObjectProperties`. Returns a pointer to the shader identifier, valid while the state object lives, of
434`D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES`; the page recommends copying and caching it. The identifier is global to the
435shader, so the same shader in another state object with the same associations yields the same bytes, and the return
436is `nullptr` when the shader is not fully resolved.
437
438**Doc quirk:** the block omits the return type and the parameter star (`const GetShaderIdentifier(`), and the return
439value is described only as "Type: const". The prose is consistent with `const void* GetShaderIdentifier(LPCWSTR)`.
440Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12stateobjectproperties/methods/id3d12stateobjectproperties_getshaderidentifier_public.md>
441
442`ID3D12StateObjectProperties` also documents `GetShaderStackSize`, `GetPipelineStackSize` and `SetPipelineStackSize`
443for raytracing stack management
444([index](https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference/d3d12/interfaces.txt)).
445
446### 3.8 Ray-tracing library shapes
447
448The public reference documents the building blocks above and stops there. What is missing, and therefore what a layer
449cannot take from this source:
450
451- **No console RTPSO page.** `D3D12_RAYTRACING_PIPELINE_CONFIG`, `..._SHADER_CONFIG`, hit groups and the DXIL library
452 are described with PC semantics plus the console global/local root signature rules; no page describes an
453 Xbox-specific pipeline layout, shader-table format or offline pipeline object.
454- **The conceptual XDXR pages are NDA-gated.** `.../graphics/newfeatures/raytracing/index.md` is public and lists
455 cards for BVH builders, BVH compression, k-DOP and offline RTPSO, but fetching `rt-offlinertpso.md` or `rt-xdxr.md`
456 returns Microsoft's "Access restricted" page: the content requires an Xbox developer program sign-in
457 ([raytracing index](https://docs.xbox.com/build/core-features/graphics/newfeatures/raytracing/index.md)).
458- **Shader tables have no page.** `D3D12_DISPATCH_RAYS_DESC` exists in the index and `GetShaderIdentifier` describes a
459 shader record as a blob the app fills in GPU memory, but no page in the graphics reference specifies the
460 record layout beyond the identifier size constant.
461
462## 4. Shader cache sessions
463
464### 4.1 Creation
465
466```cpp
467HRESULT CreateShaderCacheSession(
468 const D3D12_SHADER_CACHE_SESSION_DESC pDesc,
469 const IID & riid,
470 void ppvSession
471)
472```
473
474On `ID3D12Device9`. Returns `DXGI_ERROR_ALREADY_EXISTS` when "you tried to create a cache with an existing
475identifier", which the description below qualifies to the case where sessions are still open. `riid` receives an
476`ID3D12ShaderCacheSession`. Header `d3d12_xs.h`, `Library: d3d12_xs.lib`, `XBOX Series consoles`.
477Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device9/methods/id3d12device9_createshadercachesession_public.md>
478
479```cpp
480typedef struct D3D12_SHADER_CACHE_SESSION_DESC
481{
482 GUID Identifier;
483 D3D12_SHADER_CACHE_MODE Mode;
484 D3D12_SHADER_CACHE_FLAGS Flags;
485 UINT MaximumInMemoryCacheSizeBytes;
486 UINT MaximumInMemoryCacheEntries;
487 UINT MaximumValueFileSizeBytes;
488 UINT64 Version;
489} D3D12_SHADER_CACHE_SESSION_DESC
490```
491
492The documented semantics of each field:
493
494- `Identifier`: caches with different identifiers are stored side by side; caches with the same identifier are shared
495 by all sessions in the process. Creating a disk cache with an existing identifier opens that cache unless `Version`
496 differs, in which case it is wiped and re-created if no other session holds it; if others do, creation fails with
497 `DXGI_ERROR_ALREADY_EXISTS`.
498- `Mode`: memory or disk (§4.2).
499- `Flags`: modifier bits (§4.3).
500- `MaximumInMemoryCacheSizeBytes`: for a memory cache the whole budget; for a disk cache the size of the staging area
501 that holds stored and found entries until newer ones evict them. **Default 1 KB.**
502- `MaximumInMemoryCacheEntries`: how many entries fit in that memory. **Default 128.**
503- `MaximumValueFileSizeBytes`: disk-cache maximum file size. **Default 128 MB.**
504- `Version`: mismatch wipes and re-creates the cache, which is the intended way to invalidate after an app update.
505
506Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_shader_cache_session_desc_public.md>
507
508### 4.2 `D3D12_SHADER_CACHE_MODE`
509
510```cpp
511typedef enum D3D12_SHADER_CACHE_MODE
512{
513 D3D12_SHADER_CACHE_MODE_MEMORY = 0,
514 D3D12_SHADER_CACHE_MODE_DISK = 0
515} D3D12_SHADER_CACHE_MODE
516```
517
518`MEMORY`: no backing file, stores are discarded with the session. `DISK`: files persist across runs until cleared
519(§4.5).
520
521**Doc quirk:** both values are published as `0`, so the page cannot be used to tell the two modes apart numerically.
522It is a transcription error in the page; a layer should accept the host runtime's value rather than assume 0 means
523disk or memory.
524Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_mode_public.md>
525
526### 4.3 `D3D12_SHADER_CACHE_FLAGS`
527
528```cpp
529typedef enum D3D12_SHADER_CACHE_FLAGS
530{
531 D3D12_SHADER_CACHE_FLAG_NONE = 0,
532 D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED = 1,
533 D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR = 2
534} D3D12_SHADER_CACHE_FLAGS
535```
536
537`DRIVER_VERSIONED` makes the cache implicitly versioned per driver, stored side by side per adapter on multi-GPU
538systems, with `Version` as an extra constraint. `USE_WORKING_DIR` moves the cache from temporary storage (subject to
539disk cleanup) into the current working directory, and is "not valid for UWP apps".
540Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_flags_public.md>
541
542### 4.4 The session object
543
544`ID3D12ShaderCacheSession` "represents a shader cache session", is listed under `ID3D12DeviceChild` in its See Also,
545and declares four methods ([interface list](https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference/d3d12/interfaces.txt)):
546
547```cpp
548HRESULT StoreValue(
549 const void pKey,
550 UINT KeySize,
551 const void pValue,
552 UINT ValueSize
553)
554```
555
556Adds an entry. `DXGI_ERROR_ALREADY_EXISTS` for a duplicate key, `DXGI_ERROR_CACHE_HASH_COLLISION` when the hash
557matches but the key does not, `DXGI_ERROR_CACHE_FULL` when the insertion would exceed the maximum size.
558Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12shadercachesession/methods/id3d12shadercachesession_storevalue_public.md>
559
560```cpp
561HRESULT FindValue(
562 const void pKey,
563 UINT KeySize,
564 void pValue,
565 UINT pValueSize
566)
567```
568
569Exact-key lookup, called twice: once for the size, once for the data. Errors are
570`DXGI_ERROR_CACHE_HASH_COLLISION` and `DXGI_ERROR_NOT_FOUND`. The page notes that in-memory temporary storage makes
571the two-call pattern cheap.
572Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12shadercachesession/methods/id3d12shadercachesession_findvalue_public.md>
573
574```cpp
575D3D12_SHADER_CACHE_SESSION_DESC GetDesc(
576)
577```
578
579Returns the description the session was created with.
580Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12shadercachesession/methods/id3d12shadercachesession_getdesc_public.md>
581
582`SetDeleteOnDestroy`: when all sessions for a cache are destroyed, the cache is cleared. The Remarks list the five
583documented ways a disk cache can be cleared, and the on-disk file extensions (`*.idx`, `*.val`, `*.lock`) that only
584`USE_WORKING_DIR` caches may be deleted by hand.
585Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12shadercachesession/methods/id3d12shadercachesession_setdeleteondestroy_public.md>
586
587### 4.5 `ID3D12Device9::ShaderCacheControl`
588
589```cpp
590HRESULT ShaderCacheControl(
591 D3D12_SHADER_CACHE_KIND_FLAGS Kinds,
592 D3D12_SHADER_CACHE_CONTROL_FLAGS Control
593)
594```
595
596"May be used only in developer mode." `DISABLE` and `ENABLE` cannot be combined, and at least one flag is required.
597Any of the named caches may or may not exist.
598Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device9/methods/id3d12device9_shadercachecontrol_public.md>
599
600```cpp
601typedef enum D3D12_SHADER_CACHE_KIND_FLAGS
602{
603 D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER = 1,
604 D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CONVERSIONS = 2,
605 D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED = 4,
606 D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED = 8
607} D3D12_SHADER_CACHE_KIND_FLAGS
608```
609
610`APPLICATION_MANAGED` covers every session created by `CreateShaderCacheSession`, and a `CLEAR` on it also clears
611on-disk caches created without `USE_WORKING_DIR`.
612Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_kind_flags_public.md>
613
614```cpp
615typedef enum D3D12_SHADER_CACHE_CONTROL_FLAGS
616{
617 D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE = 1,
618 D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE = 2,
619 D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR = 4
620} D3D12_SHADER_CACHE_CONTROL_FLAGS
621```
622
623`DISABLE` also makes an attempt to use or create a cache return `DXGI_ERROR_NOT_CURRENTLY_AVAILABLE`.
624Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_control_flags_public.md>
625
626### 4.6 Support flags and the pipeline-library gate
627
628```cpp
629typedef enum D3D12_SHADER_CACHE_SUPPORT_FLAGS
630{
631 D3D12_SHADER_CACHE_SUPPORT_NONE = 0,
632 D3D12_SHADER_CACHE_SUPPORT_SINGLE_PSO = 1,
633 D3D12_SHADER_CACHE_SUPPORT_LIBRARY = 2,
634 D3D12_SHADER_CACHE_SUPPORT_AUTOMATIC_INPROC_CACHE = 4,
635 D3D12_SHADER_CACHE_SUPPORT_AUTOMATIC_DISK_CACHE = 8
636} D3D12_SHADER_CACHE_SUPPORT_FLAGS
637```
638
639`SINGLE_PSO` (the `CachedPSO` member of the PSO descriptions) "is always supported"; `LIBRARY` is what gates
640`ID3D12PipelineLibrary`.
641Source: <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_support_flags_public.md>
642
643`D3D12_FEATURE_DATA_SHADER_CACHE` is a single `SupportFlags` field, answered by `CheckFeatureSupport` under
644`D3D12_FEATURE_SHADER_CACHE`.
645Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_feature_data_shader_cache_public.md>
646
647### 4.7 Documented limits
648
649| Limit | Value | Source |
650|---|---|---|
651| In-memory staging size, default | 1 KB | [session desc](https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_shader_cache_session_desc_public.md) |
652| In-memory entries, default | 128 | [session desc](https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_shader_cache_session_desc_public.md) |
653| Disk value file, default | 128 MB | [session desc](https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_shader_cache_session_desc_public.md) |
654| Key/value sizes | no documented cap; failures surface as `DXGI_ERROR_CACHE_FULL` | [StoreValue](https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12shadercachesession/methods/id3d12shadercachesession_storevalue_public.md) |
655| Console-specific cache sizes or memory budget | not documented in the public GDK reference | — |
656
657## 5. Device, queue and pipeline creation entry points
658
659### 5.1 Device
660
661**`D3D12CreateDevice` is not documented in the public GDK graphics reference.**
662`d3d12/functions/d3d12createdevice_public.md` returns 404 and the functions index lists only six free functions:
663`D3D12CreateRootSignatureDeserializer`, `D3D12CreateVersionedRootSignatureDeserializer`,
664`D3D12EnableExperimentalFeatures`, `D3D12GetDebugInterface`, `D3D12GetInterface`, `D3D12SerializeRootSignature`
665([functions list](https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference/d3d12.txt)). The console entry
666point this project calls `D3D12XboxCreateDevice` (exported by `d3d12_xs.dll` as `D3D12ConsCreateDevice`, see
667[d3d12_xs_surface.md §2.1](d3d12_xs_surface.md)) has no page under either name.
668
669What is documented next to it is the interface selector:
670
671```cpp
672HRESULT D3D12GetInterface(
673 const IID & rclsid,
674 const IID & riid,
675 void ppvDebug
676)
677```
678
679"Selects an SDK version at runtime when the system is in Windows Developer Mode." The page defines four CLSIDs
680(`CLSID_D3D12Debug`, `CLSID_D3D12Tools`, `CLSID_D3D12DeviceRemovedExtendedData`, `CLSID_D3D12SDKConfiguration`) with
681their GUID words and maps each to an interface. It creates no device.
682Source: <https://docs.xbox.com/reference/graphics/d3d12/functions/d3d12getinterface_public.md>
683
684### 5.2 Command queue
685
686```cpp
687HRESULT CreateCommandQueue(
688 const D3D12_COMMAND_QUEUE_DESC pDesc,
689 const IID & riid,
690 void ppCommandQueue
691)
692```
693
694The desc:
695
696```cpp
697typedef struct D3D12_COMMAND_QUEUE_DESC
698{
699 D3D12_COMMAND_LIST_TYPE Type;
700 INT Priority;
701 D3D12_COMMAND_QUEUE_FLAGS Flags;
702 UINT NodeMask;
703} D3D12_COMMAND_QUEUE_DESC
704```
705
706`Priority` is a `D3D12_COMMAND_QUEUE_PRIORITY` constant, `NodeMask` must set exactly one bit, and `NodeMask` 0 means
707the single-GPU case. The same struct is returned by `ID3D12CommandQueue::GetDesc`. `ID3D12Device9::CreateCommandQueue1`
708adds a creator ID and is documented separately.
709Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_command_queue_desc_public.md>,
710<https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_createcommandqueue_public.md>
711
712### 5.3 Compute and graphics PSOs
713
714```cpp
715HRESULT CreateComputePipelineState(
716 const D3D12_COMPUTE_PIPELINE_STATE_DESC pDesc,
717 const IID & riid,
718 void ppPipelineState
719)
720```
721
722```cpp
723typedef struct D3D12_COMPUTE_PIPELINE_STATE_DESC
724{
725 ID3D12RootSignature pRootSignature;
726 D3D12_SHADER_BYTECODE CS;
727 UINT NodeMask;
728 D3D12_CACHED_PIPELINE_STATE CachedPSO;
729 D3D12_PIPELINE_STATE_FLAGS Flags;
730} D3D12_COMPUTE_PIPELINE_STATE_DESC
731```
732
733`CachedPSO` may be null/zero. `Flags` is typed by `D3D12_PIPELINE_STATE_FLAGS`, whose page is one of the 404s
734(`d3d12_xs/enums/d3d12_pipeline_state_flags_xs.md`). The returned object is immutable and "contains no methods".
735Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_createcomputepipelinestate_public.md>,
736<https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_compute_pipeline_state_desc_public.md>
737
738```cpp
739HRESULT CreateGraphicsPipelineState(
740 const D3D12_GRAPHICS_PIPELINE_STATE_DESC pDesc,
741 const IID & riid,
742 void ppPipelineState
743)
744```
745
746Same return contract (`E_OUTOFMEMORY` and the standard D3D12 codes) and the same immutable result. The graphics desc
747page is linked as `d3d12_x/structs/d3d12_graphics_pipeline_state_desc.md`, which is not part of the public `d3d12`
748index, so the field list is **not documented in the public GDK reference**.
749Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_creategraphicspipelinestate_public.md>
750
751**The stream-desc PSO has no page.** `D3D12_PIPELINE_STATE_STREAM_DESC` is documented and its Remarks name
752`ID3D12Device2::CreatePipelineState` as the consumer, but that method's page is absent: the
753`ID3D12Device2` entry in the interfaces index carries no methods, and
754`.../id3d12device2/methods/id3d12device2_createpipelinestate_public.md` returns 404. The struct itself is specified in
755full, including the alignment rule:
756
757```cpp
758typedef struct D3D12_PIPELINE_STATE_STREAM_DESC
759{
760 SIZE_T SizeInBytes;
761 void pPipelineStateSubobjectStream;
762} D3D12_PIPELINE_STATE_STREAM_DESC
763```
764
765The stream is "an alternating set of `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE`" and its subobject, each pair aligned to
766the natural word alignment (`alignas(void*)` or a union of the whole subobject with `void*`, not of the enum alone,
767which misaligns types such as `D3D12_PRIMITIVE_TOPOLOGY_TYPE`). The pipeline kind (COMPUTE, GRAPHICS, MESH) is
768inferred from which of VS/CS/MS is non-null; none or more than one fails creation. Irrelevant subobjects are ignored,
769missing ones take defaults, duplicate or derived-duplicate subobjects fail validation.
770Source: <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_pipeline_state_stream_desc_public.md>
771
772**`D3D12_PIPELINE_STATE_SUBOBJECT_TYPE` is not documented in the public GDK reference**; its page is linked as
773`d3d12_x/enums/d3d12_pipeline_state_subobject_type.md` and is not in the index.
774
775### 5.4 Pipeline libraries
776
777```cpp
778HRESULT CreatePipelineLibrary(
779 const void pLibraryBlob,
780 SIZE_T BlobLength,
781 const IID & riid,
782 void ppPipelineLibrary
783)
784```
785
786On `ID3D12Device1`. Gate it on `CheckFeatureSupport(D3D12_FEATURE_SHADER_CACHE)` returning
787`D3D12_SHADER_CACHE_SUPPORT_LIBRARY`, otherwise the call always returns `DXGI_ERROR_NOT_SUPPORTED`. A non-empty blob
788is validated and parsed but not copied, so the caller must keep it alive for the library's lifetime; an empty blob
789starts an empty library. Documented failures: `E_INVALIDARG` (corrupt or unrecognised blob),
790`D3D12_ERROR_DRIVER_VERSION_MISMATCH` (data from an old driver or runtime), `D3D12_ERROR_ADAPTER_NOT_FOUND` (data
791from other hardware). Passing `nullptr` for the output validates the blob and returns `S_FALSE`.
792Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device1/methods/id3d12device1_createpipelinelibrary_public.md>
793
794```cpp
795HRESULT StorePipeline(
796 LPCWSTR pName,
797 ID3D12PipelineState pPipeline
798)
799```
800
801Adds a PSO under a unique name; overwriting is unsupported, and `E_INVALIDARG` means the name exists.
802Source: <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12pipelinelibrary/methods/id3d12pipelinelibrary_storepipeline_public.md>
803
804### 5.5 Present
805
806**Presentation is not documented in the public GDK graphics reference.** The graphics API index contains only
807`d3d12` and `d3d12_xs`, and the only DXGI item in either is `DXGI_ADAPTER_DESC2` under `d3d12_xs/structs`; there is no
808`IDXGISwapChain`, `DXGI_PRESENT` or `PresentX` page. The console's present entry point (`PresentX` in this
809repository's usage, [d3d12_command_objects.md](d3d12_command_objects.md)) and its frame-event handshake have no
810public page under any URL form tried, including `d3d12/functions/d3d12createdevice_public.md`'s neighbours.
811
812## 6. What this means for Leonida
813
814Mapping the documented surface onto what the layer does today. Each row names the code that would change; "gap"
815means the code is absent, not that the API is undocumented.
816
817| Area | Documented contract | State in this repository | Consequence |
818|---|---|---|---|
819| Root signature blobs | `D3D12_ROOT_SIGNATURE_DESC` 1.0/1.1, `D3D_ROOT_SIGNATURE_VERSION`, `CreateRootSignature` (§2.3) | `runtime/shims/d3d12_xs_rootsig.cpp` rewrites the measured `0x03000000` high byte and downgrades 1.2 to 1.1 before forwarding to the host serializer | Correct as a forwarding shim; the console flag semantics stay unknown because the flags enum is not published (§2.4) |
820| Console root parameters to `s0..s31` | Only `D3D12_ROOT_PARAMETER`'s three inline kinds are published; no user-data slot type (§2.4) | Measured model: inline from `s4`, spill array via a 40-bit pointer at `s[0:1]` ([d3d12_vulkan.md §8.2](d3d12_vulkan.md#82-unknown--open-questions)) | The layer cannot cite a document for the mapping; the shader-side check stays the only test |
821| State objects and RTPSOs | `CreateStateObject`, subobject enum, DXIL library, hit groups, shader/pipeline configs (§3) | No `CreateStateObject`, `DispatchRays` or `GetShaderIdentifier` in `runtime/shims/d3d12_vulkan_device.cpp` | Full DXR stays unimplemented; `RaytracingTier` is answered `NOT_SUPPORTED` and that answer is what the game reacts to |
822| DXIL library exports | Library target 6.3+, `NumExports == 0` means export all, `D3D12_EXPORT_FLAG_NONE` is the only flag (§3.2, §3.3) | Not reached: no state-object path | When a state object path is added, the export-set and rename rules are the part a translator must preserve to keep `GetShaderIdentifier` stable |
823| Graphics PSOs | `CreateGraphicsPipelineState` with `D3D12_GRAPHICS_PIPELINE_STATE_DESC`; the stream desc's alignment and kind-inference rules (§5.3) | Desc-form creation exists in `d3d12_vulkan_device.cpp`; the stream-desc `CreatePipelineState` is not implemented there (only `LoadPipeline` consumes a stream desc) | A title that builds PSOs through `ID3D12Device2` needs that path; the documented alignment rule is the spec for it |
824| Compute PSO on the console slot | `CreateComputePipelineState` (§5.3) | `d3d12_xs_device.cpp` proxies PC slots 10/11 plus the measured console compute-PSO slot 62 | The console-only entry point has three documented equivalents (compute, graphics, state object); the slot's arity is measured, not documented |
825| Draws and dispatch | `DrawInstanced`, `DrawIndexedInstanced`, `Dispatch`, root-argument setters (interfaces index) | Present and GPU-tested ([first_light.md](first_light.md)) | Nothing to change from the documentation side |
826| Shader cache | Session desc with its three documented defaults, `StoreValue`/`FindValue` two-call pattern, `ShaderCacheControl` in developer mode, library gate (§4) | Implemented with `ID3D12Device9::CreateShaderCacheSession`, the session object and `ShaderCacheControl` (D3D-34, `runtime/test/d3d12_shader_cache_test.cpp`) | The defaults (1 KB / 128 entries / 128 MB) are the numbers the layer must reproduce for a host-parity answer |
827| Present | No page (§5.5) | `runtime/shims/xbox_present.cpp` plus a DXGI swapchain fallback | The layer's presenter is built on measurement; there is no document to check it against |
828| Device creation | No `D3D12CreateDevice` page; `D3D12GetInterface` only (§5.1) | `D3D12XboxCreateDevice` with an unmeasured 24-word params block | Params and flags stay open; nothing in the public reference narrows them |
829
830Two consequences follow for how this documentation is used. First, the parts a replay layer needs most precisely
831(the enum values) are the parts this reference publishes worst: three enums in this page print colliding or all-zero
832constants, and two enum pages do not exist. Values must come from the header the layer is compiled against, with the
833prose here used only for meaning. Second, the console-specific behaviour the layer actually depends on, the root
834signature to user-SGPR mapping and the present path, is exactly what Microsoft keeps out of the public reference, so
835the measured notes in [d3d12_vulkan.md](d3d12_vulkan.md) and [d3d12_command_objects.md](d3d12_command_objects.md)
836remain the operative source for those two.
837
838## 7. Pages used
839
840| Page | URL |
841|---|---|
842| Graphics API reference | <https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference.txt> |
843| `d3d12` index | <https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference/d3d12.txt> |
844| `d3d12` interfaces index | <https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference/d3d12/interfaces.txt> |
845| `D3D12_LOCAL_ROOT_SIGNATURE` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_local_root_signature_public.md> |
846| `D3D12_GLOBAL_ROOT_SIGNATURE` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_global_root_signature_public.md> |
847| `D3D12_ROOT_SIGNATURE_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_root_signature_desc_public.md> |
848| `D3D12_ROOT_PARAMETER` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_root_parameter_public.md> |
849| `D3D12_ROOT_PARAMETER_TYPE` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_root_parameter_type_public.md> |
850| `D3D_ROOT_SIGNATURE_VERSION` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d_root_signature_version_public.md> |
851| `CreateRootSignature` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_createrootsignature_public.md> |
852| `ID3D12RootSignature` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12rootsignature/id3d12rootsignature_public.md> |
853| `D3D12_STATE_SUBOBJECT_TYPE` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_state_subobject_type_public.md> |
854| `D3D12_DXIL_LIBRARY_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_dxil_library_desc_public.md> |
855| `D3D12_SHADER_BYTECODE` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_shader_bytecode_public.md> |
856| `D3D12_EXPORT_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_export_desc_public.md> |
857| `D3D12_EXPORT_FLAGS` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_export_flags_public.md> |
858| `D3D12_HIT_GROUP_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_hit_group_desc_public.md> |
859| `D3D12_HIT_GROUP_TYPE` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_hit_group_type_public.md> |
860| `D3D12_RAYTRACING_SHADER_CONFIG` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_raytracing_shader_config_public.md> |
861| `D3D12_RAYTRACING_PIPELINE_CONFIG` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_raytracing_pipeline_config_public.md> |
862| `D3D12_STATE_OBJECT_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_state_object_desc_public.md> |
863| `D3D12_STATE_SUBOBJECT` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_state_subobject_public.md> |
864| `D3D12_STATE_OBJECT_TYPE` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_state_object_type_public.md> |
865| `D3D12_EXISTING_COLLECTION_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_existing_collection_desc_public.md> |
866| `D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_subobject_to_exports_association_public.md> |
867| `D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_dxil_subobject_to_exports_association_public.md> |
868| `CreateStateObject` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device5/methods/id3d12device5_createstateobject_public.md> |
869| `GetShaderIdentifier` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12stateobjectproperties/methods/id3d12stateobjectproperties_getshaderidentifier_public.md> |
870| `CreateShaderCacheSession` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device9/methods/id3d12device9_createshadercachesession_public.md> |
871| `ShaderCacheControl` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device9/methods/id3d12device9_shadercachecontrol_public.md> |
872| `D3D12_SHADER_CACHE_SESSION_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_shader_cache_session_desc_public.md> |
873| `D3D12_SHADER_CACHE_MODE` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_mode_public.md> |
874| `D3D12_SHADER_CACHE_FLAGS` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_flags_public.md> |
875| `D3D12_SHADER_CACHE_KIND_FLAGS` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_kind_flags_public.md> |
876| `D3D12_SHADER_CACHE_CONTROL_FLAGS` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_control_flags_public.md> |
877| `D3D12_SHADER_CACHE_SUPPORT_FLAGS` | <https://docs.xbox.com/reference/graphics/d3d12/enums/d3d12_shader_cache_support_flags_public.md> |
878| `D3D12_FEATURE_DATA_SHADER_CACHE` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_feature_data_shader_cache_public.md> |
879| `ID3D12ShaderCacheSession` methods | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12shadercachesession/methods/id3d12shadercachesession_storevalue_public.md>, `..._findvalue_public.md`, `..._getdesc_public.md`, `..._setdeleteondestroy_public.md` |
880| `D3D12GetInterface` | <https://docs.xbox.com/reference/graphics/d3d12/functions/d3d12getinterface_public.md> |
881| `CreateCommandQueue` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_createcommandqueue_public.md> |
882| `D3D12_COMMAND_QUEUE_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_command_queue_desc_public.md> |
883| `CreateComputePipelineState` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_createcomputepipelinestate_public.md> |
884| `D3D12_COMPUTE_PIPELINE_STATE_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_compute_pipeline_state_desc_public.md> |
885| `CreateGraphicsPipelineState` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_creategraphicspipelinestate_public.md> |
886| `D3D12_PIPELINE_STATE_STREAM_DESC` | <https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_pipeline_state_stream_desc_public.md> |
887| `CreatePipelineLibrary` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device1/methods/id3d12device1_createpipelinelibrary_public.md> |
888| `StorePipeline` | <https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12pipelinelibrary/methods/id3d12pipelinelibrary_storepipeline_public.md> |
889| Raytracing concept index | <https://docs.xbox.com/build/core-features/graphics/newfeatures/raytracing/index.md> |
890
891Pages that were looked for and do not exist publicly (404): `d3d12/functions/d3d12createdevice_public.md`,
892`d3d12/enums/d3d12_root_signature_flags_public.md`, `d3d12_xs/enums/d3d12_root_signature_flags_xs.md`,
893`d3d12/interfaces/id3d12device2/methods/id3d12device2_createpipelinestate_public.md`,
894`d3d12_xs/enums/d3d12_pipeline_state_flags_xs.md`, every `d3d12_xs/interfaces/...` page, and the NDA-gated
895`rt-xdxr.md` / `rt-offlinertpso.md`.
diff --git a/docs/xcl_compare.md b/docs/xcl_compare.md
new file mode 100644
index 000000000..07d3e42e4
--- /dev/null
+++ b/docs/xcl_compare.md
@@ -0,0 +1,75 @@
1# Comparing the runtime with XCL's test title
2
3`tools/xcl_compare.py` runs one synthetic console executable under `gta6rt --run` and under
4[XCL](https://github.com/ivall/xcl), and lists where the two runtimes disagree. XCL already runs retail Xbox Series
5titles, so a check that passes there and fails here points at a loader, shim or D3D12 gap. It is a lead to
6investigate, not proof of a bug: some of the title's checks test XCL's own design choices.
7
8## Licence boundary
9
10XCL is GPL-2.0-only, which is not compatible with this repository's GPL-3.0-or-later (see
11[related_projects.md](related_projects.md)). The tool contains no XCL code, headers or tables. It starts programs
12built from a separate XCL checkout that you point it at, reads what they print, and writes a report outside the
13repository. Do not copy the test title, its sources or its output into this repository.
14
15## What the test title is
16
17XCL's test title (the `testtitle` and `testgamedll` crates in XCL's repository) is a fake console executable. Its
18import table names `kernelx.dll`, `xgameruntime.dll`, `xmem.dll` and a bundled game DLL, so plain Windows cannot
19start it. It runs about 50 checks (title memory, TLS, exceptions, modules, console paths, XGameRuntime, task
20queues, users, storage, D3D12.X, DirectStorage, XAudio2) and prints `[PASS] <check>` or `[FAIL] <check>: <reason>`
21for each. No game files are involved.
22
23## Run it
24
251. Build XCL in its own checkout: `cargo build --release --workspace` (Rust and the Windows SDK; XCL looks up
26 `dxcompiler.dll` in the Windows SDK).
272. Build the runtime: `scripts/build_runtime.ps1`, or CMake as in [testing.md](testing.md).
283. Run:
29
30```powershell
31python -I tools/xcl_compare.py --xcl C:\src\xcl
32python -I tools/xcl_compare.py --xcl C:\src\xcl --gui # the checks live in a window
33```
34
35The work folder defaults to `%TEMP%\leonida_xcl_compare`. It must not be on `D:`: XCL maps the console drive `D:`
36to the game folder, so a real `D:\` path is not reachable inside XCL and the title fails to load. The report is
37`report.json` in the work folder (`--out` to change it). Everything each title printed is in `xcl_output.txt` and
38`leonida_output.txt` beside it. A check counts as a difference when its status or its reason differs between the
39two runs, so a check that fails in both for different reasons is still listed.
40
41A check that prints nothing for `--timeout` seconds (15 by default) is a hang. The tool records the stacks of the
42title's threads with `cdb.exe` from the Windows SDK debugging tools (when installed), stops the title, and starts it
43again with that check skipped, so a hang does not hide the checks after it. `--skip <fragment>` skips checks by
44name. Both need two small local changes to the title's `check` function, which upstream XCL does not have: print
45`[RUN] <check>` before each check, and return early with `[SKIP] <check>` when `XCL_TESTTITLE_SKIP` holds part of
46its name. Without them the check in progress is taken from XCL's order, and a hang ends the run (the tool notices
47the repeat and stops).
48
49## Result, 2026-11-22
50
51Windows 11, RTX 5070 Ti (driver 616.92), MSVC 19.44, Windows SDK 10.0.26100, runtime at `f847748c`, XCL at
52`055b0ad` with the two local changes above in its test title.
53
54| Runtime | Pass | Fail | Hang |
55|---|---:|---:|---:|
56| XCL | 50 | 0 | 0 |
57| gta6rt | 5 | 43 | 2 |
58
59XCL passes all 50 on this NVIDIA GPU, so its open gap on 32-wide-wave GPUs (wave64 compute, geometry and mesh
60programs refused) does not affect this title. The D3D12 call traces were recorded (`--trace-d3d12`), but the runtime
61never reaches a D3D12 call, so there is nothing to compare there yet.
62
63What the differences come down to:
64
65| Difference | Reading |
66|---|---|
67| Both hangs: `XTaskQueueTerminate(queue, wait = true)` on a manual queue, from the thread that dispatches it (`TaskQueueImpl::Terminate` waits on its condition variable) | Not a runtime bug. The reference implementation in `third_party/xtaskqueue` behaves this way, and Microsoft's `XTaskQueueTerminate` documentation warns that waiting from the dispatching thread can deadlock. XCL returns there; the title relies on that. |
68| `GetModuleHandle(NULL)` and `current_exe` name `gta6rt.exe`, not the title | Covered by open #2075 (the mapped executable's module identity). |
69| `G:\` and `T:\` console paths | RT-218 (claimed). |
70| Persistent local storage | RT-219 (claimed). |
71| XUser, XGameSave folder | #279 and #3363 (open). |
72| `XAudio2Create` | RT-197, #3831 (open). |
73| `d3d12_xs.dll!D3D12CreateDevice` not found (16 D3D12.X checks) | The runtime serves the console's `D3D12XboxCreateDevice`; the title asks for `D3D12CreateDevice`. Whether the console's `d3d12_xs.dll` exports that name is not measured here. |
74| `kernelx.dll` imports `XMemAlloc`, `XMemVirtualAlloc`, `TitleMemoryStatus`, `GetConsoleType`, `SetThreadName`/`GetThreadName`; `xmem.dll` physical pages; `xcrdapi.dll!DStorageGetFactory`; `MFResetDXGIDeviceManagerX` | Unimplemented here. None is in the measured imports of the shipped modules ([runtime_imports.md](runtime_imports.md)), and the executable is not available to measure, so they are leads, not known needs. `xmem.dll!XMemAlloc` is served; the same name under `kernelx.dll` is not. |
75| The title's window is not a hidden 1920x1080 tool window | An XCL design choice (its console screen), not a console fact. |
diff --git a/docs/xdxr.md b/docs/xdxr.md
index bf445d2e3..1a2d104a4 100644
--- a/docs/xdxr.md
+++ b/docs/xdxr.md
@@ -11,6 +11,13 @@ copies and validation branches of the functions below. Addresses are RVAs (image
11the DLL is reproduced here except type names that its own exported symbols carry; check a claim by opening the 11the DLL is reproduced here except type names that its own exported symbols carry; check a claim by opening the
12function at its RVA in your own copy. 12function at its RVA in your own copy.
13 13
14**Errors are thrown, not returned.** Every rejection below in the build and prebuild-info exports stores
15`E_INVALIDARG` and throws it as an MSVC C++ exception through the `_CxxThrowException` thunk at `0x2302e`, and those
16exports return `void`: the `Dest` alignment check in `0x216a0` (branch at `0x217a3`, throw at `0x21876`), the
17`Inputs.Type` check in `0xcc00` (branch at `0xce0c`, throw at `0xd578`) and the postbuild-type check in `0xe6a0` (§4).
18Only `ValidateRehydrateAccelerationStructureBuildDesc` (`0x21a00`) returns `E_INVALIDARG` as an `HRESULT`. Checked
19with `llvm-objdump` on the 1.0.2.1 file (RT-155).
20
14| RVA | Function | What it shows | 21| RVA | Function | What it shows |
15|---|---|---| 22|---|---|---|
16| `0x216a0` | `BuildRaytracingAccelerationStructureBatched2X` (export) | Element stride `0x50`; `Dest` alignment check; postbuild loop | 23| `0x216a0` | `BuildRaytracingAccelerationStructureBatched2X` (export) | Element stride `0x50`; `Dest` alignment check; postbuild loop |
@@ -28,9 +35,9 @@ and pointer at `+0x30`/`+0x38`, zeroes `+0x40..+0x50` and calls the batched expo
28 35
29| Offset | Size | Field | Evidence | 36| Offset | Size | Field | Evidence |
30|---|---|---|---| 37|---|---|---|---|
31| `0x00` | 8 | `DestAccelerationStructureData` (GPU VA) | `0x216a0`: when postbuild info is requested, a nonzero low byte is rejected (`E_INVALIDARG`) as not 256-byte aligned | 38| `0x00` | 8 | `DestAccelerationStructureData` (GPU VA) | `0x216a0`: when postbuild info is requested, a nonzero low byte throws `E_INVALIDARG` (not 256-byte aligned) |
32| `0x08` | 24 | `Inputs` (public `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS`) | `0x21880` copies a caller's `INPUTS` here (3 words) | 39| `0x08` | 24 | `Inputs` (public `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS`) | `0x21880` copies a caller's `INPUTS` here (3 words) |
33| `0x08` | 4 | `Inputs.Type` | `0xcc00`: 0 and 1 accepted, anything else rejected (`E_INVALIDARG`) | 40| `0x08` | 4 | `Inputs.Type` | `0xcc00`: 0 and 1 accepted, anything else throws `E_INVALIDARG` |
34| `0x0c` | 4 | `Inputs.Flags` | `0xcc00` tests bits 0 (`ALLOW_UPDATE`), 2 (`PREFER_FAST_TRACE`), 4 (`MINIMIZE_MEMORY`), 5 (`PERFORM_UPDATE`) | 41| `0x0c` | 4 | `Inputs.Flags` | `0xcc00` tests bits 0 (`ALLOW_UPDATE`), 2 (`PREFER_FAST_TRACE`), 4 (`MINIMIZE_MEMORY`), 5 (`PERFORM_UPDATE`) |
35| `0x10` | 16 | `Inputs.NumDescs`, `DescsLayout`, `InstanceDescs`/`pGeometryDescs` | passed as `&desc + 8` to the per-type counters | 42| `0x10` | 16 | `Inputs.NumDescs`, `DescsLayout`, `InstanceDescs`/`pGeometryDescs` | passed as `&desc + 8` to the per-type counters |
36| `0x20` | 8 | `SourceAccelerationStructureData` | copied from the public desc by `0x21610` | 43| `0x20` | 8 | `SourceAccelerationStructureData` | copied from the public desc by `0x21610` |
@@ -87,7 +94,7 @@ Default for type 0's `0x08` value when it is negative (or when there is no type-
87| 0 `COMPACTED_SIZE`, 3 `CURRENT_SIZE` | written by one handler | 94| 0 `COMPACTED_SIZE`, 3 `CURRENT_SIZE` | written by one handler |
88| 2 `SERIALIZATION` | written by another handler | 95| 2 `SERIALIZATION` | written by another handler |
89| 1 `TOOLS_VISUALIZATION` and other values | ignored, no error | 96| 1 `TOOLS_VISUALIZATION` and other values | ignored, no error |
90| `0x10` `D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS` | rejected with `E_INVALIDARG` by `0xe6a0` before any work, for every build: the DLL only supports it for offline BVH builds | 97| `0x10` `D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS` | thrown as `E_INVALIDARG` by `0xe6a0` before any work, for every build: the DLL only supports it for offline BVH builds |
91 98
92**The offline statistics layout is not recoverable from this DLL**: it never writes them. It would have to come from 99**The offline statistics layout is not recoverable from this DLL**: it never writes them. It would have to come from
93the offline builder that produces dehydrated BVHs, which is not in the package. A runtime that implements the builder 100the offline builder that produces dehydrated BVHs, which is not in the package. A runtime that implements the builder
diff --git a/docs/xmem_exe_calls.md b/docs/xmem_exe_calls.md
new file mode 100644
index 000000000..99b62fbe1
--- /dev/null
+++ b/docs/xmem_exe_calls.md
@@ -0,0 +1,111 @@
1# XMem: how the retail executable calls it (RT-5)
2
3`game_scarlett_master.exe` imports 12 functions from `xmem.dll` (`docs/runtime_imports.md`, "The retail executable").
4Seven have no shim yet. This page records, from the file alone, how the executable calls them: how many call sites each
5has and the constant arguments those sites pass. Nothing was run: `tools/import_call_sites.py` finds the call sites, and
6the instructions that load the argument registers before each call were read by hand. No code or data of the executable
7is quoted, only the constants a call passes and the counts. Measured at `main` `1cc6e3c1`, SHA-256
8`e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993`.
9
10```powershell
11python -I tools/import_call_sites.py game_scarlett_master.exe --dll xmem.dll --dll d3d12_xs.dll --dll xg_xs.dll
12```
13
14The tool finds each import's thunk (`jmp [rip+disp32]` through its address-table slot) and the `call`/`jmp rel32`
15instructions that reach it. Its counts cover direct calls only, and a stray `E8`/`E9` byte could add one, so they are
16bounds, not a proof that every site is reached.
17
18| Import | Call sites | Shim at `main` `1cc6e3c1` |
19|---|---:|---|
20| `XMemVirtualAlloc` | 23 | yes, refuses every one of these 23 (below) |
21| `XMemMapPhysicalPages` | 12 | no |
22| `XMemAllocatePhysicalPages` | 4 | no |
23| `XMemFreePhysicalPages` | 3 | no |
24| `XMemMapPhysicalPagesScatter` | 2 | no |
25| `XMemAlloc` | 3 | yes |
26| `XMemFree` | 3 (2 calls, 1 tail jump) | yes |
27| `XMemGetWorkingSetStatistics` | 3 | yes |
28| `XMemTransferMemory` | 1 | yes |
29| `XMemIsToolsMemAvailable` | 1 | no |
30| `XMemAllocDefault`, `XMemFreeDefault` | 1 tail jump each, no call | no |
31
32The executable also exports one symbol, `__XMemAllocationHooks__`.
33
34## `XMemVirtualAlloc`: every site passes an attribute word
35
36The 23 sites pass these constants (`allocation_type`, `attributes`, `protect`; the shim's parameter order is
37`address, size, allocation_type, attributes, protect`):
38
39| `allocation_type` | `attributes` | `protect` | Sites |
40|---|---|---|---:|
41| `0x20403000` | `0x181` | `0x4` | 3 |
42| `0x20402000` | `0x21` | `0x4` | 3 |
43| `0x20003000` | `0x183` | `0x22004` | 3 |
44| `0x20402000` | `0x3` | `0x801` | 2 |
45| `0x20402000` | `0x23` | `0x2004` | 2 |
46| `0x20402000` | `0x23` | `0x2404` | 1 |
47| `0x20003000` | `0x283` | `0x2004` | 1 |
48| `0x20003000` | `0x283` | `0x2404` | 1 |
49| `0x20401000` | `0x283` | `0x42404` | 1 |
50| `0x20406000` | `0x27` | `0x1004`, `0x1404`, `0x8404`, `0x2404`, `0x2004` | 5 (one each) |
51| `0x42000` | `0x7` | `0x1` | 1 |
52
53Every `attributes` value is nonzero, and `runtime/shims/xmem.cpp` returns `ERROR_NOT_SUPPORTED` for a nonzero value
54("until their host mapping is known"), so none of the 23 calls succeeds there. Past that check the shim would also
55refuse the calls with `allocation_type` `0x20003000` (5 sites: the 2 MiB page mode) and those with bits it does not
56know: `0x4000` in `0x20406000` (5 sites) and `0x40000` in `0x42000` (1 site).
57
58The `protect` values are not Win32 protections alone. The Windows SDK's `winnt.h` defines the graphics page protections
59the high bits match: `PAGE_GRAPHICS_NOACCESS` `0x800`, `_READONLY` `0x1000`, `_READWRITE` `0x2000`, `_EXECUTE_READ`
60`0x8000`, `_COHERENT` `0x20000`, `_NOCACHE` `0x40000`, beside `PAGE_WRITECOMBINE` `0x400`. Read that way, `0x2004` is
61`PAGE_READWRITE` plus `PAGE_GRAPHICS_READWRITE`, and `0x801` is `PAGE_NOACCESS` plus `PAGE_GRAPHICS_NOACCESS`. That is
62an inference from the constants matching the SDK's names, not something the executable states. What the `attributes`
63bits mean (`0x1`, `0x2`, `0x4`, `0x20`, `0x80`, `0x100`, `0x200` appear) is **unmeasured**.
64
65## The physical-page family
66
67Four imports share one shape, and it is the Win32 AWE family's (`AllocateUserPhysicalPages`, `MapUserPhysicalPages`,
68`FreeUserPhysicalPages`, `MapUserPhysicalPagesScatter`) with the process handle replaced or dropped. These signatures
69are **inferred** from the registers loaded before each call; no documentation of these functions is public:
70
71| Function | Inferred signature | Evidence |
72|---|---|---|
73| `XMemAllocatePhysicalPages` | `BOOL (ULONG_PTR flags, ULONG_PTR* pages, ULONG_PTR* pageArray)` | 4 sites. `pages` points to a stack slot holding the wanted count; `pageArray` is a buffer of `count * 8` bytes. One site compares the count read back with the wanted one, so a partial allocation is possible. `flags` is `0x380`, `0x280` (2 sites) and `0x180` |
74| `XMemMapPhysicalPages` | `BOOL (void* virtualAddress, ULONG_PTR pages, const ULONG_PTR* pageArray)` | 12 sites. Four pass a null `pageArray` (an unmap); one maps one page through a one-element array; the result is tested at the sites that read it |
75| `XMemFreePhysicalPages` | `? (ULONG_PTR pages, ULONG_PTR* pageArray)` | 3 sites. The count is passed by value (one site frees the sum of four counts it had just unmapped), the array by pointer. Only two of the three sites were read to the argument, so this one is the least certain |
76| `XMemMapPhysicalPagesScatter` | `BOOL (void** virtualAddresses, ULONG_PTR pages, const ULONG_PTR* pageArray)` | 2 sites. Shaped like the Win32 call; the result was not followed |
77
78The page unit looks like **64 KiB**: the code that unmaps shifts byte sizes right by 16 before it passes page counts,
79and the reservations that precede the map calls use the 64 KiB page mode (`0x20402000`, above). That is inferred from
80those two facts. The meaning of `flags`, and whether the page numbers in `pageArray` carry anything beyond an index,
81are **unmeasured**.
82
83The sequence in the first function that calls them is: `XMemAllocatePhysicalPages`, then `XMemVirtualAlloc` of a range
84with `0x20402000` and attributes `0x23`, then `XMemMapPhysicalPages` of those pages at that range. So the physical-page calls depend on the
85attribute check above: until `XMemVirtualAlloc` accepts these attribute words, the map calls are never reached from
86there.
87
88The host's own AWE functions need `SeLockMemoryPrivilege`, which an ordinary user does not hold, so a shim would
89emulate the pool (a pagefile-backed section of 64 KiB pages, with views placed at the reserved range) instead of
90forwarding. That is a design note, not a measurement.
91
92## The other imports
93
94Observed constants, where the window before the call loads one:
95
96| Import | Sites | Constants seen |
97|---|---:|---|
98| `XMemAlloc` | 3 | attributes `0xf0814000` (2 sites); one size `0x60000`; one size `0x80` |
99| `XMemFree` | 3 | attributes `0x3` and `0xf0814000`; one attribute not a constant |
100| `XMemTransferMemory` | 1 | direction `1`, size `0x1000000` (16 MiB) |
101| `XMemGetWorkingSetStatistics` | 3 | kind `0x2000000a` (2 sites), `0x20000001` |
102| `XMemIsToolsMemAvailable` | 1 | arguments not read |
103
104`runtime/shims/xmem.cpp` says one call site "passes `0x5e50000`" as the attribute word. The two `XMemAlloc` sites here
105whose attribute is a constant pass `0xf0814000`, not that value, so it comes from another image.
106
107## What this does not show
108
109Which of these calls the boot reaches, and in what order, is not measured: nothing ran. A call site is code that can
110call, and the boot may reach only some of them. The first run's trace (`--trace`, `xmem_attributes` events) is the
111signal for the order.